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