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