JAL-3322 Once background displayed, allow asynchronous progress setting
[jalview.git] / getdown / src / getdown / core / src / main / java / com / threerings / getdown / data / Application.java
1 //
2 // Getdown - application installer, patcher and launcher
3 // Copyright (C) 2004-2018 Getdown authors
4 // https://github.com/threerings/getdown/blob/master/LICENSE
5
6 package com.threerings.getdown.data;
7
8 import java.io.*;
9 import java.lang.reflect.Method;
10 import java.net.MalformedURLException;
11 import java.net.Proxy;
12 import java.net.URL;
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;
21 import java.util.*;
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;
28
29 import jalview.bin.MemorySetting;
30
31 import com.threerings.getdown.util.*;
32 // avoid ambiguity with java.util.Base64 which we can't use as it's 1.8+
33 import com.threerings.getdown.util.Base64;
34
35 import com.threerings.getdown.data.EnvConfig;
36 import com.threerings.getdown.data.EnvConfig.Note;
37
38 import static com.threerings.getdown.Log.log;
39 import static java.nio.charset.StandardCharsets.UTF_8;
40
41 /**
42  * Parses and provide access to the information contained in the <code>getdown.txt</code>
43  * configuration file.
44  */
45 public class Application
46 {
47     /** The name of our configuration file. */
48     public static final String CONFIG_FILE = "getdown.txt";
49
50     /** The name of our target version file. */
51     public static final String VERSION_FILE = "version.txt";
52
53     /** System properties that are prefixed with this string will be passed through to our
54      * application (minus this prefix). */
55     public static final String PROP_PASSTHROUGH_PREFIX = "app.";
56
57     /** Suffix used for control file signatures. */
58     public static final String SIGNATURE_SUFFIX = ".sig";
59
60     /** A special classname that means 'use -jar code.jar' instead of a classname. */
61     public static final String MANIFEST_CLASS = "manifest";
62
63     /** Used to communicate information about the UI displayed when updating the application. */
64     public static final class UpdateInterface
65     {
66         /**
67          * The major steps involved in updating, along with some arbitrary percentages
68          * assigned to them, to mark global progress.
69          */
70         public enum Step
71         {
72             UPDATE_JAVA(10),
73             //VERIFY_METADATA(15, 65, 95),
74             VERIFY_METADATA(15, 45, 90),
75             DOWNLOAD(50),
76             PATCH(60),
77             //VERIFY_RESOURCES(70, 97),
78             VERIFY_RESOURCES(30, 60),
79             //REDOWNLOAD_RESOURCES(90),
80             REDOWNLOAD_RESOURCES(70),
81             //UNPACK(98),
82             UNPACK(90),
83             //LAUNCH(99);
84             LAUNCH(100);
85
86             /** What is the final percent value for this step? */
87             public final List<Integer> defaultPercents;
88
89             /** Enum constructor. */
90             Step (int... percents)
91             {
92                 this.defaultPercents = intsToList(percents);
93             }
94         }
95
96         /** The human readable name of this application. */
97         public final String name;
98
99         /** A background color, just in case. */
100         public final int background;
101
102         /** Background image specifiers for `RotatingBackgrounds`. */
103         public final List<String> rotatingBackgrounds;
104
105         /** The error background image for `RotatingBackgrounds`. */
106         public final String errorBackground;
107
108         /** The paths (relative to the appdir) of images for the window icon. */
109         public final List<String> iconImages;
110
111         /** The path (relative to the appdir) to a single background image to appear first. */
112         public final String instantBackgroundImage;
113
114         /** The path (relative to the appdir) to a single background image. */
115         public final String backgroundImage;
116
117         /** The path (relative to the appdir) to the progress bar image. */
118         public final String progressImage;
119
120         /** The dimensions of the progress bar. */
121         public final Rectangle progress;
122
123         /** The color of the progress text. */
124         public final int progressText;
125
126         /** The color of the progress bar. */
127         public final int progressBar;
128
129         /** The dimensions of the status display. */
130         public final Rectangle status;
131
132         /** The color of the status text. */
133         public final int statusText;
134
135         /** The color of the text shadow. */
136         public final int textShadow;
137
138         /** Where to point the user for help with install errors. */
139         public final String installError;
140
141         /** The dimensions of the patch notes button. */
142         public final Rectangle patchNotes;
143
144         /** The patch notes URL. */
145         public final String patchNotesUrl;
146
147         /** Whether window decorations are hidden for the UI. */
148         public final boolean hideDecorations;
149
150         /** Whether progress text should be hidden or not. */
151         public final boolean hideProgressText;
152
153         /** Whether the splash screen should update non-asynchronously before being shown. */
154         public final boolean progressSync;
155
156         /** Whether the splash screen should update non-asynchronously after being shown. */
157         public final boolean progressSyncAfterShown;
158
159         /** Whether the splash screen should retain focus. */
160         public final boolean keepOnTop;
161
162         /** Whether to display the appbase. */
163         public final boolean displayAppbase;
164
165         /** Whether to display the version. */
166         public final boolean displayVersion;
167
168         /** The minimum number of seconds to display the GUI. This is to prevent the GUI from
169           * flashing up on the screen and immediately disappearing, which can be confusing to the
170           * user. */
171         public final int minShowSeconds;
172
173         /** The global percentages for each step. A step may have more than one, and
174          * the lowest reasonable one is used if a step is revisited. */
175         public final Map<Step, List<Integer>> stepPercentages;
176
177         /** Generates a string representation of this instance. */
178         @Override
179         public String toString ()
180         {
181             return "[name=" + name + ", bg=" + background + ", bg=" + backgroundImage + ", instant_bg=" + instantBackgroundImage +
182                 ", pi=" + progressImage + ", prect=" + progress + ", pt=" + progressText +
183                 ", pb=" + progressBar + ", srect=" + status + ", st=" + statusText +
184                 ", shadow=" + textShadow + ", err=" + installError + ", nrect=" + patchNotes +
185                 ", notes=" + patchNotesUrl + ", stepPercentages=" + stepPercentages +
186                 ", hideProgressText=" + hideProgressText + ", keepOnTop=" + keepOnTop + ", progressSync=" + progressSync +
187                 ", progressSyncAfterShown=" + progressSyncAfterShown + ", minShow=" + minShowSeconds +
188                 ", displayAppbase=" + displayAppbase + ", displayVersion=" + displayVersion + "]";
189         }
190
191         public UpdateInterface (Config config)
192         {
193             this.name = config.getString("ui.name");
194             this.progress = config.getRect("ui.progress", new Rectangle(5, 5, 300, 15));
195             this.progressText = config.getColor("ui.progress_text", Color.BLACK);
196             this.hideProgressText =  config.getBoolean("ui.hide_progress_text");
197             this.progressSync =  config.getBoolean("ui.progress_sync");
198             this.progressSyncAfterShown =  config.getBoolean("ui.progress_sync_after_shown");
199             this.keepOnTop =  config.getBoolean("ui.keep_on_top");
200             this.displayAppbase =  config.getBoolean("ui.display_appbase");
201             this.displayVersion =  config.getBoolean("ui.display_version");
202             this.minShowSeconds = config.getInt("ui.min_show_seconds", 5);
203             this.progressBar = config.getColor("ui.progress_bar", 0x6699CC);
204             this.status = config.getRect("ui.status", new Rectangle(5, 25, 500, 100));
205             this.statusText = config.getColor("ui.status_text", Color.BLACK);
206             this.textShadow = config.getColor("ui.text_shadow", Color.CLEAR);
207             this.hideDecorations = config.getBoolean("ui.hide_decorations");
208             this.backgroundImage = config.getString("ui.background_image");
209             this.instantBackgroundImage = config.getString("ui.instant_background_image");
210             // default to black or white bg color, depending on the brightness of the progressText
211             int defaultBackground = (0.5f < Color.brightness(this.progressText)) ?
212                 Color.BLACK : Color.WHITE;
213             this.background = config.getColor("ui.background", defaultBackground);
214             this.progressImage = config.getString("ui.progress_image");
215             this.rotatingBackgrounds = stringsToList(
216                 config.getMultiValue("ui.rotating_background"));
217             this.iconImages = stringsToList(config.getMultiValue("ui.icon"));
218             this.errorBackground = config.getString("ui.error_background");
219
220             // On an installation error, where do we point the user.
221             String installError = config.getUrl("ui.install_error", null);
222             this.installError = (installError == null) ?
223                 "m.default_install_error" : MessageUtil.taint(installError);
224
225             // the patch notes bits
226             this.patchNotes = config.getRect("ui.patch_notes", new Rectangle(5, 50, 112, 26));
227             this.patchNotesUrl = config.getUrl("ui.patch_notes_url", null);
228
229             // step progress percentage (defaults and then customized values)
230             EnumMap<Step, List<Integer>> stepPercentages = new EnumMap<>(Step.class);
231             for (Step step : Step.values()) {
232                 stepPercentages.put(step, step.defaultPercents);
233             }
234             for (UpdateInterface.Step step : UpdateInterface.Step.values()) {
235                 String spec = config.getString("ui.percents." + step.name());
236                 if (spec != null) {
237                     try {
238                         stepPercentages.put(step, intsToList(StringUtil.parseIntArray(spec)));
239                     } catch (Exception e) {
240                         log.warning("Failed to parse percentages for " + step + ": " + spec);
241                     }
242                 }
243             }
244             this.stepPercentages = Collections.unmodifiableMap(stepPercentages);
245         }
246     }
247
248     /**
249      * Used by {@link #verifyMetadata} to communicate status in circumstances where it needs to
250      * take network actions.
251      */
252     public static interface StatusDisplay
253     {
254         /** Requests that the specified status message be displayed. */
255         public void updateStatus (String message);
256     }
257
258     /**
259      * Contains metadata for an auxiliary resource group.
260      */
261     public static class AuxGroup {
262         public final String name;
263         public final List<Resource> codes;
264         public final List<Resource> rsrcs;
265
266         public AuxGroup (String name, List<Resource> codes, List<Resource> rsrcs) {
267             this.name = name;
268             this.codes = Collections.unmodifiableList(codes);
269             this.rsrcs = Collections.unmodifiableList(rsrcs);
270         }
271     }
272
273     /** The proxy that should be used to do HTTP downloads. This must be configured prior to using
274       * the application instance. Yes this is a public mutable field, no I'm not going to create a
275       * getter and setter just to pretend like that's not the case. */
276     public Proxy proxy = Proxy.NO_PROXY;
277
278     /**
279      * Creates an application instance which records the location of the <code>getdown.txt</code>
280      * configuration file from the supplied application directory.
281      *
282      */
283     public Application (EnvConfig envc) {
284         _envc = envc;
285         _config = getLocalPath(envc.appDir, CONFIG_FILE);
286     }
287
288     /**
289      * Returns the configured application directory.
290      */
291     public File getAppDir () {
292         return _envc.appDir;
293     }
294
295     /**
296      * Returns whether the application should cache code resources prior to launching the
297      * application.
298      */
299     public boolean useCodeCache ()
300     {
301         return _useCodeCache;
302     }
303
304     /**
305      * Returns the number of days a cached code resource is allowed to stay unused before it
306      * becomes eligible for deletion.
307      */
308     public int getCodeCacheRetentionDays ()
309     {
310         return _codeCacheRetentionDays;
311     }
312
313     /**
314      * Returns the configured maximum concurrent downloads. Used to cap simultaneous downloads of
315      * app files from its hosting server.
316      */
317     public int maxConcurrentDownloads () {
318         return _maxConcDownloads;
319     }
320
321     /**
322      * Returns a resource that refers to the application configuration file itself.
323      */
324     public Resource getConfigResource ()
325     {
326         try {
327             return createResource(CONFIG_FILE, Resource.NORMAL);
328         } catch (Exception e) {
329             throw new RuntimeException("Invalid appbase '" + _vappbase + "'.", e);
330         }
331     }
332
333     /**
334      * Returns a list of the code {@link Resource} objects used by this application.
335      */
336     public List<Resource> getCodeResources ()
337     {
338         return _codes;
339     }
340
341     /**
342      * Returns a list of the non-code {@link Resource} objects used by this application.
343      */
344     public List<Resource> getResources ()
345     {
346         return _resources;
347     }
348
349     /**
350      * Returns the digest of the given {@code resource}.
351      */
352     public String getDigest (Resource resource)
353     {
354         return _digest.getDigest(resource);
355     }
356
357     /**
358      * Returns a list of all the active {@link Resource} objects used by this application (code and
359      * non-code).
360      */
361     public List<Resource> getAllActiveResources ()
362     {
363         List<Resource> allResources = new ArrayList<>();
364         allResources.addAll(getActiveCodeResources());
365         allResources.addAll(getActiveResources());
366         return allResources;
367     }
368
369     /**
370      * Returns the auxiliary resource group with the specified name, or null.
371      */
372     public AuxGroup getAuxGroup (String name)
373     {
374         return _auxgroups.get(name);
375     }
376
377     /**
378      * Returns the set of all auxiliary resource groups defined by the application. An auxiliary
379      * resource group is a collection of resource files that are not downloaded unless a group
380      * token file is present in the application directory.
381      */
382     public Iterable<AuxGroup> getAuxGroups ()
383     {
384         return _auxgroups.values();
385     }
386
387     /**
388      * Returns true if the specified auxgroup has been "activated", false if not. Non-activated
389      * groups should be ignored, activated groups should be downloaded and patched along with the
390      * main resources.
391      */
392     public boolean isAuxGroupActive (String auxgroup)
393     {
394         Boolean active = _auxactive.get(auxgroup);
395         if (active == null) {
396             // TODO: compare the contents with the MD5 hash of the auxgroup name and the client's
397             // machine ident
398             active = getLocalPath(auxgroup + ".dat").exists();
399             _auxactive.put(auxgroup, active);
400         }
401         return active;
402     }
403
404     /**
405      * Returns all main code resources and all code resources from active auxiliary resource groups.
406      */
407     public List<Resource> getActiveCodeResources ()
408     {
409         ArrayList<Resource> codes = new ArrayList<>();
410         codes.addAll(getCodeResources());
411         for (AuxGroup aux : getAuxGroups()) {
412             if (isAuxGroupActive(aux.name)) {
413                 codes.addAll(aux.codes);
414             }
415         }
416         return codes;
417     }
418
419     /**
420      * Returns all resources indicated to contain native library files (.dll, .so, etc.).
421      */
422     public List<Resource> getNativeResources ()
423     {
424         List<Resource> natives = new ArrayList<>();
425         for (Resource resource: _resources) {
426             if (resource.isNative()) {
427                 natives.add(resource);
428             }
429         }
430         return natives;
431     }
432
433     /**
434      * Returns all non-code resources and all resources from active auxiliary resource groups.
435      */
436     public List<Resource> getActiveResources ()
437     {
438         ArrayList<Resource> rsrcs = new ArrayList<>();
439         rsrcs.addAll(getResources());
440         for (AuxGroup aux : getAuxGroups()) {
441             if (isAuxGroupActive(aux.name)) {
442                 rsrcs.addAll(aux.rsrcs);
443             }
444         }
445         return rsrcs;
446     }
447
448     /**
449      * Returns a resource that can be used to download a patch file that will bring this
450      * application from its current version to the target version.
451      *
452      * @param auxgroup the auxiliary resource group for which a patch resource is desired or null
453      * for the main application patch resource.
454      */
455     public Resource getPatchResource (String auxgroup)
456     {
457         if (_targetVersion <= _version) {
458             log.warning("Requested patch resource for up-to-date or non-versioned application",
459                 "cvers", _version, "tvers", _targetVersion);
460             return null;
461         }
462
463         String infix = (auxgroup == null) ? "" : ("-" + auxgroup);
464         String pfile = "patch" + infix + _version + ".dat";
465         try {
466             URL remote = new URL(createVAppBase(_targetVersion), encodePath(pfile));
467             return new Resource(pfile, remote, getLocalPath(pfile), Resource.NORMAL);
468         } catch (Exception e) {
469             log.warning("Failed to create patch resource path",
470                 "pfile", pfile, "appbase", _appbase, "tvers", _targetVersion, "error", e);
471             return null;
472         }
473     }
474
475     /**
476      * Returns a resource for a zip file containing a Java VM that can be downloaded to use in
477      * place of the installed VM (in the case where the VM that launched Getdown does not meet the
478      * application's version requirements) or null if no VM is available for this platform.
479      */
480     public Resource getJavaVMResource ()
481     {
482         if (StringUtil.isBlank(_javaLocation)) {
483             return null;
484         }
485
486         String extension = (_javaLocation.endsWith(".tgz"))?".tgz":".jar";
487         String vmfile = LaunchUtil.LOCAL_JAVA_DIR + extension;
488                 log.info("vmfile is '"+vmfile+"'");
489                 System.out.println("vmfile is '"+vmfile+"'");
490         try {
491             URL remote = new URL(createVAppBase(_targetVersion), encodePath(_javaLocation));
492             log.info("Attempting to fetch jvm at "+remote.toString());
493             System.out.println("Attempting to fetch jvm at "+remote.toString());
494             return new Resource(vmfile, remote, getLocalPath(vmfile),
495                                 EnumSet.of(Resource.Attr.UNPACK, Resource.Attr.CLEAN));
496         } catch (Exception e) {
497             log.warning("Failed to create VM resource", "vmfile", vmfile, "appbase", _appbase,
498                 "tvers", _targetVersion, "javaloc", _javaLocation, "error", e);
499             System.out.println("Failed to create VM resource: vmfile="+vmfile+", appbase="+_appbase+
500                 ", tvers="+_targetVersion+", javaloc="+_javaLocation+", error="+e);
501             return null;
502         }
503     }
504
505     /**
506      * Returns a resource that can be used to download an archive containing all files belonging to
507      * the application.
508      */
509     public Resource getFullResource ()
510     {
511         String file = "full";
512         try {
513             URL remote = new URL(createVAppBase(_targetVersion), encodePath(file));
514             return new Resource(file, remote, getLocalPath(file), Resource.NORMAL);
515         } catch (Exception e) {
516             log.warning("Failed to create full resource path",
517                 "file", file, "appbase", _appbase, "tvers", _targetVersion, "error", e);
518             return null;
519         }
520     }
521
522     /**
523      * Returns the URL to use to report an initial download event. Returns null if no tracking
524      * start URL was configured for this application.
525      *
526      * @param event the event to be reported: start, jvm_start, jvm_complete, complete.
527      */
528     public URL getTrackingURL (String event)
529     {
530         try {
531             String suffix = _trackingURLSuffix == null ? "" : _trackingURLSuffix;
532             String ga = getGATrackingCode();
533             return _trackingURL == null ? null :
534                 HostWhitelist.verify(new URL(_trackingURL + encodePath(event + suffix + ga)));
535         } catch (MalformedURLException mue) {
536             log.warning("Invalid tracking URL", "path", _trackingURL, "event", event, "error", mue);
537             return null;
538         }
539     }
540
541     /**
542      * Returns the URL to request to report that we have reached the specified percentage of our
543      * initial download. Returns null if no tracking request was configured for the specified
544      * percentage.
545      */
546     public URL getTrackingProgressURL (int percent)
547     {
548         if (_trackingPcts == null || !_trackingPcts.contains(percent)) {
549             return null;
550         }
551         return getTrackingURL("pct" + percent);
552     }
553
554     /**
555      * Returns the name of our tracking cookie or null if it was not set.
556      */
557     public String getTrackingCookieName ()
558     {
559         return _trackingCookieName;
560     }
561
562     /**
563      * Returns the name of our tracking cookie system property or null if it was not set.
564      */
565     public String getTrackingCookieProperty ()
566     {
567         return _trackingCookieProperty;
568     }
569
570     /**
571      * Instructs the application to parse its {@code getdown.txt} configuration and prepare itself
572      * for operation. The application base URL will be parsed first so that if there are errors
573      * discovered later, the caller can use the application base to download a new {@code
574      * getdown.txt} file and try again.
575      *
576      * @return a {@code Config} instance that contains information from the config file.
577      *
578      * @exception IOException thrown if there is an error reading the file or an error encountered
579      * during its parsing.
580      */
581     public Config init (boolean checkPlatform)
582         throws IOException
583     {
584         Config config = null;
585         File cfgfile = _config;
586         Config.ParseOpts opts = Config.createOpts(checkPlatform);
587         try {
588             // if we have a configuration file, read the data from it
589             if (cfgfile.exists()) {
590                 config = Config.parseConfig(_config, opts);
591             }
592             // otherwise, try reading data from our backup config file; thanks to funny windows
593             // bullshit, we have to do this backup file fiddling in case we got screwed while
594             // updating getdown.txt during normal operation
595             else if ((cfgfile = getLocalPath(CONFIG_FILE + "_old")).exists()) {
596                 config = Config.parseConfig(cfgfile, opts);
597             }
598             // otherwise, issue a warning that we found no getdown file
599             else {
600                 log.info("Found no getdown.txt file", "appdir", getAppDir());
601             }
602         } catch (Exception e) {
603             log.warning("Failure reading config file", "file", _config, e);
604         }
605         
606         // see if there's an override config from locator file
607         Config locatorConfig = createLocatorConfig(opts);
608         
609         // merge the locator file config into config (or replace config with)
610         if (locatorConfig != null) {
611           if (config == null || locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_replace")) {
612             config = locatorConfig;
613           } else {
614             config.mergeConfig(locatorConfig, locatorConfig.getBoolean(LOCATOR_FILE_EXTENSION+"_merge"));
615           }
616         }
617
618         // if we failed to read our config file, check for an appbase specified via a system
619         // property; we can use that to bootstrap ourselves back into operation
620         if (config == null) {
621             String appbase = _envc.appBase;
622             log.info("Using 'appbase' from bootstrap config", "appbase", appbase);
623             Map<String, Object> cdata = new HashMap<>();
624             cdata.put("appbase", appbase);
625             config = new Config(cdata);
626         }
627
628         // first determine our application base, this way if anything goes wrong later in the
629         // process, our caller can use the appbase to download a new configuration file
630         _appbase = config.getString("appbase");
631         
632         // see if locatorConfig override
633         if (locatorConfig != null && !StringUtil.isBlank(locatorConfig.getString("appbase"))) {
634           _appbase = locatorConfig.getString("appbase");
635         }
636         
637         if (_appbase == null) {
638             throw new RuntimeException("m.missing_appbase");
639         }
640
641         // check if we're overriding the domain in the appbase
642         _appbase = SysProps.overrideAppbase(_appbase);
643
644         // make sure there's a trailing slash
645         if (!_appbase.endsWith("/")) {
646             _appbase = _appbase + "/";
647         }
648
649         // extract our version information
650         _version = config.getLong("version", -1L);
651
652         // if we are a versioned deployment, create a versioned appbase
653         try {
654             _vappbase = createVAppBase(_version);
655         } catch (MalformedURLException mue) {
656             String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
657             throw (IOException) new IOException(err).initCause(mue);
658         }
659
660         // check for a latest config URL
661         String latest = config.getString("latest");
662         if (latest != null) {
663             if (latest.startsWith(_appbase)) {
664                 latest = _appbase + latest.substring(_appbase.length());
665             } else {
666                 latest = SysProps.replaceDomain(latest);
667             }
668             try {
669                 _latest = HostWhitelist.verify(new URL(latest));
670             } catch (MalformedURLException mue) {
671                 log.warning("Invalid URL for latest attribute.", mue);
672             }
673         }
674
675         String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
676
677         // determine our application class name (use app-specific class _if_ one is provided)
678         _class = config.getString("class");
679         if (appPrefix.length() > 0) {
680             _class = config.getString(appPrefix + "class", _class);
681         }
682         if (_class == null) {
683             throw new IOException("m.missing_class");
684         }
685
686         // determine whether we want strict comments
687         _strictComments = config.getBoolean("strict_comments");
688
689         // check to see if we're using a custom java.version property and regex
690         _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
691         _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
692
693         // check to see if we require a particular JVM version and have a supplied JVM
694         _javaMinVersion = config.getLong("java_version", _javaMinVersion);
695         // we support java_min_version as an alias of java_version; it better expresses the check
696         // that's going on and better mirrors java_max_version
697         _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
698         // check to see if we require a particular max JVM version and have a supplied JVM
699         _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
700         // check to see if we require a particular JVM version and have a supplied JVM
701         _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
702
703         // this is a little weird, but when we're run from the digester, we see a String[] which
704         // contains java locations for all platforms which we can't grok, but the digester doesn't
705         // need to know about that; when we're run in a real application there will be only one!
706         Object javaloc = config.getRaw("java_location");
707         if (javaloc instanceof String) {
708             _javaLocation = (String)javaloc;
709         }
710
711         // determine whether we have any tracking configuration
712         _trackingURL = config.getString("tracking_url");
713
714         // check for tracking progress percent configuration
715         String trackPcts = config.getString("tracking_percents");
716         if (!StringUtil.isBlank(trackPcts)) {
717             _trackingPcts = new HashSet<>();
718             for (int pct : StringUtil.parseIntArray(trackPcts)) {
719                 _trackingPcts.add(pct);
720             }
721         } else if (!StringUtil.isBlank(_trackingURL)) {
722             _trackingPcts = new HashSet<>();
723             _trackingPcts.add(50);
724         }
725
726         // Check for tracking cookie configuration
727         _trackingCookieName = config.getString("tracking_cookie_name");
728         _trackingCookieProperty = config.getString("tracking_cookie_property");
729
730         // Some app may need an extra suffix added to the tracking URL
731         _trackingURLSuffix = config.getString("tracking_url_suffix");
732
733         // Some app may need to generate google analytics code
734         _trackingGAHash = config.getString("tracking_ga_hash");
735
736         // clear our arrays as we may be reinitializing
737         _codes.clear();
738         _resources.clear();
739         _auxgroups.clear();
740         _jvmargs.clear();
741         _appargs.clear();
742         _txtJvmArgs.clear();
743
744         // parse our code resources
745         if (config.getMultiValue("code") == null &&
746             config.getMultiValue("ucode") == null) {
747             throw new IOException("m.missing_code");
748         }
749         parseResources(config, "code", Resource.NORMAL, _codes);
750         parseResources(config, "ucode", Resource.UNPACK, _codes);
751
752         // parse our non-code resources
753         parseResources(config, "resource", Resource.NORMAL, _resources);
754         parseResources(config, "uresource", Resource.UNPACK, _resources);
755         parseResources(config, "xresource", Resource.EXEC, _resources);
756         parseResources(config, "presource", Resource.PRELOAD, _resources);
757         parseResources(config, "nresource", Resource.NATIVE, _resources);
758
759         // parse our auxiliary resource groups
760         for (String auxgroup : config.getList("auxgroups")) {
761             ArrayList<Resource> codes = new ArrayList<>();
762             parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
763             parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
764             ArrayList<Resource> rsrcs = new ArrayList<>();
765             parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
766             parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
767             parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
768             parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
769             parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
770             _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
771         }
772
773         // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
774         String[] jvmargs = config.getMultiValue("jvmarg");
775         addAll(jvmargs, _jvmargs);
776         if (appPrefix.length() > 0) {
777             jvmargs = config.getMultiValue(appPrefix + "jvmarg");
778             addAll(jvmargs, _jvmargs);
779         }
780
781         // see if a percentage of physical memory option exists
782         int jvmmempc = config.getInt("jvmmempc", -1);
783         // app_id prefixed setting overrides
784         if (appPrefix.length() > 0) {
785             jvmmempc = config.getInt(appPrefix + "jvmmempc", jvmmempc);
786         }
787         if (0 <= jvmmempc && jvmmempc <= 100) {
788           
789           long maxMemLong = -1;
790
791           try
792           {
793             maxMemLong = MemorySetting.memPercent(jvmmempc);
794           } catch (Exception e)
795           {
796             e.printStackTrace();
797           } catch (Throwable t)
798           {
799             t.printStackTrace();
800           }
801
802           if (maxMemLong > 0)
803           {
804             
805             String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
806             // remove other max heap size arg
807             ARG: for (int i = 0; i < _jvmargs.size(); i++) {
808               if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
809                 _jvmargs.remove(i);
810               }
811             }
812             addAll(maxMemHeapArg, _jvmargs);
813             
814           }
815
816         } else if (jvmmempc != -1) {
817           System.out.println("'jvmmempc' value must be in range 0 to 100 (read as '"+Integer.toString(jvmmempc)+"')");
818         }
819
820         // get the set of optimum JVM arguments
821         _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
822
823         // transfer our application arguments
824         String[] appargs = config.getMultiValue(appPrefix + "apparg");
825         addAll(appargs, _appargs);
826
827         // add the launch specific application arguments
828         _appargs.addAll(_envc.appArgs);
829         
830         // look for custom arguments
831         fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
832
833         // determine whether we want to allow offline operation (defaults to false)
834         _allowOffline = config.getBoolean("allow_offline");
835
836         // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
837         // obtain a thread dump of the running JVM
838         _windebug = getLocalPath("debug.txt").exists();
839
840         // whether to cache code resources and launch from cache
841         _useCodeCache = config.getBoolean("use_code_cache");
842         _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
843
844         // maximum simultaneous downloads
845         _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
846                                                       SysProps.threadPoolSize()));
847
848         // extract some info used to configure our child process on macOS
849         _dockName = config.getString("ui.name");
850         _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
851
852         return config;
853     }
854
855     /**
856      * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
857      */
858     protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
859     {
860         File pairFile = getLocalPath(pairLocation);
861         if (pairFile.exists()) {
862             try {
863                 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
864                 for (String[] pair : args) {
865                     if (pair[1].length() == 0) {
866                         collector.add(pair[0]);
867                     } else {
868                         collector.add(pair[0] + "=" + pair[1]);
869                     }
870                 }
871             } catch (Throwable t) {
872                 log.warning("Failed to parse '" + pairFile + "': " + t);
873             }
874         }
875     }
876
877     /**
878      * Returns a URL from which the specified path can be fetched. Our application base URL is
879      * properly versioned and combined with the supplied path.
880      */
881     public URL getRemoteURL (String path)
882         throws MalformedURLException
883     {
884         return new URL(_vappbase, encodePath(path));
885     }
886
887     /**
888      * Returns the local path to the specified resource.
889      */
890     public File getLocalPath (String path)
891     {
892         return getLocalPath(getAppDir(), path);
893     }
894
895     /**
896      * Returns true if we either have no version requirement, are running in a JVM that meets our
897      * version requirements or have what appears to be a version of the JVM that meets our
898      * requirements.
899      */
900     public boolean haveValidJavaVersion ()
901     {
902         // if we're doing no version checking, then yay!
903         if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
904
905         try {
906             // parse the version out of the java.version (or custom) system property
907             long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
908
909             log.info("Checking Java version", "current", version,
910                      "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
911
912             // if we have an unpacked VM, check the 'release' file for its version
913             Resource vmjar = getJavaVMResource();
914             if (vmjar != null && vmjar.isMarkedValid()) {
915                 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
916                 File relfile = new File(vmdir, "release");
917                 if (!relfile.exists()) {
918                     log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
919                     return true;
920                 }
921
922                 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
923                 if (vmvers == 0L) {
924                     log.warning("Unable to read version from 'release' file. Assuming valid.");
925                     return true;
926                 }
927
928                 version = vmvers;
929                 log.info("Checking version of unpacked JVM [vers=" + version + "].");
930             }
931
932             if (_javaExactVersionRequired) {
933                 if (version == _javaMinVersion) return true;
934                 else {
935                     log.warning("An exact Java VM version is required.", "current", version,
936                                 "required", _javaMinVersion);
937                     return false;
938                 }
939             }
940
941             boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
942             boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
943             return minVersionOK && maxVersionOK;
944
945         } catch (RuntimeException re) {
946             // if we can't parse the java version we're in weird land and should probably just try
947             // our luck with what we've got rather than try to download a new jvm
948             log.warning("Unable to parse VM version, hoping for the best",
949                         "error", re, "needed", _javaMinVersion);
950             return true;
951         }
952     }
953
954     /**
955      * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
956      * whether the launch is successful and, if necessary, trying again without the optimum
957      * arguments.
958      */
959     public boolean hasOptimumJvmArgs ()
960     {
961         return _optimumJvmArgs != null;
962     }
963
964     /**
965      * Returns true if the app should attempt to run even if we have no Internet connection.
966      */
967     public boolean allowOffline ()
968     {
969         return _allowOffline;
970     }
971
972     /**
973      * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
974      * previous call to {@link #init}.
975      */
976     public void attemptRecovery (StatusDisplay status)
977         throws IOException
978     {
979         status.updateStatus("m.updating_metadata");
980         downloadConfigFile();
981     }
982
983     /**
984      * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
985      * those for the target version of our application.
986      */
987     public void updateMetadata ()
988         throws IOException
989     {
990         try {
991             // update our versioned application base with the target version
992             _vappbase = createVAppBase(_targetVersion);
993         } catch (MalformedURLException mue) {
994             String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
995             throw (IOException) new IOException(err).initCause(mue);
996         }
997
998         try {
999             // now re-download our control files; we download the digest first so that if it fails,
1000             // our config file will still reference the old version and re-running the updater will
1001             // start the whole process over again
1002             downloadDigestFiles();
1003             downloadConfigFile();
1004
1005         } catch (IOException ex) {
1006             // if we are allowing offline execution, we want to allow the application to run in its
1007             // current form rather than aborting the entire process; to do this, we delete the
1008             // version.txt file and "trick" Getdown into thinking that it just needs to validate
1009             // the application as is; next time the app runs when connected to the internet, it
1010             // will have to rediscover that it needs updating and reattempt to update itself
1011             if (_allowOffline) {
1012                 log.warning("Failed to update digest files.  Attempting offline operaton.", ex);
1013                 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
1014                     log.warning("Deleting version.txt failed.  This probably isn't going to work.");
1015                 }
1016             } else {
1017                 throw ex;
1018             }
1019         }
1020     }
1021
1022     /**
1023      * Invokes the process associated with this application definition.
1024      *
1025      * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
1026      * back).
1027      */
1028     public Process createProcess (boolean optimum)
1029         throws IOException
1030     {
1031         ArrayList<String> args = new ArrayList<>();
1032
1033         // reconstruct the path to the JVM
1034         args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
1035
1036         // check whether we're using -jar mode or -classpath mode
1037         boolean dashJarMode = MANIFEST_CLASS.equals(_class);
1038
1039         // add the -classpath arguments if we're not in -jar mode
1040         ClassPath classPath = PathBuilder.buildClassPath(this);
1041         if (!dashJarMode) {
1042             args.add("-classpath");
1043             args.add(classPath.asArgumentString());
1044         }
1045
1046         // we love our Mac users, so we do nice things to preserve our application identity
1047         if (LaunchUtil.isMacOS()) {
1048             args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1049             args.add("-Xdock:name=" + _dockName);
1050         }
1051
1052         // pass along our proxy settings
1053         String proxyHost;
1054         if ((proxyHost = System.getProperty("http.proxyHost")) != null) {
1055             args.add("-Dhttp.proxyHost=" + proxyHost);
1056             args.add("-Dhttp.proxyPort=" + System.getProperty("http.proxyPort"));
1057             args.add("-Dhttps.proxyHost=" + proxyHost);
1058             args.add("-Dhttps.proxyPort=" + System.getProperty("http.proxyPort"));
1059         }
1060
1061         // add the marker indicating the app is running in getdown
1062         args.add("-D" + Properties.GETDOWN + "=true");
1063
1064         // set the native library path if we have native resources
1065         // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1066         ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1067         if (javaLibPath != null) {
1068             args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1069         }
1070
1071         // pass along any pass-through arguments
1072         for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1073             String key = (String)entry.getKey();
1074             if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1075                 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1076                 args.add("-D" + key + "=" + entry.getValue());
1077             }
1078         }
1079
1080         // add the JVM arguments
1081         for (String string : _jvmargs) {
1082             args.add(processArg(string));
1083         }
1084
1085         // add the optimum arguments if requested and available
1086         if (optimum && _optimumJvmArgs != null) {
1087             for (String string : _optimumJvmArgs) {
1088                 args.add(processArg(string));
1089             }
1090         }
1091
1092         // add the arguments from extra.txt (after the optimum ones, in case they override them)
1093         for (String string : _txtJvmArgs) {
1094             args.add(processArg(string));
1095         }
1096
1097         // if we're in -jar mode add those arguments, otherwise add the app class name
1098         if (dashJarMode) {
1099             args.add("-jar");
1100             args.add(classPath.asArgumentString());
1101         } else {
1102             args.add(_class);
1103         }
1104
1105         // almost finally check the startup file arguments
1106         for (File f : _startupFiles) {
1107           _appargs.add(f.getAbsolutePath());
1108           break; // Only add one file to open
1109         }
1110         
1111         // check if one arg with recognised extension
1112         if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1113           String filename = _appargs.get(0);
1114           String ext = null;
1115           int j = filename.lastIndexOf('.');
1116           if (j > -1) {
1117             ext = filename.substring(j+1);
1118           }
1119           if (LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase())) {
1120             // this file extension should have been dealt with in Getdown class
1121           } else {
1122             _appargs.add(0, "-open");
1123           }
1124         }
1125
1126         // finally add the application arguments
1127         for (String string : _appargs) {
1128             args.add(processArg(string));
1129         }
1130         
1131         String[] envp = createEnvironment();
1132         String[] sargs = args.toArray(new String[args.size()]);
1133         log.info("Running " + StringUtil.join(sargs, "\n  "));
1134
1135         return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1136     }
1137
1138     /**
1139      * If the application provided environment variables, combine those with the current
1140      * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1141      * If the application didn't provide any environment variables, null is returned to just use
1142      * the existing environment.
1143      */
1144     protected String[] createEnvironment ()
1145     {
1146         List<String> envvar = new ArrayList<>();
1147         fillAssignmentListFromPairs("env.txt", envvar);
1148         if (envvar.isEmpty()) {
1149             log.info("Didn't find any custom environment variables, not setting any.");
1150             return null;
1151         }
1152
1153         List<String> envAssignments = new ArrayList<>();
1154         for (String assignment : envvar) {
1155             envAssignments.add(processArg(assignment));
1156         }
1157         for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1158             envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1159         }
1160         String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1161         log.info("Environment " + StringUtil.join(envp, "\n "));
1162         return envp;
1163     }
1164
1165     /**
1166      * Runs this application directly in the current VM.
1167      */
1168     public void invokeDirect () throws IOException
1169     {
1170         ClassPath classPath = PathBuilder.buildClassPath(this);
1171         URL[] jarUrls = classPath.asUrls();
1172
1173         // create custom class loader
1174         URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1175             @Override protected PermissionCollection getPermissions (CodeSource code) {
1176                 Permissions perms = new Permissions();
1177                 perms.add(new AllPermission());
1178                 return perms;
1179             }
1180         };
1181         Thread.currentThread().setContextClassLoader(loader);
1182
1183         log.info("Configured URL class loader:");
1184         for (URL url : jarUrls) log.info("  " + url);
1185
1186         // configure any system properties that we can
1187         for (String jvmarg : _jvmargs) {
1188             if (jvmarg.startsWith("-D")) {
1189                 jvmarg = processArg(jvmarg.substring(2));
1190                 int eqidx = jvmarg.indexOf("=");
1191                 if (eqidx == -1) {
1192                     log.warning("Bogus system property: '" + jvmarg + "'?");
1193                 } else {
1194                     System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1195                 }
1196             }
1197         }
1198
1199         // pass along any pass-through arguments
1200         Map<String, String> passProps = new HashMap<>();
1201         for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1202             String key = (String)entry.getKey();
1203             if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1204                 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1205                 passProps.put(key, (String)entry.getValue());
1206             }
1207         }
1208         // we can't set these in the above loop lest we get a ConcurrentModificationException
1209         for (Map.Entry<String, String> entry : passProps.entrySet()) {
1210             System.setProperty(entry.getKey(), entry.getValue());
1211         }
1212
1213         // prepare our app arguments
1214         String[] args = new String[_appargs.size()];
1215         for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1216
1217         try {
1218             log.info("Loading " + _class);
1219             Class<?> appclass = loader.loadClass(_class);
1220             Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1221             log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1222             main.invoke(null, new Object[] { args });
1223         } catch (Exception e) {
1224             log.warning("Failure invoking app main", e);
1225         }
1226     }
1227
1228     /** Replaces the application directory and version in any argument. */
1229     protected String processArg (String arg)
1230     {
1231         arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1232         arg = arg.replace("%VERSION%", String.valueOf(_version));
1233
1234         // if this argument contains %ENV.FOO% replace those with the associated values looked up
1235         // from the environment
1236         if (arg.contains(ENV_VAR_PREFIX)) {
1237             StringBuffer sb = new StringBuffer();
1238             Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1239             while (matcher.find()) {
1240                 String varName = matcher.group(1), varValue = System.getenv(varName);
1241                 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1242                 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1243             }
1244             matcher.appendTail(sb);
1245             arg = sb.toString();
1246         }
1247
1248         return arg;
1249     }
1250
1251     /**
1252      * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1253      * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1254      * whether or not the application needs to be updated or whether we can proceed to verification
1255      * and execution.
1256      *
1257      * @return true if the application needs to be updated, false if it is up to date and can be
1258      * verified and executed.
1259      *
1260      * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1261      * metadata.
1262      */
1263     public boolean verifyMetadata (StatusDisplay status)
1264         throws IOException
1265     {
1266         log.info("Verifying application: " + _vappbase);
1267         log.info("Version: " + _version);
1268         log.info("Class: " + _class);
1269
1270         // this will read in the contents of the digest file and validate itself
1271         try {
1272             _digest = new Digest(getAppDir(), _strictComments);
1273         } catch (IOException ioe) {
1274             log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1275         }
1276
1277         // if we have no version, then we are running in unversioned mode so we need to download
1278         // our digest.txt file on every invocation
1279         if (_version == -1) {
1280             // make a note of the old meta-digest, if this changes we need to revalidate all of our
1281             // resources as one or more of them have also changed
1282             String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1283             try {
1284                 status.updateStatus("m.checking");
1285                 downloadDigestFiles();
1286                 _digest = new Digest(getAppDir(), _strictComments);
1287                 if (!olddig.equals(_digest.getMetaDigest())) {
1288                     log.info("Unversioned digest changed. Revalidating...");
1289                     status.updateStatus("m.validating");
1290                     clearValidationMarkers();
1291                 }
1292             } catch (IOException ioe) {
1293                 log.warning("Failed to refresh non-versioned digest: " +
1294                             ioe.getMessage() + ". Proceeding...");
1295             }
1296         }
1297
1298         // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1299         // redownload the digest file and give it another good college try; this time we allow
1300         // exceptions to propagate up to the caller as there is nothing else we can do
1301         if (_digest == null) {
1302             status.updateStatus("m.updating_metadata");
1303             downloadDigestFiles();
1304             _digest = new Digest(getAppDir(), _strictComments);
1305         }
1306
1307         // now verify the contents of our main config file
1308         Resource crsrc = getConfigResource();
1309         if (!_digest.validateResource(crsrc, null)) {
1310             status.updateStatus("m.updating_metadata");
1311             // attempt to redownload both of our metadata files; again we pass errors up to our
1312             // caller because there's nothing we can do to automatically recover
1313             downloadConfigFile();
1314             downloadDigestFiles();
1315             _digest = new Digest(getAppDir(), _strictComments);
1316             // revalidate everything if we end up downloading new metadata
1317             clearValidationMarkers();
1318             // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1319             if (_digest.validateResource(crsrc, null)) {
1320                 init(true);
1321             } else {
1322                 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1323                             "Blindly forging onward.");
1324             }
1325         }
1326
1327         // start by assuming we are happy with our version
1328         _targetVersion = _version;
1329
1330         // if we are a versioned application, read in the contents of the version.txt file
1331         // and/or check the latest config URL for a newer version
1332         if (_version != -1) {
1333             File vfile = getLocalPath(VERSION_FILE);
1334             long fileVersion = VersionUtil.readVersion(vfile);
1335             if (fileVersion != -1) {
1336                 _targetVersion = fileVersion;
1337             }
1338
1339             if (_latest != null) {
1340                 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1341                      InputStreamReader reader = new InputStreamReader(in, UTF_8);
1342                      BufferedReader bin = new BufferedReader(reader)) {
1343                     for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1344                         if (pair[0].equals("version")) {
1345                             _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1346                             if (fileVersion != -1 && _targetVersion > fileVersion) {
1347                                 // replace the file with the newest version
1348                                 try (FileOutputStream fos = new FileOutputStream(vfile);
1349                                      PrintStream out = new PrintStream(fos)) {
1350                                     out.println(_targetVersion);
1351                                 }
1352                             }
1353                             break;
1354                         }
1355                     }
1356                 } catch (Exception e) {
1357                     log.warning("Unable to retrieve version from latest config file.", e);
1358                 }
1359             }
1360         }
1361
1362         // finally let the caller know if we need an update
1363         return _version != _targetVersion;
1364     }
1365
1366     /**
1367      * Verifies the code and media resources associated with this application. A list of resources
1368      * that do not exist or fail the verification process will be returned. If all resources are
1369      * ready to go, null will be returned and the application is considered ready to run.
1370      *
1371      * @param obs a progress observer that will be notified of verification progress. NOTE: this
1372      * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1373      * you have to take care to get back to your UI thread.
1374      * @param alreadyValid if non-null a 1 element array that will have the number of "already
1375      * validated" resources filled in.
1376      * @param unpacked a set to populate with unpacked resources.
1377      * @param toInstall a list into which to add resources that need to be installed.
1378      * @param toDownload a list into which to add resources that need to be downloaded.
1379      */
1380     public void verifyResources (
1381         ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1382         Set<Resource> toInstall, Set<Resource> toDownload)
1383         throws InterruptedException
1384     {
1385         // resources are verified on background threads supplied by the thread pool, and progress
1386         // is reported by posting runnable actions to the actions queue which is processed by the
1387         // main (UI) thread
1388         ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1389         final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1390         final int[] completed = new int[1];
1391
1392         long start = System.currentTimeMillis();
1393
1394         // obtain the sizes of the resources to validate
1395         List<Resource> rsrcs = getAllActiveResources();
1396         long[] sizes = new long[rsrcs.size()];
1397         long totalSize = 0;
1398         for (int ii = 0; ii < sizes.length; ii++) {
1399             totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1400         }
1401         final ProgressObserver fobs = obs;
1402         // as long as we forward aggregated progress updates to the UI thread, having multiple
1403         // threads update a progress aggregator is "mostly" thread-safe
1404         final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1405             public void progress (final int percent) {
1406                 actions.add(new Runnable() {
1407                     public void run () {
1408                         fobs.progress(percent);
1409                     }
1410                 });
1411             }
1412         }, sizes);
1413
1414         final int[] fAlreadyValid = alreadyValid;
1415         final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1416         final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1417         final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1418
1419         for (int ii = 0; ii < sizes.length; ii++) {
1420             final Resource rsrc = rsrcs.get(ii);
1421             final int index = ii;
1422             exec.execute(new Runnable() {
1423                 public void run () {
1424                     verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1425                                    unpackedAsync, toInstallAsync, toDownloadAsync);
1426                     actions.add(new Runnable() {
1427                         public void run () {
1428                             completed[0] += 1;
1429                         }
1430                     });
1431                 }
1432             });
1433         }
1434
1435         while (completed[0] < rsrcs.size()) {
1436             // we should be getting progress completion updates WAY more often than one every
1437             // minute, so if things freeze up for 60 seconds, abandon ship
1438             Runnable action = actions.poll(60, TimeUnit.SECONDS);
1439             action.run();
1440         }
1441
1442         exec.shutdown();
1443
1444         toInstall.addAll(toInstallAsync);
1445         toDownload.addAll(toDownloadAsync);
1446         unpacked.addAll(unpackedAsync);
1447
1448         long complete = System.currentTimeMillis();
1449         log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1450                  "duration", (complete-start) + "ms");
1451     }
1452
1453     private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1454                                  Set<Resource> unpacked,
1455                                  Set<Resource> toInstall, Set<Resource> toDownload) {
1456         if (rsrc.isMarkedValid()) {
1457             if (alreadyValid != null) {
1458                 alreadyValid[0]++;
1459             }
1460             obs.progress(100);
1461             return;
1462         }
1463
1464         try {
1465             if (_digest.validateResource(rsrc, obs)) {
1466                 // if the resource has a _new file, add it to to-install list
1467                 if (rsrc.getLocalNew().exists()) {
1468                     toInstall.add(rsrc);
1469                     return;
1470                 }
1471                 rsrc.applyAttrs();
1472                 unpacked.add(rsrc);
1473                 rsrc.markAsValid();
1474                 return;
1475             }
1476
1477         } catch (Exception e) {
1478             log.info("Failure verifying resource. Requesting redownload...",
1479                      "rsrc", rsrc, "error", e);
1480
1481         } finally {
1482             obs.progress(100);
1483         }
1484         toDownload.add(rsrc);
1485     }
1486
1487     /**
1488      * Unpacks the resources that require it (we know that they're valid).
1489      *
1490      * @param unpacked a set of resources to skip because they're already unpacked.
1491      */
1492     public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1493         throws InterruptedException
1494     {
1495         List<Resource> rsrcs = getActiveResources();
1496
1497         // remove resources that we don't want to unpack
1498         for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1499             Resource rsrc = it.next();
1500             if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1501                 it.remove();
1502             }
1503         }
1504
1505         // obtain the sizes of the resources to unpack
1506         long[] sizes = new long[rsrcs.size()];
1507         for (int ii = 0; ii < sizes.length; ii++) {
1508             sizes[ii] = rsrcs.get(ii).getLocal().length();
1509         }
1510
1511         ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1512         for (int ii = 0; ii < sizes.length; ii++) {
1513             Resource rsrc = rsrcs.get(ii);
1514             ProgressObserver pobs = pagg.startElement(ii);
1515             try {
1516                 rsrc.unpack();
1517             } catch (IOException ioe) {
1518                 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1519             }
1520             pobs.progress(100);
1521         }
1522     }
1523
1524     /**
1525      * Clears all validation marker files.
1526      */
1527     public void clearValidationMarkers ()
1528     {
1529         clearValidationMarkers(getAllActiveResources().iterator());
1530     }
1531
1532     /**
1533      * Returns the version number for the application.  Should only be called after successful
1534      * return of verifyMetadata.
1535      */
1536     public long getVersion ()
1537     {
1538         return _version;
1539     }
1540
1541     /**
1542      * Creates a versioned application base URL for the specified version.
1543      */
1544     protected URL createVAppBase (long version)
1545         throws MalformedURLException
1546     {
1547         String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1548         return HostWhitelist.verify(new URL(url));
1549     }
1550
1551     /**
1552      * Clears all validation marker files for the resources in the supplied iterator.
1553      */
1554     protected void clearValidationMarkers (Iterator<Resource> iter)
1555     {
1556         while (iter.hasNext()) {
1557             iter.next().clearMarker();
1558         }
1559     }
1560
1561     /**
1562      * Downloads a new copy of CONFIG_FILE.
1563      */
1564     protected void downloadConfigFile ()
1565         throws IOException
1566     {
1567         downloadControlFile(CONFIG_FILE, 0);
1568     }
1569
1570     /**
1571      * @return true if gettingdown.lock was unlocked, already locked by this application or if
1572      * we're not locking at all.
1573      */
1574     public synchronized boolean lockForUpdates ()
1575     {
1576         if (_lock != null && _lock.isValid()) {
1577             return true;
1578         }
1579         try {
1580             _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1581         } catch (FileNotFoundException e) {
1582             log.warning("Unable to create lock file", "message", e.getMessage(), e);
1583             return false;
1584         }
1585         try {
1586             _lock = _lockChannel.tryLock();
1587         } catch (IOException e) {
1588             log.warning("Unable to create lock", "message", e.getMessage(), e);
1589             return false;
1590         } catch (OverlappingFileLockException e) {
1591             log.warning("The lock is held elsewhere in this JVM", e);
1592             return false;
1593         }
1594         log.info("Able to lock for updates: " + (_lock != null));
1595         return _lock != null;
1596     }
1597
1598     /**
1599      * Release gettingdown.lock
1600      */
1601     public synchronized void releaseLock ()
1602     {
1603         if (_lock != null) {
1604             log.info("Releasing lock");
1605             try {
1606                 _lock.release();
1607             } catch (IOException e) {
1608                 log.warning("Unable to release lock", "message", e.getMessage(), e);
1609             }
1610             try {
1611                 _lockChannel.close();
1612             } catch (IOException e) {
1613                 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1614             }
1615             _lockChannel = null;
1616             _lock = null;
1617         }
1618     }
1619
1620     /**
1621      * Downloads the digest files and validates their signature.
1622      * @throws IOException
1623      */
1624     protected void downloadDigestFiles ()
1625         throws IOException
1626     {
1627         for (int version = 1; version <= Digest.VERSION; version++) {
1628             downloadControlFile(Digest.digestFile(version), version);
1629         }
1630     }
1631
1632     /**
1633      * Downloads a new copy of the specified control file, optionally validating its signature.
1634      * If the download is successful, moves it over the old file on the filesystem.
1635      *
1636      * <p> TODO: Switch to PKCS #7 or CMS.
1637      *
1638      * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1639      * should indicate the version of the digest file being validated which indicates which
1640      * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1641      */
1642     protected void downloadControlFile (String path, int sigVersion)
1643         throws IOException
1644     {
1645         File target = downloadFile(path);
1646
1647         if (sigVersion > 0) {
1648             if (_envc.certs.isEmpty()) {
1649                 log.info("No signing certs, not verifying digest.txt", "path", path);
1650
1651             } else {
1652                 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1653                 byte[] signature = null;
1654                 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1655                     signature = StreamUtil.toByteArray(signatureStream);
1656                 } finally {
1657                     FileUtil.deleteHarder(signatureFile); // delete the file regardless
1658                 }
1659
1660                 byte[] buffer = new byte[8192];
1661                 int length, validated = 0;
1662                 for (Certificate cert : _envc.certs) {
1663                     try (FileInputStream dataInput = new FileInputStream(target)) {
1664                         Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1665                         sig.initVerify(cert);
1666                         while ((length = dataInput.read(buffer)) != -1) {
1667                             sig.update(buffer, 0, length);
1668                         }
1669
1670                         if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1671                             log.info("Signature does not match", "cert", cert.getPublicKey());
1672                             continue;
1673                         } else {
1674                             log.info("Signature matches", "cert", cert.getPublicKey());
1675                             validated++;
1676                         }
1677
1678                     } catch (IOException ioe) {
1679                         log.warning("Failure validating signature of " + target + ": " + ioe);
1680
1681                     } catch (GeneralSecurityException gse) {
1682                         // no problem!
1683
1684                     }
1685                 }
1686
1687                 // if we couldn't find a key that validates our digest, we are the hosed!
1688                 if (validated == 0) {
1689                     // delete the temporary digest file as we know it is invalid
1690                     FileUtil.deleteHarder(target);
1691                     throw new IOException("m.corrupt_digest_signature_error");
1692                 }
1693             }
1694         }
1695
1696         // now move the temporary file over the original
1697         File original = getLocalPath(path);
1698         if (!FileUtil.renameTo(target, original)) {
1699             throw new IOException("Failed to rename(" + target + ", " + original + ")");
1700         }
1701     }
1702
1703     /**
1704      * Download a path to a temporary file, returning a {@link File} instance with the path
1705      * contents.
1706      */
1707     protected File downloadFile (String path)
1708         throws IOException
1709     {
1710         File target = getLocalPath(path + "_new");
1711
1712         URL targetURL = null;
1713         try {
1714             targetURL = getRemoteURL(path);
1715         } catch (Exception e) {
1716             log.warning("Requested to download invalid control file",
1717                 "appbase", _vappbase, "path", path, "error", e);
1718             throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1719         }
1720
1721         log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1722
1723         // stream the URL into our temporary file
1724         URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1725         // we have to tell Java not to use caches here, otherwise it will cache any request for
1726         // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1727         // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1728         // about it; turning off caches is not a performance concern, because when Getdown asks
1729         // to download a file, it expects it to come over the wire, not from a cache
1730         uconn.setUseCaches(false);
1731         uconn.setRequestProperty("Accept-Encoding", "gzip");
1732         try (InputStream fin = uconn.getInputStream()) {
1733             String encoding = uconn.getContentEncoding();
1734             boolean gzip = "gzip".equalsIgnoreCase(encoding);
1735             try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1736                 try (FileOutputStream fout = new FileOutputStream(target)) {
1737                     StreamUtil.copy(fin2, fout);
1738                 }
1739             }
1740         }
1741
1742         return target;
1743     }
1744
1745     /** Helper function for creating {@link Resource} instances. */
1746     protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1747         throws MalformedURLException
1748     {
1749         return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1750     }
1751
1752     /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1753     protected static void addAll (String[] values, List<String> target) {
1754         if (values != null) {
1755             for (String value : values) {
1756                 target.add(value);
1757             }
1758         }
1759     }
1760
1761     /**
1762      * Make an immutable List from the specified int array.
1763      */
1764     public static List<Integer> intsToList (int[] values)
1765     {
1766         List<Integer> list = new ArrayList<>(values.length);
1767         for (int val : values) {
1768             list.add(val);
1769         }
1770         return Collections.unmodifiableList(list);
1771     }
1772
1773     /**
1774      * Make an immutable List from the specified String array.
1775      */
1776     public static List<String> stringsToList (String[] values)
1777     {
1778         return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1779     }
1780
1781     /** Used to parse resources with the specified name. */
1782     protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1783                                    List<Resource> list)
1784     {
1785         String[] rsrcs = config.getMultiValue(name);
1786         if (rsrcs == null) {
1787             return;
1788         }
1789         for (String rsrc : rsrcs) {
1790             try {
1791                 list.add(createResource(rsrc, attrs));
1792             } catch (Exception e) {
1793                 log.warning("Invalid resource '" + rsrc + "'. " + e);
1794             }
1795         }
1796     }
1797
1798     /** Possibly generates and returns a google analytics tracking cookie. */
1799     protected String getGATrackingCode ()
1800     {
1801         if (_trackingGAHash == null) {
1802             return "";
1803         }
1804         long time = System.currentTimeMillis() / 1000;
1805         if (_trackingStart == 0) {
1806             _trackingStart = time;
1807         }
1808         if (_trackingId == 0) {
1809             int low = 100000000, high = 1000000000;
1810             _trackingId = low + _rando.nextInt(high-low);
1811         }
1812         StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1813         cookie.append(".").append(_trackingId);
1814         cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1815         cookie.append(".").append(time).append(".1%3B%2B");
1816         cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1817         cookie.append(_trackingStart).append(".1.1.");
1818         cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1819         int low = 1000000000, high = 2000000000;
1820         cookie.append("&utmn=").append(_rando.nextInt(high-low));
1821         return cookie.toString();
1822     }
1823
1824     /**
1825      * Encodes a path for use in a URL.
1826      */
1827     protected static String encodePath (String path)
1828     {
1829         try {
1830             // we want to keep slashes because we're encoding an entire path; also we need to turn
1831             // + into %20 because web servers don't like + in paths or file names, blah
1832             return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1833         } catch (UnsupportedEncodingException ue) {
1834             log.warning("Failed to URL encode " + path + ": " + ue);
1835             return path;
1836         }
1837     }
1838
1839     protected File getLocalPath (File appdir, String path)
1840     {
1841         return new File(appdir, path);
1842     }
1843
1844     public static void setStartupFilesFromParameterString(String p) {
1845       // multiple files *might* be passed in as space separated quoted filenames
1846       String q = "\"";
1847       if (!StringUtil.isBlank(p)) {
1848         String[] filenames;
1849         // split quoted params or treat as single string array
1850         if (p.startsWith(q) && p.endsWith(q)) {
1851           // this fails if, e.g.
1852           // p=q("stupidfilename\" " "otherfilename")
1853           // let's hope no-one ever ends a filename with '" '
1854           filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1855         } else {
1856           // single unquoted filename
1857           filenames = new String[]{p};
1858         }
1859
1860         // check for locator file.  Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1861         String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
1862         if (
1863                 !StringUtil.isBlank(locatorFilename)
1864                 && locatorFilename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)
1865                 ) {
1866           setLocatorFile(locatorFilename);
1867           // remove the locator filename from the filenames array
1868           String[] otherFilenames = new String[filenames.length - 1];
1869           System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
1870           filenames = otherFilenames;
1871         }
1872
1873         for (int i = 0; i < filenames.length; i++) {
1874           String filename = filenames[i];
1875           // skip any other locator files in a multiple file list
1876           if (! filename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
1877             addStartupFile(filename);
1878           }
1879         }
1880       }
1881     }
1882     
1883     public static void setLocatorFile(String filename) {
1884       _locatorFile = new File(filename);
1885     }
1886     
1887     public static void addStartupFile(String filename) {
1888       _startupFiles.add(new File(filename));
1889     }
1890     
1891     private Config createLocatorConfig(Config.ParseOpts opts) {
1892       if (_locatorFile == null) {
1893         return null;
1894       }
1895       
1896       Config locatorConfig = null;
1897       
1898       try {
1899         Config tmpConfig = null;
1900         Map<String, Object> tmpData = new HashMap<>();
1901         if (_locatorFile.exists()) {
1902           tmpConfig = Config.parseConfig(_locatorFile,  opts);
1903           // appbase is sanitised in HostWhitelist
1904           Map<String, Object> tmpConfigData = tmpConfig.getData();
1905           if (tmpConfig != null) {
1906             for (Map.Entry<String, Object> entry : tmpConfigData.entrySet()) {
1907               String key = entry.getKey();
1908               Object value = entry.getValue();
1909               String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
1910               if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
1911                 tmpData.put(key, value);
1912               }
1913             }
1914           } else {
1915             log.warning("Error occurred reading config file", "file", _locatorFile);
1916           }
1917         } else {
1918           log.warning("Given locator file does not exist", "file", _locatorFile);
1919         }
1920         
1921         locatorConfig = new Config(tmpData);
1922         
1923       } catch (Exception e) {
1924         log.warning("Failure reading locator file",  "file", _locatorFile, e);
1925       }
1926       
1927       log.info("Returning locatorConfig", locatorConfig);
1928       
1929       return locatorConfig;
1930     }
1931     
1932     public String getAppbase() {
1933         return _appbase;
1934     }
1935     
1936     protected final EnvConfig _envc;
1937     protected File _config;
1938     protected Digest _digest;
1939
1940     protected long _version = -1;
1941     protected long _targetVersion = -1;
1942     protected String _appbase;
1943     protected URL _vappbase;
1944     protected URL _latest;
1945     protected String _class;
1946     protected String _dockName;
1947     protected String _dockIconPath;
1948     protected boolean _strictComments;
1949     protected boolean _windebug;
1950     protected boolean _allowOffline;
1951     protected int _maxConcDownloads;
1952
1953     protected String _trackingURL;
1954     protected Set<Integer> _trackingPcts;
1955     protected String _trackingCookieName;
1956     protected String _trackingCookieProperty;
1957     protected String _trackingURLSuffix;
1958     protected String _trackingGAHash;
1959     protected long _trackingStart;
1960     protected int _trackingId;
1961
1962     protected String _javaVersionProp = "java.version";
1963     protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
1964     protected long _javaMinVersion, _javaMaxVersion;
1965     protected boolean _javaExactVersionRequired;
1966     protected String _javaLocation;
1967
1968     protected List<Resource> _codes = new ArrayList<>();
1969     protected List<Resource> _resources = new ArrayList<>();
1970
1971     protected boolean _useCodeCache;
1972     protected int _codeCacheRetentionDays;
1973
1974     protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
1975     protected Map<String,Boolean> _auxactive = new HashMap<>();
1976
1977     protected List<String> _jvmargs = new ArrayList<>();
1978     protected List<String> _appargs = new ArrayList<>();
1979
1980     protected String[] _optimumJvmArgs;
1981
1982     protected List<String> _txtJvmArgs = new ArrayList<>();
1983
1984     /** If a warning has been issued about not being able to set modtimes. */
1985     protected boolean _warnedAboutSetLastModified;
1986
1987     /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
1988     protected FileLock _lock;
1989
1990     /** Channel to the file underlying _lock.  Kept around solely so the lock doesn't close. */
1991     protected FileChannel _lockChannel;
1992
1993     protected Random _rando = new Random();
1994
1995     protected static final String[] EMPTY_STRING_ARRAY = new String[0];
1996
1997     protected static final String ENV_VAR_PREFIX = "%ENV.";
1998     protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
1999  
2000     protected static File _locatorFile;
2001     protected static List<File> _startupFiles = new ArrayList<>();
2002     public static final String LOCATOR_FILE_EXTENSION = "jvl";
2003 }