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.URLClassLoader;
14 import java.net.URLConnection;
15 import java.net.URLEncoder;
16 import java.nio.channels.FileChannel;
17 import java.nio.channels.FileLock;
18 import java.nio.channels.OverlappingFileLockException;
19 import java.security.*;
20 import java.security.cert.Certificate;
22 import java.util.concurrent.*;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import java.util.zip.GZIPInputStream;
27 import jalview.bin.MemorySetting;
29 import com.threerings.getdown.util.*;
30 // avoid ambiguity with java.util.Base64 which we can't use as it's 1.8+
31 import com.threerings.getdown.util.Base64;
33 import com.threerings.getdown.data.EnvConfig;
34 import com.threerings.getdown.data.EnvConfig.Note;
36 import static com.threerings.getdown.Log.log;
37 import static java.nio.charset.StandardCharsets.UTF_8;
40 * Parses and provide access to the information contained in the <code>getdown.txt</code>
43 public class Application
45 /** The name of our configuration file. */
46 public static final String CONFIG_FILE = "getdown.txt";
48 /** Dir where a backup config file might reside */
49 public static final String BACKUP_CONFIG_DIR = "install";
51 /** The name of our target version file. */
52 public static final String VERSION_FILE = "version.txt";
54 /** System properties that are prefixed with this string will be passed through to our
55 * application (minus this prefix). */
56 public static final String PROP_PASSTHROUGH_PREFIX = "app.";
58 /** Suffix used for control file signatures. */
59 public static final String SIGNATURE_SUFFIX = ".sig";
61 /** A special classname that means 'use -jar code.jar' instead of a classname. */
62 public static final String MANIFEST_CLASS = "manifest";
64 /** Used to communicate information about the UI displayed when updating the application. */
65 public static final class UpdateInterface
68 * The major steps involved in updating, along with some arbitrary percentages
69 * assigned to them, to mark global progress.
75 //VERIFY_METADATA(15, 65, 95),
76 VERIFY_METADATA(15, 45, 90),
79 //VERIFY_RESOURCES(70, 97),
80 VERIFY_RESOURCES(40, 90),
81 //REDOWNLOAD_RESOURCES(90),
82 REDOWNLOAD_RESOURCES(80),
88 /** What is the final percent value for this step? */
89 public final List<Integer> defaultPercents;
91 /** Enum constructor. */
92 Step (int... percents)
94 this.defaultPercents = intsToList(percents);
98 /** The human readable name of this application. */
99 public final String name;
101 /** A background color, just in case. */
102 public final int background;
104 /** Background image specifiers for `RotatingBackgrounds`. */
105 public final List<String> rotatingBackgrounds;
107 /** The error background image for `RotatingBackgrounds`. */
108 public final String errorBackground;
110 /** The paths (relative to the appdir) of images for the window icon. */
111 public final List<String> iconImages;
113 /** The path (relative to the appdir) to a single background image to appear first. */
114 public final String instantBackgroundImage;
116 /** The path (relative to the appdir) to a single background image. */
117 public final String backgroundImage;
119 /** The path (relative to the appdir) to the progress bar image. */
120 public final String progressImage;
122 /** The dimensions of the progress bar. */
123 public final Rectangle progress;
125 /** The color of the progress text. */
126 public final int progressText;
128 /** The color of the progress bar. */
129 public final int progressBar;
131 /** The dimensions of the status display. */
132 public final Rectangle status;
134 /** The color of the status text. */
135 public final int statusText;
137 /** The color of the text shadow. */
138 public final int textShadow;
140 /** Where to point the user for help with install errors. */
141 public final String installError;
143 /** The dimensions of the patch notes button. */
144 public final Rectangle patchNotes;
146 /** The patch notes URL. */
147 public final String patchNotesUrl;
149 /** Whether window decorations are hidden for the UI. */
150 public final boolean hideDecorations;
152 /** Whether progress text should be hidden or not. */
153 public final boolean hideProgressText;
155 /** Whether the splash screen should update non-asynchronously before being shown. */
156 public final boolean progressSync;
158 /** Whether the splash screen should update non-asynchronously after being shown. */
159 public final boolean progressSyncAfterShown;
161 /** Whether the splash screen should retain focus. */
162 public final boolean keepOnTop;
164 /** Whether to display the appbase. */
165 public final boolean displayAppbase;
167 /** Whether to display the version. */
168 public final boolean displayVersion;
170 /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
171 * flashing up on the screen and immediately disappearing, which can be confusing to the
173 public final int minShowSeconds;
175 /** The global percentages for each step. A step may have more than one, and
176 * the lowest reasonable one is used if a step is revisited. */
177 public final Map<Step, List<Integer>> stepPercentages;
179 /** Generates a string representation of this instance. */
181 public String toString ()
183 return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage + ", instant_bg=" + instantBackgroundImage +
184 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
185 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
186 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
187 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
188 ", hideProgressText=" + hideProgressText + ", keepOnTop=" + keepOnTop + ", progressSync=" + progressSync +
189 ", progressSyncAfterShown=" + progressSyncAfterShown + ", minShow=" + minShowSeconds +
190 ", displayAppbase=" + displayAppbase + ", displayVersion=" + displayVersion + "]";
193 public UpdateInterface (Config config)
195 this.name = config.getString("ui.name");
196 this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
197 this.progressText = config.getColor("ui.progress_text", Color.BLACK);
198 this.hideProgressText = config.getBoolean("ui.hide_progress_text");
199 this.progressSync = config.getBoolean("ui.progress_sync_before_shown");
200 this.progressSyncAfterShown = config.getBoolean("ui.progress_sync_after_shown");
201 this.keepOnTop = config.getBoolean("ui.keep_on_top");
202 this.displayAppbase = config.getBoolean("ui.display_appbase");
203 this.displayVersion = config.getBoolean("ui.display_version");
204 this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
205 this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
206 this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
207 this.statusText = config.getColor("ui.status_text", Color.BLACK);
208 this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
209 this.hideDecorations = config.getBoolean("ui.hide_decorations");
210 this.backgroundImage = config.getString("ui.background_image");
211 this.instantBackgroundImage = config.getString("ui.instant_background_image");
212 // default to black or white bg color, depending on the brightness of the progressText
213 int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
214 Color.BLACK : Color.WHITE;
215 this.background = config.getColor("ui.background", defaultBackground);
216 this.progressImage = config.getString("ui.progress_image");
217 this.rotatingBackgrounds = stringsToList(
218 config.getMultiValue("ui.rotating_background"));
219 this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
220 this.errorBackground = config.getString("ui.error_background");
222 // On an installation error, where do we point the user.
223 String installError = config.getUrl("ui.install_error", null);
224 this.installError = (installError == null) ?
225 "m.default_install_error" : MessageUtil.taint(installError);
227 // the patch notes bits
228 this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
229 this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
231 // step progress percentage (defaults and then customized values)
232 EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
233 for (Step step : Step.values()) {
234 stepPercentages.put(step, step.defaultPercents);
236 for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
237 String spec = config.getString("ui.percents." + step.name());
240 stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
241 } catch (Exception e) {
242 log.warning("Failed to parse percentages for " + step + ": " + spec);
246 this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
251 * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
252 * take network actions.
254 public static interface StatusDisplay
256 /** Requests that the specified status message be displayed. */
257 public void updateStatus (String message);
261 * Contains metadata for an auxiliary resource group.
263 public static class AuxGroup {
264 public final String name;
265 public final List<Resource> codes;
266 public final List<Resource> rsrcs;
268 public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
270 this.codes = Collections.unmodifiableList(codes);
271 this.rsrcs = Collections.unmodifiableList(rsrcs);
275 /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
276 * the application instance. Yes this is a public mutable field, no I'm not going to create a
277 * getter and setter just to pretend like that's not the case. */
278 public Proxy proxy = Proxy.NO_PROXY;
281 * Creates an application instance which records the location of the <code>getdown.txt</code>
282 * configuration file from the supplied application directory.
285 public Application (EnvConfig envc) {
287 _config = getLocalPath(envc.appDir, CONFIG_FILE);
288 _backupConfig = getLocalPath(envc.appDir, BACKUP_CONFIG_DIR+File.separator+CONFIG_FILE);
292 * Returns the configured application directory.
294 public File getAppDir () {
299 * Returns whether the application should cache code resources prior to launching the
302 public boolean useCodeCache ()
304 return _useCodeCache;
308 * Returns the number of days a cached code resource is allowed to stay unused before it
309 * becomes eligible for deletion.
311 public int getCodeCacheRetentionDays ()
313 return _codeCacheRetentionDays;
317 * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
318 * app files from its hosting server.
320 public int maxConcurrentDownloads () {
321 return _maxConcDownloads;
325 * Returns a resource that refers to the application configuration file itself.
327 public Resource getConfigResource ()
330 return createResource(CONFIG_FILE, Resource.NORMAL);
331 } catch (Exception e) {
332 throw new RuntimeException("Invalid appbase '" + _vappbase + "'.", e);
337 * Returns a list of the code {@link Resource} objects used by this application.
339 public List<Resource> getCodeResources ()
345 * Returns a list of the non-code {@link Resource} objects used by this application.
347 public List<Resource> getResources ()
353 * Returns the digest of the given {@code resource}.
355 public String getDigest (Resource resource)
357 return _digest.getDigest(resource);
361 * Returns a list of all the active {@link Resource} objects used by this application (code and
364 public List<Resource> getAllActiveResources ()
366 List<Resource> allResources = new ArrayList<>();
367 allResources.addAll(getActiveCodeResources());
368 allResources.addAll(getActiveResources());
373 * Returns the auxiliary resource group with the specified name, or null.
375 public AuxGroup getAuxGroup (String name)
377 return _auxgroups.get(name);
381 * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
382 * resource group is a collection of resource files that are not downloaded unless a group
383 * token file is present in the application directory.
385 public Iterable<AuxGroup> getAuxGroups ()
387 return _auxgroups.values();
391 * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
392 * groups should be ignored, activated groups should be downloaded and patched along with the
395 public boolean isAuxGroupActive (String auxgroup)
397 Boolean active = _auxactive.get(auxgroup);
398 if (active == null) {
399 // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
401 active = getLocalPath(auxgroup + ".dat").exists();
402 _auxactive.put(auxgroup, active);
408 * Returns all main code resources and all code resources from active auxiliary resource groups.
410 public List<Resource> getActiveCodeResources ()
412 ArrayList<Resource> codes = new ArrayList<>();
413 codes.addAll(getCodeResources());
414 for (AuxGroup aux : getAuxGroups()) {
415 if (isAuxGroupActive(aux.name)) {
416 codes.addAll(aux.codes);
423 * Returns all resources indicated to contain native library files (.dll, .so, etc.).
425 public List<Resource> getNativeResources ()
427 List<Resource> natives = new ArrayList<>();
428 for (Resource resource: _resources) {
429 if (resource.isNative()) {
430 natives.add(resource);
437 * Returns all non-code resources and all resources from active auxiliary resource groups.
439 public List<Resource> getActiveResources ()
441 ArrayList<Resource> rsrcs = new ArrayList<>();
442 rsrcs.addAll(getResources());
443 for (AuxGroup aux : getAuxGroups()) {
444 if (isAuxGroupActive(aux.name)) {
445 rsrcs.addAll(aux.rsrcs);
452 * Returns a resource that can be used to download a patch file that will bring this
453 * application from its current version to the target version.
455 * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
456 * for the main application patch resource.
458 public Resource getPatchResource (String auxgroup)
460 if (_targetVersion <= _version) {
461 log.warning("Requested patch resource for up-to-date or non-versioned application",
462 "cvers", _version, "tvers", _targetVersion);
466 String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
467 String pfile = "patch" + infix + _version + ".dat";
469 URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
470 return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
471 } catch (Exception e) {
472 log.warning("Failed to create patch resource path",
473 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
479 * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
480 * place of the installed VM (in the case where the VM that launched Getdown does not meet the
481 * application's version requirements) or null if no VM is available for this platform.
483 public Resource getJavaVMResource ()
485 if (StringUtil.isBlank(_javaLocation)) {
489 String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
490 String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
491 log.info("vmfile is '"+vmfile+"'");
492 System.out.println("vmfile is '"+vmfile+"'");
494 URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
495 log.info("Attempting to fetch jvm at "+remote.toString());
496 System.out.println("Attempting to fetch jvm at "+remote.toString());
497 return new Resource(vmfile, remote, getLocalPath(vmfile),
498 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
499 } catch (Exception e) {
500 log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
501 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
502 System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
503 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
509 * Returns a resource that can be used to download an archive containing all files belonging to
512 public Resource getFullResource ()
514 String file = "full";
516 URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
517 return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
518 } catch (Exception e) {
519 log.warning("Failed to create full resource path",
520 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
526 * Returns the URL to use to report an initial download event. Returns null if no tracking
527 * start URL was configured for this application.
529 * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
531 public URL getTrackingURL (String event)
534 String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
535 String ga = getGATrackingCode();
536 return _trackingURL == null ? null :
537 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
538 } catch (MalformedURLException mue) {
539 log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
545 * Returns the URL to request to report that we have reached the specified percentage of our
546 * initial download. Returns null if no tracking request was configured for the specified
549 public URL getTrackingProgressURL (int percent)
551 if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
554 return getTrackingURL("pct" + percent);
558 * Returns the name of our tracking cookie or null if it was not set.
560 public String getTrackingCookieName ()
562 return _trackingCookieName;
566 * Returns the name of our tracking cookie system property or null if it was not set.
568 public String getTrackingCookieProperty ()
570 return _trackingCookieProperty;
574 * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
575 * for operation. The application base URL will be parsed first so that if there are errors
576 * discovered later, the caller can use the application base to download a new {@code
577 * getdown.txt} file and try again.
579 * @return a {@code Config} instance that contains information from the config file.
581 * @exception IOException thrown if there is an error reading the file or an error encountered
582 * during its parsing.
584 public Config init (boolean checkPlatform)
587 Config config = null;
588 File cfgfile = _config;
589 Config.ParseOpts opts = Config.createOpts(checkPlatform);
591 // if we have a configuration file, read the data from it
592 if (cfgfile.exists()) {
593 config = Config.parseConfig(_config, opts);
595 // otherwise, try reading data from our backup config file; thanks to funny windows
596 // bullshit, we have to do this backup file fiddling in case we got screwed while
597 // updating getdown.txt during normal operation
598 else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
599 config = Config.parseConfig(cfgfile, opts);
601 // otherwise, issue a warning that we found no getdown file
603 log.info("Found no getdown.txt file", "appdir", getAppDir());
605 } catch (Exception e) {
606 log.warning("Failure reading config file", "file", _config, e);
608 if (config == null || config.getString("appbase") == null || config.getString("appbase").isEmpty()) {
610 Config backupConfig = Config.parseConfig(_backupConfig, opts);
611 config = backupConfig;
612 log.warning("Using backup config file", "appdir", getAppDir(), "backupConfig", _backupConfig.getAbsoluteFile());
613 } catch (Exception e) {
614 log.warning("Failure reading backup config file", "file", _backupConfig, e);
618 // see if there's an override config from locator file
619 Config locatorConfig = createLocatorConfig(opts);
621 // merge the locator file config into config (or replace config with)
622 if (locatorConfig != null) {
623 if (config == null || locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_replace")) {
624 config = locatorConfig;
626 config.mergeConfig(locatorConfig, locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_merge"));
630 // if we failed to read our config file, check for an appbase specified via a system
631 // property; we can use that to bootstrap ourselves back into operation
632 if (config == null) {
633 String appbase = _envc.appBase;
634 log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
635 Map<String, Object> cdata = new HashMap<>();
636 cdata.put("appbase", appbase);
637 config = new Config(cdata);
640 // first determine our application base, this way if anything goes wrong later in the
641 // process, our caller can use the appbase to download a new configuration file
642 _appbase = config.getString("appbase");
644 // see if locatorConfig override
645 if (locatorConfig != null && !StringUtil.isBlank(locatorConfig.getString("appbase"))) {
646 _appbase = locatorConfig.getString("appbase");
649 if (_appbase == null) {
650 throw new RuntimeException("m.missing_appbase");
653 // check if we're overriding the domain in the appbase
654 _appbase = SysProps.overrideAppbase(_appbase);
656 // make sure there's a trailing slash
657 if (!_appbase.endsWith("/")) {
658 _appbase = _appbase + "/";
661 // extract our version information
662 _version = config.getLong("version", -1L);
664 // if we are a versioned deployment, create a versioned appbase
666 _vappbase = createVAppBase(_version);
667 } catch (MalformedURLException mue) {
668 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
669 throw (IOException) new IOException(err).initCause(mue);
672 // check for a latest config URL
673 String latest = config.getString("latest");
674 if (latest != null) {
675 if (latest.startsWith(_appbase)) {
676 latest = _appbase + latest.substring(_appbase.length());
678 latest = SysProps.replaceDomain(latest);
681 _latest = HostWhitelist.verify(new URL(latest));
682 } catch (MalformedURLException mue) {
683 log.warning("Invalid URL for latest attribute.", mue);
687 String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
689 // determine our application class name (use app-specific class _if_ one is provided)
690 _class = config.getString("class");
691 if (appPrefix.length() > 0) {
692 _class = config.getString(appPrefix + "class", _class);
694 if (_class == null) {
695 throw new IOException("m.missing_class");
698 // determine whether we want strict comments
699 _strictComments = config.getBoolean("strict_comments");
701 // check to see if we're using a custom java.version property and regex
702 _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
703 _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
705 // check to see if we require a particular JVM version and have a supplied JVM
706 _javaMinVersion = config.getLong("java_version", _javaMinVersion);
707 // we support java_min_version as an alias of java_version; it better expresses the check
708 // that's going on and better mirrors java_max_version
709 _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
710 // check to see if we require a particular max JVM version and have a supplied JVM
711 _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
712 // check to see if we require a particular JVM version and have a supplied JVM
713 _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
715 // this is a little weird, but when we're run from the digester, we see a String[] which
716 // contains java locations for all platforms which we can't grok, but the digester doesn't
717 // need to know about that; when we're run in a real application there will be only one!
718 Object javaloc = config.getRaw("java_location");
719 if (javaloc instanceof String) {
720 _javaLocation = (String)javaloc;
723 // determine whether we have any tracking configuration
724 _trackingURL = config.getString("tracking_url");
726 // check for tracking progress percent configuration
727 String trackPcts = config.getString("tracking_percents");
728 if (!StringUtil.isBlank(trackPcts)) {
729 _trackingPcts = new HashSet<>();
730 for (int pct : StringUtil.parseIntArray(trackPcts)) {
731 _trackingPcts.add(pct);
733 } else if (!StringUtil.isBlank(_trackingURL)) {
734 _trackingPcts = new HashSet<>();
735 _trackingPcts.add(50);
738 // Check for tracking cookie configuration
739 _trackingCookieName = config.getString("tracking_cookie_name");
740 _trackingCookieProperty = config.getString("tracking_cookie_property");
742 // Some app may need an extra suffix added to the tracking URL
743 _trackingURLSuffix = config.getString("tracking_url_suffix");
745 // Some app may need to generate google analytics code
746 _trackingGAHash = config.getString("tracking_ga_hash");
748 // clear our arrays as we may be reinitializing
756 // parse our code resources
757 if (config.getMultiValue("code") == null &&
758 config.getMultiValue("ucode") == null) {
759 throw new IOException("m.missing_code");
761 parseResources(config, "code", Resource.NORMAL, _codes);
762 parseResources(config, "ucode", Resource.UNPACK, _codes);
764 // parse our non-code resources
765 parseResources(config, "resource", Resource.NORMAL, _resources);
766 parseResources(config, "uresource", Resource.UNPACK, _resources);
767 parseResources(config, "xresource", Resource.EXEC, _resources);
768 parseResources(config, "presource", Resource.PRELOAD, _resources);
769 parseResources(config, "nresource", Resource.NATIVE, _resources);
771 // parse our auxiliary resource groups
772 for (String auxgroup : config.getList("auxgroups")) {
773 ArrayList<Resource> codes = new ArrayList<>();
774 parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
775 parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
776 ArrayList<Resource> rsrcs = new ArrayList<>();
777 parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
778 parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
779 parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
780 parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
781 parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
782 _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
785 // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
786 String[] jvmargs = config.getMultiValue("jvmarg");
787 addAll(jvmargs, _jvmargs);
788 if (appPrefix.length() > 0) {
789 jvmargs = config.getMultiValue(appPrefix + "jvmarg");
790 addAll(jvmargs, _jvmargs);
793 // extract jvmargs and jvmmempc from command line appargs. These will appear after and override the previous jvmargs
794 addAll(processCliJvmArgs(_envc.appArgs), _jvmargs);
796 // get the set of optimum JVM arguments
797 _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
799 // transfer our application arguments
800 String[] appargs = config.getMultiValue(appPrefix + "apparg");
801 addAll(appargs, _appargs);
803 // add the launch specific application arguments
804 _appargs.addAll(_envc.appArgs);
806 // see if a percentage of physical memory option exists if it hasn't been set by cli args
807 if (_jvmmempc > -1) {
808 _jvmmempc = config.getInt("jvmmempc", -1);
809 // app_id prefixed setting overrides
810 if (appPrefix.length() > 0) {
811 _jvmmempc = config.getInt(appPrefix + "jvmmempc", _jvmmempc);
814 if (0 <= _jvmmempc && _jvmmempc <= 100) {
816 long maxMemLong = -1;
820 maxMemLong = MemorySetting.memPercent(_jvmmempc);
821 } catch (Exception e)
824 } catch (Throwable t)
832 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
833 // remove other max heap size arg
834 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
835 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
839 addAll(maxMemHeapArg, _jvmargs);
843 } else if (_jvmmempc != -1) {
844 System.out.println("'jvmmempc' value must be in range 0 to 100 (read as '"+Integer.toString(_jvmmempc)+"')");
847 // look for custom arguments
848 fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
850 // determine whether we want to allow offline operation (defaults to false)
851 _allowOffline = config.getBoolean("allow_offline");
853 // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
854 // obtain a thread dump of the running JVM
855 _windebug = getLocalPath("debug.txt").exists();
857 // whether to cache code resources and launch from cache
858 _useCodeCache = config.getBoolean("use_code_cache");
859 _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
861 // maximum simultaneous downloads
862 _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
863 SysProps.threadPoolSize()));
865 // extract some info used to configure our child process on macOS
866 _dockName = config.getString("ui.name");
867 _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
873 * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
875 protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
877 File pairFile = getLocalPath(pairLocation);
878 if (pairFile.exists()) {
880 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
881 for (String[] pair : args) {
882 if (pair[1].length() == 0) {
883 collector.add(pair[0]);
885 collector.add(pair[0] + "=" + pair[1]);
888 } catch (Throwable t) {
889 log.warning("Failed to parse '" + pairFile + "': " + t);
895 * Returns a URL from which the specified path can be fetched. Our application base URL is
896 * properly versioned and combined with the supplied path.
898 public URL getRemoteURL (String path)
899 throws MalformedURLException
901 return new URL(_vappbase, encodePath(path));
905 * Returns the local path to the specified resource.
907 public File getLocalPath (String path)
909 return getLocalPath(getAppDir(), path);
913 * Returns true if we either have no version requirement, are running in a JVM that meets our
914 * version requirements or have what appears to be a version of the JVM that meets our
917 public boolean haveValidJavaVersion ()
919 // if we're doing no version checking, then yay!
920 if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
923 // parse the version out of the java.version (or custom) system property
924 long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
926 log.info("Checking Java version", "current", version,
927 "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
929 // if we have an unpacked VM, check the 'release' file for its version
930 Resource vmjar = getJavaVMResource();
931 if (vmjar != null && vmjar.isMarkedValid()) {
932 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
933 File relfile = new File(vmdir, "release");
934 if (!relfile.exists()) {
935 log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
939 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
941 log.warning("Unable to read version from 'release' file. Assuming valid.");
946 log.info("Checking version of unpacked JVM [vers=" + version + "].");
949 if (_javaExactVersionRequired) {
950 if (version == _javaMinVersion) return true;
952 log.warning("An exact Java VM version is required.", "current", version,
953 "required", _javaMinVersion);
958 boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
959 boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
960 return minVersionOK && maxVersionOK;
962 } catch (RuntimeException re) {
963 // if we can't parse the java version we're in weird land and should probably just try
964 // our luck with what we've got rather than try to download a new jvm
965 log.warning("Unable to parse VM version, hoping for the best",
966 "error", re, "needed", _javaMinVersion);
972 * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
973 * whether the launch is successful and, if necessary, trying again without the optimum
976 public boolean hasOptimumJvmArgs ()
978 return _optimumJvmArgs != null;
982 * Returns true if the app should attempt to run even if we have no Internet connection.
984 public boolean allowOffline ()
986 return _allowOffline;
990 * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
991 * previous call to {@link #init}.
993 public void attemptRecovery (StatusDisplay status)
996 status.updateStatus("m.updating_metadata");
997 downloadConfigFile();
1001 * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
1002 * those for the target version of our application.
1004 public void updateMetadata ()
1008 // update our versioned application base with the target version
1009 _vappbase = createVAppBase(_targetVersion);
1010 } catch (MalformedURLException mue) {
1011 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
1012 throw (IOException) new IOException(err).initCause(mue);
1016 // now re-download our control files; we download the digest first so that if it fails,
1017 // our config file will still reference the old version and re-running the updater will
1018 // start the whole process over again
1019 downloadDigestFiles();
1020 downloadConfigFile();
1022 } catch (IOException ex) {
1023 // if we are allowing offline execution, we want to allow the application to run in its
1024 // current form rather than aborting the entire process; to do this, we delete the
1025 // version.txt file and "trick" Getdown into thinking that it just needs to validate
1026 // the application as is; next time the app runs when connected to the internet, it
1027 // will have to rediscover that it needs updating and reattempt to update itself
1028 if (_allowOffline) {
1029 log.warning("Failed to update digest files. Attempting offline operaton.", ex);
1030 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
1031 log.warning("Deleting version.txt failed. This probably isn't going to work.");
1040 * Invokes the process associated with this application definition.
1042 * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
1045 public Process createProcess (boolean optimum)
1048 ArrayList<String> args = new ArrayList<>();
1050 // reconstruct the path to the JVM
1051 args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
1053 // check whether we're using -jar mode or -classpath mode
1054 boolean dashJarMode = MANIFEST_CLASS.equals(_class);
1056 // add the -classpath arguments if we're not in -jar mode
1057 ClassPath classPath = PathBuilder.buildClassPath(this);
1059 args.add("-classpath");
1060 args.add(classPath.asArgumentString());
1063 // we love our Mac users, so we do nice things to preserve our application identity
1064 if (LaunchUtil.isMacOS()) {
1065 args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1066 args.add("-Xdock:name=" + _dockName);
1069 // pass along our proxy settings
1071 if ((proxyHost = System.getProperty("http.proxyHost")) != null) {
1072 args.add("-Dhttp.proxyHost=" + proxyHost);
1073 args.add("-Dhttp.proxyPort=" + System.getProperty("http.proxyPort"));
1074 args.add("-Dhttps.proxyHost=" + proxyHost);
1075 args.add("-Dhttps.proxyPort=" + System.getProperty("http.proxyPort"));
1078 // add the marker indicating the app is running in getdown
1079 args.add("-D" + Properties.GETDOWN + "=true");
1081 // set the native library path if we have native resources
1082 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1083 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1084 if (javaLibPath != null) {
1085 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1088 // pass along any pass-through arguments
1089 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1090 String key = (String)entry.getKey();
1091 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1092 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1093 args.add("-D" + key + "=" + entry.getValue());
1097 // add the JVM arguments
1098 for (String string : _jvmargs) {
1099 args.add(processArg(string));
1102 // add the optimum arguments if requested and available
1103 if (optimum && _optimumJvmArgs != null) {
1104 for (String string : _optimumJvmArgs) {
1105 args.add(processArg(string));
1109 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1110 for (String string : _txtJvmArgs) {
1111 args.add(processArg(string));
1114 // if we're in -jar mode add those arguments, otherwise add the app class name
1117 args.add(classPath.asArgumentString());
1122 // almost finally check the startup file arguments
1123 for (File f : _startupFiles) {
1124 _appargs.add(f.getAbsolutePath());
1125 break; // Only add one file to open
1128 // check if one arg with recognised extension
1129 if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1130 String filename = _appargs.get(0);
1132 int j = filename.lastIndexOf('.');
1134 ext = filename.substring(j+1);
1136 if (ext != null && LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase())) {
1137 // this file extension should have been dealt with in Getdown class
1138 } else if (filename.startsWith("-")) {
1139 // probably an argument to jvm or jalview
1140 log.info("DOING NOTHING WITH ARG", "appargs", _appargs);
1142 _appargs.add(0, "-open");
1146 // finally add the application arguments
1147 for (String string : _appargs) {
1148 args.add(processArg(string));
1151 String[] envp = createEnvironment();
1152 String[] sargs = args.toArray(new String[args.size()]);
1153 log.info("Running " + StringUtil.join(sargs, "\n "));
1155 return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1159 * If the application provided environment variables, combine those with the current
1160 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1161 * If the application didn't provide any environment variables, null is returned to just use
1162 * the existing environment.
1164 protected String[] createEnvironment ()
1166 List<String> envvar = new ArrayList<>();
1167 fillAssignmentListFromPairs("env.txt", envvar);
1168 if (envvar.isEmpty()) {
1169 log.info("Didn't find any custom environment variables, not setting any.");
1173 List<String> envAssignments = new ArrayList<>();
1174 for (String assignment : envvar) {
1175 envAssignments.add(processArg(assignment));
1177 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1178 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1180 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1181 log.info("Environment " + StringUtil.join(envp, "\n "));
1186 * Runs this application directly in the current VM.
1188 public void invokeDirect () throws IOException
1190 ClassPath classPath = PathBuilder.buildClassPath(this);
1191 URL[] jarUrls = classPath.asUrls();
1193 // create custom class loader
1194 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1195 @Override protected PermissionCollection getPermissions (CodeSource code) {
1196 Permissions perms = new Permissions();
1197 perms.add(new AllPermission());
1201 Thread.currentThread().setContextClassLoader(loader);
1203 log.info("Configured URL class loader:");
1204 for (URL url : jarUrls) log.info(" " + url);
1206 // configure any system properties that we can
1207 for (String jvmarg : _jvmargs) {
1208 if (jvmarg.startsWith("-D")) {
1209 jvmarg = processArg(jvmarg.substring(2));
1210 int eqidx = jvmarg.indexOf("=");
1212 log.warning("Bogus system property: '" + jvmarg + "'?");
1214 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1219 // pass along any pass-through arguments
1220 Map<String, String> passProps = new HashMap<>();
1221 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1222 String key = (String)entry.getKey();
1223 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1224 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1225 passProps.put(key, (String)entry.getValue());
1228 // we can't set these in the above loop lest we get a ConcurrentModificationException
1229 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1230 System.setProperty(entry.getKey(), entry.getValue());
1233 // prepare our app arguments
1234 String[] args = new String[_appargs.size()];
1235 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1238 log.info("Loading " + _class);
1239 Class<?> appclass = loader.loadClass(_class);
1240 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1241 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1242 main.invoke(null, new Object[] { args });
1243 } catch (Exception e) {
1244 log.warning("Failure invoking app main", e);
1248 /** Replaces the application directory and version in any argument. */
1249 protected String processArg (String arg)
1251 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1252 arg = arg.replace("%VERSION%", String.valueOf(_version));
1254 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1255 // from the environment
1256 if (arg.contains(ENV_VAR_PREFIX)) {
1257 StringBuffer sb = new StringBuffer();
1258 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1259 while (matcher.find()) {
1260 String varName = matcher.group(1), varValue = System.getenv(varName);
1261 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1262 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1264 matcher.appendTail(sb);
1265 arg = sb.toString();
1272 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1273 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1274 * whether or not the application needs to be updated or whether we can proceed to verification
1277 * @return true if the application needs to be updated, false if it is up to date and can be
1278 * verified and executed.
1280 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1283 public boolean verifyMetadata (StatusDisplay status)
1286 log.info("Verifying application: " + _vappbase);
1287 log.info("Version: " + _version);
1288 log.info("Class: " + _class);
1290 // this will read in the contents of the digest file and validate itself
1292 _digest = new Digest(getAppDir(), _strictComments);
1293 } catch (IOException ioe) {
1294 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1297 // if we have no version, then we are running in unversioned mode so we need to download
1298 // our digest.txt file on every invocation
1299 if (_version == -1) {
1300 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1301 // resources as one or more of them have also changed
1302 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1304 status.updateStatus("m.checking");
1305 downloadDigestFiles();
1306 _digest = new Digest(getAppDir(), _strictComments);
1307 if (!olddig.equals(_digest.getMetaDigest())) {
1308 log.info("Unversioned digest changed. Revalidating...");
1309 status.updateStatus("m.validating");
1310 clearValidationMarkers();
1312 } catch (IOException ioe) {
1313 log.warning("Failed to refresh non-versioned digest: " +
1314 ioe.getMessage() + ". Proceeding...");
1318 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1319 // redownload the digest file and give it another good college try; this time we allow
1320 // exceptions to propagate up to the caller as there is nothing else we can do
1321 if (_digest == null) {
1322 status.updateStatus("m.updating_metadata");
1323 downloadDigestFiles();
1324 _digest = new Digest(getAppDir(), _strictComments);
1327 // now verify the contents of our main config file
1328 Resource crsrc = getConfigResource();
1329 if (!_digest.validateResource(crsrc, null)) {
1330 status.updateStatus("m.updating_metadata");
1331 // attempt to redownload both of our metadata files; again we pass errors up to our
1332 // caller because there's nothing we can do to automatically recover
1333 downloadConfigFile();
1334 downloadDigestFiles();
1335 _digest = new Digest(getAppDir(), _strictComments);
1336 // revalidate everything if we end up downloading new metadata
1337 clearValidationMarkers();
1338 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1339 if (_digest.validateResource(crsrc, null)) {
1342 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1343 "Blindly forging onward.");
1347 // start by assuming we are happy with our version
1348 _targetVersion = _version;
1350 // if we are a versioned application, read in the contents of the version.txt file
1351 // and/or check the latest config URL for a newer version
1352 if (_version != -1) {
1353 File vfile = getLocalPath(VERSION_FILE);
1354 long fileVersion = VersionUtil.readVersion(vfile);
1355 if (fileVersion != -1) {
1356 _targetVersion = fileVersion;
1359 if (_latest != null) {
1360 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1361 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1362 BufferedReader bin = new BufferedReader(reader)) {
1363 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1364 if (pair[0].equals("version")) {
1365 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1366 if (fileVersion != -1 && _targetVersion > fileVersion) {
1367 // replace the file with the newest version
1368 try (FileOutputStream fos = new FileOutputStream(vfile);
1369 PrintStream out = new PrintStream(fos)) {
1370 out.println(_targetVersion);
1376 } catch (Exception e) {
1377 log.warning("Unable to retrieve version from latest config file.", e);
1382 // finally let the caller know if we need an update
1383 return _version != _targetVersion;
1387 * Verifies the code and media resources associated with this application. A list of resources
1388 * that do not exist or fail the verification process will be returned. If all resources are
1389 * ready to go, null will be returned and the application is considered ready to run.
1391 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1392 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1393 * you have to take care to get back to your UI thread.
1394 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1395 * validated" resources filled in.
1396 * @param unpacked a set to populate with unpacked resources.
1397 * @param toInstall a list into which to add resources that need to be installed.
1398 * @param toDownload a list into which to add resources that need to be downloaded.
1400 public void verifyResources (
1401 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1402 Set<Resource> toInstall, Set<Resource> toDownload)
1403 throws InterruptedException
1405 // resources are verified on background threads supplied by the thread pool, and progress
1406 // is reported by posting runnable actions to the actions queue which is processed by the
1408 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1409 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1410 final int[] completed = new int[1];
1412 long start = System.currentTimeMillis();
1414 // obtain the sizes of the resources to validate
1415 List<Resource> rsrcs = getAllActiveResources();
1416 long[] sizes = new long[rsrcs.size()];
1418 for (int ii = 0; ii < sizes.length; ii++) {
1419 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1421 final ProgressObserver fobs = obs;
1422 // as long as we forward aggregated progress updates to the UI thread, having multiple
1423 // threads update a progress aggregator is "mostly" thread-safe
1424 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1425 public void progress (final int percent) {
1426 actions.add(new Runnable() {
1427 public void run () {
1428 fobs.progress(percent);
1434 final int[] fAlreadyValid = alreadyValid;
1435 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1436 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1437 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1439 for (int ii = 0; ii < sizes.length; ii++) {
1440 final Resource rsrc = rsrcs.get(ii);
1441 final int index = ii;
1442 exec.execute(new Runnable() {
1443 public void run () {
1444 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1445 unpackedAsync, toInstallAsync, toDownloadAsync);
1446 actions.add(new Runnable() {
1447 public void run () {
1455 while (completed[0] < rsrcs.size()) {
1456 // we should be getting progress completion updates WAY more often than one every
1457 // minute, so if things freeze up for 60 seconds, abandon ship
1458 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1464 toInstall.addAll(toInstallAsync);
1465 toDownload.addAll(toDownloadAsync);
1466 unpacked.addAll(unpackedAsync);
1468 long complete = System.currentTimeMillis();
1469 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1470 "duration", (complete-start) + "ms");
1473 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1474 Set<Resource> unpacked,
1475 Set<Resource> toInstall, Set<Resource> toDownload) {
1476 if (rsrc.isMarkedValid()) {
1477 if (alreadyValid != null) {
1485 if (_digest.validateResource(rsrc, obs)) {
1486 // if the resource has a _new file, add it to to-install list
1487 if (rsrc.getLocalNew().exists()) {
1488 toInstall.add(rsrc);
1497 } catch (Exception e) {
1498 log.info("Failure verifying resource. Requesting redownload...",
1499 "rsrc", rsrc, "error", e);
1504 toDownload.add(rsrc);
1508 * Unpacks the resources that require it (we know that they're valid).
1510 * @param unpacked a set of resources to skip because they're already unpacked.
1512 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1513 throws InterruptedException
1515 List<Resource> rsrcs = getActiveResources();
1517 // remove resources that we don't want to unpack
1518 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1519 Resource rsrc = it.next();
1520 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1525 // obtain the sizes of the resources to unpack
1526 long[] sizes = new long[rsrcs.size()];
1527 for (int ii = 0; ii < sizes.length; ii++) {
1528 sizes[ii] = rsrcs.get(ii).getLocal().length();
1531 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1532 for (int ii = 0; ii < sizes.length; ii++) {
1533 Resource rsrc = rsrcs.get(ii);
1534 ProgressObserver pobs = pagg.startElement(ii);
1537 } catch (IOException ioe) {
1538 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1545 * Clears all validation marker files.
1547 public void clearValidationMarkers ()
1549 clearValidationMarkers(getAllActiveResources().iterator());
1553 * Returns the version number for the application. Should only be called after successful
1554 * return of verifyMetadata.
1556 public long getVersion ()
1562 * Creates a versioned application base URL for the specified version.
1564 protected URL createVAppBase (long version)
1565 throws MalformedURLException
1567 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1568 return HostWhitelist.verify(new URL(url));
1572 * Clears all validation marker files for the resources in the supplied iterator.
1574 protected void clearValidationMarkers (Iterator<Resource> iter)
1576 while (iter.hasNext()) {
1577 iter.next().clearMarker();
1582 * Downloads a new copy of CONFIG_FILE.
1584 protected void downloadConfigFile ()
1587 downloadControlFile(CONFIG_FILE, 0);
1591 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1592 * we're not locking at all.
1594 public synchronized boolean lockForUpdates ()
1596 if (_lock != null && _lock.isValid()) {
1600 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1601 } catch (FileNotFoundException e) {
1602 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1606 _lock = _lockChannel.tryLock();
1607 } catch (IOException e) {
1608 log.warning("Unable to create lock", "message", e.getMessage(), e);
1610 } catch (OverlappingFileLockException e) {
1611 log.warning("The lock is held elsewhere in this JVM", e);
1614 log.info("Able to lock for updates: " + (_lock != null));
1615 return _lock != null;
1619 * Release gettingdown.lock
1621 public synchronized void releaseLock ()
1623 if (_lock != null) {
1624 log.info("Releasing lock");
1627 } catch (IOException e) {
1628 log.warning("Unable to release lock", "message", e.getMessage(), e);
1631 _lockChannel.close();
1632 } catch (IOException e) {
1633 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1635 _lockChannel = null;
1641 * Downloads the digest files and validates their signature.
1642 * @throws IOException
1644 protected void downloadDigestFiles ()
1647 for (int version = 1; version <= Digest.VERSION; version++) {
1648 downloadControlFile(Digest.digestFile(version), version);
1653 * Downloads a new copy of the specified control file, optionally validating its signature.
1654 * If the download is successful, moves it over the old file on the filesystem.
1656 * <p> TODO: Switch to PKCS #7 or CMS.
1658 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1659 * should indicate the version of the digest file being validated which indicates which
1660 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1662 protected void downloadControlFile (String path, int sigVersion)
1665 File target = downloadFile(path);
1667 if (sigVersion > 0) {
1668 if (_envc.certs.isEmpty()) {
1669 log.info("No signing certs, not verifying digest.txt", "path", path);
1672 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1673 byte[] signature = null;
1674 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1675 signature = StreamUtil.toByteArray(signatureStream);
1677 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1680 byte[] buffer = new byte[8192];
1681 int length, validated = 0;
1682 for (Certificate cert : _envc.certs) {
1683 try (FileInputStream dataInput = new FileInputStream(target)) {
1684 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1685 sig.initVerify(cert);
1686 while ((length = dataInput.read(buffer)) != -1) {
1687 sig.update(buffer, 0, length);
1690 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1691 log.info("Signature does not match", "cert", cert.getPublicKey());
1694 log.info("Signature matches", "cert", cert.getPublicKey());
1698 } catch (IOException ioe) {
1699 log.warning("Failure validating signature of " + target + ": " + ioe);
1701 } catch (GeneralSecurityException gse) {
1707 // if we couldn't find a key that validates our digest, we are the hosed!
1708 if (validated == 0) {
1709 // delete the temporary digest file as we know it is invalid
1710 FileUtil.deleteHarder(target);
1711 throw new IOException("m.corrupt_digest_signature_error");
1716 // now move the temporary file over the original
1717 File original = getLocalPath(path);
1718 if (!FileUtil.renameTo(target, original)) {
1719 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1724 * Download a path to a temporary file, returning a {@link File} instance with the path
1727 protected File downloadFile (String path)
1730 File target = getLocalPath(path + "_new");
1732 URL targetURL = null;
1734 targetURL = getRemoteURL(path);
1735 } catch (Exception e) {
1736 log.warning("Requested to download invalid control file",
1737 "appbase", _vappbase, "path", path, "error", e);
1738 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1741 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1743 // stream the URL into our temporary file
1744 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1745 // we have to tell Java not to use caches here, otherwise it will cache any request for
1746 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1747 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1748 // about it; turning off caches is not a performance concern, because when Getdown asks
1749 // to download a file, it expects it to come over the wire, not from a cache
1750 uconn.setUseCaches(false);
1751 uconn.setRequestProperty("Accept-Encoding", "gzip");
1752 try (InputStream fin = uconn.getInputStream()) {
1753 String encoding = uconn.getContentEncoding();
1754 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1755 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1756 try (FileOutputStream fout = new FileOutputStream(target)) {
1757 StreamUtil.copy(fin2, fout);
1765 /** Helper function for creating {@link Resource} instances. */
1766 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1767 throws MalformedURLException
1769 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1772 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1773 protected static void addAll (String[] values, List<String> target) {
1774 if (values != null) {
1775 for (String value : values) {
1782 * Make an immutable List from the specified int array.
1784 public static List<Integer> intsToList (int[] values)
1786 List<Integer> list = new ArrayList<>(values.length);
1787 for (int val : values) {
1790 return Collections.unmodifiableList(list);
1794 * Make an immutable List from the specified String array.
1796 public static List<String> stringsToList (String[] values)
1798 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1801 /** Used to parse resources with the specified name. */
1802 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1803 List<Resource> list)
1805 String[] rsrcs = config.getMultiValue(name);
1806 if (rsrcs == null) {
1809 for (String rsrc : rsrcs) {
1811 list.add(createResource(rsrc, attrs));
1812 } catch (Exception e) {
1813 log.warning("Invalid resource '" + rsrc + "'. " + e);
1818 /** Possibly generates and returns a google analytics tracking cookie. */
1819 protected String getGATrackingCode ()
1821 if (_trackingGAHash == null) {
1824 long time = System.currentTimeMillis() / 1000;
1825 if (_trackingStart == 0) {
1826 _trackingStart = time;
1828 if (_trackingId == 0) {
1829 int low = 100000000, high = 1000000000;
1830 _trackingId = low + _rando.nextInt(high-low);
1832 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1833 cookie.append(".").append(_trackingId);
1834 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1835 cookie.append(".").append(time).append(".1%3B%2B");
1836 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1837 cookie.append(_trackingStart).append(".1.1.");
1838 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1839 int low = 1000000000, high = 2000000000;
1840 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1841 return cookie.toString();
1845 * Encodes a path for use in a URL.
1847 protected static String encodePath (String path)
1850 // we want to keep slashes because we're encoding an entire path; also we need to turn
1851 // + into %20 because web servers don't like + in paths or file names, blah
1852 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1853 } catch (UnsupportedEncodingException ue) {
1854 log.warning("Failed to URL encode " + path + ": " + ue);
1859 protected File getLocalPath (File appdir, String path)
1861 return new File(appdir, path);
1864 public static void setStartupFilesFromParameterString(String p) {
1865 // multiple files *might* be passed in as space separated quoted filenames
1867 if (!StringUtil.isBlank(p)) {
1869 // split quoted params or treat as single string array
1870 if (p.startsWith(q) && p.endsWith(q)) {
1871 // this fails if, e.g.
1872 // p=q("stupidfilename\" " "otherfilename")
1873 // let's hope no-one ever ends a filename with '" '
1874 filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1876 // single unquoted filename
1877 filenames = new String[]{p};
1880 // check for locator file. Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1881 String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
1883 !StringUtil.isBlank(locatorFilename)
1884 && locatorFilename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)
1886 setLocatorFile(locatorFilename);
1887 // remove the locator filename from the filenames array
1888 String[] otherFilenames = new String[filenames.length - 1];
1889 System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
1890 filenames = otherFilenames;
1893 for (int i = 0; i < filenames.length; i++) {
1894 String filename = filenames[i];
1895 // skip any other locator files in a multiple file list
1896 if (! filename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
1897 addStartupFile(filename);
1903 public static void setLocatorFile(String filename) {
1904 _locatorFile = new File(filename);
1907 public static void addStartupFile(String filename) {
1908 _startupFiles.add(new File(filename));
1911 private Config createLocatorConfig(Config.ParseOpts opts) {
1912 if (_locatorFile == null) {
1916 Config locatorConfig = null;
1919 Config tmpConfig = null;
1920 Map<String, Object> tmpData = new HashMap<>();
1921 if (_locatorFile.exists()) {
1922 tmpConfig = Config.parseConfig(_locatorFile, opts);
1923 // appbase is sanitised in HostWhitelist
1924 Map<String, Object> tmpConfigData = tmpConfig.getData();
1925 if (tmpConfig != null) {
1926 for (Map.Entry<String, Object> entry : tmpConfigData.entrySet()) {
1927 String key = entry.getKey();
1928 Object value = entry.getValue();
1929 String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
1930 if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
1931 tmpData.put(key, value);
1935 log.warning("Error occurred reading config file", "file", _locatorFile);
1938 log.warning("Given locator file does not exist", "file", _locatorFile);
1941 locatorConfig = new Config(tmpData);
1943 } catch (Exception e) {
1944 log.warning("Failure reading locator file", "file", _locatorFile, e);
1947 return locatorConfig;
1950 public String getAppbase() {
1954 protected String[] processCliJvmArgs(List<String> args) {
1955 List<String> extracted = new ArrayList<>();
1957 for (String arg : args) {
1958 if (arg.startsWith("-"+CLI_JVM_ARG_PREFIX)) {
1959 String newArg = arg.substring(CLI_JVM_ARG_PREFIX.length() + 1);
1960 extracted.add(newArg);
1962 } else if (arg.startsWith("-jvmmempc=")) {
1964 _jvmmempc = Integer.parseInt(arg.substring(10));
1965 } catch (NumberFormatException e){
1966 log.warning("Could not parse jvmmempc command line argument", "arg", arg);
1971 return extracted.toArray(new String[0]);
1974 protected final EnvConfig _envc;
1975 protected File _config;
1976 protected File _backupConfig;
1977 protected Digest _digest;
1979 protected long _version = -1;
1980 protected long _targetVersion = -1;
1981 protected String _appbase;
1982 protected URL _vappbase;
1983 protected URL _latest;
1984 protected String _class;
1985 protected String _dockName;
1986 protected String _dockIconPath;
1987 protected boolean _strictComments;
1988 protected boolean _windebug;
1989 protected boolean _allowOffline;
1990 protected int _maxConcDownloads;
1992 protected String _trackingURL;
1993 protected Set<Integer> _trackingPcts;
1994 protected String _trackingCookieName;
1995 protected String _trackingCookieProperty;
1996 protected String _trackingURLSuffix;
1997 protected String _trackingGAHash;
1998 protected long _trackingStart;
1999 protected int _trackingId;
2001 protected String _javaVersionProp = "java.version";
2002 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
2003 protected long _javaMinVersion, _javaMaxVersion;
2004 protected boolean _javaExactVersionRequired;
2005 protected String _javaLocation;
2007 protected List<Resource> _codes = new ArrayList<>();
2008 protected List<Resource> _resources = new ArrayList<>();
2010 protected boolean _useCodeCache;
2011 protected int _codeCacheRetentionDays;
2013 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
2014 protected Map<String,Boolean> _auxactive = new HashMap<>();
2016 protected List<String> _jvmargs = new ArrayList<>();
2017 protected List<String> _appargs = new ArrayList<>();
2019 protected String[] _optimumJvmArgs;
2021 protected List<String> _txtJvmArgs = new ArrayList<>();
2023 /** jvmmempc for memory settings and other cli arguments for the JVM */
2024 protected int _jvmmempc = -1;
2025 protected static final String CLI_JVM_ARG_PREFIX = "JVM";
2027 /** If a warning has been issued about not being able to set modtimes. */
2028 protected boolean _warnedAboutSetLastModified;
2030 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
2031 protected FileLock _lock;
2033 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
2034 protected FileChannel _lockChannel;
2036 protected Random _rando = new Random();
2038 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
2040 protected static final String ENV_VAR_PREFIX = "%ENV.";
2041 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
2043 protected static File _locatorFile;
2044 protected static List<File> _startupFiles = new ArrayList<>();
2045 public static final String LOCATOR_FILE_EXTENSION = "jvl";