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 keepOnTop;
151 /** Whether to display the appbase. */
152 public final boolean displayAppbase;
154 /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
155 * flashing up on the screen and immediately disappearing, which can be confusing to the
157 public final int minShowSeconds;
159 /** The global percentages for each step. A step may have more than one, and
160 * the lowest reasonable one is used if a step is revisited. */
161 public final Map<Step, List<Integer>> stepPercentages;
163 /** Generates a string representation of this instance. */
165 public String toString ()
167 return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage + ", instant_bg=" + instantBackgroundImage +
168 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
169 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
170 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
171 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
172 ", hideProgressText=" + hideProgressText + ", keepOnTop=" + keepOnTop + ", minShow=" + minShowSeconds + "]";
175 public UpdateInterface (Config config)
177 this.name = config.getString("ui.name");
178 this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
179 this.progressText = config.getColor("ui.progress_text", Color.BLACK);
180 this.hideProgressText = config.getBoolean("ui.hide_progress_text");
181 this.keepOnTop = config.getBoolean("ui.keep_on_top");
182 this.displayAppbase = config.getBoolean("ui.display_appbase");
183 this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
184 this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
185 this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
186 this.statusText = config.getColor("ui.status_text", Color.BLACK);
187 this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
188 this.hideDecorations = config.getBoolean("ui.hide_decorations");
189 this.backgroundImage = config.getString("ui.background_image");
190 this.instantBackgroundImage = config.getString("ui.instant_background_image");
191 // default to black or white bg color, depending on the brightness of the progressText
192 int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
193 Color.BLACK : Color.WHITE;
194 this.background = config.getColor("ui.background", defaultBackground);
195 this.progressImage = config.getString("ui.progress_image");
196 this.rotatingBackgrounds = stringsToList(
197 config.getMultiValue("ui.rotating_background"));
198 this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
199 this.errorBackground = config.getString("ui.error_background");
201 // On an installation error, where do we point the user.
202 String installError = config.getUrl("ui.install_error", null);
203 this.installError = (installError == null) ?
204 "m.default_install_error" : MessageUtil.taint(installError);
206 // the patch notes bits
207 this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
208 this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
210 // step progress percentage (defaults and then customized values)
211 EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
212 for (Step step : Step.values()) {
213 stepPercentages.put(step, step.defaultPercents);
215 for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
216 String spec = config.getString("ui.percents." + step.name());
219 stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
220 } catch (Exception e) {
221 log.warning("Failed to parse percentages for " + step + ": " + spec);
225 this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
230 * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
231 * take network actions.
233 public static interface StatusDisplay
235 /** Requests that the specified status message be displayed. */
236 public void updateStatus (String message);
240 * Contains metadata for an auxiliary resource group.
242 public static class AuxGroup {
243 public final String name;
244 public final List<Resource> codes;
245 public final List<Resource> rsrcs;
247 public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
249 this.codes = Collections.unmodifiableList(codes);
250 this.rsrcs = Collections.unmodifiableList(rsrcs);
254 /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
255 * the application instance. Yes this is a public mutable field, no I'm not going to create a
256 * getter and setter just to pretend like that's not the case. */
257 public Proxy proxy = Proxy.NO_PROXY;
260 * Creates an application instance which records the location of the <code>getdown.txt</code>
261 * configuration file from the supplied application directory.
264 public Application (EnvConfig envc) {
266 _config = getLocalPath(envc.appDir, CONFIG_FILE);
270 * Returns the configured application directory.
272 public File getAppDir () {
277 * Returns whether the application should cache code resources prior to launching the
280 public boolean useCodeCache ()
282 return _useCodeCache;
286 * Returns the number of days a cached code resource is allowed to stay unused before it
287 * becomes eligible for deletion.
289 public int getCodeCacheRetentionDays ()
291 return _codeCacheRetentionDays;
295 * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
296 * app files from its hosting server.
298 public int maxConcurrentDownloads () {
299 return _maxConcDownloads;
303 * Returns a resource that refers to the application configuration file itself.
305 public Resource getConfigResource ()
308 return createResource(CONFIG_FILE, Resource.NORMAL);
309 } catch (Exception e) {
310 throw new RuntimeException("Invalid appbase '" + _vappbase + "'.", e);
315 * Returns a list of the code {@link Resource} objects used by this application.
317 public List<Resource> getCodeResources ()
323 * Returns a list of the non-code {@link Resource} objects used by this application.
325 public List<Resource> getResources ()
331 * Returns the digest of the given {@code resource}.
333 public String getDigest (Resource resource)
335 return _digest.getDigest(resource);
339 * Returns a list of all the active {@link Resource} objects used by this application (code and
342 public List<Resource> getAllActiveResources ()
344 List<Resource> allResources = new ArrayList<>();
345 allResources.addAll(getActiveCodeResources());
346 allResources.addAll(getActiveResources());
351 * Returns the auxiliary resource group with the specified name, or null.
353 public AuxGroup getAuxGroup (String name)
355 return _auxgroups.get(name);
359 * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
360 * resource group is a collection of resource files that are not downloaded unless a group
361 * token file is present in the application directory.
363 public Iterable<AuxGroup> getAuxGroups ()
365 return _auxgroups.values();
369 * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
370 * groups should be ignored, activated groups should be downloaded and patched along with the
373 public boolean isAuxGroupActive (String auxgroup)
375 Boolean active = _auxactive.get(auxgroup);
376 if (active == null) {
377 // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
379 active = getLocalPath(auxgroup + ".dat").exists();
380 _auxactive.put(auxgroup, active);
386 * Returns all main code resources and all code resources from active auxiliary resource groups.
388 public List<Resource> getActiveCodeResources ()
390 ArrayList<Resource> codes = new ArrayList<>();
391 codes.addAll(getCodeResources());
392 for (AuxGroup aux : getAuxGroups()) {
393 if (isAuxGroupActive(aux.name)) {
394 codes.addAll(aux.codes);
401 * Returns all resources indicated to contain native library files (.dll, .so, etc.).
403 public List<Resource> getNativeResources ()
405 List<Resource> natives = new ArrayList<>();
406 for (Resource resource: _resources) {
407 if (resource.isNative()) {
408 natives.add(resource);
415 * Returns all non-code resources and all resources from active auxiliary resource groups.
417 public List<Resource> getActiveResources ()
419 ArrayList<Resource> rsrcs = new ArrayList<>();
420 rsrcs.addAll(getResources());
421 for (AuxGroup aux : getAuxGroups()) {
422 if (isAuxGroupActive(aux.name)) {
423 rsrcs.addAll(aux.rsrcs);
430 * Returns a resource that can be used to download a patch file that will bring this
431 * application from its current version to the target version.
433 * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
434 * for the main application patch resource.
436 public Resource getPatchResource (String auxgroup)
438 if (_targetVersion <= _version) {
439 log.warning("Requested patch resource for up-to-date or non-versioned application",
440 "cvers", _version, "tvers", _targetVersion);
444 String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
445 String pfile = "patch" + infix + _version + ".dat";
447 URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
448 return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
449 } catch (Exception e) {
450 log.warning("Failed to create patch resource path",
451 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
457 * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
458 * place of the installed VM (in the case where the VM that launched Getdown does not meet the
459 * application's version requirements) or null if no VM is available for this platform.
461 public Resource getJavaVMResource ()
463 if (StringUtil.isBlank(_javaLocation)) {
467 String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
468 String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
469 log.info("vmfile is '"+vmfile+"'");
470 System.out.println("vmfile is '"+vmfile+"'");
472 URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
473 log.info("Attempting to fetch jvm at "+remote.toString());
474 System.out.println("Attempting to fetch jvm at "+remote.toString());
475 return new Resource(vmfile, remote, getLocalPath(vmfile),
476 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
477 } catch (Exception e) {
478 log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
479 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
480 System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
481 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
487 * Returns a resource that can be used to download an archive containing all files belonging to
490 public Resource getFullResource ()
492 String file = "full";
494 URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
495 return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
496 } catch (Exception e) {
497 log.warning("Failed to create full resource path",
498 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
504 * Returns the URL to use to report an initial download event. Returns null if no tracking
505 * start URL was configured for this application.
507 * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
509 public URL getTrackingURL (String event)
512 String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
513 String ga = getGATrackingCode();
514 return _trackingURL == null ? null :
515 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
516 } catch (MalformedURLException mue) {
517 log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
523 * Returns the URL to request to report that we have reached the specified percentage of our
524 * initial download. Returns null if no tracking request was configured for the specified
527 public URL getTrackingProgressURL (int percent)
529 if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
532 return getTrackingURL("pct" + percent);
536 * Returns the name of our tracking cookie or null if it was not set.
538 public String getTrackingCookieName ()
540 return _trackingCookieName;
544 * Returns the name of our tracking cookie system property or null if it was not set.
546 public String getTrackingCookieProperty ()
548 return _trackingCookieProperty;
552 * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
553 * for operation. The application base URL will be parsed first so that if there are errors
554 * discovered later, the caller can use the application base to download a new {@code
555 * getdown.txt} file and try again.
557 * @return a {@code Config} instance that contains information from the config file.
559 * @exception IOException thrown if there is an error reading the file or an error encountered
560 * during its parsing.
562 public Config init (boolean checkPlatform)
565 Config config = null;
566 File cfgfile = _config;
567 Config.ParseOpts opts = Config.createOpts(checkPlatform);
569 // if we have a configuration file, read the data from it
570 if (cfgfile.exists()) {
571 config = Config.parseConfig(_config, opts);
573 // otherwise, try reading data from our backup config file; thanks to funny windows
574 // bullshit, we have to do this backup file fiddling in case we got screwed while
575 // updating getdown.txt during normal operation
576 else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
577 config = Config.parseConfig(cfgfile, opts);
579 // otherwise, issue a warning that we found no getdown file
581 log.info("Found no getdown.txt file", "appdir", getAppDir());
583 } catch (Exception e) {
584 log.warning("Failure reading config file", "file", _config, e);
587 // see if there's an override config from locator file
588 Config locatorConfig = createLocatorConfig(opts);
590 // merge the locator file config into config (or replace config with)
591 if (locatorConfig != null) {
592 if (config == null || locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_replace")) {
593 config = locatorConfig;
595 config.mergeConfig(locatorConfig, locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_merge"));
599 // if we failed to read our config file, check for an appbase specified via a system
600 // property; we can use that to bootstrap ourselves back into operation
601 if (config == null) {
602 String appbase = _envc.appBase;
603 log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
604 Map<String, Object> cdata = new HashMap<>();
605 cdata.put("appbase", appbase);
606 config = new Config(cdata);
609 // first determine our application base, this way if anything goes wrong later in the
610 // process, our caller can use the appbase to download a new configuration file
611 _appbase = config.getString("appbase");
613 // see if locatorConfig override
614 if (locatorConfig != null && !StringUtil.isBlank(locatorConfig.getString("appbase"))) {
615 _appbase = locatorConfig.getString("appbase");
618 if (_appbase == null) {
619 throw new RuntimeException("m.missing_appbase");
622 // check if we're overriding the domain in the appbase
623 _appbase = SysProps.overrideAppbase(_appbase);
625 // make sure there's a trailing slash
626 if (!_appbase.endsWith("/")) {
627 _appbase = _appbase + "/";
630 // extract our version information
631 _version = config.getLong("version", -1L);
633 // if we are a versioned deployment, create a versioned appbase
635 _vappbase = createVAppBase(_version);
636 } catch (MalformedURLException mue) {
637 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
638 throw (IOException) new IOException(err).initCause(mue);
641 // check for a latest config URL
642 String latest = config.getString("latest");
643 if (latest != null) {
644 if (latest.startsWith(_appbase)) {
645 latest = _appbase + latest.substring(_appbase.length());
647 latest = SysProps.replaceDomain(latest);
650 _latest = HostWhitelist.verify(new URL(latest));
651 } catch (MalformedURLException mue) {
652 log.warning("Invalid URL for latest attribute.", mue);
656 String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
658 // determine our application class name (use app-specific class _if_ one is provided)
659 _class = config.getString("class");
660 if (appPrefix.length() > 0) {
661 _class = config.getString(appPrefix + "class", _class);
663 if (_class == null) {
664 throw new IOException("m.missing_class");
667 // determine whether we want strict comments
668 _strictComments = config.getBoolean("strict_comments");
670 // check to see if we're using a custom java.version property and regex
671 _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
672 _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
674 // check to see if we require a particular JVM version and have a supplied JVM
675 _javaMinVersion = config.getLong("java_version", _javaMinVersion);
676 // we support java_min_version as an alias of java_version; it better expresses the check
677 // that's going on and better mirrors java_max_version
678 _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
679 // check to see if we require a particular max JVM version and have a supplied JVM
680 _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
681 // check to see if we require a particular JVM version and have a supplied JVM
682 _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
684 // this is a little weird, but when we're run from the digester, we see a String[] which
685 // contains java locations for all platforms which we can't grok, but the digester doesn't
686 // need to know about that; when we're run in a real application there will be only one!
687 Object javaloc = config.getRaw("java_location");
688 if (javaloc instanceof String) {
689 _javaLocation = (String)javaloc;
692 // determine whether we have any tracking configuration
693 _trackingURL = config.getString("tracking_url");
695 // check for tracking progress percent configuration
696 String trackPcts = config.getString("tracking_percents");
697 if (!StringUtil.isBlank(trackPcts)) {
698 _trackingPcts = new HashSet<>();
699 for (int pct : StringUtil.parseIntArray(trackPcts)) {
700 _trackingPcts.add(pct);
702 } else if (!StringUtil.isBlank(_trackingURL)) {
703 _trackingPcts = new HashSet<>();
704 _trackingPcts.add(50);
707 // Check for tracking cookie configuration
708 _trackingCookieName = config.getString("tracking_cookie_name");
709 _trackingCookieProperty = config.getString("tracking_cookie_property");
711 // Some app may need an extra suffix added to the tracking URL
712 _trackingURLSuffix = config.getString("tracking_url_suffix");
714 // Some app may need to generate google analytics code
715 _trackingGAHash = config.getString("tracking_ga_hash");
717 // clear our arrays as we may be reinitializing
725 // parse our code resources
726 if (config.getMultiValue("code") == null &&
727 config.getMultiValue("ucode") == null) {
728 throw new IOException("m.missing_code");
730 parseResources(config, "code", Resource.NORMAL, _codes);
731 parseResources(config, "ucode", Resource.UNPACK, _codes);
733 // parse our non-code resources
734 parseResources(config, "resource", Resource.NORMAL, _resources);
735 parseResources(config, "uresource", Resource.UNPACK, _resources);
736 parseResources(config, "xresource", Resource.EXEC, _resources);
737 parseResources(config, "presource", Resource.PRELOAD, _resources);
738 parseResources(config, "nresource", Resource.NATIVE, _resources);
740 // parse our auxiliary resource groups
741 for (String auxgroup : config.getList("auxgroups")) {
742 ArrayList<Resource> codes = new ArrayList<>();
743 parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
744 parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
745 ArrayList<Resource> rsrcs = new ArrayList<>();
746 parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
747 parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
748 parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
749 parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
750 parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
751 _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
754 // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
755 String[] jvmargs = config.getMultiValue("jvmarg");
756 addAll(jvmargs, _jvmargs);
757 if (appPrefix.length() > 0) {
758 jvmargs = config.getMultiValue(appPrefix + "jvmarg");
759 addAll(jvmargs, _jvmargs);
762 // see if a percentage of physical memory option exists
763 int jvmmempc = config.getInt("jvmmempc", -1);
764 // app_id prefixed setting overrides
765 if (appPrefix.length() > 0) {
766 jvmmempc = config.getInt(appPrefix + "jvmmempc", jvmmempc);
768 if (0 <= jvmmempc && jvmmempc <= 100) {
770 long maxMemLong = -1;
774 maxMemLong = MemorySetting.memPercent(jvmmempc);
775 } catch (Exception e)
778 } catch (Throwable t)
786 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
787 // remove other max heap size arg
788 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
789 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
793 addAll(maxMemHeapArg, _jvmargs);
797 } else if (jvmmempc != -1) {
798 System.out.println("'jvmmempc' value must be in range 0 to 100 (read as '"+Integer.toString(jvmmempc)+"')");
801 // get the set of optimum JVM arguments
802 _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
804 // transfer our application arguments
805 String[] appargs = config.getMultiValue(appPrefix + "apparg");
806 addAll(appargs, _appargs);
808 // add the launch specific application arguments
809 _appargs.addAll(_envc.appArgs);
811 // look for custom arguments
812 fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
814 // determine whether we want to allow offline operation (defaults to false)
815 _allowOffline = config.getBoolean("allow_offline");
817 // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
818 // obtain a thread dump of the running JVM
819 _windebug = getLocalPath("debug.txt").exists();
821 // whether to cache code resources and launch from cache
822 _useCodeCache = config.getBoolean("use_code_cache");
823 _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
825 // maximum simultaneous downloads
826 _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
827 SysProps.threadPoolSize()));
829 // extract some info used to configure our child process on macOS
830 _dockName = config.getString("ui.name");
831 _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
837 * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
839 protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
841 File pairFile = getLocalPath(pairLocation);
842 if (pairFile.exists()) {
844 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
845 for (String[] pair : args) {
846 if (pair[1].length() == 0) {
847 collector.add(pair[0]);
849 collector.add(pair[0] + "=" + pair[1]);
852 } catch (Throwable t) {
853 log.warning("Failed to parse '" + pairFile + "': " + t);
859 * Returns a URL from which the specified path can be fetched. Our application base URL is
860 * properly versioned and combined with the supplied path.
862 public URL getRemoteURL (String path)
863 throws MalformedURLException
865 return new URL(_vappbase, encodePath(path));
869 * Returns the local path to the specified resource.
871 public File getLocalPath (String path)
873 return getLocalPath(getAppDir(), path);
877 * Returns true if we either have no version requirement, are running in a JVM that meets our
878 * version requirements or have what appears to be a version of the JVM that meets our
881 public boolean haveValidJavaVersion ()
883 // if we're doing no version checking, then yay!
884 if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
887 // parse the version out of the java.version (or custom) system property
888 long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
890 log.info("Checking Java version", "current", version,
891 "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
893 // if we have an unpacked VM, check the 'release' file for its version
894 Resource vmjar = getJavaVMResource();
895 if (vmjar != null && vmjar.isMarkedValid()) {
896 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
897 File relfile = new File(vmdir, "release");
898 if (!relfile.exists()) {
899 log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
903 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
905 log.warning("Unable to read version from 'release' file. Assuming valid.");
910 log.info("Checking version of unpacked JVM [vers=" + version + "].");
913 if (_javaExactVersionRequired) {
914 if (version == _javaMinVersion) return true;
916 log.warning("An exact Java VM version is required.", "current", version,
917 "required", _javaMinVersion);
922 boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
923 boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
924 return minVersionOK && maxVersionOK;
926 } catch (RuntimeException re) {
927 // if we can't parse the java version we're in weird land and should probably just try
928 // our luck with what we've got rather than try to download a new jvm
929 log.warning("Unable to parse VM version, hoping for the best",
930 "error", re, "needed", _javaMinVersion);
936 * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
937 * whether the launch is successful and, if necessary, trying again without the optimum
940 public boolean hasOptimumJvmArgs ()
942 return _optimumJvmArgs != null;
946 * Returns true if the app should attempt to run even if we have no Internet connection.
948 public boolean allowOffline ()
950 return _allowOffline;
954 * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
955 * previous call to {@link #init}.
957 public void attemptRecovery (StatusDisplay status)
960 status.updateStatus("m.updating_metadata");
961 downloadConfigFile();
965 * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
966 * those for the target version of our application.
968 public void updateMetadata ()
972 // update our versioned application base with the target version
973 _vappbase = createVAppBase(_targetVersion);
974 } catch (MalformedURLException mue) {
975 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
976 throw (IOException) new IOException(err).initCause(mue);
980 // now re-download our control files; we download the digest first so that if it fails,
981 // our config file will still reference the old version and re-running the updater will
982 // start the whole process over again
983 downloadDigestFiles();
984 downloadConfigFile();
986 } catch (IOException ex) {
987 // if we are allowing offline execution, we want to allow the application to run in its
988 // current form rather than aborting the entire process; to do this, we delete the
989 // version.txt file and "trick" Getdown into thinking that it just needs to validate
990 // the application as is; next time the app runs when connected to the internet, it
991 // will have to rediscover that it needs updating and reattempt to update itself
993 log.warning("Failed to update digest files. Attempting offline operaton.", ex);
994 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
995 log.warning("Deleting version.txt failed. This probably isn't going to work.");
1004 * Invokes the process associated with this application definition.
1006 * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
1009 public Process createProcess (boolean optimum)
1012 ArrayList<String> args = new ArrayList<>();
1014 // reconstruct the path to the JVM
1015 args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
1017 // check whether we're using -jar mode or -classpath mode
1018 boolean dashJarMode = MANIFEST_CLASS.equals(_class);
1020 // add the -classpath arguments if we're not in -jar mode
1021 ClassPath classPath = PathBuilder.buildClassPath(this);
1023 args.add("-classpath");
1024 args.add(classPath.asArgumentString());
1027 // we love our Mac users, so we do nice things to preserve our application identity
1028 if (LaunchUtil.isMacOS()) {
1029 args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1030 args.add("-Xdock:name=" + _dockName);
1033 // pass along our proxy settings
1035 if ((proxyHost = System.getProperty("http.proxyHost")) != null) {
1036 args.add("-Dhttp.proxyHost=" + proxyHost);
1037 args.add("-Dhttp.proxyPort=" + System.getProperty("http.proxyPort"));
1038 args.add("-Dhttps.proxyHost=" + proxyHost);
1039 args.add("-Dhttps.proxyPort=" + System.getProperty("http.proxyPort"));
1042 // add the marker indicating the app is running in getdown
1043 args.add("-D" + Properties.GETDOWN + "=true");
1045 // set the native library path if we have native resources
1046 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1047 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1048 if (javaLibPath != null) {
1049 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1052 // pass along any pass-through arguments
1053 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1054 String key = (String)entry.getKey();
1055 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1056 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1057 args.add("-D" + key + "=" + entry.getValue());
1061 // add the JVM arguments
1062 for (String string : _jvmargs) {
1063 args.add(processArg(string));
1066 // add the optimum arguments if requested and available
1067 if (optimum && _optimumJvmArgs != null) {
1068 for (String string : _optimumJvmArgs) {
1069 args.add(processArg(string));
1073 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1074 for (String string : _txtJvmArgs) {
1075 args.add(processArg(string));
1078 // if we're in -jar mode add those arguments, otherwise add the app class name
1081 args.add(classPath.asArgumentString());
1086 // almost finally check the startup file arguments
1087 for (File f : _startupFiles) {
1088 _appargs.add(f.getAbsolutePath());
1089 break; // Only add one file to open
1092 // check if one arg with recognised extension
1093 if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1094 String filename = _appargs.get(0);
1096 int j = filename.lastIndexOf('.');
1098 ext = filename.substring(j+1);
1100 if (LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase())) {
1101 // this file extension should have been dealt with in Getdown class
1103 _appargs.add(0, "-open");
1107 // finally add the application arguments
1108 for (String string : _appargs) {
1109 args.add(processArg(string));
1112 String[] envp = createEnvironment();
1113 String[] sargs = args.toArray(new String[args.size()]);
1114 log.info("Running " + StringUtil.join(sargs, "\n "));
1116 return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1120 * If the application provided environment variables, combine those with the current
1121 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1122 * If the application didn't provide any environment variables, null is returned to just use
1123 * the existing environment.
1125 protected String[] createEnvironment ()
1127 List<String> envvar = new ArrayList<>();
1128 fillAssignmentListFromPairs("env.txt", envvar);
1129 if (envvar.isEmpty()) {
1130 log.info("Didn't find any custom environment variables, not setting any.");
1134 List<String> envAssignments = new ArrayList<>();
1135 for (String assignment : envvar) {
1136 envAssignments.add(processArg(assignment));
1138 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1139 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1141 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1142 log.info("Environment " + StringUtil.join(envp, "\n "));
1147 * Runs this application directly in the current VM.
1149 public void invokeDirect () throws IOException
1151 ClassPath classPath = PathBuilder.buildClassPath(this);
1152 URL[] jarUrls = classPath.asUrls();
1154 // create custom class loader
1155 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1156 @Override protected PermissionCollection getPermissions (CodeSource code) {
1157 Permissions perms = new Permissions();
1158 perms.add(new AllPermission());
1162 Thread.currentThread().setContextClassLoader(loader);
1164 log.info("Configured URL class loader:");
1165 for (URL url : jarUrls) log.info(" " + url);
1167 // configure any system properties that we can
1168 for (String jvmarg : _jvmargs) {
1169 if (jvmarg.startsWith("-D")) {
1170 jvmarg = processArg(jvmarg.substring(2));
1171 int eqidx = jvmarg.indexOf("=");
1173 log.warning("Bogus system property: '" + jvmarg + "'?");
1175 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1180 // pass along any pass-through arguments
1181 Map<String, String> passProps = new HashMap<>();
1182 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1183 String key = (String)entry.getKey();
1184 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1185 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1186 passProps.put(key, (String)entry.getValue());
1189 // we can't set these in the above loop lest we get a ConcurrentModificationException
1190 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1191 System.setProperty(entry.getKey(), entry.getValue());
1194 // prepare our app arguments
1195 String[] args = new String[_appargs.size()];
1196 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1199 log.info("Loading " + _class);
1200 Class<?> appclass = loader.loadClass(_class);
1201 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1202 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1203 main.invoke(null, new Object[] { args });
1204 } catch (Exception e) {
1205 log.warning("Failure invoking app main", e);
1209 /** Replaces the application directory and version in any argument. */
1210 protected String processArg (String arg)
1212 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1213 arg = arg.replace("%VERSION%", String.valueOf(_version));
1215 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1216 // from the environment
1217 if (arg.contains(ENV_VAR_PREFIX)) {
1218 StringBuffer sb = new StringBuffer();
1219 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1220 while (matcher.find()) {
1221 String varName = matcher.group(1), varValue = System.getenv(varName);
1222 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1223 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1225 matcher.appendTail(sb);
1226 arg = sb.toString();
1233 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1234 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1235 * whether or not the application needs to be updated or whether we can proceed to verification
1238 * @return true if the application needs to be updated, false if it is up to date and can be
1239 * verified and executed.
1241 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1244 public boolean verifyMetadata (StatusDisplay status)
1247 log.info("Verifying application: " + _vappbase);
1248 log.info("Version: " + _version);
1249 log.info("Class: " + _class);
1251 // this will read in the contents of the digest file and validate itself
1253 _digest = new Digest(getAppDir(), _strictComments);
1254 } catch (IOException ioe) {
1255 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1258 // if we have no version, then we are running in unversioned mode so we need to download
1259 // our digest.txt file on every invocation
1260 if (_version == -1) {
1261 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1262 // resources as one or more of them have also changed
1263 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1265 status.updateStatus("m.checking");
1266 downloadDigestFiles();
1267 _digest = new Digest(getAppDir(), _strictComments);
1268 if (!olddig.equals(_digest.getMetaDigest())) {
1269 log.info("Unversioned digest changed. Revalidating...");
1270 status.updateStatus("m.validating");
1271 clearValidationMarkers();
1273 } catch (IOException ioe) {
1274 log.warning("Failed to refresh non-versioned digest: " +
1275 ioe.getMessage() + ". Proceeding...");
1279 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1280 // redownload the digest file and give it another good college try; this time we allow
1281 // exceptions to propagate up to the caller as there is nothing else we can do
1282 if (_digest == null) {
1283 status.updateStatus("m.updating_metadata");
1284 downloadDigestFiles();
1285 _digest = new Digest(getAppDir(), _strictComments);
1288 // now verify the contents of our main config file
1289 Resource crsrc = getConfigResource();
1290 if (!_digest.validateResource(crsrc, null)) {
1291 status.updateStatus("m.updating_metadata");
1292 // attempt to redownload both of our metadata files; again we pass errors up to our
1293 // caller because there's nothing we can do to automatically recover
1294 downloadConfigFile();
1295 downloadDigestFiles();
1296 _digest = new Digest(getAppDir(), _strictComments);
1297 // revalidate everything if we end up downloading new metadata
1298 clearValidationMarkers();
1299 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1300 if (_digest.validateResource(crsrc, null)) {
1303 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1304 "Blindly forging onward.");
1308 // start by assuming we are happy with our version
1309 _targetVersion = _version;
1311 // if we are a versioned application, read in the contents of the version.txt file
1312 // and/or check the latest config URL for a newer version
1313 if (_version != -1) {
1314 File vfile = getLocalPath(VERSION_FILE);
1315 long fileVersion = VersionUtil.readVersion(vfile);
1316 if (fileVersion != -1) {
1317 _targetVersion = fileVersion;
1320 if (_latest != null) {
1321 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1322 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1323 BufferedReader bin = new BufferedReader(reader)) {
1324 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1325 if (pair[0].equals("version")) {
1326 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1327 if (fileVersion != -1 && _targetVersion > fileVersion) {
1328 // replace the file with the newest version
1329 try (FileOutputStream fos = new FileOutputStream(vfile);
1330 PrintStream out = new PrintStream(fos)) {
1331 out.println(_targetVersion);
1337 } catch (Exception e) {
1338 log.warning("Unable to retrieve version from latest config file.", e);
1343 // finally let the caller know if we need an update
1344 return _version != _targetVersion;
1348 * Verifies the code and media resources associated with this application. A list of resources
1349 * that do not exist or fail the verification process will be returned. If all resources are
1350 * ready to go, null will be returned and the application is considered ready to run.
1352 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1353 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1354 * you have to take care to get back to your UI thread.
1355 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1356 * validated" resources filled in.
1357 * @param unpacked a set to populate with unpacked resources.
1358 * @param toInstall a list into which to add resources that need to be installed.
1359 * @param toDownload a list into which to add resources that need to be downloaded.
1361 public void verifyResources (
1362 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1363 Set<Resource> toInstall, Set<Resource> toDownload)
1364 throws InterruptedException
1366 // resources are verified on background threads supplied by the thread pool, and progress
1367 // is reported by posting runnable actions to the actions queue which is processed by the
1369 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1370 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1371 final int[] completed = new int[1];
1373 long start = System.currentTimeMillis();
1375 // obtain the sizes of the resources to validate
1376 List<Resource> rsrcs = getAllActiveResources();
1377 long[] sizes = new long[rsrcs.size()];
1379 for (int ii = 0; ii < sizes.length; ii++) {
1380 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1382 final ProgressObserver fobs = obs;
1383 // as long as we forward aggregated progress updates to the UI thread, having multiple
1384 // threads update a progress aggregator is "mostly" thread-safe
1385 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1386 public void progress (final int percent) {
1387 actions.add(new Runnable() {
1388 public void run () {
1389 fobs.progress(percent);
1395 final int[] fAlreadyValid = alreadyValid;
1396 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1397 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1398 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1400 for (int ii = 0; ii < sizes.length; ii++) {
1401 final Resource rsrc = rsrcs.get(ii);
1402 final int index = ii;
1403 exec.execute(new Runnable() {
1404 public void run () {
1405 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1406 unpackedAsync, toInstallAsync, toDownloadAsync);
1407 actions.add(new Runnable() {
1408 public void run () {
1416 while (completed[0] < rsrcs.size()) {
1417 // we should be getting progress completion updates WAY more often than one every
1418 // minute, so if things freeze up for 60 seconds, abandon ship
1419 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1425 toInstall.addAll(toInstallAsync);
1426 toDownload.addAll(toDownloadAsync);
1427 unpacked.addAll(unpackedAsync);
1429 long complete = System.currentTimeMillis();
1430 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1431 "duration", (complete-start) + "ms");
1434 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1435 Set<Resource> unpacked,
1436 Set<Resource> toInstall, Set<Resource> toDownload) {
1437 if (rsrc.isMarkedValid()) {
1438 if (alreadyValid != null) {
1446 if (_digest.validateResource(rsrc, obs)) {
1447 // if the resource has a _new file, add it to to-install list
1448 if (rsrc.getLocalNew().exists()) {
1449 toInstall.add(rsrc);
1458 } catch (Exception e) {
1459 log.info("Failure verifying resource. Requesting redownload...",
1460 "rsrc", rsrc, "error", e);
1465 toDownload.add(rsrc);
1469 * Unpacks the resources that require it (we know that they're valid).
1471 * @param unpacked a set of resources to skip because they're already unpacked.
1473 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1474 throws InterruptedException
1476 List<Resource> rsrcs = getActiveResources();
1478 // remove resources that we don't want to unpack
1479 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1480 Resource rsrc = it.next();
1481 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1486 // obtain the sizes of the resources to unpack
1487 long[] sizes = new long[rsrcs.size()];
1488 for (int ii = 0; ii < sizes.length; ii++) {
1489 sizes[ii] = rsrcs.get(ii).getLocal().length();
1492 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1493 for (int ii = 0; ii < sizes.length; ii++) {
1494 Resource rsrc = rsrcs.get(ii);
1495 ProgressObserver pobs = pagg.startElement(ii);
1498 } catch (IOException ioe) {
1499 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1506 * Clears all validation marker files.
1508 public void clearValidationMarkers ()
1510 clearValidationMarkers(getAllActiveResources().iterator());
1514 * Returns the version number for the application. Should only be called after successful
1515 * return of verifyMetadata.
1517 public long getVersion ()
1523 * Creates a versioned application base URL for the specified version.
1525 protected URL createVAppBase (long version)
1526 throws MalformedURLException
1528 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1529 return HostWhitelist.verify(new URL(url));
1533 * Clears all validation marker files for the resources in the supplied iterator.
1535 protected void clearValidationMarkers (Iterator<Resource> iter)
1537 while (iter.hasNext()) {
1538 iter.next().clearMarker();
1543 * Downloads a new copy of CONFIG_FILE.
1545 protected void downloadConfigFile ()
1548 downloadControlFile(CONFIG_FILE, 0);
1552 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1553 * we're not locking at all.
1555 public synchronized boolean lockForUpdates ()
1557 if (_lock != null && _lock.isValid()) {
1561 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1562 } catch (FileNotFoundException e) {
1563 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1567 _lock = _lockChannel.tryLock();
1568 } catch (IOException e) {
1569 log.warning("Unable to create lock", "message", e.getMessage(), e);
1571 } catch (OverlappingFileLockException e) {
1572 log.warning("The lock is held elsewhere in this JVM", e);
1575 log.info("Able to lock for updates: " + (_lock != null));
1576 return _lock != null;
1580 * Release gettingdown.lock
1582 public synchronized void releaseLock ()
1584 if (_lock != null) {
1585 log.info("Releasing lock");
1588 } catch (IOException e) {
1589 log.warning("Unable to release lock", "message", e.getMessage(), e);
1592 _lockChannel.close();
1593 } catch (IOException e) {
1594 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1596 _lockChannel = null;
1602 * Downloads the digest files and validates their signature.
1603 * @throws IOException
1605 protected void downloadDigestFiles ()
1608 for (int version = 1; version <= Digest.VERSION; version++) {
1609 downloadControlFile(Digest.digestFile(version), version);
1614 * Downloads a new copy of the specified control file, optionally validating its signature.
1615 * If the download is successful, moves it over the old file on the filesystem.
1617 * <p> TODO: Switch to PKCS #7 or CMS.
1619 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1620 * should indicate the version of the digest file being validated which indicates which
1621 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1623 protected void downloadControlFile (String path, int sigVersion)
1626 File target = downloadFile(path);
1628 if (sigVersion > 0) {
1629 if (_envc.certs.isEmpty()) {
1630 log.info("No signing certs, not verifying digest.txt", "path", path);
1633 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1634 byte[] signature = null;
1635 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1636 signature = StreamUtil.toByteArray(signatureStream);
1638 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1641 byte[] buffer = new byte[8192];
1642 int length, validated = 0;
1643 for (Certificate cert : _envc.certs) {
1644 try (FileInputStream dataInput = new FileInputStream(target)) {
1645 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1646 sig.initVerify(cert);
1647 while ((length = dataInput.read(buffer)) != -1) {
1648 sig.update(buffer, 0, length);
1651 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1652 log.info("Signature does not match", "cert", cert.getPublicKey());
1655 log.info("Signature matches", "cert", cert.getPublicKey());
1659 } catch (IOException ioe) {
1660 log.warning("Failure validating signature of " + target + ": " + ioe);
1662 } catch (GeneralSecurityException gse) {
1668 // if we couldn't find a key that validates our digest, we are the hosed!
1669 if (validated == 0) {
1670 // delete the temporary digest file as we know it is invalid
1671 FileUtil.deleteHarder(target);
1672 throw new IOException("m.corrupt_digest_signature_error");
1677 // now move the temporary file over the original
1678 File original = getLocalPath(path);
1679 if (!FileUtil.renameTo(target, original)) {
1680 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1685 * Download a path to a temporary file, returning a {@link File} instance with the path
1688 protected File downloadFile (String path)
1691 File target = getLocalPath(path + "_new");
1693 URL targetURL = null;
1695 targetURL = getRemoteURL(path);
1696 } catch (Exception e) {
1697 log.warning("Requested to download invalid control file",
1698 "appbase", _vappbase, "path", path, "error", e);
1699 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1702 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1704 // stream the URL into our temporary file
1705 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1706 // we have to tell Java not to use caches here, otherwise it will cache any request for
1707 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1708 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1709 // about it; turning off caches is not a performance concern, because when Getdown asks
1710 // to download a file, it expects it to come over the wire, not from a cache
1711 uconn.setUseCaches(false);
1712 uconn.setRequestProperty("Accept-Encoding", "gzip");
1713 try (InputStream fin = uconn.getInputStream()) {
1714 String encoding = uconn.getContentEncoding();
1715 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1716 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1717 try (FileOutputStream fout = new FileOutputStream(target)) {
1718 StreamUtil.copy(fin2, fout);
1726 /** Helper function for creating {@link Resource} instances. */
1727 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1728 throws MalformedURLException
1730 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1733 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1734 protected static void addAll (String[] values, List<String> target) {
1735 if (values != null) {
1736 for (String value : values) {
1743 * Make an immutable List from the specified int array.
1745 public static List<Integer> intsToList (int[] values)
1747 List<Integer> list = new ArrayList<>(values.length);
1748 for (int val : values) {
1751 return Collections.unmodifiableList(list);
1755 * Make an immutable List from the specified String array.
1757 public static List<String> stringsToList (String[] values)
1759 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1762 /** Used to parse resources with the specified name. */
1763 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1764 List<Resource> list)
1766 String[] rsrcs = config.getMultiValue(name);
1767 if (rsrcs == null) {
1770 for (String rsrc : rsrcs) {
1772 list.add(createResource(rsrc, attrs));
1773 } catch (Exception e) {
1774 log.warning("Invalid resource '" + rsrc + "'. " + e);
1779 /** Possibly generates and returns a google analytics tracking cookie. */
1780 protected String getGATrackingCode ()
1782 if (_trackingGAHash == null) {
1785 long time = System.currentTimeMillis() / 1000;
1786 if (_trackingStart == 0) {
1787 _trackingStart = time;
1789 if (_trackingId == 0) {
1790 int low = 100000000, high = 1000000000;
1791 _trackingId = low + _rando.nextInt(high-low);
1793 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1794 cookie.append(".").append(_trackingId);
1795 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1796 cookie.append(".").append(time).append(".1%3B%2B");
1797 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1798 cookie.append(_trackingStart).append(".1.1.");
1799 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1800 int low = 1000000000, high = 2000000000;
1801 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1802 return cookie.toString();
1806 * Encodes a path for use in a URL.
1808 protected static String encodePath (String path)
1811 // we want to keep slashes because we're encoding an entire path; also we need to turn
1812 // + into %20 because web servers don't like + in paths or file names, blah
1813 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1814 } catch (UnsupportedEncodingException ue) {
1815 log.warning("Failed to URL encode " + path + ": " + ue);
1820 protected File getLocalPath (File appdir, String path)
1822 return new File(appdir, path);
1825 public static void setStartupFilesFromParameterString(String p) {
1826 // multiple files *might* be passed in as space separated quoted filenames
1828 if (!StringUtil.isBlank(p)) {
1830 // split quoted params or treat as single string array
1831 if (p.startsWith(q) && p.endsWith(q)) {
1832 // this fails if, e.g.
1833 // p=q("stupidfilename\" " "otherfilename")
1834 // let's hope no-one ever ends a filename with '" '
1835 filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1837 // single unquoted filename
1838 filenames = new String[]{p};
1841 // check for locator file. Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1842 String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
1844 !StringUtil.isBlank(locatorFilename)
1845 && locatorFilename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)
1847 setLocatorFile(locatorFilename);
1848 // remove the locator filename from the filenames array
1849 String[] otherFilenames = new String[filenames.length - 1];
1850 System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
1851 filenames = otherFilenames;
1854 for (int i = 0; i < filenames.length; i++) {
1855 String filename = filenames[i];
1856 // skip any other locator files in a multiple file list
1857 if (! filename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
1858 addStartupFile(filename);
1864 public static void setLocatorFile(String filename) {
1865 _locatorFile = new File(filename);
1868 public static void addStartupFile(String filename) {
1869 _startupFiles.add(new File(filename));
1872 private Config createLocatorConfig(Config.ParseOpts opts) {
1873 if (_locatorFile == null) {
1877 Config locatorConfig = null;
1880 Config tmpConfig = null;
1881 if (_locatorFile.exists()) {
1882 tmpConfig = Config.parseConfig(_locatorFile, opts);
1884 log.warning("Given locator file does not exist", "file", _locatorFile);
1887 // appbase is sanitised in HostWhitelist
1888 Map<String, Object> tmpData = new HashMap<>();
1889 for (Map.Entry<String, Object> entry : tmpConfig.getData().entrySet()) {
1890 String key = entry.getKey();
1891 Object value = entry.getValue();
1892 String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
1893 if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
1894 tmpData.put(key, value);
1897 locatorConfig = new Config(tmpData);
1899 } catch (Exception e) {
1900 log.warning("Failure reading locator file", "file", _locatorFile, e);
1903 log.info("Returning locatorConfig", locatorConfig);
1905 return locatorConfig;
1908 public String getAppbase() {
1912 protected final EnvConfig _envc;
1913 protected File _config;
1914 protected Digest _digest;
1916 protected long _version = -1;
1917 protected long _targetVersion = -1;
1918 protected String _appbase;
1919 protected URL _vappbase;
1920 protected URL _latest;
1921 protected String _class;
1922 protected String _dockName;
1923 protected String _dockIconPath;
1924 protected boolean _strictComments;
1925 protected boolean _windebug;
1926 protected boolean _allowOffline;
1927 protected int _maxConcDownloads;
1929 protected String _trackingURL;
1930 protected Set<Integer> _trackingPcts;
1931 protected String _trackingCookieName;
1932 protected String _trackingCookieProperty;
1933 protected String _trackingURLSuffix;
1934 protected String _trackingGAHash;
1935 protected long _trackingStart;
1936 protected int _trackingId;
1938 protected String _javaVersionProp = "java.version";
1939 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
1940 protected long _javaMinVersion, _javaMaxVersion;
1941 protected boolean _javaExactVersionRequired;
1942 protected String _javaLocation;
1944 protected List<Resource> _codes = new ArrayList<>();
1945 protected List<Resource> _resources = new ArrayList<>();
1947 protected boolean _useCodeCache;
1948 protected int _codeCacheRetentionDays;
1950 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
1951 protected Map<String,Boolean> _auxactive = new HashMap<>();
1953 protected List<String> _jvmargs = new ArrayList<>();
1954 protected List<String> _appargs = new ArrayList<>();
1956 protected String[] _optimumJvmArgs;
1958 protected List<String> _txtJvmArgs = new ArrayList<>();
1960 /** If a warning has been issued about not being able to set modtimes. */
1961 protected boolean _warnedAboutSetLastModified;
1963 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
1964 protected FileLock _lock;
1966 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
1967 protected FileChannel _lockChannel;
1969 protected Random _rando = new Random();
1971 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
1973 protected static final String ENV_VAR_PREFIX = "%ENV.";
1974 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
1976 protected static File _locatorFile;
1977 protected static List<File> _startupFiles = new ArrayList<>();
1978 public static final String LOCATOR_FILE_EXTENSION = "jvl";