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