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 com.install4j.api.launcher.Variables;
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 /** Set this if SHIFT key is down -- reverts to the BACKUP_CONFIG_DIR ("install") */
72 private static boolean shiftKeyPressed = false;
74 /** Used to communicate information about the UI displayed when updating the application. */
75 public static final class UpdateInterface
78 * The major steps involved in updating, along with some arbitrary percentages
79 * assigned to them, to mark global progress.
85 //VERIFY_METADATA(15, 65, 95),
86 VERIFY_METADATA(15, 45, 90),
89 //VERIFY_RESOURCES(70, 97),
90 VERIFY_RESOURCES(40, 90),
91 //REDOWNLOAD_RESOURCES(90),
92 REDOWNLOAD_RESOURCES(80),
98 /** What is the final percent value for this step? */
99 public final List<Integer> defaultPercents;
101 /** Enum constructor. */
102 Step (int... percents)
104 this.defaultPercents = intsToList(percents);
108 /** The human readable name of this application. */
109 public final String name;
111 /** A background color, just in case. */
112 public final int background;
114 /** Background image specifiers for `RotatingBackgrounds`. */
115 public final List<String> rotatingBackgrounds;
117 /** The error background image for `RotatingBackgrounds`. */
118 public final String errorBackground;
120 /** The paths (relative to the appdir) of images for the window icon. */
121 public final List<String> iconImages;
123 /** The path (relative to the appdir) to a single background image to appear first. */
124 public final String instantBackgroundImage;
126 /** The path (relative to the appdir) to a single background image. */
127 public final String backgroundImage;
129 /** The path (relative to the appdir) to the progress bar image. */
130 public final String progressImage;
132 /** The dimensions of the progress bar. */
133 public final Rectangle progress;
135 /** The color of the progress text. */
136 public final int progressText;
138 /** The color of the progress bar. */
139 public final int progressBar;
141 /** The dimensions of the status display. */
142 public final Rectangle status;
144 /** The color of the status text. */
145 public final int statusText;
147 /** The color of the text shadow. */
148 public final int textShadow;
150 /** Where to point the user for help with install errors. */
151 public final String installError;
153 /** The dimensions of the patch notes button. */
154 public final Rectangle patchNotes;
156 /** The patch notes URL. */
157 public final String patchNotesUrl;
159 /** Whether window decorations are hidden for the UI. */
160 public final boolean hideDecorations;
162 /** Whether progress text should be hidden or not. */
163 public final boolean hideProgressText;
165 /** Whether the splash screen should update non-asynchronously before being shown. */
166 public final boolean progressSync;
168 /** Whether the splash screen should update non-asynchronously after being shown. */
169 public final boolean progressSyncAfterShown;
171 /** Whether the splash screen should retain focus. */
172 public final boolean keepOnTop;
174 /** Whether to display the appbase. */
175 public final boolean displayAppbase;
177 /** Whether to display the version. */
178 public final boolean displayVersion;
180 /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
181 * flashing up on the screen and immediately disappearing, which can be confusing to the
183 public final int minShowSeconds;
185 /** The global percentages for each step. A step may have more than one, and
186 * the lowest reasonable one is used if a step is revisited. */
187 public final Map<Step, List<Integer>> stepPercentages;
189 /** Generates a string representation of this instance. */
191 public String toString ()
193 return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage + ", instant_bg=" + instantBackgroundImage +
194 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
195 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
196 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
197 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
198 ", hideProgressText=" + hideProgressText + ", keepOnTop=" + keepOnTop + ", progressSync=" + progressSync +
199 ", progressSyncAfterShown=" + progressSyncAfterShown + ", minShow=" + minShowSeconds +
200 ", displayAppbase=" + displayAppbase + ", displayVersion=" + displayVersion + "]";
203 public UpdateInterface (Config config)
205 this.name = config.getString("ui.name");
206 this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
207 this.progressText = config.getColor("ui.progress_text", Color.BLACK);
208 this.hideProgressText = config.getBoolean("ui.hide_progress_text");
209 this.progressSync = config.getBoolean("ui.progress_sync_before_shown");
210 this.progressSyncAfterShown = config.getBoolean("ui.progress_sync_after_shown");
211 this.keepOnTop = config.getBoolean("ui.keep_on_top");
212 this.displayAppbase = config.getBoolean("ui.display_appbase");
213 this.displayVersion = config.getBoolean("ui.display_version");
214 this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
215 this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
216 this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
217 this.statusText = config.getColor("ui.status_text", Color.BLACK);
218 this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
219 this.hideDecorations = config.getBoolean("ui.hide_decorations");
220 this.backgroundImage = config.getString("ui.background_image");
221 this.instantBackgroundImage = config.getString("ui.instant_background_image");
222 // default to black or white bg color, depending on the brightness of the progressText
223 int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
224 Color.BLACK : Color.WHITE;
225 this.background = config.getColor("ui.background", defaultBackground);
226 this.progressImage = config.getString("ui.progress_image");
227 this.rotatingBackgrounds = stringsToList(
228 config.getMultiValue("ui.rotating_background"));
229 this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
230 this.errorBackground = config.getString("ui.error_background");
232 // On an installation error, where do we point the user.
233 String installError = config.getUrl("ui.install_error", null);
234 this.installError = (installError == null) ?
235 "m.default_install_error" : MessageUtil.taint(installError);
237 // the patch notes bits
238 this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
239 this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
241 // step progress percentage (defaults and then customized values)
242 EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
243 for (Step step : Step.values()) {
244 stepPercentages.put(step, step.defaultPercents);
246 for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
247 String spec = config.getString("ui.percents." + step.name());
250 stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
251 } catch (Exception e) {
252 log.warning("Failed to parse percentages for " + step + ": " + spec);
256 this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
261 * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
262 * take network actions.
264 public static interface StatusDisplay
266 /** Requests that the specified status message be displayed. */
267 public void updateStatus (String message);
271 * Contains metadata for an auxiliary resource group.
273 public static class AuxGroup {
274 public final String name;
275 public final List<Resource> codes;
276 public final List<Resource> rsrcs;
278 public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
280 this.codes = Collections.unmodifiableList(codes);
281 this.rsrcs = Collections.unmodifiableList(rsrcs);
285 /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
286 * the application instance. Yes this is a public mutable field, no I'm not going to create a
287 * getter and setter just to pretend like that's not the case. */
288 public Proxy proxy = Proxy.NO_PROXY;
291 * Creates an application instance which records the location of the <code>getdown.txt</code>
292 * configuration file from the supplied application directory.
295 public Application (EnvConfig envc) {
297 _config = getLocalPath(envc.appDir, CONFIG_FILE);
298 _backupConfig = getLocalPath(envc.appDir, BACKUP_CONFIG_DIR+File.separator+CONFIG_FILE);
302 * Returns the configured application directory.
304 public File getAppDir () {
309 * Returns whether the application should cache code resources prior to launching the
312 public boolean useCodeCache ()
314 return _useCodeCache;
318 * Returns the number of days a cached code resource is allowed to stay unused before it
319 * becomes eligible for deletion.
321 public int getCodeCacheRetentionDays ()
323 return _codeCacheRetentionDays;
327 * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
328 * app files from its hosting server.
330 public int maxConcurrentDownloads () {
331 return _maxConcDownloads;
335 * Returns a resource that refers to the application configuration file itself.
337 public Resource getConfigResource ()
340 return createResource(CONFIG_FILE, Resource.NORMAL);
341 } catch (Exception e) {
342 throw new RuntimeException("Invalid appbase '" + _vappbase + "'.", e);
347 * Returns a list of the code {@link Resource} objects used by this application.
349 public List<Resource> getCodeResources ()
355 * Returns a list of the non-code {@link Resource} objects used by this application.
357 public List<Resource> getResources ()
363 * Returns the digest of the given {@code resource}.
365 public String getDigest (Resource resource)
367 return _digest.getDigest(resource);
371 * Returns a list of all the active {@link Resource} objects used by this application (code and
374 public List<Resource> getAllActiveResources ()
376 List<Resource> allResources = new ArrayList<>();
377 allResources.addAll(getActiveCodeResources());
378 allResources.addAll(getActiveResources());
383 * Returns the auxiliary resource group with the specified name, or null.
385 public AuxGroup getAuxGroup (String name)
387 return _auxgroups.get(name);
391 * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
392 * resource group is a collection of resource files that are not downloaded unless a group
393 * token file is present in the application directory.
395 public Iterable<AuxGroup> getAuxGroups ()
397 return _auxgroups.values();
401 * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
402 * groups should be ignored, activated groups should be downloaded and patched along with the
405 public boolean isAuxGroupActive (String auxgroup)
407 Boolean active = _auxactive.get(auxgroup);
408 if (active == null) {
409 // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
411 active = getLocalPath(auxgroup + ".dat").exists();
412 _auxactive.put(auxgroup, active);
418 * Returns all main code resources and all code resources from active auxiliary resource groups.
420 public List<Resource> getActiveCodeResources ()
422 ArrayList<Resource> codes = new ArrayList<>();
423 codes.addAll(getCodeResources());
424 for (AuxGroup aux : getAuxGroups()) {
425 if (isAuxGroupActive(aux.name)) {
426 codes.addAll(aux.codes);
433 * Returns all resources indicated to contain native library files (.dll, .so, etc.).
435 public List<Resource> getNativeResources ()
437 List<Resource> natives = new ArrayList<>();
438 for (Resource resource: _resources) {
439 if (resource.isNative()) {
440 natives.add(resource);
447 * Returns all non-code resources and all resources from active auxiliary resource groups.
449 public List<Resource> getActiveResources ()
451 ArrayList<Resource> rsrcs = new ArrayList<>();
452 rsrcs.addAll(getResources());
453 for (AuxGroup aux : getAuxGroups()) {
454 if (isAuxGroupActive(aux.name)) {
455 rsrcs.addAll(aux.rsrcs);
462 * Returns a resource that can be used to download a patch file that will bring this
463 * application from its current version to the target version.
465 * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
466 * for the main application patch resource.
468 public Resource getPatchResource (String auxgroup)
470 if (_targetVersion <= _version) {
471 log.warning("Requested patch resource for up-to-date or non-versioned application",
472 "cvers", _version, "tvers", _targetVersion);
476 String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
477 String pfile = "patch" + infix + _version + ".dat";
479 URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
480 return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
481 } catch (Exception e) {
482 log.warning("Failed to create patch resource path",
483 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
489 * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
490 * place of the installed VM (in the case where the VM that launched Getdown does not meet the
491 * application's version requirements) or null if no VM is available for this platform.
493 public Resource getJavaVMResource ()
495 if (StringUtil.isBlank(_javaLocation)) {
499 String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
500 String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
501 log.info("vmfile is '"+vmfile+"'");
502 System.out.println("vmfile is '"+vmfile+"'");
504 URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
505 log.info("Attempting to fetch jvm at "+remote.toString());
506 System.out.println("Attempting to fetch jvm at "+remote.toString());
507 return new Resource(vmfile, remote, getLocalPath(vmfile),
508 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
509 } catch (Exception e) {
510 log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
511 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
512 System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
513 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
519 * Returns a resource that can be used to download an archive containing all files belonging to
522 public Resource getFullResource ()
524 String file = "full";
526 URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
527 return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
528 } catch (Exception e) {
529 log.warning("Failed to create full resource path",
530 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
536 * Returns the URL to use to report an initial download event. Returns null if no tracking
537 * start URL was configured for this application.
539 * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
541 public URL getTrackingURL (String event)
544 String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
545 String ga = getGATrackingCode();
546 return _trackingURL == null ? null :
547 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
548 } catch (MalformedURLException mue) {
549 log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
555 * Returns the URL to request to report that we have reached the specified percentage of our
556 * initial download. Returns null if no tracking request was configured for the specified
559 public URL getTrackingProgressURL (int percent)
561 if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
564 return getTrackingURL("pct" + percent);
568 * Returns the name of our tracking cookie or null if it was not set.
570 public String getTrackingCookieName ()
572 return _trackingCookieName;
576 * Returns the name of our tracking cookie system property or null if it was not set.
578 public String getTrackingCookieProperty ()
580 return _trackingCookieProperty;
584 * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
585 * for operation. The application base URL will be parsed first so that if there are errors
586 * discovered later, the caller can use the application base to download a new {@code
587 * getdown.txt} file and try again.
589 * @return a {@code Config} instance that contains information from the config file.
591 * @exception IOException thrown if there is an error reading the file or an error encountered
592 * during its parsing.
594 public Config init (boolean checkPlatform)
597 if (_initialised && _initialisedConfig != null)
599 return _initialisedConfig;
603 Application.i4jVersion = com.install4j.api.launcher.Variables.getCompilerVariable("sys.install4jVersion");
604 } catch (IOException e)
606 System.err.println("install4j version not available");
607 } catch (NoClassDefFoundError e)
609 log.warning("Starting without install4j classes");
610 } catch (Throwable t)
612 System.err.println("install4j not available");
616 Config config = null;
617 File cfgfile = _config;
618 Config.ParseOpts opts = Config.createOpts(checkPlatform);
620 // if we have a configuration file, read the data from it
621 if (cfgfile.exists()) {
622 config = Config.parseConfig(_config, opts);
624 // otherwise, try reading data from our backup config file; thanks to funny windows
625 // bullshit, we have to do this backup file fiddling in case we got screwed while
626 // updating getdown.txt during normal operation
627 else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
628 config = Config.parseConfig(cfgfile, opts);
630 // otherwise, issue a warning that we found no getdown file
632 log.info("Found no getdown.txt file", "appdir", getAppDir());
634 } catch (Exception e) {
635 log.warning("Failure reading config file", "file", _config, e);
638 System.out.println("3 SHIFT key"+(getShiftKeyPressed()?"":" not")+" pressed");
639 if (getShiftKeyPressed() || config == null || config.getString("appbase") == null || config.getString("appbase").isEmpty()) {
640 System.out.println("4 SHIFT key"+(getShiftKeyPressed()?"":" not")+" pressed");
642 Config backupConfig = Config.parseConfig(_backupConfig, opts);
643 config = backupConfig;
644 log.warning("Using backup config file", "appdir", getAppDir(), "backupConfig", _backupConfig.getAbsoluteFile());
645 } catch (Exception e) {
646 log.warning("Failure reading backup config file", "file", _backupConfig, e);
650 // see if there's an override config from locator file
651 Config locatorConfig = createLocatorConfig(opts);
653 // merge the locator file config into config (or replace config with)
654 if (locatorConfig != null) {
655 if (config == null || locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_replace")) {
656 config = locatorConfig;
658 config.mergeConfig(locatorConfig, locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_merge"));
662 // if we failed to read our config file, check for an appbase specified via a system
663 // property; we can use that to bootstrap ourselves back into operation
664 if (config == null) {
665 String appbase = _envc.appBase;
666 log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
667 Map<String, Object> cdata = new HashMap<>();
668 cdata.put("appbase", appbase);
669 config = new Config(cdata);
672 // first determine our application base, this way if anything goes wrong later in the
673 // process, our caller can use the appbase to download a new configuration file
674 _appbase = config.getString("appbase");
676 // see if locatorConfig override
677 if (locatorConfig != null && !StringUtil.isBlank(locatorConfig.getString("appbase"))) {
678 _appbase = locatorConfig.getString("appbase");
681 if (_appbase == null) {
682 throw new RuntimeException("m.missing_appbase");
685 // check if we're overriding the domain in the appbase
686 _appbase = SysProps.overrideAppbase(_appbase);
688 // make sure there's a trailing slash
689 if (!_appbase.endsWith("/")) {
690 _appbase = _appbase + "/";
693 // extract our version information
694 _version = config.getLong("version", -1L);
696 // if we are a versioned deployment, create a versioned appbase
698 _vappbase = createVAppBase(_version);
699 } catch (MalformedURLException mue) {
700 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
701 throw (IOException) new IOException(err).initCause(mue);
704 // check for a latest config URL
705 String latest = config.getString("latest");
706 if (latest != null) {
707 if (latest.startsWith(_appbase)) {
708 latest = _appbase + latest.substring(_appbase.length());
710 latest = SysProps.replaceDomain(latest);
713 _latest = HostWhitelist.verify(new URL(latest));
714 } catch (MalformedURLException mue) {
715 log.warning("Invalid URL for latest attribute.", mue);
719 String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
721 // determine our application class name (use app-specific class _if_ one is provided)
722 _class = config.getString("class");
723 if (appPrefix.length() > 0) {
724 _class = config.getString(appPrefix + "class", _class);
726 if (_class == null) {
727 throw new IOException("m.missing_class");
730 // determine whether we want strict comments
731 _strictComments = config.getBoolean("strict_comments");
733 // check to see if we're using a custom java.version property and regex
734 _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
735 _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
737 // check to see if we require a particular JVM version and have a supplied JVM
738 _javaMinVersion = config.getLong("java_version", _javaMinVersion);
739 // we support java_min_version as an alias of java_version; it better expresses the check
740 // that's going on and better mirrors java_max_version
741 _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
742 // check to see if we require a particular max JVM version and have a supplied JVM
743 _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
744 // check to see if we require a particular JVM version and have a supplied JVM
745 _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
747 // this is a little weird, but when we're run from the digester, we see a String[] which
748 // contains java locations for all platforms which we can't grok, but the digester doesn't
749 // need to know about that; when we're run in a real application there will be only one!
750 Object javaloc = config.getRaw("java_location");
751 if (javaloc instanceof String) {
752 _javaLocation = (String)javaloc;
755 // determine whether we have any tracking configuration
756 _trackingURL = config.getString("tracking_url");
758 // check for tracking progress percent configuration
759 String trackPcts = config.getString("tracking_percents");
760 if (!StringUtil.isBlank(trackPcts)) {
761 _trackingPcts = new HashSet<>();
762 for (int pct : StringUtil.parseIntArray(trackPcts)) {
763 _trackingPcts.add(pct);
765 } else if (!StringUtil.isBlank(_trackingURL)) {
766 _trackingPcts = new HashSet<>();
767 _trackingPcts.add(50);
770 // Check for tracking cookie configuration
771 _trackingCookieName = config.getString("tracking_cookie_name");
772 _trackingCookieProperty = config.getString("tracking_cookie_property");
774 // Some app may need an extra suffix added to the tracking URL
775 _trackingURLSuffix = config.getString("tracking_url_suffix");
777 // Some app may need to generate google analytics code
778 _trackingGAHash = config.getString("tracking_ga_hash");
780 // clear our arrays as we may be reinitializing
788 // parse our code resources
789 if (config.getMultiValue("code") == null &&
790 config.getMultiValue("ucode") == null) {
791 throw new IOException("m.missing_code");
793 parseResources(config, "code", Resource.NORMAL, _codes);
794 parseResources(config, "ucode", Resource.UNPACK, _codes);
796 // parse our non-code resources
797 parseResources(config, "resource", Resource.NORMAL, _resources);
798 parseResources(config, "uresource", Resource.UNPACK, _resources);
799 parseResources(config, "xresource", Resource.EXEC, _resources);
800 parseResources(config, "presource", Resource.PRELOAD, _resources);
801 parseResources(config, "nresource", Resource.NATIVE, _resources);
803 // parse our auxiliary resource groups
804 for (String auxgroup : config.getList("auxgroups")) {
805 ArrayList<Resource> codes = new ArrayList<>();
806 parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
807 parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
808 ArrayList<Resource> rsrcs = new ArrayList<>();
809 parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
810 parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
811 parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
812 parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
813 parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
814 _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
817 // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
818 String[] jvmargs = config.getMultiValue("jvmarg");
819 addAll(jvmargs, _jvmargs);
820 if (appPrefix.length() > 0) {
821 jvmargs = config.getMultiValue(appPrefix + "jvmarg");
822 addAll(jvmargs, _jvmargs);
825 // see if a percentage of physical memory, or max heap size options exist
826 jvmmempc = config.getString("jvmmempc", null);
827 jvmmemmax = config.getString("jvmmemmax", null);
828 // app_id prefixed setting overrides
829 if (appPrefix.length() > 0) {
830 jvmmempc = config.getString(appPrefix + "jvmmempc", jvmmempc);
831 jvmmemmax = config.getString(appPrefix + "jvmmemmax", jvmmemmax);
834 // get the set of optimum JVM arguments
835 _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
837 // transfer our application arguments
838 String[] appargs = config.getMultiValue(appPrefix + "apparg");
839 addAll(appargs, _appargs);
841 // add the launch specific application arguments
842 _appargs.addAll(_envc.appArgs);
844 // look for custom arguments
845 fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
847 // determine whether we want to allow offline operation (defaults to false)
848 _allowOffline = config.getBoolean("allow_offline");
850 // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
851 // obtain a thread dump of the running JVM
852 _windebug = getLocalPath("debug.txt").exists();
854 // whether to cache code resources and launch from cache
855 _useCodeCache = config.getBoolean("use_code_cache");
856 _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
858 // maximum simultaneous downloads
859 _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
860 SysProps.threadPoolSize()));
862 // extract some info used to configure our child process on macOS
863 _dockName = config.getString("ui.name");
864 _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
867 _initialisedConfig = config;
872 * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
874 protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
876 File pairFile = getLocalPath(pairLocation);
877 if (pairFile.exists()) {
879 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
880 for (String[] pair : args) {
881 if (pair[1].length() == 0) {
882 collector.add(pair[0]);
884 collector.add(pair[0] + "=" + pair[1]);
887 } catch (Throwable t) {
888 log.warning("Failed to parse '" + pairFile + "': " + t);
894 * Returns a URL from which the specified path can be fetched. Our application base URL is
895 * properly versioned and combined with the supplied path.
897 public URL getRemoteURL (String path)
898 throws MalformedURLException
900 return new URL(_vappbase, encodePath(path));
904 * Returns the local path to the specified resource.
906 public File getLocalPath (String path)
908 return getLocalPath(getAppDir(), path);
912 * Returns true if we either have no version requirement, are running in a JVM that meets our
913 * version requirements or have what appears to be a version of the JVM that meets our
916 public boolean haveValidJavaVersion ()
918 // if we're doing no version checking, then yay!
919 if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
922 // parse the version out of the java.version (or custom) system property
923 long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
925 log.info("Checking Java version", "current", version,
926 "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
928 // if we have an unpacked VM, check the 'release' file for its version
929 Resource vmjar = getJavaVMResource();
930 if (vmjar != null && vmjar.isMarkedValid()) {
931 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
932 File relfile = new File(vmdir, "release");
933 if (!relfile.exists()) {
934 log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
938 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
940 log.warning("Unable to read version from 'release' file. Assuming valid.");
945 log.info("Checking version of unpacked JVM [vers=" + version + "].");
948 if (_javaExactVersionRequired) {
949 if (version == _javaMinVersion) return true;
951 log.warning("An exact Java VM version is required.", "current", version,
952 "required", _javaMinVersion);
957 boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
958 boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
959 return minVersionOK && maxVersionOK;
961 } catch (RuntimeException re) {
962 // if we can't parse the java version we're in weird land and should probably just try
963 // our luck with what we've got rather than try to download a new jvm
964 log.warning("Unable to parse VM version, hoping for the best",
965 "error", re, "needed", _javaMinVersion);
971 * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
972 * whether the launch is successful and, if necessary, trying again without the optimum
975 public boolean hasOptimumJvmArgs ()
977 return _optimumJvmArgs != null;
981 * Returns true if the app should attempt to run even if we have no Internet connection.
983 public boolean allowOffline ()
985 return _allowOffline;
989 * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
990 * previous call to {@link #init}.
992 public void attemptRecovery (StatusDisplay status)
995 status.updateStatus("m.updating_metadata");
996 downloadConfigFile();
1000 * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
1001 * those for the target version of our application.
1003 public void updateMetadata ()
1007 // update our versioned application base with the target version
1008 _vappbase = createVAppBase(_targetVersion);
1009 } catch (MalformedURLException mue) {
1010 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
1011 throw (IOException) new IOException(err).initCause(mue);
1015 // now re-download our control files; we download the digest first so that if it fails,
1016 // our config file will still reference the old version and re-running the updater will
1017 // start the whole process over again
1018 downloadDigestFiles();
1019 downloadConfigFile();
1021 } catch (IOException ex) {
1022 // if we are allowing offline execution, we want to allow the application to run in its
1023 // current form rather than aborting the entire process; to do this, we delete the
1024 // version.txt file and "trick" Getdown into thinking that it just needs to validate
1025 // the application as is; next time the app runs when connected to the internet, it
1026 // will have to rediscover that it needs updating and reattempt to update itself
1027 if (_allowOffline) {
1028 log.warning("Failed to update digest files. Attempting offline operaton.", ex);
1029 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
1030 log.warning("Deleting version.txt failed. This probably isn't going to work.");
1039 * Invokes the process associated with this application definition.
1041 * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
1044 public Process createProcess (boolean optimum)
1047 ArrayList<String> args = new ArrayList<>();
1049 // reconstruct the path to the JVM
1050 args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
1052 // check whether we're using -jar mode or -classpath mode
1053 boolean dashJarMode = MANIFEST_CLASS.equals(_class);
1055 // add the -classpath arguments if we're not in -jar mode
1056 ClassPath classPath = PathBuilder.buildClassPath(this);
1058 args.add("-classpath");
1059 args.add(classPath.asArgumentString());
1062 // we love our Mac users, so we do nice things to preserve our application identity
1063 if (LaunchUtil.isMacOS()) {
1064 args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1065 args.add("-Xdock:name=" + _dockName);
1068 // pass along our proxy settings
1069 String proxyHost = System.getProperty("http.proxyHost");
1070 String proxyPort = StringUtil.isBlank(System.getProperty("http.proxyPort")) ? "80" : System.getProperty("http.proxyPort");
1071 if (StringUtil.isBlank(proxyHost) && ! proxy.equals(Proxy.NO_PROXY)) {
1073 SocketAddress a = proxy.address();
1074 if (a != null && a instanceof InetSocketAddress) {
1075 InetSocketAddress ia = (InetSocketAddress)a;
1076 proxyHost = ia.getHostString();
1077 proxyPort = String.valueOf(ia.getPort());
1079 } catch (Exception e) {
1080 log.error("Problem obtaining proxy settings from Proxy object");
1081 e.printStackTrace();
1084 if (proxyHost != null) {
1085 log.info("Using proxy settings "+proxyHost+":"+proxyPort);
1086 args.add("-Dhttp.proxyHost=" + proxyHost);
1087 args.add("-Dhttp.proxyPort=" + proxyPort);
1088 args.add("-Dhttps.proxyHost=" + proxyHost);
1089 args.add("-Dhttps.proxyPort=" + proxyPort);
1091 log.info("Not setting proxy");
1094 // add the marker indicating the app is running in getdown
1095 args.add("-D" + Properties.GETDOWN + "=true");
1096 args.add("-Dsys.install4jVersion=" + Application.i4jVersion);
1097 args.add("-Dinstaller_template_version=" + System.getProperty("installer_template_version"));
1098 args.add("-Dlauncher_version=" + Build.version());
1100 // set HiDPI property if wanted
1101 String scalePropertyArg = HiDPISetting.getScalePropertyArg();
1102 if (scalePropertyArg != null)
1104 args.add(scalePropertyArg);
1107 // set the native library path if we have native resources
1108 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1109 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1110 if (javaLibPath != null) {
1111 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1114 // pass along any pass-through arguments
1115 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1116 String key = (String)entry.getKey();
1117 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1118 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1119 args.add("-D" + key + "=" + entry.getValue());
1123 // test for jalview/s URL. Insert startupNotification URI into start of _appargs
1124 if (! StringUtil.isBlank(_jalviewUri)) {
1125 _appargs.add(0, _jalviewUri);
1127 if (_appargs.size() > 0) {
1128 String uri = _appargs.get(0);
1130 log.info("TRYING TO PARSE URL '"+uri+"'");
1131 URI jalviewUri = new URI(uri);
1132 if (jalviewUri != null) {
1133 String scheme = jalviewUri.getScheme();
1134 if (scheme != null && (scheme.equals("jalview") || scheme.equals("jalviews"))) {
1135 boolean https = jalviewUri.getScheme().equals("jalviews");
1136 String host = jalviewUri.getHost();
1137 int port = jalviewUri.getPort();
1138 String file = jalviewUri.getPath();
1139 String ref = jalviewUri.getFragment();
1140 String query = jalviewUri.getQuery();
1143 _appargs.add("-open");
1144 if (host != null && host.length() > 0) {
1145 URL newUrl = new URL(
1146 (https?"https":"http")
1149 + (port > -1? String.valueOf(port) : "")
1150 + jalviewUri.getRawPath()
1151 + (query != null && query.length() > 0 ? "?" + jalviewUri.getRawQuery() : "")
1153 _appargs.add(newUrl.toString());
1158 if (ref != null && ref.length() > 0) {
1159 String[] refArgs = ref.split("&");
1160 for (String refArg : refArgs) {
1161 if (refArg.startsWith("jvmmempc=")) {
1162 jvmmempc = refArg.substring(9);
1165 if (refArg.startsWith("jvmmemmax=")) {
1166 jvmmemmax = refArg.substring(10);
1169 _appargs.add(URLDecoder.decode(refArg, "UTF-8"));
1175 } catch (URISyntaxException e) {
1176 log.error("Malformed jalview URI", uri);
1180 for (String argString: _appargs) {
1181 if (argString.startsWith("-jvmmempc=")) {
1182 jvmmempc = argString.substring(10);
1185 if (argString.startsWith("-jvmmemmax=")) {
1186 jvmmemmax = argString.substring(11);
1191 // add the memory setting from jvmmempc and jvmmemmax
1192 long maxMemLong = -1;
1193 maxMemLong = MemorySetting.getMemorySetting(jvmmemmax, jvmmempc);
1196 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
1197 // remove other max heap size arg
1198 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
1199 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
1204 addAll(maxMemHeapArg, _jvmargs);
1207 // add the JVM arguments
1208 for (String string : _jvmargs) {
1209 args.add(processArg(string));
1212 // add the optimum arguments if requested and available
1213 if (optimum && _optimumJvmArgs != null) {
1214 for (String string : _optimumJvmArgs) {
1215 args.add(processArg(string));
1219 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1220 for (String string : _txtJvmArgs) {
1221 args.add(processArg(string));
1224 // if we're in -jar mode add those arguments, otherwise add the app class name
1227 args.add(classPath.asArgumentString());
1232 // almost finally check the startup file arguments
1233 for (File f : _startupFiles) {
1234 _appargs.add(f.getAbsolutePath());
1235 break; // Only add one file to open
1238 // check if one arg with recognised extension
1239 if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1240 String filename = _appargs.get(0);
1242 int j = filename.lastIndexOf('.');
1244 ext = filename.substring(j+1);
1246 if (ext != null && LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase())) {
1247 // this file extension should have been dealt with in Getdown class
1249 _appargs.add(0, "-open");
1253 // finally add the application arguments
1254 for (String string : _appargs) {
1255 args.add(processArg(string));
1258 String[] envp = createEnvironment();
1259 String[] sargs = args.toArray(new String[args.size()]);
1260 log.info("Running " + StringUtil.join(sargs, "\n "));
1262 return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1266 * If the application provided environment variables, combine those with the current
1267 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1268 * If the application didn't provide any environment variables, null is returned to just use
1269 * the existing environment.
1271 protected String[] createEnvironment ()
1273 List<String> envvar = new ArrayList<>();
1274 fillAssignmentListFromPairs("env.txt", envvar);
1275 if (envvar.isEmpty()) {
1276 log.info("Didn't find any custom environment variables, not setting any.");
1280 List<String> envAssignments = new ArrayList<>();
1281 for (String assignment : envvar) {
1282 envAssignments.add(processArg(assignment));
1284 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1285 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1287 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1288 log.info("Environment " + StringUtil.join(envp, "\n "));
1293 * Runs this application directly in the current VM.
1295 public void invokeDirect () throws IOException
1297 ClassPath classPath = PathBuilder.buildClassPath(this);
1298 URL[] jarUrls = classPath.asUrls();
1300 // create custom class loader
1301 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1302 @Override protected PermissionCollection getPermissions (CodeSource code) {
1303 Permissions perms = new Permissions();
1304 perms.add(new AllPermission());
1308 Thread.currentThread().setContextClassLoader(loader);
1310 log.info("Configured URL class loader:");
1311 for (URL url : jarUrls) log.info(" " + url);
1313 // configure any system properties that we can
1314 for (String jvmarg : _jvmargs) {
1315 if (jvmarg.startsWith("-D")) {
1316 jvmarg = processArg(jvmarg.substring(2));
1317 int eqidx = jvmarg.indexOf("=");
1319 log.warning("Bogus system property: '" + jvmarg + "'?");
1321 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1326 // pass along any pass-through arguments
1327 Map<String, String> passProps = new HashMap<>();
1328 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1329 String key = (String)entry.getKey();
1330 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1331 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1332 passProps.put(key, (String)entry.getValue());
1335 // we can't set these in the above loop lest we get a ConcurrentModificationException
1336 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1337 System.setProperty(entry.getKey(), entry.getValue());
1340 // prepare our app arguments
1341 String[] args = new String[_appargs.size()];
1342 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1345 log.info("Loading " + _class);
1346 Class<?> appclass = loader.loadClass(_class);
1347 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1348 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1349 main.invoke(null, new Object[] { args });
1350 } catch (Exception e) {
1351 log.warning("Failure invoking app main", e);
1355 /** Replaces the application directory and version in any argument. */
1356 protected String processArg (String arg)
1358 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1359 arg = arg.replace("%VERSION%", String.valueOf(_version));
1361 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1362 // from the environment
1363 if (arg.contains(ENV_VAR_PREFIX)) {
1364 StringBuffer sb = new StringBuffer();
1365 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1366 while (matcher.find()) {
1367 String varName = matcher.group(1), varValue = System.getenv(varName);
1368 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1369 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1371 matcher.appendTail(sb);
1372 arg = sb.toString();
1379 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1380 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1381 * whether or not the application needs to be updated or whether we can proceed to verification
1384 * @return true if the application needs to be updated, false if it is up to date and can be
1385 * verified and executed.
1387 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1390 public boolean verifyMetadata (StatusDisplay status)
1393 log.info("Verifying application: " + _vappbase);
1394 log.info("Version: " + _version);
1395 log.info("Class: " + _class);
1397 // this will read in the contents of the digest file and validate itself
1399 _digest = new Digest(getAppDir(), _strictComments);
1400 } catch (IOException ioe) {
1401 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1404 // if we have no version, then we are running in unversioned mode so we need to download
1405 // our digest.txt file on every invocation
1406 if (_version == -1) {
1407 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1408 // resources as one or more of them have also changed
1409 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1411 status.updateStatus("m.checking");
1412 downloadDigestFiles();
1413 _digest = new Digest(getAppDir(), _strictComments);
1414 if (!olddig.equals(_digest.getMetaDigest())) {
1415 log.info("Unversioned digest changed. Revalidating...");
1416 status.updateStatus("m.validating");
1417 clearValidationMarkers();
1419 } catch (IOException ioe) {
1420 log.warning("Failed to refresh non-versioned digest: " +
1421 ioe.getMessage() + ". Proceeding...");
1425 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1426 // redownload the digest file and give it another good college try; this time we allow
1427 // exceptions to propagate up to the caller as there is nothing else we can do
1428 if (_digest == null) {
1429 status.updateStatus("m.updating_metadata");
1430 downloadDigestFiles();
1431 _digest = new Digest(getAppDir(), _strictComments);
1434 // now verify the contents of our main config file
1435 Resource crsrc = getConfigResource();
1436 if (!_digest.validateResource(crsrc, null)) {
1437 status.updateStatus("m.updating_metadata");
1438 // attempt to redownload both of our metadata files; again we pass errors up to our
1439 // caller because there's nothing we can do to automatically recover
1440 downloadConfigFile();
1441 downloadDigestFiles();
1442 _digest = new Digest(getAppDir(), _strictComments);
1443 // revalidate everything if we end up downloading new metadata
1444 clearValidationMarkers();
1445 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1446 if (_digest.validateResource(crsrc, null)) {
1447 // unset _initialisedConfig so new file is initialised
1448 _initialisedConfig = null;
1451 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1452 "Blindly forging onward.");
1456 // start by assuming we are happy with our version
1457 _targetVersion = _version;
1459 // if we are a versioned application, read in the contents of the version.txt file
1460 // and/or check the latest config URL for a newer version
1461 if (_version != -1) {
1462 File vfile = getLocalPath(VERSION_FILE);
1463 long fileVersion = VersionUtil.readVersion(vfile);
1464 if (fileVersion != -1) {
1465 _targetVersion = fileVersion;
1468 if (_latest != null) {
1469 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1470 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1471 BufferedReader bin = new BufferedReader(reader)) {
1472 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1473 if (pair[0].equals("version")) {
1474 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1475 if (fileVersion != -1 && _targetVersion > fileVersion) {
1476 // replace the file with the newest version
1477 try (FileOutputStream fos = new FileOutputStream(vfile);
1478 PrintStream out = new PrintStream(fos)) {
1479 out.println(_targetVersion);
1485 } catch (Exception e) {
1486 log.warning("Unable to retrieve version from latest config file.", e);
1491 // finally let the caller know if we need an update
1492 return _version != _targetVersion;
1496 * Verifies the code and media resources associated with this application. A list of resources
1497 * that do not exist or fail the verification process will be returned. If all resources are
1498 * ready to go, null will be returned and the application is considered ready to run.
1500 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1501 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1502 * you have to take care to get back to your UI thread.
1503 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1504 * validated" resources filled in.
1505 * @param unpacked a set to populate with unpacked resources.
1506 * @param toInstall a list into which to add resources that need to be installed.
1507 * @param toDownload a list into which to add resources that need to be downloaded.
1509 public void verifyResources (
1510 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1511 Set<Resource> toInstall, Set<Resource> toDownload)
1512 throws InterruptedException
1514 // resources are verified on background threads supplied by the thread pool, and progress
1515 // is reported by posting runnable actions to the actions queue which is processed by the
1517 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1518 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1519 final int[] completed = new int[1];
1521 long start = System.currentTimeMillis();
1523 // obtain the sizes of the resources to validate
1524 List<Resource> rsrcs = getAllActiveResources();
1525 long[] sizes = new long[rsrcs.size()];
1527 for (int ii = 0; ii < sizes.length; ii++) {
1528 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1530 final ProgressObserver fobs = obs;
1531 // as long as we forward aggregated progress updates to the UI thread, having multiple
1532 // threads update a progress aggregator is "mostly" thread-safe
1533 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1534 public void progress (final int percent) {
1535 actions.add(new Runnable() {
1536 public void run () {
1537 fobs.progress(percent);
1543 final int[] fAlreadyValid = alreadyValid;
1544 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1545 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1546 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1548 for (int ii = 0; ii < sizes.length; ii++) {
1549 final Resource rsrc = rsrcs.get(ii);
1550 final int index = ii;
1551 exec.execute(new Runnable() {
1552 public void run () {
1553 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1554 unpackedAsync, toInstallAsync, toDownloadAsync);
1555 actions.add(new Runnable() {
1556 public void run () {
1564 while (completed[0] < rsrcs.size()) {
1565 // we should be getting progress completion updates WAY more often than one every
1566 // minute, so if things freeze up for 60 seconds, abandon ship
1567 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1573 toInstall.addAll(toInstallAsync);
1574 toDownload.addAll(toDownloadAsync);
1575 unpacked.addAll(unpackedAsync);
1577 long complete = System.currentTimeMillis();
1578 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1579 "duration", (complete-start) + "ms");
1582 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1583 Set<Resource> unpacked,
1584 Set<Resource> toInstall, Set<Resource> toDownload) {
1585 if (rsrc.isMarkedValid()) {
1586 if (alreadyValid != null) {
1594 if (_digest.validateResource(rsrc, obs)) {
1595 // if the resource has a _new file, add it to to-install list
1596 if (rsrc.getLocalNew().exists()) {
1597 toInstall.add(rsrc);
1606 } catch (Exception e) {
1607 log.info("Failure verifying resource. Requesting redownload...",
1608 "rsrc", rsrc, "error", e);
1613 toDownload.add(rsrc);
1617 * Unpacks the resources that require it (we know that they're valid).
1619 * @param unpacked a set of resources to skip because they're already unpacked.
1621 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1622 throws InterruptedException
1624 List<Resource> rsrcs = getActiveResources();
1626 // remove resources that we don't want to unpack
1627 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1628 Resource rsrc = it.next();
1629 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1634 // obtain the sizes of the resources to unpack
1635 long[] sizes = new long[rsrcs.size()];
1636 for (int ii = 0; ii < sizes.length; ii++) {
1637 sizes[ii] = rsrcs.get(ii).getLocal().length();
1640 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1641 for (int ii = 0; ii < sizes.length; ii++) {
1642 Resource rsrc = rsrcs.get(ii);
1643 ProgressObserver pobs = pagg.startElement(ii);
1646 } catch (IOException ioe) {
1647 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1654 * Clears all validation marker files.
1656 public void clearValidationMarkers ()
1658 clearValidationMarkers(getAllActiveResources().iterator());
1662 * Returns the version number for the application. Should only be called after successful
1663 * return of verifyMetadata.
1665 public long getVersion ()
1671 * Creates a versioned application base URL for the specified version.
1673 protected URL createVAppBase (long version)
1674 throws MalformedURLException
1676 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1677 return HostWhitelist.verify(new URL(url));
1681 * Clears all validation marker files for the resources in the supplied iterator.
1683 protected void clearValidationMarkers (Iterator<Resource> iter)
1685 while (iter.hasNext()) {
1686 iter.next().clearMarker();
1691 * Downloads a new copy of CONFIG_FILE.
1693 protected void downloadConfigFile ()
1696 downloadControlFile(CONFIG_FILE, 0);
1700 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1701 * we're not locking at all.
1703 public synchronized boolean lockForUpdates ()
1705 if (_lock != null && _lock.isValid()) {
1709 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1710 } catch (FileNotFoundException e) {
1711 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1715 _lock = _lockChannel.tryLock();
1716 } catch (IOException e) {
1717 log.warning("Unable to create lock", "message", e.getMessage(), e);
1719 } catch (OverlappingFileLockException e) {
1720 log.warning("The lock is held elsewhere in this JVM", e);
1723 log.info("Able to lock for updates: " + (_lock != null));
1724 return _lock != null;
1728 * Release gettingdown.lock
1730 public synchronized void releaseLock ()
1732 if (_lock != null) {
1733 log.info("Releasing lock");
1736 } catch (IOException e) {
1737 log.warning("Unable to release lock", "message", e.getMessage(), e);
1740 _lockChannel.close();
1741 } catch (IOException e) {
1742 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1744 _lockChannel = null;
1750 * Downloads the digest files and validates their signature.
1751 * @throws IOException
1753 protected void downloadDigestFiles ()
1756 for (int version = 1; version <= Digest.VERSION; version++) {
1757 downloadControlFile(Digest.digestFile(version), version);
1762 * Downloads a new copy of the specified control file, optionally validating its signature.
1763 * If the download is successful, moves it over the old file on the filesystem.
1765 * <p> TODO: Switch to PKCS #7 or CMS.
1767 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1768 * should indicate the version of the digest file being validated which indicates which
1769 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1771 protected void downloadControlFile (String path, int sigVersion)
1774 File target = downloadFile(path);
1776 if (sigVersion > 0) {
1777 if (_envc.certs.isEmpty()) {
1778 log.info("No signing certs, not verifying digest.txt", "path", path);
1781 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1782 byte[] signature = null;
1783 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1784 signature = StreamUtil.toByteArray(signatureStream);
1786 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1789 byte[] buffer = new byte[8192];
1790 int length, validated = 0;
1791 for (Certificate cert : _envc.certs) {
1792 try (FileInputStream dataInput = new FileInputStream(target)) {
1793 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1794 sig.initVerify(cert);
1795 while ((length = dataInput.read(buffer)) != -1) {
1796 sig.update(buffer, 0, length);
1799 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1800 log.info("Signature does not match", "cert", cert.getPublicKey());
1803 log.info("Signature matches", "cert", cert.getPublicKey());
1807 } catch (IOException ioe) {
1808 log.warning("Failure validating signature of " + target + ": " + ioe);
1810 } catch (GeneralSecurityException gse) {
1816 // if we couldn't find a key that validates our digest, we are the hosed!
1817 if (validated == 0) {
1818 // delete the temporary digest file as we know it is invalid
1819 FileUtil.deleteHarder(target);
1820 throw new IOException("m.corrupt_digest_signature_error");
1825 // now move the temporary file over the original
1826 File original = getLocalPath(path);
1827 if (!FileUtil.renameTo(target, original)) {
1828 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1833 * Download a path to a temporary file, returning a {@link File} instance with the path
1836 protected File downloadFile (String path)
1839 File target = getLocalPath(path + "_new");
1841 URL targetURL = null;
1843 targetURL = getRemoteURL(path);
1844 } catch (Exception e) {
1845 log.warning("Requested to download invalid control file",
1846 "appbase", _vappbase, "path", path, "error", e);
1847 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1850 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1852 // stream the URL into our temporary file
1853 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1854 // we have to tell Java not to use caches here, otherwise it will cache any request for
1855 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1856 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1857 // about it; turning off caches is not a performance concern, because when Getdown asks
1858 // to download a file, it expects it to come over the wire, not from a cache
1859 uconn.setUseCaches(false);
1860 uconn.setRequestProperty("Accept-Encoding", "gzip");
1861 try (InputStream fin = uconn.getInputStream()) {
1862 String encoding = uconn.getContentEncoding();
1863 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1864 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1865 try (FileOutputStream fout = new FileOutputStream(target)) {
1866 StreamUtil.copy(fin2, fout);
1874 /** Helper function for creating {@link Resource} instances. */
1875 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1876 throws MalformedURLException
1878 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1881 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1882 protected static void addAll (String[] values, List<String> target) {
1883 if (values != null) {
1884 for (String value : values) {
1891 * Make an immutable List from the specified int array.
1893 public static List<Integer> intsToList (int[] values)
1895 List<Integer> list = new ArrayList<>(values.length);
1896 for (int val : values) {
1899 return Collections.unmodifiableList(list);
1903 * Make an immutable List from the specified String array.
1905 public static List<String> stringsToList (String[] values)
1907 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1910 /** Used to parse resources with the specified name. */
1911 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1912 List<Resource> list)
1914 String[] rsrcs = config.getMultiValue(name);
1915 if (rsrcs == null) {
1918 for (String rsrc : rsrcs) {
1920 list.add(createResource(rsrc, attrs));
1921 } catch (Exception e) {
1922 log.warning("Invalid resource '" + rsrc + "'. " + e);
1927 /** Possibly generates and returns a google analytics tracking cookie. */
1928 protected String getGATrackingCode ()
1930 if (_trackingGAHash == null) {
1933 long time = System.currentTimeMillis() / 1000;
1934 if (_trackingStart == 0) {
1935 _trackingStart = time;
1937 if (_trackingId == 0) {
1938 int low = 100000000, high = 1000000000;
1939 _trackingId = low + _rando.nextInt(high-low);
1941 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1942 cookie.append(".").append(_trackingId);
1943 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1944 cookie.append(".").append(time).append(".1%3B%2B");
1945 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1946 cookie.append(_trackingStart).append(".1.1.");
1947 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1948 int low = 1000000000, high = 2000000000;
1949 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1950 return cookie.toString();
1954 * Encodes a path for use in a URL.
1956 protected static String encodePath (String path)
1959 // we want to keep slashes because we're encoding an entire path; also we need to turn
1960 // + into %20 because web servers don't like + in paths or file names, blah
1961 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1962 } catch (UnsupportedEncodingException ue) {
1963 log.warning("Failed to URL encode " + path + ": " + ue);
1968 protected File getLocalPath (File appdir, String path)
1970 return new File(appdir, path);
1973 public static void setStartupFilesFromParameterString(String p) {
1974 // multiple files *might* be passed in as space separated quoted filenames
1976 if (!StringUtil.isBlank(p)) {
1978 // split quoted params or treat as single string array
1979 if (p.startsWith(q) && p.endsWith(q)) {
1980 // this fails if, e.g.
1981 // p=q("stupidfilename\" " "otherfilename")
1982 // let's hope no-one ever ends a filename with '" '
1983 filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1985 // single unquoted filename
1986 filenames = new String[]{p};
1989 // check for locator file. Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1990 String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
1992 !StringUtil.isBlank(locatorFilename)
1993 && locatorFilename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)
1995 setLocatorFile(locatorFilename);
1996 // remove the locator filename from the filenames array
1997 String[] otherFilenames = new String[filenames.length - 1];
1998 System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
1999 filenames = otherFilenames;
2002 for (int i = 0; i < filenames.length; i++) {
2003 String filename = filenames[i];
2004 // skip any other locator files in a multiple file list
2005 if (filename.startsWith("jalview://") || filename.startsWith("jalviews://")) {
2006 setJalviewUri(filename);
2007 } else if (! filename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
2008 addStartupFile(filename);
2014 public static void setLocatorFile(String filename) {
2015 _locatorFile = new File(filename);
2018 public static void addStartupFile(String filename) {
2019 _startupFiles.add(new File(filename));
2022 public static void setJalviewUri(String uri) {
2026 private Config createLocatorConfig(Config.ParseOpts opts) {
2027 if (_locatorFile == null) {
2031 Config locatorConfig = null;
2034 Config tmpConfig = null;
2035 Map<String, Object> tmpData = new HashMap<>();
2036 if (_locatorFile.exists()) {
2037 tmpConfig = Config.parseConfig(_locatorFile, opts);
2038 // appbase is sanitised in HostWhitelist
2039 Map<String, Object> tmpConfigData = tmpConfig.getData();
2040 if (tmpConfig != null) {
2041 for (Map.Entry<String, Object> entry : tmpConfigData.entrySet()) {
2042 String key = entry.getKey();
2043 Object value = entry.getValue();
2044 String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
2045 if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
2046 tmpData.put(key, value);
2050 log.warning("Error occurred reading config file", "file", _locatorFile);
2053 log.warning("Given locator file does not exist", "file", _locatorFile);
2056 locatorConfig = new Config(tmpData);
2058 } catch (Exception e) {
2059 log.warning("Failure reading locator file", "file", _locatorFile, e);
2062 return locatorConfig;
2065 public String getAppbase() {
2069 public static boolean getShiftKeyPressed() {
2070 return shiftKeyPressed;
2073 public static void setShiftKeyPressed(boolean down) {
2074 shiftKeyPressed |= down;
2077 public boolean isInstallationAppbase() {
2078 // if not on the installation appbase, give half a second for SHIFT key to be pressed
2079 Config.ParseOpts opts = null;
2080 Config config = null;
2082 Config backupConfig = Config.parseConfig(_backupConfig, opts);
2083 System.out.println("1 SHIFT key"+(getShiftKeyPressed()?"":" not")+" pressed");
2085 System.out.println("2 SHIFT key"+(getShiftKeyPressed()?"":" not")+" pressed");
2086 return (true || (config != null && backupConfig != null && backupConfig.getString("appbase") != null && (!backupConfig.getString("appbase").equals(config.getString("appbase")))));
2088 } catch (NullPointerException e) {
2089 e.printStackTrace();
2090 } catch (InterruptedException e) {
2091 e.printStackTrace();
2092 } catch (IOException e) {
2093 e.printStackTrace();
2098 protected final EnvConfig _envc;
2099 protected File _config;
2100 protected File _backupConfig;
2101 protected Digest _digest;
2103 protected long _version = -1;
2104 protected long _targetVersion = -1;
2105 protected String _appbase;
2106 protected URL _vappbase;
2107 protected URL _latest;
2108 protected String _class;
2109 protected String _dockName;
2110 protected String _dockIconPath;
2111 protected boolean _strictComments;
2112 protected boolean _windebug;
2113 protected boolean _allowOffline;
2114 protected int _maxConcDownloads;
2116 protected String _trackingURL;
2117 protected Set<Integer> _trackingPcts;
2118 protected String _trackingCookieName;
2119 protected String _trackingCookieProperty;
2120 protected String _trackingURLSuffix;
2121 protected String _trackingGAHash;
2122 protected long _trackingStart;
2123 protected int _trackingId;
2125 protected String _javaVersionProp = "java.version";
2126 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
2127 protected long _javaMinVersion, _javaMaxVersion;
2128 protected boolean _javaExactVersionRequired;
2129 protected String _javaLocation;
2131 protected List<Resource> _codes = new ArrayList<>();
2132 protected List<Resource> _resources = new ArrayList<>();
2134 protected boolean _useCodeCache;
2135 protected int _codeCacheRetentionDays;
2137 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
2138 protected Map<String,Boolean> _auxactive = new HashMap<>();
2140 protected List<String> _jvmargs = new ArrayList<>();
2141 protected List<String> _appargs = new ArrayList<>();
2143 protected String[] _optimumJvmArgs;
2145 protected List<String> _txtJvmArgs = new ArrayList<>();
2147 /** If a warning has been issued about not being able to set modtimes. */
2148 protected boolean _warnedAboutSetLastModified;
2150 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
2151 protected FileLock _lock;
2153 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
2154 protected FileChannel _lockChannel;
2156 protected Random _rando = new Random();
2158 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
2160 protected static final String ENV_VAR_PREFIX = "%ENV.";
2161 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
2163 protected static File _locatorFile;
2164 protected static List<File> _startupFiles = new ArrayList<>();
2165 protected static String _jalviewUri;
2166 public static final String LOCATOR_FILE_EXTENSION = "jvl";
2168 private boolean _initialised = false;
2169 private Config _initialisedConfig = null;
2171 public static String i4jVersion = null;
2172 private String jvmmempc = null;
2173 private String jvmmemmax = null;