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