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