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