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;
13 import java.net.URISyntaxException;
15 import java.net.URLClassLoader;
16 import java.net.URLConnection;
17 import java.net.URLDecoder;
18 import java.net.URLEncoder;
19 import java.nio.channels.FileChannel;
20 import java.nio.channels.FileLock;
21 import java.nio.channels.OverlappingFileLockException;
22 import java.security.*;
23 import java.security.cert.Certificate;
25 import java.util.concurrent.*;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28 import java.util.zip.GZIPInputStream;
30 import jalview.bin.MemorySetting;
31 import com.install4j.api.launcher.Variables;
33 import com.threerings.getdown.util.*;
34 // avoid ambiguity with java.util.Base64 which we can't use as it's 1.8+
35 import com.threerings.getdown.util.Base64;
37 import com.threerings.getdown.data.EnvConfig;
38 import com.threerings.getdown.data.EnvConfig.Note;
40 import static com.threerings.getdown.Log.log;
41 import static java.nio.charset.StandardCharsets.UTF_8;
44 * Parses and provide access to the information contained in the <code>getdown.txt</code>
47 public class Application
49 /** The name of our configuration file. */
50 public static final String CONFIG_FILE = "getdown.txt";
52 /** Dir where a backup config file might reside */
53 public static final String BACKUP_CONFIG_DIR = "install";
55 /** The name of our target version file. */
56 public static final String VERSION_FILE = "version.txt";
58 /** System properties that are prefixed with this string will be passed through to our
59 * application (minus this prefix). */
60 public static final String PROP_PASSTHROUGH_PREFIX = "app.";
62 /** Suffix used for control file signatures. */
63 public static final String SIGNATURE_SUFFIX = ".sig";
65 /** A special classname that means 'use -jar code.jar' instead of a classname. */
66 public static final String MANIFEST_CLASS = "manifest";
68 /** Used to communicate information about the UI displayed when updating the application. */
69 public static final class UpdateInterface
72 * The major steps involved in updating, along with some arbitrary percentages
73 * assigned to them, to mark global progress.
79 //VERIFY_METADATA(15, 65, 95),
80 VERIFY_METADATA(15, 45, 90),
83 //VERIFY_RESOURCES(70, 97),
84 VERIFY_RESOURCES(40, 90),
85 //REDOWNLOAD_RESOURCES(90),
86 REDOWNLOAD_RESOURCES(80),
92 /** What is the final percent value for this step? */
93 public final List<Integer> defaultPercents;
95 /** Enum constructor. */
96 Step (int... percents)
98 this.defaultPercents = intsToList(percents);
102 /** The human readable name of this application. */
103 public final String name;
105 /** A background color, just in case. */
106 public final int background;
108 /** Background image specifiers for `RotatingBackgrounds`. */
109 public final List<String> rotatingBackgrounds;
111 /** The error background image for `RotatingBackgrounds`. */
112 public final String errorBackground;
114 /** The paths (relative to the appdir) of images for the window icon. */
115 public final List<String> iconImages;
117 /** The path (relative to the appdir) to a single background image to appear first. */
118 public final String instantBackgroundImage;
120 /** The path (relative to the appdir) to a single background image. */
121 public final String backgroundImage;
123 /** The path (relative to the appdir) to the progress bar image. */
124 public final String progressImage;
126 /** The dimensions of the progress bar. */
127 public final Rectangle progress;
129 /** The color of the progress text. */
130 public final int progressText;
132 /** The color of the progress bar. */
133 public final int progressBar;
135 /** The dimensions of the status display. */
136 public final Rectangle status;
138 /** The color of the status text. */
139 public final int statusText;
141 /** The color of the text shadow. */
142 public final int textShadow;
144 /** Where to point the user for help with install errors. */
145 public final String installError;
147 /** The dimensions of the patch notes button. */
148 public final Rectangle patchNotes;
150 /** The patch notes URL. */
151 public final String patchNotesUrl;
153 /** Whether window decorations are hidden for the UI. */
154 public final boolean hideDecorations;
156 /** Whether progress text should be hidden or not. */
157 public final boolean hideProgressText;
159 /** Whether the splash screen should update non-asynchronously before being shown. */
160 public final boolean progressSync;
162 /** Whether the splash screen should update non-asynchronously after being shown. */
163 public final boolean progressSyncAfterShown;
165 /** Whether the splash screen should retain focus. */
166 public final boolean keepOnTop;
168 /** Whether to display the appbase. */
169 public final boolean displayAppbase;
171 /** Whether to display the version. */
172 public final boolean displayVersion;
174 /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
175 * flashing up on the screen and immediately disappearing, which can be confusing to the
177 public final int minShowSeconds;
179 /** The global percentages for each step. A step may have more than one, and
180 * the lowest reasonable one is used if a step is revisited. */
181 public final Map<Step, List<Integer>> stepPercentages;
183 /** Generates a string representation of this instance. */
185 public String toString ()
187 return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage + ", instant_bg=" + instantBackgroundImage +
188 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
189 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
190 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
191 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
192 ", hideProgressText=" + hideProgressText + ", keepOnTop=" + keepOnTop + ", progressSync=" + progressSync +
193 ", progressSyncAfterShown=" + progressSyncAfterShown + ", minShow=" + minShowSeconds +
194 ", displayAppbase=" + displayAppbase + ", displayVersion=" + displayVersion + "]";
197 public UpdateInterface (Config config)
199 this.name = config.getString("ui.name");
200 this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
201 this.progressText = config.getColor("ui.progress_text", Color.BLACK);
202 this.hideProgressText = config.getBoolean("ui.hide_progress_text");
203 this.progressSync = config.getBoolean("ui.progress_sync_before_shown");
204 this.progressSyncAfterShown = config.getBoolean("ui.progress_sync_after_shown");
205 this.keepOnTop = config.getBoolean("ui.keep_on_top");
206 this.displayAppbase = config.getBoolean("ui.display_appbase");
207 this.displayVersion = config.getBoolean("ui.display_version");
208 this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
209 this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
210 this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
211 this.statusText = config.getColor("ui.status_text", Color.BLACK);
212 this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
213 this.hideDecorations = config.getBoolean("ui.hide_decorations");
214 this.backgroundImage = config.getString("ui.background_image");
215 this.instantBackgroundImage = config.getString("ui.instant_background_image");
216 // default to black or white bg color, depending on the brightness of the progressText
217 int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
218 Color.BLACK : Color.WHITE;
219 this.background = config.getColor("ui.background", defaultBackground);
220 this.progressImage = config.getString("ui.progress_image");
221 this.rotatingBackgrounds = stringsToList(
222 config.getMultiValue("ui.rotating_background"));
223 this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
224 this.errorBackground = config.getString("ui.error_background");
226 // On an installation error, where do we point the user.
227 String installError = config.getUrl("ui.install_error", null);
228 this.installError = (installError == null) ?
229 "m.default_install_error" : MessageUtil.taint(installError);
231 // the patch notes bits
232 this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
233 this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
235 // step progress percentage (defaults and then customized values)
236 EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
237 for (Step step : Step.values()) {
238 stepPercentages.put(step, step.defaultPercents);
240 for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
241 String spec = config.getString("ui.percents." + step.name());
244 stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
245 } catch (Exception e) {
246 log.warning("Failed to parse percentages for " + step + ": " + spec);
250 this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
255 * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
256 * take network actions.
258 public static interface StatusDisplay
260 /** Requests that the specified status message be displayed. */
261 public void updateStatus (String message);
265 * Contains metadata for an auxiliary resource group.
267 public static class AuxGroup {
268 public final String name;
269 public final List<Resource> codes;
270 public final List<Resource> rsrcs;
272 public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
274 this.codes = Collections.unmodifiableList(codes);
275 this.rsrcs = Collections.unmodifiableList(rsrcs);
279 /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
280 * the application instance. Yes this is a public mutable field, no I'm not going to create a
281 * getter and setter just to pretend like that's not the case. */
282 public Proxy proxy = Proxy.NO_PROXY;
285 * Creates an application instance which records the location of the <code>getdown.txt</code>
286 * configuration file from the supplied application directory.
289 public Application (EnvConfig envc) {
291 _config = getLocalPath(envc.appDir, CONFIG_FILE);
292 _backupConfig = getLocalPath(envc.appDir, BACKUP_CONFIG_DIR+File.separator+CONFIG_FILE);
296 * Returns the configured application directory.
298 public File getAppDir () {
303 * Returns whether the application should cache code resources prior to launching the
306 public boolean useCodeCache ()
308 return _useCodeCache;
312 * Returns the number of days a cached code resource is allowed to stay unused before it
313 * becomes eligible for deletion.
315 public int getCodeCacheRetentionDays ()
317 return _codeCacheRetentionDays;
321 * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
322 * app files from its hosting server.
324 public int maxConcurrentDownloads () {
325 return _maxConcDownloads;
329 * Returns a resource that refers to the application configuration file itself.
331 public Resource getConfigResource ()
334 return createResource(CONFIG_FILE, Resource.NORMAL);
335 } catch (Exception e) {
336 throw new RuntimeException("Invalid appbase '" + _vappbase + "'.", e);
341 * Returns a list of the code {@link Resource} objects used by this application.
343 public List<Resource> getCodeResources ()
349 * Returns a list of the non-code {@link Resource} objects used by this application.
351 public List<Resource> getResources ()
357 * Returns the digest of the given {@code resource}.
359 public String getDigest (Resource resource)
361 return _digest.getDigest(resource);
365 * Returns a list of all the active {@link Resource} objects used by this application (code and
368 public List<Resource> getAllActiveResources ()
370 List<Resource> allResources = new ArrayList<>();
371 allResources.addAll(getActiveCodeResources());
372 allResources.addAll(getActiveResources());
377 * Returns the auxiliary resource group with the specified name, or null.
379 public AuxGroup getAuxGroup (String name)
381 return _auxgroups.get(name);
385 * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
386 * resource group is a collection of resource files that are not downloaded unless a group
387 * token file is present in the application directory.
389 public Iterable<AuxGroup> getAuxGroups ()
391 return _auxgroups.values();
395 * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
396 * groups should be ignored, activated groups should be downloaded and patched along with the
399 public boolean isAuxGroupActive (String auxgroup)
401 Boolean active = _auxactive.get(auxgroup);
402 if (active == null) {
403 // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
405 active = getLocalPath(auxgroup + ".dat").exists();
406 _auxactive.put(auxgroup, active);
412 * Returns all main code resources and all code resources from active auxiliary resource groups.
414 public List<Resource> getActiveCodeResources ()
416 ArrayList<Resource> codes = new ArrayList<>();
417 codes.addAll(getCodeResources());
418 for (AuxGroup aux : getAuxGroups()) {
419 if (isAuxGroupActive(aux.name)) {
420 codes.addAll(aux.codes);
427 * Returns all resources indicated to contain native library files (.dll, .so, etc.).
429 public List<Resource> getNativeResources ()
431 List<Resource> natives = new ArrayList<>();
432 for (Resource resource: _resources) {
433 if (resource.isNative()) {
434 natives.add(resource);
441 * Returns all non-code resources and all resources from active auxiliary resource groups.
443 public List<Resource> getActiveResources ()
445 ArrayList<Resource> rsrcs = new ArrayList<>();
446 rsrcs.addAll(getResources());
447 for (AuxGroup aux : getAuxGroups()) {
448 if (isAuxGroupActive(aux.name)) {
449 rsrcs.addAll(aux.rsrcs);
456 * Returns a resource that can be used to download a patch file that will bring this
457 * application from its current version to the target version.
459 * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
460 * for the main application patch resource.
462 public Resource getPatchResource (String auxgroup)
464 if (_targetVersion <= _version) {
465 log.warning("Requested patch resource for up-to-date or non-versioned application",
466 "cvers", _version, "tvers", _targetVersion);
470 String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
471 String pfile = "patch" + infix + _version + ".dat";
473 URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
474 return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
475 } catch (Exception e) {
476 log.warning("Failed to create patch resource path",
477 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
483 * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
484 * place of the installed VM (in the case where the VM that launched Getdown does not meet the
485 * application's version requirements) or null if no VM is available for this platform.
487 public Resource getJavaVMResource ()
489 if (StringUtil.isBlank(_javaLocation)) {
493 String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
494 String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
495 log.info("vmfile is '"+vmfile+"'");
496 System.out.println("vmfile is '"+vmfile+"'");
498 URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
499 log.info("Attempting to fetch jvm at "+remote.toString());
500 System.out.println("Attempting to fetch jvm at "+remote.toString());
501 return new Resource(vmfile, remote, getLocalPath(vmfile),
502 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
503 } catch (Exception e) {
504 log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
505 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
506 System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
507 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
513 * Returns a resource that can be used to download an archive containing all files belonging to
516 public Resource getFullResource ()
518 String file = "full";
520 URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
521 return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
522 } catch (Exception e) {
523 log.warning("Failed to create full resource path",
524 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
530 * Returns the URL to use to report an initial download event. Returns null if no tracking
531 * start URL was configured for this application.
533 * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
535 public URL getTrackingURL (String event)
538 String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
539 String ga = getGATrackingCode();
540 return _trackingURL == null ? null :
541 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
542 } catch (MalformedURLException mue) {
543 log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
549 * Returns the URL to request to report that we have reached the specified percentage of our
550 * initial download. Returns null if no tracking request was configured for the specified
553 public URL getTrackingProgressURL (int percent)
555 if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
558 return getTrackingURL("pct" + percent);
562 * Returns the name of our tracking cookie or null if it was not set.
564 public String getTrackingCookieName ()
566 return _trackingCookieName;
570 * Returns the name of our tracking cookie system property or null if it was not set.
572 public String getTrackingCookieProperty ()
574 return _trackingCookieProperty;
578 * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
579 * for operation. The application base URL will be parsed first so that if there are errors
580 * discovered later, the caller can use the application base to download a new {@code
581 * getdown.txt} file and try again.
583 * @return a {@code Config} instance that contains information from the config file.
585 * @exception IOException thrown if there is an error reading the file or an error encountered
586 * during its parsing.
588 public Config init (boolean checkPlatform)
591 if (_initialised && _initialisedConfig != null)
593 return _initialisedConfig;
597 Application.i4jVersion = com.install4j.api.launcher.Variables.getCompilerVariable("sys.install4jVersion");
598 } catch (IOException e)
600 System.err.println("install4j version not available");
601 } catch (NoClassDefFoundError e)
603 log.warning("Starting without install4j classes");
604 } catch (Throwable t)
606 System.err.println("install4j not available");
610 Config config = null;
611 File cfgfile = _config;
612 Config.ParseOpts opts = Config.createOpts(checkPlatform);
614 // if we have a configuration file, read the data from it
615 if (cfgfile.exists()) {
616 config = Config.parseConfig(_config, opts);
618 // otherwise, try reading data from our backup config file; thanks to funny windows
619 // bullshit, we have to do this backup file fiddling in case we got screwed while
620 // updating getdown.txt during normal operation
621 else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
622 config = Config.parseConfig(cfgfile, opts);
624 // otherwise, issue a warning that we found no getdown file
626 log.info("Found no getdown.txt file", "appdir", getAppDir());
628 } catch (Exception e) {
629 log.warning("Failure reading config file", "file", _config, e);
631 if (config == null || config.getString("appbase") == null || config.getString("appbase").isEmpty()) {
633 Config backupConfig = Config.parseConfig(_backupConfig, opts);
634 config = backupConfig;
635 log.warning("Using backup config file", "appdir", getAppDir(), "backupConfig", _backupConfig.getAbsoluteFile());
636 } catch (Exception e) {
637 log.warning("Failure reading backup config file", "file", _backupConfig, e);
641 // see if there's an override config from locator file
642 Config locatorConfig = createLocatorConfig(opts);
644 // merge the locator file config into config (or replace config with)
645 if (locatorConfig != null) {
646 if (config == null || locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_replace")) {
647 config = locatorConfig;
649 config.mergeConfig(locatorConfig, locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_merge"));
653 // if we failed to read our config file, check for an appbase specified via a system
654 // property; we can use that to bootstrap ourselves back into operation
655 if (config == null) {
656 String appbase = _envc.appBase;
657 log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
658 Map<String, Object> cdata = new HashMap<>();
659 cdata.put("appbase", appbase);
660 config = new Config(cdata);
663 // first determine our application base, this way if anything goes wrong later in the
664 // process, our caller can use the appbase to download a new configuration file
665 _appbase = config.getString("appbase");
667 // see if locatorConfig override
668 if (locatorConfig != null && !StringUtil.isBlank(locatorConfig.getString("appbase"))) {
669 _appbase = locatorConfig.getString("appbase");
672 if (_appbase == null) {
673 throw new RuntimeException("m.missing_appbase");
676 // check if we're overriding the domain in the appbase
677 _appbase = SysProps.overrideAppbase(_appbase);
679 // make sure there's a trailing slash
680 if (!_appbase.endsWith("/")) {
681 _appbase = _appbase + "/";
684 // extract our version information
685 _version = config.getLong("version", -1L);
687 // if we are a versioned deployment, create a versioned appbase
689 _vappbase = createVAppBase(_version);
690 } catch (MalformedURLException mue) {
691 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
692 throw (IOException) new IOException(err).initCause(mue);
695 // check for a latest config URL
696 String latest = config.getString("latest");
697 if (latest != null) {
698 if (latest.startsWith(_appbase)) {
699 latest = _appbase + latest.substring(_appbase.length());
701 latest = SysProps.replaceDomain(latest);
704 _latest = HostWhitelist.verify(new URL(latest));
705 } catch (MalformedURLException mue) {
706 log.warning("Invalid URL for latest attribute.", mue);
710 String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
712 // determine our application class name (use app-specific class _if_ one is provided)
713 _class = config.getString("class");
714 if (appPrefix.length() > 0) {
715 _class = config.getString(appPrefix + "class", _class);
717 if (_class == null) {
718 throw new IOException("m.missing_class");
721 // determine whether we want strict comments
722 _strictComments = config.getBoolean("strict_comments");
724 // check to see if we're using a custom java.version property and regex
725 _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
726 _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
728 // check to see if we require a particular JVM version and have a supplied JVM
729 _javaMinVersion = config.getLong("java_version", _javaMinVersion);
730 // we support java_min_version as an alias of java_version; it better expresses the check
731 // that's going on and better mirrors java_max_version
732 _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
733 // check to see if we require a particular max JVM version and have a supplied JVM
734 _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
735 // check to see if we require a particular JVM version and have a supplied JVM
736 _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
738 // this is a little weird, but when we're run from the digester, we see a String[] which
739 // contains java locations for all platforms which we can't grok, but the digester doesn't
740 // need to know about that; when we're run in a real application there will be only one!
741 Object javaloc = config.getRaw("java_location");
742 if (javaloc instanceof String) {
743 _javaLocation = (String)javaloc;
746 // determine whether we have any tracking configuration
747 _trackingURL = config.getString("tracking_url");
749 // check for tracking progress percent configuration
750 String trackPcts = config.getString("tracking_percents");
751 if (!StringUtil.isBlank(trackPcts)) {
752 _trackingPcts = new HashSet<>();
753 for (int pct : StringUtil.parseIntArray(trackPcts)) {
754 _trackingPcts.add(pct);
756 } else if (!StringUtil.isBlank(_trackingURL)) {
757 _trackingPcts = new HashSet<>();
758 _trackingPcts.add(50);
761 // Check for tracking cookie configuration
762 _trackingCookieName = config.getString("tracking_cookie_name");
763 _trackingCookieProperty = config.getString("tracking_cookie_property");
765 // Some app may need an extra suffix added to the tracking URL
766 _trackingURLSuffix = config.getString("tracking_url_suffix");
768 // Some app may need to generate google analytics code
769 _trackingGAHash = config.getString("tracking_ga_hash");
771 // clear our arrays as we may be reinitializing
779 // parse our code resources
780 if (config.getMultiValue("code") == null &&
781 config.getMultiValue("ucode") == null) {
782 throw new IOException("m.missing_code");
784 parseResources(config, "code", Resource.NORMAL, _codes);
785 parseResources(config, "ucode", Resource.UNPACK, _codes);
787 // parse our non-code resources
788 parseResources(config, "resource", Resource.NORMAL, _resources);
789 parseResources(config, "uresource", Resource.UNPACK, _resources);
790 parseResources(config, "xresource", Resource.EXEC, _resources);
791 parseResources(config, "presource", Resource.PRELOAD, _resources);
792 parseResources(config, "nresource", Resource.NATIVE, _resources);
794 // parse our auxiliary resource groups
795 for (String auxgroup : config.getList("auxgroups")) {
796 ArrayList<Resource> codes = new ArrayList<>();
797 parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
798 parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
799 ArrayList<Resource> rsrcs = new ArrayList<>();
800 parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
801 parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
802 parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
803 parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
804 parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
805 _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
808 // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
809 String[] jvmargs = config.getMultiValue("jvmarg");
810 addAll(jvmargs, _jvmargs);
811 if (appPrefix.length() > 0) {
812 jvmargs = config.getMultiValue(appPrefix + "jvmarg");
813 addAll(jvmargs, _jvmargs);
816 // see if a percentage of physical memory, or max heap size options exist
817 jvmmempc = config.getString("jvmmempc", null);
818 jvmmemmax = config.getString("jvmmemmax", null);
819 // app_id prefixed setting overrides
820 if (appPrefix.length() > 0) {
821 jvmmempc = config.getString(appPrefix + "jvmmempc", jvmmempc);
822 jvmmemmax = config.getString(appPrefix + "jvmmemmax", jvmmemmax);
825 // get the set of optimum JVM arguments
826 _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
828 // transfer our application arguments
829 String[] appargs = config.getMultiValue(appPrefix + "apparg");
830 addAll(appargs, _appargs);
832 // add the launch specific application arguments
833 _appargs.addAll(_envc.appArgs);
835 // look for custom arguments
836 fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
838 // determine whether we want to allow offline operation (defaults to false)
839 _allowOffline = config.getBoolean("allow_offline");
841 // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
842 // obtain a thread dump of the running JVM
843 _windebug = getLocalPath("debug.txt").exists();
845 // whether to cache code resources and launch from cache
846 _useCodeCache = config.getBoolean("use_code_cache");
847 _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
849 // maximum simultaneous downloads
850 _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
851 SysProps.threadPoolSize()));
853 // extract some info used to configure our child process on macOS
854 _dockName = config.getString("ui.name");
855 _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
858 _initialisedConfig = config;
863 * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
865 protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
867 File pairFile = getLocalPath(pairLocation);
868 if (pairFile.exists()) {
870 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
871 for (String[] pair : args) {
872 if (pair[1].length() == 0) {
873 collector.add(pair[0]);
875 collector.add(pair[0] + "=" + pair[1]);
878 } catch (Throwable t) {
879 log.warning("Failed to parse '" + pairFile + "': " + t);
885 * Returns a URL from which the specified path can be fetched. Our application base URL is
886 * properly versioned and combined with the supplied path.
888 public URL getRemoteURL (String path)
889 throws MalformedURLException
891 return new URL(_vappbase, encodePath(path));
895 * Returns the local path to the specified resource.
897 public File getLocalPath (String path)
899 return getLocalPath(getAppDir(), path);
903 * Returns true if we either have no version requirement, are running in a JVM that meets our
904 * version requirements or have what appears to be a version of the JVM that meets our
907 public boolean haveValidJavaVersion ()
909 // if we're doing no version checking, then yay!
910 if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
913 // parse the version out of the java.version (or custom) system property
914 long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
916 log.info("Checking Java version", "current", version,
917 "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
919 // if we have an unpacked VM, check the 'release' file for its version
920 Resource vmjar = getJavaVMResource();
921 if (vmjar != null && vmjar.isMarkedValid()) {
922 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
923 File relfile = new File(vmdir, "release");
924 if (!relfile.exists()) {
925 log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
929 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
931 log.warning("Unable to read version from 'release' file. Assuming valid.");
936 log.info("Checking version of unpacked JVM [vers=" + version + "].");
939 if (_javaExactVersionRequired) {
940 if (version == _javaMinVersion) return true;
942 log.warning("An exact Java VM version is required.", "current", version,
943 "required", _javaMinVersion);
948 boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
949 boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
950 return minVersionOK && maxVersionOK;
952 } catch (RuntimeException re) {
953 // if we can't parse the java version we're in weird land and should probably just try
954 // our luck with what we've got rather than try to download a new jvm
955 log.warning("Unable to parse VM version, hoping for the best",
956 "error", re, "needed", _javaMinVersion);
962 * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
963 * whether the launch is successful and, if necessary, trying again without the optimum
966 public boolean hasOptimumJvmArgs ()
968 return _optimumJvmArgs != null;
972 * Returns true if the app should attempt to run even if we have no Internet connection.
974 public boolean allowOffline ()
976 return _allowOffline;
980 * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
981 * previous call to {@link #init}.
983 public void attemptRecovery (StatusDisplay status)
986 status.updateStatus("m.updating_metadata");
987 downloadConfigFile();
991 * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
992 * those for the target version of our application.
994 public void updateMetadata ()
998 // update our versioned application base with the target version
999 _vappbase = createVAppBase(_targetVersion);
1000 } catch (MalformedURLException mue) {
1001 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
1002 throw (IOException) new IOException(err).initCause(mue);
1006 // now re-download our control files; we download the digest first so that if it fails,
1007 // our config file will still reference the old version and re-running the updater will
1008 // start the whole process over again
1009 downloadDigestFiles();
1010 downloadConfigFile();
1012 } catch (IOException ex) {
1013 // if we are allowing offline execution, we want to allow the application to run in its
1014 // current form rather than aborting the entire process; to do this, we delete the
1015 // version.txt file and "trick" Getdown into thinking that it just needs to validate
1016 // the application as is; next time the app runs when connected to the internet, it
1017 // will have to rediscover that it needs updating and reattempt to update itself
1018 if (_allowOffline) {
1019 log.warning("Failed to update digest files. Attempting offline operaton.", ex);
1020 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
1021 log.warning("Deleting version.txt failed. This probably isn't going to work.");
1030 * Invokes the process associated with this application definition.
1032 * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
1035 public Process createProcess (boolean optimum)
1038 ArrayList<String> args = new ArrayList<>();
1040 // reconstruct the path to the JVM
1041 args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
1043 // check whether we're using -jar mode or -classpath mode
1044 boolean dashJarMode = MANIFEST_CLASS.equals(_class);
1046 // add the -classpath arguments if we're not in -jar mode
1047 ClassPath classPath = PathBuilder.buildClassPath(this);
1049 args.add("-classpath");
1050 args.add(classPath.asArgumentString());
1053 // we love our Mac users, so we do nice things to preserve our application identity
1054 if (LaunchUtil.isMacOS()) {
1055 args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1056 args.add("-Xdock:name=" + _dockName);
1059 // pass along our proxy settings
1061 if ((proxyHost = System.getProperty("http.proxyHost")) != null) {
1062 args.add("-Dhttp.proxyHost=" + proxyHost);
1063 args.add("-Dhttp.proxyPort=" + System.getProperty("http.proxyPort"));
1064 args.add("-Dhttps.proxyHost=" + proxyHost);
1065 args.add("-Dhttps.proxyPort=" + System.getProperty("http.proxyPort"));
1068 // add the marker indicating the app is running in getdown
1069 args.add("-D" + Properties.GETDOWN + "=true");
1070 args.add("-Dsys.install4jVersion=" + Application.i4jVersion);
1071 args.add("-Dinstaller_template_version=" + System.getProperty("installer_template_version"));
1072 args.add("-Dlauncher_version=" + Build.version());
1074 // set the native library path if we have native resources
1075 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1076 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1077 if (javaLibPath != null) {
1078 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1081 // pass along any pass-through arguments
1082 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1083 String key = (String)entry.getKey();
1084 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1085 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1086 args.add("-D" + key + "=" + entry.getValue());
1090 // test for jalview/s URL
1091 if (_appargs.size() > 0) {
1092 String uri = _appargs.get(0);
1094 log.info("TRYING TO PARSE URL '"+uri+"'");
1095 URI jalviewUri = new URI(uri);
1096 if (jalviewUri.getScheme().equals("jalview") || jalviewUri.getScheme().equals("jalviews")) {
1097 boolean https = jalviewUri.getScheme().equals("jalviews");
1098 String host = jalviewUri.getHost();
1099 int port = jalviewUri.getPort();
1100 String file = jalviewUri.getPath();
1101 String ref = jalviewUri.getFragment();
1102 String query = jalviewUri.getQuery();
1105 _appargs.add("-open");
1106 if (host != null && host.length() > 0) {
1107 URL newUrl = new URL(
1108 (https?"https":"http")
1111 + (port > -1? String.valueOf(port) : "")
1112 + jalviewUri.getRawPath()
1113 + (query != null && query.length() > 0 ? "?" + jalviewUri.getRawQuery() : "")
1115 _appargs.add(newUrl.toString());
1120 if (ref != null && ref.length() > 0) {
1121 String[] refArgs = ref.split("&");
1122 for (String refArg : refArgs) {
1123 if (refArg.startsWith("jvmmempc=")) {
1124 jvmmempc = refArg.substring(9);
1127 if (refArg.startsWith("jvmmemmax=")) {
1128 jvmmemmax = refArg.substring(10);
1131 _appargs.add(URLDecoder.decode(refArg, "UTF-8"));
1136 } catch (URISyntaxException e) {
1137 log.error("Malformed jalview URI", uri);
1141 for (String argString: _appargs) {
1142 if (argString.startsWith("-jvmmempc=")) {
1143 jvmmempc = argString.substring(10);
1146 if (argString.startsWith("-jvmmemmax=")) {
1147 jvmmemmax = argString.substring(11);
1152 // add the memory setting from jvmmempc and jvmmemmax
1153 long maxMemLong = -1;
1154 maxMemLong = MemorySetting.getMemorySetting(jvmmemmax, jvmmempc);
1157 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
1158 // remove other max heap size arg
1159 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
1160 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
1165 addAll(maxMemHeapArg, _jvmargs);
1168 // add the JVM arguments
1169 for (String string : _jvmargs) {
1170 args.add(processArg(string));
1173 // add the optimum arguments if requested and available
1174 if (optimum && _optimumJvmArgs != null) {
1175 for (String string : _optimumJvmArgs) {
1176 args.add(processArg(string));
1180 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1181 for (String string : _txtJvmArgs) {
1182 args.add(processArg(string));
1185 // if we're in -jar mode add those arguments, otherwise add the app class name
1188 args.add(classPath.asArgumentString());
1193 // almost finally check the startup file arguments
1194 for (File f : _startupFiles) {
1195 _appargs.add(f.getAbsolutePath());
1196 break; // Only add one file to open
1199 // check if one arg with recognised extension
1200 if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1201 String filename = _appargs.get(0);
1203 int j = filename.lastIndexOf('.');
1205 ext = filename.substring(j+1);
1207 if (ext != null && LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase())) {
1208 // this file extension should have been dealt with in Getdown class
1210 _appargs.add(0, "-open");
1214 // finally add the application arguments
1215 for (String string : _appargs) {
1216 args.add(processArg(string));
1219 String[] envp = createEnvironment();
1220 String[] sargs = args.toArray(new String[args.size()]);
1221 log.info("Running " + StringUtil.join(sargs, "\n "));
1223 return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1227 * If the application provided environment variables, combine those with the current
1228 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1229 * If the application didn't provide any environment variables, null is returned to just use
1230 * the existing environment.
1232 protected String[] createEnvironment ()
1234 List<String> envvar = new ArrayList<>();
1235 fillAssignmentListFromPairs("env.txt", envvar);
1236 if (envvar.isEmpty()) {
1237 log.info("Didn't find any custom environment variables, not setting any.");
1241 List<String> envAssignments = new ArrayList<>();
1242 for (String assignment : envvar) {
1243 envAssignments.add(processArg(assignment));
1245 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1246 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1248 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1249 log.info("Environment " + StringUtil.join(envp, "\n "));
1254 * Runs this application directly in the current VM.
1256 public void invokeDirect () throws IOException
1258 ClassPath classPath = PathBuilder.buildClassPath(this);
1259 URL[] jarUrls = classPath.asUrls();
1261 // create custom class loader
1262 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1263 @Override protected PermissionCollection getPermissions (CodeSource code) {
1264 Permissions perms = new Permissions();
1265 perms.add(new AllPermission());
1269 Thread.currentThread().setContextClassLoader(loader);
1271 log.info("Configured URL class loader:");
1272 for (URL url : jarUrls) log.info(" " + url);
1274 // configure any system properties that we can
1275 for (String jvmarg : _jvmargs) {
1276 if (jvmarg.startsWith("-D")) {
1277 jvmarg = processArg(jvmarg.substring(2));
1278 int eqidx = jvmarg.indexOf("=");
1280 log.warning("Bogus system property: '" + jvmarg + "'?");
1282 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1287 // pass along any pass-through arguments
1288 Map<String, String> passProps = new HashMap<>();
1289 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1290 String key = (String)entry.getKey();
1291 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1292 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1293 passProps.put(key, (String)entry.getValue());
1296 // we can't set these in the above loop lest we get a ConcurrentModificationException
1297 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1298 System.setProperty(entry.getKey(), entry.getValue());
1301 // prepare our app arguments
1302 String[] args = new String[_appargs.size()];
1303 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1306 log.info("Loading " + _class);
1307 Class<?> appclass = loader.loadClass(_class);
1308 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1309 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1310 main.invoke(null, new Object[] { args });
1311 } catch (Exception e) {
1312 log.warning("Failure invoking app main", e);
1316 /** Replaces the application directory and version in any argument. */
1317 protected String processArg (String arg)
1319 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1320 arg = arg.replace("%VERSION%", String.valueOf(_version));
1322 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1323 // from the environment
1324 if (arg.contains(ENV_VAR_PREFIX)) {
1325 StringBuffer sb = new StringBuffer();
1326 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1327 while (matcher.find()) {
1328 String varName = matcher.group(1), varValue = System.getenv(varName);
1329 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1330 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1332 matcher.appendTail(sb);
1333 arg = sb.toString();
1340 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1341 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1342 * whether or not the application needs to be updated or whether we can proceed to verification
1345 * @return true if the application needs to be updated, false if it is up to date and can be
1346 * verified and executed.
1348 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1351 public boolean verifyMetadata (StatusDisplay status)
1354 log.info("Verifying application: " + _vappbase);
1355 log.info("Version: " + _version);
1356 log.info("Class: " + _class);
1358 // this will read in the contents of the digest file and validate itself
1360 _digest = new Digest(getAppDir(), _strictComments);
1361 } catch (IOException ioe) {
1362 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1365 // if we have no version, then we are running in unversioned mode so we need to download
1366 // our digest.txt file on every invocation
1367 if (_version == -1) {
1368 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1369 // resources as one or more of them have also changed
1370 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1372 status.updateStatus("m.checking");
1373 downloadDigestFiles();
1374 _digest = new Digest(getAppDir(), _strictComments);
1375 if (!olddig.equals(_digest.getMetaDigest())) {
1376 log.info("Unversioned digest changed. Revalidating...");
1377 status.updateStatus("m.validating");
1378 clearValidationMarkers();
1380 } catch (IOException ioe) {
1381 log.warning("Failed to refresh non-versioned digest: " +
1382 ioe.getMessage() + ". Proceeding...");
1386 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1387 // redownload the digest file and give it another good college try; this time we allow
1388 // exceptions to propagate up to the caller as there is nothing else we can do
1389 if (_digest == null) {
1390 status.updateStatus("m.updating_metadata");
1391 downloadDigestFiles();
1392 _digest = new Digest(getAppDir(), _strictComments);
1395 // now verify the contents of our main config file
1396 Resource crsrc = getConfigResource();
1397 if (!_digest.validateResource(crsrc, null)) {
1398 status.updateStatus("m.updating_metadata");
1399 // attempt to redownload both of our metadata files; again we pass errors up to our
1400 // caller because there's nothing we can do to automatically recover
1401 downloadConfigFile();
1402 downloadDigestFiles();
1403 _digest = new Digest(getAppDir(), _strictComments);
1404 // revalidate everything if we end up downloading new metadata
1405 clearValidationMarkers();
1406 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1407 if (_digest.validateResource(crsrc, null)) {
1410 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1411 "Blindly forging onward.");
1415 // start by assuming we are happy with our version
1416 _targetVersion = _version;
1418 // if we are a versioned application, read in the contents of the version.txt file
1419 // and/or check the latest config URL for a newer version
1420 if (_version != -1) {
1421 File vfile = getLocalPath(VERSION_FILE);
1422 long fileVersion = VersionUtil.readVersion(vfile);
1423 if (fileVersion != -1) {
1424 _targetVersion = fileVersion;
1427 if (_latest != null) {
1428 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1429 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1430 BufferedReader bin = new BufferedReader(reader)) {
1431 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1432 if (pair[0].equals("version")) {
1433 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1434 if (fileVersion != -1 && _targetVersion > fileVersion) {
1435 // replace the file with the newest version
1436 try (FileOutputStream fos = new FileOutputStream(vfile);
1437 PrintStream out = new PrintStream(fos)) {
1438 out.println(_targetVersion);
1444 } catch (Exception e) {
1445 log.warning("Unable to retrieve version from latest config file.", e);
1450 // finally let the caller know if we need an update
1451 return _version != _targetVersion;
1455 * Verifies the code and media resources associated with this application. A list of resources
1456 * that do not exist or fail the verification process will be returned. If all resources are
1457 * ready to go, null will be returned and the application is considered ready to run.
1459 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1460 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1461 * you have to take care to get back to your UI thread.
1462 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1463 * validated" resources filled in.
1464 * @param unpacked a set to populate with unpacked resources.
1465 * @param toInstall a list into which to add resources that need to be installed.
1466 * @param toDownload a list into which to add resources that need to be downloaded.
1468 public void verifyResources (
1469 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1470 Set<Resource> toInstall, Set<Resource> toDownload)
1471 throws InterruptedException
1473 // resources are verified on background threads supplied by the thread pool, and progress
1474 // is reported by posting runnable actions to the actions queue which is processed by the
1476 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1477 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1478 final int[] completed = new int[1];
1480 long start = System.currentTimeMillis();
1482 // obtain the sizes of the resources to validate
1483 List<Resource> rsrcs = getAllActiveResources();
1484 long[] sizes = new long[rsrcs.size()];
1486 for (int ii = 0; ii < sizes.length; ii++) {
1487 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1489 final ProgressObserver fobs = obs;
1490 // as long as we forward aggregated progress updates to the UI thread, having multiple
1491 // threads update a progress aggregator is "mostly" thread-safe
1492 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1493 public void progress (final int percent) {
1494 actions.add(new Runnable() {
1495 public void run () {
1496 fobs.progress(percent);
1502 final int[] fAlreadyValid = alreadyValid;
1503 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1504 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1505 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1507 for (int ii = 0; ii < sizes.length; ii++) {
1508 final Resource rsrc = rsrcs.get(ii);
1509 final int index = ii;
1510 exec.execute(new Runnable() {
1511 public void run () {
1512 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1513 unpackedAsync, toInstallAsync, toDownloadAsync);
1514 actions.add(new Runnable() {
1515 public void run () {
1523 while (completed[0] < rsrcs.size()) {
1524 // we should be getting progress completion updates WAY more often than one every
1525 // minute, so if things freeze up for 60 seconds, abandon ship
1526 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1532 toInstall.addAll(toInstallAsync);
1533 toDownload.addAll(toDownloadAsync);
1534 unpacked.addAll(unpackedAsync);
1536 long complete = System.currentTimeMillis();
1537 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1538 "duration", (complete-start) + "ms");
1541 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1542 Set<Resource> unpacked,
1543 Set<Resource> toInstall, Set<Resource> toDownload) {
1544 if (rsrc.isMarkedValid()) {
1545 if (alreadyValid != null) {
1553 if (_digest.validateResource(rsrc, obs)) {
1554 // if the resource has a _new file, add it to to-install list
1555 if (rsrc.getLocalNew().exists()) {
1556 toInstall.add(rsrc);
1565 } catch (Exception e) {
1566 log.info("Failure verifying resource. Requesting redownload...",
1567 "rsrc", rsrc, "error", e);
1572 toDownload.add(rsrc);
1576 * Unpacks the resources that require it (we know that they're valid).
1578 * @param unpacked a set of resources to skip because they're already unpacked.
1580 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1581 throws InterruptedException
1583 List<Resource> rsrcs = getActiveResources();
1585 // remove resources that we don't want to unpack
1586 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1587 Resource rsrc = it.next();
1588 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1593 // obtain the sizes of the resources to unpack
1594 long[] sizes = new long[rsrcs.size()];
1595 for (int ii = 0; ii < sizes.length; ii++) {
1596 sizes[ii] = rsrcs.get(ii).getLocal().length();
1599 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1600 for (int ii = 0; ii < sizes.length; ii++) {
1601 Resource rsrc = rsrcs.get(ii);
1602 ProgressObserver pobs = pagg.startElement(ii);
1605 } catch (IOException ioe) {
1606 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1613 * Clears all validation marker files.
1615 public void clearValidationMarkers ()
1617 clearValidationMarkers(getAllActiveResources().iterator());
1621 * Returns the version number for the application. Should only be called after successful
1622 * return of verifyMetadata.
1624 public long getVersion ()
1630 * Creates a versioned application base URL for the specified version.
1632 protected URL createVAppBase (long version)
1633 throws MalformedURLException
1635 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1636 return HostWhitelist.verify(new URL(url));
1640 * Clears all validation marker files for the resources in the supplied iterator.
1642 protected void clearValidationMarkers (Iterator<Resource> iter)
1644 while (iter.hasNext()) {
1645 iter.next().clearMarker();
1650 * Downloads a new copy of CONFIG_FILE.
1652 protected void downloadConfigFile ()
1655 downloadControlFile(CONFIG_FILE, 0);
1659 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1660 * we're not locking at all.
1662 public synchronized boolean lockForUpdates ()
1664 if (_lock != null && _lock.isValid()) {
1668 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1669 } catch (FileNotFoundException e) {
1670 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1674 _lock = _lockChannel.tryLock();
1675 } catch (IOException e) {
1676 log.warning("Unable to create lock", "message", e.getMessage(), e);
1678 } catch (OverlappingFileLockException e) {
1679 log.warning("The lock is held elsewhere in this JVM", e);
1682 log.info("Able to lock for updates: " + (_lock != null));
1683 return _lock != null;
1687 * Release gettingdown.lock
1689 public synchronized void releaseLock ()
1691 if (_lock != null) {
1692 log.info("Releasing lock");
1695 } catch (IOException e) {
1696 log.warning("Unable to release lock", "message", e.getMessage(), e);
1699 _lockChannel.close();
1700 } catch (IOException e) {
1701 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1703 _lockChannel = null;
1709 * Downloads the digest files and validates their signature.
1710 * @throws IOException
1712 protected void downloadDigestFiles ()
1715 for (int version = 1; version <= Digest.VERSION; version++) {
1716 downloadControlFile(Digest.digestFile(version), version);
1721 * Downloads a new copy of the specified control file, optionally validating its signature.
1722 * If the download is successful, moves it over the old file on the filesystem.
1724 * <p> TODO: Switch to PKCS #7 or CMS.
1726 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1727 * should indicate the version of the digest file being validated which indicates which
1728 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1730 protected void downloadControlFile (String path, int sigVersion)
1733 File target = downloadFile(path);
1735 if (sigVersion > 0) {
1736 if (_envc.certs.isEmpty()) {
1737 log.info("No signing certs, not verifying digest.txt", "path", path);
1740 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1741 byte[] signature = null;
1742 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1743 signature = StreamUtil.toByteArray(signatureStream);
1745 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1748 byte[] buffer = new byte[8192];
1749 int length, validated = 0;
1750 for (Certificate cert : _envc.certs) {
1751 try (FileInputStream dataInput = new FileInputStream(target)) {
1752 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1753 sig.initVerify(cert);
1754 while ((length = dataInput.read(buffer)) != -1) {
1755 sig.update(buffer, 0, length);
1758 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1759 log.info("Signature does not match", "cert", cert.getPublicKey());
1762 log.info("Signature matches", "cert", cert.getPublicKey());
1766 } catch (IOException ioe) {
1767 log.warning("Failure validating signature of " + target + ": " + ioe);
1769 } catch (GeneralSecurityException gse) {
1775 // if we couldn't find a key that validates our digest, we are the hosed!
1776 if (validated == 0) {
1777 // delete the temporary digest file as we know it is invalid
1778 FileUtil.deleteHarder(target);
1779 throw new IOException("m.corrupt_digest_signature_error");
1784 // now move the temporary file over the original
1785 File original = getLocalPath(path);
1786 if (!FileUtil.renameTo(target, original)) {
1787 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1792 * Download a path to a temporary file, returning a {@link File} instance with the path
1795 protected File downloadFile (String path)
1798 File target = getLocalPath(path + "_new");
1800 URL targetURL = null;
1802 targetURL = getRemoteURL(path);
1803 } catch (Exception e) {
1804 log.warning("Requested to download invalid control file",
1805 "appbase", _vappbase, "path", path, "error", e);
1806 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1809 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1811 // stream the URL into our temporary file
1812 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1813 // we have to tell Java not to use caches here, otherwise it will cache any request for
1814 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1815 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1816 // about it; turning off caches is not a performance concern, because when Getdown asks
1817 // to download a file, it expects it to come over the wire, not from a cache
1818 uconn.setUseCaches(false);
1819 uconn.setRequestProperty("Accept-Encoding", "gzip");
1820 try (InputStream fin = uconn.getInputStream()) {
1821 String encoding = uconn.getContentEncoding();
1822 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1823 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1824 try (FileOutputStream fout = new FileOutputStream(target)) {
1825 StreamUtil.copy(fin2, fout);
1833 /** Helper function for creating {@link Resource} instances. */
1834 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1835 throws MalformedURLException
1837 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1840 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1841 protected static void addAll (String[] values, List<String> target) {
1842 if (values != null) {
1843 for (String value : values) {
1850 * Make an immutable List from the specified int array.
1852 public static List<Integer> intsToList (int[] values)
1854 List<Integer> list = new ArrayList<>(values.length);
1855 for (int val : values) {
1858 return Collections.unmodifiableList(list);
1862 * Make an immutable List from the specified String array.
1864 public static List<String> stringsToList (String[] values)
1866 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1869 /** Used to parse resources with the specified name. */
1870 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1871 List<Resource> list)
1873 String[] rsrcs = config.getMultiValue(name);
1874 if (rsrcs == null) {
1877 for (String rsrc : rsrcs) {
1879 list.add(createResource(rsrc, attrs));
1880 } catch (Exception e) {
1881 log.warning("Invalid resource '" + rsrc + "'. " + e);
1886 /** Possibly generates and returns a google analytics tracking cookie. */
1887 protected String getGATrackingCode ()
1889 if (_trackingGAHash == null) {
1892 long time = System.currentTimeMillis() / 1000;
1893 if (_trackingStart == 0) {
1894 _trackingStart = time;
1896 if (_trackingId == 0) {
1897 int low = 100000000, high = 1000000000;
1898 _trackingId = low + _rando.nextInt(high-low);
1900 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1901 cookie.append(".").append(_trackingId);
1902 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1903 cookie.append(".").append(time).append(".1%3B%2B");
1904 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1905 cookie.append(_trackingStart).append(".1.1.");
1906 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1907 int low = 1000000000, high = 2000000000;
1908 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1909 return cookie.toString();
1913 * Encodes a path for use in a URL.
1915 protected static String encodePath (String path)
1918 // we want to keep slashes because we're encoding an entire path; also we need to turn
1919 // + into %20 because web servers don't like + in paths or file names, blah
1920 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1921 } catch (UnsupportedEncodingException ue) {
1922 log.warning("Failed to URL encode " + path + ": " + ue);
1927 protected File getLocalPath (File appdir, String path)
1929 return new File(appdir, path);
1932 public static void setStartupFilesFromParameterString(String p) {
1933 // multiple files *might* be passed in as space separated quoted filenames
1935 if (!StringUtil.isBlank(p)) {
1937 // split quoted params or treat as single string array
1938 if (p.startsWith(q) && p.endsWith(q)) {
1939 // this fails if, e.g.
1940 // p=q("stupidfilename\" " "otherfilename")
1941 // let's hope no-one ever ends a filename with '" '
1942 filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1944 // single unquoted filename
1945 filenames = new String[]{p};
1948 // check for locator file. Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1949 String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
1951 !StringUtil.isBlank(locatorFilename)
1952 && locatorFilename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)
1954 setLocatorFile(locatorFilename);
1955 // remove the locator filename from the filenames array
1956 String[] otherFilenames = new String[filenames.length - 1];
1957 System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
1958 filenames = otherFilenames;
1961 for (int i = 0; i < filenames.length; i++) {
1962 String filename = filenames[i];
1963 // skip any other locator files in a multiple file list
1964 if (! filename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
1965 addStartupFile(filename);
1971 public static void setLocatorFile(String filename) {
1972 _locatorFile = new File(filename);
1975 public static void addStartupFile(String filename) {
1976 _startupFiles.add(new File(filename));
1979 private Config createLocatorConfig(Config.ParseOpts opts) {
1980 if (_locatorFile == null) {
1984 Config locatorConfig = null;
1987 Config tmpConfig = null;
1988 Map<String, Object> tmpData = new HashMap<>();
1989 if (_locatorFile.exists()) {
1990 tmpConfig = Config.parseConfig(_locatorFile, opts);
1991 // appbase is sanitised in HostWhitelist
1992 Map<String, Object> tmpConfigData = tmpConfig.getData();
1993 if (tmpConfig != null) {
1994 for (Map.Entry<String, Object> entry : tmpConfigData.entrySet()) {
1995 String key = entry.getKey();
1996 Object value = entry.getValue();
1997 String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
1998 if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
1999 tmpData.put(key, value);
2003 log.warning("Error occurred reading config file", "file", _locatorFile);
2006 log.warning("Given locator file does not exist", "file", _locatorFile);
2009 locatorConfig = new Config(tmpData);
2011 } catch (Exception e) {
2012 log.warning("Failure reading locator file", "file", _locatorFile, e);
2015 return locatorConfig;
2018 public String getAppbase() {
2022 protected final EnvConfig _envc;
2023 protected File _config;
2024 protected File _backupConfig;
2025 protected Digest _digest;
2027 protected long _version = -1;
2028 protected long _targetVersion = -1;
2029 protected String _appbase;
2030 protected URL _vappbase;
2031 protected URL _latest;
2032 protected String _class;
2033 protected String _dockName;
2034 protected String _dockIconPath;
2035 protected boolean _strictComments;
2036 protected boolean _windebug;
2037 protected boolean _allowOffline;
2038 protected int _maxConcDownloads;
2040 protected String _trackingURL;
2041 protected Set<Integer> _trackingPcts;
2042 protected String _trackingCookieName;
2043 protected String _trackingCookieProperty;
2044 protected String _trackingURLSuffix;
2045 protected String _trackingGAHash;
2046 protected long _trackingStart;
2047 protected int _trackingId;
2049 protected String _javaVersionProp = "java.version";
2050 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
2051 protected long _javaMinVersion, _javaMaxVersion;
2052 protected boolean _javaExactVersionRequired;
2053 protected String _javaLocation;
2055 protected List<Resource> _codes = new ArrayList<>();
2056 protected List<Resource> _resources = new ArrayList<>();
2058 protected boolean _useCodeCache;
2059 protected int _codeCacheRetentionDays;
2061 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
2062 protected Map<String,Boolean> _auxactive = new HashMap<>();
2064 protected List<String> _jvmargs = new ArrayList<>();
2065 protected List<String> _appargs = new ArrayList<>();
2067 protected String[] _optimumJvmArgs;
2069 protected List<String> _txtJvmArgs = new ArrayList<>();
2071 /** If a warning has been issued about not being able to set modtimes. */
2072 protected boolean _warnedAboutSetLastModified;
2074 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
2075 protected FileLock _lock;
2077 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
2078 protected FileChannel _lockChannel;
2080 protected Random _rando = new Random();
2082 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
2084 protected static final String ENV_VAR_PREFIX = "%ENV.";
2085 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
2087 protected static File _locatorFile;
2088 protected static List<File> _startupFiles = new ArrayList<>();
2089 public static final String LOCATOR_FILE_EXTENSION = "jvl";
2091 private boolean _initialised = false;
2092 private Config _initialisedConfig = null;
2094 public static String i4jVersion = null;
2095 private String jvmmempc = null;
2096 private String jvmmemmax = null;