2 // Getdown - application installer, patcher and launcher
3 // Copyright (C) 2004-2018 Getdown authors
4 // https://github.com/threerings/getdown/blob/master/LICENSE
6 package com.threerings.getdown.data;
9 import java.lang.reflect.Method;
10 import java.net.MalformedURLException;
11 import java.net.Proxy;
13 import java.net.URLClassLoader;
14 import java.net.URLConnection;
15 import java.net.URLEncoder;
16 import java.nio.channels.FileChannel;
17 import java.nio.channels.FileLock;
18 import java.nio.channels.OverlappingFileLockException;
19 import java.security.*;
20 import java.security.cert.Certificate;
22 import java.util.concurrent.*;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import java.util.zip.GZIPInputStream;
27 import jalview.bin.MemorySetting;
29 import com.threerings.getdown.util.*;
30 // avoid ambiguity with java.util.Base64 which we can't use as it's 1.8+
31 import com.threerings.getdown.util.Base64;
33 import com.threerings.getdown.data.EnvConfig;
34 import com.threerings.getdown.data.EnvConfig.Note;
36 import static com.threerings.getdown.Log.log;
37 import static java.nio.charset.StandardCharsets.UTF_8;
40 * Parses and provide access to the information contained in the <code>getdown.txt</code>
43 public class Application
45 /** The name of our configuration file. */
46 public static final String CONFIG_FILE = "getdown.txt";
48 /** Dir where a backup config file might reside */
49 public static final String BACKUP_CONFIG_DIR = "install";
51 /** The name of our target version file. */
52 public static final String VERSION_FILE = "version.txt";
54 /** System properties that are prefixed with this string will be passed through to our
55 * application (minus this prefix). */
56 public static final String PROP_PASSTHROUGH_PREFIX = "app.";
58 /** Suffix used for control file signatures. */
59 public static final String SIGNATURE_SUFFIX = ".sig";
61 /** A special classname that means 'use -jar code.jar' instead of a classname. */
62 public static final String MANIFEST_CLASS = "manifest";
64 /** Used to communicate information about the UI displayed when updating the application. */
65 public static final class UpdateInterface
68 * The major steps involved in updating, along with some arbitrary percentages
69 * assigned to them, to mark global progress.
74 //VERIFY_METADATA(15, 65, 95),
75 VERIFY_METADATA(15, 45, 90),
78 //VERIFY_RESOURCES(70, 97),
79 VERIFY_RESOURCES(30, 90),
80 //REDOWNLOAD_RESOURCES(90),
81 REDOWNLOAD_RESOURCES(75),
87 /** What is the final percent value for this step? */
88 public final List<Integer> defaultPercents;
90 /** Enum constructor. */
91 Step (int... percents)
93 this.defaultPercents = intsToList(percents);
97 /** The human readable name of this application. */
98 public final String name;
100 /** A background color, just in case. */
101 public final int background;
103 /** Background image specifiers for `RotatingBackgrounds`. */
104 public final List<String> rotatingBackgrounds;
106 /** The error background image for `RotatingBackgrounds`. */
107 public final String errorBackground;
109 /** The paths (relative to the appdir) of images for the window icon. */
110 public final List<String> iconImages;
112 /** The path (relative to the appdir) to a single background image to appear first. */
113 public final String instantBackgroundImage;
115 /** The path (relative to the appdir) to a single background image. */
116 public final String backgroundImage;
118 /** The path (relative to the appdir) to the progress bar image. */
119 public final String progressImage;
121 /** The dimensions of the progress bar. */
122 public final Rectangle progress;
124 /** The color of the progress text. */
125 public final int progressText;
127 /** The color of the progress bar. */
128 public final int progressBar;
130 /** The dimensions of the status display. */
131 public final Rectangle status;
133 /** The color of the status text. */
134 public final int statusText;
136 /** The color of the text shadow. */
137 public final int textShadow;
139 /** Where to point the user for help with install errors. */
140 public final String installError;
142 /** The dimensions of the patch notes button. */
143 public final Rectangle patchNotes;
145 /** The patch notes URL. */
146 public final String patchNotesUrl;
148 /** Whether window decorations are hidden for the UI. */
149 public final boolean hideDecorations;
151 /** Whether progress text should be hidden or not. */
152 public final boolean hideProgressText;
154 /** Whether the splash screen should update non-asynchronously before being shown. */
155 public final boolean progressSync;
157 /** Whether the splash screen should update non-asynchronously after being shown. */
158 public final boolean progressSyncAfterShown;
160 /** Whether the splash screen should retain focus. */
161 public final boolean keepOnTop;
163 /** Whether to display the appbase. */
164 public final boolean displayAppbase;
166 /** Whether to display the version. */
167 public final boolean displayVersion;
169 /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
170 * flashing up on the screen and immediately disappearing, which can be confusing to the
172 public final int minShowSeconds;
174 /** The global percentages for each step. A step may have more than one, and
175 * the lowest reasonable one is used if a step is revisited. */
176 public final Map<Step, List<Integer>> stepPercentages;
178 /** Generates a string representation of this instance. */
180 public String toString ()
182 return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage + ", instant_bg=" + instantBackgroundImage +
183 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
184 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
185 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
186 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
187 ", hideProgressText=" + hideProgressText + ", keepOnTop=" + keepOnTop + ", progressSync=" + progressSync +
188 ", progressSyncAfterShown=" + progressSyncAfterShown + ", minShow=" + minShowSeconds +
189 ", displayAppbase=" + displayAppbase + ", displayVersion=" + displayVersion + "]";
192 public UpdateInterface (Config config)
194 this.name = config.getString("ui.name");
195 this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
196 this.progressText = config.getColor("ui.progress_text", Color.BLACK);
197 this.hideProgressText = config.getBoolean("ui.hide_progress_text");
198 this.progressSync = config.getBoolean("ui.progress_sync_before_shown");
199 this.progressSyncAfterShown = config.getBoolean("ui.progress_sync_after_shown");
200 this.keepOnTop = config.getBoolean("ui.keep_on_top");
201 this.displayAppbase = config.getBoolean("ui.display_appbase");
202 this.displayVersion = config.getBoolean("ui.display_version");
203 this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
204 this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
205 this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
206 this.statusText = config.getColor("ui.status_text", Color.BLACK);
207 this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
208 this.hideDecorations = config.getBoolean("ui.hide_decorations");
209 this.backgroundImage = config.getString("ui.background_image");
210 this.instantBackgroundImage = config.getString("ui.instant_background_image");
211 // default to black or white bg color, depending on the brightness of the progressText
212 int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
213 Color.BLACK : Color.WHITE;
214 this.background = config.getColor("ui.background", defaultBackground);
215 this.progressImage = config.getString("ui.progress_image");
216 this.rotatingBackgrounds = stringsToList(
217 config.getMultiValue("ui.rotating_background"));
218 this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
219 this.errorBackground = config.getString("ui.error_background");
221 // On an installation error, where do we point the user.
222 String installError = config.getUrl("ui.install_error", null);
223 this.installError = (installError == null) ?
224 "m.default_install_error" : MessageUtil.taint(installError);
226 // the patch notes bits
227 this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
228 this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
230 // step progress percentage (defaults and then customized values)
231 EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
232 for (Step step : Step.values()) {
233 stepPercentages.put(step, step.defaultPercents);
235 for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
236 String spec = config.getString("ui.percents." + step.name());
239 stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
240 } catch (Exception e) {
241 log.warning("Failed to parse percentages for " + step + ": " + spec);
245 this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
250 * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
251 * take network actions.
253 public static interface StatusDisplay
255 /** Requests that the specified status message be displayed. */
256 public void updateStatus (String message);
260 * Contains metadata for an auxiliary resource group.
262 public static class AuxGroup {
263 public final String name;
264 public final List<Resource> codes;
265 public final List<Resource> rsrcs;
267 public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
269 this.codes = Collections.unmodifiableList(codes);
270 this.rsrcs = Collections.unmodifiableList(rsrcs);
274 /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
275 * the application instance. Yes this is a public mutable field, no I'm not going to create a
276 * getter and setter just to pretend like that's not the case. */
277 public Proxy proxy = Proxy.NO_PROXY;
280 * Creates an application instance which records the location of the <code>getdown.txt</code>
281 * configuration file from the supplied application directory.
284 public Application (EnvConfig envc) {
286 _config = getLocalPath(envc.appDir, CONFIG_FILE);
287 _backupConfig = getLocalPath(envc.appDir, BACKUP_CONFIG_DIR+File.separator+CONFIG_FILE);
288 log.warning("Backup config file now", "_backupConfig", _backupConfig, "exists", _backupConfig.exists(), "isReadable", _backupConfig.canRead());
292 * Returns the configured application directory.
294 public File getAppDir () {
299 * Returns whether the application should cache code resources prior to launching the
302 public boolean useCodeCache ()
304 return _useCodeCache;
308 * Returns the number of days a cached code resource is allowed to stay unused before it
309 * becomes eligible for deletion.
311 public int getCodeCacheRetentionDays ()
313 return _codeCacheRetentionDays;
317 * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
318 * app files from its hosting server.
320 public int maxConcurrentDownloads () {
321 return _maxConcDownloads;
325 * Returns a resource that refers to the application configuration file itself.
327 public Resource getConfigResource ()
331 return createResource(CONFIG_FILE, Resource.NORMAL);
332 } catch (Exception e) {
333 log.warning("Invalid appbase '" + _vappbase + "'.", e);
338 * Returns a list of the code {@link Resource} objects used by this application.
340 public List<Resource> getCodeResources ()
346 * Returns a list of the non-code {@link Resource} objects used by this application.
348 public List<Resource> getResources ()
354 * Returns the digest of the given {@code resource}.
356 public String getDigest (Resource resource)
358 return _digest.getDigest(resource);
362 * Returns a list of all the active {@link Resource} objects used by this application (code and
365 public List<Resource> getAllActiveResources ()
367 List<Resource> allResources = new ArrayList<>();
368 allResources.addAll(getActiveCodeResources());
369 allResources.addAll(getActiveResources());
374 * Returns the auxiliary resource group with the specified name, or null.
376 public AuxGroup getAuxGroup (String name)
378 return _auxgroups.get(name);
382 * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
383 * resource group is a collection of resource files that are not downloaded unless a group
384 * token file is present in the application directory.
386 public Iterable<AuxGroup> getAuxGroups ()
388 return _auxgroups.values();
392 * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
393 * groups should be ignored, activated groups should be downloaded and patched along with the
396 public boolean isAuxGroupActive (String auxgroup)
398 Boolean active = _auxactive.get(auxgroup);
399 if (active == null) {
400 // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
402 active = getLocalPath(auxgroup + ".dat").exists();
403 _auxactive.put(auxgroup, active);
409 * Returns all main code resources and all code resources from active auxiliary resource groups.
411 public List<Resource> getActiveCodeResources ()
413 ArrayList<Resource> codes = new ArrayList<>();
414 codes.addAll(getCodeResources());
415 for (AuxGroup aux : getAuxGroups()) {
416 if (isAuxGroupActive(aux.name)) {
417 codes.addAll(aux.codes);
424 * Returns all resources indicated to contain native library files (.dll, .so, etc.).
426 public List<Resource> getNativeResources ()
428 List<Resource> natives = new ArrayList<>();
429 for (Resource resource: _resources) {
430 if (resource.isNative()) {
431 natives.add(resource);
438 * Returns all non-code resources and all resources from active auxiliary resource groups.
440 public List<Resource> getActiveResources ()
442 ArrayList<Resource> rsrcs = new ArrayList<>();
443 rsrcs.addAll(getResources());
444 for (AuxGroup aux : getAuxGroups()) {
445 if (isAuxGroupActive(aux.name)) {
446 rsrcs.addAll(aux.rsrcs);
453 * Returns a resource that can be used to download a patch file that will bring this
454 * application from its current version to the target version.
456 * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
457 * for the main application patch resource.
459 public Resource getPatchResource (String auxgroup)
461 if (_targetVersion <= _version) {
462 log.warning("Requested patch resource for up-to-date or non-versioned application",
463 "cvers", _version, "tvers", _targetVersion);
467 String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
468 String pfile = "patch" + infix + _version + ".dat";
470 URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
471 return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
472 } catch (Exception e) {
473 log.warning("Failed to create patch resource path",
474 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
480 * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
481 * place of the installed VM (in the case where the VM that launched Getdown does not meet the
482 * application's version requirements) or null if no VM is available for this platform.
484 public Resource getJavaVMResource ()
486 if (StringUtil.isBlank(_javaLocation)) {
490 String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
491 String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
492 log.info("vmfile is '"+vmfile+"'");
493 System.out.println("vmfile is '"+vmfile+"'");
495 URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
496 log.info("Attempting to fetch jvm at "+remote.toString());
497 System.out.println("Attempting to fetch jvm at "+remote.toString());
498 return new Resource(vmfile, remote, getLocalPath(vmfile),
499 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
500 } catch (Exception e) {
501 log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
502 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
503 System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
504 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
510 * Returns a resource that can be used to download an archive containing all files belonging to
513 public Resource getFullResource ()
515 String file = "full";
517 URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
518 return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
519 } catch (Exception e) {
520 log.warning("Failed to create full resource path",
521 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
527 * Returns the URL to use to report an initial download event. Returns null if no tracking
528 * start URL was configured for this application.
530 * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
532 public URL getTrackingURL (String event)
535 String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
536 String ga = getGATrackingCode();
537 return _trackingURL == null ? null :
538 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
539 } catch (MalformedURLException mue) {
540 log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
546 * Returns the URL to request to report that we have reached the specified percentage of our
547 * initial download. Returns null if no tracking request was configured for the specified
550 public URL getTrackingProgressURL (int percent)
552 if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
555 return getTrackingURL("pct" + percent);
559 * Returns the name of our tracking cookie or null if it was not set.
561 public String getTrackingCookieName ()
563 return _trackingCookieName;
567 * Returns the name of our tracking cookie system property or null if it was not set.
569 public String getTrackingCookieProperty ()
571 return _trackingCookieProperty;
575 * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
576 * for operation. The application base URL will be parsed first so that if there are errors
577 * discovered later, the caller can use the application base to download a new {@code
578 * getdown.txt} file and try again.
580 * @return a {@code Config} instance that contains information from the config file.
582 * @exception IOException thrown if there is an error reading the file or an error encountered
583 * during its parsing.
585 public Config init (boolean checkPlatform)
588 Config config = null;
589 File cfgfile = _config;
590 Config.ParseOpts opts = Config.createOpts(checkPlatform);
592 // if we have a configuration file, read the data from it
593 if (cfgfile.exists()) {
594 config = Config.parseConfig(_config, opts);
596 // otherwise, try reading data from our backup config file; thanks to funny windows
597 // bullshit, we have to do this backup file fiddling in case we got screwed while
598 // updating getdown.txt during normal operation
599 else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
600 config = Config.parseConfig(cfgfile, opts);
602 // otherwise, issue a warning that we found no getdown file
604 log.info("Found no getdown.txt file", "appdir", getAppDir());
606 } catch (Exception e) {
607 log.warning("Failure reading config file", "file", _config, e);
609 if (config == null || config.getString("appbase") == null || config.getString("appbase").isEmpty()) {
611 Config backupConfig = Config.parseConfig(_backupConfig, opts);
612 config = backupConfig;
613 log.warning("Using backup config file", "appdir", getAppDir(), "backupConfig", _backupConfig.getAbsoluteFile());
614 } catch (Exception e) {
615 log.warning("Failure reading backup config file", "file", _backupConfig, e);
619 // see if there's an override config from locator file
620 Config locatorConfig = createLocatorConfig(opts);
622 // merge the locator file config into config (or replace config with)
623 if (locatorConfig != null) {
624 if (config == null || locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_replace")) {
625 config = locatorConfig;
627 config.mergeConfig(locatorConfig, locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_merge"));
631 // if we failed to read our config file, check for an appbase specified via a system
632 // property; we can use that to bootstrap ourselves back into operation
633 if (config == null) {
634 String appbase = _envc.appBase;
635 log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
636 Map<String, Object> cdata = new HashMap<>();
637 cdata.put("appbase", appbase);
638 config = new Config(cdata);
641 // first determine our application base, this way if anything goes wrong later in the
642 // process, our caller can use the appbase to download a new configuration file
643 _appbase = config.getString("appbase");
645 // see if locatorConfig override
646 if (locatorConfig != null && !StringUtil.isBlank(locatorConfig.getString("appbase"))) {
647 _appbase = locatorConfig.getString("appbase");
650 if (_appbase == null) {
651 throw new RuntimeException("m.missing_appbase");
654 // check if we're overriding the domain in the appbase
655 _appbase = SysProps.overrideAppbase(_appbase);
657 // make sure there's a trailing slash
658 if (!_appbase.endsWith("/")) {
659 _appbase = _appbase + "/";
662 // extract our version information
663 _version = config.getLong("version", -1L);
665 // if we are a versioned deployment, create a versioned appbase
667 _vappbase = createVAppBase(_version);
668 } catch (MalformedURLException mue) {
669 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
670 throw (IOException) new IOException(err).initCause(mue);
673 // check for a latest config URL
674 String latest = config.getString("latest");
675 if (latest != null) {
676 if (latest.startsWith(_appbase)) {
677 latest = _appbase + latest.substring(_appbase.length());
679 latest = SysProps.replaceDomain(latest);
682 _latest = HostWhitelist.verify(new URL(latest));
683 } catch (MalformedURLException mue) {
684 log.warning("Invalid URL for latest attribute.", mue);
688 String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
690 // determine our application class name (use app-specific class _if_ one is provided)
691 _class = config.getString("class");
692 if (appPrefix.length() > 0) {
693 _class = config.getString(appPrefix + "class", _class);
695 if (_class == null) {
696 throw new IOException("m.missing_class");
699 // determine whether we want strict comments
700 _strictComments = config.getBoolean("strict_comments");
702 // check to see if we're using a custom java.version property and regex
703 _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
704 _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
706 // check to see if we require a particular JVM version and have a supplied JVM
707 _javaMinVersion = config.getLong("java_version", _javaMinVersion);
708 // we support java_min_version as an alias of java_version; it better expresses the check
709 // that's going on and better mirrors java_max_version
710 _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
711 // check to see if we require a particular max JVM version and have a supplied JVM
712 _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
713 // check to see if we require a particular JVM version and have a supplied JVM
714 _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
716 // this is a little weird, but when we're run from the digester, we see a String[] which
717 // contains java locations for all platforms which we can't grok, but the digester doesn't
718 // need to know about that; when we're run in a real application there will be only one!
719 Object javaloc = config.getRaw("java_location");
720 if (javaloc instanceof String) {
721 _javaLocation = (String)javaloc;
724 // determine whether we have any tracking configuration
725 _trackingURL = config.getString("tracking_url");
727 // check for tracking progress percent configuration
728 String trackPcts = config.getString("tracking_percents");
729 if (!StringUtil.isBlank(trackPcts)) {
730 _trackingPcts = new HashSet<>();
731 for (int pct : StringUtil.parseIntArray(trackPcts)) {
732 _trackingPcts.add(pct);
734 } else if (!StringUtil.isBlank(_trackingURL)) {
735 _trackingPcts = new HashSet<>();
736 _trackingPcts.add(50);
739 // Check for tracking cookie configuration
740 _trackingCookieName = config.getString("tracking_cookie_name");
741 _trackingCookieProperty = config.getString("tracking_cookie_property");
743 // Some app may need an extra suffix added to the tracking URL
744 _trackingURLSuffix = config.getString("tracking_url_suffix");
746 // Some app may need to generate google analytics code
747 _trackingGAHash = config.getString("tracking_ga_hash");
749 // clear our arrays as we may be reinitializing
757 // parse our code resources
758 if (config.getMultiValue("code") == null &&
759 config.getMultiValue("ucode") == null) {
760 throw new IOException("m.missing_code");
762 parseResources(config, "code", Resource.NORMAL, _codes);
763 parseResources(config, "ucode", Resource.UNPACK, _codes);
765 // parse our non-code resources
766 parseResources(config, "resource", Resource.NORMAL, _resources);
767 parseResources(config, "uresource", Resource.UNPACK, _resources);
768 parseResources(config, "xresource", Resource.EXEC, _resources);
769 parseResources(config, "presource", Resource.PRELOAD, _resources);
770 parseResources(config, "nresource", Resource.NATIVE, _resources);
772 // parse our auxiliary resource groups
773 for (String auxgroup : config.getList("auxgroups")) {
774 ArrayList<Resource> codes = new ArrayList<>();
775 parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
776 parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
777 ArrayList<Resource> rsrcs = new ArrayList<>();
778 parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
779 parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
780 parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
781 parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
782 parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
783 _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
786 // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
787 String[] jvmargs = config.getMultiValue("jvmarg");
788 addAll(jvmargs, _jvmargs);
789 if (appPrefix.length() > 0) {
790 jvmargs = config.getMultiValue(appPrefix + "jvmarg");
791 addAll(jvmargs, _jvmargs);
794 // see if a percentage of physical memory option exists
795 int jvmmempc = config.getInt("jvmmempc", -1);
796 // app_id prefixed setting overrides
797 if (appPrefix.length() > 0) {
798 jvmmempc = config.getInt(appPrefix + "jvmmempc", jvmmempc);
800 if (0 <= jvmmempc && jvmmempc <= 100) {
802 long maxMemLong = -1;
806 maxMemLong = MemorySetting.memPercent(jvmmempc);
807 } catch (Exception e)
810 } catch (Throwable t)
818 String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
819 // remove other max heap size arg
820 ARG: for (int i = 0; i < _jvmargs.size(); i++) {
821 if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
825 addAll(maxMemHeapArg, _jvmargs);
829 } else if (jvmmempc != -1) {
830 System.out.println("'jvmmempc' value must be in range 0 to 100 (read as '"+Integer.toString(jvmmempc)+"')");
833 // get the set of optimum JVM arguments
834 _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
836 // transfer our application arguments
837 String[] appargs = config.getMultiValue(appPrefix + "apparg");
838 addAll(appargs, _appargs);
840 // add the launch specific application arguments
841 _appargs.addAll(_envc.appArgs);
843 // look for custom arguments
844 fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
846 // determine whether we want to allow offline operation (defaults to false)
847 _allowOffline = config.getBoolean("allow_offline");
849 // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
850 // obtain a thread dump of the running JVM
851 _windebug = getLocalPath("debug.txt").exists();
853 // whether to cache code resources and launch from cache
854 _useCodeCache = config.getBoolean("use_code_cache");
855 _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
857 // maximum simultaneous downloads
858 _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
859 SysProps.threadPoolSize()));
861 // extract some info used to configure our child process on macOS
862 _dockName = config.getString("ui.name");
863 _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
869 * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
871 protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
873 File pairFile = getLocalPath(pairLocation);
874 if (pairFile.exists()) {
876 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
877 for (String[] pair : args) {
878 if (pair[1].length() == 0) {
879 collector.add(pair[0]);
881 collector.add(pair[0] + "=" + pair[1]);
884 } catch (Throwable t) {
885 log.warning("Failed to parse '" + pairFile + "': " + t);
891 * Returns a URL from which the specified path can be fetched. Our application base URL is
892 * properly versioned and combined with the supplied path.
894 public URL getRemoteURL (String path)
895 throws MalformedURLException
897 return new URL(_vappbase, encodePath(path));
901 * Returns the local path to the specified resource.
903 public File getLocalPath (String path)
905 return getLocalPath(getAppDir(), path);
909 * Returns true if we either have no version requirement, are running in a JVM that meets our
910 * version requirements or have what appears to be a version of the JVM that meets our
913 public boolean haveValidJavaVersion ()
915 // if we're doing no version checking, then yay!
916 if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
919 // parse the version out of the java.version (or custom) system property
920 long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
922 log.info("Checking Java version", "current", version,
923 "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
925 // if we have an unpacked VM, check the 'release' file for its version
926 Resource vmjar = getJavaVMResource();
927 if (vmjar != null && vmjar.isMarkedValid()) {
928 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
929 File relfile = new File(vmdir, "release");
930 if (!relfile.exists()) {
931 log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
935 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
937 log.warning("Unable to read version from 'release' file. Assuming valid.");
942 log.info("Checking version of unpacked JVM [vers=" + version + "].");
945 if (_javaExactVersionRequired) {
946 if (version == _javaMinVersion) return true;
948 log.warning("An exact Java VM version is required.", "current", version,
949 "required", _javaMinVersion);
954 boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
955 boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
956 return minVersionOK && maxVersionOK;
958 } catch (RuntimeException re) {
959 // if we can't parse the java version we're in weird land and should probably just try
960 // our luck with what we've got rather than try to download a new jvm
961 log.warning("Unable to parse VM version, hoping for the best",
962 "error", re, "needed", _javaMinVersion);
968 * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
969 * whether the launch is successful and, if necessary, trying again without the optimum
972 public boolean hasOptimumJvmArgs ()
974 return _optimumJvmArgs != null;
978 * Returns true if the app should attempt to run even if we have no Internet connection.
980 public boolean allowOffline ()
982 return _allowOffline;
986 * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
987 * previous call to {@link #init}.
989 public void attemptRecovery (StatusDisplay status)
992 status.updateStatus("m.updating_metadata");
993 downloadConfigFile();
997 * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
998 * those for the target version of our application.
1000 public void updateMetadata ()
1004 // update our versioned application base with the target version
1005 _vappbase = createVAppBase(_targetVersion);
1006 } catch (MalformedURLException mue) {
1007 String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
1008 throw (IOException) new IOException(err).initCause(mue);
1012 // now re-download our control files; we download the digest first so that if it fails,
1013 // our config file will still reference the old version and re-running the updater will
1014 // start the whole process over again
1015 downloadDigestFiles();
1016 downloadConfigFile();
1018 } catch (IOException ex) {
1019 // if we are allowing offline execution, we want to allow the application to run in its
1020 // current form rather than aborting the entire process; to do this, we delete the
1021 // version.txt file and "trick" Getdown into thinking that it just needs to validate
1022 // the application as is; next time the app runs when connected to the internet, it
1023 // will have to rediscover that it needs updating and reattempt to update itself
1024 if (_allowOffline) {
1025 log.warning("Failed to update digest files. Attempting offline operaton.", ex);
1026 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
1027 log.warning("Deleting version.txt failed. This probably isn't going to work.");
1036 * Invokes the process associated with this application definition.
1038 * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
1041 public Process createProcess (boolean optimum)
1044 ArrayList<String> args = new ArrayList<>();
1046 // reconstruct the path to the JVM
1047 args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
1049 // check whether we're using -jar mode or -classpath mode
1050 boolean dashJarMode = MANIFEST_CLASS.equals(_class);
1052 // add the -classpath arguments if we're not in -jar mode
1053 ClassPath classPath = PathBuilder.buildClassPath(this);
1055 args.add("-classpath");
1056 args.add(classPath.asArgumentString());
1059 // we love our Mac users, so we do nice things to preserve our application identity
1060 if (LaunchUtil.isMacOS()) {
1061 args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1062 args.add("-Xdock:name=" + _dockName);
1065 // pass along our proxy settings
1067 if ((proxyHost = System.getProperty("http.proxyHost")) != null) {
1068 args.add("-Dhttp.proxyHost=" + proxyHost);
1069 args.add("-Dhttp.proxyPort=" + System.getProperty("http.proxyPort"));
1070 args.add("-Dhttps.proxyHost=" + proxyHost);
1071 args.add("-Dhttps.proxyPort=" + System.getProperty("http.proxyPort"));
1074 // add the marker indicating the app is running in getdown
1075 args.add("-D" + Properties.GETDOWN + "=true");
1077 // set the native library path if we have native resources
1078 // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1079 ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1080 if (javaLibPath != null) {
1081 args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1084 // pass along any pass-through arguments
1085 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1086 String key = (String)entry.getKey();
1087 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1088 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1089 args.add("-D" + key + "=" + entry.getValue());
1093 // add the JVM arguments
1094 for (String string : _jvmargs) {
1095 args.add(processArg(string));
1098 // add the optimum arguments if requested and available
1099 if (optimum && _optimumJvmArgs != null) {
1100 for (String string : _optimumJvmArgs) {
1101 args.add(processArg(string));
1105 // add the arguments from extra.txt (after the optimum ones, in case they override them)
1106 for (String string : _txtJvmArgs) {
1107 args.add(processArg(string));
1110 // if we're in -jar mode add those arguments, otherwise add the app class name
1113 args.add(classPath.asArgumentString());
1118 // almost finally check the startup file arguments
1119 for (File f : _startupFiles) {
1120 _appargs.add(f.getAbsolutePath());
1121 break; // Only add one file to open
1124 // check if one arg with recognised extension
1125 if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1126 String filename = _appargs.get(0);
1128 int j = filename.lastIndexOf('.');
1130 ext = filename.substring(j+1);
1132 if (LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase())) {
1133 // this file extension should have been dealt with in Getdown class
1135 _appargs.add(0, "-open");
1139 // finally add the application arguments
1140 for (String string : _appargs) {
1141 args.add(processArg(string));
1144 String[] envp = createEnvironment();
1145 String[] sargs = args.toArray(new String[args.size()]);
1146 log.info("Running " + StringUtil.join(sargs, "\n "));
1148 return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1152 * If the application provided environment variables, combine those with the current
1153 * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1154 * If the application didn't provide any environment variables, null is returned to just use
1155 * the existing environment.
1157 protected String[] createEnvironment ()
1159 List<String> envvar = new ArrayList<>();
1160 fillAssignmentListFromPairs("env.txt", envvar);
1161 if (envvar.isEmpty()) {
1162 log.info("Didn't find any custom environment variables, not setting any.");
1166 List<String> envAssignments = new ArrayList<>();
1167 for (String assignment : envvar) {
1168 envAssignments.add(processArg(assignment));
1170 for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1171 envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1173 String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1174 log.info("Environment " + StringUtil.join(envp, "\n "));
1179 * Runs this application directly in the current VM.
1181 public void invokeDirect () throws IOException
1183 ClassPath classPath = PathBuilder.buildClassPath(this);
1184 URL[] jarUrls = classPath.asUrls();
1186 // create custom class loader
1187 URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1188 @Override protected PermissionCollection getPermissions (CodeSource code) {
1189 Permissions perms = new Permissions();
1190 perms.add(new AllPermission());
1194 Thread.currentThread().setContextClassLoader(loader);
1196 log.info("Configured URL class loader:");
1197 for (URL url : jarUrls) log.info(" " + url);
1199 // configure any system properties that we can
1200 for (String jvmarg : _jvmargs) {
1201 if (jvmarg.startsWith("-D")) {
1202 jvmarg = processArg(jvmarg.substring(2));
1203 int eqidx = jvmarg.indexOf("=");
1205 log.warning("Bogus system property: '" + jvmarg + "'?");
1207 System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1212 // pass along any pass-through arguments
1213 Map<String, String> passProps = new HashMap<>();
1214 for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1215 String key = (String)entry.getKey();
1216 if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1217 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1218 passProps.put(key, (String)entry.getValue());
1221 // we can't set these in the above loop lest we get a ConcurrentModificationException
1222 for (Map.Entry<String, String> entry : passProps.entrySet()) {
1223 System.setProperty(entry.getKey(), entry.getValue());
1226 // prepare our app arguments
1227 String[] args = new String[_appargs.size()];
1228 for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1231 log.info("Loading " + _class);
1232 Class<?> appclass = loader.loadClass(_class);
1233 Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1234 log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1235 main.invoke(null, new Object[] { args });
1236 } catch (Exception e) {
1237 log.warning("Failure invoking app main", e);
1241 /** Replaces the application directory and version in any argument. */
1242 protected String processArg (String arg)
1244 arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1245 arg = arg.replace("%VERSION%", String.valueOf(_version));
1247 // if this argument contains %ENV.FOO% replace those with the associated values looked up
1248 // from the environment
1249 if (arg.contains(ENV_VAR_PREFIX)) {
1250 StringBuffer sb = new StringBuffer();
1251 Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1252 while (matcher.find()) {
1253 String varName = matcher.group(1), varValue = System.getenv(varName);
1254 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1255 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1257 matcher.appendTail(sb);
1258 arg = sb.toString();
1265 * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1266 * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1267 * whether or not the application needs to be updated or whether we can proceed to verification
1270 * @return true if the application needs to be updated, false if it is up to date and can be
1271 * verified and executed.
1273 * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1276 public boolean verifyMetadata (StatusDisplay status)
1279 log.info("Verifying application: " + _vappbase);
1280 log.info("Version: " + _version);
1281 log.info("Class: " + _class);
1283 // this will read in the contents of the digest file and validate itself
1285 _digest = new Digest(getAppDir(), _strictComments);
1286 } catch (IOException ioe) {
1287 log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1290 // if we have no version, then we are running in unversioned mode so we need to download
1291 // our digest.txt file on every invocation
1292 if (_version == -1) {
1293 // make a note of the old meta-digest, if this changes we need to revalidate all of our
1294 // resources as one or more of them have also changed
1295 String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1297 status.updateStatus("m.checking");
1298 downloadDigestFiles();
1299 _digest = new Digest(getAppDir(), _strictComments);
1300 if (!olddig.equals(_digest.getMetaDigest())) {
1301 log.info("Unversioned digest changed. Revalidating...");
1302 status.updateStatus("m.validating");
1303 clearValidationMarkers();
1305 } catch (IOException ioe) {
1306 log.warning("Failed to refresh non-versioned digest: " +
1307 ioe.getMessage() + ". Proceeding...");
1311 // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1312 // redownload the digest file and give it another good college try; this time we allow
1313 // exceptions to propagate up to the caller as there is nothing else we can do
1314 if (_digest == null) {
1315 status.updateStatus("m.updating_metadata");
1316 downloadDigestFiles();
1317 _digest = new Digest(getAppDir(), _strictComments);
1320 // now verify the contents of our main config file
1321 Resource crsrc = getConfigResource();
1322 if (!_digest.validateResource(crsrc, null)) {
1323 status.updateStatus("m.updating_metadata");
1324 // attempt to redownload both of our metadata files; again we pass errors up to our
1325 // caller because there's nothing we can do to automatically recover
1326 downloadConfigFile();
1327 downloadDigestFiles();
1328 _digest = new Digest(getAppDir(), _strictComments);
1329 // revalidate everything if we end up downloading new metadata
1330 clearValidationMarkers();
1331 // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1332 if (_digest.validateResource(crsrc, null)) {
1335 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1336 "Blindly forging onward.");
1340 // start by assuming we are happy with our version
1341 _targetVersion = _version;
1343 // if we are a versioned application, read in the contents of the version.txt file
1344 // and/or check the latest config URL for a newer version
1345 if (_version != -1) {
1346 File vfile = getLocalPath(VERSION_FILE);
1347 long fileVersion = VersionUtil.readVersion(vfile);
1348 if (fileVersion != -1) {
1349 _targetVersion = fileVersion;
1352 if (_latest != null) {
1353 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1354 InputStreamReader reader = new InputStreamReader(in, UTF_8);
1355 BufferedReader bin = new BufferedReader(reader)) {
1356 for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1357 if (pair[0].equals("version")) {
1358 _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1359 if (fileVersion != -1 && _targetVersion > fileVersion) {
1360 // replace the file with the newest version
1361 try (FileOutputStream fos = new FileOutputStream(vfile);
1362 PrintStream out = new PrintStream(fos)) {
1363 out.println(_targetVersion);
1369 } catch (Exception e) {
1370 log.warning("Unable to retrieve version from latest config file.", e);
1375 // finally let the caller know if we need an update
1376 return _version != _targetVersion;
1380 * Verifies the code and media resources associated with this application. A list of resources
1381 * that do not exist or fail the verification process will be returned. If all resources are
1382 * ready to go, null will be returned and the application is considered ready to run.
1384 * @param obs a progress observer that will be notified of verification progress. NOTE: this
1385 * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1386 * you have to take care to get back to your UI thread.
1387 * @param alreadyValid if non-null a 1 element array that will have the number of "already
1388 * validated" resources filled in.
1389 * @param unpacked a set to populate with unpacked resources.
1390 * @param toInstall a list into which to add resources that need to be installed.
1391 * @param toDownload a list into which to add resources that need to be downloaded.
1393 public void verifyResources (
1394 ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1395 Set<Resource> toInstall, Set<Resource> toDownload)
1396 throws InterruptedException
1398 // resources are verified on background threads supplied by the thread pool, and progress
1399 // is reported by posting runnable actions to the actions queue which is processed by the
1401 ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1402 final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1403 final int[] completed = new int[1];
1405 long start = System.currentTimeMillis();
1407 // obtain the sizes of the resources to validate
1408 List<Resource> rsrcs = getAllActiveResources();
1409 long[] sizes = new long[rsrcs.size()];
1411 for (int ii = 0; ii < sizes.length; ii++) {
1412 totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1414 final ProgressObserver fobs = obs;
1415 // as long as we forward aggregated progress updates to the UI thread, having multiple
1416 // threads update a progress aggregator is "mostly" thread-safe
1417 final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1418 public void progress (final int percent) {
1419 actions.add(new Runnable() {
1420 public void run () {
1421 fobs.progress(percent);
1427 final int[] fAlreadyValid = alreadyValid;
1428 final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1429 final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1430 final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1432 for (int ii = 0; ii < sizes.length; ii++) {
1433 final Resource rsrc = rsrcs.get(ii);
1434 final int index = ii;
1435 exec.execute(new Runnable() {
1436 public void run () {
1437 verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1438 unpackedAsync, toInstallAsync, toDownloadAsync);
1439 actions.add(new Runnable() {
1440 public void run () {
1448 while (completed[0] < rsrcs.size()) {
1449 // we should be getting progress completion updates WAY more often than one every
1450 // minute, so if things freeze up for 60 seconds, abandon ship
1451 Runnable action = actions.poll(60, TimeUnit.SECONDS);
1457 toInstall.addAll(toInstallAsync);
1458 toDownload.addAll(toDownloadAsync);
1459 unpacked.addAll(unpackedAsync);
1461 long complete = System.currentTimeMillis();
1462 log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1463 "duration", (complete-start) + "ms");
1466 private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1467 Set<Resource> unpacked,
1468 Set<Resource> toInstall, Set<Resource> toDownload) {
1469 if (rsrc.isMarkedValid()) {
1470 if (alreadyValid != null) {
1478 if (_digest.validateResource(rsrc, obs)) {
1479 // if the resource has a _new file, add it to to-install list
1480 if (rsrc.getLocalNew().exists()) {
1481 toInstall.add(rsrc);
1490 } catch (Exception e) {
1491 log.info("Failure verifying resource. Requesting redownload...",
1492 "rsrc", rsrc, "error", e);
1497 toDownload.add(rsrc);
1501 * Unpacks the resources that require it (we know that they're valid).
1503 * @param unpacked a set of resources to skip because they're already unpacked.
1505 public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1506 throws InterruptedException
1508 List<Resource> rsrcs = getActiveResources();
1510 // remove resources that we don't want to unpack
1511 for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1512 Resource rsrc = it.next();
1513 if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1518 // obtain the sizes of the resources to unpack
1519 long[] sizes = new long[rsrcs.size()];
1520 for (int ii = 0; ii < sizes.length; ii++) {
1521 sizes[ii] = rsrcs.get(ii).getLocal().length();
1524 ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1525 for (int ii = 0; ii < sizes.length; ii++) {
1526 Resource rsrc = rsrcs.get(ii);
1527 ProgressObserver pobs = pagg.startElement(ii);
1530 } catch (IOException ioe) {
1531 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1538 * Clears all validation marker files.
1540 public void clearValidationMarkers ()
1542 clearValidationMarkers(getAllActiveResources().iterator());
1546 * Returns the version number for the application. Should only be called after successful
1547 * return of verifyMetadata.
1549 public long getVersion ()
1555 * Creates a versioned application base URL for the specified version.
1557 protected URL createVAppBase (long version)
1558 throws MalformedURLException
1560 String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1561 return HostWhitelist.verify(new URL(url));
1565 * Clears all validation marker files for the resources in the supplied iterator.
1567 protected void clearValidationMarkers (Iterator<Resource> iter)
1569 while (iter.hasNext()) {
1570 iter.next().clearMarker();
1575 * Downloads a new copy of CONFIG_FILE.
1577 protected void downloadConfigFile ()
1580 downloadControlFile(CONFIG_FILE, 0);
1584 * @return true if gettingdown.lock was unlocked, already locked by this application or if
1585 * we're not locking at all.
1587 public synchronized boolean lockForUpdates ()
1589 if (_lock != null && _lock.isValid()) {
1593 _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1594 } catch (FileNotFoundException e) {
1595 log.warning("Unable to create lock file", "message", e.getMessage(), e);
1599 _lock = _lockChannel.tryLock();
1600 } catch (IOException e) {
1601 log.warning("Unable to create lock", "message", e.getMessage(), e);
1603 } catch (OverlappingFileLockException e) {
1604 log.warning("The lock is held elsewhere in this JVM", e);
1607 log.info("Able to lock for updates: " + (_lock != null));
1608 return _lock != null;
1612 * Release gettingdown.lock
1614 public synchronized void releaseLock ()
1616 if (_lock != null) {
1617 log.info("Releasing lock");
1620 } catch (IOException e) {
1621 log.warning("Unable to release lock", "message", e.getMessage(), e);
1624 _lockChannel.close();
1625 } catch (IOException e) {
1626 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1628 _lockChannel = null;
1634 * Downloads the digest files and validates their signature.
1635 * @throws IOException
1637 protected void downloadDigestFiles ()
1640 for (int version = 1; version <= Digest.VERSION; version++) {
1641 downloadControlFile(Digest.digestFile(version), version);
1646 * Downloads a new copy of the specified control file, optionally validating its signature.
1647 * If the download is successful, moves it over the old file on the filesystem.
1649 * <p> TODO: Switch to PKCS #7 or CMS.
1651 * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1652 * should indicate the version of the digest file being validated which indicates which
1653 * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1655 protected void downloadControlFile (String path, int sigVersion)
1658 File target = downloadFile(path);
1660 if (sigVersion > 0) {
1661 if (_envc.certs.isEmpty()) {
1662 log.info("No signing certs, not verifying digest.txt", "path", path);
1665 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1666 byte[] signature = null;
1667 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1668 signature = StreamUtil.toByteArray(signatureStream);
1670 FileUtil.deleteHarder(signatureFile); // delete the file regardless
1673 byte[] buffer = new byte[8192];
1674 int length, validated = 0;
1675 for (Certificate cert : _envc.certs) {
1676 try (FileInputStream dataInput = new FileInputStream(target)) {
1677 Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1678 sig.initVerify(cert);
1679 while ((length = dataInput.read(buffer)) != -1) {
1680 sig.update(buffer, 0, length);
1683 if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1684 log.info("Signature does not match", "cert", cert.getPublicKey());
1687 log.info("Signature matches", "cert", cert.getPublicKey());
1691 } catch (IOException ioe) {
1692 log.warning("Failure validating signature of " + target + ": " + ioe);
1694 } catch (GeneralSecurityException gse) {
1700 // if we couldn't find a key that validates our digest, we are the hosed!
1701 if (validated == 0) {
1702 // delete the temporary digest file as we know it is invalid
1703 FileUtil.deleteHarder(target);
1704 throw new IOException("m.corrupt_digest_signature_error");
1709 // now move the temporary file over the original
1710 File original = getLocalPath(path);
1711 if (!FileUtil.renameTo(target, original)) {
1712 throw new IOException("Failed to rename(" + target + ", " + original + ")");
1717 * Download a path to a temporary file, returning a {@link File} instance with the path
1720 protected File downloadFile (String path)
1723 File target = getLocalPath(path + "_new");
1725 URL targetURL = null;
1727 targetURL = getRemoteURL(path);
1728 } catch (Exception e) {
1729 log.warning("Requested to download invalid control file",
1730 "appbase", _vappbase, "path", path, "error", e);
1731 throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1734 log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1736 // stream the URL into our temporary file
1737 URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1738 // we have to tell Java not to use caches here, otherwise it will cache any request for
1739 // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1740 // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1741 // about it; turning off caches is not a performance concern, because when Getdown asks
1742 // to download a file, it expects it to come over the wire, not from a cache
1743 uconn.setUseCaches(false);
1744 uconn.setRequestProperty("Accept-Encoding", "gzip");
1745 try (InputStream fin = uconn.getInputStream()) {
1746 String encoding = uconn.getContentEncoding();
1747 boolean gzip = "gzip".equalsIgnoreCase(encoding);
1748 try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1749 try (FileOutputStream fout = new FileOutputStream(target)) {
1750 StreamUtil.copy(fin2, fout);
1758 /** Helper function for creating {@link Resource} instances. */
1759 protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1760 throws MalformedURLException
1762 return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1765 /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1766 protected static void addAll (String[] values, List<String> target) {
1767 if (values != null) {
1768 for (String value : values) {
1775 * Make an immutable List from the specified int array.
1777 public static List<Integer> intsToList (int[] values)
1779 List<Integer> list = new ArrayList<>(values.length);
1780 for (int val : values) {
1783 return Collections.unmodifiableList(list);
1787 * Make an immutable List from the specified String array.
1789 public static List<String> stringsToList (String[] values)
1791 return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1794 /** Used to parse resources with the specified name. */
1795 protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1796 List<Resource> list)
1798 String[] rsrcs = config.getMultiValue(name);
1799 if (rsrcs == null) {
1802 for (String rsrc : rsrcs) {
1804 list.add(createResource(rsrc, attrs));
1805 } catch (Exception e) {
1806 log.warning("Invalid resource '" + rsrc + "'. " + e);
1811 /** Possibly generates and returns a google analytics tracking cookie. */
1812 protected String getGATrackingCode ()
1814 if (_trackingGAHash == null) {
1817 long time = System.currentTimeMillis() / 1000;
1818 if (_trackingStart == 0) {
1819 _trackingStart = time;
1821 if (_trackingId == 0) {
1822 int low = 100000000, high = 1000000000;
1823 _trackingId = low + _rando.nextInt(high-low);
1825 StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1826 cookie.append(".").append(_trackingId);
1827 cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1828 cookie.append(".").append(time).append(".1%3B%2B");
1829 cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1830 cookie.append(_trackingStart).append(".1.1.");
1831 cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1832 int low = 1000000000, high = 2000000000;
1833 cookie.append("&utmn=").append(_rando.nextInt(high-low));
1834 return cookie.toString();
1838 * Encodes a path for use in a URL.
1840 protected static String encodePath (String path)
1843 // we want to keep slashes because we're encoding an entire path; also we need to turn
1844 // + into %20 because web servers don't like + in paths or file names, blah
1845 return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1846 } catch (UnsupportedEncodingException ue) {
1847 log.warning("Failed to URL encode " + path + ": " + ue);
1852 protected File getLocalPath (File appdir, String path)
1854 return new File(appdir, path);
1857 public static void setStartupFilesFromParameterString(String p) {
1858 // multiple files *might* be passed in as space separated quoted filenames
1860 if (!StringUtil.isBlank(p)) {
1862 // split quoted params or treat as single string array
1863 if (p.startsWith(q) && p.endsWith(q)) {
1864 // this fails if, e.g.
1865 // p=q("stupidfilename\" " "otherfilename")
1866 // let's hope no-one ever ends a filename with '" '
1867 filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1869 // single unquoted filename
1870 filenames = new String[]{p};
1873 // check for locator file. Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1874 String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
1876 !StringUtil.isBlank(locatorFilename)
1877 && locatorFilename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)
1879 setLocatorFile(locatorFilename);
1880 // remove the locator filename from the filenames array
1881 String[] otherFilenames = new String[filenames.length - 1];
1882 System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
1883 filenames = otherFilenames;
1886 for (int i = 0; i < filenames.length; i++) {
1887 String filename = filenames[i];
1888 // skip any other locator files in a multiple file list
1889 if (! filename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
1890 addStartupFile(filename);
1896 public static void setLocatorFile(String filename) {
1897 _locatorFile = new File(filename);
1900 public static void addStartupFile(String filename) {
1901 _startupFiles.add(new File(filename));
1904 private Config createLocatorConfig(Config.ParseOpts opts) {
1905 if (_locatorFile == null) {
1909 Config locatorConfig = null;
1912 Config tmpConfig = null;
1913 Map<String, Object> tmpData = new HashMap<>();
1914 if (_locatorFile.exists()) {
1915 tmpConfig = Config.parseConfig(_locatorFile, opts);
1916 // appbase is sanitised in HostWhitelist
1917 Map<String, Object> tmpConfigData = tmpConfig.getData();
1918 if (tmpConfig != null) {
1919 for (Map.Entry<String, Object> entry : tmpConfigData.entrySet()) {
1920 String key = entry.getKey();
1921 Object value = entry.getValue();
1922 String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
1923 if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
1924 tmpData.put(key, value);
1928 log.warning("Error occurred reading config file", "file", _locatorFile);
1931 log.warning("Given locator file does not exist", "file", _locatorFile);
1934 locatorConfig = new Config(tmpData);
1936 } catch (Exception e) {
1937 log.warning("Failure reading locator file", "file", _locatorFile, e);
1940 return locatorConfig;
1943 public String getAppbase() {
1947 protected final EnvConfig _envc;
1948 protected File _config;
1949 protected File _backupConfig;
1950 protected Digest _digest;
1952 protected long _version = -1;
1953 protected long _targetVersion = -1;
1954 protected String _appbase;
1955 protected URL _vappbase;
1956 protected URL _latest;
1957 protected String _class;
1958 protected String _dockName;
1959 protected String _dockIconPath;
1960 protected boolean _strictComments;
1961 protected boolean _windebug;
1962 protected boolean _allowOffline;
1963 protected int _maxConcDownloads;
1965 protected String _trackingURL;
1966 protected Set<Integer> _trackingPcts;
1967 protected String _trackingCookieName;
1968 protected String _trackingCookieProperty;
1969 protected String _trackingURLSuffix;
1970 protected String _trackingGAHash;
1971 protected long _trackingStart;
1972 protected int _trackingId;
1974 protected String _javaVersionProp = "java.version";
1975 protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
1976 protected long _javaMinVersion, _javaMaxVersion;
1977 protected boolean _javaExactVersionRequired;
1978 protected String _javaLocation;
1980 protected List<Resource> _codes = new ArrayList<>();
1981 protected List<Resource> _resources = new ArrayList<>();
1983 protected boolean _useCodeCache;
1984 protected int _codeCacheRetentionDays;
1986 protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
1987 protected Map<String,Boolean> _auxactive = new HashMap<>();
1989 protected List<String> _jvmargs = new ArrayList<>();
1990 protected List<String> _appargs = new ArrayList<>();
1992 protected String[] _optimumJvmArgs;
1994 protected List<String> _txtJvmArgs = new ArrayList<>();
1996 /** If a warning has been issued about not being able to set modtimes. */
1997 protected boolean _warnedAboutSetLastModified;
1999 /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
2000 protected FileLock _lock;
2002 /** Channel to the file underlying _lock. Kept around solely so the lock doesn't close. */
2003 protected FileChannel _lockChannel;
2005 protected Random _rando = new Random();
2007 protected static final String[] EMPTY_STRING_ARRAY = new String[0];
2009 protected static final String ENV_VAR_PREFIX = "%ENV.";
2010 protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
2012 protected static File _locatorFile;
2013 protected static List<File> _startupFiles = new ArrayList<>();
2014 public static final String LOCATOR_FILE_EXTENSION = "jvl";