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