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 marker indicating the app is running in getdown
1089 args.add("-D" + Properties.GETDOWN + "=true");
1090 args.add("-Dsys.install4jVersion=" + Application.i4jVersion);
1091 args.add("-Dinstaller_template_version=" + System.getProperty("installer_template_version"));
1092 args.add("-Dlauncher_version=" + Build.version());
1094 // set HiDPI property if wanted
1095 String scalePropertyArg = HiDPISetting.getScalePropertyArg();
1096 if (scalePropertyArg != null)
1098 args.add(scalePropertyArg);
1101 // set the native library path if we have native resources
1102 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1103 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1104 if (javaLibPath != null) {
1105 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1108 // pass along any pass-through arguments
1109 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1110 String key = (String)entry.getKey();
1111 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1112 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1113 args.add("-D" + key + "=" + entry.getValue());
1117 // test for jalview/s URL. Insert startupNotification URI into start of _appargs
1118 if (! StringUtil.isBlank(_jalviewUri)) {
1119 _appargs.add(0, _jalviewUri);
1121 if (_appargs.size() > 0) {
1122 String uri = _appargs.get(0);
1124 log.info("TRYING TO PARSE URL '"+uri+"'");
1125 URI jalviewUri = new URI(uri);
1126 if (jalviewUri != null) {
1127 String scheme = jalviewUri.getScheme();
1128 if (scheme != null && (scheme.equals("jalview") || scheme.equals("jalviews"))) {
1129 boolean https = jalviewUri.getScheme().equals("jalviews");
1130 String host = jalviewUri.getHost();
1131 int port = jalviewUri.getPort();
1132 String file = jalviewUri.getPath();
1133 String ref = jalviewUri.getFragment();
1134 String query = jalviewUri.getQuery();
1137 _appargs.add("-open");
1138 if (host != null && host.length() > 0) {
1139 URL newUrl = new URL(
1140 (https?"https":"http")
1143 + (port > -1? String.valueOf(port) : "")
1144 + jalviewUri.getRawPath()
1145 + (query != null && query.length() > 0 ? "?" + jalviewUri.getRawQuery() : "")
1147 _appargs.add(newUrl.toString());
1152 if (ref != null && ref.length() > 0) {
1153 String[] refArgs = ref.split("&");
1154 for (String refArg : refArgs) {
1155 if (refArg.startsWith("jvmmempc=")) {
1156 jvmmempc = refArg.substring(9);
1159 if (refArg.startsWith("jvmmemmax=")) {
1160 jvmmemmax = refArg.substring(10);
1163 _appargs.add(URLDecoder.decode(refArg, "UTF-8"));
1169 } catch (URISyntaxException e) {
1170 log.error("Malformed jalview URI", uri);
1174 for (String argString: _appargs) {
1175 if (argString.startsWith("-jvmmempc=")) {
1176 jvmmempc = argString.substring(10);
1179 if (argString.startsWith("-jvmmemmax=")) {
1180 jvmmemmax = argString.substring(11);
1185 // use saved preferences if no cmdline args
1186 LaunchUtils.loadChannelProps(getAppDir());
1187 if (LaunchUtils.getBooleanUserPreference(MemorySetting.CUSTOMISED_SETTINGS)) {
1188 if (jvmmempc == null) {
1189 jvmmempc = LaunchUtils.getUserPreference(MemorySetting.MEMORY_JVMMEMPC);
1191 if (jvmmemmax == null) {
1192 jvmmemmax = LaunchUtils.getUserPreference(MemorySetting.MEMORY_JVMMEMMAX);
1196 // add the memory setting from jvmmempc and jvmmemmax
1197 long maxMemLong = -1;
1198 maxMemLong = MemorySetting.getMemorySetting(jvmmemmax, jvmmempc);
1201 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
1202 // remove other max heap size arg
1203 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
1204 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
1209 addAll(maxMemHeapArg, _jvmargs);
1212 // add the JVM arguments
1213 for (String string : _jvmargs) {
1214 args.add(processArg(string));
1217 // add the optimum arguments if requested and available
1218 if (optimum && _optimumJvmArgs != null) {
1219 for (String string : _optimumJvmArgs) {
1220 args.add(processArg(string));
1224 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1225 for (String string : _txtJvmArgs) {
1226 args.add(processArg(string));
1229 // if we're in -jar mode add those arguments, otherwise add the app class name
1232 args.add(classPath.asArgumentString());
1237 // almost finally check the startup file arguments
1238 for (File f : _startupFiles) {
1239 _appargs.add(f.getAbsolutePath());
1240 break; // Only add one file to open
1243 // check if one arg with recognised extension
1244 if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1245 String filename = _appargs.get(0);
1247 int j = filename.lastIndexOf('.');
1249 ext = filename.substring(j+1);
1251 if (ext != null && LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase(Locale.ROOT))) {
1252 // this file extension should have been dealt with in Getdown class
1254 _appargs.add(0, "-open");
1258 // finally add the application arguments
1259 for (String string : _appargs) {
1260 args.add(processArg(string));
1263 String[] envp = createEnvironment();
1264 String[] sargs = args.toArray(new String[args.size()]);
1265 log.info("Running " + StringUtil.join(sargs, "\n "));
1267 // don't set the working dir, leave it the same as the working dir of the invocation
1268 //return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1269 return Runtime.getRuntime().exec(sargs, envp);
1273 * If the application provided environment variables, combine those with the current
1274 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1275 * If the application didn't provide any environment variables, null is returned to just use
1276 * the existing environment.
1278 protected String[] createEnvironment ()
1280 List<String> envvar = new ArrayList<>();
1281 fillAssignmentListFromPairs("env.txt", envvar);
1282 if (envvar.isEmpty()) {
1283 log.info("Didn't find any custom environment variables, not setting any.");
1287 List<String> envAssignments = new ArrayList<>();
1288 for (String assignment : envvar) {
1289 envAssignments.add(processArg(assignment));
1291 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1292 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1294 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1295 log.info("Environment " + StringUtil.join(envp, "\n "));
1300 * Runs this application directly in the current VM.
1302 public void invokeDirect () throws IOException
1304 ClassPath classPath = PathBuilder.buildClassPath(this);
1305 URL[] jarUrls = classPath.asUrls();
1307 // create custom class loader
1308 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1309 @Override protected PermissionCollection getPermissions (CodeSource code) {
1310 Permissions perms = new Permissions();
1311 perms.add(new AllPermission());
1315 Thread.currentThread().setContextClassLoader(loader);
1317 log.info("Configured URL class loader:");
1318 for (URL url : jarUrls) log.info(" " + url);
1320 // configure any system properties that we can
1321 for (String jvmarg : _jvmargs) {
1322 if (jvmarg.startsWith("-D")) {
1323 jvmarg = processArg(jvmarg.substring(2));
1324 int eqidx = jvmarg.indexOf("=");
1326 log.warning("Bogus system property: '" + jvmarg + "'?");
1328 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1333 // pass along any pass-through arguments
1334 Map<String, String> passProps = new HashMap<>();
1335 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1336 String key = (String)entry.getKey();
1337 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1338 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1339 passProps.put(key, (String)entry.getValue());
1342 // we can't set these in the above loop lest we get a ConcurrentModificationException
1343 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1344 System.setProperty(entry.getKey(), entry.getValue());
1347 // prepare our app arguments
1348 String[] args = new String[_appargs.size()];
1349 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1352 log.info("Loading " + _class);
1353 Class<?> appclass = loader.loadClass(_class);
1354 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1355 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1356 main.invoke(null, new Object[] { args });
1357 } catch (Exception e) {
1358 log.warning("Failure invoking app main", e);
1362 /** Replaces the application directory and version in any argument. */
1363 protected String processArg (String arg)
1365 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1366 arg = arg.replace("%VERSION%", String.valueOf(_version));
1368 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1369 // from the environment
1370 if (arg.contains(ENV_VAR_PREFIX)) {
1371 StringBuffer sb = new StringBuffer();
1372 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1373 while (matcher.find()) {
1374 String varName = matcher.group(1), varValue = System.getenv(varName);
1375 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1376 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1378 matcher.appendTail(sb);
1379 arg = sb.toString();
1386 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1387 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1388 * whether or not the application needs to be updated or whether we can proceed to verification
1391 * @return true if the application needs to be updated, false if it is up to date and can be
1392 * verified and executed.
1394 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1397 public boolean verifyMetadata (StatusDisplay status)
1400 log.info("Verifying application: " + _vappbase);
1401 log.info("Version: " + _version);
1402 log.info("Class: " + _class);
1404 // this will read in the contents of the digest file and validate itself
1406 _digest = new Digest(getAppDir(), _strictComments);
1407 } catch (IOException ioe) {
1408 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1411 // if we have no version, then we are running in unversioned mode so we need to download
1412 // our digest.txt file on every invocation
1413 if (_version == -1) {
1414 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1415 // resources as one or more of them have also changed
1416 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1418 status.updateStatus("m.checking");
1419 downloadDigestFiles();
1420 _digest = new Digest(getAppDir(), _strictComments);
1421 if (!olddig.equals(_digest.getMetaDigest())) {
1422 log.info("Unversioned digest changed. Revalidating...");
1423 status.updateStatus("m.validating");
1424 clearValidationMarkers();
1426 } catch (IOException ioe) {
1427 log.warning("Failed to refresh non-versioned digest: " +
1428 ioe.getMessage() + ". Proceeding...");
1432 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1433 // redownload the digest file and give it another good college try; this time we allow
1434 // exceptions to propagate up to the caller as there is nothing else we can do
1435 if (_digest == null) {
1436 status.updateStatus("m.updating_metadata");
1437 downloadDigestFiles();
1438 _digest = new Digest(getAppDir(), _strictComments);
1441 // now verify the contents of our main config file
1442 Resource crsrc = getConfigResource();
1443 if (!_digest.validateResource(crsrc, null)) {
1444 status.updateStatus("m.updating_metadata");
1445 // attempt to redownload both of our metadata files; again we pass errors up to our
1446 // caller because there's nothing we can do to automatically recover
1447 downloadConfigFile();
1448 downloadDigestFiles();
1449 _digest = new Digest(getAppDir(), _strictComments);
1450 // revalidate everything if we end up downloading new metadata
1451 clearValidationMarkers();
1452 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1453 if (_digest.validateResource(crsrc, null)) {
1454 // unset _initialisedConfig so new file is initialised
1455 _initialisedConfig = null;
1458 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1459 "Blindly forging onward.");
1463 // start by assuming we are happy with our version
1464 _targetVersion = _version;
1466 // if we are a versioned application, read in the contents of the version.txt file
1467 // and/or check the latest config URL for a newer version
1468 if (_version != -1) {
1469 File vfile = getLocalPath(VERSION_FILE);
1470 long fileVersion = VersionUtil.readVersion(vfile);
1471 if (fileVersion != -1) {
1472 _targetVersion = fileVersion;
1475 if (_latest != null) {
1476 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1477 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1478 BufferedReader bin = new BufferedReader(reader)) {
1479 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1480 if (pair[0].equals("version")) {
1481 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1482 if (fileVersion != -1 && _targetVersion > fileVersion) {
1483 // replace the file with the newest version
1484 try (FileOutputStream fos = new FileOutputStream(vfile);
1485 PrintStream out = new PrintStream(fos)) {
1486 out.println(_targetVersion);
1492 } catch (Exception e) {
1493 log.warning("Unable to retrieve version from latest config file.", e);
1498 // finally let the caller know if we need an update
1499 return _version != _targetVersion;
1503 * Verifies the code and media resources associated with this application. A list of resources
1504 * that do not exist or fail the verification process will be returned. If all resources are
1505 * ready to go, null will be returned and the application is considered ready to run.
1507 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1508 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1509 * you have to take care to get back to your UI thread.
1510 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1511 * validated" resources filled in.
1512 * @param unpacked a set to populate with unpacked resources.
1513 * @param toInstall a list into which to add resources that need to be installed.
1514 * @param toDownload a list into which to add resources that need to be downloaded.
1516 public void verifyResources (
1517 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1518 Set<Resource> toInstall, Set<Resource> toDownload)
1519 throws InterruptedException
1521 // resources are verified on background threads supplied by the thread pool, and progress
1522 // is reported by posting runnable actions to the actions queue which is processed by the
1524 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1525 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1526 final int[] completed = new int[1];
1528 long start = System.currentTimeMillis();
1530 // obtain the sizes of the resources to validate
1531 List<Resource> rsrcs = getAllActiveResources();
1532 long[] sizes = new long[rsrcs.size()];
1534 for (int ii = 0; ii < sizes.length; ii++) {
1535 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1537 final ProgressObserver fobs = obs;
1538 // as long as we forward aggregated progress updates to the UI thread, having multiple
1539 // threads update a progress aggregator is "mostly" thread-safe
1540 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1541 public void progress (final int percent) {
1542 actions.add(new Runnable() {
1543 public void run () {
1544 fobs.progress(percent);
1550 final int[] fAlreadyValid = alreadyValid;
1551 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1552 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1553 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1555 for (int ii = 0; ii < sizes.length; ii++) {
1556 final Resource rsrc = rsrcs.get(ii);
1557 final int index = ii;
1558 exec.execute(new Runnable() {
1559 public void run () {
1560 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1561 unpackedAsync, toInstallAsync, toDownloadAsync);
1562 actions.add(new Runnable() {
1563 public void run () {
1571 while (completed[0] < rsrcs.size()) {
1572 // we should be getting progress completion updates WAY more often than one every
1573 // minute, so if things freeze up for 60 seconds, abandon ship
1574 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1580 toInstall.addAll(toInstallAsync);
1581 toDownload.addAll(toDownloadAsync);
1582 unpacked.addAll(unpackedAsync);
1584 long complete = System.currentTimeMillis();
1585 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1586 "duration", (complete-start) + "ms");
1589 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1590 Set<Resource> unpacked,
1591 Set<Resource> toInstall, Set<Resource> toDownload) {
1592 if (rsrc.isMarkedValid()) {
1593 if (alreadyValid != null) {
1601 if (_digest.validateResource(rsrc, obs)) {
1602 // if the resource has a _new file, add it to to-install list
1603 if (rsrc.getLocalNew().exists()) {
1604 toInstall.add(rsrc);
1613 } catch (Exception e) {
1614 log.info("Failure verifying resource. Requesting redownload...",
1615 "rsrc", rsrc, "error", e);
1620 toDownload.add(rsrc);
1624 * Unpacks the resources that require it (we know that they're valid).
1626 * @param unpacked a set of resources to skip because they're already unpacked.
1628 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1629 throws InterruptedException
1631 List<Resource> rsrcs = getActiveResources();
1633 // remove resources that we don't want to unpack
1634 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1635 Resource rsrc = it.next();
1636 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1641 // obtain the sizes of the resources to unpack
1642 long[] sizes = new long[rsrcs.size()];
1643 for (int ii = 0; ii < sizes.length; ii++) {
1644 sizes[ii] = rsrcs.get(ii).getLocal().length();
1647 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1648 for (int ii = 0; ii < sizes.length; ii++) {
1649 Resource rsrc = rsrcs.get(ii);
1650 ProgressObserver pobs = pagg.startElement(ii);
1653 } catch (IOException ioe) {
1654 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1661 * Clears all validation marker files.
1663 public void clearValidationMarkers ()
1665 clearValidationMarkers(getAllActiveResources().iterator());
1669 * Returns the version number for the application. Should only be called after successful
1670 * return of verifyMetadata.
1672 public long getVersion ()
1678 * Creates a versioned application base URL for the specified version.
1680 protected URL createVAppBase (long version)
1681 throws MalformedURLException
1683 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1684 return HostWhitelist.verify(new URL(url));
1688 * Clears all validation marker files for the resources in the supplied iterator.
1690 protected void clearValidationMarkers (Iterator<Resource> iter)
1692 while (iter.hasNext()) {
1693 iter.next().clearMarker();
1698 * Downloads a new copy of CONFIG_FILE.
1700 protected void downloadConfigFile ()
1703 downloadControlFile(CONFIG_FILE, 0);
1707 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1708 * we're not locking at all.
1710 public synchronized boolean lockForUpdates ()
1712 if (_lock != null && _lock.isValid()) {
1716 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1717 } catch (FileNotFoundException e) {
1718 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1722 _lock = _lockChannel.tryLock();
1723 } catch (IOException e) {
1724 log.warning("Unable to create lock", "message", e.getMessage(), e);
1726 } catch (OverlappingFileLockException e) {
1727 log.warning("The lock is held elsewhere in this JVM", e);
1730 log.info("Able to lock for updates: " + (_lock != null));
1731 return _lock != null;
1735 * Release gettingdown.lock
1737 public synchronized void releaseLock ()
1739 if (_lock != null) {
1740 log.info("Releasing lock");
1743 } catch (IOException e) {
1744 log.warning("Unable to release lock", "message", e.getMessage(), e);
1747 _lockChannel.close();
1748 } catch (IOException e) {
1749 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1751 _lockChannel = null;
1757 * Downloads the digest files and validates their signature.
1758 * @throws IOException
1760 protected void downloadDigestFiles ()
1763 for (int version = 1; version <= Digest.VERSION; version++) {
1764 downloadControlFile(Digest.digestFile(version), version);
1769 * Downloads a new copy of the specified control file, optionally validating its signature.
1770 * If the download is successful, moves it over the old file on the filesystem.
1772 * <p> TODO: Switch to PKCS #7 or CMS.
1774 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1775 * should indicate the version of the digest file being validated which indicates which
1776 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1778 protected void downloadControlFile (String path, int sigVersion)
1781 File target = downloadFile(path);
1783 if (sigVersion > 0) {
1784 if (_envc.certs.isEmpty()) {
1785 log.info("No signing certs, not verifying digest.txt", "path", path);
1788 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1789 byte[] signature = null;
1790 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1791 signature = StreamUtil.toByteArray(signatureStream);
1793 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1796 byte[] buffer = new byte[8192];
1797 int length, validated = 0;
1798 for (Certificate cert : _envc.certs) {
1799 try (FileInputStream dataInput = new FileInputStream(target)) {
1800 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1801 sig.initVerify(cert);
1802 while ((length = dataInput.read(buffer)) != -1) {
1803 sig.update(buffer, 0, length);
1806 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1807 log.info("Signature does not match", "cert", cert.getPublicKey());
1810 log.info("Signature matches", "cert", cert.getPublicKey());
1814 } catch (IOException ioe) {
1815 log.warning("Failure validating signature of " + target + ": " + ioe);
1817 } catch (GeneralSecurityException gse) {
1823 // if we couldn't find a key that validates our digest, we are the hosed!
1824 if (validated == 0) {
1825 // delete the temporary digest file as we know it is invalid
1826 FileUtil.deleteHarder(target);
1827 throw new IOException("m.corrupt_digest_signature_error");
1832 // now move the temporary file over the original
1833 File original = getLocalPath(path);
1834 if (!FileUtil.renameTo(target, original)) {
1835 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1840 * Download a path to a temporary file, returning a {@link File} instance with the path
1843 protected File downloadFile (String path)
1846 File target = getLocalPath(path + "_new");
1848 URL targetURL = null;
1850 targetURL = getRemoteURL(path);
1851 } catch (Exception e) {
1852 log.warning("Requested to download invalid control file",
1853 "appbase", _vappbase, "path", path, "error", e);
1854 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1857 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1859 // stream the URL into our temporary file
1860 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1861 // we have to tell Java not to use caches here, otherwise it will cache any request for
1862 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1863 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1864 // about it; turning off caches is not a performance concern, because when Getdown asks
1865 // to download a file, it expects it to come over the wire, not from a cache
1866 uconn.setUseCaches(false);
1867 uconn.setRequestProperty("Accept-Encoding", "gzip");
1868 try (InputStream fin = uconn.getInputStream()) {
1869 String encoding = uconn.getContentEncoding();
1870 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1871 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1872 try (FileOutputStream fout = new FileOutputStream(target)) {
1873 StreamUtil.copy(fin2, fout);
1881 /** Helper function for creating {@link Resource} instances. */
1882 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1883 throws MalformedURLException
1885 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1888 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1889 protected static void addAll (String[] values, List<String> target) {
1890 if (values != null) {
1891 for (String value : values) {
1898 * Make an immutable List from the specified int array.
1900 public static List<Integer> intsToList (int[] values)
1902 List<Integer> list = new ArrayList<>(values.length);
1903 for (int val : values) {
1906 return Collections.unmodifiableList(list);
1910 * Make an immutable List from the specified String array.
1912 public static List<String> stringsToList (String[] values)
1914 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1917 /** Used to parse resources with the specified name. */
1918 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1919 List<Resource> list)
1921 String[] rsrcs = config.getMultiValue(name);
1922 if (rsrcs == null) {
1925 for (String rsrc : rsrcs) {
1927 list.add(createResource(rsrc, attrs));
1928 } catch (Exception e) {
1929 log.warning("Invalid resource '" + rsrc + "'. " + e);
1934 /** Possibly generates and returns a google analytics tracking cookie. */
1935 protected String getGATrackingCode ()
1937 if (_trackingGAHash == null) {
1940 long time = System.currentTimeMillis() / 1000;
1941 if (_trackingStart == 0) {
1942 _trackingStart = time;
1944 if (_trackingId == 0) {
1945 int low = 100000000, high = 1000000000;
1946 _trackingId = low + _rando.nextInt(high-low);
1948 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1949 cookie.append(".").append(_trackingId);
1950 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1951 cookie.append(".").append(time).append(".1%3B%2B");
1952 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1953 cookie.append(_trackingStart).append(".1.1.");
1954 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1955 int low = 1000000000, high = 2000000000;
1956 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1957 return cookie.toString();
1961 * Encodes a path for use in a URL.
1963 protected static String encodePath (String path)
1966 // we want to keep slashes because we're encoding an entire path; also we need to turn
1967 // + into %20 because web servers don't like + in paths or file names, blah
1968 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1969 } catch (UnsupportedEncodingException ue) {
1970 log.warning("Failed to URL encode " + path + ": " + ue);
1975 protected File getLocalPath (File appdir, String path)
1977 return new File(appdir, path);
1980 public static void setStartupFilesFromParameterString(String p) {
1981 // multiple files *might* be passed in as space separated quoted filenames
1983 if (!StringUtil.isBlank(p)) {
1985 // split quoted params or treat as single string array
1986 if (p.startsWith(q) && p.endsWith(q)) {
1987 // this fails if, e.g.
1988 // p=q("stupidfilename\" " "otherfilename")
1989 // let's hope no-one ever ends a filename with '" '
1990 filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1992 // single unquoted filename
1993 filenames = new String[]{p};
1996 // check for locator file. Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1997 String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
1999 !StringUtil.isBlank(locatorFilename)
2000 && locatorFilename.toLowerCase(Locale.ROOT).endsWith("."+Application.LOCATOR_FILE_EXTENSION)
2002 setLocatorFile(locatorFilename);
2003 // remove the locator filename from the filenames array
2004 String[] otherFilenames = new String[filenames.length - 1];
2005 System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
2006 filenames = otherFilenames;
2009 for (int i = 0; i < filenames.length; i++) {
2010 String filename = filenames[i];
2011 // skip any other locator files in a multiple file list
2012 if (filename.startsWith("jalview://") || filename.startsWith("jalviews://")) {
2013 setJalviewUri(filename);
2014 } else if (! filename.toLowerCase(Locale.ROOT).endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
2015 addStartupFile(filename);
2021 public static void setLocatorFile(String filename) {
2022 _locatorFile = new File(filename);
2025 public static void addStartupFile(String filename) {
2026 _startupFiles.add(new File(filename));
2029 public static void setJalviewUri(String uri) {
2033 private Config createLocatorConfig(Config.ParseOpts opts) {
2034 if (_locatorFile == null) {
2038 Config locatorConfig = null;
2041 Config tmpConfig = null;
2042 Map<String, Object> tmpData = new HashMap<>();
2043 if (_locatorFile.exists()) {
2044 tmpConfig = Config.parseConfig(_locatorFile, opts);
2045 // appbase is sanitised in HostWhitelist
2046 Map<String, Object> tmpConfigData = tmpConfig.getData();
2047 if (tmpConfig != null) {
2048 for (Map.Entry<String, Object> entry : tmpConfigData.entrySet()) {
2049 String key = entry.getKey();
2050 Object value = entry.getValue();
2051 String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
2052 if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
2053 tmpData.put(key, value);
2057 log.warning("Error occurred reading config file", "file", _locatorFile);
2060 log.warning("Given locator file does not exist", "file", _locatorFile);
2063 locatorConfig = new Config(tmpData);
2065 } catch (Exception e) {
2066 log.warning("Failure reading locator file", "file", _locatorFile, e);
2069 return locatorConfig;
2072 public String getAppbase() {
2076 protected final EnvConfig _envc;
2077 protected File _config;
2078 protected File _backupConfig;
2079 protected Digest _digest;
2081 protected long _version = -1;
2082 protected long _targetVersion = -1;
2083 protected String _appbase;
2084 protected URL _vappbase;
2085 protected URL _latest;
2086 protected String _class;
2087 protected String _dockName;
2088 protected String _dockIconPath;
2089 protected boolean _strictComments;
2090 protected boolean _windebug;
2091 protected boolean _allowOffline;
2092 protected int _maxConcDownloads;
2094 protected String _trackingURL;
2095 protected Set<Integer> _trackingPcts;
2096 protected String _trackingCookieName;
2097 protected String _trackingCookieProperty;
2098 protected String _trackingURLSuffix;
2099 protected String _trackingGAHash;
2100 protected long _trackingStart;
2101 protected int _trackingId;
2103 protected String _javaVersionProp = "java.version";
2104 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
2105 protected long _javaMinVersion, _javaMaxVersion;
2106 protected boolean _javaExactVersionRequired;
2107 protected String _javaLocation;
2109 protected List<Resource> _codes = new ArrayList<>();
2110 protected List<Resource> _resources = new ArrayList<>();
2112 protected boolean _useCodeCache;
2113 protected int _codeCacheRetentionDays;
2115 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
2116 protected Map<String,Boolean> _auxactive = new HashMap<>();
2118 protected List<String> _jvmargs = new ArrayList<>();
2119 protected List<String> _appargs = new ArrayList<>();
2121 protected String[] _optimumJvmArgs;
2123 protected List<String> _txtJvmArgs = new ArrayList<>();
2125 /** If a warning has been issued about not being able to set modtimes. */
2126 protected boolean _warnedAboutSetLastModified;
2128 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
2129 protected FileLock _lock;
2131 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
2132 protected FileChannel _lockChannel;
2134 protected Random _rando = new Random();
2136 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
2138 protected static final String ENV_VAR_PREFIX = "%ENV.";
2139 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
2141 protected static File _locatorFile;
2142 protected static List<File> _startupFiles = new ArrayList<>();
2143 protected static String _jalviewUri;
2144 public static final String LOCATOR_FILE_EXTENSION = "jvl";
2146 private boolean _initialised = false;
2147 private Config _initialisedConfig = null;
2149 public static String i4jVersion = null;
2150 private String jvmmempc = null;
2151 private String jvmmemmax = null;