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.URISyntaxException;
17 import java.net.URLClassLoader;
18 import java.net.URLConnection;
19 import java.net.URLDecoder;
20 import java.net.URLEncoder;
21 import java.nio.channels.FileChannel;
22 import java.nio.channels.FileLock;
23 import java.nio.channels.OverlappingFileLockException;
24 import java.security.*;
25 import java.security.cert.Certificate;
27 import java.util.concurrent.*;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30 import java.util.zip.GZIPInputStream;
32 import jalview.bin.HiDPISetting;
33 import jalview.bin.MemorySetting;
34 import jalview.util.LaunchUtils;
36 import com.threerings.getdown.util.*;
37 // avoid ambiguity with java.util.Base64 which we can't use as it's 1.8+
38 import com.threerings.getdown.util.Base64;
40 import com.threerings.getdown.data.EnvConfig;
41 import com.threerings.getdown.data.EnvConfig.Note;
43 import static com.threerings.getdown.Log.log;
44 import static java.nio.charset.StandardCharsets.UTF_8;
47 * Parses and provide access to the information contained in the <code>getdown.txt</code>
50 public class Application
52 /** The name of our configuration file. */
53 public static final String CONFIG_FILE = "getdown.txt";
55 /** Dir where a backup config file might reside */
56 public static final String BACKUP_CONFIG_DIR = "install";
58 /** The name of our target version file. */
59 public static final String VERSION_FILE = "version.txt";
61 /** System properties that are prefixed with this string will be passed through to our
62 * application (minus this prefix). */
63 public static final String PROP_PASSTHROUGH_PREFIX = "app.";
65 /** Suffix used for control file signatures. */
66 public static final String SIGNATURE_SUFFIX = ".sig";
68 /** A special classname that means 'use -jar code.jar' instead of a classname. */
69 public static final String MANIFEST_CLASS = "manifest";
71 /** Used to communicate information about the UI displayed when updating the application. */
72 public static final class UpdateInterface
75 * The major steps involved in updating, along with some arbitrary percentages
76 * assigned to them, to mark global progress.
82 //VERIFY_METADATA(15, 65, 95),
83 VERIFY_METADATA(15, 45, 90),
86 //VERIFY_RESOURCES(70, 97),
87 VERIFY_RESOURCES(40, 90),
88 //REDOWNLOAD_RESOURCES(90),
89 REDOWNLOAD_RESOURCES(80),
95 /** What is the final percent value for this step? */
96 public final List<Integer> defaultPercents;
98 /** Enum constructor. */
99 Step (int... percents)
101 this.defaultPercents = intsToList(percents);
105 /** The human readable name of this application. */
106 public final String name;
108 /** A background color, just in case. */
109 public final int background;
111 /** Background image specifiers for `RotatingBackgrounds`. */
112 public final List<String> rotatingBackgrounds;
114 /** The error background image for `RotatingBackgrounds`. */
115 public final String errorBackground;
117 /** The paths (relative to the appdir) of images for the window icon. */
118 public final List<String> iconImages;
120 /** The path (relative to the appdir) to a single background image to appear first. */
121 public final String instantBackgroundImage;
123 /** The path (relative to the appdir) to a single background image. */
124 public final String backgroundImage;
126 /** The path (relative to the appdir) to the progress bar image. */
127 public final String progressImage;
129 /** The dimensions of the progress bar. */
130 public final Rectangle progress;
132 /** The color of the progress text. */
133 public final int progressText;
135 /** The color of the progress bar. */
136 public final int progressBar;
138 /** The dimensions of the status display. */
139 public final Rectangle status;
141 /** The color of the status text. */
142 public final int statusText;
144 /** The color of the text shadow. */
145 public final int textShadow;
147 /** Where to point the user for help with install errors. */
148 public final String installError;
150 /** The dimensions of the patch notes button. */
151 public final Rectangle patchNotes;
153 /** The patch notes URL. */
154 public final String patchNotesUrl;
156 /** Whether window decorations are hidden for the UI. */
157 public final boolean hideDecorations;
159 /** Whether progress text should be hidden or not. */
160 public final boolean hideProgressText;
162 /** Whether the splash screen should update non-asynchronously before being shown. */
163 public final boolean progressSync;
165 /** Whether the splash screen should update non-asynchronously after being shown. */
166 public final boolean progressSyncAfterShown;
168 /** Whether the splash screen should retain focus. */
169 public final boolean keepOnTop;
171 /** Whether to display the appbase. */
172 public final boolean displayAppbase;
174 /** Whether to display the version. */
175 public final boolean displayVersion;
177 /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
178 * flashing up on the screen and immediately disappearing, which can be confusing to the
180 public final int minShowSeconds;
182 /** The global percentages for each step. A step may have more than one, and
183 * the lowest reasonable one is used if a step is revisited. */
184 public final Map<Step, List<Integer>> stepPercentages;
186 /** Generates a string representation of this instance. */
188 public String toString ()
190 return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage + ", instant_bg=" + instantBackgroundImage +
191 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
192 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
193 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
194 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
195 ", hideProgressText=" + hideProgressText + ", keepOnTop=" + keepOnTop + ", progressSync=" + progressSync +
196 ", progressSyncAfterShown=" + progressSyncAfterShown + ", minShow=" + minShowSeconds +
197 ", displayAppbase=" + displayAppbase + ", displayVersion=" + displayVersion + "]";
200 public UpdateInterface (Config config)
202 this.name = config.getString("ui.name");
203 this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
204 this.progressText = config.getColor("ui.progress_text", Color.BLACK);
205 this.hideProgressText = config.getBoolean("ui.hide_progress_text");
206 this.progressSync = config.getBoolean("ui.progress_sync_before_shown");
207 this.progressSyncAfterShown = config.getBoolean("ui.progress_sync_after_shown");
208 this.keepOnTop = config.getBoolean("ui.keep_on_top");
209 this.displayAppbase = config.getBoolean("ui.display_appbase");
210 this.displayVersion = config.getBoolean("ui.display_version");
211 this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
212 this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
213 this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
214 this.statusText = config.getColor("ui.status_text", Color.BLACK);
215 this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
216 this.hideDecorations = config.getBoolean("ui.hide_decorations");
217 this.backgroundImage = config.getString("ui.background_image");
218 this.instantBackgroundImage = config.getString("ui.instant_background_image");
219 // default to black or white bg color, depending on the brightness of the progressText
220 int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
221 Color.BLACK : Color.WHITE;
222 this.background = config.getColor("ui.background", defaultBackground);
223 this.progressImage = config.getString("ui.progress_image");
224 this.rotatingBackgrounds = stringsToList(
225 config.getMultiValue("ui.rotating_background"));
226 this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
227 this.errorBackground = config.getString("ui.error_background");
229 // On an installation error, where do we point the user.
230 String installError = config.getUrl("ui.install_error", null);
231 this.installError = (installError == null) ?
232 "m.default_install_error" : MessageUtil.taint(installError);
234 // the patch notes bits
235 this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
236 this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
238 // step progress percentage (defaults and then customized values)
239 EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
240 for (Step step : Step.values()) {
241 stepPercentages.put(step, step.defaultPercents);
243 for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
244 String spec = config.getString("ui.percents." + step.name());
247 stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
248 } catch (Exception e) {
249 log.warning("Failed to parse percentages for " + step + ": " + spec);
253 this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
258 * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
259 * take network actions.
261 public static interface StatusDisplay
263 /** Requests that the specified status message be displayed. */
264 public void updateStatus (String message);
268 * Contains metadata for an auxiliary resource group.
270 public static class AuxGroup {
271 public final String name;
272 public final List<Resource> codes;
273 public final List<Resource> rsrcs;
275 public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
277 this.codes = Collections.unmodifiableList(codes);
278 this.rsrcs = Collections.unmodifiableList(rsrcs);
282 /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
283 * the application instance. Yes this is a public mutable field, no I'm not going to create a
284 * getter and setter just to pretend like that's not the case. */
285 public Proxy proxy = Proxy.NO_PROXY;
288 * Creates an application instance which records the location of the <code>getdown.txt</code>
289 * configuration file from the supplied application directory.
292 public Application (EnvConfig envc) {
294 _config = getLocalPath(envc.appDir, CONFIG_FILE);
295 _backupConfig = getLocalPath(envc.appDir, BACKUP_CONFIG_DIR+File.separator+CONFIG_FILE);
299 * Returns the configured application directory.
301 public File getAppDir () {
306 * Returns whether the application should cache code resources prior to launching the
309 public boolean useCodeCache ()
311 return _useCodeCache;
315 * Returns the number of days a cached code resource is allowed to stay unused before it
316 * becomes eligible for deletion.
318 public int getCodeCacheRetentionDays ()
320 return _codeCacheRetentionDays;
324 * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
325 * app files from its hosting server.
327 public int maxConcurrentDownloads () {
328 return _maxConcDownloads;
332 * Returns a resource that refers to the application configuration file itself.
334 public Resource getConfigResource ()
337 return createResource(CONFIG_FILE, Resource.NORMAL);
338 } catch (Exception e) {
339 throw new RuntimeException("Invalid appbase '" + _vappbase + "'.", e);
344 * Returns a list of the code {@link Resource} objects used by this application.
346 public List<Resource> getCodeResources ()
352 * Returns a list of the non-code {@link Resource} objects used by this application.
354 public List<Resource> getResources ()
360 * Returns the digest of the given {@code resource}.
362 public String getDigest (Resource resource)
364 return _digest.getDigest(resource);
368 * Returns a list of all the active {@link Resource} objects used by this application (code and
371 public List<Resource> getAllActiveResources ()
373 List<Resource> allResources = new ArrayList<>();
374 allResources.addAll(getActiveCodeResources());
375 allResources.addAll(getActiveResources());
380 * Returns the auxiliary resource group with the specified name, or null.
382 public AuxGroup getAuxGroup (String name)
384 return _auxgroups.get(name);
388 * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
389 * resource group is a collection of resource files that are not downloaded unless a group
390 * token file is present in the application directory.
392 public Iterable<AuxGroup> getAuxGroups ()
394 return _auxgroups.values();
398 * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
399 * groups should be ignored, activated groups should be downloaded and patched along with the
402 public boolean isAuxGroupActive (String auxgroup)
404 Boolean active = _auxactive.get(auxgroup);
405 if (active == null) {
406 // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
408 active = getLocalPath(auxgroup + ".dat").exists();
409 _auxactive.put(auxgroup, active);
415 * Returns all main code resources and all code resources from active auxiliary resource groups.
417 public List<Resource> getActiveCodeResources ()
419 ArrayList<Resource> codes = new ArrayList<>();
420 codes.addAll(getCodeResources());
421 for (AuxGroup aux : getAuxGroups()) {
422 if (isAuxGroupActive(aux.name)) {
423 codes.addAll(aux.codes);
430 * Returns all resources indicated to contain native library files (.dll, .so, etc.).
432 public List<Resource> getNativeResources ()
434 List<Resource> natives = new ArrayList<>();
435 for (Resource resource: _resources) {
436 if (resource.isNative()) {
437 natives.add(resource);
444 * Returns all non-code resources and all resources from active auxiliary resource groups.
446 public List<Resource> getActiveResources ()
448 ArrayList<Resource> rsrcs = new ArrayList<>();
449 rsrcs.addAll(getResources());
450 for (AuxGroup aux : getAuxGroups()) {
451 if (isAuxGroupActive(aux.name)) {
452 rsrcs.addAll(aux.rsrcs);
459 * Returns a resource that can be used to download a patch file that will bring this
460 * application from its current version to the target version.
462 * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
463 * for the main application patch resource.
465 public Resource getPatchResource (String auxgroup)
467 if (_targetVersion <= _version) {
468 log.warning("Requested patch resource for up-to-date or non-versioned application",
469 "cvers", _version, "tvers", _targetVersion);
473 String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
474 String pfile = "patch" + infix + _version + ".dat";
476 URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
477 return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
478 } catch (Exception e) {
479 log.warning("Failed to create patch resource path",
480 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
486 * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
487 * place of the installed VM (in the case where the VM that launched Getdown does not meet the
488 * application's version requirements) or null if no VM is available for this platform.
490 public Resource getJavaVMResource ()
492 if (StringUtil.isBlank(_javaLocation)) {
496 String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
497 String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
498 log.info("vmfile is '"+vmfile+"'");
499 System.out.println("vmfile is '"+vmfile+"'");
501 URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
502 log.info("Attempting to fetch jvm at "+remote.toString());
503 System.out.println("Attempting to fetch jvm at "+remote.toString());
504 return new Resource(vmfile, remote, getLocalPath(vmfile),
505 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
506 } catch (Exception e) {
507 log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
508 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
509 System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
510 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
516 * Returns a resource that can be used to download an archive containing all files belonging to
519 public Resource getFullResource ()
521 String file = "full";
523 URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
524 return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
525 } catch (Exception e) {
526 log.warning("Failed to create full resource path",
527 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
533 * Returns the URL to use to report an initial download event. Returns null if no tracking
534 * start URL was configured for this application.
536 * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
538 public URL getTrackingURL (String event)
541 String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
542 String ga = getGATrackingCode();
543 return _trackingURL == null ? null :
544 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
545 } catch (MalformedURLException mue) {
546 log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
552 * Returns the URL to request to report that we have reached the specified percentage of our
553 * initial download. Returns null if no tracking request was configured for the specified
556 public URL getTrackingProgressURL (int percent)
558 if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
561 return getTrackingURL("pct" + percent);
565 * Returns the name of our tracking cookie or null if it was not set.
567 public String getTrackingCookieName ()
569 return _trackingCookieName;
573 * Returns the name of our tracking cookie system property or null if it was not set.
575 public String getTrackingCookieProperty ()
577 return _trackingCookieProperty;
581 * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
582 * for operation. The application base URL will be parsed first so that if there are errors
583 * discovered later, the caller can use the application base to download a new {@code
584 * getdown.txt} file and try again.
586 * @return a {@code Config} instance that contains information from the config file.
588 * @exception IOException thrown if there is an error reading the file or an error encountered
589 * during its parsing.
591 public Config init (boolean checkPlatform)
594 if (_initialised && _initialisedConfig != null)
596 return _initialisedConfig;
600 Application.i4jVersion = com.install4j.api.launcher.Variables.getCompilerVariable("sys.install4jVersion");
601 } catch (IOException e)
603 System.err.println("install4j version not available");
604 } catch (NoClassDefFoundError e)
606 log.warning("Starting without install4j classes");
607 } catch (Throwable t)
609 System.err.println("install4j not available");
613 Config config = null;
614 File cfgfile = _config;
615 Config.ParseOpts opts = Config.createOpts(checkPlatform);
617 // if we have a configuration file, read the data from it
618 if (cfgfile.exists()) {
619 config = Config.parseConfig(_config, opts);
621 // otherwise, try reading data from our backup config file; thanks to funny windows
622 // bullshit, we have to do this backup file fiddling in case we got screwed while
623 // updating getdown.txt during normal operation
624 else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
625 config = Config.parseConfig(cfgfile, opts);
627 // otherwise, issue a warning that we found no getdown file
629 log.info("Found no getdown.txt file", "appdir", getAppDir());
631 } catch (Exception e) {
632 log.warning("Failure reading config file", "file", _config, e);
634 if (config == null || config.getString("appbase") == null || config.getString("appbase").isEmpty()) {
636 Config backupConfig = Config.parseConfig(_backupConfig, opts);
637 config = backupConfig;
638 log.warning("Using backup config file", "appdir", getAppDir(), "backupConfig", _backupConfig.getAbsoluteFile());
639 } catch (Exception e) {
640 log.warning("Failure reading backup config file", "file", _backupConfig, e);
644 // see if there's an override config from locator file
645 Config locatorConfig = createLocatorConfig(opts);
647 // merge the locator file config into config (or replace config with)
648 if (locatorConfig != null) {
649 if (config == null || locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_replace")) {
650 config = locatorConfig;
652 config.mergeConfig(locatorConfig, locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_merge"));
656 // if we failed to read our config file, check for an appbase specified via a system
657 // property; we can use that to bootstrap ourselves back into operation
658 if (config == null) {
659 String appbase = _envc.appBase;
660 log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
661 Map<String, Object> cdata = new HashMap<>();
662 cdata.put("appbase", appbase);
663 config = new Config(cdata);
666 // first determine our application base, this way if anything goes wrong later in the
667 // process, our caller can use the appbase to download a new configuration file
668 _appbase = config.getString("appbase");
670 // see if locatorConfig override
671 if (locatorConfig != null && !StringUtil.isBlank(locatorConfig.getString("appbase"))) {
672 _appbase = locatorConfig.getString("appbase");
675 if (_appbase == null) {
676 throw new RuntimeException("m.missing_appbase");
679 // check if we're overriding the domain in the appbase
680 _appbase = SysProps.overrideAppbase(_appbase);
682 // make sure there's a trailing slash
683 if (!_appbase.endsWith("/")) {
684 _appbase = _appbase + "/";
687 // extract our version information
688 _version = config.getLong("version", -1L);
690 // if we are a versioned deployment, create a versioned appbase
692 _vappbase = createVAppBase(_version);
693 } catch (MalformedURLException mue) {
694 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
695 throw (IOException) new IOException(err).initCause(mue);
698 // check for a latest config URL
699 String latest = config.getString("latest");
700 if (latest != null) {
701 if (latest.startsWith(_appbase)) {
702 latest = _appbase + latest.substring(_appbase.length());
704 latest = SysProps.replaceDomain(latest);
707 _latest = HostWhitelist.verify(new URL(latest));
708 } catch (MalformedURLException mue) {
709 log.warning("Invalid URL for latest attribute.", mue);
713 String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
715 // determine our application class name (use app-specific class _if_ one is provided)
716 _class = config.getString("class");
717 if (appPrefix.length() > 0) {
718 _class = config.getString(appPrefix + "class", _class);
720 if (_class == null) {
721 throw new IOException("m.missing_class");
724 // determine whether we want strict comments
725 _strictComments = config.getBoolean("strict_comments");
727 // check to see if we're using a custom java.version property and regex
728 _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
729 _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
731 // check to see if we require a particular JVM version and have a supplied JVM
732 _javaMinVersion = config.getLong("java_version", _javaMinVersion);
733 // we support java_min_version as an alias of java_version; it better expresses the check
734 // that's going on and better mirrors java_max_version
735 _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
736 // check to see if we require a particular max JVM version and have a supplied JVM
737 _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
738 // check to see if we require a particular JVM version and have a supplied JVM
739 _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
741 // this is a little weird, but when we're run from the digester, we see a String[] which
742 // contains java locations for all platforms which we can't grok, but the digester doesn't
743 // need to know about that; when we're run in a real application there will be only one!
744 Object javaloc = config.getRaw("java_location");
745 if (javaloc instanceof String) {
746 _javaLocation = (String)javaloc;
749 // determine whether we have any tracking configuration
750 _trackingURL = config.getString("tracking_url");
752 // check for tracking progress percent configuration
753 String trackPcts = config.getString("tracking_percents");
754 if (!StringUtil.isBlank(trackPcts)) {
755 _trackingPcts = new HashSet<>();
756 for (int pct : StringUtil.parseIntArray(trackPcts)) {
757 _trackingPcts.add(pct);
759 } else if (!StringUtil.isBlank(_trackingURL)) {
760 _trackingPcts = new HashSet<>();
761 _trackingPcts.add(50);
764 // Check for tracking cookie configuration
765 _trackingCookieName = config.getString("tracking_cookie_name");
766 _trackingCookieProperty = config.getString("tracking_cookie_property");
768 // Some app may need an extra suffix added to the tracking URL
769 _trackingURLSuffix = config.getString("tracking_url_suffix");
771 // Some app may need to generate google analytics code
772 _trackingGAHash = config.getString("tracking_ga_hash");
774 // clear our arrays as we may be reinitializing
782 // parse our code resources
783 if (config.getMultiValue("code") == null &&
784 config.getMultiValue("ucode") == null) {
785 throw new IOException("m.missing_code");
787 parseResources(config, "code", Resource.NORMAL, _codes);
788 parseResources(config, "ucode", Resource.UNPACK, _codes);
790 // parse our non-code resources
791 parseResources(config, "resource", Resource.NORMAL, _resources);
792 parseResources(config, "uresource", Resource.UNPACK, _resources);
793 parseResources(config, "xresource", Resource.EXEC, _resources);
794 parseResources(config, "presource", Resource.PRELOAD, _resources);
795 parseResources(config, "nresource", Resource.NATIVE, _resources);
797 // parse our auxiliary resource groups
798 for (String auxgroup : config.getList("auxgroups")) {
799 ArrayList<Resource> codes = new ArrayList<>();
800 parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
801 parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
802 ArrayList<Resource> rsrcs = new ArrayList<>();
803 parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
804 parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
805 parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
806 parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
807 parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
808 _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
811 // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
812 String[] jvmargs = config.getMultiValue("jvmarg");
813 addAll(jvmargs, _jvmargs);
814 if (appPrefix.length() > 0) {
815 jvmargs = config.getMultiValue(appPrefix + "jvmarg");
816 addAll(jvmargs, _jvmargs);
819 // see if a percentage of physical memory, or max heap size options exist
820 jvmmempc = config.getString("jvmmempc", null);
821 jvmmemmax = config.getString("jvmmemmax", null);
822 // app_id prefixed setting overrides
823 if (appPrefix.length() > 0) {
824 jvmmempc = config.getString(appPrefix + "jvmmempc", jvmmempc);
825 jvmmemmax = config.getString(appPrefix + "jvmmemmax", jvmmemmax);
828 // get the set of optimum JVM arguments
829 _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
831 // transfer our application arguments
832 String[] appargs = config.getMultiValue(appPrefix + "apparg");
833 addAll(appargs, _appargs);
835 // add the launch specific application arguments
836 _appargs.addAll(_envc.appArgs);
838 // look for custom arguments
839 fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
841 // determine whether we want to allow offline operation (defaults to false)
842 _allowOffline = config.getBoolean("allow_offline");
844 // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
845 // obtain a thread dump of the running JVM
846 _windebug = getLocalPath("debug.txt").exists();
848 // whether to cache code resources and launch from cache
849 _useCodeCache = config.getBoolean("use_code_cache");
850 _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
852 // maximum simultaneous downloads
853 _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
854 SysProps.threadPoolSize()));
856 // extract some info used to configure our child process on macOS
857 _dockName = config.getString("ui.name");
858 _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
861 _initialisedConfig = config;
866 * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
868 protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
870 File pairFile = getLocalPath(pairLocation);
871 if (pairFile.exists()) {
873 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
874 for (String[] pair : args) {
875 if (pair[1].length() == 0) {
876 collector.add(pair[0]);
878 collector.add(pair[0] + "=" + pair[1]);
881 } catch (Throwable t) {
882 log.warning("Failed to parse '" + pairFile + "': " + t);
888 * Returns a URL from which the specified path can be fetched. Our application base URL is
889 * properly versioned and combined with the supplied path.
891 public URL getRemoteURL (String path)
892 throws MalformedURLException
894 return new URL(_vappbase, encodePath(path));
898 * Returns the local path to the specified resource.
900 public File getLocalPath (String path)
902 return getLocalPath(getAppDir(), path);
906 * Returns true if we either have no version requirement, are running in a JVM that meets our
907 * version requirements or have what appears to be a version of the JVM that meets our
910 public boolean haveValidJavaVersion ()
912 // if we're doing no version checking, then yay!
913 if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
916 // parse the version out of the java.version (or custom) system property
917 long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
919 log.info("Checking Java version", "current", version,
920 "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
922 // if we have an unpacked VM, check the 'release' file for its version
923 Resource vmjar = getJavaVMResource();
924 if (vmjar != null && vmjar.isMarkedValid()) {
925 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
926 File relfile = new File(vmdir, "release");
927 if (!relfile.exists()) {
928 log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
932 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
934 log.warning("Unable to read version from 'release' file. Assuming valid.");
939 log.info("Checking version of unpacked JVM [vers=" + version + "].");
942 if (_javaExactVersionRequired) {
943 if (version == _javaMinVersion) return true;
945 log.warning("An exact Java VM version is required.", "current", version,
946 "required", _javaMinVersion);
951 boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
952 boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
953 return minVersionOK && maxVersionOK;
955 } catch (RuntimeException re) {
956 // if we can't parse the java version we're in weird land and should probably just try
957 // our luck with what we've got rather than try to download a new jvm
958 log.warning("Unable to parse VM version, hoping for the best",
959 "error", re, "needed", _javaMinVersion);
965 * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
966 * whether the launch is successful and, if necessary, trying again without the optimum
969 public boolean hasOptimumJvmArgs ()
971 return _optimumJvmArgs != null;
975 * Returns true if the app should attempt to run even if we have no Internet connection.
977 public boolean allowOffline ()
979 return _allowOffline;
983 * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
984 * previous call to {@link #init}.
986 public void attemptRecovery (StatusDisplay status)
989 status.updateStatus("m.updating_metadata");
990 downloadConfigFile();
994 * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
995 * those for the target version of our application.
997 public void updateMetadata ()
1001 // update our versioned application base with the target version
1002 _vappbase = createVAppBase(_targetVersion);
1003 } catch (MalformedURLException mue) {
1004 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
1005 throw (IOException) new IOException(err).initCause(mue);
1009 // now re-download our control files; we download the digest first so that if it fails,
1010 // our config file will still reference the old version and re-running the updater will
1011 // start the whole process over again
1012 downloadDigestFiles();
1013 downloadConfigFile();
1015 } catch (IOException ex) {
1016 // if we are allowing offline execution, we want to allow the application to run in its
1017 // current form rather than aborting the entire process; to do this, we delete the
1018 // version.txt file and "trick" Getdown into thinking that it just needs to validate
1019 // the application as is; next time the app runs when connected to the internet, it
1020 // will have to rediscover that it needs updating and reattempt to update itself
1021 if (_allowOffline) {
1022 log.warning("Failed to update digest files. Attempting offline operaton.", ex);
1023 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
1024 log.warning("Deleting version.txt failed. This probably isn't going to work.");
1033 * Invokes the process associated with this application definition.
1035 * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
1038 public Process createProcess (boolean optimum)
1041 ArrayList<String> args = new ArrayList<>();
1043 // reconstruct the path to the JVM
1044 args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
1046 // check whether we're using -jar mode or -classpath mode
1047 boolean dashJarMode = MANIFEST_CLASS.equals(_class);
1049 // add the -classpath arguments if we're not in -jar mode
1050 ClassPath classPath = PathBuilder.buildClassPath(this);
1052 args.add("-classpath");
1053 args.add(classPath.asArgumentString());
1056 // we love our Mac users, so we do nice things to preserve our application identity
1057 if (LaunchUtil.isMacOS()) {
1058 args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1059 args.add("-Xdock:name=" + _dockName);
1062 // pass along our proxy settings
1063 String proxyHost = System.getProperty("http.proxyHost");
1064 String proxyPort = StringUtil.isBlank(System.getProperty("http.proxyPort")) ? "80" : System.getProperty("http.proxyPort");
1065 if (StringUtil.isBlank(proxyHost) && ! proxy.equals(Proxy.NO_PROXY)) {
1067 SocketAddress a = proxy.address();
1068 if (a != null && a instanceof InetSocketAddress) {
1069 InetSocketAddress ia = (InetSocketAddress)a;
1070 proxyHost = ia.getHostString();
1071 proxyPort = String.valueOf(ia.getPort());
1073 } catch (Exception e) {
1074 log.error("Problem obtaining proxy settings from Proxy object");
1075 e.printStackTrace();
1078 if (proxyHost != null) {
1079 log.info("Using proxy settings "+proxyHost+":"+proxyPort);
1080 args.add("-Dhttp.proxyHost=" + proxyHost);
1081 args.add("-Dhttp.proxyPort=" + proxyPort);
1082 args.add("-Dhttps.proxyHost=" + proxyHost);
1083 args.add("-Dhttps.proxyPort=" + proxyPort);
1085 log.info("Not setting proxy");
1088 // add the getdownappbase property. getdownappdir is added by getdown.txt
1089 args.add("-Dgetdownappbase=" + getAppbase().toString());
1091 // add the marker indicating the app is running in getdown
1092 args.add("-D" + Properties.GETDOWN + "=true");
1093 args.add("-Dsys.install4jVersion=" + Application.i4jVersion);
1094 args.add("-Dinstaller_template_version=" + System.getProperty("installer_template_version"));
1095 args.add("-Dlauncher_version=" + Build.version());
1097 // set HiDPI property if wanted
1098 String scalePropertyArg = HiDPISetting.getScalePropertyArg();
1099 if (scalePropertyArg != null)
1101 args.add(scalePropertyArg);
1104 // set the native library path if we have native resources
1105 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1106 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1107 if (javaLibPath != null) {
1108 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1111 // pass along any pass-through arguments
1112 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1113 String key = (String)entry.getKey();
1114 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1115 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1116 args.add("-D" + key + "=" + entry.getValue());
1120 // test for jalview/s URL. Insert startupNotification URI into start of _appargs
1121 if (! StringUtil.isBlank(_jalviewUri)) {
1122 _appargs.add(0, _jalviewUri);
1124 if (_appargs.size() > 0) {
1125 String uri = _appargs.get(0);
1127 log.info("TRYING TO PARSE URL '"+uri+"'");
1128 URI jalviewUri = new URI(uri);
1129 if (jalviewUri != null) {
1130 String scheme = jalviewUri.getScheme();
1131 if (scheme != null && (scheme.equals("jalview") || scheme.equals("jalviews"))) {
1132 boolean https = jalviewUri.getScheme().equals("jalviews");
1133 String host = jalviewUri.getHost();
1134 int port = jalviewUri.getPort();
1135 String file = jalviewUri.getPath();
1136 String ref = jalviewUri.getFragment();
1137 String query = jalviewUri.getQuery();
1140 _appargs.add("-open");
1141 if (host != null && host.length() > 0) {
1142 URL newUrl = new URL(
1143 (https?"https":"http")
1146 + (port > -1? String.valueOf(port) : "")
1147 + jalviewUri.getRawPath()
1148 + (query != null && query.length() > 0 ? "?" + jalviewUri.getRawQuery() : "")
1150 _appargs.add(newUrl.toString());
1155 if (ref != null && ref.length() > 0) {
1156 String[] refArgs = ref.split("&");
1157 for (String refArg : refArgs) {
1158 if (refArg.startsWith("jvmmempc=")) {
1159 jvmmempc = refArg.substring(9);
1162 if (refArg.startsWith("jvmmemmax=")) {
1163 jvmmemmax = refArg.substring(10);
1166 _appargs.add(URLDecoder.decode(refArg, "UTF-8"));
1172 } catch (URISyntaxException e) {
1173 log.error("Malformed jalview URI", uri);
1177 for (String argString: _appargs) {
1178 if (argString.startsWith("-jvmmempc=")) {
1179 jvmmempc = argString.substring(10);
1182 if (argString.startsWith("-jvmmemmax=")) {
1183 jvmmemmax = argString.substring(11);
1188 // use saved preferences if no cmdline args
1189 LaunchUtils.loadChannelProps(getAppDir());
1190 if (LaunchUtils.getBooleanUserPreference(MemorySetting.CUSTOMISED_SETTINGS)) {
1191 if (jvmmempc == null) {
1192 jvmmempc = LaunchUtils.getUserPreference(MemorySetting.MEMORY_JVMMEMPC);
1194 if (jvmmemmax == null) {
1195 jvmmemmax = LaunchUtils.getUserPreference(MemorySetting.MEMORY_JVMMEMMAX);
1199 // add the memory setting from jvmmempc and jvmmemmax
1200 long maxMemLong = -1;
1201 maxMemLong = MemorySetting.getMemorySetting(jvmmemmax, jvmmempc);
1204 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
1205 // remove other max heap size arg
1206 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
1207 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
1212 addAll(maxMemHeapArg, _jvmargs);
1215 // add the JVM arguments
1216 for (String string : _jvmargs) {
1217 args.add(processArg(string));
1220 // add the optimum arguments if requested and available
1221 if (optimum && _optimumJvmArgs != null) {
1222 for (String string : _optimumJvmArgs) {
1223 args.add(processArg(string));
1227 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1228 for (String string : _txtJvmArgs) {
1229 args.add(processArg(string));
1232 // if we're in -jar mode add those arguments, otherwise add the app class name
1235 args.add(classPath.asArgumentString());
1240 // almost finally check the startup file arguments
1241 for (File f : _startupFiles) {
1242 _appargs.add(f.getAbsolutePath());
1243 break; // Only add one file to open
1246 // check if one arg with recognised extension
1247 if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1248 String filename = _appargs.get(0);
1250 int j = filename.lastIndexOf('.');
1252 ext = filename.substring(j+1);
1254 if (ext != null && LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase(Locale.ROOT))) {
1255 // this file extension should have been dealt with in Getdown class
1257 _appargs.add(0, "-open");
1261 // finally add the application arguments
1262 for (String string : _appargs) {
1263 args.add(processArg(string));
1266 String[] envp = createEnvironment();
1267 String[] sargs = args.toArray(new String[args.size()]);
1268 log.info("Running " + StringUtil.join(sargs, "\n "));
1270 // don't set the working dir, leave it the same as the working dir of the invocation
1271 //return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1272 return Runtime.getRuntime().exec(sargs, envp);
1276 * If the application provided environment variables, combine those with the current
1277 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1278 * If the application didn't provide any environment variables, null is returned to just use
1279 * the existing environment.
1281 protected String[] createEnvironment ()
1283 List<String> envvar = new ArrayList<>();
1284 fillAssignmentListFromPairs("env.txt", envvar);
1285 if (envvar.isEmpty()) {
1286 log.info("Didn't find any custom environment variables, not setting any.");
1290 List<String> envAssignments = new ArrayList<>();
1291 for (String assignment : envvar) {
1292 envAssignments.add(processArg(assignment));
1294 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1295 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1297 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1298 log.info("Environment " + StringUtil.join(envp, "\n "));
1303 * Runs this application directly in the current VM.
1305 public void invokeDirect () throws IOException
1307 ClassPath classPath = PathBuilder.buildClassPath(this);
1308 URL[] jarUrls = classPath.asUrls();
1310 // create custom class loader
1311 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1312 @Override protected PermissionCollection getPermissions (CodeSource code) {
1313 Permissions perms = new Permissions();
1314 perms.add(new AllPermission());
1318 Thread.currentThread().setContextClassLoader(loader);
1320 log.info("Configured URL class loader:");
1321 for (URL url : jarUrls) log.info(" " + url);
1323 // configure any system properties that we can
1324 for (String jvmarg : _jvmargs) {
1325 if (jvmarg.startsWith("-D")) {
1326 jvmarg = processArg(jvmarg.substring(2));
1327 int eqidx = jvmarg.indexOf("=");
1329 log.warning("Bogus system property: '" + jvmarg + "'?");
1331 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1336 // pass along any pass-through arguments
1337 Map<String, String> passProps = new HashMap<>();
1338 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1339 String key = (String)entry.getKey();
1340 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1341 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1342 passProps.put(key, (String)entry.getValue());
1345 // we can't set these in the above loop lest we get a ConcurrentModificationException
1346 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1347 System.setProperty(entry.getKey(), entry.getValue());
1350 // prepare our app arguments
1351 String[] args = new String[_appargs.size()];
1352 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1355 log.info("Loading " + _class);
1356 Class<?> appclass = loader.loadClass(_class);
1357 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1358 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1359 main.invoke(null, new Object[] { args });
1360 } catch (Exception e) {
1361 log.warning("Failure invoking app main", e);
1365 /** Replaces the application directory and version in any argument. */
1366 protected String processArg (String arg)
1368 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1369 arg = arg.replace("%VERSION%", String.valueOf(_version));
1371 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1372 // from the environment
1373 if (arg.contains(ENV_VAR_PREFIX)) {
1374 StringBuffer sb = new StringBuffer();
1375 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1376 while (matcher.find()) {
1377 String varName = matcher.group(1), varValue = System.getenv(varName);
1378 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1379 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1381 matcher.appendTail(sb);
1382 arg = sb.toString();
1389 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1390 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1391 * whether or not the application needs to be updated or whether we can proceed to verification
1394 * @return true if the application needs to be updated, false if it is up to date and can be
1395 * verified and executed.
1397 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1400 public boolean verifyMetadata (StatusDisplay status)
1403 log.info("Verifying application: " + _vappbase);
1404 log.info("Version: " + _version);
1405 log.info("Class: " + _class);
1407 // this will read in the contents of the digest file and validate itself
1409 _digest = new Digest(getAppDir(), _strictComments);
1410 } catch (IOException ioe) {
1411 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1414 // if we have no version, then we are running in unversioned mode so we need to download
1415 // our digest.txt file on every invocation
1416 if (_version == -1) {
1417 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1418 // resources as one or more of them have also changed
1419 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1421 status.updateStatus("m.checking");
1422 downloadDigestFiles();
1423 _digest = new Digest(getAppDir(), _strictComments);
1424 if (!olddig.equals(_digest.getMetaDigest())) {
1425 log.info("Unversioned digest changed. Revalidating...");
1426 status.updateStatus("m.validating");
1427 clearValidationMarkers();
1429 } catch (IOException ioe) {
1430 log.warning("Failed to refresh non-versioned digest: " +
1431 ioe.getMessage() + ". Proceeding...");
1435 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1436 // redownload the digest file and give it another good college try; this time we allow
1437 // exceptions to propagate up to the caller as there is nothing else we can do
1438 if (_digest == null) {
1439 status.updateStatus("m.updating_metadata");
1440 downloadDigestFiles();
1441 _digest = new Digest(getAppDir(), _strictComments);
1444 // now verify the contents of our main config file
1445 Resource crsrc = getConfigResource();
1446 if (!_digest.validateResource(crsrc, null)) {
1447 status.updateStatus("m.updating_metadata");
1448 // attempt to redownload both of our metadata files; again we pass errors up to our
1449 // caller because there's nothing we can do to automatically recover
1450 downloadConfigFile();
1451 downloadDigestFiles();
1452 _digest = new Digest(getAppDir(), _strictComments);
1453 // revalidate everything if we end up downloading new metadata
1454 clearValidationMarkers();
1455 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1456 if (_digest.validateResource(crsrc, null)) {
1457 // unset _initialisedConfig so new file is initialised
1458 _initialisedConfig = null;
1461 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1462 "Blindly forging onward.");
1466 // start by assuming we are happy with our version
1467 _targetVersion = _version;
1469 // if we are a versioned application, read in the contents of the version.txt file
1470 // and/or check the latest config URL for a newer version
1471 if (_version != -1) {
1472 File vfile = getLocalPath(VERSION_FILE);
1473 long fileVersion = VersionUtil.readVersion(vfile);
1474 if (fileVersion != -1) {
1475 _targetVersion = fileVersion;
1478 if (_latest != null) {
1479 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1480 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1481 BufferedReader bin = new BufferedReader(reader)) {
1482 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1483 if (pair[0].equals("version")) {
1484 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1485 if (fileVersion != -1 && _targetVersion > fileVersion) {
1486 // replace the file with the newest version
1487 try (FileOutputStream fos = new FileOutputStream(vfile);
1488 PrintStream out = new PrintStream(fos)) {
1489 out.println(_targetVersion);
1495 } catch (Exception e) {
1496 log.warning("Unable to retrieve version from latest config file.", e);
1501 // finally let the caller know if we need an update
1502 return _version != _targetVersion;
1506 * Verifies the code and media resources associated with this application. A list of resources
1507 * that do not exist or fail the verification process will be returned. If all resources are
1508 * ready to go, null will be returned and the application is considered ready to run.
1510 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1511 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1512 * you have to take care to get back to your UI thread.
1513 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1514 * validated" resources filled in.
1515 * @param unpacked a set to populate with unpacked resources.
1516 * @param toInstall a list into which to add resources that need to be installed.
1517 * @param toDownload a list into which to add resources that need to be downloaded.
1519 public void verifyResources (
1520 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1521 Set<Resource> toInstall, Set<Resource> toDownload)
1522 throws InterruptedException
1524 // resources are verified on background threads supplied by the thread pool, and progress
1525 // is reported by posting runnable actions to the actions queue which is processed by the
1527 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1528 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1529 final int[] completed = new int[1];
1531 long start = System.currentTimeMillis();
1533 // obtain the sizes of the resources to validate
1534 List<Resource> rsrcs = getAllActiveResources();
1535 long[] sizes = new long[rsrcs.size()];
1537 for (int ii = 0; ii < sizes.length; ii++) {
1538 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1540 final ProgressObserver fobs = obs;
1541 // as long as we forward aggregated progress updates to the UI thread, having multiple
1542 // threads update a progress aggregator is "mostly" thread-safe
1543 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1544 public void progress (final int percent) {
1545 actions.add(new Runnable() {
1546 public void run () {
1547 fobs.progress(percent);
1553 final int[] fAlreadyValid = alreadyValid;
1554 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1555 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1556 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1558 for (int ii = 0; ii < sizes.length; ii++) {
1559 final Resource rsrc = rsrcs.get(ii);
1560 final int index = ii;
1561 exec.execute(new Runnable() {
1562 public void run () {
1563 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1564 unpackedAsync, toInstallAsync, toDownloadAsync);
1565 actions.add(new Runnable() {
1566 public void run () {
1574 while (completed[0] < rsrcs.size()) {
1575 // we should be getting progress completion updates WAY more often than one every
1576 // minute, so if things freeze up for 60 seconds, abandon ship
1577 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1583 toInstall.addAll(toInstallAsync);
1584 toDownload.addAll(toDownloadAsync);
1585 unpacked.addAll(unpackedAsync);
1587 long complete = System.currentTimeMillis();
1588 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1589 "duration", (complete-start) + "ms");
1592 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1593 Set<Resource> unpacked,
1594 Set<Resource> toInstall, Set<Resource> toDownload) {
1595 if (rsrc.isMarkedValid()) {
1596 if (alreadyValid != null) {
1604 if (_digest.validateResource(rsrc, obs)) {
1605 // if the resource has a _new file, add it to to-install list
1606 if (rsrc.getLocalNew().exists()) {
1607 toInstall.add(rsrc);
1616 } catch (Exception e) {
1617 log.info("Failure verifying resource. Requesting redownload...",
1618 "rsrc", rsrc, "error", e);
1623 toDownload.add(rsrc);
1627 * Unpacks the resources that require it (we know that they're valid).
1629 * @param unpacked a set of resources to skip because they're already unpacked.
1631 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1632 throws InterruptedException
1634 List<Resource> rsrcs = getActiveResources();
1636 // remove resources that we don't want to unpack
1637 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1638 Resource rsrc = it.next();
1639 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1644 // obtain the sizes of the resources to unpack
1645 long[] sizes = new long[rsrcs.size()];
1646 for (int ii = 0; ii < sizes.length; ii++) {
1647 sizes[ii] = rsrcs.get(ii).getLocal().length();
1650 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1651 for (int ii = 0; ii < sizes.length; ii++) {
1652 Resource rsrc = rsrcs.get(ii);
1653 ProgressObserver pobs = pagg.startElement(ii);
1656 } catch (IOException ioe) {
1657 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1664 * Clears all validation marker files.
1666 public void clearValidationMarkers ()
1668 clearValidationMarkers(getAllActiveResources().iterator());
1672 * Returns the version number for the application. Should only be called after successful
1673 * return of verifyMetadata.
1675 public long getVersion ()
1681 * Creates a versioned application base URL for the specified version.
1683 protected URL createVAppBase (long version)
1684 throws MalformedURLException
1686 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1687 return HostWhitelist.verify(new URL(url));
1691 * Clears all validation marker files for the resources in the supplied iterator.
1693 protected void clearValidationMarkers (Iterator<Resource> iter)
1695 while (iter.hasNext()) {
1696 iter.next().clearMarker();
1701 * Downloads a new copy of CONFIG_FILE.
1703 protected void downloadConfigFile ()
1706 downloadControlFile(CONFIG_FILE, 0);
1710 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1711 * we're not locking at all.
1713 public synchronized boolean lockForUpdates ()
1715 if (_lock != null && _lock.isValid()) {
1719 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1720 } catch (FileNotFoundException e) {
1721 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1725 _lock = _lockChannel.tryLock();
1726 } catch (IOException e) {
1727 log.warning("Unable to create lock", "message", e.getMessage(), e);
1729 } catch (OverlappingFileLockException e) {
1730 log.warning("The lock is held elsewhere in this JVM", e);
1733 log.info("Able to lock for updates: " + (_lock != null));
1734 return _lock != null;
1738 * Release gettingdown.lock
1740 public synchronized void releaseLock ()
1742 if (_lock != null) {
1743 log.info("Releasing lock");
1746 } catch (IOException e) {
1747 log.warning("Unable to release lock", "message", e.getMessage(), e);
1750 _lockChannel.close();
1751 } catch (IOException e) {
1752 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1754 _lockChannel = null;
1760 * Downloads the digest files and validates their signature.
1761 * @throws IOException
1763 protected void downloadDigestFiles ()
1766 for (int version = 1; version <= Digest.VERSION; version++) {
1767 downloadControlFile(Digest.digestFile(version), version);
1772 * Downloads a new copy of the specified control file, optionally validating its signature.
1773 * If the download is successful, moves it over the old file on the filesystem.
1775 * <p> TODO: Switch to PKCS #7 or CMS.
1777 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1778 * should indicate the version of the digest file being validated which indicates which
1779 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1781 protected void downloadControlFile (String path, int sigVersion)
1784 File target = downloadFile(path);
1786 if (sigVersion > 0) {
1787 if (_envc.certs.isEmpty()) {
1788 log.info("No signing certs, not verifying digest.txt", "path", path);
1791 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1792 byte[] signature = null;
1793 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1794 signature = StreamUtil.toByteArray(signatureStream);
1796 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1799 byte[] buffer = new byte[8192];
1800 int length, validated = 0;
1801 for (Certificate cert : _envc.certs) {
1802 try (FileInputStream dataInput = new FileInputStream(target)) {
1803 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1804 sig.initVerify(cert);
1805 while ((length = dataInput.read(buffer)) != -1) {
1806 sig.update(buffer, 0, length);
1809 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1810 log.info("Signature does not match", "cert", cert.getPublicKey());
1813 log.info("Signature matches", "cert", cert.getPublicKey());
1817 } catch (IOException ioe) {
1818 log.warning("Failure validating signature of " + target + ": " + ioe);
1820 } catch (GeneralSecurityException gse) {
1826 // if we couldn't find a key that validates our digest, we are the hosed!
1827 if (validated == 0) {
1828 // delete the temporary digest file as we know it is invalid
1829 FileUtil.deleteHarder(target);
1830 throw new IOException("m.corrupt_digest_signature_error");
1835 // now move the temporary file over the original
1836 File original = getLocalPath(path);
1837 if (!FileUtil.renameTo(target, original)) {
1838 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1843 * Download a path to a temporary file, returning a {@link File} instance with the path
1846 protected File downloadFile (String path)
1849 File target = getLocalPath(path + "_new");
1851 URL targetURL = null;
1853 targetURL = getRemoteURL(path);
1854 } catch (Exception e) {
1855 log.warning("Requested to download invalid control file",
1856 "appbase", _vappbase, "path", path, "error", e);
1857 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1860 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1862 // stream the URL into our temporary file
1863 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1864 // we have to tell Java not to use caches here, otherwise it will cache any request for
1865 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1866 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1867 // about it; turning off caches is not a performance concern, because when Getdown asks
1868 // to download a file, it expects it to come over the wire, not from a cache
1869 uconn.setUseCaches(false);
1870 uconn.setRequestProperty("Accept-Encoding", "gzip");
1871 try (InputStream fin = uconn.getInputStream()) {
1872 String encoding = uconn.getContentEncoding();
1873 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1874 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1875 try (FileOutputStream fout = new FileOutputStream(target)) {
1876 StreamUtil.copy(fin2, fout);
1884 /** Helper function for creating {@link Resource} instances. */
1885 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1886 throws MalformedURLException
1888 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1891 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1892 protected static void addAll (String[] values, List<String> target) {
1893 if (values != null) {
1894 for (String value : values) {
1901 * Make an immutable List from the specified int array.
1903 public static List<Integer> intsToList (int[] values)
1905 List<Integer> list = new ArrayList<>(values.length);
1906 for (int val : values) {
1909 return Collections.unmodifiableList(list);
1913 * Make an immutable List from the specified String array.
1915 public static List<String> stringsToList (String[] values)
1917 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1920 /** Used to parse resources with the specified name. */
1921 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1922 List<Resource> list)
1924 String[] rsrcs = config.getMultiValue(name);
1925 if (rsrcs == null) {
1928 for (String rsrc : rsrcs) {
1930 list.add(createResource(rsrc, attrs));
1931 } catch (Exception e) {
1932 log.warning("Invalid resource '" + rsrc + "'. " + e);
1937 /** Possibly generates and returns a google analytics tracking cookie. */
1938 protected String getGATrackingCode ()
1940 if (_trackingGAHash == null) {
1943 long time = System.currentTimeMillis() / 1000;
1944 if (_trackingStart == 0) {
1945 _trackingStart = time;
1947 if (_trackingId == 0) {
1948 int low = 100000000, high = 1000000000;
1949 _trackingId = low + _rando.nextInt(high-low);
1951 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1952 cookie.append(".").append(_trackingId);
1953 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1954 cookie.append(".").append(time).append(".1%3B%2B");
1955 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1956 cookie.append(_trackingStart).append(".1.1.");
1957 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1958 int low = 1000000000, high = 2000000000;
1959 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1960 return cookie.toString();
1964 * Encodes a path for use in a URL.
1966 protected static String encodePath (String path)
1969 // we want to keep slashes because we're encoding an entire path; also we need to turn
1970 // + into %20 because web servers don't like + in paths or file names, blah
1971 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1972 } catch (UnsupportedEncodingException ue) {
1973 log.warning("Failed to URL encode " + path + ": " + ue);
1978 protected File getLocalPath (File appdir, String path)
1980 return new File(appdir, path);
1983 public static void setStartupFilesFromParameterString(String p) {
1984 // multiple files *might* be passed in as space separated quoted filenames
1986 if (!StringUtil.isBlank(p)) {
1988 // split quoted params or treat as single string array
1989 if (p.startsWith(q) && p.endsWith(q)) {
1990 // this fails if, e.g.
1991 // p=q("stupidfilename\" " "otherfilename")
1992 // let's hope no-one ever ends a filename with '" '
1993 filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1995 // single unquoted filename
1996 filenames = new String[]{p};
1999 // check for locator file. Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
2000 String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
2002 !StringUtil.isBlank(locatorFilename)
2003 && locatorFilename.toLowerCase(Locale.ROOT).endsWith("."+Application.LOCATOR_FILE_EXTENSION)
2005 setLocatorFile(locatorFilename);
2006 // remove the locator filename from the filenames array
2007 String[] otherFilenames = new String[filenames.length - 1];
2008 System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
2009 filenames = otherFilenames;
2012 for (int i = 0; i < filenames.length; i++) {
2013 String filename = filenames[i];
2014 // skip any other locator files in a multiple file list
2015 if (filename.startsWith("jalview://") || filename.startsWith("jalviews://")) {
2016 setJalviewUri(filename);
2017 } else if (! filename.toLowerCase(Locale.ROOT).endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
2018 addStartupFile(filename);
2024 public static void setLocatorFile(String filename) {
2025 _locatorFile = new File(filename);
2028 public static void addStartupFile(String filename) {
2029 _startupFiles.add(new File(filename));
2032 public static void setJalviewUri(String uri) {
2036 private Config createLocatorConfig(Config.ParseOpts opts) {
2037 if (_locatorFile == null) {
2041 Config locatorConfig = null;
2044 Config tmpConfig = null;
2045 Map<String, Object> tmpData = new HashMap<>();
2046 if (_locatorFile.exists()) {
2047 tmpConfig = Config.parseConfig(_locatorFile, opts);
2048 // appbase is sanitised in HostWhitelist
2049 Map<String, Object> tmpConfigData = tmpConfig.getData();
2050 if (tmpConfig != null) {
2051 for (Map.Entry<String, Object> entry : tmpConfigData.entrySet()) {
2052 String key = entry.getKey();
2053 Object value = entry.getValue();
2054 String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
2055 if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
2056 tmpData.put(key, value);
2060 log.warning("Error occurred reading config file", "file", _locatorFile);
2063 log.warning("Given locator file does not exist", "file", _locatorFile);
2066 locatorConfig = new Config(tmpData);
2068 } catch (Exception e) {
2069 log.warning("Failure reading locator file", "file", _locatorFile, e);
2072 return locatorConfig;
2075 public String getAppbase() {
2079 protected final EnvConfig _envc;
2080 protected File _config;
2081 protected File _backupConfig;
2082 protected Digest _digest;
2084 protected long _version = -1;
2085 protected long _targetVersion = -1;
2086 protected String _appbase;
2087 protected URL _vappbase;
2088 protected URL _latest;
2089 protected String _class;
2090 protected String _dockName;
2091 protected String _dockIconPath;
2092 protected boolean _strictComments;
2093 protected boolean _windebug;
2094 protected boolean _allowOffline;
2095 protected int _maxConcDownloads;
2097 protected String _trackingURL;
2098 protected Set<Integer> _trackingPcts;
2099 protected String _trackingCookieName;
2100 protected String _trackingCookieProperty;
2101 protected String _trackingURLSuffix;
2102 protected String _trackingGAHash;
2103 protected long _trackingStart;
2104 protected int _trackingId;
2106 protected String _javaVersionProp = "java.version";
2107 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
2108 protected long _javaMinVersion, _javaMaxVersion;
2109 protected boolean _javaExactVersionRequired;
2110 protected String _javaLocation;
2112 protected List<Resource> _codes = new ArrayList<>();
2113 protected List<Resource> _resources = new ArrayList<>();
2115 protected boolean _useCodeCache;
2116 protected int _codeCacheRetentionDays;
2118 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
2119 protected Map<String,Boolean> _auxactive = new HashMap<>();
2121 protected List<String> _jvmargs = new ArrayList<>();
2122 protected List<String> _appargs = new ArrayList<>();
2124 protected String[] _optimumJvmArgs;
2126 protected List<String> _txtJvmArgs = new ArrayList<>();
2128 /** If a warning has been issued about not being able to set modtimes. */
2129 protected boolean _warnedAboutSetLastModified;
2131 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
2132 protected FileLock _lock;
2134 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
2135 protected FileChannel _lockChannel;
2137 protected Random _rando = new Random();
2139 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
2141 protected static final String ENV_VAR_PREFIX = "%ENV.";
2142 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
2144 protected static File _locatorFile;
2145 protected static List<File> _startupFiles = new ArrayList<>();
2146 protected static String _jalviewUri;
2147 public static final String LOCATOR_FILE_EXTENSION = "jvl";
2149 private boolean _initialised = false;
2150 private Config _initialisedConfig = null;
2152 public static String i4jVersion = null;
2153 private String jvmmempc = null;
2154 private String jvmmemmax = null;