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