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