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.bin.LaunchUtils;
35 import jalview.util.ChannelProperties;
37 import com.threerings.getdown.util.*;
38 // avoid ambiguity with java.util.Base64 which we can't use as it's 1.8+
39 import com.threerings.getdown.util.Base64;
41 import com.threerings.getdown.data.EnvConfig;
42 import com.threerings.getdown.data.EnvConfig.Note;
44 import static com.threerings.getdown.Log.log;
45 import static java.nio.charset.StandardCharsets.UTF_8;
48 * Parses and provide access to the information contained in the <code>getdown.txt</code>
51 public class Application
53 /** The name of our configuration file. */
54 public static final String CONFIG_FILE = "getdown.txt";
56 /** Dir where a backup config file might reside */
57 public static final String BACKUP_CONFIG_DIR = "install";
59 /** The name of our target version file. */
60 public static final String VERSION_FILE = "version.txt";
62 /** System properties that are prefixed with this string will be passed through to our
63 * application (minus this prefix). */
64 public static final String PROP_PASSTHROUGH_PREFIX = "app.";
66 /** Suffix used for control file signatures. */
67 public static final String SIGNATURE_SUFFIX = ".sig";
69 /** A special classname that means 'use -jar code.jar' instead of a classname. */
70 public static final String MANIFEST_CLASS = "manifest";
72 /** Used to communicate information about the UI displayed when updating the application. */
73 public static final class UpdateInterface
76 * The major steps involved in updating, along with some arbitrary percentages
77 * assigned to them, to mark global progress.
83 //VERIFY_METADATA(15, 65, 95),
84 VERIFY_METADATA(15, 45, 90),
87 //VERIFY_RESOURCES(70, 97),
88 VERIFY_RESOURCES(40, 90),
89 //REDOWNLOAD_RESOURCES(90),
90 REDOWNLOAD_RESOURCES(80),
96 /** What is the final percent value for this step? */
97 public final List<Integer> defaultPercents;
99 /** Enum constructor. */
100 Step (int... percents)
102 this.defaultPercents = intsToList(percents);
106 /** The human readable name of this application. */
107 public final String name;
109 /** A background color, just in case. */
110 public final int background;
112 /** Background image specifiers for `RotatingBackgrounds`. */
113 public final List<String> rotatingBackgrounds;
115 /** The error background image for `RotatingBackgrounds`. */
116 public final String errorBackground;
118 /** The paths (relative to the appdir) of images for the window icon. */
119 public final List<String> iconImages;
121 /** The path (relative to the appdir) to a single background image to appear first. */
122 public final String instantBackgroundImage;
124 /** The path (relative to the appdir) to a single background image. */
125 public final String backgroundImage;
127 /** The path (relative to the appdir) to the progress bar image. */
128 public final String progressImage;
130 /** The dimensions of the progress bar. */
131 public final Rectangle progress;
133 /** The color of the progress text. */
134 public final int progressText;
136 /** The color of the progress bar. */
137 public final int progressBar;
139 /** The dimensions of the status display. */
140 public final Rectangle status;
142 /** The color of the status text. */
143 public final int statusText;
145 /** The color of the text shadow. */
146 public final int textShadow;
148 /** Where to point the user for help with install errors. */
149 public final String installError;
151 /** The dimensions of the patch notes button. */
152 public final Rectangle patchNotes;
154 /** The patch notes URL. */
155 public final String patchNotesUrl;
157 /** Whether window decorations are hidden for the UI. */
158 public final boolean hideDecorations;
160 /** Whether progress text should be hidden or not. */
161 public final boolean hideProgressText;
163 /** Whether the splash screen should update non-asynchronously before being shown. */
164 public final boolean progressSync;
166 /** Whether the splash screen should update non-asynchronously after being shown. */
167 public final boolean progressSyncAfterShown;
169 /** Whether the splash screen should retain focus. */
170 public final boolean keepOnTop;
172 /** Whether to display the appbase. */
173 public final boolean displayAppbase;
175 /** Whether to display the version. */
176 public final boolean displayVersion;
178 /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
179 * flashing up on the screen and immediately disappearing, which can be confusing to the
181 public final int minShowSeconds;
183 /** The global percentages for each step. A step may have more than one, and
184 * the lowest reasonable one is used if a step is revisited. */
185 public final Map<Step, List<Integer>> stepPercentages;
187 /** Generates a string representation of this instance. */
189 public String toString ()
191 return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage + ", instant_bg=" + instantBackgroundImage +
192 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
193 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
194 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
195 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
196 ", hideProgressText=" + hideProgressText + ", keepOnTop=" + keepOnTop + ", progressSync=" + progressSync +
197 ", progressSyncAfterShown=" + progressSyncAfterShown + ", minShow=" + minShowSeconds +
198 ", displayAppbase=" + displayAppbase + ", displayVersion=" + displayVersion + "]";
201 public UpdateInterface (Config config)
203 this.name = config.getString("ui.name");
204 this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
205 this.progressText = config.getColor("ui.progress_text", Color.BLACK);
206 this.hideProgressText = config.getBoolean("ui.hide_progress_text");
207 this.progressSync = config.getBoolean("ui.progress_sync_before_shown");
208 this.progressSyncAfterShown = config.getBoolean("ui.progress_sync_after_shown");
209 this.keepOnTop = config.getBoolean("ui.keep_on_top");
210 this.displayAppbase = config.getBoolean("ui.display_appbase");
211 this.displayVersion = config.getBoolean("ui.display_version");
212 this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
213 this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
214 this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
215 this.statusText = config.getColor("ui.status_text", Color.BLACK);
216 this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
217 this.hideDecorations = config.getBoolean("ui.hide_decorations");
218 this.backgroundImage = config.getString("ui.background_image");
219 this.instantBackgroundImage = config.getString("ui.instant_background_image");
220 // default to black or white bg color, depending on the brightness of the progressText
221 int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
222 Color.BLACK : Color.WHITE;
223 this.background = config.getColor("ui.background", defaultBackground);
224 this.progressImage = config.getString("ui.progress_image");
225 this.rotatingBackgrounds = stringsToList(
226 config.getMultiValue("ui.rotating_background"));
227 this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
228 this.errorBackground = config.getString("ui.error_background");
230 // On an installation error, where do we point the user.
231 String installError = config.getUrl("ui.install_error", null);
232 this.installError = (installError == null) ?
233 "m.default_install_error" : MessageUtil.taint(installError);
235 // the patch notes bits
236 this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
237 this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
239 // step progress percentage (defaults and then customized values)
240 EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
241 for (Step step : Step.values()) {
242 stepPercentages.put(step, step.defaultPercents);
244 for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
245 String spec = config.getString("ui.percents." + step.name());
248 stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
249 } catch (Exception e) {
250 log.warning("Failed to parse percentages for " + step + ": " + spec);
254 this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
259 * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
260 * take network actions.
262 public static interface StatusDisplay
264 /** Requests that the specified status message be displayed. */
265 public void updateStatus (String message);
269 * Contains metadata for an auxiliary resource group.
271 public static class AuxGroup {
272 public final String name;
273 public final List<Resource> codes;
274 public final List<Resource> rsrcs;
276 public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
278 this.codes = Collections.unmodifiableList(codes);
279 this.rsrcs = Collections.unmodifiableList(rsrcs);
283 /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
284 * the application instance. Yes this is a public mutable field, no I'm not going to create a
285 * getter and setter just to pretend like that's not the case. */
286 public Proxy proxy = Proxy.NO_PROXY;
289 * Creates an application instance which records the location of the <code>getdown.txt</code>
290 * configuration file from the supplied application directory.
293 public Application (EnvConfig envc) {
295 _config = getLocalPath(envc.appDir, CONFIG_FILE);
296 _backupConfig = getLocalPath(envc.appDir, BACKUP_CONFIG_DIR+File.separator+CONFIG_FILE);
300 * Returns the configured application directory.
302 public File getAppDir () {
307 * Returns whether the application should cache code resources prior to launching the
310 public boolean useCodeCache ()
312 return _useCodeCache;
316 * Returns the number of days a cached code resource is allowed to stay unused before it
317 * becomes eligible for deletion.
319 public int getCodeCacheRetentionDays ()
321 return _codeCacheRetentionDays;
325 * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
326 * app files from its hosting server.
328 public int maxConcurrentDownloads () {
329 return _maxConcDownloads;
333 * Returns a resource that refers to the application configuration file itself.
335 public Resource getConfigResource ()
338 return createResource(CONFIG_FILE, Resource.NORMAL);
339 } catch (Exception e) {
340 throw new RuntimeException("Invalid appbase '" + _vappbase + "'.", e);
345 * Returns a list of the code {@link Resource} objects used by this application.
347 public List<Resource> getCodeResources ()
353 * Returns a list of the non-code {@link Resource} objects used by this application.
355 public List<Resource> getResources ()
361 * Returns the digest of the given {@code resource}.
363 public String getDigest (Resource resource)
365 return _digest.getDigest(resource);
369 * Returns a list of all the active {@link Resource} objects used by this application (code and
372 public List<Resource> getAllActiveResources ()
374 List<Resource> allResources = new ArrayList<>();
375 allResources.addAll(getActiveCodeResources());
376 allResources.addAll(getActiveResources());
381 * Returns the auxiliary resource group with the specified name, or null.
383 public AuxGroup getAuxGroup (String name)
385 return _auxgroups.get(name);
389 * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
390 * resource group is a collection of resource files that are not downloaded unless a group
391 * token file is present in the application directory.
393 public Iterable<AuxGroup> getAuxGroups ()
395 return _auxgroups.values();
399 * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
400 * groups should be ignored, activated groups should be downloaded and patched along with the
403 public boolean isAuxGroupActive (String auxgroup)
405 Boolean active = _auxactive.get(auxgroup);
406 if (active == null) {
407 // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
409 active = getLocalPath(auxgroup + ".dat").exists();
410 _auxactive.put(auxgroup, active);
416 * Returns all main code resources and all code resources from active auxiliary resource groups.
418 public List<Resource> getActiveCodeResources ()
420 ArrayList<Resource> codes = new ArrayList<>();
421 codes.addAll(getCodeResources());
422 for (AuxGroup aux : getAuxGroups()) {
423 if (isAuxGroupActive(aux.name)) {
424 codes.addAll(aux.codes);
431 * Returns all resources indicated to contain native library files (.dll, .so, etc.).
433 public List<Resource> getNativeResources ()
435 List<Resource> natives = new ArrayList<>();
436 for (Resource resource: _resources) {
437 if (resource.isNative()) {
438 natives.add(resource);
445 * Returns all non-code resources and all resources from active auxiliary resource groups.
447 public List<Resource> getActiveResources ()
449 ArrayList<Resource> rsrcs = new ArrayList<>();
450 rsrcs.addAll(getResources());
451 for (AuxGroup aux : getAuxGroups()) {
452 if (isAuxGroupActive(aux.name)) {
453 rsrcs.addAll(aux.rsrcs);
460 * Returns a resource that can be used to download a patch file that will bring this
461 * application from its current version to the target version.
463 * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
464 * for the main application patch resource.
466 public Resource getPatchResource (String auxgroup)
468 if (_targetVersion <= _version) {
469 log.warning("Requested patch resource for up-to-date or non-versioned application",
470 "cvers", _version, "tvers", _targetVersion);
474 String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
475 String pfile = "patch" + infix + _version + ".dat";
477 URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
478 return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
479 } catch (Exception e) {
480 log.warning("Failed to create patch resource path",
481 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
487 * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
488 * place of the installed VM (in the case where the VM that launched Getdown does not meet the
489 * application's version requirements) or null if no VM is available for this platform.
491 public Resource getJavaVMResource ()
493 if (StringUtil.isBlank(_javaLocation)) {
497 String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
498 String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
499 log.info("vmfile is '"+vmfile+"'");
500 System.out.println("vmfile is '"+vmfile+"'");
502 URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
503 log.info("Attempting to fetch jvm at "+remote.toString());
504 System.out.println("Attempting to fetch jvm at "+remote.toString());
505 return new Resource(vmfile, remote, getLocalPath(vmfile),
506 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
507 } catch (Exception e) {
508 log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
509 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
510 System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
511 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
517 * Returns a resource that can be used to download an archive containing all files belonging to
520 public Resource getFullResource ()
522 String file = "full";
524 URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
525 return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
526 } catch (Exception e) {
527 log.warning("Failed to create full resource path",
528 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
534 * Returns the URL to use to report an initial download event. Returns null if no tracking
535 * start URL was configured for this application.
537 * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
539 public URL getTrackingURL (String event)
542 String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
543 String ga = getGATrackingCode();
544 return _trackingURL == null ? null :
545 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
546 } catch (MalformedURLException mue) {
547 log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
553 * Returns the URL to request to report that we have reached the specified percentage of our
554 * initial download. Returns null if no tracking request was configured for the specified
557 public URL getTrackingProgressURL (int percent)
559 if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
562 return getTrackingURL("pct" + percent);
566 * Returns the name of our tracking cookie or null if it was not set.
568 public String getTrackingCookieName ()
570 return _trackingCookieName;
574 * Returns the name of our tracking cookie system property or null if it was not set.
576 public String getTrackingCookieProperty ()
578 return _trackingCookieProperty;
582 * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
583 * for operation. The application base URL will be parsed first so that if there are errors
584 * discovered later, the caller can use the application base to download a new {@code
585 * getdown.txt} file and try again.
587 * @return a {@code Config} instance that contains information from the config file.
589 * @exception IOException thrown if there is an error reading the file or an error encountered
590 * during its parsing.
592 public Config init (boolean checkPlatform)
595 if (_initialised && _initialisedConfig != null)
597 return _initialisedConfig;
601 Application.i4jVersion = com.install4j.api.launcher.Variables.getCompilerVariable("sys.install4jVersion");
602 } catch (IOException e)
604 System.err.println("install4j version not available");
605 } catch (NoClassDefFoundError e)
607 log.warning("Starting without install4j classes");
608 } catch (Throwable t)
610 System.err.println("install4j not available");
614 Config config = null;
615 File cfgfile = _config;
616 Config.ParseOpts opts = Config.createOpts(checkPlatform);
618 // if we have a configuration file, read the data from it
619 if (cfgfile.exists()) {
620 config = Config.parseConfig(_config, opts);
622 // otherwise, try reading data from our backup config file; thanks to funny windows
623 // bullshit, we have to do this backup file fiddling in case we got screwed while
624 // updating getdown.txt during normal operation
625 else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
626 config = Config.parseConfig(cfgfile, opts);
628 // otherwise, issue a warning that we found no getdown file
630 log.info("Found no getdown.txt file", "appdir", getAppDir());
632 } catch (Exception e) {
633 log.warning("Failure reading config file", "file", _config, e);
635 if (config == null || config.getString("appbase") == null || config.getString("appbase").isEmpty()) {
637 Config backupConfig = Config.parseConfig(_backupConfig, opts);
638 config = backupConfig;
639 log.warning("Using backup config file", "appdir", getAppDir(), "backupConfig", _backupConfig.getAbsoluteFile());
640 } catch (Exception e) {
641 log.warning("Failure reading backup config file", "file", _backupConfig, e);
645 // see if there's an override config from locator file
646 Config locatorConfig = createLocatorConfig(opts);
648 // merge the locator file config into config (or replace config with)
649 if (locatorConfig != null) {
650 if (config == null || locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_replace")) {
651 config = locatorConfig;
653 config.mergeConfig(locatorConfig, locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_merge"));
657 // if we failed to read our config file, check for an appbase specified via a system
658 // property; we can use that to bootstrap ourselves back into operation
659 if (config == null) {
660 String appbase = _envc.appBase;
661 log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
662 Map<String, Object> cdata = new HashMap<>();
663 cdata.put("appbase", appbase);
664 config = new Config(cdata);
667 // first determine our application base, this way if anything goes wrong later in the
668 // process, our caller can use the appbase to download a new configuration file
669 _appbase = config.getString("appbase");
671 // see if locatorConfig override
672 if (locatorConfig != null && !StringUtil.isBlank(locatorConfig.getString("appbase"))) {
673 _appbase = locatorConfig.getString("appbase");
676 if (_appbase == null) {
677 throw new RuntimeException("m.missing_appbase");
680 // check if we're overriding the domain in the appbase
681 _appbase = SysProps.overrideAppbase(_appbase);
683 // make sure there's a trailing slash
684 if (!_appbase.endsWith("/")) {
685 _appbase = _appbase + "/";
688 // extract our version information
689 _version = config.getLong("version", -1L);
691 // if we are a versioned deployment, create a versioned appbase
693 _vappbase = createVAppBase(_version);
694 } catch (MalformedURLException mue) {
695 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
696 throw (IOException) new IOException(err).initCause(mue);
699 // check for a latest config URL
700 String latest = config.getString("latest");
701 if (latest != null) {
702 if (latest.startsWith(_appbase)) {
703 latest = _appbase + latest.substring(_appbase.length());
705 latest = SysProps.replaceDomain(latest);
708 _latest = HostWhitelist.verify(new URL(latest));
709 } catch (MalformedURLException mue) {
710 log.warning("Invalid URL for latest attribute.", mue);
714 String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
716 // determine our application class name (use app-specific class _if_ one is provided)
717 _class = config.getString("class");
718 if (appPrefix.length() > 0) {
719 _class = config.getString(appPrefix + "class", _class);
721 if (_class == null) {
722 throw new IOException("m.missing_class");
725 // determine whether we want strict comments
726 _strictComments = config.getBoolean("strict_comments");
728 // check to see if we're using a custom java.version property and regex
729 _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
730 _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
732 // check to see if we require a particular JVM version and have a supplied JVM
733 _javaMinVersion = config.getLong("java_version", _javaMinVersion);
734 // we support java_min_version as an alias of java_version; it better expresses the check
735 // that's going on and better mirrors java_max_version
736 _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
737 // check to see if we require a particular max JVM version and have a supplied JVM
738 _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
739 // check to see if we require a particular JVM version and have a supplied JVM
740 _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
742 // this is a little weird, but when we're run from the digester, we see a String[] which
743 // contains java locations for all platforms which we can't grok, but the digester doesn't
744 // need to know about that; when we're run in a real application there will be only one!
745 Object javaloc = config.getRaw("java_location");
746 if (javaloc instanceof String) {
747 _javaLocation = (String)javaloc;
750 // determine whether we have any tracking configuration
751 _trackingURL = config.getString("tracking_url");
753 // check for tracking progress percent configuration
754 String trackPcts = config.getString("tracking_percents");
755 if (!StringUtil.isBlank(trackPcts)) {
756 _trackingPcts = new HashSet<>();
757 for (int pct : StringUtil.parseIntArray(trackPcts)) {
758 _trackingPcts.add(pct);
760 } else if (!StringUtil.isBlank(_trackingURL)) {
761 _trackingPcts = new HashSet<>();
762 _trackingPcts.add(50);
765 // Check for tracking cookie configuration
766 _trackingCookieName = config.getString("tracking_cookie_name");
767 _trackingCookieProperty = config.getString("tracking_cookie_property");
769 // Some app may need an extra suffix added to the tracking URL
770 _trackingURLSuffix = config.getString("tracking_url_suffix");
772 // Some app may need to generate google analytics code
773 _trackingGAHash = config.getString("tracking_ga_hash");
775 // clear our arrays as we may be reinitializing
783 // parse our code resources
784 if (config.getMultiValue("code") == null &&
785 config.getMultiValue("ucode") == null) {
786 throw new IOException("m.missing_code");
788 parseResources(config, "code", Resource.NORMAL, _codes);
789 parseResources(config, "ucode", Resource.UNPACK, _codes);
791 // parse our non-code resources
792 parseResources(config, "resource", Resource.NORMAL, _resources);
793 parseResources(config, "uresource", Resource.UNPACK, _resources);
794 parseResources(config, "xresource", Resource.EXEC, _resources);
795 parseResources(config, "presource", Resource.PRELOAD, _resources);
796 parseResources(config, "nresource", Resource.NATIVE, _resources);
798 // parse our auxiliary resource groups
799 for (String auxgroup : config.getList("auxgroups")) {
800 ArrayList<Resource> codes = new ArrayList<>();
801 parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
802 parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
803 ArrayList<Resource> rsrcs = new ArrayList<>();
804 parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
805 parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
806 parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
807 parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
808 parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
809 _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
812 // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
813 String[] jvmargs = config.getMultiValue("jvmarg");
814 addAll(jvmargs, _jvmargs);
815 if (appPrefix.length() > 0) {
816 jvmargs = config.getMultiValue(appPrefix + "jvmarg");
817 addAll(jvmargs, _jvmargs);
820 // see if a percentage of physical memory, or max heap size options exist
821 jvmmempc = config.getString("jvmmempc", null);
822 jvmmemmax = config.getString("jvmmemmax", null);
823 // app_id prefixed setting overrides
824 if (appPrefix.length() > 0) {
825 jvmmempc = config.getString(appPrefix + "jvmmempc", jvmmempc);
826 jvmmemmax = config.getString(appPrefix + "jvmmemmax", jvmmemmax);
829 // get the set of optimum JVM arguments
830 _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
832 // transfer our application arguments
833 String[] appargs = config.getMultiValue(appPrefix + "apparg");
834 addAll(appargs, _appargs);
836 // add the launch specific application arguments
837 _appargs.addAll(_envc.appArgs);
839 // look for custom arguments
840 fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
842 // determine whether we want to allow offline operation (defaults to false)
843 _allowOffline = config.getBoolean("allow_offline");
845 // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
846 // obtain a thread dump of the running JVM
847 _windebug = getLocalPath("debug.txt").exists();
849 // whether to cache code resources and launch from cache
850 _useCodeCache = config.getBoolean("use_code_cache");
851 _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
853 // maximum simultaneous downloads
854 _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
855 SysProps.threadPoolSize()));
857 // extract some info used to configure our child process on macOS
858 _dockName = config.getString("ui.name");
859 _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
862 _initialisedConfig = config;
867 * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
869 protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
871 File pairFile = getLocalPath(pairLocation);
872 if (pairFile.exists()) {
874 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
875 for (String[] pair : args) {
876 if (pair[1].length() == 0) {
877 collector.add(pair[0]);
879 collector.add(pair[0] + "=" + pair[1]);
882 } catch (Throwable t) {
883 log.warning("Failed to parse '" + pairFile + "': " + t);
889 * Returns a URL from which the specified path can be fetched. Our application base URL is
890 * properly versioned and combined with the supplied path.
892 public URL getRemoteURL (String path)
893 throws MalformedURLException
895 return new URL(_vappbase, encodePath(path));
899 * Returns the local path to the specified resource.
901 public File getLocalPath (String path)
903 return getLocalPath(getAppDir(), path);
907 * Returns true if we either have no version requirement, are running in a JVM that meets our
908 * version requirements or have what appears to be a version of the JVM that meets our
911 public boolean haveValidJavaVersion ()
913 // if we're doing no version checking, then yay!
914 if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
917 // parse the version out of the java.version (or custom) system property
918 long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
920 log.info("Checking Java version", "current", version,
921 "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
923 // if we have an unpacked VM, check the 'release' file for its version
924 Resource vmjar = getJavaVMResource();
925 if (vmjar != null && vmjar.isMarkedValid()) {
926 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
927 File relfile = new File(vmdir, "release");
928 if (!relfile.exists()) {
929 log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
933 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
935 log.warning("Unable to read version from 'release' file. Assuming valid.");
940 log.info("Checking version of unpacked JVM [vers=" + version + "].");
943 if (_javaExactVersionRequired) {
944 if (version == _javaMinVersion) return true;
946 log.warning("An exact Java VM version is required.", "current", version,
947 "required", _javaMinVersion);
952 boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
953 boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
954 return minVersionOK && maxVersionOK;
956 } catch (RuntimeException re) {
957 // if we can't parse the java version we're in weird land and should probably just try
958 // our luck with what we've got rather than try to download a new jvm
959 log.warning("Unable to parse VM version, hoping for the best",
960 "error", re, "needed", _javaMinVersion);
966 * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
967 * whether the launch is successful and, if necessary, trying again without the optimum
970 public boolean hasOptimumJvmArgs ()
972 return _optimumJvmArgs != null;
976 * Returns true if the app should attempt to run even if we have no Internet connection.
978 public boolean allowOffline ()
980 return _allowOffline;
984 * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
985 * previous call to {@link #init}.
987 public void attemptRecovery (StatusDisplay status)
990 status.updateStatus("m.updating_metadata");
991 downloadConfigFile();
995 * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
996 * those for the target version of our application.
998 public void updateMetadata ()
1002 // update our versioned application base with the target version
1003 _vappbase = createVAppBase(_targetVersion);
1004 } catch (MalformedURLException mue) {
1005 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
1006 throw (IOException) new IOException(err).initCause(mue);
1010 // now re-download our control files; we download the digest first so that if it fails,
1011 // our config file will still reference the old version and re-running the updater will
1012 // start the whole process over again
1013 downloadDigestFiles();
1014 downloadConfigFile();
1016 } catch (IOException ex) {
1017 // if we are allowing offline execution, we want to allow the application to run in its
1018 // current form rather than aborting the entire process; to do this, we delete the
1019 // version.txt file and "trick" Getdown into thinking that it just needs to validate
1020 // the application as is; next time the app runs when connected to the internet, it
1021 // will have to rediscover that it needs updating and reattempt to update itself
1022 if (_allowOffline) {
1023 log.warning("Failed to update digest files. Attempting offline operaton.", ex);
1024 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
1025 log.warning("Deleting version.txt failed. This probably isn't going to work.");
1034 * Invokes the process associated with this application definition.
1036 * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
1039 public Process createProcess (boolean optimum)
1042 ArrayList<String> args = new ArrayList<>();
1044 // reconstruct the path to the JVM
1045 args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
1047 // check whether we're using -jar mode or -classpath mode
1048 boolean dashJarMode = MANIFEST_CLASS.equals(_class);
1050 // add the -classpath arguments if we're not in -jar mode
1051 ClassPath classPath = PathBuilder.buildClassPath(this);
1053 args.add("-classpath");
1054 args.add(classPath.asArgumentString());
1057 // we love our Mac users, so we do nice things to preserve our application identity
1058 if (LaunchUtil.isMacOS()) {
1059 args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1060 args.add("-Xdock:name=" + _dockName);
1063 // pass along our proxy settings
1064 String proxyHost = System.getProperty("http.proxyHost");
1065 String proxyPort = StringUtil.isBlank(System.getProperty("http.proxyPort")) ? "80" : System.getProperty("http.proxyPort");
1066 if (StringUtil.isBlank(proxyHost) && ! proxy.equals(Proxy.NO_PROXY)) {
1068 SocketAddress a = proxy.address();
1069 if (a != null && a instanceof InetSocketAddress) {
1070 InetSocketAddress ia = (InetSocketAddress)a;
1071 proxyHost = ia.getHostString();
1072 proxyPort = String.valueOf(ia.getPort());
1074 } catch (Exception e) {
1075 log.error("Problem obtaining proxy settings from Proxy object");
1076 e.printStackTrace();
1079 if (proxyHost != null) {
1080 log.info("Using proxy settings "+proxyHost+":"+proxyPort);
1081 args.add("-Dhttp.proxyHost=" + proxyHost);
1082 args.add("-Dhttp.proxyPort=" + proxyPort);
1083 args.add("-Dhttps.proxyHost=" + proxyHost);
1084 args.add("-Dhttps.proxyPort=" + proxyPort);
1086 log.info("Not setting proxy");
1089 // add the marker indicating the app is running in getdown
1090 args.add("-D" + Properties.GETDOWN + "=true");
1091 args.add("-Dsys.install4jVersion=" + Application.i4jVersion);
1092 args.add("-Dinstaller_template_version=" + System.getProperty("installer_template_version"));
1093 args.add("-Dlauncher_version=" + Build.version());
1095 // set HiDPI property if wanted
1096 String scalePropertyArg = HiDPISetting.getScalePropertyArg();
1097 if (scalePropertyArg != null)
1099 args.add(scalePropertyArg);
1102 // set the native library path if we have native resources
1103 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1104 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1105 if (javaLibPath != null) {
1106 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1109 // pass along any pass-through arguments
1110 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1111 String key = (String)entry.getKey();
1112 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1113 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1114 args.add("-D" + key + "=" + entry.getValue());
1118 // test for jalview/s URL. Insert startupNotification URI into start of _appargs
1119 if (! StringUtil.isBlank(_jalviewUri)) {
1120 _appargs.add(0, _jalviewUri);
1122 if (_appargs.size() > 0) {
1123 String uri = _appargs.get(0);
1125 log.info("TRYING TO PARSE URL '"+uri+"'");
1126 URI jalviewUri = new URI(uri);
1127 if (jalviewUri != null) {
1128 String scheme = jalviewUri.getScheme();
1129 if (scheme != null && (scheme.equals("jalview") || scheme.equals("jalviews"))) {
1130 boolean https = jalviewUri.getScheme().equals("jalviews");
1131 String host = jalviewUri.getHost();
1132 int port = jalviewUri.getPort();
1133 String file = jalviewUri.getPath();
1134 String ref = jalviewUri.getFragment();
1135 String query = jalviewUri.getQuery();
1138 _appargs.add("-open");
1139 if (host != null && host.length() > 0) {
1140 URL newUrl = new URL(
1141 (https?"https":"http")
1144 + (port > -1? String.valueOf(port) : "")
1145 + jalviewUri.getRawPath()
1146 + (query != null && query.length() > 0 ? "?" + jalviewUri.getRawQuery() : "")
1148 _appargs.add(newUrl.toString());
1153 if (ref != null && ref.length() > 0) {
1154 String[] refArgs = ref.split("&");
1155 for (String refArg : refArgs) {
1156 if (refArg.startsWith("jvmmempc=")) {
1157 jvmmempc = refArg.substring(9);
1160 if (refArg.startsWith("jvmmemmax=")) {
1161 jvmmemmax = refArg.substring(10);
1164 _appargs.add(URLDecoder.decode(refArg, "UTF-8"));
1170 } catch (URISyntaxException e) {
1171 log.error("Malformed jalview URI", uri);
1175 for (String argString: _appargs) {
1176 if (argString.startsWith("-jvmmempc=")) {
1177 jvmmempc = argString.substring(10);
1180 if (argString.startsWith("-jvmmemmax=")) {
1181 jvmmemmax = argString.substring(11);
1186 // use saved preferences if no cmdline args
1187 File channelProps = getLocalPath(ChannelProperties.CHANNEL_PROPERTIES_FILENAME);
1188 if (channelProps.exists()) {
1190 InputStream is = new FileInputStream(channelProps);
1191 ChannelProperties.loadProps(is);
1192 } catch (IOException e) {
1193 log.error(e.getMessage());
1196 boolean useCustomisedSettings = Boolean.parseBoolean(LaunchUtils.getUserPreference(MemorySetting.CUSTOMISED_SETTINGS));
1197 if (useCustomisedSettings) {
1198 if (jvmmempc == null) {
1199 jvmmempc = LaunchUtils.getUserPreference(MemorySetting.MEMORY_JVMMEMPC);
1201 if (jvmmemmax == null) {
1202 jvmmemmax = LaunchUtils.getUserPreference(MemorySetting.MEMORY_JVMMEMMAX);
1206 // add the memory setting from jvmmempc and jvmmemmax
1207 long maxMemLong = -1;
1208 maxMemLong = MemorySetting.getMemorySetting(jvmmemmax, jvmmempc);
1211 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
1212 // remove other max heap size arg
1213 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
1214 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
1219 addAll(maxMemHeapArg, _jvmargs);
1222 // add the JVM arguments
1223 for (String string : _jvmargs) {
1224 args.add(processArg(string));
1227 // add the optimum arguments if requested and available
1228 if (optimum && _optimumJvmArgs != null) {
1229 for (String string : _optimumJvmArgs) {
1230 args.add(processArg(string));
1234 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1235 for (String string : _txtJvmArgs) {
1236 args.add(processArg(string));
1239 // if we're in -jar mode add those arguments, otherwise add the app class name
1242 args.add(classPath.asArgumentString());
1247 // almost finally check the startup file arguments
1248 for (File f : _startupFiles) {
1249 _appargs.add(f.getAbsolutePath());
1250 break; // Only add one file to open
1253 // check if one arg with recognised extension
1254 if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1255 String filename = _appargs.get(0);
1257 int j = filename.lastIndexOf('.');
1259 ext = filename.substring(j+1);
1261 if (ext != null && LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase())) {
1262 // this file extension should have been dealt with in Getdown class
1264 _appargs.add(0, "-open");
1268 // finally add the application arguments
1269 for (String string : _appargs) {
1270 args.add(processArg(string));
1273 String[] envp = createEnvironment();
1274 String[] sargs = args.toArray(new String[args.size()]);
1275 log.info("Running " + StringUtil.join(sargs, "\n "));
1277 return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1281 * If the application provided environment variables, combine those with the current
1282 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1283 * If the application didn't provide any environment variables, null is returned to just use
1284 * the existing environment.
1286 protected String[] createEnvironment ()
1288 List<String> envvar = new ArrayList<>();
1289 fillAssignmentListFromPairs("env.txt", envvar);
1290 if (envvar.isEmpty()) {
1291 log.info("Didn't find any custom environment variables, not setting any.");
1295 List<String> envAssignments = new ArrayList<>();
1296 for (String assignment : envvar) {
1297 envAssignments.add(processArg(assignment));
1299 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1300 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1302 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1303 log.info("Environment " + StringUtil.join(envp, "\n "));
1308 * Runs this application directly in the current VM.
1310 public void invokeDirect () throws IOException
1312 ClassPath classPath = PathBuilder.buildClassPath(this);
1313 URL[] jarUrls = classPath.asUrls();
1315 // create custom class loader
1316 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1317 @Override protected PermissionCollection getPermissions (CodeSource code) {
1318 Permissions perms = new Permissions();
1319 perms.add(new AllPermission());
1323 Thread.currentThread().setContextClassLoader(loader);
1325 log.info("Configured URL class loader:");
1326 for (URL url : jarUrls) log.info(" " + url);
1328 // configure any system properties that we can
1329 for (String jvmarg : _jvmargs) {
1330 if (jvmarg.startsWith("-D")) {
1331 jvmarg = processArg(jvmarg.substring(2));
1332 int eqidx = jvmarg.indexOf("=");
1334 log.warning("Bogus system property: '" + jvmarg + "'?");
1336 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1341 // pass along any pass-through arguments
1342 Map<String, String> passProps = new HashMap<>();
1343 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1344 String key = (String)entry.getKey();
1345 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1346 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1347 passProps.put(key, (String)entry.getValue());
1350 // we can't set these in the above loop lest we get a ConcurrentModificationException
1351 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1352 System.setProperty(entry.getKey(), entry.getValue());
1355 // prepare our app arguments
1356 String[] args = new String[_appargs.size()];
1357 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1360 log.info("Loading " + _class);
1361 Class<?> appclass = loader.loadClass(_class);
1362 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1363 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1364 main.invoke(null, new Object[] { args });
1365 } catch (Exception e) {
1366 log.warning("Failure invoking app main", e);
1370 /** Replaces the application directory and version in any argument. */
1371 protected String processArg (String arg)
1373 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1374 arg = arg.replace("%VERSION%", String.valueOf(_version));
1376 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1377 // from the environment
1378 if (arg.contains(ENV_VAR_PREFIX)) {
1379 StringBuffer sb = new StringBuffer();
1380 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1381 while (matcher.find()) {
1382 String varName = matcher.group(1), varValue = System.getenv(varName);
1383 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1384 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1386 matcher.appendTail(sb);
1387 arg = sb.toString();
1394 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1395 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1396 * whether or not the application needs to be updated or whether we can proceed to verification
1399 * @return true if the application needs to be updated, false if it is up to date and can be
1400 * verified and executed.
1402 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1405 public boolean verifyMetadata (StatusDisplay status)
1408 log.info("Verifying application: " + _vappbase);
1409 log.info("Version: " + _version);
1410 log.info("Class: " + _class);
1412 // this will read in the contents of the digest file and validate itself
1414 _digest = new Digest(getAppDir(), _strictComments);
1415 } catch (IOException ioe) {
1416 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1419 // if we have no version, then we are running in unversioned mode so we need to download
1420 // our digest.txt file on every invocation
1421 if (_version == -1) {
1422 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1423 // resources as one or more of them have also changed
1424 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1426 status.updateStatus("m.checking");
1427 downloadDigestFiles();
1428 _digest = new Digest(getAppDir(), _strictComments);
1429 if (!olddig.equals(_digest.getMetaDigest())) {
1430 log.info("Unversioned digest changed. Revalidating...");
1431 status.updateStatus("m.validating");
1432 clearValidationMarkers();
1434 } catch (IOException ioe) {
1435 log.warning("Failed to refresh non-versioned digest: " +
1436 ioe.getMessage() + ". Proceeding...");
1440 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1441 // redownload the digest file and give it another good college try; this time we allow
1442 // exceptions to propagate up to the caller as there is nothing else we can do
1443 if (_digest == null) {
1444 status.updateStatus("m.updating_metadata");
1445 downloadDigestFiles();
1446 _digest = new Digest(getAppDir(), _strictComments);
1449 // now verify the contents of our main config file
1450 Resource crsrc = getConfigResource();
1451 if (!_digest.validateResource(crsrc, null)) {
1452 status.updateStatus("m.updating_metadata");
1453 // attempt to redownload both of our metadata files; again we pass errors up to our
1454 // caller because there's nothing we can do to automatically recover
1455 downloadConfigFile();
1456 downloadDigestFiles();
1457 _digest = new Digest(getAppDir(), _strictComments);
1458 // revalidate everything if we end up downloading new metadata
1459 clearValidationMarkers();
1460 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1461 if (_digest.validateResource(crsrc, null)) {
1462 // unset _initialisedConfig so new file is initialised
1463 _initialisedConfig = null;
1466 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1467 "Blindly forging onward.");
1471 // start by assuming we are happy with our version
1472 _targetVersion = _version;
1474 // if we are a versioned application, read in the contents of the version.txt file
1475 // and/or check the latest config URL for a newer version
1476 if (_version != -1) {
1477 File vfile = getLocalPath(VERSION_FILE);
1478 long fileVersion = VersionUtil.readVersion(vfile);
1479 if (fileVersion != -1) {
1480 _targetVersion = fileVersion;
1483 if (_latest != null) {
1484 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1485 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1486 BufferedReader bin = new BufferedReader(reader)) {
1487 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1488 if (pair[0].equals("version")) {
1489 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1490 if (fileVersion != -1 && _targetVersion > fileVersion) {
1491 // replace the file with the newest version
1492 try (FileOutputStream fos = new FileOutputStream(vfile);
1493 PrintStream out = new PrintStream(fos)) {
1494 out.println(_targetVersion);
1500 } catch (Exception e) {
1501 log.warning("Unable to retrieve version from latest config file.", e);
1506 // finally let the caller know if we need an update
1507 return _version != _targetVersion;
1511 * Verifies the code and media resources associated with this application. A list of resources
1512 * that do not exist or fail the verification process will be returned. If all resources are
1513 * ready to go, null will be returned and the application is considered ready to run.
1515 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1516 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1517 * you have to take care to get back to your UI thread.
1518 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1519 * validated" resources filled in.
1520 * @param unpacked a set to populate with unpacked resources.
1521 * @param toInstall a list into which to add resources that need to be installed.
1522 * @param toDownload a list into which to add resources that need to be downloaded.
1524 public void verifyResources (
1525 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1526 Set<Resource> toInstall, Set<Resource> toDownload)
1527 throws InterruptedException
1529 // resources are verified on background threads supplied by the thread pool, and progress
1530 // is reported by posting runnable actions to the actions queue which is processed by the
1532 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1533 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1534 final int[] completed = new int[1];
1536 long start = System.currentTimeMillis();
1538 // obtain the sizes of the resources to validate
1539 List<Resource> rsrcs = getAllActiveResources();
1540 long[] sizes = new long[rsrcs.size()];
1542 for (int ii = 0; ii < sizes.length; ii++) {
1543 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1545 final ProgressObserver fobs = obs;
1546 // as long as we forward aggregated progress updates to the UI thread, having multiple
1547 // threads update a progress aggregator is "mostly" thread-safe
1548 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1549 public void progress (final int percent) {
1550 actions.add(new Runnable() {
1551 public void run () {
1552 fobs.progress(percent);
1558 final int[] fAlreadyValid = alreadyValid;
1559 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1560 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1561 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1563 for (int ii = 0; ii < sizes.length; ii++) {
1564 final Resource rsrc = rsrcs.get(ii);
1565 final int index = ii;
1566 exec.execute(new Runnable() {
1567 public void run () {
1568 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1569 unpackedAsync, toInstallAsync, toDownloadAsync);
1570 actions.add(new Runnable() {
1571 public void run () {
1579 while (completed[0] < rsrcs.size()) {
1580 // we should be getting progress completion updates WAY more often than one every
1581 // minute, so if things freeze up for 60 seconds, abandon ship
1582 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1588 toInstall.addAll(toInstallAsync);
1589 toDownload.addAll(toDownloadAsync);
1590 unpacked.addAll(unpackedAsync);
1592 long complete = System.currentTimeMillis();
1593 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1594 "duration", (complete-start) + "ms");
1597 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1598 Set<Resource> unpacked,
1599 Set<Resource> toInstall, Set<Resource> toDownload) {
1600 if (rsrc.isMarkedValid()) {
1601 if (alreadyValid != null) {
1609 if (_digest.validateResource(rsrc, obs)) {
1610 // if the resource has a _new file, add it to to-install list
1611 if (rsrc.getLocalNew().exists()) {
1612 toInstall.add(rsrc);
1621 } catch (Exception e) {
1622 log.info("Failure verifying resource. Requesting redownload...",
1623 "rsrc", rsrc, "error", e);
1628 toDownload.add(rsrc);
1632 * Unpacks the resources that require it (we know that they're valid).
1634 * @param unpacked a set of resources to skip because they're already unpacked.
1636 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1637 throws InterruptedException
1639 List<Resource> rsrcs = getActiveResources();
1641 // remove resources that we don't want to unpack
1642 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1643 Resource rsrc = it.next();
1644 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1649 // obtain the sizes of the resources to unpack
1650 long[] sizes = new long[rsrcs.size()];
1651 for (int ii = 0; ii < sizes.length; ii++) {
1652 sizes[ii] = rsrcs.get(ii).getLocal().length();
1655 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1656 for (int ii = 0; ii < sizes.length; ii++) {
1657 Resource rsrc = rsrcs.get(ii);
1658 ProgressObserver pobs = pagg.startElement(ii);
1661 } catch (IOException ioe) {
1662 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1669 * Clears all validation marker files.
1671 public void clearValidationMarkers ()
1673 clearValidationMarkers(getAllActiveResources().iterator());
1677 * Returns the version number for the application. Should only be called after successful
1678 * return of verifyMetadata.
1680 public long getVersion ()
1686 * Creates a versioned application base URL for the specified version.
1688 protected URL createVAppBase (long version)
1689 throws MalformedURLException
1691 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1692 return HostWhitelist.verify(new URL(url));
1696 * Clears all validation marker files for the resources in the supplied iterator.
1698 protected void clearValidationMarkers (Iterator<Resource> iter)
1700 while (iter.hasNext()) {
1701 iter.next().clearMarker();
1706 * Downloads a new copy of CONFIG_FILE.
1708 protected void downloadConfigFile ()
1711 downloadControlFile(CONFIG_FILE, 0);
1715 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1716 * we're not locking at all.
1718 public synchronized boolean lockForUpdates ()
1720 if (_lock != null && _lock.isValid()) {
1724 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1725 } catch (FileNotFoundException e) {
1726 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1730 _lock = _lockChannel.tryLock();
1731 } catch (IOException e) {
1732 log.warning("Unable to create lock", "message", e.getMessage(), e);
1734 } catch (OverlappingFileLockException e) {
1735 log.warning("The lock is held elsewhere in this JVM", e);
1738 log.info("Able to lock for updates: " + (_lock != null));
1739 return _lock != null;
1743 * Release gettingdown.lock
1745 public synchronized void releaseLock ()
1747 if (_lock != null) {
1748 log.info("Releasing lock");
1751 } catch (IOException e) {
1752 log.warning("Unable to release lock", "message", e.getMessage(), e);
1755 _lockChannel.close();
1756 } catch (IOException e) {
1757 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1759 _lockChannel = null;
1765 * Downloads the digest files and validates their signature.
1766 * @throws IOException
1768 protected void downloadDigestFiles ()
1771 for (int version = 1; version <= Digest.VERSION; version++) {
1772 downloadControlFile(Digest.digestFile(version), version);
1777 * Downloads a new copy of the specified control file, optionally validating its signature.
1778 * If the download is successful, moves it over the old file on the filesystem.
1780 * <p> TODO: Switch to PKCS #7 or CMS.
1782 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1783 * should indicate the version of the digest file being validated which indicates which
1784 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1786 protected void downloadControlFile (String path, int sigVersion)
1789 File target = downloadFile(path);
1791 if (sigVersion > 0) {
1792 if (_envc.certs.isEmpty()) {
1793 log.info("No signing certs, not verifying digest.txt", "path", path);
1796 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1797 byte[] signature = null;
1798 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1799 signature = StreamUtil.toByteArray(signatureStream);
1801 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1804 byte[] buffer = new byte[8192];
1805 int length, validated = 0;
1806 for (Certificate cert : _envc.certs) {
1807 try (FileInputStream dataInput = new FileInputStream(target)) {
1808 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1809 sig.initVerify(cert);
1810 while ((length = dataInput.read(buffer)) != -1) {
1811 sig.update(buffer, 0, length);
1814 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1815 log.info("Signature does not match", "cert", cert.getPublicKey());
1818 log.info("Signature matches", "cert", cert.getPublicKey());
1822 } catch (IOException ioe) {
1823 log.warning("Failure validating signature of " + target + ": " + ioe);
1825 } catch (GeneralSecurityException gse) {
1831 // if we couldn't find a key that validates our digest, we are the hosed!
1832 if (validated == 0) {
1833 // delete the temporary digest file as we know it is invalid
1834 FileUtil.deleteHarder(target);
1835 throw new IOException("m.corrupt_digest_signature_error");
1840 // now move the temporary file over the original
1841 File original = getLocalPath(path);
1842 if (!FileUtil.renameTo(target, original)) {
1843 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1848 * Download a path to a temporary file, returning a {@link File} instance with the path
1851 protected File downloadFile (String path)
1854 File target = getLocalPath(path + "_new");
1856 URL targetURL = null;
1858 targetURL = getRemoteURL(path);
1859 } catch (Exception e) {
1860 log.warning("Requested to download invalid control file",
1861 "appbase", _vappbase, "path", path, "error", e);
1862 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1865 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1867 // stream the URL into our temporary file
1868 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1869 // we have to tell Java not to use caches here, otherwise it will cache any request for
1870 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1871 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1872 // about it; turning off caches is not a performance concern, because when Getdown asks
1873 // to download a file, it expects it to come over the wire, not from a cache
1874 uconn.setUseCaches(false);
1875 uconn.setRequestProperty("Accept-Encoding", "gzip");
1876 try (InputStream fin = uconn.getInputStream()) {
1877 String encoding = uconn.getContentEncoding();
1878 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1879 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1880 try (FileOutputStream fout = new FileOutputStream(target)) {
1881 StreamUtil.copy(fin2, fout);
1889 /** Helper function for creating {@link Resource} instances. */
1890 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1891 throws MalformedURLException
1893 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1896 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1897 protected static void addAll (String[] values, List<String> target) {
1898 if (values != null) {
1899 for (String value : values) {
1906 * Make an immutable List from the specified int array.
1908 public static List<Integer> intsToList (int[] values)
1910 List<Integer> list = new ArrayList<>(values.length);
1911 for (int val : values) {
1914 return Collections.unmodifiableList(list);
1918 * Make an immutable List from the specified String array.
1920 public static List<String> stringsToList (String[] values)
1922 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1925 /** Used to parse resources with the specified name. */
1926 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1927 List<Resource> list)
1929 String[] rsrcs = config.getMultiValue(name);
1930 if (rsrcs == null) {
1933 for (String rsrc : rsrcs) {
1935 list.add(createResource(rsrc, attrs));
1936 } catch (Exception e) {
1937 log.warning("Invalid resource '" + rsrc + "'. " + e);
1942 /** Possibly generates and returns a google analytics tracking cookie. */
1943 protected String getGATrackingCode ()
1945 if (_trackingGAHash == null) {
1948 long time = System.currentTimeMillis() / 1000;
1949 if (_trackingStart == 0) {
1950 _trackingStart = time;
1952 if (_trackingId == 0) {
1953 int low = 100000000, high = 1000000000;
1954 _trackingId = low + _rando.nextInt(high-low);
1956 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1957 cookie.append(".").append(_trackingId);
1958 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1959 cookie.append(".").append(time).append(".1%3B%2B");
1960 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1961 cookie.append(_trackingStart).append(".1.1.");
1962 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1963 int low = 1000000000, high = 2000000000;
1964 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1965 return cookie.toString();
1969 * Encodes a path for use in a URL.
1971 protected static String encodePath (String path)
1974 // we want to keep slashes because we're encoding an entire path; also we need to turn
1975 // + into %20 because web servers don't like + in paths or file names, blah
1976 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1977 } catch (UnsupportedEncodingException ue) {
1978 log.warning("Failed to URL encode " + path + ": " + ue);
1983 protected File getLocalPath (File appdir, String path)
1985 return new File(appdir, path);
1988 public static void setStartupFilesFromParameterString(String p) {
1989 // multiple files *might* be passed in as space separated quoted filenames
1991 if (!StringUtil.isBlank(p)) {
1993 // split quoted params or treat as single string array
1994 if (p.startsWith(q) && p.endsWith(q)) {
1995 // this fails if, e.g.
1996 // p=q("stupidfilename\" " "otherfilename")
1997 // let's hope no-one ever ends a filename with '" '
1998 filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
2000 // single unquoted filename
2001 filenames = new String[]{p};
2004 // check for locator file. Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
2005 String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
2007 !StringUtil.isBlank(locatorFilename)
2008 && locatorFilename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)
2010 setLocatorFile(locatorFilename);
2011 // remove the locator filename from the filenames array
2012 String[] otherFilenames = new String[filenames.length - 1];
2013 System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
2014 filenames = otherFilenames;
2017 for (int i = 0; i < filenames.length; i++) {
2018 String filename = filenames[i];
2019 // skip any other locator files in a multiple file list
2020 if (filename.startsWith("jalview://") || filename.startsWith("jalviews://")) {
2021 setJalviewUri(filename);
2022 } else if (! filename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
2023 addStartupFile(filename);
2029 public static void setLocatorFile(String filename) {
2030 _locatorFile = new File(filename);
2033 public static void addStartupFile(String filename) {
2034 _startupFiles.add(new File(filename));
2037 public static void setJalviewUri(String uri) {
2041 private Config createLocatorConfig(Config.ParseOpts opts) {
2042 if (_locatorFile == null) {
2046 Config locatorConfig = null;
2049 Config tmpConfig = null;
2050 Map<String, Object> tmpData = new HashMap<>();
2051 if (_locatorFile.exists()) {
2052 tmpConfig = Config.parseConfig(_locatorFile, opts);
2053 // appbase is sanitised in HostWhitelist
2054 Map<String, Object> tmpConfigData = tmpConfig.getData();
2055 if (tmpConfig != null) {
2056 for (Map.Entry<String, Object> entry : tmpConfigData.entrySet()) {
2057 String key = entry.getKey();
2058 Object value = entry.getValue();
2059 String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
2060 if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
2061 tmpData.put(key, value);
2065 log.warning("Error occurred reading config file", "file", _locatorFile);
2068 log.warning("Given locator file does not exist", "file", _locatorFile);
2071 locatorConfig = new Config(tmpData);
2073 } catch (Exception e) {
2074 log.warning("Failure reading locator file", "file", _locatorFile, e);
2077 return locatorConfig;
2080 public String getAppbase() {
2084 protected final EnvConfig _envc;
2085 protected File _config;
2086 protected File _backupConfig;
2087 protected Digest _digest;
2089 protected long _version = -1;
2090 protected long _targetVersion = -1;
2091 protected String _appbase;
2092 protected URL _vappbase;
2093 protected URL _latest;
2094 protected String _class;
2095 protected String _dockName;
2096 protected String _dockIconPath;
2097 protected boolean _strictComments;
2098 protected boolean _windebug;
2099 protected boolean _allowOffline;
2100 protected int _maxConcDownloads;
2102 protected String _trackingURL;
2103 protected Set<Integer> _trackingPcts;
2104 protected String _trackingCookieName;
2105 protected String _trackingCookieProperty;
2106 protected String _trackingURLSuffix;
2107 protected String _trackingGAHash;
2108 protected long _trackingStart;
2109 protected int _trackingId;
2111 protected String _javaVersionProp = "java.version";
2112 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
2113 protected long _javaMinVersion, _javaMaxVersion;
2114 protected boolean _javaExactVersionRequired;
2115 protected String _javaLocation;
2117 protected List<Resource> _codes = new ArrayList<>();
2118 protected List<Resource> _resources = new ArrayList<>();
2120 protected boolean _useCodeCache;
2121 protected int _codeCacheRetentionDays;
2123 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
2124 protected Map<String,Boolean> _auxactive = new HashMap<>();
2126 protected List<String> _jvmargs = new ArrayList<>();
2127 protected List<String> _appargs = new ArrayList<>();
2129 protected String[] _optimumJvmArgs;
2131 protected List<String> _txtJvmArgs = new ArrayList<>();
2133 /** If a warning has been issued about not being able to set modtimes. */
2134 protected boolean _warnedAboutSetLastModified;
2136 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
2137 protected FileLock _lock;
2139 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
2140 protected FileChannel _lockChannel;
2142 protected Random _rando = new Random();
2144 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
2146 protected static final String ENV_VAR_PREFIX = "%ENV.";
2147 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
2149 protected static File _locatorFile;
2150 protected static List<File> _startupFiles = new ArrayList<>();
2151 protected static String _jalviewUri;
2152 public static final String LOCATOR_FILE_EXTENSION = "jvl";
2154 private boolean _initialised = false;
2155 private Config _initialisedConfig = null;
2157 public static String i4jVersion = null;
2158 private String jvmmempc = null;
2159 private String jvmmemmax = null;