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 static com.threerings.getdown.Log.log;
35 import static java.nio.charset.StandardCharsets.UTF_8;
38 * Parses and provide access to the information contained in the <code>getdown.txt</code>
41 public class Application
43 /** The name of our configuration file. */
44 public static final String CONFIG_FILE = "getdown.txt";
46 /** The name of our target version file. */
47 public static final String VERSION_FILE = "version.txt";
49 /** System properties that are prefixed with this string will be passed through to our
50 * application (minus this prefix). */
51 public static final String PROP_PASSTHROUGH_PREFIX = "app.";
53 /** Suffix used for control file signatures. */
54 public static final String SIGNATURE_SUFFIX = ".sig";
56 /** A special classname that means 'use -jar code.jar' instead of a classname. */
57 public static final String MANIFEST_CLASS = "manifest";
59 /** Used to communicate information about the UI displayed when updating the application. */
60 public static final class UpdateInterface
63 * The major steps involved in updating, along with some arbitrary percentages
64 * assigned to them, to mark global progress.
69 VERIFY_METADATA(15, 65, 95),
72 VERIFY_RESOURCES(70, 97),
73 REDOWNLOAD_RESOURCES(90),
77 /** What is the final percent value for this step? */
78 public final List<Integer> defaultPercents;
80 /** Enum constructor. */
81 Step (int... percents)
83 this.defaultPercents = intsToList(percents);
87 /** The human readable name of this application. */
88 public final String name;
90 /** A background color, just in case. */
91 public final int background;
93 /** Background image specifiers for `RotatingBackgrounds`. */
94 public final List<String> rotatingBackgrounds;
96 /** The error background image for `RotatingBackgrounds`. */
97 public final String errorBackground;
99 /** The paths (relative to the appdir) of images for the window icon. */
100 public final List<String> iconImages;
102 /** The path (relative to the appdir) to a single background image. */
103 public final String backgroundImage;
105 /** The path (relative to the appdir) to the progress bar image. */
106 public final String progressImage;
108 /** The dimensions of the progress bar. */
109 public final Rectangle progress;
111 /** The color of the progress text. */
112 public final int progressText;
114 /** The color of the progress bar. */
115 public final int progressBar;
117 /** The dimensions of the status display. */
118 public final Rectangle status;
120 /** The color of the status text. */
121 public final int statusText;
123 /** The color of the text shadow. */
124 public final int textShadow;
126 /** Where to point the user for help with install errors. */
127 public final String installError;
129 /** The dimensions of the patch notes button. */
130 public final Rectangle patchNotes;
132 /** The patch notes URL. */
133 public final String patchNotesUrl;
135 /** Whether window decorations are hidden for the UI. */
136 public final boolean hideDecorations;
138 /** Whether progress text should be hidden or not. */
139 public final boolean hideProgressText;
141 /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
142 * flashing up on the screen and immediately disappearing, which can be confusing to the
144 public final int minShowSeconds;
146 /** The global percentages for each step. A step may have more than one, and
147 * the lowest reasonable one is used if a step is revisited. */
148 public final Map<Step, List<Integer>> stepPercentages;
150 /** Generates a string representation of this instance. */
152 public String toString ()
154 return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage +
155 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
156 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
157 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
158 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
159 ", hideProgressText" + hideProgressText + ", minShow=" + minShowSeconds + "]";
162 public UpdateInterface (Config config)
164 this.name = config.getString("ui.name");
165 this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
166 this.progressText = config.getColor("ui.progress_text", Color.BLACK);
167 this.hideProgressText = config.getBoolean("ui.hide_progress_text");
168 this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
169 this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
170 this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
171 this.statusText = config.getColor("ui.status_text", Color.BLACK);
172 this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
173 this.hideDecorations = config.getBoolean("ui.hide_decorations");
174 this.backgroundImage = config.getString("ui.background_image");
175 // default to black or white bg color, depending on the brightness of the progressText
176 int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
177 Color.BLACK : Color.WHITE;
178 this.background = config.getColor("ui.background", defaultBackground);
179 this.progressImage = config.getString("ui.progress_image");
180 this.rotatingBackgrounds = stringsToList(
181 config.getMultiValue("ui.rotating_background"));
182 this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
183 this.errorBackground = config.getString("ui.error_background");
185 // On an installation error, where do we point the user.
186 String installError = config.getUrl("ui.install_error", null);
187 this.installError = (installError == null) ?
188 "m.default_install_error" : MessageUtil.taint(installError);
190 // the patch notes bits
191 this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
192 this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
194 // step progress percentage (defaults and then customized values)
195 EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
196 for (Step step : Step.values()) {
197 stepPercentages.put(step, step.defaultPercents);
199 for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
200 String spec = config.getString("ui.percents." + step.name());
203 stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
204 } catch (Exception e) {
205 log.warning("Failed to parse percentages for " + step + ": " + spec);
209 this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
214 * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
215 * take network actions.
217 public static interface StatusDisplay
219 /** Requests that the specified status message be displayed. */
220 public void updateStatus (String message);
224 * Contains metadata for an auxiliary resource group.
226 public static class AuxGroup {
227 public final String name;
228 public final List<Resource> codes;
229 public final List<Resource> rsrcs;
231 public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
233 this.codes = Collections.unmodifiableList(codes);
234 this.rsrcs = Collections.unmodifiableList(rsrcs);
238 /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
239 * the application instance. Yes this is a public mutable field, no I'm not going to create a
240 * getter and setter just to pretend like that's not the case. */
241 public Proxy proxy = Proxy.NO_PROXY;
244 * Creates an application instance which records the location of the <code>getdown.txt</code>
245 * configuration file from the supplied application directory.
248 public Application (EnvConfig envc) {
250 _config = getLocalPath(envc.appDir, CONFIG_FILE);
254 * Returns the configured application directory.
256 public File getAppDir () {
261 * Returns whether the application should cache code resources prior to launching the
264 public boolean useCodeCache ()
266 return _useCodeCache;
270 * Returns the number of days a cached code resource is allowed to stay unused before it
271 * becomes eligible for deletion.
273 public int getCodeCacheRetentionDays ()
275 return _codeCacheRetentionDays;
279 * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
280 * app files from its hosting server.
282 public int maxConcurrentDownloads () {
283 return _maxConcDownloads;
287 * Returns a resource that refers to the application configuration file itself.
289 public Resource getConfigResource ()
292 return createResource(CONFIG_FILE, Resource.NORMAL);
293 } catch (Exception e) {
294 throw new RuntimeException("Invalid appbase '" + _vappbase + "'.", e);
299 * Returns a list of the code {@link Resource} objects used by this application.
301 public List<Resource> getCodeResources ()
307 * Returns a list of the non-code {@link Resource} objects used by this application.
309 public List<Resource> getResources ()
315 * Returns the digest of the given {@code resource}.
317 public String getDigest (Resource resource)
319 return _digest.getDigest(resource);
323 * Returns a list of all the active {@link Resource} objects used by this application (code and
326 public List<Resource> getAllActiveResources ()
328 List<Resource> allResources = new ArrayList<>();
329 allResources.addAll(getActiveCodeResources());
330 allResources.addAll(getActiveResources());
335 * Returns the auxiliary resource group with the specified name, or null.
337 public AuxGroup getAuxGroup (String name)
339 return _auxgroups.get(name);
343 * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
344 * resource group is a collection of resource files that are not downloaded unless a group
345 * token file is present in the application directory.
347 public Iterable<AuxGroup> getAuxGroups ()
349 return _auxgroups.values();
353 * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
354 * groups should be ignored, activated groups should be downloaded and patched along with the
357 public boolean isAuxGroupActive (String auxgroup)
359 Boolean active = _auxactive.get(auxgroup);
360 if (active == null) {
361 // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
363 active = getLocalPath(auxgroup + ".dat").exists();
364 _auxactive.put(auxgroup, active);
370 * Returns all main code resources and all code resources from active auxiliary resource groups.
372 public List<Resource> getActiveCodeResources ()
374 ArrayList<Resource> codes = new ArrayList<>();
375 codes.addAll(getCodeResources());
376 for (AuxGroup aux : getAuxGroups()) {
377 if (isAuxGroupActive(aux.name)) {
378 codes.addAll(aux.codes);
385 * Returns all resources indicated to contain native library files (.dll, .so, etc.).
387 public List<Resource> getNativeResources ()
389 List<Resource> natives = new ArrayList<>();
390 for (Resource resource: _resources) {
391 if (resource.isNative()) {
392 natives.add(resource);
399 * Returns all non-code resources and all resources from active auxiliary resource groups.
401 public List<Resource> getActiveResources ()
403 ArrayList<Resource> rsrcs = new ArrayList<>();
404 rsrcs.addAll(getResources());
405 for (AuxGroup aux : getAuxGroups()) {
406 if (isAuxGroupActive(aux.name)) {
407 rsrcs.addAll(aux.rsrcs);
414 * Returns a resource that can be used to download a patch file that will bring this
415 * application from its current version to the target version.
417 * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
418 * for the main application patch resource.
420 public Resource getPatchResource (String auxgroup)
422 if (_targetVersion <= _version) {
423 log.warning("Requested patch resource for up-to-date or non-versioned application",
424 "cvers", _version, "tvers", _targetVersion);
428 String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
429 String pfile = "patch" + infix + _version + ".dat";
431 URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
432 return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
433 } catch (Exception e) {
434 log.warning("Failed to create patch resource path",
435 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
441 * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
442 * place of the installed VM (in the case where the VM that launched Getdown does not meet the
443 * application's version requirements) or null if no VM is available for this platform.
445 public Resource getJavaVMResource ()
447 if (StringUtil.isBlank(_javaLocation)) {
451 String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
452 String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
453 log.info("vmfile is '"+vmfile+"'");
454 System.out.println("vmfile is '"+vmfile+"'");
456 URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
457 log.info("Attempting to fetch jvm at "+remote.toString());
458 System.out.println("Attempting to fetch jvm at "+remote.toString());
459 return new Resource(vmfile, remote, getLocalPath(vmfile),
460 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
461 } catch (Exception e) {
462 log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
463 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
464 System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
465 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
471 * Returns a resource that can be used to download an archive containing all files belonging to
474 public Resource getFullResource ()
476 String file = "full";
478 URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
479 return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
480 } catch (Exception e) {
481 log.warning("Failed to create full resource path",
482 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
488 * Returns the URL to use to report an initial download event. Returns null if no tracking
489 * start URL was configured for this application.
491 * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
493 public URL getTrackingURL (String event)
496 String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
497 String ga = getGATrackingCode();
498 return _trackingURL == null ? null :
499 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
500 } catch (MalformedURLException mue) {
501 log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
507 * Returns the URL to request to report that we have reached the specified percentage of our
508 * initial download. Returns null if no tracking request was configured for the specified
511 public URL getTrackingProgressURL (int percent)
513 if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
516 return getTrackingURL("pct" + percent);
520 * Returns the name of our tracking cookie or null if it was not set.
522 public String getTrackingCookieName ()
524 return _trackingCookieName;
528 * Returns the name of our tracking cookie system property or null if it was not set.
530 public String getTrackingCookieProperty ()
532 return _trackingCookieProperty;
536 * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
537 * for operation. The application base URL will be parsed first so that if there are errors
538 * discovered later, the caller can use the application base to download a new {@code
539 * getdown.txt} file and try again.
541 * @return a {@code Config} instance that contains information from the config file.
543 * @exception IOException thrown if there is an error reading the file or an error encountered
544 * during its parsing.
546 public Config init (boolean checkPlatform)
549 Config config = null;
550 File cfgfile = _config;
551 Config.ParseOpts opts = Config.createOpts(checkPlatform);
553 // if we have a configuration file, read the data from it
554 if (cfgfile.exists()) {
555 config = Config.parseConfig(_config, opts);
557 // otherwise, try reading data from our backup config file; thanks to funny windows
558 // bullshit, we have to do this backup file fiddling in case we got screwed while
559 // updating getdown.txt during normal operation
560 else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
561 config = Config.parseConfig(cfgfile, opts);
563 // otherwise, issue a warning that we found no getdown file
565 log.info("Found no getdown.txt file", "appdir", getAppDir());
567 } catch (Exception e) {
568 log.warning("Failure reading config file", "file", config, e);
571 // if we failed to read our config file, check for an appbase specified via a system
572 // property; we can use that to bootstrap ourselves back into operation
573 if (config == null) {
574 String appbase = _envc.appBase;
575 log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
576 Map<String, Object> cdata = new HashMap<>();
577 cdata.put("appbase", appbase);
578 config = new Config(cdata);
581 // first determine our application base, this way if anything goes wrong later in the
582 // process, our caller can use the appbase to download a new configuration file
583 _appbase = config.getString("appbase");
584 if (_appbase == null) {
585 throw new RuntimeException("m.missing_appbase");
588 // check if we're overriding the domain in the appbase
589 _appbase = SysProps.overrideAppbase(_appbase);
591 // make sure there's a trailing slash
592 if (!_appbase.endsWith("/")) {
593 _appbase = _appbase + "/";
596 // extract our version information
597 _version = config.getLong("version", -1L);
599 // if we are a versioned deployment, create a versioned appbase
601 _vappbase = createVAppBase(_version);
602 } catch (MalformedURLException mue) {
603 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
604 throw (IOException) new IOException(err).initCause(mue);
607 // check for a latest config URL
608 String latest = config.getString("latest");
609 if (latest != null) {
610 if (latest.startsWith(_appbase)) {
611 latest = _appbase + latest.substring(_appbase.length());
613 latest = SysProps.replaceDomain(latest);
616 _latest = HostWhitelist.verify(new URL(latest));
617 } catch (MalformedURLException mue) {
618 log.warning("Invalid URL for latest attribute.", mue);
622 String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
624 // determine our application class name (use app-specific class _if_ one is provided)
625 _class = config.getString("class");
626 if (appPrefix.length() > 0) {
627 _class = config.getString(appPrefix + "class", _class);
629 if (_class == null) {
630 throw new IOException("m.missing_class");
633 // determine whether we want strict comments
634 _strictComments = config.getBoolean("strict_comments");
636 // check to see if we're using a custom java.version property and regex
637 _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
638 _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
640 // check to see if we require a particular JVM version and have a supplied JVM
641 _javaMinVersion = config.getLong("java_version", _javaMinVersion);
642 // we support java_min_version as an alias of java_version; it better expresses the check
643 // that's going on and better mirrors java_max_version
644 _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
645 // check to see if we require a particular max JVM version and have a supplied JVM
646 _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
647 // check to see if we require a particular JVM version and have a supplied JVM
648 _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
650 // this is a little weird, but when we're run from the digester, we see a String[] which
651 // contains java locations for all platforms which we can't grok, but the digester doesn't
652 // need to know about that; when we're run in a real application there will be only one!
653 Object javaloc = config.getRaw("java_location");
654 if (javaloc instanceof String) {
655 _javaLocation = (String)javaloc;
658 // determine whether we have any tracking configuration
659 _trackingURL = config.getString("tracking_url");
661 // check for tracking progress percent configuration
662 String trackPcts = config.getString("tracking_percents");
663 if (!StringUtil.isBlank(trackPcts)) {
664 _trackingPcts = new HashSet<>();
665 for (int pct : StringUtil.parseIntArray(trackPcts)) {
666 _trackingPcts.add(pct);
668 } else if (!StringUtil.isBlank(_trackingURL)) {
669 _trackingPcts = new HashSet<>();
670 _trackingPcts.add(50);
673 // Check for tracking cookie configuration
674 _trackingCookieName = config.getString("tracking_cookie_name");
675 _trackingCookieProperty = config.getString("tracking_cookie_property");
677 // Some app may need an extra suffix added to the tracking URL
678 _trackingURLSuffix = config.getString("tracking_url_suffix");
680 // Some app may need to generate google analytics code
681 _trackingGAHash = config.getString("tracking_ga_hash");
683 // clear our arrays as we may be reinitializing
691 // parse our code resources
692 if (config.getMultiValue("code") == null &&
693 config.getMultiValue("ucode") == null) {
694 throw new IOException("m.missing_code");
696 parseResources(config, "code", Resource.NORMAL, _codes);
697 parseResources(config, "ucode", Resource.UNPACK, _codes);
699 // parse our non-code resources
700 parseResources(config, "resource", Resource.NORMAL, _resources);
701 parseResources(config, "uresource", Resource.UNPACK, _resources);
702 parseResources(config, "xresource", Resource.EXEC, _resources);
703 parseResources(config, "presource", Resource.PRELOAD, _resources);
704 parseResources(config, "nresource", Resource.NATIVE, _resources);
706 // parse our auxiliary resource groups
707 for (String auxgroup : config.getList("auxgroups")) {
708 ArrayList<Resource> codes = new ArrayList<>();
709 parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
710 parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
711 ArrayList<Resource> rsrcs = new ArrayList<>();
712 parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
713 parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
714 parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
715 parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
716 parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
717 _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
720 // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
721 String[] jvmargs = config.getMultiValue("jvmarg");
722 addAll(jvmargs, _jvmargs);
723 if (appPrefix.length() > 0) {
724 jvmargs = config.getMultiValue(appPrefix + "jvmarg");
725 addAll(jvmargs, _jvmargs);
728 // see if a percentage of physical memory option exists
729 int jvmmempc = config.getInt("jvmmempc", -1);
730 // app_id prefixed setting overrides
731 if (appPrefix.length() > 0) {
732 jvmmempc = config.getInt(appPrefix + "jvmmempc", jvmmempc);
734 if (0 <= jvmmempc && jvmmempc <= 100) {
735 final Object o = ManagementFactory.getOperatingSystemMXBean();
738 if (o instanceof OperatingSystemMXBean) {
739 final OperatingSystemMXBean osb = (OperatingSystemMXBean) o;
740 long physicalMem = osb.getTotalPhysicalMemorySize();
741 long requestedMem = physicalMem*jvmmempc/100;
742 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(requestedMem)};
743 // remove other max heap size arg
744 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
745 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
749 addAll(maxMemHeapArg, _jvmargs);
753 catch (NoClassDefFoundError e) {
754 // com.sun.management.OperatingSystemMXBean doesn't exist in this JVM
755 System.out.println("No com.sun.management.OperatingSystemMXBean. Cannot use 'jvmmempc'.");
757 } else if (jvmmempc != -1) {
758 System.out.println("'jvmmempc' value must be in range 0 to 100 (read as '"+Integer.toString(jvmmempc)+"')");
761 // get the set of optimum JVM arguments
762 _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
764 // transfer our application arguments
765 String[] appargs = config.getMultiValue(appPrefix + "apparg");
766 addAll(appargs, _appargs);
768 // add the launch specific application arguments
769 _appargs.addAll(_envc.appArgs);
771 // look for custom arguments
772 fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
774 // determine whether we want to allow offline operation (defaults to false)
775 _allowOffline = config.getBoolean("allow_offline");
777 // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
778 // obtain a thread dump of the running JVM
779 _windebug = getLocalPath("debug.txt").exists();
781 // whether to cache code resources and launch from cache
782 _useCodeCache = config.getBoolean("use_code_cache");
783 _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
785 // maximum simultaneous downloads
786 _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
787 SysProps.threadPoolSize()));
789 // extract some info used to configure our child process on macOS
790 _dockName = config.getString("ui.name");
791 _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
797 * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
799 protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
801 File pairFile = getLocalPath(pairLocation);
802 if (pairFile.exists()) {
804 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
805 for (String[] pair : args) {
806 if (pair[1].length() == 0) {
807 collector.add(pair[0]);
809 collector.add(pair[0] + "=" + pair[1]);
812 } catch (Throwable t) {
813 log.warning("Failed to parse '" + pairFile + "': " + t);
819 * Returns a URL from which the specified path can be fetched. Our application base URL is
820 * properly versioned and combined with the supplied path.
822 public URL getRemoteURL (String path)
823 throws MalformedURLException
825 return new URL(_vappbase, encodePath(path));
829 * Returns the local path to the specified resource.
831 public File getLocalPath (String path)
833 return getLocalPath(getAppDir(), path);
837 * Returns true if we either have no version requirement, are running in a JVM that meets our
838 * version requirements or have what appears to be a version of the JVM that meets our
841 public boolean haveValidJavaVersion ()
843 // if we're doing no version checking, then yay!
844 if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
847 // parse the version out of the java.version (or custom) system property
848 long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
850 log.info("Checking Java version", "current", version,
851 "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
853 // if we have an unpacked VM, check the 'release' file for its version
854 Resource vmjar = getJavaVMResource();
855 if (vmjar != null && vmjar.isMarkedValid()) {
856 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
857 File relfile = new File(vmdir, "release");
858 if (!relfile.exists()) {
859 log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
863 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
865 log.warning("Unable to read version from 'release' file. Assuming valid.");
870 log.info("Checking version of unpacked JVM [vers=" + version + "].");
873 if (_javaExactVersionRequired) {
874 if (version == _javaMinVersion) return true;
876 log.warning("An exact Java VM version is required.", "current", version,
877 "required", _javaMinVersion);
882 boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
883 boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
884 return minVersionOK && maxVersionOK;
886 } catch (RuntimeException re) {
887 // if we can't parse the java version we're in weird land and should probably just try
888 // our luck with what we've got rather than try to download a new jvm
889 log.warning("Unable to parse VM version, hoping for the best",
890 "error", re, "needed", _javaMinVersion);
896 * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
897 * whether the launch is successful and, if necessary, trying again without the optimum
900 public boolean hasOptimumJvmArgs ()
902 return _optimumJvmArgs != null;
906 * Returns true if the app should attempt to run even if we have no Internet connection.
908 public boolean allowOffline ()
910 return _allowOffline;
914 * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
915 * previous call to {@link #init}.
917 public void attemptRecovery (StatusDisplay status)
920 status.updateStatus("m.updating_metadata");
921 downloadConfigFile();
925 * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
926 * those for the target version of our application.
928 public void updateMetadata ()
932 // update our versioned application base with the target version
933 _vappbase = createVAppBase(_targetVersion);
934 } catch (MalformedURLException mue) {
935 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
936 throw (IOException) new IOException(err).initCause(mue);
940 // now re-download our control files; we download the digest first so that if it fails,
941 // our config file will still reference the old version and re-running the updater will
942 // start the whole process over again
943 downloadDigestFiles();
944 downloadConfigFile();
946 } catch (IOException ex) {
947 // if we are allowing offline execution, we want to allow the application to run in its
948 // current form rather than aborting the entire process; to do this, we delete the
949 // version.txt file and "trick" Getdown into thinking that it just needs to validate
950 // the application as is; next time the app runs when connected to the internet, it
951 // will have to rediscover that it needs updating and reattempt to update itself
953 log.warning("Failed to update digest files. Attempting offline operaton.", ex);
954 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
955 log.warning("Deleting version.txt failed. This probably isn't going to work.");
964 * Invokes the process associated with this application definition.
966 * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
969 public Process createProcess (boolean optimum)
972 ArrayList<String> args = new ArrayList<>();
974 // reconstruct the path to the JVM
975 args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
977 // check whether we're using -jar mode or -classpath mode
978 boolean dashJarMode = MANIFEST_CLASS.equals(_class);
980 // add the -classpath arguments if we're not in -jar mode
981 ClassPath classPath = PathBuilder.buildClassPath(this);
983 args.add("-classpath");
984 args.add(classPath.asArgumentString());
987 // we love our Mac users, so we do nice things to preserve our application identity
988 if (LaunchUtil.isMacOS()) {
989 args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
990 args.add("-Xdock:name=" + _dockName);
993 // pass along our proxy settings
995 if ((proxyHost = System.getProperty("http.proxyHost")) != null) {
996 args.add("-Dhttp.proxyHost=" + proxyHost);
997 args.add("-Dhttp.proxyPort=" + System.getProperty("http.proxyPort"));
998 args.add("-Dhttps.proxyHost=" + proxyHost);
999 args.add("-Dhttps.proxyPort=" + System.getProperty("http.proxyPort"));
1002 // add the marker indicating the app is running in getdown
1003 args.add("-D" + Properties.GETDOWN + "=true");
1005 // set the native library path if we have native resources
1006 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1007 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1008 if (javaLibPath != null) {
1009 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1012 // pass along any pass-through arguments
1013 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1014 String key = (String)entry.getKey();
1015 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1016 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1017 args.add("-D" + key + "=" + entry.getValue());
1021 // add the JVM arguments
1022 for (String string : _jvmargs) {
1023 args.add(processArg(string));
1026 // add the optimum arguments if requested and available
1027 if (optimum && _optimumJvmArgs != null) {
1028 for (String string : _optimumJvmArgs) {
1029 args.add(processArg(string));
1033 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1034 for (String string : _txtJvmArgs) {
1035 args.add(processArg(string));
1038 // if we're in -jar mode add those arguments, otherwise add the app class name
1041 args.add(classPath.asArgumentString());
1046 // finally add the application arguments
1047 for (String string : _appargs) {
1048 args.add(processArg(string));
1051 String[] envp = createEnvironment();
1052 String[] sargs = args.toArray(new String[args.size()]);
1053 log.info("Running " + StringUtil.join(sargs, "\n "));
1055 return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1059 * If the application provided environment variables, combine those with the current
1060 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1061 * If the application didn't provide any environment variables, null is returned to just use
1062 * the existing environment.
1064 protected String[] createEnvironment ()
1066 List<String> envvar = new ArrayList<>();
1067 fillAssignmentListFromPairs("env.txt", envvar);
1068 if (envvar.isEmpty()) {
1069 log.info("Didn't find any custom environment variables, not setting any.");
1073 List<String> envAssignments = new ArrayList<>();
1074 for (String assignment : envvar) {
1075 envAssignments.add(processArg(assignment));
1077 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1078 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1080 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1081 log.info("Environment " + StringUtil.join(envp, "\n "));
1086 * Runs this application directly in the current VM.
1088 public void invokeDirect () throws IOException
1090 ClassPath classPath = PathBuilder.buildClassPath(this);
1091 URL[] jarUrls = classPath.asUrls();
1093 // create custom class loader
1094 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1095 @Override protected PermissionCollection getPermissions (CodeSource code) {
1096 Permissions perms = new Permissions();
1097 perms.add(new AllPermission());
1101 Thread.currentThread().setContextClassLoader(loader);
1103 log.info("Configured URL class loader:");
1104 for (URL url : jarUrls) log.info(" " + url);
1106 // configure any system properties that we can
1107 for (String jvmarg : _jvmargs) {
1108 if (jvmarg.startsWith("-D")) {
1109 jvmarg = processArg(jvmarg.substring(2));
1110 int eqidx = jvmarg.indexOf("=");
1112 log.warning("Bogus system property: '" + jvmarg + "'?");
1114 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1119 // pass along any pass-through arguments
1120 Map<String, String> passProps = new HashMap<>();
1121 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1122 String key = (String)entry.getKey();
1123 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1124 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1125 passProps.put(key, (String)entry.getValue());
1128 // we can't set these in the above loop lest we get a ConcurrentModificationException
1129 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1130 System.setProperty(entry.getKey(), entry.getValue());
1133 // prepare our app arguments
1134 String[] args = new String[_appargs.size()];
1135 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1138 log.info("Loading " + _class);
1139 Class<?> appclass = loader.loadClass(_class);
1140 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1141 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1142 main.invoke(null, new Object[] { args });
1143 } catch (Exception e) {
1144 log.warning("Failure invoking app main", e);
1148 /** Replaces the application directory and version in any argument. */
1149 protected String processArg (String arg)
1151 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1152 arg = arg.replace("%VERSION%", String.valueOf(_version));
1154 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1155 // from the environment
1156 if (arg.contains(ENV_VAR_PREFIX)) {
1157 StringBuffer sb = new StringBuffer();
1158 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1159 while (matcher.find()) {
1160 String varName = matcher.group(1), varValue = System.getenv(varName);
1161 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1162 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1164 matcher.appendTail(sb);
1165 arg = sb.toString();
1172 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1173 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1174 * whether or not the application needs to be updated or whether we can proceed to verification
1177 * @return true if the application needs to be updated, false if it is up to date and can be
1178 * verified and executed.
1180 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1183 public boolean verifyMetadata (StatusDisplay status)
1186 log.info("Verifying application: " + _vappbase);
1187 log.info("Version: " + _version);
1188 log.info("Class: " + _class);
1190 // this will read in the contents of the digest file and validate itself
1192 _digest = new Digest(getAppDir(), _strictComments);
1193 } catch (IOException ioe) {
1194 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1197 // if we have no version, then we are running in unversioned mode so we need to download
1198 // our digest.txt file on every invocation
1199 if (_version == -1) {
1200 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1201 // resources as one or more of them have also changed
1202 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1204 status.updateStatus("m.checking");
1205 downloadDigestFiles();
1206 _digest = new Digest(getAppDir(), _strictComments);
1207 if (!olddig.equals(_digest.getMetaDigest())) {
1208 log.info("Unversioned digest changed. Revalidating...");
1209 status.updateStatus("m.validating");
1210 clearValidationMarkers();
1212 } catch (IOException ioe) {
1213 log.warning("Failed to refresh non-versioned digest: " +
1214 ioe.getMessage() + ". Proceeding...");
1218 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1219 // redownload the digest file and give it another good college try; this time we allow
1220 // exceptions to propagate up to the caller as there is nothing else we can do
1221 if (_digest == null) {
1222 status.updateStatus("m.updating_metadata");
1223 downloadDigestFiles();
1224 _digest = new Digest(getAppDir(), _strictComments);
1227 // now verify the contents of our main config file
1228 Resource crsrc = getConfigResource();
1229 if (!_digest.validateResource(crsrc, null)) {
1230 status.updateStatus("m.updating_metadata");
1231 // attempt to redownload both of our metadata files; again we pass errors up to our
1232 // caller because there's nothing we can do to automatically recover
1233 downloadConfigFile();
1234 downloadDigestFiles();
1235 _digest = new Digest(getAppDir(), _strictComments);
1236 // revalidate everything if we end up downloading new metadata
1237 clearValidationMarkers();
1238 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1239 if (_digest.validateResource(crsrc, null)) {
1242 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1243 "Blindly forging onward.");
1247 // start by assuming we are happy with our version
1248 _targetVersion = _version;
1250 // if we are a versioned application, read in the contents of the version.txt file
1251 // and/or check the latest config URL for a newer version
1252 if (_version != -1) {
1253 File vfile = getLocalPath(VERSION_FILE);
1254 long fileVersion = VersionUtil.readVersion(vfile);
1255 if (fileVersion != -1) {
1256 _targetVersion = fileVersion;
1259 if (_latest != null) {
1260 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1261 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1262 BufferedReader bin = new BufferedReader(reader)) {
1263 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1264 if (pair[0].equals("version")) {
1265 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1266 if (fileVersion != -1 && _targetVersion > fileVersion) {
1267 // replace the file with the newest version
1268 try (FileOutputStream fos = new FileOutputStream(vfile);
1269 PrintStream out = new PrintStream(fos)) {
1270 out.println(_targetVersion);
1276 } catch (Exception e) {
1277 log.warning("Unable to retrieve version from latest config file.", e);
1282 // finally let the caller know if we need an update
1283 return _version != _targetVersion;
1287 * Verifies the code and media resources associated with this application. A list of resources
1288 * that do not exist or fail the verification process will be returned. If all resources are
1289 * ready to go, null will be returned and the application is considered ready to run.
1291 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1292 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1293 * you have to take care to get back to your UI thread.
1294 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1295 * validated" resources filled in.
1296 * @param unpacked a set to populate with unpacked resources.
1297 * @param toInstall a list into which to add resources that need to be installed.
1298 * @param toDownload a list into which to add resources that need to be downloaded.
1300 public void verifyResources (
1301 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1302 Set<Resource> toInstall, Set<Resource> toDownload)
1303 throws InterruptedException
1305 // resources are verified on background threads supplied by the thread pool, and progress
1306 // is reported by posting runnable actions to the actions queue which is processed by the
1308 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1309 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1310 final int[] completed = new int[1];
1312 long start = System.currentTimeMillis();
1314 // obtain the sizes of the resources to validate
1315 List<Resource> rsrcs = getAllActiveResources();
1316 long[] sizes = new long[rsrcs.size()];
1318 for (int ii = 0; ii < sizes.length; ii++) {
1319 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1321 final ProgressObserver fobs = obs;
1322 // as long as we forward aggregated progress updates to the UI thread, having multiple
1323 // threads update a progress aggregator is "mostly" thread-safe
1324 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1325 public void progress (final int percent) {
1326 actions.add(new Runnable() {
1327 public void run () {
1328 fobs.progress(percent);
1334 final int[] fAlreadyValid = alreadyValid;
1335 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1336 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1337 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1339 for (int ii = 0; ii < sizes.length; ii++) {
1340 final Resource rsrc = rsrcs.get(ii);
1341 final int index = ii;
1342 exec.execute(new Runnable() {
1343 public void run () {
1344 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1345 unpackedAsync, toInstallAsync, toDownloadAsync);
1346 actions.add(new Runnable() {
1347 public void run () {
1355 while (completed[0] < rsrcs.size()) {
1356 // we should be getting progress completion updates WAY more often than one every
1357 // minute, so if things freeze up for 60 seconds, abandon ship
1358 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1364 toInstall.addAll(toInstallAsync);
1365 toDownload.addAll(toDownloadAsync);
1366 unpacked.addAll(unpackedAsync);
1368 long complete = System.currentTimeMillis();
1369 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1370 "duration", (complete-start) + "ms");
1373 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1374 Set<Resource> unpacked,
1375 Set<Resource> toInstall, Set<Resource> toDownload) {
1376 if (rsrc.isMarkedValid()) {
1377 if (alreadyValid != null) {
1385 if (_digest.validateResource(rsrc, obs)) {
1386 // if the resource has a _new file, add it to to-install list
1387 if (rsrc.getLocalNew().exists()) {
1388 toInstall.add(rsrc);
1397 } catch (Exception e) {
1398 log.info("Failure verifying resource. Requesting redownload...",
1399 "rsrc", rsrc, "error", e);
1404 toDownload.add(rsrc);
1408 * Unpacks the resources that require it (we know that they're valid).
1410 * @param unpacked a set of resources to skip because they're already unpacked.
1412 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1413 throws InterruptedException
1415 List<Resource> rsrcs = getActiveResources();
1417 // remove resources that we don't want to unpack
1418 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1419 Resource rsrc = it.next();
1420 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1425 // obtain the sizes of the resources to unpack
1426 long[] sizes = new long[rsrcs.size()];
1427 for (int ii = 0; ii < sizes.length; ii++) {
1428 sizes[ii] = rsrcs.get(ii).getLocal().length();
1431 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1432 for (int ii = 0; ii < sizes.length; ii++) {
1433 Resource rsrc = rsrcs.get(ii);
1434 ProgressObserver pobs = pagg.startElement(ii);
1437 } catch (IOException ioe) {
1438 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1445 * Clears all validation marker files.
1447 public void clearValidationMarkers ()
1449 clearValidationMarkers(getAllActiveResources().iterator());
1453 * Returns the version number for the application. Should only be called after successful
1454 * return of verifyMetadata.
1456 public long getVersion ()
1462 * Creates a versioned application base URL for the specified version.
1464 protected URL createVAppBase (long version)
1465 throws MalformedURLException
1467 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1468 return HostWhitelist.verify(new URL(url));
1472 * Clears all validation marker files for the resources in the supplied iterator.
1474 protected void clearValidationMarkers (Iterator<Resource> iter)
1476 while (iter.hasNext()) {
1477 iter.next().clearMarker();
1482 * Downloads a new copy of CONFIG_FILE.
1484 protected void downloadConfigFile ()
1487 downloadControlFile(CONFIG_FILE, 0);
1491 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1492 * we're not locking at all.
1494 public synchronized boolean lockForUpdates ()
1496 if (_lock != null && _lock.isValid()) {
1500 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1501 } catch (FileNotFoundException e) {
1502 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1506 _lock = _lockChannel.tryLock();
1507 } catch (IOException e) {
1508 log.warning("Unable to create lock", "message", e.getMessage(), e);
1510 } catch (OverlappingFileLockException e) {
1511 log.warning("The lock is held elsewhere in this JVM", e);
1514 log.info("Able to lock for updates: " + (_lock != null));
1515 return _lock != null;
1519 * Release gettingdown.lock
1521 public synchronized void releaseLock ()
1523 if (_lock != null) {
1524 log.info("Releasing lock");
1527 } catch (IOException e) {
1528 log.warning("Unable to release lock", "message", e.getMessage(), e);
1531 _lockChannel.close();
1532 } catch (IOException e) {
1533 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1535 _lockChannel = null;
1541 * Downloads the digest files and validates their signature.
1542 * @throws IOException
1544 protected void downloadDigestFiles ()
1547 for (int version = 1; version <= Digest.VERSION; version++) {
1548 downloadControlFile(Digest.digestFile(version), version);
1553 * Downloads a new copy of the specified control file, optionally validating its signature.
1554 * If the download is successful, moves it over the old file on the filesystem.
1556 * <p> TODO: Switch to PKCS #7 or CMS.
1558 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1559 * should indicate the version of the digest file being validated which indicates which
1560 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1562 protected void downloadControlFile (String path, int sigVersion)
1565 File target = downloadFile(path);
1567 if (sigVersion > 0) {
1568 if (_envc.certs.isEmpty()) {
1569 log.info("No signing certs, not verifying digest.txt", "path", path);
1572 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1573 byte[] signature = null;
1574 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1575 signature = StreamUtil.toByteArray(signatureStream);
1577 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1580 byte[] buffer = new byte[8192];
1581 int length, validated = 0;
1582 for (Certificate cert : _envc.certs) {
1583 try (FileInputStream dataInput = new FileInputStream(target)) {
1584 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1585 sig.initVerify(cert);
1586 while ((length = dataInput.read(buffer)) != -1) {
1587 sig.update(buffer, 0, length);
1590 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1591 log.info("Signature does not match", "cert", cert.getPublicKey());
1594 log.info("Signature matches", "cert", cert.getPublicKey());
1598 } catch (IOException ioe) {
1599 log.warning("Failure validating signature of " + target + ": " + ioe);
1601 } catch (GeneralSecurityException gse) {
1607 // if we couldn't find a key that validates our digest, we are the hosed!
1608 if (validated == 0) {
1609 // delete the temporary digest file as we know it is invalid
1610 FileUtil.deleteHarder(target);
1611 throw new IOException("m.corrupt_digest_signature_error");
1616 // now move the temporary file over the original
1617 File original = getLocalPath(path);
1618 if (!FileUtil.renameTo(target, original)) {
1619 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1624 * Download a path to a temporary file, returning a {@link File} instance with the path
1627 protected File downloadFile (String path)
1630 File target = getLocalPath(path + "_new");
1632 URL targetURL = null;
1634 targetURL = getRemoteURL(path);
1635 } catch (Exception e) {
1636 log.warning("Requested to download invalid control file",
1637 "appbase", _vappbase, "path", path, "error", e);
1638 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1641 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1643 // stream the URL into our temporary file
1644 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1645 // we have to tell Java not to use caches here, otherwise it will cache any request for
1646 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1647 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1648 // about it; turning off caches is not a performance concern, because when Getdown asks
1649 // to download a file, it expects it to come over the wire, not from a cache
1650 uconn.setUseCaches(false);
1651 uconn.setRequestProperty("Accept-Encoding", "gzip");
1652 try (InputStream fin = uconn.getInputStream()) {
1653 String encoding = uconn.getContentEncoding();
1654 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1655 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1656 try (FileOutputStream fout = new FileOutputStream(target)) {
1657 StreamUtil.copy(fin2, fout);
1665 /** Helper function for creating {@link Resource} instances. */
1666 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1667 throws MalformedURLException
1669 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1672 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1673 protected static void addAll (String[] values, List<String> target) {
1674 if (values != null) {
1675 for (String value : values) {
1682 * Make an immutable List from the specified int array.
1684 public static List<Integer> intsToList (int[] values)
1686 List<Integer> list = new ArrayList<>(values.length);
1687 for (int val : values) {
1690 return Collections.unmodifiableList(list);
1694 * Make an immutable List from the specified String array.
1696 public static List<String> stringsToList (String[] values)
1698 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1701 /** Used to parse resources with the specified name. */
1702 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1703 List<Resource> list)
1705 String[] rsrcs = config.getMultiValue(name);
1706 if (rsrcs == null) {
1709 for (String rsrc : rsrcs) {
1711 list.add(createResource(rsrc, attrs));
1712 } catch (Exception e) {
1713 log.warning("Invalid resource '" + rsrc + "'. " + e);
1718 /** Possibly generates and returns a google analytics tracking cookie. */
1719 protected String getGATrackingCode ()
1721 if (_trackingGAHash == null) {
1724 long time = System.currentTimeMillis() / 1000;
1725 if (_trackingStart == 0) {
1726 _trackingStart = time;
1728 if (_trackingId == 0) {
1729 int low = 100000000, high = 1000000000;
1730 _trackingId = low + _rando.nextInt(high-low);
1732 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1733 cookie.append(".").append(_trackingId);
1734 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1735 cookie.append(".").append(time).append(".1%3B%2B");
1736 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1737 cookie.append(_trackingStart).append(".1.1.");
1738 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1739 int low = 1000000000, high = 2000000000;
1740 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1741 return cookie.toString();
1745 * Encodes a path for use in a URL.
1747 protected static String encodePath (String path)
1750 // we want to keep slashes because we're encoding an entire path; also we need to turn
1751 // + into %20 because web servers don't like + in paths or file names, blah
1752 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1753 } catch (UnsupportedEncodingException ue) {
1754 log.warning("Failed to URL encode " + path + ": " + ue);
1759 protected File getLocalPath (File appdir, String path)
1761 return new File(appdir, path);
1764 protected final EnvConfig _envc;
1765 protected File _config;
1766 protected Digest _digest;
1768 protected long _version = -1;
1769 protected long _targetVersion = -1;
1770 protected String _appbase;
1771 protected URL _vappbase;
1772 protected URL _latest;
1773 protected String _class;
1774 protected String _dockName;
1775 protected String _dockIconPath;
1776 protected boolean _strictComments;
1777 protected boolean _windebug;
1778 protected boolean _allowOffline;
1779 protected int _maxConcDownloads;
1781 protected String _trackingURL;
1782 protected Set<Integer> _trackingPcts;
1783 protected String _trackingCookieName;
1784 protected String _trackingCookieProperty;
1785 protected String _trackingURLSuffix;
1786 protected String _trackingGAHash;
1787 protected long _trackingStart;
1788 protected int _trackingId;
1790 protected String _javaVersionProp = "java.version";
1791 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
1792 protected long _javaMinVersion, _javaMaxVersion;
1793 protected boolean _javaExactVersionRequired;
1794 protected String _javaLocation;
1796 protected List<Resource> _codes = new ArrayList<>();
1797 protected List<Resource> _resources = new ArrayList<>();
1799 protected boolean _useCodeCache;
1800 protected int _codeCacheRetentionDays;
1802 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
1803 protected Map<String,Boolean> _auxactive = new HashMap<>();
1805 protected List<String> _jvmargs = new ArrayList<>();
1806 protected List<String> _appargs = new ArrayList<>();
1808 protected String[] _optimumJvmArgs;
1810 protected List<String> _txtJvmArgs = new ArrayList<>();
1812 /** If a warning has been issued about not being able to set modtimes. */
1813 protected boolean _warnedAboutSetLastModified;
1815 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
1816 protected FileLock _lock;
1818 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
1819 protected FileChannel _lockChannel;
1821 protected Random _rando = new Random();
1823 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
1825 protected static final String ENV_VAR_PREFIX = "%ENV.";
1826 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");