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