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