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