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;
26 import com.sun.management.OperatingSystemMXBean;
27 import java.lang.management.ManagementFactory;
29 import jalview.bin.MemorySetting;
31 import com.threerings.getdown.util.*;
32 // avoid ambiguity with java.util.Base64 which we can't use as it's 1.8+
33 import com.threerings.getdown.util.Base64;
35 import com.threerings.getdown.data.EnvConfig;
36 import com.threerings.getdown.data.EnvConfig.Note;
38 import static com.threerings.getdown.Log.log;
39 import static java.nio.charset.StandardCharsets.UTF_8;
42 * Parses and provide access to the information contained in the <code>getdown.txt</code>
45 public class Application
47 /** The name of our configuration file. */
48 public static final String CONFIG_FILE = "getdown.txt";
50 /** The name of our target version file. */
51 public static final String VERSION_FILE = "version.txt";
53 /** System properties that are prefixed with this string will be passed through to our
54 * application (minus this prefix). */
55 public static final String PROP_PASSTHROUGH_PREFIX = "app.";
57 /** Suffix used for control file signatures. */
58 public static final String SIGNATURE_SUFFIX = ".sig";
60 /** A special classname that means 'use -jar code.jar' instead of a classname. */
61 public static final String MANIFEST_CLASS = "manifest";
63 /** Used to communicate information about the UI displayed when updating the application. */
64 public static final class UpdateInterface
67 * The major steps involved in updating, along with some arbitrary percentages
68 * assigned to them, to mark global progress.
73 VERIFY_METADATA(15, 65, 95),
76 VERIFY_RESOURCES(70, 97),
77 REDOWNLOAD_RESOURCES(90),
81 /** What is the final percent value for this step? */
82 public final List<Integer> defaultPercents;
84 /** Enum constructor. */
85 Step (int... percents)
87 this.defaultPercents = intsToList(percents);
91 /** The human readable name of this application. */
92 public final String name;
94 /** A background color, just in case. */
95 public final int background;
97 /** Background image specifiers for `RotatingBackgrounds`. */
98 public final List<String> rotatingBackgrounds;
100 /** The error background image for `RotatingBackgrounds`. */
101 public final String errorBackground;
103 /** The paths (relative to the appdir) of images for the window icon. */
104 public final List<String> iconImages;
106 /** The path (relative to the appdir) to a single background image to appear first. */
107 public final String instantBackgroundImage;
109 /** The path (relative to the appdir) to a single background image. */
110 public final String backgroundImage;
112 /** The path (relative to the appdir) to the progress bar image. */
113 public final String progressImage;
115 /** The dimensions of the progress bar. */
116 public final Rectangle progress;
118 /** The color of the progress text. */
119 public final int progressText;
121 /** The color of the progress bar. */
122 public final int progressBar;
124 /** The dimensions of the status display. */
125 public final Rectangle status;
127 /** The color of the status text. */
128 public final int statusText;
130 /** The color of the text shadow. */
131 public final int textShadow;
133 /** Where to point the user for help with install errors. */
134 public final String installError;
136 /** The dimensions of the patch notes button. */
137 public final Rectangle patchNotes;
139 /** The patch notes URL. */
140 public final String patchNotesUrl;
142 /** Whether window decorations are hidden for the UI. */
143 public final boolean hideDecorations;
145 /** Whether progress text should be hidden or not. */
146 public final boolean hideProgressText;
148 /** Whether the splash screen should retain focus. */
149 public final boolean progressSync;
151 /** Whether the splash screen should retain focus. */
152 public final boolean keepOnTop;
154 /** Whether to display the appbase. */
155 public final boolean displayAppbase;
157 /** Whether to display the version. */
158 public final boolean displayVersion;
160 /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
161 * flashing up on the screen and immediately disappearing, which can be confusing to the
163 public final int minShowSeconds;
165 /** The global percentages for each step. A step may have more than one, and
166 * the lowest reasonable one is used if a step is revisited. */
167 public final Map<Step, List<Integer>> stepPercentages;
169 /** Generates a string representation of this instance. */
171 public String toString ()
173 return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage + ", instant_bg=" + instantBackgroundImage +
174 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
175 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
176 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
177 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
178 ", hideProgressText=" + hideProgressText + ", keepOnTop=" + keepOnTop + ", progressSync=" + progressSync + ", minShow=" + minShowSeconds +
179 ", displayAppbase=" + displayAppbase + ", displayVersion=" + displayVersion + "]";
182 public UpdateInterface (Config config)
184 this.name = config.getString("ui.name");
185 this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
186 this.progressText = config.getColor("ui.progress_text", Color.BLACK);
187 this.hideProgressText = config.getBoolean("ui.hide_progress_text");
188 this.progressSync = config.getBoolean("ui.progress_sync");
189 this.keepOnTop = config.getBoolean("ui.keep_on_top");
190 this.displayAppbase = config.getBoolean("ui.display_appbase");
191 this.displayVersion = config.getBoolean("ui.display_version");
192 this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
193 this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
194 this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
195 this.statusText = config.getColor("ui.status_text", Color.BLACK);
196 this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
197 this.hideDecorations = config.getBoolean("ui.hide_decorations");
198 this.backgroundImage = config.getString("ui.background_image");
199 this.instantBackgroundImage = config.getString("ui.instant_background_image");
200 // default to black or white bg color, depending on the brightness of the progressText
201 int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
202 Color.BLACK : Color.WHITE;
203 this.background = config.getColor("ui.background", defaultBackground);
204 this.progressImage = config.getString("ui.progress_image");
205 this.rotatingBackgrounds = stringsToList(
206 config.getMultiValue("ui.rotating_background"));
207 this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
208 this.errorBackground = config.getString("ui.error_background");
210 // On an installation error, where do we point the user.
211 String installError = config.getUrl("ui.install_error", null);
212 this.installError = (installError == null) ?
213 "m.default_install_error" : MessageUtil.taint(installError);
215 // the patch notes bits
216 this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
217 this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
219 // step progress percentage (defaults and then customized values)
220 EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
221 for (Step step : Step.values()) {
222 stepPercentages.put(step, step.defaultPercents);
224 for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
225 String spec = config.getString("ui.percents." + step.name());
228 stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
229 } catch (Exception e) {
230 log.warning("Failed to parse percentages for " + step + ": " + spec);
234 this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
239 * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
240 * take network actions.
242 public static interface StatusDisplay
244 /** Requests that the specified status message be displayed. */
245 public void updateStatus (String message);
249 * Contains metadata for an auxiliary resource group.
251 public static class AuxGroup {
252 public final String name;
253 public final List<Resource> codes;
254 public final List<Resource> rsrcs;
256 public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
258 this.codes = Collections.unmodifiableList(codes);
259 this.rsrcs = Collections.unmodifiableList(rsrcs);
263 /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
264 * the application instance. Yes this is a public mutable field, no I'm not going to create a
265 * getter and setter just to pretend like that's not the case. */
266 public Proxy proxy = Proxy.NO_PROXY;
269 * Creates an application instance which records the location of the <code>getdown.txt</code>
270 * configuration file from the supplied application directory.
273 public Application (EnvConfig envc) {
275 _config = getLocalPath(envc.appDir, CONFIG_FILE);
279 * Returns the configured application directory.
281 public File getAppDir () {
286 * Returns whether the application should cache code resources prior to launching the
289 public boolean useCodeCache ()
291 return _useCodeCache;
295 * Returns the number of days a cached code resource is allowed to stay unused before it
296 * becomes eligible for deletion.
298 public int getCodeCacheRetentionDays ()
300 return _codeCacheRetentionDays;
304 * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
305 * app files from its hosting server.
307 public int maxConcurrentDownloads () {
308 return _maxConcDownloads;
312 * Returns a resource that refers to the application configuration file itself.
314 public Resource getConfigResource ()
317 return createResource(CONFIG_FILE, Resource.NORMAL);
318 } catch (Exception e) {
319 throw new RuntimeException("Invalid appbase '" + _vappbase + "'.", e);
324 * Returns a list of the code {@link Resource} objects used by this application.
326 public List<Resource> getCodeResources ()
332 * Returns a list of the non-code {@link Resource} objects used by this application.
334 public List<Resource> getResources ()
340 * Returns the digest of the given {@code resource}.
342 public String getDigest (Resource resource)
344 return _digest.getDigest(resource);
348 * Returns a list of all the active {@link Resource} objects used by this application (code and
351 public List<Resource> getAllActiveResources ()
353 List<Resource> allResources = new ArrayList<>();
354 allResources.addAll(getActiveCodeResources());
355 allResources.addAll(getActiveResources());
360 * Returns the auxiliary resource group with the specified name, or null.
362 public AuxGroup getAuxGroup (String name)
364 return _auxgroups.get(name);
368 * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
369 * resource group is a collection of resource files that are not downloaded unless a group
370 * token file is present in the application directory.
372 public Iterable<AuxGroup> getAuxGroups ()
374 return _auxgroups.values();
378 * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
379 * groups should be ignored, activated groups should be downloaded and patched along with the
382 public boolean isAuxGroupActive (String auxgroup)
384 Boolean active = _auxactive.get(auxgroup);
385 if (active == null) {
386 // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
388 active = getLocalPath(auxgroup + ".dat").exists();
389 _auxactive.put(auxgroup, active);
395 * Returns all main code resources and all code resources from active auxiliary resource groups.
397 public List<Resource> getActiveCodeResources ()
399 ArrayList<Resource> codes = new ArrayList<>();
400 codes.addAll(getCodeResources());
401 for (AuxGroup aux : getAuxGroups()) {
402 if (isAuxGroupActive(aux.name)) {
403 codes.addAll(aux.codes);
410 * Returns all resources indicated to contain native library files (.dll, .so, etc.).
412 public List<Resource> getNativeResources ()
414 List<Resource> natives = new ArrayList<>();
415 for (Resource resource: _resources) {
416 if (resource.isNative()) {
417 natives.add(resource);
424 * Returns all non-code resources and all resources from active auxiliary resource groups.
426 public List<Resource> getActiveResources ()
428 ArrayList<Resource> rsrcs = new ArrayList<>();
429 rsrcs.addAll(getResources());
430 for (AuxGroup aux : getAuxGroups()) {
431 if (isAuxGroupActive(aux.name)) {
432 rsrcs.addAll(aux.rsrcs);
439 * Returns a resource that can be used to download a patch file that will bring this
440 * application from its current version to the target version.
442 * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
443 * for the main application patch resource.
445 public Resource getPatchResource (String auxgroup)
447 if (_targetVersion <= _version) {
448 log.warning("Requested patch resource for up-to-date or non-versioned application",
449 "cvers", _version, "tvers", _targetVersion);
453 String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
454 String pfile = "patch" + infix + _version + ".dat";
456 URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
457 return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
458 } catch (Exception e) {
459 log.warning("Failed to create patch resource path",
460 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
466 * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
467 * place of the installed VM (in the case where the VM that launched Getdown does not meet the
468 * application's version requirements) or null if no VM is available for this platform.
470 public Resource getJavaVMResource ()
472 if (StringUtil.isBlank(_javaLocation)) {
476 String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
477 String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
478 log.info("vmfile is '"+vmfile+"'");
479 System.out.println("vmfile is '"+vmfile+"'");
481 URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
482 log.info("Attempting to fetch jvm at "+remote.toString());
483 System.out.println("Attempting to fetch jvm at "+remote.toString());
484 return new Resource(vmfile, remote, getLocalPath(vmfile),
485 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
486 } catch (Exception e) {
487 log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
488 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
489 System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
490 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
496 * Returns a resource that can be used to download an archive containing all files belonging to
499 public Resource getFullResource ()
501 String file = "full";
503 URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
504 return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
505 } catch (Exception e) {
506 log.warning("Failed to create full resource path",
507 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
513 * Returns the URL to use to report an initial download event. Returns null if no tracking
514 * start URL was configured for this application.
516 * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
518 public URL getTrackingURL (String event)
521 String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
522 String ga = getGATrackingCode();
523 return _trackingURL == null ? null :
524 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
525 } catch (MalformedURLException mue) {
526 log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
532 * Returns the URL to request to report that we have reached the specified percentage of our
533 * initial download. Returns null if no tracking request was configured for the specified
536 public URL getTrackingProgressURL (int percent)
538 if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
541 return getTrackingURL("pct" + percent);
545 * Returns the name of our tracking cookie or null if it was not set.
547 public String getTrackingCookieName ()
549 return _trackingCookieName;
553 * Returns the name of our tracking cookie system property or null if it was not set.
555 public String getTrackingCookieProperty ()
557 return _trackingCookieProperty;
561 * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
562 * for operation. The application base URL will be parsed first so that if there are errors
563 * discovered later, the caller can use the application base to download a new {@code
564 * getdown.txt} file and try again.
566 * @return a {@code Config} instance that contains information from the config file.
568 * @exception IOException thrown if there is an error reading the file or an error encountered
569 * during its parsing.
571 public Config init (boolean checkPlatform)
574 Config config = null;
575 File cfgfile = _config;
576 Config.ParseOpts opts = Config.createOpts(checkPlatform);
578 // if we have a configuration file, read the data from it
579 if (cfgfile.exists()) {
580 config = Config.parseConfig(_config, opts);
582 // otherwise, try reading data from our backup config file; thanks to funny windows
583 // bullshit, we have to do this backup file fiddling in case we got screwed while
584 // updating getdown.txt during normal operation
585 else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
586 config = Config.parseConfig(cfgfile, opts);
588 // otherwise, issue a warning that we found no getdown file
590 log.info("Found no getdown.txt file", "appdir", getAppDir());
592 } catch (Exception e) {
593 log.warning("Failure reading config file", "file", _config, e);
596 // see if there's an override config from locator file
597 Config locatorConfig = createLocatorConfig(opts);
599 // merge the locator file config into config (or replace config with)
600 if (locatorConfig != null) {
601 if (config == null || locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_replace")) {
602 config = locatorConfig;
604 config.mergeConfig(locatorConfig, locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_merge"));
608 // if we failed to read our config file, check for an appbase specified via a system
609 // property; we can use that to bootstrap ourselves back into operation
610 if (config == null) {
611 String appbase = _envc.appBase;
612 log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
613 Map<String, Object> cdata = new HashMap<>();
614 cdata.put("appbase", appbase);
615 config = new Config(cdata);
618 // first determine our application base, this way if anything goes wrong later in the
619 // process, our caller can use the appbase to download a new configuration file
620 _appbase = config.getString("appbase");
622 // see if locatorConfig override
623 if (locatorConfig != null && !StringUtil.isBlank(locatorConfig.getString("appbase"))) {
624 _appbase = locatorConfig.getString("appbase");
627 if (_appbase == null) {
628 throw new RuntimeException("m.missing_appbase");
631 // check if we're overriding the domain in the appbase
632 _appbase = SysProps.overrideAppbase(_appbase);
634 // make sure there's a trailing slash
635 if (!_appbase.endsWith("/")) {
636 _appbase = _appbase + "/";
639 // extract our version information
640 _version = config.getLong("version", -1L);
642 // if we are a versioned deployment, create a versioned appbase
644 _vappbase = createVAppBase(_version);
645 } catch (MalformedURLException mue) {
646 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
647 throw (IOException) new IOException(err).initCause(mue);
650 // check for a latest config URL
651 String latest = config.getString("latest");
652 if (latest != null) {
653 if (latest.startsWith(_appbase)) {
654 latest = _appbase + latest.substring(_appbase.length());
656 latest = SysProps.replaceDomain(latest);
659 _latest = HostWhitelist.verify(new URL(latest));
660 } catch (MalformedURLException mue) {
661 log.warning("Invalid URL for latest attribute.", mue);
665 String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
667 // determine our application class name (use app-specific class _if_ one is provided)
668 _class = config.getString("class");
669 if (appPrefix.length() > 0) {
670 _class = config.getString(appPrefix + "class", _class);
672 if (_class == null) {
673 throw new IOException("m.missing_class");
676 // determine whether we want strict comments
677 _strictComments = config.getBoolean("strict_comments");
679 // check to see if we're using a custom java.version property and regex
680 _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
681 _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
683 // check to see if we require a particular JVM version and have a supplied JVM
684 _javaMinVersion = config.getLong("java_version", _javaMinVersion);
685 // we support java_min_version as an alias of java_version; it better expresses the check
686 // that's going on and better mirrors java_max_version
687 _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
688 // check to see if we require a particular max JVM version and have a supplied JVM
689 _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
690 // check to see if we require a particular JVM version and have a supplied JVM
691 _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
693 // this is a little weird, but when we're run from the digester, we see a String[] which
694 // contains java locations for all platforms which we can't grok, but the digester doesn't
695 // need to know about that; when we're run in a real application there will be only one!
696 Object javaloc = config.getRaw("java_location");
697 if (javaloc instanceof String) {
698 _javaLocation = (String)javaloc;
701 // determine whether we have any tracking configuration
702 _trackingURL = config.getString("tracking_url");
704 // check for tracking progress percent configuration
705 String trackPcts = config.getString("tracking_percents");
706 if (!StringUtil.isBlank(trackPcts)) {
707 _trackingPcts = new HashSet<>();
708 for (int pct : StringUtil.parseIntArray(trackPcts)) {
709 _trackingPcts.add(pct);
711 } else if (!StringUtil.isBlank(_trackingURL)) {
712 _trackingPcts = new HashSet<>();
713 _trackingPcts.add(50);
716 // Check for tracking cookie configuration
717 _trackingCookieName = config.getString("tracking_cookie_name");
718 _trackingCookieProperty = config.getString("tracking_cookie_property");
720 // Some app may need an extra suffix added to the tracking URL
721 _trackingURLSuffix = config.getString("tracking_url_suffix");
723 // Some app may need to generate google analytics code
724 _trackingGAHash = config.getString("tracking_ga_hash");
726 // clear our arrays as we may be reinitializing
734 // parse our code resources
735 if (config.getMultiValue("code") == null &&
736 config.getMultiValue("ucode") == null) {
737 throw new IOException("m.missing_code");
739 parseResources(config, "code", Resource.NORMAL, _codes);
740 parseResources(config, "ucode", Resource.UNPACK, _codes);
742 // parse our non-code resources
743 parseResources(config, "resource", Resource.NORMAL, _resources);
744 parseResources(config, "uresource", Resource.UNPACK, _resources);
745 parseResources(config, "xresource", Resource.EXEC, _resources);
746 parseResources(config, "presource", Resource.PRELOAD, _resources);
747 parseResources(config, "nresource", Resource.NATIVE, _resources);
749 // parse our auxiliary resource groups
750 for (String auxgroup : config.getList("auxgroups")) {
751 ArrayList<Resource> codes = new ArrayList<>();
752 parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
753 parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
754 ArrayList<Resource> rsrcs = new ArrayList<>();
755 parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
756 parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
757 parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
758 parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
759 parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
760 _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
763 // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
764 String[] jvmargs = config.getMultiValue("jvmarg");
765 addAll(jvmargs, _jvmargs);
766 if (appPrefix.length() > 0) {
767 jvmargs = config.getMultiValue(appPrefix + "jvmarg");
768 addAll(jvmargs, _jvmargs);
771 // see if a percentage of physical memory option exists
772 int jvmmempc = config.getInt("jvmmempc", -1);
773 // app_id prefixed setting overrides
774 if (appPrefix.length() > 0) {
775 jvmmempc = config.getInt(appPrefix + "jvmmempc", jvmmempc);
777 if (0 <= jvmmempc && jvmmempc <= 100) {
779 long maxMemLong = -1;
783 maxMemLong = MemorySetting.memPercent(jvmmempc);
784 } catch (Exception e)
787 } catch (Throwable t)
795 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
796 // remove other max heap size arg
797 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
798 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
802 addAll(maxMemHeapArg, _jvmargs);
806 } else if (jvmmempc != -1) {
807 System.out.println("'jvmmempc' value must be in range 0 to 100 (read as '"+Integer.toString(jvmmempc)+"')");
810 // get the set of optimum JVM arguments
811 _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
813 // transfer our application arguments
814 String[] appargs = config.getMultiValue(appPrefix + "apparg");
815 addAll(appargs, _appargs);
817 // add the launch specific application arguments
818 _appargs.addAll(_envc.appArgs);
820 // look for custom arguments
821 fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
823 // determine whether we want to allow offline operation (defaults to false)
824 _allowOffline = config.getBoolean("allow_offline");
826 // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
827 // obtain a thread dump of the running JVM
828 _windebug = getLocalPath("debug.txt").exists();
830 // whether to cache code resources and launch from cache
831 _useCodeCache = config.getBoolean("use_code_cache");
832 _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
834 // maximum simultaneous downloads
835 _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
836 SysProps.threadPoolSize()));
838 // extract some info used to configure our child process on macOS
839 _dockName = config.getString("ui.name");
840 _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
846 * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
848 protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
850 File pairFile = getLocalPath(pairLocation);
851 if (pairFile.exists()) {
853 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
854 for (String[] pair : args) {
855 if (pair[1].length() == 0) {
856 collector.add(pair[0]);
858 collector.add(pair[0] + "=" + pair[1]);
861 } catch (Throwable t) {
862 log.warning("Failed to parse '" + pairFile + "': " + t);
868 * Returns a URL from which the specified path can be fetched. Our application base URL is
869 * properly versioned and combined with the supplied path.
871 public URL getRemoteURL (String path)
872 throws MalformedURLException
874 return new URL(_vappbase, encodePath(path));
878 * Returns the local path to the specified resource.
880 public File getLocalPath (String path)
882 return getLocalPath(getAppDir(), path);
886 * Returns true if we either have no version requirement, are running in a JVM that meets our
887 * version requirements or have what appears to be a version of the JVM that meets our
890 public boolean haveValidJavaVersion ()
892 // if we're doing no version checking, then yay!
893 if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
896 // parse the version out of the java.version (or custom) system property
897 long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
899 log.info("Checking Java version", "current", version,
900 "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
902 // if we have an unpacked VM, check the 'release' file for its version
903 Resource vmjar = getJavaVMResource();
904 if (vmjar != null && vmjar.isMarkedValid()) {
905 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
906 File relfile = new File(vmdir, "release");
907 if (!relfile.exists()) {
908 log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
912 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
914 log.warning("Unable to read version from 'release' file. Assuming valid.");
919 log.info("Checking version of unpacked JVM [vers=" + version + "].");
922 if (_javaExactVersionRequired) {
923 if (version == _javaMinVersion) return true;
925 log.warning("An exact Java VM version is required.", "current", version,
926 "required", _javaMinVersion);
931 boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
932 boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
933 return minVersionOK && maxVersionOK;
935 } catch (RuntimeException re) {
936 // if we can't parse the java version we're in weird land and should probably just try
937 // our luck with what we've got rather than try to download a new jvm
938 log.warning("Unable to parse VM version, hoping for the best",
939 "error", re, "needed", _javaMinVersion);
945 * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
946 * whether the launch is successful and, if necessary, trying again without the optimum
949 public boolean hasOptimumJvmArgs ()
951 return _optimumJvmArgs != null;
955 * Returns true if the app should attempt to run even if we have no Internet connection.
957 public boolean allowOffline ()
959 return _allowOffline;
963 * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
964 * previous call to {@link #init}.
966 public void attemptRecovery (StatusDisplay status)
969 status.updateStatus("m.updating_metadata");
970 downloadConfigFile();
974 * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
975 * those for the target version of our application.
977 public void updateMetadata ()
981 // update our versioned application base with the target version
982 _vappbase = createVAppBase(_targetVersion);
983 } catch (MalformedURLException mue) {
984 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
985 throw (IOException) new IOException(err).initCause(mue);
989 // now re-download our control files; we download the digest first so that if it fails,
990 // our config file will still reference the old version and re-running the updater will
991 // start the whole process over again
992 downloadDigestFiles();
993 downloadConfigFile();
995 } catch (IOException ex) {
996 // if we are allowing offline execution, we want to allow the application to run in its
997 // current form rather than aborting the entire process; to do this, we delete the
998 // version.txt file and "trick" Getdown into thinking that it just needs to validate
999 // the application as is; next time the app runs when connected to the internet, it
1000 // will have to rediscover that it needs updating and reattempt to update itself
1001 if (_allowOffline) {
1002 log.warning("Failed to update digest files. Attempting offline operaton.", ex);
1003 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
1004 log.warning("Deleting version.txt failed. This probably isn't going to work.");
1013 * Invokes the process associated with this application definition.
1015 * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
1018 public Process createProcess (boolean optimum)
1021 ArrayList<String> args = new ArrayList<>();
1023 // reconstruct the path to the JVM
1024 args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
1026 // check whether we're using -jar mode or -classpath mode
1027 boolean dashJarMode = MANIFEST_CLASS.equals(_class);
1029 // add the -classpath arguments if we're not in -jar mode
1030 ClassPath classPath = PathBuilder.buildClassPath(this);
1032 args.add("-classpath");
1033 args.add(classPath.asArgumentString());
1036 // we love our Mac users, so we do nice things to preserve our application identity
1037 if (LaunchUtil.isMacOS()) {
1038 args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1039 args.add("-Xdock:name=" + _dockName);
1042 // pass along our proxy settings
1044 if ((proxyHost = System.getProperty("http.proxyHost")) != null) {
1045 args.add("-Dhttp.proxyHost=" + proxyHost);
1046 args.add("-Dhttp.proxyPort=" + System.getProperty("http.proxyPort"));
1047 args.add("-Dhttps.proxyHost=" + proxyHost);
1048 args.add("-Dhttps.proxyPort=" + System.getProperty("http.proxyPort"));
1051 // add the marker indicating the app is running in getdown
1052 args.add("-D" + Properties.GETDOWN + "=true");
1054 // set the native library path if we have native resources
1055 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1056 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1057 if (javaLibPath != null) {
1058 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1061 // pass along any pass-through arguments
1062 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1063 String key = (String)entry.getKey();
1064 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1065 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1066 args.add("-D" + key + "=" + entry.getValue());
1070 // add the JVM arguments
1071 for (String string : _jvmargs) {
1072 args.add(processArg(string));
1075 // add the optimum arguments if requested and available
1076 if (optimum && _optimumJvmArgs != null) {
1077 for (String string : _optimumJvmArgs) {
1078 args.add(processArg(string));
1082 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1083 for (String string : _txtJvmArgs) {
1084 args.add(processArg(string));
1087 // if we're in -jar mode add those arguments, otherwise add the app class name
1090 args.add(classPath.asArgumentString());
1095 // almost finally check the startup file arguments
1096 for (File f : _startupFiles) {
1097 _appargs.add(f.getAbsolutePath());
1098 break; // Only add one file to open
1101 // check if one arg with recognised extension
1102 if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1103 String filename = _appargs.get(0);
1105 int j = filename.lastIndexOf('.');
1107 ext = filename.substring(j+1);
1109 if (LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase())) {
1110 // this file extension should have been dealt with in Getdown class
1112 _appargs.add(0, "-open");
1116 // finally add the application arguments
1117 for (String string : _appargs) {
1118 args.add(processArg(string));
1121 String[] envp = createEnvironment();
1122 String[] sargs = args.toArray(new String[args.size()]);
1123 log.info("Running " + StringUtil.join(sargs, "\n "));
1125 return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1129 * If the application provided environment variables, combine those with the current
1130 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1131 * If the application didn't provide any environment variables, null is returned to just use
1132 * the existing environment.
1134 protected String[] createEnvironment ()
1136 List<String> envvar = new ArrayList<>();
1137 fillAssignmentListFromPairs("env.txt", envvar);
1138 if (envvar.isEmpty()) {
1139 log.info("Didn't find any custom environment variables, not setting any.");
1143 List<String> envAssignments = new ArrayList<>();
1144 for (String assignment : envvar) {
1145 envAssignments.add(processArg(assignment));
1147 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1148 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1150 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1151 log.info("Environment " + StringUtil.join(envp, "\n "));
1156 * Runs this application directly in the current VM.
1158 public void invokeDirect () throws IOException
1160 ClassPath classPath = PathBuilder.buildClassPath(this);
1161 URL[] jarUrls = classPath.asUrls();
1163 // create custom class loader
1164 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1165 @Override protected PermissionCollection getPermissions (CodeSource code) {
1166 Permissions perms = new Permissions();
1167 perms.add(new AllPermission());
1171 Thread.currentThread().setContextClassLoader(loader);
1173 log.info("Configured URL class loader:");
1174 for (URL url : jarUrls) log.info(" " + url);
1176 // configure any system properties that we can
1177 for (String jvmarg : _jvmargs) {
1178 if (jvmarg.startsWith("-D")) {
1179 jvmarg = processArg(jvmarg.substring(2));
1180 int eqidx = jvmarg.indexOf("=");
1182 log.warning("Bogus system property: '" + jvmarg + "'?");
1184 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1189 // pass along any pass-through arguments
1190 Map<String, String> passProps = new HashMap<>();
1191 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1192 String key = (String)entry.getKey();
1193 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1194 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1195 passProps.put(key, (String)entry.getValue());
1198 // we can't set these in the above loop lest we get a ConcurrentModificationException
1199 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1200 System.setProperty(entry.getKey(), entry.getValue());
1203 // prepare our app arguments
1204 String[] args = new String[_appargs.size()];
1205 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1208 log.info("Loading " + _class);
1209 Class<?> appclass = loader.loadClass(_class);
1210 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1211 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1212 main.invoke(null, new Object[] { args });
1213 } catch (Exception e) {
1214 log.warning("Failure invoking app main", e);
1218 /** Replaces the application directory and version in any argument. */
1219 protected String processArg (String arg)
1221 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1222 arg = arg.replace("%VERSION%", String.valueOf(_version));
1224 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1225 // from the environment
1226 if (arg.contains(ENV_VAR_PREFIX)) {
1227 StringBuffer sb = new StringBuffer();
1228 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1229 while (matcher.find()) {
1230 String varName = matcher.group(1), varValue = System.getenv(varName);
1231 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1232 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1234 matcher.appendTail(sb);
1235 arg = sb.toString();
1242 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1243 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1244 * whether or not the application needs to be updated or whether we can proceed to verification
1247 * @return true if the application needs to be updated, false if it is up to date and can be
1248 * verified and executed.
1250 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1253 public boolean verifyMetadata (StatusDisplay status)
1256 log.info("Verifying application: " + _vappbase);
1257 log.info("Version: " + _version);
1258 log.info("Class: " + _class);
1260 // this will read in the contents of the digest file and validate itself
1262 _digest = new Digest(getAppDir(), _strictComments);
1263 } catch (IOException ioe) {
1264 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1267 // if we have no version, then we are running in unversioned mode so we need to download
1268 // our digest.txt file on every invocation
1269 if (_version == -1) {
1270 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1271 // resources as one or more of them have also changed
1272 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1274 status.updateStatus("m.checking");
1275 downloadDigestFiles();
1276 _digest = new Digest(getAppDir(), _strictComments);
1277 if (!olddig.equals(_digest.getMetaDigest())) {
1278 log.info("Unversioned digest changed. Revalidating...");
1279 status.updateStatus("m.validating");
1280 clearValidationMarkers();
1282 } catch (IOException ioe) {
1283 log.warning("Failed to refresh non-versioned digest: " +
1284 ioe.getMessage() + ". Proceeding...");
1288 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1289 // redownload the digest file and give it another good college try; this time we allow
1290 // exceptions to propagate up to the caller as there is nothing else we can do
1291 if (_digest == null) {
1292 status.updateStatus("m.updating_metadata");
1293 downloadDigestFiles();
1294 _digest = new Digest(getAppDir(), _strictComments);
1297 // now verify the contents of our main config file
1298 Resource crsrc = getConfigResource();
1299 if (!_digest.validateResource(crsrc, null)) {
1300 status.updateStatus("m.updating_metadata");
1301 // attempt to redownload both of our metadata files; again we pass errors up to our
1302 // caller because there's nothing we can do to automatically recover
1303 downloadConfigFile();
1304 downloadDigestFiles();
1305 _digest = new Digest(getAppDir(), _strictComments);
1306 // revalidate everything if we end up downloading new metadata
1307 clearValidationMarkers();
1308 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1309 if (_digest.validateResource(crsrc, null)) {
1312 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1313 "Blindly forging onward.");
1317 // start by assuming we are happy with our version
1318 _targetVersion = _version;
1320 // if we are a versioned application, read in the contents of the version.txt file
1321 // and/or check the latest config URL for a newer version
1322 if (_version != -1) {
1323 File vfile = getLocalPath(VERSION_FILE);
1324 long fileVersion = VersionUtil.readVersion(vfile);
1325 if (fileVersion != -1) {
1326 _targetVersion = fileVersion;
1329 if (_latest != null) {
1330 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1331 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1332 BufferedReader bin = new BufferedReader(reader)) {
1333 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1334 if (pair[0].equals("version")) {
1335 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1336 if (fileVersion != -1 && _targetVersion > fileVersion) {
1337 // replace the file with the newest version
1338 try (FileOutputStream fos = new FileOutputStream(vfile);
1339 PrintStream out = new PrintStream(fos)) {
1340 out.println(_targetVersion);
1346 } catch (Exception e) {
1347 log.warning("Unable to retrieve version from latest config file.", e);
1352 // finally let the caller know if we need an update
1353 return _version != _targetVersion;
1357 * Verifies the code and media resources associated with this application. A list of resources
1358 * that do not exist or fail the verification process will be returned. If all resources are
1359 * ready to go, null will be returned and the application is considered ready to run.
1361 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1362 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1363 * you have to take care to get back to your UI thread.
1364 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1365 * validated" resources filled in.
1366 * @param unpacked a set to populate with unpacked resources.
1367 * @param toInstall a list into which to add resources that need to be installed.
1368 * @param toDownload a list into which to add resources that need to be downloaded.
1370 public void verifyResources (
1371 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1372 Set<Resource> toInstall, Set<Resource> toDownload)
1373 throws InterruptedException
1375 // resources are verified on background threads supplied by the thread pool, and progress
1376 // is reported by posting runnable actions to the actions queue which is processed by the
1378 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1379 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1380 final int[] completed = new int[1];
1382 long start = System.currentTimeMillis();
1384 // obtain the sizes of the resources to validate
1385 List<Resource> rsrcs = getAllActiveResources();
1386 long[] sizes = new long[rsrcs.size()];
1388 for (int ii = 0; ii < sizes.length; ii++) {
1389 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1391 final ProgressObserver fobs = obs;
1392 // as long as we forward aggregated progress updates to the UI thread, having multiple
1393 // threads update a progress aggregator is "mostly" thread-safe
1394 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1395 public void progress (final int percent) {
1396 actions.add(new Runnable() {
1397 public void run () {
1398 fobs.progress(percent);
1404 final int[] fAlreadyValid = alreadyValid;
1405 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1406 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1407 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1409 for (int ii = 0; ii < sizes.length; ii++) {
1410 final Resource rsrc = rsrcs.get(ii);
1411 final int index = ii;
1412 exec.execute(new Runnable() {
1413 public void run () {
1414 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1415 unpackedAsync, toInstallAsync, toDownloadAsync);
1416 actions.add(new Runnable() {
1417 public void run () {
1425 while (completed[0] < rsrcs.size()) {
1426 // we should be getting progress completion updates WAY more often than one every
1427 // minute, so if things freeze up for 60 seconds, abandon ship
1428 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1434 toInstall.addAll(toInstallAsync);
1435 toDownload.addAll(toDownloadAsync);
1436 unpacked.addAll(unpackedAsync);
1438 long complete = System.currentTimeMillis();
1439 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1440 "duration", (complete-start) + "ms");
1443 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1444 Set<Resource> unpacked,
1445 Set<Resource> toInstall, Set<Resource> toDownload) {
1446 if (rsrc.isMarkedValid()) {
1447 if (alreadyValid != null) {
1455 if (_digest.validateResource(rsrc, obs)) {
1456 // if the resource has a _new file, add it to to-install list
1457 if (rsrc.getLocalNew().exists()) {
1458 toInstall.add(rsrc);
1467 } catch (Exception e) {
1468 log.info("Failure verifying resource. Requesting redownload...",
1469 "rsrc", rsrc, "error", e);
1474 toDownload.add(rsrc);
1478 * Unpacks the resources that require it (we know that they're valid).
1480 * @param unpacked a set of resources to skip because they're already unpacked.
1482 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1483 throws InterruptedException
1485 List<Resource> rsrcs = getActiveResources();
1487 // remove resources that we don't want to unpack
1488 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1489 Resource rsrc = it.next();
1490 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1495 // obtain the sizes of the resources to unpack
1496 long[] sizes = new long[rsrcs.size()];
1497 for (int ii = 0; ii < sizes.length; ii++) {
1498 sizes[ii] = rsrcs.get(ii).getLocal().length();
1501 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1502 for (int ii = 0; ii < sizes.length; ii++) {
1503 Resource rsrc = rsrcs.get(ii);
1504 ProgressObserver pobs = pagg.startElement(ii);
1507 } catch (IOException ioe) {
1508 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1515 * Clears all validation marker files.
1517 public void clearValidationMarkers ()
1519 clearValidationMarkers(getAllActiveResources().iterator());
1523 * Returns the version number for the application. Should only be called after successful
1524 * return of verifyMetadata.
1526 public long getVersion ()
1532 * Creates a versioned application base URL for the specified version.
1534 protected URL createVAppBase (long version)
1535 throws MalformedURLException
1537 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1538 return HostWhitelist.verify(new URL(url));
1542 * Clears all validation marker files for the resources in the supplied iterator.
1544 protected void clearValidationMarkers (Iterator<Resource> iter)
1546 while (iter.hasNext()) {
1547 iter.next().clearMarker();
1552 * Downloads a new copy of CONFIG_FILE.
1554 protected void downloadConfigFile ()
1557 downloadControlFile(CONFIG_FILE, 0);
1561 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1562 * we're not locking at all.
1564 public synchronized boolean lockForUpdates ()
1566 if (_lock != null && _lock.isValid()) {
1570 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1571 } catch (FileNotFoundException e) {
1572 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1576 _lock = _lockChannel.tryLock();
1577 } catch (IOException e) {
1578 log.warning("Unable to create lock", "message", e.getMessage(), e);
1580 } catch (OverlappingFileLockException e) {
1581 log.warning("The lock is held elsewhere in this JVM", e);
1584 log.info("Able to lock for updates: " + (_lock != null));
1585 return _lock != null;
1589 * Release gettingdown.lock
1591 public synchronized void releaseLock ()
1593 if (_lock != null) {
1594 log.info("Releasing lock");
1597 } catch (IOException e) {
1598 log.warning("Unable to release lock", "message", e.getMessage(), e);
1601 _lockChannel.close();
1602 } catch (IOException e) {
1603 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1605 _lockChannel = null;
1611 * Downloads the digest files and validates their signature.
1612 * @throws IOException
1614 protected void downloadDigestFiles ()
1617 for (int version = 1; version <= Digest.VERSION; version++) {
1618 downloadControlFile(Digest.digestFile(version), version);
1623 * Downloads a new copy of the specified control file, optionally validating its signature.
1624 * If the download is successful, moves it over the old file on the filesystem.
1626 * <p> TODO: Switch to PKCS #7 or CMS.
1628 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1629 * should indicate the version of the digest file being validated which indicates which
1630 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1632 protected void downloadControlFile (String path, int sigVersion)
1635 File target = downloadFile(path);
1637 if (sigVersion > 0) {
1638 if (_envc.certs.isEmpty()) {
1639 log.info("No signing certs, not verifying digest.txt", "path", path);
1642 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1643 byte[] signature = null;
1644 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1645 signature = StreamUtil.toByteArray(signatureStream);
1647 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1650 byte[] buffer = new byte[8192];
1651 int length, validated = 0;
1652 for (Certificate cert : _envc.certs) {
1653 try (FileInputStream dataInput = new FileInputStream(target)) {
1654 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1655 sig.initVerify(cert);
1656 while ((length = dataInput.read(buffer)) != -1) {
1657 sig.update(buffer, 0, length);
1660 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1661 log.info("Signature does not match", "cert", cert.getPublicKey());
1664 log.info("Signature matches", "cert", cert.getPublicKey());
1668 } catch (IOException ioe) {
1669 log.warning("Failure validating signature of " + target + ": " + ioe);
1671 } catch (GeneralSecurityException gse) {
1677 // if we couldn't find a key that validates our digest, we are the hosed!
1678 if (validated == 0) {
1679 // delete the temporary digest file as we know it is invalid
1680 FileUtil.deleteHarder(target);
1681 throw new IOException("m.corrupt_digest_signature_error");
1686 // now move the temporary file over the original
1687 File original = getLocalPath(path);
1688 if (!FileUtil.renameTo(target, original)) {
1689 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1694 * Download a path to a temporary file, returning a {@link File} instance with the path
1697 protected File downloadFile (String path)
1700 File target = getLocalPath(path + "_new");
1702 URL targetURL = null;
1704 targetURL = getRemoteURL(path);
1705 } catch (Exception e) {
1706 log.warning("Requested to download invalid control file",
1707 "appbase", _vappbase, "path", path, "error", e);
1708 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1711 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1713 // stream the URL into our temporary file
1714 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1715 // we have to tell Java not to use caches here, otherwise it will cache any request for
1716 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1717 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1718 // about it; turning off caches is not a performance concern, because when Getdown asks
1719 // to download a file, it expects it to come over the wire, not from a cache
1720 uconn.setUseCaches(false);
1721 uconn.setRequestProperty("Accept-Encoding", "gzip");
1722 try (InputStream fin = uconn.getInputStream()) {
1723 String encoding = uconn.getContentEncoding();
1724 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1725 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1726 try (FileOutputStream fout = new FileOutputStream(target)) {
1727 StreamUtil.copy(fin2, fout);
1735 /** Helper function for creating {@link Resource} instances. */
1736 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1737 throws MalformedURLException
1739 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1742 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1743 protected static void addAll (String[] values, List<String> target) {
1744 if (values != null) {
1745 for (String value : values) {
1752 * Make an immutable List from the specified int array.
1754 public static List<Integer> intsToList (int[] values)
1756 List<Integer> list = new ArrayList<>(values.length);
1757 for (int val : values) {
1760 return Collections.unmodifiableList(list);
1764 * Make an immutable List from the specified String array.
1766 public static List<String> stringsToList (String[] values)
1768 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1771 /** Used to parse resources with the specified name. */
1772 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1773 List<Resource> list)
1775 String[] rsrcs = config.getMultiValue(name);
1776 if (rsrcs == null) {
1779 for (String rsrc : rsrcs) {
1781 list.add(createResource(rsrc, attrs));
1782 } catch (Exception e) {
1783 log.warning("Invalid resource '" + rsrc + "'. " + e);
1788 /** Possibly generates and returns a google analytics tracking cookie. */
1789 protected String getGATrackingCode ()
1791 if (_trackingGAHash == null) {
1794 long time = System.currentTimeMillis() / 1000;
1795 if (_trackingStart == 0) {
1796 _trackingStart = time;
1798 if (_trackingId == 0) {
1799 int low = 100000000, high = 1000000000;
1800 _trackingId = low + _rando.nextInt(high-low);
1802 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1803 cookie.append(".").append(_trackingId);
1804 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1805 cookie.append(".").append(time).append(".1%3B%2B");
1806 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1807 cookie.append(_trackingStart).append(".1.1.");
1808 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1809 int low = 1000000000, high = 2000000000;
1810 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1811 return cookie.toString();
1815 * Encodes a path for use in a URL.
1817 protected static String encodePath (String path)
1820 // we want to keep slashes because we're encoding an entire path; also we need to turn
1821 // + into %20 because web servers don't like + in paths or file names, blah
1822 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1823 } catch (UnsupportedEncodingException ue) {
1824 log.warning("Failed to URL encode " + path + ": " + ue);
1829 protected File getLocalPath (File appdir, String path)
1831 return new File(appdir, path);
1834 public static void setStartupFilesFromParameterString(String p) {
1835 // multiple files *might* be passed in as space separated quoted filenames
1837 if (!StringUtil.isBlank(p)) {
1839 // split quoted params or treat as single string array
1840 if (p.startsWith(q) && p.endsWith(q)) {
1841 // this fails if, e.g.
1842 // p=q("stupidfilename\" " "otherfilename")
1843 // let's hope no-one ever ends a filename with '" '
1844 filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1846 // single unquoted filename
1847 filenames = new String[]{p};
1850 // check for locator file. Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1851 String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
1853 !StringUtil.isBlank(locatorFilename)
1854 && locatorFilename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)
1856 setLocatorFile(locatorFilename);
1857 // remove the locator filename from the filenames array
1858 String[] otherFilenames = new String[filenames.length - 1];
1859 System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
1860 filenames = otherFilenames;
1863 for (int i = 0; i < filenames.length; i++) {
1864 String filename = filenames[i];
1865 // skip any other locator files in a multiple file list
1866 if (! filename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
1867 addStartupFile(filename);
1873 public static void setLocatorFile(String filename) {
1874 _locatorFile = new File(filename);
1877 public static void addStartupFile(String filename) {
1878 _startupFiles.add(new File(filename));
1881 private Config createLocatorConfig(Config.ParseOpts opts) {
1882 if (_locatorFile == null) {
1886 Config locatorConfig = null;
1889 Config tmpConfig = null;
1890 Map<String, Object> tmpData = new HashMap<>();
1891 if (_locatorFile.exists()) {
1892 tmpConfig = Config.parseConfig(_locatorFile, opts);
1893 // appbase is sanitised in HostWhitelist
1894 Map<String, Object> tmpConfigData = tmpConfig.getData();
1895 if (tmpConfig != null) {
1896 for (Map.Entry<String, Object> entry : tmpConfigData.entrySet()) {
1897 String key = entry.getKey();
1898 Object value = entry.getValue();
1899 String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
1900 if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
1901 tmpData.put(key, value);
1905 log.warning("Error occurred reading config file", "file", _locatorFile);
1908 log.warning("Given locator file does not exist", "file", _locatorFile);
1911 locatorConfig = new Config(tmpData);
1913 } catch (Exception e) {
1914 log.warning("Failure reading locator file", "file", _locatorFile, e);
1917 log.info("Returning locatorConfig", locatorConfig);
1919 return locatorConfig;
1922 public String getAppbase() {
1926 protected final EnvConfig _envc;
1927 protected File _config;
1928 protected Digest _digest;
1930 protected long _version = -1;
1931 protected long _targetVersion = -1;
1932 protected String _appbase;
1933 protected URL _vappbase;
1934 protected URL _latest;
1935 protected String _class;
1936 protected String _dockName;
1937 protected String _dockIconPath;
1938 protected boolean _strictComments;
1939 protected boolean _windebug;
1940 protected boolean _allowOffline;
1941 protected int _maxConcDownloads;
1943 protected String _trackingURL;
1944 protected Set<Integer> _trackingPcts;
1945 protected String _trackingCookieName;
1946 protected String _trackingCookieProperty;
1947 protected String _trackingURLSuffix;
1948 protected String _trackingGAHash;
1949 protected long _trackingStart;
1950 protected int _trackingId;
1952 protected String _javaVersionProp = "java.version";
1953 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
1954 protected long _javaMinVersion, _javaMaxVersion;
1955 protected boolean _javaExactVersionRequired;
1956 protected String _javaLocation;
1958 protected List<Resource> _codes = new ArrayList<>();
1959 protected List<Resource> _resources = new ArrayList<>();
1961 protected boolean _useCodeCache;
1962 protected int _codeCacheRetentionDays;
1964 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
1965 protected Map<String,Boolean> _auxactive = new HashMap<>();
1967 protected List<String> _jvmargs = new ArrayList<>();
1968 protected List<String> _appargs = new ArrayList<>();
1970 protected String[] _optimumJvmArgs;
1972 protected List<String> _txtJvmArgs = new ArrayList<>();
1974 /** If a warning has been issued about not being able to set modtimes. */
1975 protected boolean _warnedAboutSetLastModified;
1977 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
1978 protected FileLock _lock;
1980 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
1981 protected FileChannel _lockChannel;
1983 protected Random _rando = new Random();
1985 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
1987 protected static final String ENV_VAR_PREFIX = "%ENV.";
1988 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
1990 protected static File _locatorFile;
1991 protected static List<File> _startupFiles = new ArrayList<>();
1992 public static final String LOCATOR_FILE_EXTENSION = "jvl";