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