fd53c7978042cced54d5587d9d7c3cca001365bc
[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. Insert startupNotification URI into start of _appargs
1091         if (! StringUtil.isBlank(_jalviewUri)) {
1092           _appargs.add(0, _jalviewUri);
1093         }
1094         if (_appargs.size() > 0) {
1095           String uri = _appargs.get(0);
1096           try {
1097             log.info("TRYING TO PARSE URL '"+uri+"'");
1098             URI jalviewUri = new URI(uri);
1099             if (jalviewUri != null) {
1100               String scheme = jalviewUri.getScheme();
1101               if (scheme != null && (scheme.equals("jalview") || scheme.equals("jalviews"))) {
1102                 boolean https = jalviewUri.getScheme().equals("jalviews");
1103                 String host = jalviewUri.getHost();
1104                 int port = jalviewUri.getPort();
1105                 String file = jalviewUri.getPath();
1106                 String ref = jalviewUri.getFragment();
1107                 String query = jalviewUri.getQuery();
1108                 
1109                 _appargs.clear();
1110                 _appargs.add("-open");
1111                 if (host != null && host.length() > 0) {
1112                   URL newUrl = new URL(
1113                           (https?"https":"http")
1114                           + "://"
1115                           + host
1116                           + (port > -1? String.valueOf(port) : "")
1117                           + jalviewUri.getRawPath()
1118                           + (query != null && query.length() > 0 ? "?" + jalviewUri.getRawQuery() : "")
1119                           );
1120                   _appargs.add(newUrl.toString());
1121                 } else {
1122                   _appargs.add(file);
1123                 }
1124                 
1125                 if (ref != null && ref.length() > 0) {
1126                   String[] refArgs = ref.split("&");
1127                   for (String refArg : refArgs) {
1128                     if (refArg.startsWith("jvmmempc=")) {
1129                       jvmmempc = refArg.substring(9);
1130                       continue;
1131                     }
1132                     if (refArg.startsWith("jvmmemmax=")) {
1133                       jvmmemmax = refArg.substring(10);
1134                       continue;
1135                     }
1136                     _appargs.add(URLDecoder.decode(refArg, "UTF-8"));
1137                   }
1138                 }
1139                 
1140               }
1141             }
1142           } catch (URISyntaxException e) {
1143             log.error("Malformed jalview URI", uri);
1144           }
1145         }
1146         
1147         for (String argString: _appargs) {
1148           if (argString.startsWith("-jvmmempc=")) {
1149             jvmmempc = argString.substring(10);
1150             continue;
1151           }
1152           if (argString.startsWith("-jvmmemmax=")) {
1153             jvmmemmax = argString.substring(11);
1154             continue;
1155           }
1156         }
1157         
1158         // add the memory setting from jvmmempc and jvmmemmax
1159         long maxMemLong = -1;
1160         maxMemLong = MemorySetting.getMemorySetting(jvmmemmax, jvmmempc);
1161         if (maxMemLong > 0)
1162         {
1163           String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(maxMemLong)};
1164           // remove other max heap size arg
1165           ARG: for (int i = 0; i < _jvmargs.size(); i++) {
1166             if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
1167               _jvmargs.remove(i);
1168               break ARG;
1169             }
1170           }
1171           addAll(maxMemHeapArg, _jvmargs);
1172         }
1173  
1174         // add the JVM arguments
1175         for (String string : _jvmargs) {
1176             args.add(processArg(string));
1177         }
1178
1179         // add the optimum arguments if requested and available
1180         if (optimum && _optimumJvmArgs != null) {
1181             for (String string : _optimumJvmArgs) {
1182                 args.add(processArg(string));
1183             }
1184         }
1185
1186         // add the arguments from extra.txt (after the optimum ones, in case they override them)
1187         for (String string : _txtJvmArgs) {
1188             args.add(processArg(string));
1189         }
1190
1191         // if we're in -jar mode add those arguments, otherwise add the app class name
1192         if (dashJarMode) {
1193             args.add("-jar");
1194             args.add(classPath.asArgumentString());
1195         } else {
1196             args.add(_class);
1197         }
1198
1199         // almost finally check the startup file arguments
1200         for (File f : _startupFiles) {
1201           _appargs.add(f.getAbsolutePath());
1202           break; // Only add one file to open
1203         }
1204         
1205         // check if one arg with recognised extension
1206         if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1207           String filename = _appargs.get(0);
1208           String ext = null;
1209           int j = filename.lastIndexOf('.');
1210           if (j > -1) {
1211             ext = filename.substring(j+1);
1212           }
1213           if (ext != null && LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase())) {
1214             // this file extension should have been dealt with in Getdown class
1215           } else {
1216             _appargs.add(0, "-open");
1217           }
1218         }
1219
1220         // finally add the application arguments
1221         for (String string : _appargs) {
1222             args.add(processArg(string));
1223         }
1224
1225         String[] envp = createEnvironment();
1226         String[] sargs = args.toArray(new String[args.size()]);
1227         log.info("Running " + StringUtil.join(sargs, "\n  "));
1228
1229         return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1230     }
1231
1232     /**
1233      * If the application provided environment variables, combine those with the current
1234      * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1235      * If the application didn't provide any environment variables, null is returned to just use
1236      * the existing environment.
1237      */
1238     protected String[] createEnvironment ()
1239     {
1240         List<String> envvar = new ArrayList<>();
1241         fillAssignmentListFromPairs("env.txt", envvar);
1242         if (envvar.isEmpty()) {
1243             log.info("Didn't find any custom environment variables, not setting any.");
1244             return null;
1245         }
1246
1247         List<String> envAssignments = new ArrayList<>();
1248         for (String assignment : envvar) {
1249             envAssignments.add(processArg(assignment));
1250         }
1251         for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1252             envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1253         }
1254         String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1255         log.info("Environment " + StringUtil.join(envp, "\n "));
1256         return envp;
1257     }
1258
1259     /**
1260      * Runs this application directly in the current VM.
1261      */
1262     public void invokeDirect () throws IOException
1263     {
1264         ClassPath classPath = PathBuilder.buildClassPath(this);
1265         URL[] jarUrls = classPath.asUrls();
1266
1267         // create custom class loader
1268         URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1269             @Override protected PermissionCollection getPermissions (CodeSource code) {
1270                 Permissions perms = new Permissions();
1271                 perms.add(new AllPermission());
1272                 return perms;
1273             }
1274         };
1275         Thread.currentThread().setContextClassLoader(loader);
1276
1277         log.info("Configured URL class loader:");
1278         for (URL url : jarUrls) log.info("  " + url);
1279
1280         // configure any system properties that we can
1281         for (String jvmarg : _jvmargs) {
1282             if (jvmarg.startsWith("-D")) {
1283                 jvmarg = processArg(jvmarg.substring(2));
1284                 int eqidx = jvmarg.indexOf("=");
1285                 if (eqidx == -1) {
1286                     log.warning("Bogus system property: '" + jvmarg + "'?");
1287                 } else {
1288                     System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1289                 }
1290             }
1291         }
1292
1293         // pass along any pass-through arguments
1294         Map<String, String> passProps = new HashMap<>();
1295         for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1296             String key = (String)entry.getKey();
1297             if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1298                 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1299                 passProps.put(key, (String)entry.getValue());
1300             }
1301         }
1302         // we can't set these in the above loop lest we get a ConcurrentModificationException
1303         for (Map.Entry<String, String> entry : passProps.entrySet()) {
1304             System.setProperty(entry.getKey(), entry.getValue());
1305         }
1306
1307         // prepare our app arguments
1308         String[] args = new String[_appargs.size()];
1309         for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1310
1311         try {
1312             log.info("Loading " + _class);
1313             Class<?> appclass = loader.loadClass(_class);
1314             Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1315             log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1316             main.invoke(null, new Object[] { args });
1317         } catch (Exception e) {
1318             log.warning("Failure invoking app main", e);
1319         }
1320     }
1321
1322     /** Replaces the application directory and version in any argument. */
1323     protected String processArg (String arg)
1324     {
1325         arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1326         arg = arg.replace("%VERSION%", String.valueOf(_version));
1327
1328         // if this argument contains %ENV.FOO% replace those with the associated values looked up
1329         // from the environment
1330         if (arg.contains(ENV_VAR_PREFIX)) {
1331             StringBuffer sb = new StringBuffer();
1332             Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1333             while (matcher.find()) {
1334                 String varName = matcher.group(1), varValue = System.getenv(varName);
1335                 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1336                 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1337             }
1338             matcher.appendTail(sb);
1339             arg = sb.toString();
1340         }
1341
1342         return arg;
1343     }
1344
1345     /**
1346      * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1347      * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1348      * whether or not the application needs to be updated or whether we can proceed to verification
1349      * and execution.
1350      *
1351      * @return true if the application needs to be updated, false if it is up to date and can be
1352      * verified and executed.
1353      *
1354      * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1355      * metadata.
1356      */
1357     public boolean verifyMetadata (StatusDisplay status)
1358         throws IOException
1359     {
1360         log.info("Verifying application: " + _vappbase);
1361         log.info("Version: " + _version);
1362         log.info("Class: " + _class);
1363
1364         // this will read in the contents of the digest file and validate itself
1365         try {
1366             _digest = new Digest(getAppDir(), _strictComments);
1367         } catch (IOException ioe) {
1368             log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1369         }
1370
1371         // if we have no version, then we are running in unversioned mode so we need to download
1372         // our digest.txt file on every invocation
1373         if (_version == -1) {
1374             // make a note of the old meta-digest, if this changes we need to revalidate all of our
1375             // resources as one or more of them have also changed
1376             String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1377             try {
1378                 status.updateStatus("m.checking");
1379                 downloadDigestFiles();
1380                 _digest = new Digest(getAppDir(), _strictComments);
1381                 if (!olddig.equals(_digest.getMetaDigest())) {
1382                     log.info("Unversioned digest changed. Revalidating...");
1383                     status.updateStatus("m.validating");
1384                     clearValidationMarkers();
1385                 }
1386             } catch (IOException ioe) {
1387                 log.warning("Failed to refresh non-versioned digest: " +
1388                             ioe.getMessage() + ". Proceeding...");
1389             }
1390         }
1391
1392         // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1393         // redownload the digest file and give it another good college try; this time we allow
1394         // exceptions to propagate up to the caller as there is nothing else we can do
1395         if (_digest == null) {
1396             status.updateStatus("m.updating_metadata");
1397             downloadDigestFiles();
1398             _digest = new Digest(getAppDir(), _strictComments);
1399         }
1400
1401         // now verify the contents of our main config file
1402         Resource crsrc = getConfigResource();
1403         if (!_digest.validateResource(crsrc, null)) {
1404             status.updateStatus("m.updating_metadata");
1405             // attempt to redownload both of our metadata files; again we pass errors up to our
1406             // caller because there's nothing we can do to automatically recover
1407             downloadConfigFile();
1408             downloadDigestFiles();
1409             _digest = new Digest(getAppDir(), _strictComments);
1410             // revalidate everything if we end up downloading new metadata
1411             clearValidationMarkers();
1412             // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1413             if (_digest.validateResource(crsrc, null)) {
1414                 init(true);
1415             } else {
1416                 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1417                             "Blindly forging onward.");
1418             }
1419         }
1420
1421         // start by assuming we are happy with our version
1422         _targetVersion = _version;
1423
1424         // if we are a versioned application, read in the contents of the version.txt file
1425         // and/or check the latest config URL for a newer version
1426         if (_version != -1) {
1427             File vfile = getLocalPath(VERSION_FILE);
1428             long fileVersion = VersionUtil.readVersion(vfile);
1429             if (fileVersion != -1) {
1430                 _targetVersion = fileVersion;
1431             }
1432
1433             if (_latest != null) {
1434                 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1435                      InputStreamReader reader = new InputStreamReader(in, UTF_8);
1436                      BufferedReader bin = new BufferedReader(reader)) {
1437                     for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1438                         if (pair[0].equals("version")) {
1439                             _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1440                             if (fileVersion != -1 && _targetVersion > fileVersion) {
1441                                 // replace the file with the newest version
1442                                 try (FileOutputStream fos = new FileOutputStream(vfile);
1443                                      PrintStream out = new PrintStream(fos)) {
1444                                     out.println(_targetVersion);
1445                                 }
1446                             }
1447                             break;
1448                         }
1449                     }
1450                 } catch (Exception e) {
1451                     log.warning("Unable to retrieve version from latest config file.", e);
1452                 }
1453             }
1454         }
1455
1456         // finally let the caller know if we need an update
1457         return _version != _targetVersion;
1458     }
1459
1460     /**
1461      * Verifies the code and media resources associated with this application. A list of resources
1462      * that do not exist or fail the verification process will be returned. If all resources are
1463      * ready to go, null will be returned and the application is considered ready to run.
1464      *
1465      * @param obs a progress observer that will be notified of verification progress. NOTE: this
1466      * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1467      * you have to take care to get back to your UI thread.
1468      * @param alreadyValid if non-null a 1 element array that will have the number of "already
1469      * validated" resources filled in.
1470      * @param unpacked a set to populate with unpacked resources.
1471      * @param toInstall a list into which to add resources that need to be installed.
1472      * @param toDownload a list into which to add resources that need to be downloaded.
1473      */
1474     public void verifyResources (
1475         ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1476         Set<Resource> toInstall, Set<Resource> toDownload)
1477         throws InterruptedException
1478     {
1479         // resources are verified on background threads supplied by the thread pool, and progress
1480         // is reported by posting runnable actions to the actions queue which is processed by the
1481         // main (UI) thread
1482         ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1483         final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1484         final int[] completed = new int[1];
1485
1486         long start = System.currentTimeMillis();
1487
1488         // obtain the sizes of the resources to validate
1489         List<Resource> rsrcs = getAllActiveResources();
1490         long[] sizes = new long[rsrcs.size()];
1491         long totalSize = 0;
1492         for (int ii = 0; ii < sizes.length; ii++) {
1493             totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1494         }
1495         final ProgressObserver fobs = obs;
1496         // as long as we forward aggregated progress updates to the UI thread, having multiple
1497         // threads update a progress aggregator is "mostly" thread-safe
1498         final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1499             public void progress (final int percent) {
1500                 actions.add(new Runnable() {
1501                     public void run () {
1502                         fobs.progress(percent);
1503                     }
1504                 });
1505             }
1506         }, sizes);
1507
1508         final int[] fAlreadyValid = alreadyValid;
1509         final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1510         final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1511         final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1512
1513         for (int ii = 0; ii < sizes.length; ii++) {
1514             final Resource rsrc = rsrcs.get(ii);
1515             final int index = ii;
1516             exec.execute(new Runnable() {
1517                 public void run () {
1518                     verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1519                                    unpackedAsync, toInstallAsync, toDownloadAsync);
1520                     actions.add(new Runnable() {
1521                         public void run () {
1522                             completed[0] += 1;
1523                         }
1524                     });
1525                 }
1526             });
1527         }
1528
1529         while (completed[0] < rsrcs.size()) {
1530             // we should be getting progress completion updates WAY more often than one every
1531             // minute, so if things freeze up for 60 seconds, abandon ship
1532             Runnable action = actions.poll(60, TimeUnit.SECONDS);
1533             action.run();
1534         }
1535
1536         exec.shutdown();
1537
1538         toInstall.addAll(toInstallAsync);
1539         toDownload.addAll(toDownloadAsync);
1540         unpacked.addAll(unpackedAsync);
1541
1542         long complete = System.currentTimeMillis();
1543         log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1544                  "duration", (complete-start) + "ms");
1545     }
1546
1547     private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1548                                  Set<Resource> unpacked,
1549                                  Set<Resource> toInstall, Set<Resource> toDownload) {
1550         if (rsrc.isMarkedValid()) {
1551             if (alreadyValid != null) {
1552                 alreadyValid[0]++;
1553             }
1554             obs.progress(100);
1555             return;
1556         }
1557
1558         try {
1559             if (_digest.validateResource(rsrc, obs)) {
1560                 // if the resource has a _new file, add it to to-install list
1561                 if (rsrc.getLocalNew().exists()) {
1562                     toInstall.add(rsrc);
1563                     return;
1564                 }
1565                 rsrc.applyAttrs();
1566                 unpacked.add(rsrc);
1567                 rsrc.markAsValid();
1568                 return;
1569             }
1570
1571         } catch (Exception e) {
1572             log.info("Failure verifying resource. Requesting redownload...",
1573                      "rsrc", rsrc, "error", e);
1574
1575         } finally {
1576             obs.progress(100);
1577         }
1578         toDownload.add(rsrc);
1579     }
1580
1581     /**
1582      * Unpacks the resources that require it (we know that they're valid).
1583      *
1584      * @param unpacked a set of resources to skip because they're already unpacked.
1585      */
1586     public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1587         throws InterruptedException
1588     {
1589         List<Resource> rsrcs = getActiveResources();
1590
1591         // remove resources that we don't want to unpack
1592         for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1593             Resource rsrc = it.next();
1594             if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1595                 it.remove();
1596             }
1597         }
1598
1599         // obtain the sizes of the resources to unpack
1600         long[] sizes = new long[rsrcs.size()];
1601         for (int ii = 0; ii < sizes.length; ii++) {
1602             sizes[ii] = rsrcs.get(ii).getLocal().length();
1603         }
1604
1605         ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1606         for (int ii = 0; ii < sizes.length; ii++) {
1607             Resource rsrc = rsrcs.get(ii);
1608             ProgressObserver pobs = pagg.startElement(ii);
1609             try {
1610                 rsrc.unpack();
1611             } catch (IOException ioe) {
1612                 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1613             }
1614             pobs.progress(100);
1615         }
1616     }
1617
1618     /**
1619      * Clears all validation marker files.
1620      */
1621     public void clearValidationMarkers ()
1622     {
1623         clearValidationMarkers(getAllActiveResources().iterator());
1624     }
1625
1626     /**
1627      * Returns the version number for the application.  Should only be called after successful
1628      * return of verifyMetadata.
1629      */
1630     public long getVersion ()
1631     {
1632         return _version;
1633     }
1634
1635     /**
1636      * Creates a versioned application base URL for the specified version.
1637      */
1638     protected URL createVAppBase (long version)
1639         throws MalformedURLException
1640     {
1641         String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1642         return HostWhitelist.verify(new URL(url));
1643     }
1644
1645     /**
1646      * Clears all validation marker files for the resources in the supplied iterator.
1647      */
1648     protected void clearValidationMarkers (Iterator<Resource> iter)
1649     {
1650         while (iter.hasNext()) {
1651             iter.next().clearMarker();
1652         }
1653     }
1654
1655     /**
1656      * Downloads a new copy of CONFIG_FILE.
1657      */
1658     protected void downloadConfigFile ()
1659         throws IOException
1660     {
1661         downloadControlFile(CONFIG_FILE, 0);
1662     }
1663
1664     /**
1665      * @return true if gettingdown.lock was unlocked, already locked by this application or if
1666      * we're not locking at all.
1667      */
1668     public synchronized boolean lockForUpdates ()
1669     {
1670         if (_lock != null && _lock.isValid()) {
1671             return true;
1672         }
1673         try {
1674             _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1675         } catch (FileNotFoundException e) {
1676             log.warning("Unable to create lock file", "message", e.getMessage(), e);
1677             return false;
1678         }
1679         try {
1680             _lock = _lockChannel.tryLock();
1681         } catch (IOException e) {
1682             log.warning("Unable to create lock", "message", e.getMessage(), e);
1683             return false;
1684         } catch (OverlappingFileLockException e) {
1685             log.warning("The lock is held elsewhere in this JVM", e);
1686             return false;
1687         }
1688         log.info("Able to lock for updates: " + (_lock != null));
1689         return _lock != null;
1690     }
1691
1692     /**
1693      * Release gettingdown.lock
1694      */
1695     public synchronized void releaseLock ()
1696     {
1697         if (_lock != null) {
1698             log.info("Releasing lock");
1699             try {
1700                 _lock.release();
1701             } catch (IOException e) {
1702                 log.warning("Unable to release lock", "message", e.getMessage(), e);
1703             }
1704             try {
1705                 _lockChannel.close();
1706             } catch (IOException e) {
1707                 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1708             }
1709             _lockChannel = null;
1710             _lock = null;
1711         }
1712     }
1713
1714     /**
1715      * Downloads the digest files and validates their signature.
1716      * @throws IOException
1717      */
1718     protected void downloadDigestFiles ()
1719         throws IOException
1720     {
1721         for (int version = 1; version <= Digest.VERSION; version++) {
1722             downloadControlFile(Digest.digestFile(version), version);
1723         }
1724     }
1725
1726     /**
1727      * Downloads a new copy of the specified control file, optionally validating its signature.
1728      * If the download is successful, moves it over the old file on the filesystem.
1729      *
1730      * <p> TODO: Switch to PKCS #7 or CMS.
1731      *
1732      * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1733      * should indicate the version of the digest file being validated which indicates which
1734      * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1735      */
1736     protected void downloadControlFile (String path, int sigVersion)
1737         throws IOException
1738     {
1739         File target = downloadFile(path);
1740
1741         if (sigVersion > 0) {
1742             if (_envc.certs.isEmpty()) {
1743                 log.info("No signing certs, not verifying digest.txt", "path", path);
1744
1745             } else {
1746                 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1747                 byte[] signature = null;
1748                 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1749                     signature = StreamUtil.toByteArray(signatureStream);
1750                 } finally {
1751                     FileUtil.deleteHarder(signatureFile); // delete the file regardless
1752                 }
1753
1754                 byte[] buffer = new byte[8192];
1755                 int length, validated = 0;
1756                 for (Certificate cert : _envc.certs) {
1757                     try (FileInputStream dataInput = new FileInputStream(target)) {
1758                         Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1759                         sig.initVerify(cert);
1760                         while ((length = dataInput.read(buffer)) != -1) {
1761                             sig.update(buffer, 0, length);
1762                         }
1763
1764                         if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1765                             log.info("Signature does not match", "cert", cert.getPublicKey());
1766                             continue;
1767                         } else {
1768                             log.info("Signature matches", "cert", cert.getPublicKey());
1769                             validated++;
1770                         }
1771
1772                     } catch (IOException ioe) {
1773                         log.warning("Failure validating signature of " + target + ": " + ioe);
1774
1775                     } catch (GeneralSecurityException gse) {
1776                         // no problem!
1777
1778                     }
1779                 }
1780
1781                 // if we couldn't find a key that validates our digest, we are the hosed!
1782                 if (validated == 0) {
1783                     // delete the temporary digest file as we know it is invalid
1784                     FileUtil.deleteHarder(target);
1785                     throw new IOException("m.corrupt_digest_signature_error");
1786                 }
1787             }
1788         }
1789
1790         // now move the temporary file over the original
1791         File original = getLocalPath(path);
1792         if (!FileUtil.renameTo(target, original)) {
1793             throw new IOException("Failed to rename(" + target + ", " + original + ")");
1794         }
1795     }
1796
1797     /**
1798      * Download a path to a temporary file, returning a {@link File} instance with the path
1799      * contents.
1800      */
1801     protected File downloadFile (String path)
1802         throws IOException
1803     {
1804         File target = getLocalPath(path + "_new");
1805
1806         URL targetURL = null;
1807         try {
1808             targetURL = getRemoteURL(path);
1809         } catch (Exception e) {
1810             log.warning("Requested to download invalid control file",
1811                 "appbase", _vappbase, "path", path, "error", e);
1812             throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1813         }
1814
1815         log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1816
1817         // stream the URL into our temporary file
1818         URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1819         // we have to tell Java not to use caches here, otherwise it will cache any request for
1820         // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1821         // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1822         // about it; turning off caches is not a performance concern, because when Getdown asks
1823         // to download a file, it expects it to come over the wire, not from a cache
1824         uconn.setUseCaches(false);
1825         uconn.setRequestProperty("Accept-Encoding", "gzip");
1826         try (InputStream fin = uconn.getInputStream()) {
1827             String encoding = uconn.getContentEncoding();
1828             boolean gzip = "gzip".equalsIgnoreCase(encoding);
1829             try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1830                 try (FileOutputStream fout = new FileOutputStream(target)) {
1831                     StreamUtil.copy(fin2, fout);
1832                 }
1833             }
1834         }
1835
1836         return target;
1837     }
1838
1839     /** Helper function for creating {@link Resource} instances. */
1840     protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1841         throws MalformedURLException
1842     {
1843         return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1844     }
1845
1846     /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1847     protected static void addAll (String[] values, List<String> target) {
1848         if (values != null) {
1849             for (String value : values) {
1850                 target.add(value);
1851             }
1852         }
1853     }
1854
1855     /**
1856      * Make an immutable List from the specified int array.
1857      */
1858     public static List<Integer> intsToList (int[] values)
1859     {
1860         List<Integer> list = new ArrayList<>(values.length);
1861         for (int val : values) {
1862             list.add(val);
1863         }
1864         return Collections.unmodifiableList(list);
1865     }
1866
1867     /**
1868      * Make an immutable List from the specified String array.
1869      */
1870     public static List<String> stringsToList (String[] values)
1871     {
1872         return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1873     }
1874
1875     /** Used to parse resources with the specified name. */
1876     protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1877                                    List<Resource> list)
1878     {
1879         String[] rsrcs = config.getMultiValue(name);
1880         if (rsrcs == null) {
1881             return;
1882         }
1883         for (String rsrc : rsrcs) {
1884             try {
1885                 list.add(createResource(rsrc, attrs));
1886             } catch (Exception e) {
1887                 log.warning("Invalid resource '" + rsrc + "'. " + e);
1888             }
1889         }
1890     }
1891
1892     /** Possibly generates and returns a google analytics tracking cookie. */
1893     protected String getGATrackingCode ()
1894     {
1895         if (_trackingGAHash == null) {
1896             return "";
1897         }
1898         long time = System.currentTimeMillis() / 1000;
1899         if (_trackingStart == 0) {
1900             _trackingStart = time;
1901         }
1902         if (_trackingId == 0) {
1903             int low = 100000000, high = 1000000000;
1904             _trackingId = low + _rando.nextInt(high-low);
1905         }
1906         StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1907         cookie.append(".").append(_trackingId);
1908         cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1909         cookie.append(".").append(time).append(".1%3B%2B");
1910         cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1911         cookie.append(_trackingStart).append(".1.1.");
1912         cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1913         int low = 1000000000, high = 2000000000;
1914         cookie.append("&utmn=").append(_rando.nextInt(high-low));
1915         return cookie.toString();
1916     }
1917
1918     /**
1919      * Encodes a path for use in a URL.
1920      */
1921     protected static String encodePath (String path)
1922     {
1923         try {
1924             // we want to keep slashes because we're encoding an entire path; also we need to turn
1925             // + into %20 because web servers don't like + in paths or file names, blah
1926             return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1927         } catch (UnsupportedEncodingException ue) {
1928             log.warning("Failed to URL encode " + path + ": " + ue);
1929             return path;
1930         }
1931     }
1932
1933     protected File getLocalPath (File appdir, String path)
1934     {
1935         return new File(appdir, path);
1936     }
1937
1938     public static void setStartupFilesFromParameterString(String p) {
1939       // multiple files *might* be passed in as space separated quoted filenames
1940       String q = "\"";
1941       if (!StringUtil.isBlank(p)) {
1942         String[] filenames;
1943         // split quoted params or treat as single string array
1944         if (p.startsWith(q) && p.endsWith(q)) {
1945           // this fails if, e.g.
1946           // p=q("stupidfilename\" " "otherfilename")
1947           // let's hope no-one ever ends a filename with '" '
1948           filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1949         } else {
1950           // single unquoted filename
1951           filenames = new String[]{p};
1952         }
1953
1954         // check for locator file.  Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1955         String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
1956         if (
1957                 !StringUtil.isBlank(locatorFilename)
1958                 && locatorFilename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)
1959                 ) {
1960           setLocatorFile(locatorFilename);
1961           // remove the locator filename from the filenames array
1962           String[] otherFilenames = new String[filenames.length - 1];
1963           System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
1964           filenames = otherFilenames;
1965         }
1966
1967         for (int i = 0; i < filenames.length; i++) {
1968           String filename = filenames[i];
1969           // skip any other locator files in a multiple file list
1970           if (filename.startsWith("jalview://") || filename.startsWith("jalviews://")) {
1971             setJalviewUri(filename);
1972           } else if (! filename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
1973             addStartupFile(filename);
1974           }
1975         }
1976       }
1977     }
1978     
1979     public static void setLocatorFile(String filename) {
1980       _locatorFile = new File(filename);
1981     }
1982     
1983     public static void addStartupFile(String filename) {
1984       _startupFiles.add(new File(filename));
1985     }
1986     
1987     public static void setJalviewUri(String uri) {
1988       _jalviewUri = uri;
1989     }
1990     
1991     private Config createLocatorConfig(Config.ParseOpts opts) {
1992       if (_locatorFile == null) {
1993         return null;
1994       }
1995       
1996       Config locatorConfig = null;
1997       
1998       try {
1999         Config tmpConfig = null;
2000         Map<String, Object> tmpData = new HashMap<>();
2001         if (_locatorFile.exists()) {
2002           tmpConfig = Config.parseConfig(_locatorFile,  opts);
2003           // appbase is sanitised in HostWhitelist
2004           Map<String, Object> tmpConfigData = tmpConfig.getData();
2005           if (tmpConfig != null) {
2006             for (Map.Entry<String, Object> entry : tmpConfigData.entrySet()) {
2007               String key = entry.getKey();
2008               Object value = entry.getValue();
2009               String mkey = key.indexOf('.') > -1 ? key.substring(key.indexOf('.') + 1) : key;
2010               if (Config.allowedReplaceKeys.contains(mkey) || Config.allowedMergeKeys.contains(mkey)) {
2011                 tmpData.put(key, value);
2012               }
2013             }
2014           } else {
2015             log.warning("Error occurred reading config file", "file", _locatorFile);
2016           }
2017         } else {
2018           log.warning("Given locator file does not exist", "file", _locatorFile);
2019         }
2020         
2021         locatorConfig = new Config(tmpData);
2022         
2023       } catch (Exception e) {
2024         log.warning("Failure reading locator file",  "file", _locatorFile, e);
2025       }
2026       
2027       return locatorConfig;
2028     }
2029     
2030     public String getAppbase() {
2031         return _appbase;
2032     }
2033     
2034     protected final EnvConfig _envc;
2035     protected File _config;
2036     protected File _backupConfig;
2037     protected Digest _digest;
2038
2039     protected long _version = -1;
2040     protected long _targetVersion = -1;
2041     protected String _appbase;
2042     protected URL _vappbase;
2043     protected URL _latest;
2044     protected String _class;
2045     protected String _dockName;
2046     protected String _dockIconPath;
2047     protected boolean _strictComments;
2048     protected boolean _windebug;
2049     protected boolean _allowOffline;
2050     protected int _maxConcDownloads;
2051
2052     protected String _trackingURL;
2053     protected Set<Integer> _trackingPcts;
2054     protected String _trackingCookieName;
2055     protected String _trackingCookieProperty;
2056     protected String _trackingURLSuffix;
2057     protected String _trackingGAHash;
2058     protected long _trackingStart;
2059     protected int _trackingId;
2060
2061     protected String _javaVersionProp = "java.version";
2062     protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
2063     protected long _javaMinVersion, _javaMaxVersion;
2064     protected boolean _javaExactVersionRequired;
2065     protected String _javaLocation;
2066
2067     protected List<Resource> _codes = new ArrayList<>();
2068     protected List<Resource> _resources = new ArrayList<>();
2069
2070     protected boolean _useCodeCache;
2071     protected int _codeCacheRetentionDays;
2072
2073     protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
2074     protected Map<String,Boolean> _auxactive = new HashMap<>();
2075
2076     protected List<String> _jvmargs = new ArrayList<>();
2077     protected List<String> _appargs = new ArrayList<>();
2078
2079     protected String[] _optimumJvmArgs;
2080
2081     protected List<String> _txtJvmArgs = new ArrayList<>();
2082
2083     /** If a warning has been issued about not being able to set modtimes. */
2084     protected boolean _warnedAboutSetLastModified;
2085
2086     /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
2087     protected FileLock _lock;
2088
2089     /** Channel to the file underlying _lock.  Kept around solely so the lock doesn't close. */
2090     protected FileChannel _lockChannel;
2091
2092     protected Random _rando = new Random();
2093
2094     protected static final String[] EMPTY_STRING_ARRAY = new String[0];
2095
2096     protected static final String ENV_VAR_PREFIX = "%ENV.";
2097     protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
2098  
2099     protected static File _locatorFile;
2100     protected static List<File> _startupFiles = new ArrayList<>();
2101     protected static String _jalviewUri;
2102     public static final String LOCATOR_FILE_EXTENSION = "jvl";
2103
2104     private boolean _initialised = false;
2105     private Config _initialisedConfig = null;
2106     
2107     public static String i4jVersion = null;
2108     private String jvmmempc = null;
2109     private String jvmmemmax = null;
2110 }