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