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