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;
30 import com.threerings.getdown.util.*;
31 // avoid ambiguity with java.util.Base64 which we can't use as it's 1.8+
32 import com.threerings.getdown.util.Base64;
34 import com.threerings.getdown.data.EnvConfig;
35 import com.threerings.getdown.data.EnvConfig.Note;
37 import static com.threerings.getdown.Log.log;
38 import static java.nio.charset.StandardCharsets.UTF_8;
41 * Parses and provide access to the information contained in the <code>getdown.txt</code>
44 public class Application
46 /** The name of our configuration file. */
47 public static final String CONFIG_FILE = "getdown.txt";
49 /** The name of our target version file. */
50 public static final String VERSION_FILE = "version.txt";
52 /** System properties that are prefixed with this string will be passed through to our
53 * application (minus this prefix). */
54 public static final String PROP_PASSTHROUGH_PREFIX = "app.";
56 /** Suffix used for control file signatures. */
57 public static final String SIGNATURE_SUFFIX = ".sig";
59 /** A special classname that means 'use -jar code.jar' instead of a classname. */
60 public static final String MANIFEST_CLASS = "manifest";
62 /** Used to communicate information about the UI displayed when updating the application. */
63 public static final class UpdateInterface
66 * The major steps involved in updating, along with some arbitrary percentages
67 * assigned to them, to mark global progress.
72 VERIFY_METADATA(15, 65, 95),
75 VERIFY_RESOURCES(70, 97),
76 REDOWNLOAD_RESOURCES(90),
80 /** What is the final percent value for this step? */
81 public final List<Integer> defaultPercents;
83 /** Enum constructor. */
84 Step (int... percents)
86 this.defaultPercents = intsToList(percents);
90 /** The human readable name of this application. */
91 public final String name;
93 /** A background color, just in case. */
94 public final int background;
96 /** Background image specifiers for `RotatingBackgrounds`. */
97 public final List<String> rotatingBackgrounds;
99 /** The error background image for `RotatingBackgrounds`. */
100 public final String errorBackground;
102 /** The paths (relative to the appdir) of images for the window icon. */
103 public final List<String> iconImages;
105 /** The path (relative to the appdir) to a single background image. */
106 public final String backgroundImage;
108 /** The path (relative to the appdir) to the progress bar image. */
109 public final String progressImage;
111 /** The dimensions of the progress bar. */
112 public final Rectangle progress;
114 /** The color of the progress text. */
115 public final int progressText;
117 /** The color of the progress bar. */
118 public final int progressBar;
120 /** The dimensions of the status display. */
121 public final Rectangle status;
123 /** The color of the status text. */
124 public final int statusText;
126 /** The color of the text shadow. */
127 public final int textShadow;
129 /** Where to point the user for help with install errors. */
130 public final String installError;
132 /** The dimensions of the patch notes button. */
133 public final Rectangle patchNotes;
135 /** The patch notes URL. */
136 public final String patchNotesUrl;
138 /** Whether window decorations are hidden for the UI. */
139 public final boolean hideDecorations;
141 /** Whether progress text should be hidden or not. */
142 public final boolean hideProgressText;
144 /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
145 * flashing up on the screen and immediately disappearing, which can be confusing to the
147 public final int minShowSeconds;
149 /** The global percentages for each step. A step may have more than one, and
150 * the lowest reasonable one is used if a step is revisited. */
151 public final Map<Step, List<Integer>> stepPercentages;
153 /** Generates a string representation of this instance. */
155 public String toString ()
157 return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage +
158 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
159 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
160 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
161 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
162 ", hideProgressText" + hideProgressText + ", minShow=" + minShowSeconds + "]";
165 public UpdateInterface (Config config)
167 this.name = config.getString("ui.name");
168 this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
169 this.progressText = config.getColor("ui.progress_text", Color.BLACK);
170 this.hideProgressText = config.getBoolean("ui.hide_progress_text");
171 this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
172 this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
173 this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
174 this.statusText = config.getColor("ui.status_text", Color.BLACK);
175 this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
176 this.hideDecorations = config.getBoolean("ui.hide_decorations");
177 this.backgroundImage = config.getString("ui.background_image");
178 // default to black or white bg color, depending on the brightness of the progressText
179 int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
180 Color.BLACK : Color.WHITE;
181 this.background = config.getColor("ui.background", defaultBackground);
182 this.progressImage = config.getString("ui.progress_image");
183 this.rotatingBackgrounds = stringsToList(
184 config.getMultiValue("ui.rotating_background"));
185 this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
186 this.errorBackground = config.getString("ui.error_background");
188 // On an installation error, where do we point the user.
189 String installError = config.getUrl("ui.install_error", null);
190 this.installError = (installError == null) ?
191 "m.default_install_error" : MessageUtil.taint(installError);
193 // the patch notes bits
194 this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
195 this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
197 // step progress percentage (defaults and then customized values)
198 EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
199 for (Step step : Step.values()) {
200 stepPercentages.put(step, step.defaultPercents);
202 for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
203 String spec = config.getString("ui.percents." + step.name());
206 stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
207 } catch (Exception e) {
208 log.warning("Failed to parse percentages for " + step + ": " + spec);
212 this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
217 * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
218 * take network actions.
220 public static interface StatusDisplay
222 /** Requests that the specified status message be displayed. */
223 public void updateStatus (String message);
227 * Contains metadata for an auxiliary resource group.
229 public static class AuxGroup {
230 public final String name;
231 public final List<Resource> codes;
232 public final List<Resource> rsrcs;
234 public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
236 this.codes = Collections.unmodifiableList(codes);
237 this.rsrcs = Collections.unmodifiableList(rsrcs);
241 /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
242 * the application instance. Yes this is a public mutable field, no I'm not going to create a
243 * getter and setter just to pretend like that's not the case. */
244 public Proxy proxy = Proxy.NO_PROXY;
247 * Creates an application instance which records the location of the <code>getdown.txt</code>
248 * configuration file from the supplied application directory.
251 public Application (EnvConfig envc) {
253 _config = getLocalPath(envc.appDir, CONFIG_FILE);
257 * Returns the configured application directory.
259 public File getAppDir () {
264 * Returns whether the application should cache code resources prior to launching the
267 public boolean useCodeCache ()
269 return _useCodeCache;
273 * Returns the number of days a cached code resource is allowed to stay unused before it
274 * becomes eligible for deletion.
276 public int getCodeCacheRetentionDays ()
278 return _codeCacheRetentionDays;
282 * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
283 * app files from its hosting server.
285 public int maxConcurrentDownloads () {
286 return _maxConcDownloads;
290 * Returns a resource that refers to the application configuration file itself.
292 public Resource getConfigResource ()
295 return createResource(CONFIG_FILE, Resource.NORMAL);
296 } catch (Exception e) {
297 throw new RuntimeException("Invalid appbase '" + _vappbase + "'.", e);
302 * Returns a list of the code {@link Resource} objects used by this application.
304 public List<Resource> getCodeResources ()
310 * Returns a list of the non-code {@link Resource} objects used by this application.
312 public List<Resource> getResources ()
318 * Returns the digest of the given {@code resource}.
320 public String getDigest (Resource resource)
322 return _digest.getDigest(resource);
326 * Returns a list of all the active {@link Resource} objects used by this application (code and
329 public List<Resource> getAllActiveResources ()
331 List<Resource> allResources = new ArrayList<>();
332 allResources.addAll(getActiveCodeResources());
333 allResources.addAll(getActiveResources());
338 * Returns the auxiliary resource group with the specified name, or null.
340 public AuxGroup getAuxGroup (String name)
342 return _auxgroups.get(name);
346 * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
347 * resource group is a collection of resource files that are not downloaded unless a group
348 * token file is present in the application directory.
350 public Iterable<AuxGroup> getAuxGroups ()
352 return _auxgroups.values();
356 * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
357 * groups should be ignored, activated groups should be downloaded and patched along with the
360 public boolean isAuxGroupActive (String auxgroup)
362 Boolean active = _auxactive.get(auxgroup);
363 if (active == null) {
364 // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
366 active = getLocalPath(auxgroup + ".dat").exists();
367 _auxactive.put(auxgroup, active);
373 * Returns all main code resources and all code resources from active auxiliary resource groups.
375 public List<Resource> getActiveCodeResources ()
377 ArrayList<Resource> codes = new ArrayList<>();
378 codes.addAll(getCodeResources());
379 for (AuxGroup aux : getAuxGroups()) {
380 if (isAuxGroupActive(aux.name)) {
381 codes.addAll(aux.codes);
388 * Returns all resources indicated to contain native library files (.dll, .so, etc.).
390 public List<Resource> getNativeResources ()
392 List<Resource> natives = new ArrayList<>();
393 for (Resource resource: _resources) {
394 if (resource.isNative()) {
395 natives.add(resource);
402 * Returns all non-code resources and all resources from active auxiliary resource groups.
404 public List<Resource> getActiveResources ()
406 ArrayList<Resource> rsrcs = new ArrayList<>();
407 rsrcs.addAll(getResources());
408 for (AuxGroup aux : getAuxGroups()) {
409 if (isAuxGroupActive(aux.name)) {
410 rsrcs.addAll(aux.rsrcs);
417 * Returns a resource that can be used to download a patch file that will bring this
418 * application from its current version to the target version.
420 * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
421 * for the main application patch resource.
423 public Resource getPatchResource (String auxgroup)
425 if (_targetVersion <= _version) {
426 log.warning("Requested patch resource for up-to-date or non-versioned application",
427 "cvers", _version, "tvers", _targetVersion);
431 String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
432 String pfile = "patch" + infix + _version + ".dat";
434 URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
435 return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
436 } catch (Exception e) {
437 log.warning("Failed to create patch resource path",
438 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
444 * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
445 * place of the installed VM (in the case where the VM that launched Getdown does not meet the
446 * application's version requirements) or null if no VM is available for this platform.
448 public Resource getJavaVMResource ()
450 if (StringUtil.isBlank(_javaLocation)) {
454 String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
455 String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
456 log.info("vmfile is '"+vmfile+"'");
457 System.out.println("vmfile is '"+vmfile+"'");
459 URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
460 log.info("Attempting to fetch jvm at "+remote.toString());
461 System.out.println("Attempting to fetch jvm at "+remote.toString());
462 return new Resource(vmfile, remote, getLocalPath(vmfile),
463 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
464 } catch (Exception e) {
465 log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
466 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
467 System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
468 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
474 * Returns a resource that can be used to download an archive containing all files belonging to
477 public Resource getFullResource ()
479 String file = "full";
481 URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
482 return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
483 } catch (Exception e) {
484 log.warning("Failed to create full resource path",
485 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
491 * Returns the URL to use to report an initial download event. Returns null if no tracking
492 * start URL was configured for this application.
494 * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
496 public URL getTrackingURL (String event)
499 String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
500 String ga = getGATrackingCode();
501 return _trackingURL == null ? null :
502 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
503 } catch (MalformedURLException mue) {
504 log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
510 * Returns the URL to request to report that we have reached the specified percentage of our
511 * initial download. Returns null if no tracking request was configured for the specified
514 public URL getTrackingProgressURL (int percent)
516 if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
519 return getTrackingURL("pct" + percent);
523 * Returns the name of our tracking cookie or null if it was not set.
525 public String getTrackingCookieName ()
527 return _trackingCookieName;
531 * Returns the name of our tracking cookie system property or null if it was not set.
533 public String getTrackingCookieProperty ()
535 return _trackingCookieProperty;
539 * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
540 * for operation. The application base URL will be parsed first so that if there are errors
541 * discovered later, the caller can use the application base to download a new {@code
542 * getdown.txt} file and try again.
544 * @return a {@code Config} instance that contains information from the config file.
546 * @exception IOException thrown if there is an error reading the file or an error encountered
547 * during its parsing.
549 public Config init (boolean checkPlatform)
552 Config config = null;
553 File cfgfile = _config;
554 Config.ParseOpts opts = Config.createOpts(checkPlatform);
556 // if we have a configuration file, read the data from it
557 if (cfgfile.exists()) {
558 config = Config.parseConfig(_config, opts);
560 // otherwise, try reading data from our backup config file; thanks to funny windows
561 // bullshit, we have to do this backup file fiddling in case we got screwed while
562 // updating getdown.txt during normal operation
563 else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
564 config = Config.parseConfig(cfgfile, opts);
566 // otherwise, issue a warning that we found no getdown file
568 log.info("Found no getdown.txt file", "appdir", getAppDir());
570 } catch (Exception e) {
571 log.warning("Failure reading config file", "file", _config, e);
574 // see if there's an override config from locator file
575 Config locatorConfig = createLocatorConfig(opts);
577 // merge the locator file config into config (or replace config with)
578 if (locatorConfig != null) {
579 if (config == null || locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_replace")) {
580 config = locatorConfig;
582 config.mergeConfig(locatorConfig, locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_merge"));
586 // if we failed to read our config file, check for an appbase specified via a system
587 // property; we can use that to bootstrap ourselves back into operation
588 if (config == null) {
589 String appbase = _envc.appBase;
590 log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
591 Map<String, Object> cdata = new HashMap<>();
592 cdata.put("appbase", appbase);
593 config = new Config(cdata);
596 // first determine our application base, this way if anything goes wrong later in the
597 // process, our caller can use the appbase to download a new configuration file
598 _appbase = config.getString("appbase");
600 if (_appbase == null) {
601 throw new RuntimeException("m.missing_appbase");
604 // check if we're overriding the domain in the appbase
605 _appbase = SysProps.overrideAppbase(_appbase);
607 // make sure there's a trailing slash
608 if (!_appbase.endsWith("/")) {
609 _appbase = _appbase + "/";
612 // extract our version information
613 _version = config.getLong("version", -1L);
615 // if we are a versioned deployment, create a versioned appbase
617 _vappbase = createVAppBase(_version);
618 } catch (MalformedURLException mue) {
619 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
620 throw (IOException) new IOException(err).initCause(mue);
623 // check for a latest config URL
624 String latest = config.getString("latest");
625 if (latest != null) {
626 if (latest.startsWith(_appbase)) {
627 latest = _appbase + latest.substring(_appbase.length());
629 latest = SysProps.replaceDomain(latest);
632 _latest = HostWhitelist.verify(new URL(latest));
633 } catch (MalformedURLException mue) {
634 log.warning("Invalid URL for latest attribute.", mue);
638 String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
640 // determine our application class name (use app-specific class _if_ one is provided)
641 _class = config.getString("class");
642 if (appPrefix.length() > 0) {
643 _class = config.getString(appPrefix + "class", _class);
645 if (_class == null) {
646 throw new IOException("m.missing_class");
649 // determine whether we want strict comments
650 _strictComments = config.getBoolean("strict_comments");
652 // check to see if we're using a custom java.version property and regex
653 _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
654 _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
656 // check to see if we require a particular JVM version and have a supplied JVM
657 _javaMinVersion = config.getLong("java_version", _javaMinVersion);
658 // we support java_min_version as an alias of java_version; it better expresses the check
659 // that's going on and better mirrors java_max_version
660 _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
661 // check to see if we require a particular max JVM version and have a supplied JVM
662 _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
663 // check to see if we require a particular JVM version and have a supplied JVM
664 _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
666 // this is a little weird, but when we're run from the digester, we see a String[] which
667 // contains java locations for all platforms which we can't grok, but the digester doesn't
668 // need to know about that; when we're run in a real application there will be only one!
669 Object javaloc = config.getRaw("java_location");
670 if (javaloc instanceof String) {
671 _javaLocation = (String)javaloc;
674 // determine whether we have any tracking configuration
675 _trackingURL = config.getString("tracking_url");
677 // check for tracking progress percent configuration
678 String trackPcts = config.getString("tracking_percents");
679 if (!StringUtil.isBlank(trackPcts)) {
680 _trackingPcts = new HashSet<>();
681 for (int pct : StringUtil.parseIntArray(trackPcts)) {
682 _trackingPcts.add(pct);
684 } else if (!StringUtil.isBlank(_trackingURL)) {
685 _trackingPcts = new HashSet<>();
686 _trackingPcts.add(50);
689 // Check for tracking cookie configuration
690 _trackingCookieName = config.getString("tracking_cookie_name");
691 _trackingCookieProperty = config.getString("tracking_cookie_property");
693 // Some app may need an extra suffix added to the tracking URL
694 _trackingURLSuffix = config.getString("tracking_url_suffix");
696 // Some app may need to generate google analytics code
697 _trackingGAHash = config.getString("tracking_ga_hash");
699 // clear our arrays as we may be reinitializing
707 // parse our code resources
708 if (config.getMultiValue("code") == null &&
709 config.getMultiValue("ucode") == null) {
710 throw new IOException("m.missing_code");
712 parseResources(config, "code", Resource.NORMAL, _codes);
713 parseResources(config, "ucode", Resource.UNPACK, _codes);
715 // parse our non-code resources
716 parseResources(config, "resource", Resource.NORMAL, _resources);
717 parseResources(config, "uresource", Resource.UNPACK, _resources);
718 parseResources(config, "xresource", Resource.EXEC, _resources);
719 parseResources(config, "presource", Resource.PRELOAD, _resources);
720 parseResources(config, "nresource", Resource.NATIVE, _resources);
722 // parse our auxiliary resource groups
723 for (String auxgroup : config.getList("auxgroups")) {
724 ArrayList<Resource> codes = new ArrayList<>();
725 parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
726 parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
727 ArrayList<Resource> rsrcs = new ArrayList<>();
728 parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
729 parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
730 parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
731 parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
732 parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
733 _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
736 // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
737 String[] jvmargs = config.getMultiValue("jvmarg");
738 addAll(jvmargs, _jvmargs);
739 if (appPrefix.length() > 0) {
740 jvmargs = config.getMultiValue(appPrefix + "jvmarg");
741 addAll(jvmargs, _jvmargs);
744 // see if a percentage of physical memory option exists
745 int jvmmempc = config.getInt("jvmmempc", -1);
746 // app_id prefixed setting overrides
747 if (appPrefix.length() > 0) {
748 jvmmempc = config.getInt(appPrefix + "jvmmempc", jvmmempc);
750 if (0 <= jvmmempc && jvmmempc <= 100) {
751 final Object o = ManagementFactory.getOperatingSystemMXBean();
754 if (o instanceof OperatingSystemMXBean) {
755 final OperatingSystemMXBean osb = (OperatingSystemMXBean) o;
756 long physicalMem = osb.getTotalPhysicalMemorySize();
757 long requestedMem = physicalMem*jvmmempc/100;
758 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(requestedMem)};
759 // remove other max heap size arg
760 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
761 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
765 addAll(maxMemHeapArg, _jvmargs);
769 catch (NoClassDefFoundError e) {
770 // com.sun.management.OperatingSystemMXBean doesn't exist in this JVM
771 System.out.println("No com.sun.management.OperatingSystemMXBean. Cannot use 'jvmmempc'.");
773 } else if (jvmmempc != -1) {
774 System.out.println("'jvmmempc' value must be in range 0 to 100 (read as '"+Integer.toString(jvmmempc)+"')");
777 // get the set of optimum JVM arguments
778 _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
780 // transfer our application arguments
781 String[] appargs = config.getMultiValue(appPrefix + "apparg");
782 addAll(appargs, _appargs);
784 // add the launch specific application arguments
785 _appargs.addAll(_envc.appArgs);
787 // look for custom arguments
788 fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
790 // determine whether we want to allow offline operation (defaults to false)
791 _allowOffline = config.getBoolean("allow_offline");
793 // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
794 // obtain a thread dump of the running JVM
795 _windebug = getLocalPath("debug.txt").exists();
797 // whether to cache code resources and launch from cache
798 _useCodeCache = config.getBoolean("use_code_cache");
799 _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
801 // maximum simultaneous downloads
802 _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
803 SysProps.threadPoolSize()));
805 // extract some info used to configure our child process on macOS
806 _dockName = config.getString("ui.name");
807 _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
813 * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
815 protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
817 File pairFile = getLocalPath(pairLocation);
818 if (pairFile.exists()) {
820 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
821 for (String[] pair : args) {
822 if (pair[1].length() == 0) {
823 collector.add(pair[0]);
825 collector.add(pair[0] + "=" + pair[1]);
828 } catch (Throwable t) {
829 log.warning("Failed to parse '" + pairFile + "': " + t);
835 * Returns a URL from which the specified path can be fetched. Our application base URL is
836 * properly versioned and combined with the supplied path.
838 public URL getRemoteURL (String path)
839 throws MalformedURLException
841 return new URL(_vappbase, encodePath(path));
845 * Returns the local path to the specified resource.
847 public File getLocalPath (String path)
849 return getLocalPath(getAppDir(), path);
853 * Returns true if we either have no version requirement, are running in a JVM that meets our
854 * version requirements or have what appears to be a version of the JVM that meets our
857 public boolean haveValidJavaVersion ()
859 // if we're doing no version checking, then yay!
860 if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
863 // parse the version out of the java.version (or custom) system property
864 long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
866 log.info("Checking Java version", "current", version,
867 "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
869 // if we have an unpacked VM, check the 'release' file for its version
870 Resource vmjar = getJavaVMResource();
871 if (vmjar != null && vmjar.isMarkedValid()) {
872 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
873 File relfile = new File(vmdir, "release");
874 if (!relfile.exists()) {
875 log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
879 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
881 log.warning("Unable to read version from 'release' file. Assuming valid.");
886 log.info("Checking version of unpacked JVM [vers=" + version + "].");
889 if (_javaExactVersionRequired) {
890 if (version == _javaMinVersion) return true;
892 log.warning("An exact Java VM version is required.", "current", version,
893 "required", _javaMinVersion);
898 boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
899 boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
900 return minVersionOK && maxVersionOK;
902 } catch (RuntimeException re) {
903 // if we can't parse the java version we're in weird land and should probably just try
904 // our luck with what we've got rather than try to download a new jvm
905 log.warning("Unable to parse VM version, hoping for the best",
906 "error", re, "needed", _javaMinVersion);
912 * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
913 * whether the launch is successful and, if necessary, trying again without the optimum
916 public boolean hasOptimumJvmArgs ()
918 return _optimumJvmArgs != null;
922 * Returns true if the app should attempt to run even if we have no Internet connection.
924 public boolean allowOffline ()
926 return _allowOffline;
930 * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
931 * previous call to {@link #init}.
933 public void attemptRecovery (StatusDisplay status)
936 status.updateStatus("m.updating_metadata");
937 downloadConfigFile();
941 * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
942 * those for the target version of our application.
944 public void updateMetadata ()
948 // update our versioned application base with the target version
949 _vappbase = createVAppBase(_targetVersion);
950 } catch (MalformedURLException mue) {
951 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
952 throw (IOException) new IOException(err).initCause(mue);
956 // now re-download our control files; we download the digest first so that if it fails,
957 // our config file will still reference the old version and re-running the updater will
958 // start the whole process over again
959 downloadDigestFiles();
960 downloadConfigFile();
962 } catch (IOException ex) {
963 // if we are allowing offline execution, we want to allow the application to run in its
964 // current form rather than aborting the entire process; to do this, we delete the
965 // version.txt file and "trick" Getdown into thinking that it just needs to validate
966 // the application as is; next time the app runs when connected to the internet, it
967 // will have to rediscover that it needs updating and reattempt to update itself
969 log.warning("Failed to update digest files. Attempting offline operaton.", ex);
970 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
971 log.warning("Deleting version.txt failed. This probably isn't going to work.");
980 * Invokes the process associated with this application definition.
982 * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
985 public Process createProcess (boolean optimum)
988 ArrayList<String> args = new ArrayList<>();
990 // reconstruct the path to the JVM
991 args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
993 // check whether we're using -jar mode or -classpath mode
994 boolean dashJarMode = MANIFEST_CLASS.equals(_class);
996 // add the -classpath arguments if we're not in -jar mode
997 ClassPath classPath = PathBuilder.buildClassPath(this);
999 args.add("-classpath");
1000 args.add(classPath.asArgumentString());
1003 // we love our Mac users, so we do nice things to preserve our application identity
1004 if (LaunchUtil.isMacOS()) {
1005 args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1006 args.add("-Xdock:name=" + _dockName);
1009 // pass along our proxy settings
1011 if ((proxyHost = System.getProperty("http.proxyHost")) != null) {
1012 args.add("-Dhttp.proxyHost=" + proxyHost);
1013 args.add("-Dhttp.proxyPort=" + System.getProperty("http.proxyPort"));
1014 args.add("-Dhttps.proxyHost=" + proxyHost);
1015 args.add("-Dhttps.proxyPort=" + System.getProperty("http.proxyPort"));
1018 // add the marker indicating the app is running in getdown
1019 args.add("-D" + Properties.GETDOWN + "=true");
1021 // set the native library path if we have native resources
1022 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1023 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1024 if (javaLibPath != null) {
1025 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1028 // pass along any pass-through arguments
1029 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1030 String key = (String)entry.getKey();
1031 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1032 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1033 args.add("-D" + key + "=" + entry.getValue());
1037 // add the JVM arguments
1038 for (String string : _jvmargs) {
1039 args.add(processArg(string));
1042 // add the optimum arguments if requested and available
1043 if (optimum && _optimumJvmArgs != null) {
1044 for (String string : _optimumJvmArgs) {
1045 args.add(processArg(string));
1049 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1050 for (String string : _txtJvmArgs) {
1051 args.add(processArg(string));
1054 // if we're in -jar mode add those arguments, otherwise add the app class name
1057 args.add(classPath.asArgumentString());
1062 // almost finally check the startup file arguments
1063 for (File f : _startupFiles) {
1064 _appargs.add(f.getAbsolutePath());
1065 break; // Only add one file to open
1068 // check if one arg with recognised extension
1069 if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1070 String filename = _appargs.get(0);
1072 int j = filename.lastIndexOf('.');
1074 ext = filename.substring(j+1);
1076 if (LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase())) {
1077 // this file extension should have been dealt with in Getdown class
1079 _appargs.add(0, "-open");
1083 // finally add the application arguments
1084 for (String string : _appargs) {
1085 args.add(processArg(string));
1088 String[] envp = createEnvironment();
1089 String[] sargs = args.toArray(new String[args.size()]);
1090 log.info("Running " + StringUtil.join(sargs, "\n "));
1092 return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1096 * If the application provided environment variables, combine those with the current
1097 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1098 * If the application didn't provide any environment variables, null is returned to just use
1099 * the existing environment.
1101 protected String[] createEnvironment ()
1103 List<String> envvar = new ArrayList<>();
1104 fillAssignmentListFromPairs("env.txt", envvar);
1105 if (envvar.isEmpty()) {
1106 log.info("Didn't find any custom environment variables, not setting any.");
1110 List<String> envAssignments = new ArrayList<>();
1111 for (String assignment : envvar) {
1112 envAssignments.add(processArg(assignment));
1114 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1115 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1117 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1118 log.info("Environment " + StringUtil.join(envp, "\n "));
1123 * Runs this application directly in the current VM.
1125 public void invokeDirect () throws IOException
1127 ClassPath classPath = PathBuilder.buildClassPath(this);
1128 URL[] jarUrls = classPath.asUrls();
1130 // create custom class loader
1131 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1132 @Override protected PermissionCollection getPermissions (CodeSource code) {
1133 Permissions perms = new Permissions();
1134 perms.add(new AllPermission());
1138 Thread.currentThread().setContextClassLoader(loader);
1140 log.info("Configured URL class loader:");
1141 for (URL url : jarUrls) log.info(" " + url);
1143 // configure any system properties that we can
1144 for (String jvmarg : _jvmargs) {
1145 if (jvmarg.startsWith("-D")) {
1146 jvmarg = processArg(jvmarg.substring(2));
1147 int eqidx = jvmarg.indexOf("=");
1149 log.warning("Bogus system property: '" + jvmarg + "'?");
1151 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1156 // pass along any pass-through arguments
1157 Map<String, String> passProps = new HashMap<>();
1158 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1159 String key = (String)entry.getKey();
1160 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1161 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1162 passProps.put(key, (String)entry.getValue());
1165 // we can't set these in the above loop lest we get a ConcurrentModificationException
1166 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1167 System.setProperty(entry.getKey(), entry.getValue());
1170 // prepare our app arguments
1171 String[] args = new String[_appargs.size()];
1172 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1175 log.info("Loading " + _class);
1176 Class<?> appclass = loader.loadClass(_class);
1177 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1178 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1179 main.invoke(null, new Object[] { args });
1180 } catch (Exception e) {
1181 log.warning("Failure invoking app main", e);
1185 /** Replaces the application directory and version in any argument. */
1186 protected String processArg (String arg)
1188 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1189 arg = arg.replace("%VERSION%", String.valueOf(_version));
1191 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1192 // from the environment
1193 if (arg.contains(ENV_VAR_PREFIX)) {
1194 StringBuffer sb = new StringBuffer();
1195 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1196 while (matcher.find()) {
1197 String varName = matcher.group(1), varValue = System.getenv(varName);
1198 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1199 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1201 matcher.appendTail(sb);
1202 arg = sb.toString();
1209 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1210 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1211 * whether or not the application needs to be updated or whether we can proceed to verification
1214 * @return true if the application needs to be updated, false if it is up to date and can be
1215 * verified and executed.
1217 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1220 public boolean verifyMetadata (StatusDisplay status)
1223 log.info("Verifying application: " + _vappbase);
1224 log.info("Version: " + _version);
1225 log.info("Class: " + _class);
1227 // this will read in the contents of the digest file and validate itself
1229 _digest = new Digest(getAppDir(), _strictComments);
1230 } catch (IOException ioe) {
1231 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1234 // if we have no version, then we are running in unversioned mode so we need to download
1235 // our digest.txt file on every invocation
1236 if (_version == -1) {
1237 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1238 // resources as one or more of them have also changed
1239 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1241 status.updateStatus("m.checking");
1242 downloadDigestFiles();
1243 _digest = new Digest(getAppDir(), _strictComments);
1244 if (!olddig.equals(_digest.getMetaDigest())) {
1245 log.info("Unversioned digest changed. Revalidating...");
1246 status.updateStatus("m.validating");
1247 clearValidationMarkers();
1249 } catch (IOException ioe) {
1250 log.warning("Failed to refresh non-versioned digest: " +
1251 ioe.getMessage() + ". Proceeding...");
1255 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1256 // redownload the digest file and give it another good college try; this time we allow
1257 // exceptions to propagate up to the caller as there is nothing else we can do
1258 if (_digest == null) {
1259 status.updateStatus("m.updating_metadata");
1260 downloadDigestFiles();
1261 _digest = new Digest(getAppDir(), _strictComments);
1264 // now verify the contents of our main config file
1265 Resource crsrc = getConfigResource();
1266 if (!_digest.validateResource(crsrc, null)) {
1267 status.updateStatus("m.updating_metadata");
1268 // attempt to redownload both of our metadata files; again we pass errors up to our
1269 // caller because there's nothing we can do to automatically recover
1270 downloadConfigFile();
1271 downloadDigestFiles();
1272 _digest = new Digest(getAppDir(), _strictComments);
1273 // revalidate everything if we end up downloading new metadata
1274 clearValidationMarkers();
1275 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1276 if (_digest.validateResource(crsrc, null)) {
1279 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1280 "Blindly forging onward.");
1284 // start by assuming we are happy with our version
1285 _targetVersion = _version;
1287 // if we are a versioned application, read in the contents of the version.txt file
1288 // and/or check the latest config URL for a newer version
1289 if (_version != -1) {
1290 File vfile = getLocalPath(VERSION_FILE);
1291 long fileVersion = VersionUtil.readVersion(vfile);
1292 if (fileVersion != -1) {
1293 _targetVersion = fileVersion;
1296 if (_latest != null) {
1297 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1298 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1299 BufferedReader bin = new BufferedReader(reader)) {
1300 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1301 if (pair[0].equals("version")) {
1302 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1303 if (fileVersion != -1 && _targetVersion > fileVersion) {
1304 // replace the file with the newest version
1305 try (FileOutputStream fos = new FileOutputStream(vfile);
1306 PrintStream out = new PrintStream(fos)) {
1307 out.println(_targetVersion);
1313 } catch (Exception e) {
1314 log.warning("Unable to retrieve version from latest config file.", e);
1319 // finally let the caller know if we need an update
1320 return _version != _targetVersion;
1324 * Verifies the code and media resources associated with this application. A list of resources
1325 * that do not exist or fail the verification process will be returned. If all resources are
1326 * ready to go, null will be returned and the application is considered ready to run.
1328 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1329 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1330 * you have to take care to get back to your UI thread.
1331 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1332 * validated" resources filled in.
1333 * @param unpacked a set to populate with unpacked resources.
1334 * @param toInstall a list into which to add resources that need to be installed.
1335 * @param toDownload a list into which to add resources that need to be downloaded.
1337 public void verifyResources (
1338 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1339 Set<Resource> toInstall, Set<Resource> toDownload)
1340 throws InterruptedException
1342 // resources are verified on background threads supplied by the thread pool, and progress
1343 // is reported by posting runnable actions to the actions queue which is processed by the
1345 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1346 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1347 final int[] completed = new int[1];
1349 long start = System.currentTimeMillis();
1351 // obtain the sizes of the resources to validate
1352 List<Resource> rsrcs = getAllActiveResources();
1353 long[] sizes = new long[rsrcs.size()];
1355 for (int ii = 0; ii < sizes.length; ii++) {
1356 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1358 final ProgressObserver fobs = obs;
1359 // as long as we forward aggregated progress updates to the UI thread, having multiple
1360 // threads update a progress aggregator is "mostly" thread-safe
1361 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1362 public void progress (final int percent) {
1363 actions.add(new Runnable() {
1364 public void run () {
1365 fobs.progress(percent);
1371 final int[] fAlreadyValid = alreadyValid;
1372 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1373 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1374 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1376 for (int ii = 0; ii < sizes.length; ii++) {
1377 final Resource rsrc = rsrcs.get(ii);
1378 final int index = ii;
1379 exec.execute(new Runnable() {
1380 public void run () {
1381 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1382 unpackedAsync, toInstallAsync, toDownloadAsync);
1383 actions.add(new Runnable() {
1384 public void run () {
1392 while (completed[0] < rsrcs.size()) {
1393 // we should be getting progress completion updates WAY more often than one every
1394 // minute, so if things freeze up for 60 seconds, abandon ship
1395 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1401 toInstall.addAll(toInstallAsync);
1402 toDownload.addAll(toDownloadAsync);
1403 unpacked.addAll(unpackedAsync);
1405 long complete = System.currentTimeMillis();
1406 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1407 "duration", (complete-start) + "ms");
1410 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1411 Set<Resource> unpacked,
1412 Set<Resource> toInstall, Set<Resource> toDownload) {
1413 if (rsrc.isMarkedValid()) {
1414 if (alreadyValid != null) {
1422 if (_digest.validateResource(rsrc, obs)) {
1423 // if the resource has a _new file, add it to to-install list
1424 if (rsrc.getLocalNew().exists()) {
1425 toInstall.add(rsrc);
1434 } catch (Exception e) {
1435 log.info("Failure verifying resource. Requesting redownload...",
1436 "rsrc", rsrc, "error", e);
1441 toDownload.add(rsrc);
1445 * Unpacks the resources that require it (we know that they're valid).
1447 * @param unpacked a set of resources to skip because they're already unpacked.
1449 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1450 throws InterruptedException
1452 List<Resource> rsrcs = getActiveResources();
1454 // remove resources that we don't want to unpack
1455 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1456 Resource rsrc = it.next();
1457 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1462 // obtain the sizes of the resources to unpack
1463 long[] sizes = new long[rsrcs.size()];
1464 for (int ii = 0; ii < sizes.length; ii++) {
1465 sizes[ii] = rsrcs.get(ii).getLocal().length();
1468 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1469 for (int ii = 0; ii < sizes.length; ii++) {
1470 Resource rsrc = rsrcs.get(ii);
1471 ProgressObserver pobs = pagg.startElement(ii);
1474 } catch (IOException ioe) {
1475 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1482 * Clears all validation marker files.
1484 public void clearValidationMarkers ()
1486 clearValidationMarkers(getAllActiveResources().iterator());
1490 * Returns the version number for the application. Should only be called after successful
1491 * return of verifyMetadata.
1493 public long getVersion ()
1499 * Creates a versioned application base URL for the specified version.
1501 protected URL createVAppBase (long version)
1502 throws MalformedURLException
1504 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1505 return HostWhitelist.verify(new URL(url));
1509 * Clears all validation marker files for the resources in the supplied iterator.
1511 protected void clearValidationMarkers (Iterator<Resource> iter)
1513 while (iter.hasNext()) {
1514 iter.next().clearMarker();
1519 * Downloads a new copy of CONFIG_FILE.
1521 protected void downloadConfigFile ()
1524 downloadControlFile(CONFIG_FILE, 0);
1528 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1529 * we're not locking at all.
1531 public synchronized boolean lockForUpdates ()
1533 if (_lock != null && _lock.isValid()) {
1537 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1538 } catch (FileNotFoundException e) {
1539 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1543 _lock = _lockChannel.tryLock();
1544 } catch (IOException e) {
1545 log.warning("Unable to create lock", "message", e.getMessage(), e);
1547 } catch (OverlappingFileLockException e) {
1548 log.warning("The lock is held elsewhere in this JVM", e);
1551 log.info("Able to lock for updates: " + (_lock != null));
1552 return _lock != null;
1556 * Release gettingdown.lock
1558 public synchronized void releaseLock ()
1560 if (_lock != null) {
1561 log.info("Releasing lock");
1564 } catch (IOException e) {
1565 log.warning("Unable to release lock", "message", e.getMessage(), e);
1568 _lockChannel.close();
1569 } catch (IOException e) {
1570 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1572 _lockChannel = null;
1578 * Downloads the digest files and validates their signature.
1579 * @throws IOException
1581 protected void downloadDigestFiles ()
1584 for (int version = 1; version <= Digest.VERSION; version++) {
1585 downloadControlFile(Digest.digestFile(version), version);
1590 * Downloads a new copy of the specified control file, optionally validating its signature.
1591 * If the download is successful, moves it over the old file on the filesystem.
1593 * <p> TODO: Switch to PKCS #7 or CMS.
1595 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1596 * should indicate the version of the digest file being validated which indicates which
1597 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1599 protected void downloadControlFile (String path, int sigVersion)
1602 File target = downloadFile(path);
1604 if (sigVersion > 0) {
1605 if (_envc.certs.isEmpty()) {
1606 log.info("No signing certs, not verifying digest.txt", "path", path);
1609 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1610 byte[] signature = null;
1611 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1612 signature = StreamUtil.toByteArray(signatureStream);
1614 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1617 byte[] buffer = new byte[8192];
1618 int length, validated = 0;
1619 for (Certificate cert : _envc.certs) {
1620 try (FileInputStream dataInput = new FileInputStream(target)) {
1621 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1622 sig.initVerify(cert);
1623 while ((length = dataInput.read(buffer)) != -1) {
1624 sig.update(buffer, 0, length);
1627 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1628 log.info("Signature does not match", "cert", cert.getPublicKey());
1631 log.info("Signature matches", "cert", cert.getPublicKey());
1635 } catch (IOException ioe) {
1636 log.warning("Failure validating signature of " + target + ": " + ioe);
1638 } catch (GeneralSecurityException gse) {
1644 // if we couldn't find a key that validates our digest, we are the hosed!
1645 if (validated == 0) {
1646 // delete the temporary digest file as we know it is invalid
1647 FileUtil.deleteHarder(target);
1648 throw new IOException("m.corrupt_digest_signature_error");
1653 // now move the temporary file over the original
1654 File original = getLocalPath(path);
1655 if (!FileUtil.renameTo(target, original)) {
1656 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1661 * Download a path to a temporary file, returning a {@link File} instance with the path
1664 protected File downloadFile (String path)
1667 File target = getLocalPath(path + "_new");
1669 URL targetURL = null;
1671 targetURL = getRemoteURL(path);
1672 } catch (Exception e) {
1673 log.warning("Requested to download invalid control file",
1674 "appbase", _vappbase, "path", path, "error", e);
1675 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1678 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1680 // stream the URL into our temporary file
1681 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1682 // we have to tell Java not to use caches here, otherwise it will cache any request for
1683 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1684 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1685 // about it; turning off caches is not a performance concern, because when Getdown asks
1686 // to download a file, it expects it to come over the wire, not from a cache
1687 uconn.setUseCaches(false);
1688 uconn.setRequestProperty("Accept-Encoding", "gzip");
1689 try (InputStream fin = uconn.getInputStream()) {
1690 String encoding = uconn.getContentEncoding();
1691 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1692 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1693 try (FileOutputStream fout = new FileOutputStream(target)) {
1694 StreamUtil.copy(fin2, fout);
1702 /** Helper function for creating {@link Resource} instances. */
1703 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1704 throws MalformedURLException
1706 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1709 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1710 protected static void addAll (String[] values, List<String> target) {
1711 if (values != null) {
1712 for (String value : values) {
1719 * Make an immutable List from the specified int array.
1721 public static List<Integer> intsToList (int[] values)
1723 List<Integer> list = new ArrayList<>(values.length);
1724 for (int val : values) {
1727 return Collections.unmodifiableList(list);
1731 * Make an immutable List from the specified String array.
1733 public static List<String> stringsToList (String[] values)
1735 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1738 /** Used to parse resources with the specified name. */
1739 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1740 List<Resource> list)
1742 String[] rsrcs = config.getMultiValue(name);
1743 if (rsrcs == null) {
1746 for (String rsrc : rsrcs) {
1748 list.add(createResource(rsrc, attrs));
1749 } catch (Exception e) {
1750 log.warning("Invalid resource '" + rsrc + "'. " + e);
1755 /** Possibly generates and returns a google analytics tracking cookie. */
1756 protected String getGATrackingCode ()
1758 if (_trackingGAHash == null) {
1761 long time = System.currentTimeMillis() / 1000;
1762 if (_trackingStart == 0) {
1763 _trackingStart = time;
1765 if (_trackingId == 0) {
1766 int low = 100000000, high = 1000000000;
1767 _trackingId = low + _rando.nextInt(high-low);
1769 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1770 cookie.append(".").append(_trackingId);
1771 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1772 cookie.append(".").append(time).append(".1%3B%2B");
1773 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1774 cookie.append(_trackingStart).append(".1.1.");
1775 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1776 int low = 1000000000, high = 2000000000;
1777 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1778 return cookie.toString();
1782 * Encodes a path for use in a URL.
1784 protected static String encodePath (String path)
1787 // we want to keep slashes because we're encoding an entire path; also we need to turn
1788 // + into %20 because web servers don't like + in paths or file names, blah
1789 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1790 } catch (UnsupportedEncodingException ue) {
1791 log.warning("Failed to URL encode " + path + ": " + ue);
1796 protected File getLocalPath (File appdir, String path)
1798 return new File(appdir, path);
1801 public static void setStartupFilesFromParameterString(String p) {
1802 // multiple files *might* be passed in as space separated quoted filenames
1804 if (!StringUtil.isBlank(p)) {
1806 // split quoted params or treat as single string array
1807 if (p.startsWith(q) && p.endsWith(q)) {
1808 // this fails if, e.g.
1809 // p=q("stupidfilename\" " "otherfilename")
1810 // let's hope no-one ever ends a filename with '" '
1811 filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1813 // single unquoted filename
1814 filenames = new String[]{p};
1817 // check for locator file. Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1818 String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
1820 !StringUtil.isBlank(locatorFilename)
1821 && locatorFilename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)
1823 setLocatorFile(locatorFilename);
1824 // remove the locator filename from the filenames array
1825 String[] otherFilenames = new String[filenames.length - 1];
1826 System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
1827 filenames = otherFilenames;
1830 for (int i = 0; i < filenames.length; i++) {
1831 String filename = filenames[i];
1832 // skip any other locator files in a multiple file list
1833 if (! filename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
1834 addStartupFile(filename);
1840 public static void setLocatorFile(String filename) {
1841 _locatorFile = new File(filename);
1844 public static void addStartupFile(String filename) {
1845 _startupFiles.add(new File(filename));
1849 private Config createLocatorConfig(Config.ParseOpts opts) {
1850 if (_locatorFile == null) {
1854 Config locatorConfig = null;
1857 Config tmpConfig = null;
1858 if (_locatorFile.exists()) {
1859 tmpConfig = Config.parseConfig(_locatorFile, opts);
1861 log.warning("Given locator file does not exist", "file", _locatorFile);
1864 // appbase is sanitised in HostWhitelist and here!
1865 Map<String, Object> tmpdata = new HashMap<>();
1866 tmpdata.put("appbase", tmpConfig.getString("appbase"));
1867 tmpdata.put("appargs", tmpConfig.getString("appargs"));
1868 tmpdata.put("jvmargs", tmpConfig.getString("jvmargs"));
1869 tmpdata.put(LOCATOR_FILE_EXTENSION+"replace", tmpConfig.getString(LOCATOR_FILE_EXTENSION+"replace"));
1870 tmpdata.put(LOCATOR_FILE_EXTENSION+"merge", tmpConfig.getString(LOCATOR_FILE_EXTENSION+"merge"));
1871 locatorConfig = new Config(tmpdata);
1873 } catch (Exception e) {
1874 log.warning("Failure reading locator file", "file", _locatorFile, e);
1877 return locatorConfig;
1880 protected final EnvConfig _envc;
1881 protected File _config;
1882 protected Digest _digest;
1884 protected long _version = -1;
1885 protected long _targetVersion = -1;
1886 protected String _appbase;
1887 protected URL _vappbase;
1888 protected URL _latest;
1889 protected String _class;
1890 protected String _dockName;
1891 protected String _dockIconPath;
1892 protected boolean _strictComments;
1893 protected boolean _windebug;
1894 protected boolean _allowOffline;
1895 protected int _maxConcDownloads;
1897 protected String _trackingURL;
1898 protected Set<Integer> _trackingPcts;
1899 protected String _trackingCookieName;
1900 protected String _trackingCookieProperty;
1901 protected String _trackingURLSuffix;
1902 protected String _trackingGAHash;
1903 protected long _trackingStart;
1904 protected int _trackingId;
1906 protected String _javaVersionProp = "java.version";
1907 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
1908 protected long _javaMinVersion, _javaMaxVersion;
1909 protected boolean _javaExactVersionRequired;
1910 protected String _javaLocation;
1912 protected List<Resource> _codes = new ArrayList<>();
1913 protected List<Resource> _resources = new ArrayList<>();
1915 protected boolean _useCodeCache;
1916 protected int _codeCacheRetentionDays;
1918 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
1919 protected Map<String,Boolean> _auxactive = new HashMap<>();
1921 protected List<String> _jvmargs = new ArrayList<>();
1922 protected List<String> _appargs = new ArrayList<>();
1924 protected String[] _optimumJvmArgs;
1926 protected List<String> _txtJvmArgs = new ArrayList<>();
1928 /** If a warning has been issued about not being able to set modtimes. */
1929 protected boolean _warnedAboutSetLastModified;
1931 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
1932 protected FileLock _lock;
1934 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
1935 protected FileChannel _lockChannel;
1937 protected Random _rando = new Random();
1939 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
1941 protected static final String ENV_VAR_PREFIX = "%ENV.";
1942 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
1944 protected static File _locatorFile;
1945 protected static List<File> _startupFiles = new ArrayList<>();
1946 public static final String LOCATOR_FILE_EXTENSION = "jvl";