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