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