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