source: josm/trunk/src/org/openstreetmap/josm/tools/PlatformHookUnixoid.java@ 12288

Last change on this file since 12288 was 12241, checked in by Don-vip, 7 years ago

see #11924, see #14649 - java 9 does not seem to include Dutch certificates yet, load them from /usr/share/ca-certificates/mozilla (see Debian ca-certificates package)

  • Property svn:eol-style set to native
File size: 18.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Desktop;
7import java.awt.event.KeyEvent;
8import java.io.BufferedReader;
9import java.io.File;
10import java.io.FileInputStream;
11import java.io.IOException;
12import java.net.URI;
13import java.net.URISyntaxException;
14import java.nio.charset.StandardCharsets;
15import java.nio.file.Files;
16import java.nio.file.Path;
17import java.nio.file.Paths;
18import java.security.KeyStoreException;
19import java.security.NoSuchAlgorithmException;
20import java.security.cert.CertificateException;
21import java.security.cert.CertificateFactory;
22import java.security.cert.X509Certificate;
23import java.util.Arrays;
24import java.util.List;
25import java.util.Locale;
26
27import org.openstreetmap.josm.Main;
28import org.openstreetmap.josm.io.CertificateAmendment.CertAmend;
29
30/**
31 * {@code PlatformHook} implementation for Unix systems.
32 * @since 1023
33 */
34public class PlatformHookUnixoid implements PlatformHook {
35
36 private String osDescription;
37
38 // rpm returns translated string "package %s is not installed\n", can't find a way to force english output
39 // translations from https://github.com/rpm-software-management/rpm
40 private static final String[] NOT_INSTALLED = {
41 "not installed", // en
42 "no s'ha instal·lat", // ca
43 "尚未安裝", // cmn
44 "není nainstalován", // cs
45 "ikke installeret", // da
46 "nicht installiert", // de
47 "ne estas instalita", // eo
48 "no está instalado", // es
49 "ole asennettu", // fi
50 "pas installé", // fr
51 "non è stato installato", // it
52 "はインストールされていません。", // ja
53 "패키지가 설치되어 있지 않습니다", // ko
54 "ikke installert", // nb
55 "nie jest zainstalowany", // pl
56 "não está instalado", // pt
57 "не установлен", // ru
58 "ni nameščen", // sl
59 "nie je nainštalovaný", // sk
60 "није инсталиран", // sr
61 "inte installerat", // sv
62 "kurulu değil", // tr
63 "не встановлено", // uk
64 "chưa cài đặt gói", // vi
65 "未安装软件包", // zh_CN
66 "尚未安裝" // zh_TW
67 };
68
69 @Override
70 public void preStartupHook() {
71 // See #12022 - Disable GNOME ATK Java wrapper as it causes a lot of serious trouble
72 if ("org.GNOME.Accessibility.AtkWrapper".equals(System.getProperty("assistive_technologies"))) {
73 System.clearProperty("assistive_technologies");
74 }
75 }
76
77 @Override
78 public void openUrl(String url) throws IOException {
79 for (String program : Main.pref.getCollection("browser.unix",
80 Arrays.asList("xdg-open", "#DESKTOP#", "$BROWSER", "gnome-open", "kfmclient openURL", "firefox"))) {
81 try {
82 if ("#DESKTOP#".equals(program)) {
83 Desktop.getDesktop().browse(new URI(url));
84 } else if (program.startsWith("$")) {
85 program = System.getenv().get(program.substring(1));
86 Runtime.getRuntime().exec(new String[]{program, url});
87 } else {
88 Runtime.getRuntime().exec(new String[]{program, url});
89 }
90 return;
91 } catch (IOException | URISyntaxException e) {
92 Main.warn(e);
93 }
94 }
95 }
96
97 @Override
98 public void initSystemShortcuts() {
99 // CHECKSTYLE.OFF: LineLength
100 // TODO: Insert system shortcuts here. See Windows and especially OSX to see how to.
101 for (int i = KeyEvent.VK_F1; i <= KeyEvent.VK_F12; ++i) {
102 Shortcut.registerSystemShortcut("screen:toogle"+i, tr("reserved"), i, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
103 .setAutomatic();
104 }
105 Shortcut.registerSystemShortcut("system:reset", tr("reserved"), KeyEvent.VK_DELETE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
106 .setAutomatic();
107 Shortcut.registerSystemShortcut("system:resetX", tr("reserved"), KeyEvent.VK_BACK_SPACE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK)
108 .setAutomatic();
109 // CHECKSTYLE.ON: LineLength
110 }
111
112 @Override
113 public String getDefaultStyle() {
114 return "javax.swing.plaf.metal.MetalLookAndFeel";
115 }
116
117 /**
118 * Determines if the distribution is Debian or Ubuntu, or a derivative.
119 * @return {@code true} if the distribution is Debian, Ubuntu or Mint, {@code false} otherwise
120 */
121 public static boolean isDebianOrUbuntu() {
122 try {
123 String dist = Utils.execOutput(Arrays.asList("lsb_release", "-i", "-s"));
124 return "Debian".equalsIgnoreCase(dist) || "Ubuntu".equalsIgnoreCase(dist) || "Mint".equalsIgnoreCase(dist);
125 } catch (IOException e) {
126 // lsb_release is not available on all Linux systems, so don't log at warning level
127 Main.debug(e);
128 return false;
129 }
130 }
131
132 /**
133 * Get the package name including detailed version.
134 * @param packageNames The possible package names (when a package can have different names on different distributions)
135 * @return The package name and package version if it can be identified, null otherwise
136 * @since 7314
137 */
138 public static String getPackageDetails(String... packageNames) {
139 try {
140 // CHECKSTYLE.OFF: SingleSpaceSeparator
141 boolean dpkg = Paths.get("/usr/bin/dpkg-query").toFile().exists();
142 boolean eque = Paths.get("/usr/bin/equery").toFile().exists();
143 boolean rpm = Paths.get("/bin/rpm").toFile().exists();
144 // CHECKSTYLE.ON: SingleSpaceSeparator
145 if (dpkg || rpm || eque) {
146 for (String packageName : packageNames) {
147 String[] args;
148 if (dpkg) {
149 args = new String[] {"dpkg-query", "--show", "--showformat", "${Architecture}-${Version}", packageName};
150 } else if (eque) {
151 args = new String[] {"equery", "-q", "list", "-e", "--format=$fullversion", packageName};
152 } else {
153 args = new String[] {"rpm", "-q", "--qf", "%{arch}-%{version}", packageName};
154 }
155 String version = Utils.execOutput(Arrays.asList(args));
156 if (version != null) {
157 for (String notInstalled : NOT_INSTALLED) {
158 if (version.contains(notInstalled))
159 break;
160 }
161 return packageName + ':' + version;
162 }
163 }
164 }
165 } catch (IOException e) {
166 Main.warn(e);
167 }
168 return null;
169 }
170
171 /**
172 * Get the Java package name including detailed version.
173 *
174 * Some Java bugs are specific to a certain security update, so in addition
175 * to the Java version, we also need the exact package version.
176 *
177 * @return The package name and package version if it can be identified, null otherwise
178 */
179 public String getJavaPackageDetails() {
180 String home = System.getProperty("java.home");
181 if (home.contains("java-8-openjdk") || home.contains("java-1.8.0-openjdk")) {
182 return getPackageDetails("openjdk-8-jre", "java-1_8_0-openjdk", "java-1.8.0-openjdk");
183 } else if (home.contains("java-9-openjdk") || home.contains("java-1.9.0-openjdk")) {
184 return getPackageDetails("openjdk-9-jre", "java-1_9_0-openjdk", "java-1.9.0-openjdk");
185 } else if (home.contains("icedtea")) {
186 return getPackageDetails("icedtea-bin");
187 } else if (home.contains("oracle")) {
188 return getPackageDetails("oracle-jdk-bin", "oracle-jre-bin");
189 }
190 return null;
191 }
192
193 /**
194 * Get the Web Start package name including detailed version.
195 *
196 * OpenJDK packages are shipped with icedtea-web package,
197 * but its version generally does not match main java package version.
198 *
199 * Simply return {@code null} if there's no separate package for Java WebStart.
200 *
201 * @return The package name and package version if it can be identified, null otherwise
202 */
203 public String getWebStartPackageDetails() {
204 if (isOpenJDK()) {
205 return getPackageDetails("icedtea-netx", "icedtea-web");
206 }
207 return null;
208 }
209
210 /**
211 * Get the Gnome ATK wrapper package name including detailed version.
212 *
213 * Debian and Ubuntu derivatives come with a pre-enabled accessibility software
214 * completely buggy that makes Swing crash in a lot of different ways.
215 *
216 * Simply return {@code null} if it's not found.
217 *
218 * @return The package name and package version if it can be identified, null otherwise
219 */
220 public String getAtkWrapperPackageDetails() {
221 if (isOpenJDK() && isDebianOrUbuntu()) {
222 return getPackageDetails("libatk-wrapper-java");
223 }
224 return null;
225 }
226
227 private String buildOSDescription() {
228 String osName = System.getProperty("os.name");
229 if ("Linux".equalsIgnoreCase(osName)) {
230 try {
231 // Try lsb_release (only available on LSB-compliant Linux systems,
232 // see https://www.linuxbase.org/lsb-cert/productdir.php?by_prod )
233 String line = exec("lsb_release -ds");
234 if (line != null && !line.isEmpty()) {
235 line = line.replaceAll("\"+", "");
236 line = line.replaceAll("NAME=", ""); // strange code for some Gentoo's
237 if (line.startsWith("Linux ")) // e.g. Linux Mint
238 return line;
239 else if (!line.isEmpty())
240 return "Linux " + line;
241 }
242 } catch (IOException e) {
243 Main.debug(e);
244 // Non LSB-compliant Linux system. List of common fallback release files: http://linuxmafia.com/faq/Admin/release-files.html
245 for (LinuxReleaseInfo info : new LinuxReleaseInfo[]{
246 new LinuxReleaseInfo("/etc/lsb-release", "DISTRIB_DESCRIPTION", "DISTRIB_ID", "DISTRIB_RELEASE"),
247 new LinuxReleaseInfo("/etc/os-release", "PRETTY_NAME", "NAME", "VERSION"),
248 new LinuxReleaseInfo("/etc/arch-release"),
249 new LinuxReleaseInfo("/etc/debian_version", "Debian GNU/Linux "),
250 new LinuxReleaseInfo("/etc/fedora-release"),
251 new LinuxReleaseInfo("/etc/gentoo-release"),
252 new LinuxReleaseInfo("/etc/redhat-release"),
253 new LinuxReleaseInfo("/etc/SuSE-release")
254 }) {
255 String description = info.extractDescription();
256 if (description != null && !description.isEmpty()) {
257 return "Linux " + description;
258 }
259 }
260 }
261 }
262 return osName;
263 }
264
265 @Override
266 public String getOSDescription() {
267 if (osDescription == null) {
268 osDescription = buildOSDescription();
269 }
270 return osDescription;
271 }
272
273 private static class LinuxReleaseInfo {
274 private final String path;
275 private final String descriptionField;
276 private final String idField;
277 private final String releaseField;
278 private final boolean plainText;
279 private final String prefix;
280
281 LinuxReleaseInfo(String path, String descriptionField, String idField, String releaseField) {
282 this(path, descriptionField, idField, releaseField, false, null);
283 }
284
285 LinuxReleaseInfo(String path) {
286 this(path, null, null, null, true, null);
287 }
288
289 LinuxReleaseInfo(String path, String prefix) {
290 this(path, null, null, null, true, prefix);
291 }
292
293 private LinuxReleaseInfo(String path, String descriptionField, String idField, String releaseField, boolean plainText, String prefix) {
294 this.path = path;
295 this.descriptionField = descriptionField;
296 this.idField = idField;
297 this.releaseField = releaseField;
298 this.plainText = plainText;
299 this.prefix = prefix;
300 }
301
302 @Override
303 public String toString() {
304 return "ReleaseInfo [path=" + path + ", descriptionField=" + descriptionField +
305 ", idField=" + idField + ", releaseField=" + releaseField + ']';
306 }
307
308 /**
309 * Extracts OS detailed information from a Linux release file (/etc/xxx-release)
310 * @return The OS detailed information, or {@code null}
311 */
312 public String extractDescription() {
313 String result = null;
314 if (path != null) {
315 Path p = Paths.get(path);
316 if (p.toFile().exists()) {
317 try (BufferedReader reader = Files.newBufferedReader(p, StandardCharsets.UTF_8)) {
318 String id = null;
319 String release = null;
320 String line;
321 while (result == null && (line = reader.readLine()) != null) {
322 if (line.contains("=")) {
323 String[] tokens = line.split("=");
324 if (tokens.length >= 2) {
325 // Description, if available, contains exactly what we need
326 if (descriptionField != null && descriptionField.equalsIgnoreCase(tokens[0])) {
327 result = Utils.strip(tokens[1]);
328 } else if (idField != null && idField.equalsIgnoreCase(tokens[0])) {
329 id = Utils.strip(tokens[1]);
330 } else if (releaseField != null && releaseField.equalsIgnoreCase(tokens[0])) {
331 release = Utils.strip(tokens[1]);
332 }
333 }
334 } else if (plainText && !line.isEmpty()) {
335 // Files composed of a single line
336 result = Utils.strip(line);
337 }
338 }
339 // If no description has been found, try to rebuild it with "id" + "release" (i.e. "name" + "version")
340 if (result == null && id != null && release != null) {
341 result = id + ' ' + release;
342 }
343 } catch (IOException e) {
344 // Ignore
345 Main.trace(e);
346 }
347 }
348 }
349 // Append prefix if any
350 if (result != null && !result.isEmpty() && prefix != null && !prefix.isEmpty()) {
351 result = prefix + result;
352 }
353 if (result != null)
354 result = result.replaceAll("\"+", "");
355 return result;
356 }
357 }
358
359 /**
360 * Get the dot directory <code>~/.josm</code>.
361 * @return the dot directory
362 */
363 private static File getDotDirectory() {
364 String dirName = "." + Main.pref.getJOSMDirectoryBaseName().toLowerCase(Locale.ENGLISH);
365 return new File(System.getProperty("user.home"), dirName);
366 }
367
368 /**
369 * Returns true if the dot directory should be used for storing preferences,
370 * cache and user data.
371 * Currently this is the case, if the dot directory already exists.
372 * @return true if the dot directory should be used
373 */
374 private static boolean useDotDirectory() {
375 return getDotDirectory().exists();
376 }
377
378 @Override
379 public File getDefaultCacheDirectory() {
380 if (useDotDirectory()) {
381 return new File(getDotDirectory(), "cache");
382 } else {
383 String xdgCacheDir = System.getenv("XDG_CACHE_HOME");
384 if (xdgCacheDir != null && !xdgCacheDir.isEmpty()) {
385 return new File(xdgCacheDir, Main.pref.getJOSMDirectoryBaseName());
386 } else {
387 return new File(System.getProperty("user.home") + File.separator +
388 ".cache" + File.separator + Main.pref.getJOSMDirectoryBaseName());
389 }
390 }
391 }
392
393 @Override
394 public File getDefaultPrefDirectory() {
395 if (useDotDirectory()) {
396 return getDotDirectory();
397 } else {
398 String xdgConfigDir = System.getenv("XDG_CONFIG_HOME");
399 if (xdgConfigDir != null && !xdgConfigDir.isEmpty()) {
400 return new File(xdgConfigDir, Main.pref.getJOSMDirectoryBaseName());
401 } else {
402 return new File(System.getProperty("user.home") + File.separator +
403 ".config" + File.separator + Main.pref.getJOSMDirectoryBaseName());
404 }
405 }
406 }
407
408 @Override
409 public File getDefaultUserDataDirectory() {
410 if (useDotDirectory()) {
411 return getDotDirectory();
412 } else {
413 String xdgDataDir = System.getenv("XDG_DATA_HOME");
414 if (xdgDataDir != null && !xdgDataDir.isEmpty()) {
415 return new File(xdgDataDir, Main.pref.getJOSMDirectoryBaseName());
416 } else {
417 return new File(System.getProperty("user.home") + File.separator +
418 ".local" + File.separator + "share" + File.separator + Main.pref.getJOSMDirectoryBaseName());
419 }
420 }
421 }
422
423 @Override
424 public List<File> getDefaultProj4NadshiftDirectories() {
425 return Arrays.asList(new File("/usr/local/share/proj"), new File("/usr/share/proj"));
426 }
427
428 @Override
429 public X509Certificate getX509Certificate(CertAmend certAmend)
430 throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
431 File f = new File("/usr/share/ca-certificates/mozilla", certAmend.getFilename());
432 if (f.exists()) {
433 CertificateFactory fact = CertificateFactory.getInstance("X.509");
434 try (FileInputStream is = new FileInputStream(f)) {
435 return (X509Certificate) fact.generateCertificate(is);
436 }
437 }
438 return null;
439 }
440}
Note: See TracBrowser for help on using the repository browser.