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