2 // Getdown - application installer, patcher and launcher
3 // Copyright (C) 2004-2018 Getdown authors
4 // https://github.com/threerings/getdown/blob/master/LICENSE
6 package com.threerings.getdown.data;
9 import java.lang.reflect.Method;
10 import java.net.MalformedURLException;
11 import java.net.Proxy;
12 import java.net.SocketAddress;
13 import java.net.InetSocketAddress;
15 import java.net.URLClassLoader;
16 import java.net.URLConnection;
17 import java.net.URLDecoder;
18 import java.net.URLEncoder;
19 import java.nio.channels.FileChannel;
20 import java.nio.channels.FileLock;
21 import java.nio.channels.OverlappingFileLockException;
22 import java.security.*;
23 import java.security.cert.Certificate;
25 import java.util.concurrent.*;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28 import java.util.zip.GZIPInputStream;
30 import jalview.bin.HiDPISetting;
31 import jalview.bin.MemorySetting;
32 import jalview.util.HttpUtils;
33 import jalview.util.LaunchUtils;
35 import com.threerings.getdown.util.*;
36 // avoid ambiguity with java.util.Base64 which we can't use as it's 1.8+
37 import com.threerings.getdown.util.Base64;
39 import com.threerings.getdown.data.EnvConfig;
40 import com.threerings.getdown.data.EnvConfig.Note;
42 import static com.threerings.getdown.Log.log;
43 import static java.nio.charset.StandardCharsets.UTF_8;
46 * Parses and provide access to the information contained in the <code>getdown.txt</code>
49 public class Application
51 /** The name of our configuration file. */
52 public static final String CONFIG_FILE = "getdown.txt";
54 /** Dir where a backup config file might reside */
55 public static final String BACKUP_CONFIG_DIR = "install";
57 /** The name of our target version file. */
58 public static final String VERSION_FILE = "version.txt";
60 /** System properties that are prefixed with this string will be passed through to our
61 * application (minus this prefix). */
62 public static final String PROP_PASSTHROUGH_PREFIX = "app.";
64 /** Suffix used for control file signatures. */
65 public static final String SIGNATURE_SUFFIX = ".sig";
67 /** A special classname that means 'use -jar code.jar' instead of a classname. */
68 public static final String MANIFEST_CLASS = "manifest";
70 /** Used to communicate information about the UI displayed when updating the application. */
71 public static final class UpdateInterface
74 * The major steps involved in updating, along with some arbitrary percentages
75 * assigned to them, to mark global progress.
81 //VERIFY_METADATA(15, 65, 95),
82 VERIFY_METADATA(15, 45, 90),
85 //VERIFY_RESOURCES(70, 97),
86 VERIFY_RESOURCES(40, 90),
87 //REDOWNLOAD_RESOURCES(90),
88 REDOWNLOAD_RESOURCES(80),
94 /** What is the final percent value for this step? */
95 public final List<Integer> defaultPercents;
97 /** Enum constructor. */
98 Step (int... percents)
100 this.defaultPercents = intsToList(percents);
104 /** The human readable name of this application. */
105 public final String name;
107 /** A background color, just in case. */
108 public final int background;
110 /** Background image specifiers for `RotatingBackgrounds`. */
111 public final List<String> rotatingBackgrounds;
113 /** The error background image for `RotatingBackgrounds`. */
114 public final String errorBackground;
116 /** The paths (relative to the appdir) of images for the window icon. */
117 public final List<String> iconImages;
119 /** The path (relative to the appdir) to a single background image to appear first. */
120 public final String instantBackgroundImage;
122 /** The path (relative to the appdir) to a single background image. */
123 public final String backgroundImage;
125 /** The path (relative to the appdir) to the progress bar image. */
126 public final String progressImage;
128 /** The dimensions of the progress bar. */
129 public final Rectangle progress;
131 /** The color of the progress text. */
132 public final int progressText;
134 /** The color of the progress bar. */
135 public final int progressBar;
137 /** The dimensions of the status display. */
138 public final Rectangle status;
140 /** The color of the status text. */
141 public final int statusText;
143 /** The color of the text shadow. */
144 public final int textShadow;
146 /** Where to point the user for help with install errors. */
147 public final String installError;
149 /** The dimensions of the patch notes button. */
150 public final Rectangle patchNotes;
152 /** The patch notes URL. */
153 public final String patchNotesUrl;
155 /** Whether window decorations are hidden for the UI. */
156 public final boolean hideDecorations;
158 /** Whether progress text should be hidden or not. */
159 public final boolean hideProgressText;
161 /** Whether the splash screen should update non-asynchronously before being shown. */
162 public final boolean progressSync;
164 /** Whether the splash screen should update non-asynchronously after being shown. */
165 public final boolean progressSyncAfterShown;
167 /** Whether the splash screen should retain focus. */
168 public final boolean keepOnTop;
170 /** Whether to display the appbase. */
171 public final boolean displayAppbase;
173 /** Whether to display the version. */
174 public final boolean displayVersion;
176 /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
177 * flashing up on the screen and immediately disappearing, which can be confusing to the
179 public final int minShowSeconds;
181 /** The global percentages for each step. A step may have more than one, and
182 * the lowest reasonable one is used if a step is revisited. */
183 public final Map<Step, List<Integer>> stepPercentages;
185 /** Generates a string representation of this instance. */
187 public String toString ()
189 return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage + ", instant_bg=" + instantBackgroundImage +
190 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
191 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
192 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
193 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
194 ", hideProgressText=" + hideProgressText + ", keepOnTop=" + keepOnTop + ", progressSync=" + progressSync +
195 ", progressSyncAfterShown=" + progressSyncAfterShown + ", minShow=" + minShowSeconds +
196 ", displayAppbase=" + displayAppbase + ", displayVersion=" + displayVersion + "]";
199 public UpdateInterface (Config config)
201 this.name = config.getString("ui.name");
202 this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
203 this.progressText = config.getColor("ui.progress_text", Color.BLACK);
204 this.hideProgressText = config.getBoolean("ui.hide_progress_text");
205 this.progressSync = config.getBoolean("ui.progress_sync_before_shown");
206 this.progressSyncAfterShown = config.getBoolean("ui.progress_sync_after_shown");
207 this.keepOnTop = config.getBoolean("ui.keep_on_top");
208 this.displayAppbase = config.getBoolean("ui.display_appbase");
209 this.displayVersion = config.getBoolean("ui.display_version");
210 this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
211 this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
212 this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
213 this.statusText = config.getColor("ui.status_text", Color.BLACK);
214 this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
215 this.hideDecorations = config.getBoolean("ui.hide_decorations");
216 this.backgroundImage = config.getString("ui.background_image");
217 this.instantBackgroundImage = config.getString("ui.instant_background_image");
218 // default to black or white bg color, depending on the brightness of the progressText
219 int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
220 Color.BLACK : Color.WHITE;
221 this.background = config.getColor("ui.background", defaultBackground);
222 this.progressImage = config.getString("ui.progress_image");
223 this.rotatingBackgrounds = stringsToList(
224 config.getMultiValue("ui.rotating_background"));
225 this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
226 this.errorBackground = config.getString("ui.error_background");
228 // On an installation error, where do we point the user.
229 String installError = config.getUrl("ui.install_error", null);
230 this.installError = (installError == null) ?
231 "m.default_install_error" : MessageUtil.taint(installError);
233 // the patch notes bits
234 this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
235 this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
237 // step progress percentage (defaults and then customized values)
238 EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
239 for (Step step : Step.values()) {
240 stepPercentages.put(step, step.defaultPercents);
242 for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
243 String spec = config.getString("ui.percents." + step.name());
246 stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
247 } catch (Exception e) {
248 log.warning("Failed to parse percentages for " + step + ": " + spec);
252 this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
257 * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
258 * take network actions.
260 public static interface StatusDisplay
262 /** Requests that the specified status message be displayed. */
263 public void updateStatus (String message);
267 * Contains metadata for an auxiliary resource group.
269 public static class AuxGroup {
270 public final String name;
271 public final List<Resource> codes;
272 public final List<Resource> rsrcs;
274 public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
276 this.codes = Collections.unmodifiableList(codes);
277 this.rsrcs = Collections.unmodifiableList(rsrcs);
281 /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
282 * the application instance. Yes this is a public mutable field, no I'm not going to create a
283 * getter and setter just to pretend like that's not the case. */
284 public Proxy proxy = Proxy.NO_PROXY;
287 * Creates an application instance which records the location of the <code>getdown.txt</code>
288 * configuration file from the supplied application directory.
291 public Application (EnvConfig envc) {
293 _config = getLocalPath(envc.appDir, CONFIG_FILE);
294 _backupConfig = getLocalPath(envc.appDir, BACKUP_CONFIG_DIR+File.separator+CONFIG_FILE);
298 * Returns the configured application directory.
300 public File getAppDir () {
305 * Returns whether the application should cache code resources prior to launching the
308 public boolean useCodeCache ()
310 return _useCodeCache;
314 * Returns the number of days a cached code resource is allowed to stay unused before it
315 * becomes eligible for deletion.
317 public int getCodeCacheRetentionDays ()
319 return _codeCacheRetentionDays;
323 * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
324 * app files from its hosting server.
326 public int maxConcurrentDownloads () {
327 return _maxConcDownloads;
331 * Returns a resource that refers to the application configuration file itself.
333 public Resource getConfigResource ()
336 return createResource(CONFIG_FILE, Resource.NORMAL);
337 } catch (Exception e) {
338 throw new RuntimeException("Invalid appbase '" + _vappbase + "'.", e);
343 * Returns a list of the code {@link Resource} objects used by this application.
345 public List<Resource> getCodeResources ()
351 * Returns a list of the non-code {@link Resource} objects used by this application.
353 public List<Resource> getResources ()
359 * Returns the digest of the given {@code resource}.
361 public String getDigest (Resource resource)
363 return _digest.getDigest(resource);
367 * Returns a list of all the active {@link Resource} objects used by this application (code and
370 public List<Resource> getAllActiveResources ()
372 List<Resource> allResources = new ArrayList<>();
373 allResources.addAll(getActiveCodeResources());
374 allResources.addAll(getActiveResources());
379 * Returns the auxiliary resource group with the specified name, or null.
381 public AuxGroup getAuxGroup (String name)
383 return _auxgroups.get(name);
387 * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
388 * resource group is a collection of resource files that are not downloaded unless a group
389 * token file is present in the application directory.
391 public Iterable<AuxGroup> getAuxGroups ()
393 return _auxgroups.values();
397 * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
398 * groups should be ignored, activated groups should be downloaded and patched along with the
401 public boolean isAuxGroupActive (String auxgroup)
403 Boolean active = _auxactive.get(auxgroup);
404 if (active == null) {
405 // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
407 active = getLocalPath(auxgroup + ".dat").exists();
408 _auxactive.put(auxgroup, active);
414 * Returns all main code resources and all code resources from active auxiliary resource groups.
416 public List<Resource> getActiveCodeResources ()
418 ArrayList<Resource> codes = new ArrayList<>();
419 codes.addAll(getCodeResources());
420 for (AuxGroup aux : getAuxGroups()) {
421 if (isAuxGroupActive(aux.name)) {
422 codes.addAll(aux.codes);
429 * Returns all resources indicated to contain native library files (.dll, .so, etc.).
431 public List<Resource> getNativeResources ()
433 List<Resource> natives = new ArrayList<>();
434 for (Resource resource: _resources) {
435 if (resource.isNative()) {
436 natives.add(resource);
443 * Returns all non-code resources and all resources from active auxiliary resource groups.
445 public List<Resource> getActiveResources ()
447 ArrayList<Resource> rsrcs = new ArrayList<>();
448 rsrcs.addAll(getResources());
449 for (AuxGroup aux : getAuxGroups()) {
450 if (isAuxGroupActive(aux.name)) {
451 rsrcs.addAll(aux.rsrcs);
458 * Returns a resource that can be used to download a patch file that will bring this
459 * application from its current version to the target version.
461 * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
462 * for the main application patch resource.
464 public Resource getPatchResource (String auxgroup)
466 if (_targetVersion <= _version) {
467 log.warning("Requested patch resource for up-to-date or non-versioned application",
468 "cvers", _version, "tvers", _targetVersion);
472 String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
473 String pfile = "patch" + infix + _version + ".dat";
475 URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
476 return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
477 } catch (Exception e) {
478 log.warning("Failed to create patch resource path",
479 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
485 * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
486 * place of the installed VM (in the case where the VM that launched Getdown does not meet the
487 * application's version requirements) or null if no VM is available for this platform.
489 public Resource getJavaVMResource ()
491 if (StringUtil.isBlank(_javaLocation)) {
495 String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
496 String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
497 log.info("vmfile is '"+vmfile+"'");
498 System.out.println("vmfile is '"+vmfile+"'");
500 URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
501 log.info("Attempting to fetch jvm at "+remote.toString());
502 System.out.println("Attempting to fetch jvm at "+remote.toString());
503 return new Resource(vmfile, remote, getLocalPath(vmfile),
504 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
505 } catch (Exception e) {
506 log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
507 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
508 System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
509 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
515 * Returns a resource that can be used to download an archive containing all files belonging to
518 public Resource getFullResource ()
520 String file = "full";
522 URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
523 return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
524 } catch (Exception e) {
525 log.warning("Failed to create full resource path",
526 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
532 * Returns the URL to use to report an initial download event. Returns null if no tracking
533 * start URL was configured for this application.
535 * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
537 public URL getTrackingURL (String event)
540 String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
541 String ga = getGATrackingCode();
542 return _trackingURL == null ? null :
543 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
544 } catch (MalformedURLException mue) {
545 log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
551 * Returns the URL to request to report that we have reached the specified percentage of our
552 * initial download. Returns null if no tracking request was configured for the specified
555 public URL getTrackingProgressURL (int percent)
557 if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
560 return getTrackingURL("pct" + percent);
564 * Returns the name of our tracking cookie or null if it was not set.
566 public String getTrackingCookieName ()
568 return _trackingCookieName;
572 * Returns the name of our tracking cookie system property or null if it was not set.
574 public String getTrackingCookieProperty ()
576 return _trackingCookieProperty;
580 * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
581 * for operation. The application base URL will be parsed first so that if there are errors
582 * discovered later, the caller can use the application base to download a new {@code
583 * getdown.txt} file and try again.
585 * @return a {@code Config} instance that contains information from the config file.
587 * @exception IOException thrown if there is an error reading the file or an error encountered
588 * during its parsing.
590 public Config init (boolean checkPlatform)
593 if (_initialised && _initialisedConfig != null)
595 return _initialisedConfig;
599 Application.i4jVersion = com.install4j.api.launcher.Variables.getCompilerVariable("sys.install4jVersion");
600 } catch (IOException e)
602 System.err.println("install4j version not available");
603 } catch (NoClassDefFoundError e)
605 log.warning("Starting without install4j classes");
606 } catch (Throwable t)
608 System.err.println("install4j not available");
612 Config config = null;
613 File cfgfile = _config;
614 Config.ParseOpts opts = Config.createOpts(checkPlatform);
616 // if we have a configuration file, read the data from it
617 if (cfgfile.exists()) {
618 config = Config.parseConfig(_config, opts);
620 // otherwise, try reading data from our backup config file; thanks to funny windows
621 // bullshit, we have to do this backup file fiddling in case we got screwed while
622 // updating getdown.txt during normal operation
623 else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
624 config = Config.parseConfig(cfgfile, opts);
626 // otherwise, issue a warning that we found no getdown file
628 log.info("Found no getdown.txt file", "appdir", getAppDir());
630 } catch (Exception e) {
631 log.warning("Failure reading config file", "file", _config, e);
633 if (config == null || config.getString("appbase") == null || config.getString("appbase").isEmpty()) {
635 Config backupConfig = Config.parseConfig(_backupConfig, opts);
636 config = backupConfig;
637 log.warning("Using backup config file", "appdir", getAppDir(), "backupConfig", _backupConfig.getAbsoluteFile());
638 } catch (Exception e) {
639 log.warning("Failure reading backup config file", "file", _backupConfig, e);
643 // see if there's an override config from locator file
644 Config locatorConfig = createLocatorConfig(opts);
646 // merge the locator file config into config (or replace config with)
647 if (locatorConfig != null) {
648 if (config == null || locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_replace")) {
649 config = locatorConfig;
651 config.mergeConfig(locatorConfig, locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_merge"));
655 // if we failed to read our config file, check for an appbase specified via a system
656 // property; we can use that to bootstrap ourselves back into operation
657 if (config == null) {
658 String appbase = _envc.appBase;
659 log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
660 Map<String, Object> cdata = new HashMap<>();
661 cdata.put("appbase", appbase);
662 config = new Config(cdata);
665 // first determine our application base, this way if anything goes wrong later in the
666 // process, our caller can use the appbase to download a new configuration file
667 _appbase = config.getString("appbase");
669 // see if locatorConfig override
670 if (locatorConfig != null && !StringUtil.isBlank(locatorConfig.getString("appbase"))) {
671 _appbase = locatorConfig.getString("appbase");
674 if (_appbase == null) {
675 throw new RuntimeException("m.missing_appbase");
678 // check if we're overriding the domain in the appbase
679 _appbase = SysProps.overrideAppbase(_appbase);
681 // make sure there's a trailing slash
682 if (!_appbase.endsWith("/")) {
683 _appbase = _appbase + "/";
686 // extract our version information
687 _version = config.getLong("version", -1L);
689 // if we are a versioned deployment, create a versioned appbase
691 _vappbase = createVAppBase(_version);
692 } catch (MalformedURLException mue) {
693 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
694 throw (IOException) new IOException(err).initCause(mue);
697 // check for a latest config URL
698 String latest = config.getString("latest");
699 if (latest != null) {
700 if (latest.startsWith(_appbase)) {
701 latest = _appbase + latest.substring(_appbase.length());
703 latest = SysProps.replaceDomain(latest);
706 _latest = HostWhitelist.verify(new URL(latest));
707 } catch (MalformedURLException mue) {
708 log.warning("Invalid URL for latest attribute.", mue);
712 String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
714 // determine our application class name (use app-specific class _if_ one is provided)
715 _class = config.getString("class");
716 if (appPrefix.length() > 0) {
717 _class = config.getString(appPrefix + "class", _class);
719 if (_class == null) {
720 throw new IOException("m.missing_class");
723 // determine whether we want strict comments
724 _strictComments = config.getBoolean("strict_comments");
726 // check to see if we're using a custom java.version property and regex
727 _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
728 _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
730 // check to see if we require a particular JVM version and have a supplied JVM
731 _javaMinVersion = config.getLong("java_version", _javaMinVersion);
732 // we support java_min_version as an alias of java_version; it better expresses the check
733 // that's going on and better mirrors java_max_version
734 _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
735 // check to see if we require a particular max JVM version and have a supplied JVM
736 _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
737 // check to see if we require a particular JVM version and have a supplied JVM
738 _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
740 // this is a little weird, but when we're run from the digester, we see a String[] which
741 // contains java locations for all platforms which we can't grok, but the digester doesn't
742 // need to know about that; when we're run in a real application there will be only one!
743 Object javaloc = config.getRaw("java_location");
744 if (javaloc instanceof String) {
745 _javaLocation = (String)javaloc;
748 // determine whether we have any tracking configuration
749 _trackingURL = config.getString("tracking_url");
751 // check for tracking progress percent configuration
752 String trackPcts = config.getString("tracking_percents");
753 if (!StringUtil.isBlank(trackPcts)) {
754 _trackingPcts = new HashSet<>();
755 for (int pct : StringUtil.parseIntArray(trackPcts)) {
756 _trackingPcts.add(pct);
758 } else if (!StringUtil.isBlank(_trackingURL)) {
759 _trackingPcts = new HashSet<>();
760 _trackingPcts.add(50);
763 // Check for tracking cookie configuration
764 _trackingCookieName = config.getString("tracking_cookie_name");
765 _trackingCookieProperty = config.getString("tracking_cookie_property");
767 // Some app may need an extra suffix added to the tracking URL
768 _trackingURLSuffix = config.getString("tracking_url_suffix");
770 // Some app may need to generate google analytics code
771 _trackingGAHash = config.getString("tracking_ga_hash");
773 // clear our arrays as we may be reinitializing
781 // parse our code resources
782 if (config.getMultiValue("code") == null &&
783 config.getMultiValue("ucode") == null) {
784 throw new IOException("m.missing_code");
786 parseResources(config, "code", Resource.NORMAL, _codes);
787 parseResources(config, "ucode", Resource.UNPACK, _codes);
789 // parse our non-code resources
790 parseResources(config, "resource", Resource.NORMAL, _resources);
791 parseResources(config, "uresource", Resource.UNPACK, _resources);
792 parseResources(config, "xresource", Resource.EXEC, _resources);
793 parseResources(config, "presource", Resource.PRELOAD, _resources);
794 parseResources(config, "nresource", Resource.NATIVE, _resources);
796 // parse our auxiliary resource groups
797 for (String auxgroup : config.getList("auxgroups")) {
798 ArrayList<Resource> codes = new ArrayList<>();
799 parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
800 parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
801 ArrayList<Resource> rsrcs = new ArrayList<>();
802 parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
803 parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
804 parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
805 parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
806 parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
807 _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
810 // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
811 String[] jvmargs = config.getMultiValue("jvmarg");
812 addAll(jvmargs, _jvmargs);
813 if (appPrefix.length() > 0) {
814 jvmargs = config.getMultiValue(appPrefix + "jvmarg");
815 addAll(jvmargs, _jvmargs);
818 // see if a percentage of physical memory, or max heap size options exist
819 jvmmempc = config.getString("jvmmempc", null);
820 jvmmemmax = config.getString("jvmmemmax", null);
821 // app_id prefixed setting overrides
822 if (appPrefix.length() > 0) {
823 jvmmempc = config.getString(appPrefix + "jvmmempc", jvmmempc);
824 jvmmemmax = config.getString(appPrefix + "jvmmemmax", jvmmemmax);
827 // get the set of optimum JVM arguments
828 _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
830 // transfer our application arguments
831 String[] appargs = config.getMultiValue(appPrefix + "apparg");
832 addAll(appargs, _appargs);
834 // add the launch specific application arguments
835 _appargs.addAll(_envc.appArgs);
837 // look for custom arguments
838 fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
840 // determine whether we want to allow offline operation (defaults to false)
841 _allowOffline = config.getBoolean("allow_offline");
843 // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
844 // obtain a thread dump of the running JVM
845 _windebug = getLocalPath("debug.txt").exists();
847 // whether to cache code resources and launch from cache
848 _useCodeCache = config.getBoolean("use_code_cache");
849 _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
851 // maximum simultaneous downloads
852 _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
853 SysProps.threadPoolSize()));
855 // extract some info used to configure our child process on macOS
856 _dockName = config.getString("ui.name");
857 _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
860 _initialisedConfig = config;
865 * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
867 protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
869 File pairFile = getLocalPath(pairLocation);
870 if (pairFile.exists()) {
872 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
873 for (String[] pair : args) {
874 if (pair[1].length() == 0) {
875 collector.add(pair[0]);
877 collector.add(pair[0] + "=" + pair[1]);
880 } catch (Throwable t) {
881 log.warning("Failed to parse '" + pairFile + "': " + t);
887 * Returns a URL from which the specified path can be fetched. Our application base URL is
888 * properly versioned and combined with the supplied path.
890 public URL getRemoteURL (String path)
891 throws MalformedURLException
893 return new URL(_vappbase, encodePath(path));
897 * Returns the local path to the specified resource.
899 public File getLocalPath (String path)
901 return getLocalPath(getAppDir(), path);
905 * Returns true if we either have no version requirement, are running in a JVM that meets our
906 * version requirements or have what appears to be a version of the JVM that meets our
909 public boolean haveValidJavaVersion ()
911 // if we're doing no version checking, then yay!
912 if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
915 // parse the version out of the java.version (or custom) system property
916 long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
918 log.info("Checking Java version", "current", version,
919 "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
921 // if we have an unpacked VM, check the 'release' file for its version
922 Resource vmjar = getJavaVMResource();
923 if (vmjar != null && vmjar.isMarkedValid()) {
924 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
925 File relfile = new File(vmdir, "release");
926 if (!relfile.exists()) {
927 log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
931 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
933 log.warning("Unable to read version from 'release' file. Assuming valid.");
938 log.info("Checking version of unpacked JVM [vers=" + version + "].");
941 if (_javaExactVersionRequired) {
942 if (version == _javaMinVersion) return true;
944 log.warning("An exact Java VM version is required.", "current", version,
945 "required", _javaMinVersion);
950 boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
951 boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
952 return minVersionOK && maxVersionOK;
954 } catch (RuntimeException re) {
955 // if we can't parse the java version we're in weird land and should probably just try
956 // our luck with what we've got rather than try to download a new jvm
957 log.warning("Unable to parse VM version, hoping for the best",
958 "error", re, "needed", _javaMinVersion);
964 * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
965 * whether the launch is successful and, if necessary, trying again without the optimum
968 public boolean hasOptimumJvmArgs ()
970 return _optimumJvmArgs != null;
974 * Returns true if the app should attempt to run even if we have no Internet connection.
976 public boolean allowOffline ()
978 return _allowOffline;
982 * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
983 * previous call to {@link #init}.
985 public void attemptRecovery (StatusDisplay status)
988 status.updateStatus("m.updating_metadata");
989 downloadConfigFile();
993 * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
994 * those for the target version of our application.
996 public void updateMetadata ()
1000 // update our versioned application base with the target version
1001 _vappbase = createVAppBase(_targetVersion);
1002 } catch (MalformedURLException mue) {
1003 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
1004 throw (IOException) new IOException(err).initCause(mue);
1008 // now re-download our control files; we download the digest first so that if it fails,
1009 // our config file will still reference the old version and re-running the updater will
1010 // start the whole process over again
1011 downloadDigestFiles();
1012 downloadConfigFile();
1014 } catch (IOException ex) {
1015 // if we are allowing offline execution, we want to allow the application to run in its
1016 // current form rather than aborting the entire process; to do this, we delete the
1017 // version.txt file and "trick" Getdown into thinking that it just needs to validate
1018 // the application as is; next time the app runs when connected to the internet, it
1019 // will have to rediscover that it needs updating and reattempt to update itself
1020 if (_allowOffline) {
1021 log.warning("Failed to update digest files. Attempting offline operaton.", ex);
1022 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
1023 log.warning("Deleting version.txt failed. This probably isn't going to work.");
1032 * Invokes the process associated with this application definition.
1034 * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
1037 public Process createProcess (boolean optimum)
1040 ArrayList<String> args = new ArrayList<>();
1042 // reconstruct the path to the JVM
1043 args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
1045 // check whether we're using -jar mode or -classpath mode
1046 boolean dashJarMode = MANIFEST_CLASS.equals(_class);
1048 // add the -classpath arguments if we're not in -jar mode
1049 ClassPath classPath = PathBuilder.buildClassPath(this);
1051 args.add("-classpath");
1052 args.add(classPath.asArgumentString());
1055 // we love our Mac users, so we do nice things to preserve our application identity
1056 if (LaunchUtil.isMacOS()) {
1057 args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1058 args.add("-Xdock:name=" + _dockName);
1061 // pass along our proxy settings
1062 String proxyHost = System.getProperty("http.proxyHost");
1063 String proxyPort = StringUtil.isBlank(System.getProperty("http.proxyPort")) ? "80" : System.getProperty("http.proxyPort");
1064 if (StringUtil.isBlank(proxyHost) && ! proxy.equals(Proxy.NO_PROXY)) {
1066 SocketAddress a = proxy.address();
1067 if (a != null && a instanceof InetSocketAddress) {
1068 InetSocketAddress ia = (InetSocketAddress)a;
1069 proxyHost = ia.getHostString();
1070 proxyPort = String.valueOf(ia.getPort());
1072 } catch (Exception e) {
1073 log.error("Problem obtaining proxy settings from Proxy object");
1074 e.printStackTrace();
1077 if (proxyHost != null) {
1078 log.info("Using proxy settings "+proxyHost+":"+proxyPort);
1079 args.add("-Dhttp.proxyHost=" + proxyHost);
1080 args.add("-Dhttp.proxyPort=" + proxyPort);
1081 args.add("-Dhttps.proxyHost=" + proxyHost);
1082 args.add("-Dhttps.proxyPort=" + proxyPort);
1084 log.info("Not setting proxy");
1087 // add the getdowninstanceappbase property. getdownappdir is added by getdown.txt
1088 args.add("-Dgetdowninstanceappbase=" + getAppbase().toString());
1090 // add the marker indicating the app is running in getdown
1091 args.add("-D" + Properties.GETDOWN + "=true");
1092 args.add("-Dsys.install4jVersion=" + Application.i4jVersion);
1093 args.add("-Dinstaller_template_version=" + System.getProperty("installer_template_version"));
1094 args.add("-Dlauncher_version=" + Build.version());
1096 // set HiDPI property if wanted
1097 String scalePropertyArg = HiDPISetting.getScalePropertyArg();
1098 if (scalePropertyArg != null)
1100 args.add(scalePropertyArg);
1103 // set the native library path if we have native resources
1104 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1105 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1106 if (javaLibPath != null) {
1107 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1110 // pass along any pass-through arguments
1111 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1112 String key = (String)entry.getKey();
1113 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1114 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1115 args.add("-D" + key + "=" + entry.getValue());
1119 // test for jalviewX://... URI. Insert startupNotification URI into start of _appargs
1120 if (! StringUtil.isBlank(_jalviewUri)) {
1121 _appargs.add(0, _jalviewUri);
1123 /* don't convert jalviewX:// URIs to https:// URLs as Jalview can now do that
1124 if (_appargs.size() > 0) {
1125 String jalviewUri = _appargs.get(0);
1126 log.info("Trying to parse uri '"+jalviewUri+"'");
1127 if (HttpUtils.isJalviewSchemeUri(jalviewUri)) {
1128 String jalviewUrl = HttpUtils.equivalentJalviewUrl(jalviewUri);
1129 log.info("Turned url '"+jalviewUri+"' into '"+jalviewUrl+"'");
1131 _appargs.add(jalviewUrl);
1136 for (String argString: _appargs) {
1137 if (argString.startsWith("-jvmmempc=")) {
1138 jvmmempc = argString.substring(10);
1141 if (argString.startsWith("-jvmmemmax=")) {
1142 jvmmemmax = argString.substring(11);
1145 if (argString.startsWith("--jvmmempc=")) {
1146 jvmmempc = argString.substring(11);
1149 if (argString.startsWith("--jvmmemmax=")) {
1150 jvmmemmax = argString.substring(12);
1155 // use saved preferences if no cmdline args
1156 LaunchUtils.loadChannelProps(getAppDir());
1157 if (LaunchUtils.getBooleanUserPreference(MemorySetting.CUSTOMISED_SETTINGS)) {
1158 if (jvmmempc == null) {
1159 jvmmempc = LaunchUtils.getUserPreference(MemorySetting.MEMORY_JVMMEMPC);
1161 if (jvmmemmax == null) {
1162 jvmmemmax = LaunchUtils.getUserPreference(MemorySetting.MEMORY_JVMMEMMAX);
1166 // add the memory setting from jvmmempc and jvmmemmax
1167 long maxMemLong = -1;
1168 maxMemLong = MemorySetting.getMemorySetting(jvmmemmax, jvmmempc);
1171 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
1172 // remove other max heap size arg
1173 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
1174 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
1179 addAll(maxMemHeapArg, _jvmargs);
1182 // add the JVM arguments
1183 for (String string : _jvmargs) {
1184 args.add(processArg(string));
1187 // add the optimum arguments if requested and available
1188 if (optimum && _optimumJvmArgs != null) {
1189 for (String string : _optimumJvmArgs) {
1190 args.add(processArg(string));
1194 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1195 for (String string : _txtJvmArgs) {
1196 args.add(processArg(string));
1199 // if we're in -jar mode add those arguments, otherwise add the app class name
1202 args.add(classPath.asArgumentString());
1207 // almost finally check the startup file arguments
1208 for (String f : _startupFiles) {
1209 _appargs.add(HttpUtils.isPlausibleUri(f)?f:new File(f).getAbsolutePath());
1212 // check if one arg with recognised extension
1213 if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1214 String filename = _appargs.get(0);
1216 int j = filename.lastIndexOf('.');
1218 ext = filename.substring(j+1);
1220 if (ext != null && LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase(Locale.ROOT))) {
1221 // this file extension should have been dealt with in Getdown class
1225 // finally add the application arguments
1226 for (String string : _appargs) {
1227 args.add(processArg(string));
1230 String[] envp = createEnvironment();
1231 String[] sargs = args.toArray(new String[args.size()]);
1232 log.info("Running " + StringUtil.join(sargs, "\n "));
1234 // don't set the working dir, leave it the same as the working dir of the invocation
1235 //return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1236 return Runtime.getRuntime().exec(sargs, envp);
1240 * If the application provided environment variables, combine those with the current
1241 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1242 * If the application didn't provide any environment variables, null is returned to just use
1243 * the existing environment.
1245 protected String[] createEnvironment ()
1247 List<String> envvar = new ArrayList<>();
1248 fillAssignmentListFromPairs("env.txt", envvar);
1249 if (envvar.isEmpty()) {
1250 log.info("Didn't find any custom environment variables, not setting any.");
1254 List<String> envAssignments = new ArrayList<>();
1255 for (String assignment : envvar) {
1256 envAssignments.add(processArg(assignment));
1258 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1259 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1261 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1262 log.info("Environment " + StringUtil.join(envp, "\n "));
1267 * Runs this application directly in the current VM.
1269 public void invokeDirect () throws IOException
1271 ClassPath classPath = PathBuilder.buildClassPath(this);
1272 URL[] jarUrls = classPath.asUrls();
1274 // create custom class loader
1275 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1276 @Override protected PermissionCollection getPermissions (CodeSource code) {
1277 Permissions perms = new Permissions();
1278 perms.add(new AllPermission());
1282 Thread.currentThread().setContextClassLoader(loader);
1284 log.info("Configured URL class loader:");
1285 for (URL url : jarUrls) log.info(" " + url);
1287 // configure any system properties that we can
1288 for (String jvmarg : _jvmargs) {
1289 if (jvmarg.startsWith("-D")) {
1290 jvmarg = processArg(jvmarg.substring(2));
1291 int eqidx = jvmarg.indexOf("=");
1293 log.warning("Bogus system property: '" + jvmarg + "'?");
1295 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1300 // pass along any pass-through arguments
1301 Map<String, String> passProps = new HashMap<>();
1302 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1303 String key = (String)entry.getKey();
1304 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1305 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1306 passProps.put(key, (String)entry.getValue());
1309 // we can't set these in the above loop lest we get a ConcurrentModificationException
1310 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1311 System.setProperty(entry.getKey(), entry.getValue());
1314 // prepare our app arguments
1315 String[] args = new String[_appargs.size()];
1316 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1319 log.info("Loading " + _class);
1320 Class<?> appclass = loader.loadClass(_class);
1321 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1322 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1323 main.invoke(null, new Object[] { args });
1324 } catch (Exception e) {
1325 log.warning("Failure invoking app main", e);
1329 /** Replaces the application directory and version in any argument. */
1330 protected String processArg (String arg)
1332 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1333 arg = arg.replace("%VERSION%", String.valueOf(_version));
1335 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1336 // from the environment
1337 if (arg.contains(ENV_VAR_PREFIX)) {
1338 StringBuffer sb = new StringBuffer();
1339 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1340 while (matcher.find()) {
1341 String varName = matcher.group(1), varValue = System.getenv(varName);
1342 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1343 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1345 matcher.appendTail(sb);
1346 arg = sb.toString();
1353 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1354 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1355 * whether or not the application needs to be updated or whether we can proceed to verification
1358 * @return true if the application needs to be updated, false if it is up to date and can be
1359 * verified and executed.
1361 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1364 public boolean verifyMetadata (StatusDisplay status)
1367 log.info("Verifying application: " + _vappbase);
1368 log.info("Version: " + _version);
1369 log.info("Class: " + _class);
1371 // this will read in the contents of the digest file and validate itself
1373 _digest = new Digest(getAppDir(), _strictComments);
1374 } catch (IOException ioe) {
1375 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1378 // if we have no version, then we are running in unversioned mode so we need to download
1379 // our digest.txt file on every invocation
1380 if (_version == -1) {
1381 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1382 // resources as one or more of them have also changed
1383 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1385 status.updateStatus("m.checking");
1386 downloadDigestFiles();
1387 _digest = new Digest(getAppDir(), _strictComments);
1388 if (!olddig.equals(_digest.getMetaDigest())) {
1389 log.info("Unversioned digest changed. Revalidating...");
1390 status.updateStatus("m.validating");
1391 clearValidationMarkers();
1393 } catch (IOException ioe) {
1394 log.warning("Failed to refresh non-versioned digest: " +
1395 ioe.getMessage() + ". Proceeding...");
1399 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1400 // redownload the digest file and give it another good college try; this time we allow
1401 // exceptions to propagate up to the caller as there is nothing else we can do
1402 if (_digest == null) {
1403 status.updateStatus("m.updating_metadata");
1404 downloadDigestFiles();
1405 _digest = new Digest(getAppDir(), _strictComments);
1408 // now verify the contents of our main config file
1409 Resource crsrc = getConfigResource();
1410 if (!_digest.validateResource(crsrc, null)) {
1411 status.updateStatus("m.updating_metadata");
1412 // attempt to redownload both of our metadata files; again we pass errors up to our
1413 // caller because there's nothing we can do to automatically recover
1414 downloadConfigFile();
1415 downloadDigestFiles();
1416 _digest = new Digest(getAppDir(), _strictComments);
1417 // revalidate everything if we end up downloading new metadata
1418 clearValidationMarkers();
1419 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1420 if (_digest.validateResource(crsrc, null)) {
1421 // unset _initialisedConfig so new file is initialised
1422 _initialisedConfig = null;
1425 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1426 "Blindly forging onward.");
1430 // start by assuming we are happy with our version
1431 _targetVersion = _version;
1433 // if we are a versioned application, read in the contents of the version.txt file
1434 // and/or check the latest config URL for a newer version
1435 if (_version != -1) {
1436 File vfile = getLocalPath(VERSION_FILE);
1437 long fileVersion = VersionUtil.readVersion(vfile);
1438 if (fileVersion != -1) {
1439 _targetVersion = fileVersion;
1442 if (_latest != null) {
1443 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1444 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1445 BufferedReader bin = new BufferedReader(reader)) {
1446 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1447 if (pair[0].equals("version")) {
1448 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1449 if (fileVersion != -1 && _targetVersion > fileVersion) {
1450 // replace the file with the newest version
1451 try (FileOutputStream fos = new FileOutputStream(vfile);
1452 PrintStream out = new PrintStream(fos)) {
1453 out.println(_targetVersion);
1459 } catch (Exception e) {
1460 log.warning("Unable to retrieve version from latest config file.", e);
1465 // finally let the caller know if we need an update
1466 return _version != _targetVersion;
1470 * Verifies the code and media resources associated with this application. A list of resources
1471 * that do not exist or fail the verification process will be returned. If all resources are
1472 * ready to go, null will be returned and the application is considered ready to run.
1474 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1475 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1476 * you have to take care to get back to your UI thread.
1477 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1478 * validated" resources filled in.
1479 * @param unpacked a set to populate with unpacked resources.
1480 * @param toInstall a list into which to add resources that need to be installed.
1481 * @param toDownload a list into which to add resources that need to be downloaded.
1483 public void verifyResources (
1484 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1485 Set<Resource> toInstall, Set<Resource> toDownload)
1486 throws InterruptedException
1488 // resources are verified on background threads supplied by the thread pool, and progress
1489 // is reported by posting runnable actions to the actions queue which is processed by the
1491 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1492 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1493 final int[] completed = new int[1];
1495 long start = System.currentTimeMillis();
1497 // obtain the sizes of the resources to validate
1498 List<Resource> rsrcs = getAllActiveResources();
1499 long[] sizes = new long[rsrcs.size()];
1501 for (int ii = 0; ii < sizes.length; ii++) {
1502 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1504 final ProgressObserver fobs = obs;
1505 // as long as we forward aggregated progress updates to the UI thread, having multiple
1506 // threads update a progress aggregator is "mostly" thread-safe
1507 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1508 public void progress (final int percent) {
1509 actions.add(new Runnable() {
1510 public void run () {
1511 fobs.progress(percent);
1517 final int[] fAlreadyValid = alreadyValid;
1518 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1519 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1520 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1522 for (int ii = 0; ii < sizes.length; ii++) {
1523 final Resource rsrc = rsrcs.get(ii);
1524 final int index = ii;
1525 exec.execute(new Runnable() {
1526 public void run () {
1527 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1528 unpackedAsync, toInstallAsync, toDownloadAsync);
1529 actions.add(new Runnable() {
1530 public void run () {
1538 while (completed[0] < rsrcs.size()) {
1539 // we should be getting progress completion updates WAY more often than one every
1540 // minute, so if things freeze up for 60 seconds, abandon ship
1541 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1547 toInstall.addAll(toInstallAsync);
1548 toDownload.addAll(toDownloadAsync);
1549 unpacked.addAll(unpackedAsync);
1551 long complete = System.currentTimeMillis();
1552 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1553 "duration", (complete-start) + "ms");
1556 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1557 Set<Resource> unpacked,
1558 Set<Resource> toInstall, Set<Resource> toDownload) {
1559 if (rsrc.isMarkedValid()) {
1560 if (alreadyValid != null) {
1568 if (_digest.validateResource(rsrc, obs)) {
1569 // if the resource has a _new file, add it to to-install list
1570 if (rsrc.getLocalNew().exists()) {
1571 toInstall.add(rsrc);
1580 } catch (Exception e) {
1581 log.info("Failure verifying resource. Requesting redownload...",
1582 "rsrc", rsrc, "error", e);
1587 toDownload.add(rsrc);
1591 * Unpacks the resources that require it (we know that they're valid).
1593 * @param unpacked a set of resources to skip because they're already unpacked.
1595 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1596 throws InterruptedException
1598 List<Resource> rsrcs = getActiveResources();
1600 // remove resources that we don't want to unpack
1601 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1602 Resource rsrc = it.next();
1603 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1608 // obtain the sizes of the resources to unpack
1609 long[] sizes = new long[rsrcs.size()];
1610 for (int ii = 0; ii < sizes.length; ii++) {
1611 sizes[ii] = rsrcs.get(ii).getLocal().length();
1614 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1615 for (int ii = 0; ii < sizes.length; ii++) {
1616 Resource rsrc = rsrcs.get(ii);
1617 ProgressObserver pobs = pagg.startElement(ii);
1620 } catch (IOException ioe) {
1621 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1628 * Clears all validation marker files.
1630 public void clearValidationMarkers ()
1632 clearValidationMarkers(getAllActiveResources().iterator());
1636 * Returns the version number for the application. Should only be called after successful
1637 * return of verifyMetadata.
1639 public long getVersion ()
1645 * Creates a versioned application base URL for the specified version.
1647 protected URL createVAppBase (long version)
1648 throws MalformedURLException
1650 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1651 return HostWhitelist.verify(new URL(url));
1655 * Clears all validation marker files for the resources in the supplied iterator.
1657 protected void clearValidationMarkers (Iterator<Resource> iter)
1659 while (iter.hasNext()) {
1660 iter.next().clearMarker();
1665 * Downloads a new copy of CONFIG_FILE.
1667 protected void downloadConfigFile ()
1670 downloadControlFile(CONFIG_FILE, 0);
1674 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1675 * we're not locking at all.
1677 public synchronized boolean lockForUpdates ()
1679 if (_lock != null && _lock.isValid()) {
1683 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1684 } catch (FileNotFoundException e) {
1685 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1689 _lock = _lockChannel.tryLock();
1690 } catch (IOException e) {
1691 log.warning("Unable to create lock", "message", e.getMessage(), e);
1693 } catch (OverlappingFileLockException e) {
1694 log.warning("The lock is held elsewhere in this JVM", e);
1697 log.info("Able to lock for updates: " + (_lock != null));
1698 return _lock != null;
1702 * Release gettingdown.lock
1704 public synchronized void releaseLock ()
1706 if (_lock != null) {
1707 log.info("Releasing lock");
1710 } catch (IOException e) {
1711 log.warning("Unable to release lock", "message", e.getMessage(), e);
1714 _lockChannel.close();
1715 } catch (IOException e) {
1716 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1718 _lockChannel = null;
1724 * Downloads the digest files and validates their signature.
1725 * @throws IOException
1727 protected void downloadDigestFiles ()
1730 for (int version = 1; version <= Digest.VERSION; version++) {
1731 downloadControlFile(Digest.digestFile(version), version);
1736 * Downloads a new copy of the specified control file, optionally validating its signature.
1737 * If the download is successful, moves it over the old file on the filesystem.
1739 * <p> TODO: Switch to PKCS #7 or CMS.
1741 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1742 * should indicate the version of the digest file being validated which indicates which
1743 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1745 protected void downloadControlFile (String path, int sigVersion)
1748 File target = downloadFile(path);
1750 if (sigVersion > 0) {
1751 if (_envc.certs.isEmpty()) {
1752 log.info("No signing certs, not verifying digest.txt", "path", path);
1755 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1756 byte[] signature = null;
1757 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1758 signature = StreamUtil.toByteArray(signatureStream);
1760 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1763 byte[] buffer = new byte[8192];
1764 int length, validated = 0;
1765 for (Certificate cert : _envc.certs) {
1766 try (FileInputStream dataInput = new FileInputStream(target)) {
1767 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1768 sig.initVerify(cert);
1769 while ((length = dataInput.read(buffer)) != -1) {
1770 sig.update(buffer, 0, length);
1773 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1774 log.info("Signature does not match", "cert", cert.getPublicKey());
1777 log.info("Signature matches", "cert", cert.getPublicKey());
1781 } catch (IOException ioe) {
1782 log.warning("Failure validating signature of " + target + ": " + ioe);
1784 } catch (GeneralSecurityException gse) {
1790 // if we couldn't find a key that validates our digest, we are the hosed!
1791 if (validated == 0) {
1792 // delete the temporary digest file as we know it is invalid
1793 FileUtil.deleteHarder(target);
1794 throw new IOException("m.corrupt_digest_signature_error");
1799 // now move the temporary file over the original
1800 File original = getLocalPath(path);
1801 if (!FileUtil.renameTo(target, original)) {
1802 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1807 * Download a path to a temporary file, returning a {@link File} instance with the path
1810 protected File downloadFile (String path)
1813 File target = getLocalPath(path + "_new");
1815 URL targetURL = null;
1817 targetURL = getRemoteURL(path);
1818 } catch (Exception e) {
1819 log.warning("Requested to download invalid control file",
1820 "appbase", _vappbase, "path", path, "error", e);
1821 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1824 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1826 // stream the URL into our temporary file
1827 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1828 // we have to tell Java not to use caches here, otherwise it will cache any request for
1829 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1830 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1831 // about it; turning off caches is not a performance concern, because when Getdown asks
1832 // to download a file, it expects it to come over the wire, not from a cache
1833 uconn.setUseCaches(false);
1834 uconn.setRequestProperty("Accept-Encoding", "gzip");
1835 try (InputStream fin = uconn.getInputStream()) {
1836 String encoding = uconn.getContentEncoding();
1837 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1838 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1839 try (FileOutputStream fout = new FileOutputStream(target)) {
1840 StreamUtil.copy(fin2, fout);
1848 /** Helper function for creating {@link Resource} instances. */
1849 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1850 throws MalformedURLException
1852 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1855 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1856 protected static void addAll (String[] values, List<String> target) {
1857 if (values != null) {
1858 for (String value : values) {
1865 * Make an immutable List from the specified int array.
1867 public static List<Integer> intsToList (int[] values)
1869 List<Integer> list = new ArrayList<>(values.length);
1870 for (int val : values) {
1873 return Collections.unmodifiableList(list);
1877 * Make an immutable List from the specified String array.
1879 public static List<String> stringsToList (String[] values)
1881 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1884 /** Used to parse resources with the specified name. */
1885 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1886 List<Resource> list)
1888 String[] rsrcs = config.getMultiValue(name);
1889 if (rsrcs == null) {
1892 for (String rsrc : rsrcs) {
1894 list.add(createResource(rsrc, attrs));
1895 } catch (Exception e) {
1896 log.warning("Invalid resource '" + rsrc + "'. " + e);
1901 /** Possibly generates and returns a google analytics tracking cookie. */
1902 protected String getGATrackingCode ()
1904 if (_trackingGAHash == null) {
1907 long time = System.currentTimeMillis() / 1000;
1908 if (_trackingStart == 0) {
1909 _trackingStart = time;
1911 if (_trackingId == 0) {
1912 int low = 100000000, high = 1000000000;
1913 _trackingId = low + _rando.nextInt(high-low);
1915 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1916 cookie.append(".").append(_trackingId);
1917 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1918 cookie.append(".").append(time).append(".1%3B%2B");
1919 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1920 cookie.append(_trackingStart).append(".1.1.");
1921 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1922 int low = 1000000000, high = 2000000000;
1923 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1924 return cookie.toString();
1928 * Encodes a path for use in a URL.
1930 protected static String encodePath (String path)
1933 // we want to keep slashes because we're encoding an entire path; also we need to turn
1934 // + into %20 because web servers don't like + in paths or file names, blah
1935 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1936 } catch (UnsupportedEncodingException ue) {
1937 log.warning("Failed to URL encode " + path + ": " + ue);
1942 protected File getLocalPath (File appdir, String path)
1944 return new File(appdir, path);
1947 public static void setStartupFilesFromParameters(List<String> parameters) {
1948 // multiple files *might* be passed in as space separated quoted filenames
1950 for (String p: parameters) {
1951 if (!StringUtil.isBlank(p)) {
1953 // split quoted params or treat as single string array
1954 if (p.startsWith(q) && p.endsWith(q)) {
1955 filename = p.substring(q.length(),p.length()-q.length());
1957 // single unquoted filename
1961 /* Now letting Jalview convert these URIs.
1962 // convert jalviewX://... URLs
1963 if (HttpUtils.isJalviewSchemeUri(filename)) {
1964 filename = HttpUtils.equivalentJalviewUrl(filename);
1968 // check for locator file. Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1969 if (filename.toLowerCase(Locale.ROOT).endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
1970 // convert jalviewX://... JVL files
1971 setLocatorFile(HttpUtils.equivalentJalviewUrl(filename));
1973 // skip any other locator files in a multiple file list
1974 addStartupFile(filename);
1980 public static String getStartupFilesParameterString(List<String> parameters, boolean changeJalviewSchemeUris) {
1981 StringBuilder sb = new StringBuilder();
1982 boolean first = true;
1983 for(String f : parameters) {
1989 String p = changeJalviewSchemeUris ? HttpUtils.equivalentJalviewUrl(f) : f;
1990 if (p.contains(" ")) {
1998 return sb.toString();
2001 public static void setLocatorFile(String filename) {
2002 _locatorFile = filename;
2005 public static void addStartupFile(String filename) {
2006 _startupFiles.add(filename);
2009 public static void setJalviewUri(String uri) {
2013 private Config createLocatorConfig(Config.ParseOpts opts) {
2014 if (_locatorFile == null) {
2018 Config locatorConfig = null;
2021 Config tmpConfig = null;
2022 Map<String, Object> tmpData = new HashMap<>();
2023 if (HttpUtils.startsWithHttpOrHttps(_locatorFile)) {
2024 URL locatorUrl = new URL(_locatorFile);
2025 try (InputStream in = ConnectionUtil.open(proxy, locatorUrl, 0, 0).getInputStream();
2026 InputStreamReader reader = new InputStreamReader(in, UTF_8);
2027 BufferedReader bin = new BufferedReader(reader)) {
2028 tmpConfig = Config.parseConfig(bin, opts);
2030 } else if (new File(_locatorFile).exists()) {
2031 tmpConfig = Config.parseConfig(new File(_locatorFile), opts);
2033 if (tmpConfig != null) {
2034 // appbase is sanitised in HostWhitelist
2035 Map<String, Object> tmpConfigData = tmpConfig.getData();
2036 if (tmpConfig != null) {
2037 for (Map.Entry<String, Object> entry : tmpConfigData.entrySet()) {
2038 String key = entry.getKey();
2039 Object value = entry.getValue();
2040 String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
2041 if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
2042 tmpData.put(key, value);
2046 log.warning("Error occurred reading config file", "file", _locatorFile);
2049 log.warning("Given locator file does not exist", "file", _locatorFile);
2052 locatorConfig = new Config(tmpData);
2054 } catch (Exception e) {
2055 log.warning("Failure reading locator file", "file", _locatorFile, e);
2058 return locatorConfig;
2061 public String getAppbase() {
2065 protected final EnvConfig _envc;
2066 protected File _config;
2067 protected File _backupConfig;
2068 protected Digest _digest;
2070 protected long _version = -1;
2071 protected long _targetVersion = -1;
2072 protected String _appbase;
2073 protected URL _vappbase;
2074 protected URL _latest;
2075 protected String _class;
2076 protected String _dockName;
2077 protected String _dockIconPath;
2078 protected boolean _strictComments;
2079 protected boolean _windebug;
2080 protected boolean _allowOffline;
2081 protected int _maxConcDownloads;
2083 protected String _trackingURL;
2084 protected Set<Integer> _trackingPcts;
2085 protected String _trackingCookieName;
2086 protected String _trackingCookieProperty;
2087 protected String _trackingURLSuffix;
2088 protected String _trackingGAHash;
2089 protected long _trackingStart;
2090 protected int _trackingId;
2092 protected String _javaVersionProp = "java.version";
2093 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
2094 protected long _javaMinVersion, _javaMaxVersion;
2095 protected boolean _javaExactVersionRequired;
2096 protected String _javaLocation;
2098 protected List<Resource> _codes = new ArrayList<>();
2099 protected List<Resource> _resources = new ArrayList<>();
2101 protected boolean _useCodeCache;
2102 protected int _codeCacheRetentionDays;
2104 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
2105 protected Map<String,Boolean> _auxactive = new HashMap<>();
2107 protected List<String> _jvmargs = new ArrayList<>();
2108 protected List<String> _appargs = new ArrayList<>();
2110 protected String[] _optimumJvmArgs;
2112 protected List<String> _txtJvmArgs = new ArrayList<>();
2114 /** If a warning has been issued about not being able to set modtimes. */
2115 protected boolean _warnedAboutSetLastModified;
2117 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
2118 protected FileLock _lock;
2120 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
2121 protected FileChannel _lockChannel;
2123 protected Random _rando = new Random();
2125 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
2127 protected static final String ENV_VAR_PREFIX = "%ENV.";
2128 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
2130 protected static String _locatorFile;
2131 protected static List<String> _startupFiles = new ArrayList<>();
2132 protected static String _jalviewUri;
2133 public static final String LOCATOR_FILE_EXTENSION = "jvl";
2135 private boolean _initialised = false;
2136 private Config _initialisedConfig = null;
2138 public static String i4jVersion = null;
2139 private String jvmmempc = null;
2140 private String jvmmemmax = null;