001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import java.lang.reflect.InvocationTargetException;
005import java.lang.reflect.Method;
006import java.nio.charset.StandardCharsets;
007import java.util.ArrayList;
008import java.util.Arrays;
009import java.util.Collections;
010import java.util.HashMap;
011import java.util.List;
012import java.util.Map;
013import java.util.prefs.Preferences;
014
015/**
016 * Utility class to access Window registry (read access only).
017 * As the implementation relies on internal JDK class {@code java.util.prefs.WindowsPreferences} and its native JNI
018 * method {@code Java_java_util_prefs_WindowsPreferences_WindowsRegQueryValueEx}, only String values (REG_SZ)
019 * are supported.
020 * Adapted from <a href="http://stackoverflow.com/a/6163701/2257172">StackOverflow</a>.
021 * @since 12217
022 */
023public final class WinRegistry {
024
025    /**
026     * Registry entries subordinate to this key define the preferences of the current user.
027     * These preferences include the settings of environment variables, data about program groups,
028     * colors, printers, network connections, and application preferences.
029     * See <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms724836(v=vs.85).aspx">Predefined Keys</a>
030     */
031    public static final long HKEY_CURRENT_USER = 0x80000001L;
032
033    /**
034     * Registry entries subordinate to this key define the physical state of the computer, including data about the bus type,
035     * system memory, and installed hardware and software. It contains subkeys that hold current configuration data,
036     * including Plug and Play information (the Enum branch, which includes a complete list of all hardware that has ever been
037     * on the system), network logon preferences, network security information, software-related information (such as server
038     * names and the location of the server), and other system information.
039     * See <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms724836(v=vs.85).aspx">Predefined Keys</a>
040     */
041    public static final long HKEY_LOCAL_MACHINE = 0x80000002L;
042
043    private static final long REG_SUCCESS = 0L;
044
045    private static final int KEY_READ = 0x20019;
046    private static final Preferences USER_ROOT = Preferences.userRoot();
047    private static final Preferences SYSTEM_ROOT = Preferences.systemRoot();
048    private static final Class<? extends Preferences> USER_CLASS = USER_ROOT.getClass();
049    private static final String HKEY_EQ = "hkey=";
050
051    /**
052     * Wrapper for Windows registry API RegOpenKey(long, byte[], int)
053     * Returns {@code long[]}
054     */
055    private static final Method REG_OPEN_KEY;
056    /**
057     * Wrapper for Windows registry API RegCloseKey(long)
058     * Returns {@code int}
059     */
060    private static final Method REG_CLOSE_KEY;
061    /**
062     * Wrapper for Windows registry API RegQueryValueEx(long, byte[])
063     * Returns {@code byte[]}
064     */
065    private static final Method REG_QUERY_VALUE_EX;
066    /**
067     * Wrapper for Windows registry API RegEnumValue(long, int, int)
068     * Returns {@code byte[]}
069     */
070    private static final Method REG_ENUM_VALUE;
071    /**
072     * Wrapper for RegQueryInfoKey(long)
073     * Returns {@code long[]}
074     */
075    private static final Method REG_QUERY_INFO_KEY;
076    /**
077     * Wrapper for RegEnumKeyEx(long, int, int)
078     * Returns {@code byte[]}
079     */
080    private static final Method REG_ENUM_KEY_EX;
081
082    static {
083        REG_OPEN_KEY = getDeclaredMethod("WindowsRegOpenKey", long.class, byte[].class, int.class);
084        REG_CLOSE_KEY = getDeclaredMethod("WindowsRegCloseKey", long.class);
085        REG_QUERY_VALUE_EX = getDeclaredMethod("WindowsRegQueryValueEx", long.class, byte[].class);
086        REG_ENUM_VALUE = getDeclaredMethod("WindowsRegEnumValue", long.class, int.class, int.class);
087        REG_QUERY_INFO_KEY = getDeclaredMethod("WindowsRegQueryInfoKey1", long.class);
088        REG_ENUM_KEY_EX = getDeclaredMethod("WindowsRegEnumKeyEx", long.class, int.class, int.class);
089        ReflectionUtils.setObjectsAccessible(REG_OPEN_KEY, REG_CLOSE_KEY, REG_QUERY_VALUE_EX, REG_ENUM_VALUE,
090                REG_QUERY_INFO_KEY, REG_ENUM_KEY_EX);
091    }
092
093    private static Method getDeclaredMethod(String name, Class<?>... parameterTypes) {
094        try {
095            return USER_CLASS.getDeclaredMethod(name, parameterTypes);
096        } catch (NoSuchMethodException e) {
097            Logging.log(Logging.LEVEL_ERROR, "Unable to find WindowsReg method", e);
098            return null;
099        } catch (RuntimeException e) {
100            Logging.log(Logging.LEVEL_ERROR, "Unable to get WindowsReg method", e);
101            return null;
102        }
103    }
104
105    private WinRegistry() {
106        // Hide default constructor for utilities classes
107    }
108
109    /**
110     * Read a value from key and value name
111     * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
112     * @param key  key name
113     * @param valueName  value name
114     * @return the value
115     * @throws IllegalArgumentException if hkey not HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
116     * @throws IllegalAccessException if Java language access control is enforced and the underlying method is inaccessible
117     * @throws InvocationTargetException if the underlying method throws an exception
118     * @since 19100 (method definition)
119     */
120    public static String readString(long hkey, String key, String valueName)
121            throws IllegalAccessException, InvocationTargetException {
122        if (hkey == HKEY_LOCAL_MACHINE) {
123            return readString(SYSTEM_ROOT, hkey, key, valueName);
124        } else if (hkey == HKEY_CURRENT_USER) {
125            return readString(USER_ROOT, hkey, key, valueName);
126        } else {
127            throw new IllegalArgumentException(HKEY_EQ + hkey);
128        }
129    }
130
131    /**
132     * Read value(s) and value name(s) form given key
133     * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
134     * @param key  key name
135     * @return the value name(s) plus the value(s)
136     * @throws IllegalArgumentException if hkey not HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
137     * @throws IllegalAccessException if Java language access control is enforced and the underlying method is inaccessible
138     * @throws InvocationTargetException if the underlying method throws an exception
139     */
140    public static Map<String, String> readStringValues(long hkey, String key)
141            throws IllegalAccessException, InvocationTargetException {
142        if (hkey == HKEY_LOCAL_MACHINE) {
143            return readStringValues(SYSTEM_ROOT, hkey, key);
144        } else if (hkey == HKEY_CURRENT_USER) {
145            return readStringValues(USER_ROOT, hkey, key);
146        } else {
147            throw new IllegalArgumentException(HKEY_EQ + hkey);
148        }
149    }
150
151    /**
152     * Read the value name(s) from a given key
153     * @param hkey  HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
154     * @param key  key name
155     * @return the value name(s)
156     * @throws IllegalArgumentException if hkey not HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
157     * @throws IllegalAccessException if Java language access control is enforced and the underlying method is inaccessible
158     * @throws InvocationTargetException if the underlying method throws an exception
159     */
160    public static List<String> readStringSubKeys(long hkey, String key)
161            throws IllegalAccessException, InvocationTargetException {
162        if (hkey == HKEY_LOCAL_MACHINE) {
163            return readStringSubKeys(SYSTEM_ROOT, hkey, key);
164        } else if (hkey == HKEY_CURRENT_USER) {
165            return readStringSubKeys(USER_ROOT, hkey, key);
166        } else {
167            throw new IllegalArgumentException(HKEY_EQ + hkey);
168        }
169    }
170
171    // =====================
172
173    private static long getNumber(Object array, int index) {
174        if (array instanceof long[]) {
175            return ((long[]) array)[index];
176        }
177        throw new IllegalArgumentException();
178    }
179
180    private static String readString(Preferences root, long hkey, String key, String value)
181            throws IllegalAccessException, InvocationTargetException {
182        if (REG_OPEN_KEY == null || REG_QUERY_VALUE_EX == null || REG_CLOSE_KEY == null) {
183            return null;
184        }
185        Object handles = REG_OPEN_KEY.invoke(root, hkey, toCstr(key), KEY_READ);
186        if (getNumber(handles, 1) != REG_SUCCESS) {
187            return null;
188        }
189        byte[] valb = (byte[]) REG_QUERY_VALUE_EX.invoke(root, getNumber(handles, 0), toCstr(value));
190        REG_CLOSE_KEY.invoke(root, getNumber(handles, 0));
191        return (valb != null ? new String(valb, StandardCharsets.UTF_8).trim() : null);
192    }
193
194    private static Map<String, String> readStringValues(Preferences root, long hkey, String key)
195            throws IllegalAccessException, InvocationTargetException {
196        if (REG_OPEN_KEY == null || REG_QUERY_INFO_KEY == null || REG_ENUM_VALUE == null || REG_CLOSE_KEY == null) {
197            return Collections.emptyMap();
198        }
199        HashMap<String, String> results = new HashMap<>();
200        Object handles = REG_OPEN_KEY.invoke(root, hkey, toCstr(key), KEY_READ);
201        if (getNumber(handles, 1) != REG_SUCCESS) {
202            return Collections.emptyMap();
203        }
204        Object info = REG_QUERY_INFO_KEY.invoke(root, getNumber(handles, 0));
205
206        int count = Math.toIntExact(getNumber(info, 0));
207        int maxlen = Math.toIntExact(getNumber(info, 3));
208        for (int index = 0; index < count; index++) {
209            byte[] name = (byte[]) REG_ENUM_VALUE.invoke(root, getNumber(handles, 0), index, maxlen + 1);
210            String value = readString(hkey, key, new String(name, StandardCharsets.UTF_8));
211            results.put(new String(name, StandardCharsets.UTF_8).trim(), value);
212        }
213        REG_CLOSE_KEY.invoke(root, getNumber(handles, 0));
214        return Collections.unmodifiableMap(results);
215    }
216
217    private static List<String> readStringSubKeys(Preferences root, long hkey, String key)
218            throws IllegalAccessException, InvocationTargetException {
219        if (REG_OPEN_KEY == null || REG_QUERY_INFO_KEY == null || REG_ENUM_KEY_EX == null || REG_CLOSE_KEY == null) {
220            return Collections.emptyList();
221        }
222        List<String> results = new ArrayList<>();
223        Object handles = REG_OPEN_KEY.invoke(root, hkey, toCstr(key), KEY_READ);
224        if (getNumber(handles, 1) != REG_SUCCESS) {
225            return Collections.emptyList();
226        }
227        Object info = REG_QUERY_INFO_KEY.invoke(root, getNumber(handles, 0));
228
229        int count = Math.toIntExact(getNumber(info, 0));
230        int maxlen = Math.toIntExact(getNumber(info, 3));
231        for (int index = 0; index < count; index++) {
232            byte[] name = (byte[]) REG_ENUM_KEY_EX.invoke(root, getNumber(handles, 0), index, maxlen + 1);
233            results.add(new String(name, StandardCharsets.UTF_8).trim());
234        }
235        REG_CLOSE_KEY.invoke(root, getNumber(handles, 0));
236        return Collections.unmodifiableList(results);
237    }
238
239    // utility
240    private static byte[] toCstr(String str) {
241        byte[] array = str.getBytes(StandardCharsets.UTF_8);
242        byte[] biggerCopy = Arrays.copyOf(array, array.length + 1);
243        biggerCopy[array.length] = 0;
244        return biggerCopy;
245    }
246}