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