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