JAL-3246 JAL-3247 Reworked JVL files as getdown.txt config with limitations
[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         if (_appbase == null) {
601             throw new RuntimeException("m.missing_appbase");
602         }
603
604         // check if we're overriding the domain in the appbase
605         _appbase = SysProps.overrideAppbase(_appbase);
606
607         // make sure there's a trailing slash
608         if (!_appbase.endsWith("/")) {
609             _appbase = _appbase + "/";
610         }
611
612         // extract our version information
613         _version = config.getLong("version", -1L);
614
615         // if we are a versioned deployment, create a versioned appbase
616         try {
617             _vappbase = createVAppBase(_version);
618         } catch (MalformedURLException mue) {
619             String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
620             throw (IOException) new IOException(err).initCause(mue);
621         }
622
623         // check for a latest config URL
624         String latest = config.getString("latest");
625         if (latest != null) {
626             if (latest.startsWith(_appbase)) {
627                 latest = _appbase + latest.substring(_appbase.length());
628             } else {
629                 latest = SysProps.replaceDomain(latest);
630             }
631             try {
632                 _latest = HostWhitelist.verify(new URL(latest));
633             } catch (MalformedURLException mue) {
634                 log.warning("Invalid URL for latest attribute.", mue);
635             }
636         }
637
638         String appPrefix = _envc.appId == null ? "" : (_envc.appId + ".");
639
640         // determine our application class name (use app-specific class _if_ one is provided)
641         _class = config.getString("class");
642         if (appPrefix.length() > 0) {
643             _class = config.getString(appPrefix + "class", _class);
644         }
645         if (_class == null) {
646             throw new IOException("m.missing_class");
647         }
648
649         // determine whether we want strict comments
650         _strictComments = config.getBoolean("strict_comments");
651
652         // check to see if we're using a custom java.version property and regex
653         _javaVersionProp = config.getString("java_version_prop", _javaVersionProp);
654         _javaVersionRegex = config.getString("java_version_regex", _javaVersionRegex);
655
656         // check to see if we require a particular JVM version and have a supplied JVM
657         _javaMinVersion = config.getLong("java_version", _javaMinVersion);
658         // we support java_min_version as an alias of java_version; it better expresses the check
659         // that's going on and better mirrors java_max_version
660         _javaMinVersion = config.getLong("java_min_version", _javaMinVersion);
661         // check to see if we require a particular max JVM version and have a supplied JVM
662         _javaMaxVersion = config.getLong("java_max_version", _javaMaxVersion);
663         // check to see if we require a particular JVM version and have a supplied JVM
664         _javaExactVersionRequired = config.getBoolean("java_exact_version_required");
665
666         // this is a little weird, but when we're run from the digester, we see a String[] which
667         // contains java locations for all platforms which we can't grok, but the digester doesn't
668         // need to know about that; when we're run in a real application there will be only one!
669         Object javaloc = config.getRaw("java_location");
670         if (javaloc instanceof String) {
671             _javaLocation = (String)javaloc;
672         }
673
674         // determine whether we have any tracking configuration
675         _trackingURL = config.getString("tracking_url");
676
677         // check for tracking progress percent configuration
678         String trackPcts = config.getString("tracking_percents");
679         if (!StringUtil.isBlank(trackPcts)) {
680             _trackingPcts = new HashSet<>();
681             for (int pct : StringUtil.parseIntArray(trackPcts)) {
682                 _trackingPcts.add(pct);
683             }
684         } else if (!StringUtil.isBlank(_trackingURL)) {
685             _trackingPcts = new HashSet<>();
686             _trackingPcts.add(50);
687         }
688
689         // Check for tracking cookie configuration
690         _trackingCookieName = config.getString("tracking_cookie_name");
691         _trackingCookieProperty = config.getString("tracking_cookie_property");
692
693         // Some app may need an extra suffix added to the tracking URL
694         _trackingURLSuffix = config.getString("tracking_url_suffix");
695
696         // Some app may need to generate google analytics code
697         _trackingGAHash = config.getString("tracking_ga_hash");
698
699         // clear our arrays as we may be reinitializing
700         _codes.clear();
701         _resources.clear();
702         _auxgroups.clear();
703         _jvmargs.clear();
704         _appargs.clear();
705         _txtJvmArgs.clear();
706
707         // parse our code resources
708         if (config.getMultiValue("code") == null &&
709             config.getMultiValue("ucode") == null) {
710             throw new IOException("m.missing_code");
711         }
712         parseResources(config, "code", Resource.NORMAL, _codes);
713         parseResources(config, "ucode", Resource.UNPACK, _codes);
714
715         // parse our non-code resources
716         parseResources(config, "resource", Resource.NORMAL, _resources);
717         parseResources(config, "uresource", Resource.UNPACK, _resources);
718         parseResources(config, "xresource", Resource.EXEC, _resources);
719         parseResources(config, "presource", Resource.PRELOAD, _resources);
720         parseResources(config, "nresource", Resource.NATIVE, _resources);
721
722         // parse our auxiliary resource groups
723         for (String auxgroup : config.getList("auxgroups")) {
724             ArrayList<Resource> codes = new ArrayList<>();
725             parseResources(config, auxgroup + ".code", Resource.NORMAL, codes);
726             parseResources(config, auxgroup + ".ucode", Resource.UNPACK, codes);
727             ArrayList<Resource> rsrcs = new ArrayList<>();
728             parseResources(config, auxgroup + ".resource", Resource.NORMAL, rsrcs);
729             parseResources(config, auxgroup + ".xresource", Resource.EXEC, rsrcs);
730             parseResources(config, auxgroup + ".uresource", Resource.UNPACK, rsrcs);
731             parseResources(config, auxgroup + ".presource", Resource.PRELOAD, rsrcs);
732             parseResources(config, auxgroup + ".nresource", Resource.NATIVE, rsrcs);
733             _auxgroups.put(auxgroup, new AuxGroup(auxgroup, codes, rsrcs));
734         }
735
736         // transfer our JVM arguments (we include both "global" args and app_id-prefixed args)
737         String[] jvmargs = config.getMultiValue("jvmarg");
738         addAll(jvmargs, _jvmargs);
739         if (appPrefix.length() > 0) {
740             jvmargs = config.getMultiValue(appPrefix + "jvmarg");
741             addAll(jvmargs, _jvmargs);
742         }
743
744         // see if a percentage of physical memory option exists
745         int jvmmempc = config.getInt("jvmmempc", -1);
746         // app_id prefixed setting overrides
747         if (appPrefix.length() > 0) {
748             jvmmempc = config.getInt(appPrefix + "jvmmempc", jvmmempc);
749         }
750         if (0 <= jvmmempc && jvmmempc <= 100) {
751             final Object o = ManagementFactory.getOperatingSystemMXBean();
752
753             try {
754                 if (o instanceof OperatingSystemMXBean) {
755                     final OperatingSystemMXBean osb = (OperatingSystemMXBean) o;
756                     long physicalMem = osb.getTotalPhysicalMemorySize();
757                     long requestedMem = physicalMem*jvmmempc/100;
758                     String[] maxMemHeapArg = new String[]{"-Xmx"+Long.toString(requestedMem)};
759                     // remove other max heap size arg
760                     ARG: for (int i = 0; i < _jvmargs.size(); i++) {
761                            if (_jvmargs.get(i) instanceof java.lang.String && _jvmargs.get(i).startsWith("-Xmx")) {
762                                 _jvmargs.remove(i);
763                            }
764                     }
765                     addAll(maxMemHeapArg, _jvmargs);
766
767                 }
768             }
769             catch (NoClassDefFoundError e) {
770                 // com.sun.management.OperatingSystemMXBean doesn't exist in this JVM
771                 System.out.println("No com.sun.management.OperatingSystemMXBean. Cannot use 'jvmmempc'.");
772             }
773         } else if (jvmmempc != -1) {
774           System.out.println("'jvmmempc' value must be in range 0 to 100 (read as '"+Integer.toString(jvmmempc)+"')");
775         }
776
777         // get the set of optimum JVM arguments
778         _optimumJvmArgs = config.getMultiValue("optimum_jvmarg");
779
780         // transfer our application arguments
781         String[] appargs = config.getMultiValue(appPrefix + "apparg");
782         addAll(appargs, _appargs);
783
784         // add the launch specific application arguments
785         _appargs.addAll(_envc.appArgs);
786         
787         // look for custom arguments
788         fillAssignmentListFromPairs("extra.txt", _txtJvmArgs);
789
790         // determine whether we want to allow offline operation (defaults to false)
791         _allowOffline = config.getBoolean("allow_offline");
792
793         // look for a debug.txt file which causes us to run in java.exe on Windows so that we can
794         // obtain a thread dump of the running JVM
795         _windebug = getLocalPath("debug.txt").exists();
796
797         // whether to cache code resources and launch from cache
798         _useCodeCache = config.getBoolean("use_code_cache");
799         _codeCacheRetentionDays = config.getInt("code_cache_retention_days", 7);
800
801         // maximum simultaneous downloads
802         _maxConcDownloads = Math.max(1, config.getInt("max_concurrent_downloads",
803                                                       SysProps.threadPoolSize()));
804
805         // extract some info used to configure our child process on macOS
806         _dockName = config.getString("ui.name");
807         _dockIconPath = config.getString("ui.mac_dock_icon", "../desktop.icns");
808
809         return config;
810     }
811
812     /**
813      * Adds strings of the form pair0=pair1 to collector for each pair parsed out of pairLocation.
814      */
815     protected void fillAssignmentListFromPairs (String pairLocation, List<String> collector)
816     {
817         File pairFile = getLocalPath(pairLocation);
818         if (pairFile.exists()) {
819             try {
820                 List<String[]> args = Config.parsePairs(pairFile, Config.createOpts(false));
821                 for (String[] pair : args) {
822                     if (pair[1].length() == 0) {
823                         collector.add(pair[0]);
824                     } else {
825                         collector.add(pair[0] + "=" + pair[1]);
826                     }
827                 }
828             } catch (Throwable t) {
829                 log.warning("Failed to parse '" + pairFile + "': " + t);
830             }
831         }
832     }
833
834     /**
835      * Returns a URL from which the specified path can be fetched. Our application base URL is
836      * properly versioned and combined with the supplied path.
837      */
838     public URL getRemoteURL (String path)
839         throws MalformedURLException
840     {
841         return new URL(_vappbase, encodePath(path));
842     }
843
844     /**
845      * Returns the local path to the specified resource.
846      */
847     public File getLocalPath (String path)
848     {
849         return getLocalPath(getAppDir(), path);
850     }
851
852     /**
853      * Returns true if we either have no version requirement, are running in a JVM that meets our
854      * version requirements or have what appears to be a version of the JVM that meets our
855      * requirements.
856      */
857     public boolean haveValidJavaVersion ()
858     {
859         // if we're doing no version checking, then yay!
860         if (_javaMinVersion == 0 && _javaMaxVersion == 0) return true;
861
862         try {
863             // parse the version out of the java.version (or custom) system property
864             long version = SysProps.parseJavaVersion(_javaVersionProp, _javaVersionRegex);
865
866             log.info("Checking Java version", "current", version,
867                      "wantMin", _javaMinVersion, "wantMax", _javaMaxVersion);
868
869             // if we have an unpacked VM, check the 'release' file for its version
870             Resource vmjar = getJavaVMResource();
871             if (vmjar != null && vmjar.isMarkedValid()) {
872                 File vmdir = new File(getAppDir(), LaunchUtil.LOCAL_JAVA_DIR);
873                 File relfile = new File(vmdir, "release");
874                 if (!relfile.exists()) {
875                     log.warning("Unpacked JVM missing 'release' file. Assuming valid version.");
876                     return true;
877                 }
878
879                 long vmvers = VersionUtil.readReleaseVersion(relfile, _javaVersionRegex);
880                 if (vmvers == 0L) {
881                     log.warning("Unable to read version from 'release' file. Assuming valid.");
882                     return true;
883                 }
884
885                 version = vmvers;
886                 log.info("Checking version of unpacked JVM [vers=" + version + "].");
887             }
888
889             if (_javaExactVersionRequired) {
890                 if (version == _javaMinVersion) return true;
891                 else {
892                     log.warning("An exact Java VM version is required.", "current", version,
893                                 "required", _javaMinVersion);
894                     return false;
895                 }
896             }
897
898             boolean minVersionOK = (_javaMinVersion == 0) || (version >= _javaMinVersion);
899             boolean maxVersionOK = (_javaMaxVersion == 0) || (version <= _javaMaxVersion);
900             return minVersionOK && maxVersionOK;
901
902         } catch (RuntimeException re) {
903             // if we can't parse the java version we're in weird land and should probably just try
904             // our luck with what we've got rather than try to download a new jvm
905             log.warning("Unable to parse VM version, hoping for the best",
906                         "error", re, "needed", _javaMinVersion);
907             return true;
908         }
909     }
910
911     /**
912      * Checks whether the app has a set of "optimum" JVM args that we wish to try first, detecting
913      * whether the launch is successful and, if necessary, trying again without the optimum
914      * arguments.
915      */
916     public boolean hasOptimumJvmArgs ()
917     {
918         return _optimumJvmArgs != null;
919     }
920
921     /**
922      * Returns true if the app should attempt to run even if we have no Internet connection.
923      */
924     public boolean allowOffline ()
925     {
926         return _allowOffline;
927     }
928
929     /**
930      * Attempts to redownload the <code>getdown.txt</code> file based on information parsed from a
931      * previous call to {@link #init}.
932      */
933     public void attemptRecovery (StatusDisplay status)
934         throws IOException
935     {
936         status.updateStatus("m.updating_metadata");
937         downloadConfigFile();
938     }
939
940     /**
941      * Downloads and replaces the <code>getdown.txt</code> and <code>digest.txt</code> files with
942      * those for the target version of our application.
943      */
944     public void updateMetadata ()
945         throws IOException
946     {
947         try {
948             // update our versioned application base with the target version
949             _vappbase = createVAppBase(_targetVersion);
950         } catch (MalformedURLException mue) {
951             String err = MessageUtil.tcompose("m.invalid_appbase", _appbase);
952             throw (IOException) new IOException(err).initCause(mue);
953         }
954
955         try {
956             // now re-download our control files; we download the digest first so that if it fails,
957             // our config file will still reference the old version and re-running the updater will
958             // start the whole process over again
959             downloadDigestFiles();
960             downloadConfigFile();
961
962         } catch (IOException ex) {
963             // if we are allowing offline execution, we want to allow the application to run in its
964             // current form rather than aborting the entire process; to do this, we delete the
965             // version.txt file and "trick" Getdown into thinking that it just needs to validate
966             // the application as is; next time the app runs when connected to the internet, it
967             // will have to rediscover that it needs updating and reattempt to update itself
968             if (_allowOffline) {
969                 log.warning("Failed to update digest files.  Attempting offline operaton.", ex);
970                 if (!FileUtil.deleteHarder(getLocalPath(VERSION_FILE))) {
971                     log.warning("Deleting version.txt failed.  This probably isn't going to work.");
972                 }
973             } else {
974                 throw ex;
975             }
976         }
977     }
978
979     /**
980      * Invokes the process associated with this application definition.
981      *
982      * @param optimum whether or not to include the set of optimum arguments (as opposed to falling
983      * back).
984      */
985     public Process createProcess (boolean optimum)
986         throws IOException
987     {
988         ArrayList<String> args = new ArrayList<>();
989
990         // reconstruct the path to the JVM
991         args.add(LaunchUtil.getJVMPath(getAppDir(), _windebug || optimum));
992
993         // check whether we're using -jar mode or -classpath mode
994         boolean dashJarMode = MANIFEST_CLASS.equals(_class);
995
996         // add the -classpath arguments if we're not in -jar mode
997         ClassPath classPath = PathBuilder.buildClassPath(this);
998         if (!dashJarMode) {
999             args.add("-classpath");
1000             args.add(classPath.asArgumentString());
1001         }
1002
1003         // we love our Mac users, so we do nice things to preserve our application identity
1004         if (LaunchUtil.isMacOS()) {
1005             args.add("-Xdock:icon=" + getLocalPath(_dockIconPath).getAbsolutePath());
1006             args.add("-Xdock:name=" + _dockName);
1007         }
1008
1009         // pass along our proxy settings
1010         String proxyHost;
1011         if ((proxyHost = System.getProperty("http.proxyHost")) != null) {
1012             args.add("-Dhttp.proxyHost=" + proxyHost);
1013             args.add("-Dhttp.proxyPort=" + System.getProperty("http.proxyPort"));
1014             args.add("-Dhttps.proxyHost=" + proxyHost);
1015             args.add("-Dhttps.proxyPort=" + System.getProperty("http.proxyPort"));
1016         }
1017
1018         // add the marker indicating the app is running in getdown
1019         args.add("-D" + Properties.GETDOWN + "=true");
1020
1021         // set the native library path if we have native resources
1022         // @TODO optional getdown.txt parameter to set addCurrentLibraryPath to true or false?
1023         ClassPath javaLibPath = PathBuilder.buildLibsPath(this, true);
1024         if (javaLibPath != null) {
1025             args.add("-Djava.library.path=" + javaLibPath.asArgumentString());
1026         }
1027
1028         // pass along any pass-through arguments
1029         for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1030             String key = (String)entry.getKey();
1031             if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1032                 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1033                 args.add("-D" + key + "=" + entry.getValue());
1034             }
1035         }
1036
1037         // add the JVM arguments
1038         for (String string : _jvmargs) {
1039             args.add(processArg(string));
1040         }
1041
1042         // add the optimum arguments if requested and available
1043         if (optimum && _optimumJvmArgs != null) {
1044             for (String string : _optimumJvmArgs) {
1045                 args.add(processArg(string));
1046             }
1047         }
1048
1049         // add the arguments from extra.txt (after the optimum ones, in case they override them)
1050         for (String string : _txtJvmArgs) {
1051             args.add(processArg(string));
1052         }
1053
1054         // if we're in -jar mode add those arguments, otherwise add the app class name
1055         if (dashJarMode) {
1056             args.add("-jar");
1057             args.add(classPath.asArgumentString());
1058         } else {
1059             args.add(_class);
1060         }
1061
1062         // almost finally check the startup file arguments
1063         for (File f : _startupFiles) {
1064           _appargs.add(f.getAbsolutePath());
1065           break; // Only add one file to open
1066         }
1067         
1068         // check if one arg with recognised extension
1069         if ( _appargs.size() == 1 && _appargs.get(0) != null ) {
1070           String filename = _appargs.get(0);
1071           String ext = null;
1072           int j = filename.lastIndexOf('.');
1073           if (j > -1) {
1074             ext = filename.substring(j+1);
1075           }
1076           if (LOCATOR_FILE_EXTENSION.equals(ext.toLowerCase())) {
1077             // this file extension should have been dealt with in Getdown class
1078           } else {
1079             _appargs.add(0, "-open");
1080           }
1081         }
1082
1083         // finally add the application arguments
1084         for (String string : _appargs) {
1085             args.add(processArg(string));
1086         }
1087         
1088         String[] envp = createEnvironment();
1089         String[] sargs = args.toArray(new String[args.size()]);
1090         log.info("Running " + StringUtil.join(sargs, "\n  "));
1091
1092         return Runtime.getRuntime().exec(sargs, envp, getAppDir());
1093     }
1094
1095     /**
1096      * If the application provided environment variables, combine those with the current
1097      * environment and return that in a style usable for {@link Runtime#exec(String, String[])}.
1098      * If the application didn't provide any environment variables, null is returned to just use
1099      * the existing environment.
1100      */
1101     protected String[] createEnvironment ()
1102     {
1103         List<String> envvar = new ArrayList<>();
1104         fillAssignmentListFromPairs("env.txt", envvar);
1105         if (envvar.isEmpty()) {
1106             log.info("Didn't find any custom environment variables, not setting any.");
1107             return null;
1108         }
1109
1110         List<String> envAssignments = new ArrayList<>();
1111         for (String assignment : envvar) {
1112             envAssignments.add(processArg(assignment));
1113         }
1114         for (Map.Entry<String, String> environmentEntry : System.getenv().entrySet()) {
1115             envAssignments.add(environmentEntry.getKey() + "=" + environmentEntry.getValue());
1116         }
1117         String[] envp = envAssignments.toArray(new String[envAssignments.size()]);
1118         log.info("Environment " + StringUtil.join(envp, "\n "));
1119         return envp;
1120     }
1121
1122     /**
1123      * Runs this application directly in the current VM.
1124      */
1125     public void invokeDirect () throws IOException
1126     {
1127         ClassPath classPath = PathBuilder.buildClassPath(this);
1128         URL[] jarUrls = classPath.asUrls();
1129
1130         // create custom class loader
1131         URLClassLoader loader = new URLClassLoader(jarUrls, ClassLoader.getSystemClassLoader()) {
1132             @Override protected PermissionCollection getPermissions (CodeSource code) {
1133                 Permissions perms = new Permissions();
1134                 perms.add(new AllPermission());
1135                 return perms;
1136             }
1137         };
1138         Thread.currentThread().setContextClassLoader(loader);
1139
1140         log.info("Configured URL class loader:");
1141         for (URL url : jarUrls) log.info("  " + url);
1142
1143         // configure any system properties that we can
1144         for (String jvmarg : _jvmargs) {
1145             if (jvmarg.startsWith("-D")) {
1146                 jvmarg = processArg(jvmarg.substring(2));
1147                 int eqidx = jvmarg.indexOf("=");
1148                 if (eqidx == -1) {
1149                     log.warning("Bogus system property: '" + jvmarg + "'?");
1150                 } else {
1151                     System.setProperty(jvmarg.substring(0, eqidx), jvmarg.substring(eqidx+1));
1152                 }
1153             }
1154         }
1155
1156         // pass along any pass-through arguments
1157         Map<String, String> passProps = new HashMap<>();
1158         for (Map.Entry<Object, Object> entry : System.getProperties().entrySet()) {
1159             String key = (String)entry.getKey();
1160             if (key.startsWith(PROP_PASSTHROUGH_PREFIX)) {
1161                 key = key.substring(PROP_PASSTHROUGH_PREFIX.length());
1162                 passProps.put(key, (String)entry.getValue());
1163             }
1164         }
1165         // we can't set these in the above loop lest we get a ConcurrentModificationException
1166         for (Map.Entry<String, String> entry : passProps.entrySet()) {
1167             System.setProperty(entry.getKey(), entry.getValue());
1168         }
1169
1170         // prepare our app arguments
1171         String[] args = new String[_appargs.size()];
1172         for (int ii = 0; ii < args.length; ii++) args[ii] = processArg(_appargs.get(ii));
1173
1174         try {
1175             log.info("Loading " + _class);
1176             Class<?> appclass = loader.loadClass(_class);
1177             Method main = appclass.getMethod("main", EMPTY_STRING_ARRAY.getClass());
1178             log.info("Invoking main({" + StringUtil.join(args, ", ") + "})");
1179             main.invoke(null, new Object[] { args });
1180         } catch (Exception e) {
1181             log.warning("Failure invoking app main", e);
1182         }
1183     }
1184
1185     /** Replaces the application directory and version in any argument. */
1186     protected String processArg (String arg)
1187     {
1188         arg = arg.replace("%APPDIR%", getAppDir().getAbsolutePath());
1189         arg = arg.replace("%VERSION%", String.valueOf(_version));
1190
1191         // if this argument contains %ENV.FOO% replace those with the associated values looked up
1192         // from the environment
1193         if (arg.contains(ENV_VAR_PREFIX)) {
1194             StringBuffer sb = new StringBuffer();
1195             Matcher matcher = ENV_VAR_PATTERN.matcher(arg);
1196             while (matcher.find()) {
1197                 String varName = matcher.group(1), varValue = System.getenv(varName);
1198                 String repValue = varValue == null ? "MISSING:"+varName : varValue;
1199                 matcher.appendReplacement(sb, Matcher.quoteReplacement(repValue));
1200             }
1201             matcher.appendTail(sb);
1202             arg = sb.toString();
1203         }
1204
1205         return arg;
1206     }
1207
1208     /**
1209      * Loads the <code>digest.txt</code> file and verifies the contents of both that file and the
1210      * <code>getdown.text</code> file. Then it loads the <code>version.txt</code> and decides
1211      * whether or not the application needs to be updated or whether we can proceed to verification
1212      * and execution.
1213      *
1214      * @return true if the application needs to be updated, false if it is up to date and can be
1215      * verified and executed.
1216      *
1217      * @exception IOException thrown if we encounter an unrecoverable error while verifying the
1218      * metadata.
1219      */
1220     public boolean verifyMetadata (StatusDisplay status)
1221         throws IOException
1222     {
1223         log.info("Verifying application: " + _vappbase);
1224         log.info("Version: " + _version);
1225         log.info("Class: " + _class);
1226
1227         // this will read in the contents of the digest file and validate itself
1228         try {
1229             _digest = new Digest(getAppDir(), _strictComments);
1230         } catch (IOException ioe) {
1231             log.info("Failed to load digest: " + ioe.getMessage() + ". Attempting recovery...");
1232         }
1233
1234         // if we have no version, then we are running in unversioned mode so we need to download
1235         // our digest.txt file on every invocation
1236         if (_version == -1) {
1237             // make a note of the old meta-digest, if this changes we need to revalidate all of our
1238             // resources as one or more of them have also changed
1239             String olddig = (_digest == null) ? "" : _digest.getMetaDigest();
1240             try {
1241                 status.updateStatus("m.checking");
1242                 downloadDigestFiles();
1243                 _digest = new Digest(getAppDir(), _strictComments);
1244                 if (!olddig.equals(_digest.getMetaDigest())) {
1245                     log.info("Unversioned digest changed. Revalidating...");
1246                     status.updateStatus("m.validating");
1247                     clearValidationMarkers();
1248                 }
1249             } catch (IOException ioe) {
1250                 log.warning("Failed to refresh non-versioned digest: " +
1251                             ioe.getMessage() + ". Proceeding...");
1252             }
1253         }
1254
1255         // regardless of whether we're versioned, if we failed to read the digest from disk, try to
1256         // redownload the digest file and give it another good college try; this time we allow
1257         // exceptions to propagate up to the caller as there is nothing else we can do
1258         if (_digest == null) {
1259             status.updateStatus("m.updating_metadata");
1260             downloadDigestFiles();
1261             _digest = new Digest(getAppDir(), _strictComments);
1262         }
1263
1264         // now verify the contents of our main config file
1265         Resource crsrc = getConfigResource();
1266         if (!_digest.validateResource(crsrc, null)) {
1267             status.updateStatus("m.updating_metadata");
1268             // attempt to redownload both of our metadata files; again we pass errors up to our
1269             // caller because there's nothing we can do to automatically recover
1270             downloadConfigFile();
1271             downloadDigestFiles();
1272             _digest = new Digest(getAppDir(), _strictComments);
1273             // revalidate everything if we end up downloading new metadata
1274             clearValidationMarkers();
1275             // if the new copy validates, reinitialize ourselves; otherwise report baffling hoseage
1276             if (_digest.validateResource(crsrc, null)) {
1277                 init(true);
1278             } else {
1279                 log.warning(CONFIG_FILE + " failed to validate even after redownloading. " +
1280                             "Blindly forging onward.");
1281             }
1282         }
1283
1284         // start by assuming we are happy with our version
1285         _targetVersion = _version;
1286
1287         // if we are a versioned application, read in the contents of the version.txt file
1288         // and/or check the latest config URL for a newer version
1289         if (_version != -1) {
1290             File vfile = getLocalPath(VERSION_FILE);
1291             long fileVersion = VersionUtil.readVersion(vfile);
1292             if (fileVersion != -1) {
1293                 _targetVersion = fileVersion;
1294             }
1295
1296             if (_latest != null) {
1297                 try (InputStream in = ConnectionUtil.open(proxy, _latest, 0, 0).getInputStream();
1298                      InputStreamReader reader = new InputStreamReader(in, UTF_8);
1299                      BufferedReader bin = new BufferedReader(reader)) {
1300                     for (String[] pair : Config.parsePairs(bin, Config.createOpts(false))) {
1301                         if (pair[0].equals("version")) {
1302                             _targetVersion = Math.max(Long.parseLong(pair[1]), _targetVersion);
1303                             if (fileVersion != -1 && _targetVersion > fileVersion) {
1304                                 // replace the file with the newest version
1305                                 try (FileOutputStream fos = new FileOutputStream(vfile);
1306                                      PrintStream out = new PrintStream(fos)) {
1307                                     out.println(_targetVersion);
1308                                 }
1309                             }
1310                             break;
1311                         }
1312                     }
1313                 } catch (Exception e) {
1314                     log.warning("Unable to retrieve version from latest config file.", e);
1315                 }
1316             }
1317         }
1318
1319         // finally let the caller know if we need an update
1320         return _version != _targetVersion;
1321     }
1322
1323     /**
1324      * Verifies the code and media resources associated with this application. A list of resources
1325      * that do not exist or fail the verification process will be returned. If all resources are
1326      * ready to go, null will be returned and the application is considered ready to run.
1327      *
1328      * @param obs a progress observer that will be notified of verification progress. NOTE: this
1329      * observer may be called from arbitrary threads, so if you update a UI based on calls to it,
1330      * you have to take care to get back to your UI thread.
1331      * @param alreadyValid if non-null a 1 element array that will have the number of "already
1332      * validated" resources filled in.
1333      * @param unpacked a set to populate with unpacked resources.
1334      * @param toInstall a list into which to add resources that need to be installed.
1335      * @param toDownload a list into which to add resources that need to be downloaded.
1336      */
1337     public void verifyResources (
1338         ProgressObserver obs, int[] alreadyValid, Set<Resource> unpacked,
1339         Set<Resource> toInstall, Set<Resource> toDownload)
1340         throws InterruptedException
1341     {
1342         // resources are verified on background threads supplied by the thread pool, and progress
1343         // is reported by posting runnable actions to the actions queue which is processed by the
1344         // main (UI) thread
1345         ExecutorService exec = Executors.newFixedThreadPool(SysProps.threadPoolSize());
1346         final BlockingQueue<Runnable> actions = new LinkedBlockingQueue<Runnable>();
1347         final int[] completed = new int[1];
1348
1349         long start = System.currentTimeMillis();
1350
1351         // obtain the sizes of the resources to validate
1352         List<Resource> rsrcs = getAllActiveResources();
1353         long[] sizes = new long[rsrcs.size()];
1354         long totalSize = 0;
1355         for (int ii = 0; ii < sizes.length; ii++) {
1356             totalSize += sizes[ii] = rsrcs.get(ii).getLocal().length();
1357         }
1358         final ProgressObserver fobs = obs;
1359         // as long as we forward aggregated progress updates to the UI thread, having multiple
1360         // threads update a progress aggregator is "mostly" thread-safe
1361         final ProgressAggregator pagg = new ProgressAggregator(new ProgressObserver() {
1362             public void progress (final int percent) {
1363                 actions.add(new Runnable() {
1364                     public void run () {
1365                         fobs.progress(percent);
1366                     }
1367                 });
1368             }
1369         }, sizes);
1370
1371         final int[] fAlreadyValid = alreadyValid;
1372         final Set<Resource> toInstallAsync = new ConcurrentSkipListSet<>(toInstall);
1373         final Set<Resource> toDownloadAsync = new ConcurrentSkipListSet<>();
1374         final Set<Resource> unpackedAsync = new ConcurrentSkipListSet<>();
1375
1376         for (int ii = 0; ii < sizes.length; ii++) {
1377             final Resource rsrc = rsrcs.get(ii);
1378             final int index = ii;
1379             exec.execute(new Runnable() {
1380                 public void run () {
1381                     verifyResource(rsrc, pagg.startElement(index), fAlreadyValid,
1382                                    unpackedAsync, toInstallAsync, toDownloadAsync);
1383                     actions.add(new Runnable() {
1384                         public void run () {
1385                             completed[0] += 1;
1386                         }
1387                     });
1388                 }
1389             });
1390         }
1391
1392         while (completed[0] < rsrcs.size()) {
1393             // we should be getting progress completion updates WAY more often than one every
1394             // minute, so if things freeze up for 60 seconds, abandon ship
1395             Runnable action = actions.poll(60, TimeUnit.SECONDS);
1396             action.run();
1397         }
1398
1399         exec.shutdown();
1400
1401         toInstall.addAll(toInstallAsync);
1402         toDownload.addAll(toDownloadAsync);
1403         unpacked.addAll(unpackedAsync);
1404
1405         long complete = System.currentTimeMillis();
1406         log.info("Verified resources", "count", rsrcs.size(), "size", (totalSize/1024) + "k",
1407                  "duration", (complete-start) + "ms");
1408     }
1409
1410     private void verifyResource (Resource rsrc, ProgressObserver obs, int[] alreadyValid,
1411                                  Set<Resource> unpacked,
1412                                  Set<Resource> toInstall, Set<Resource> toDownload) {
1413         if (rsrc.isMarkedValid()) {
1414             if (alreadyValid != null) {
1415                 alreadyValid[0]++;
1416             }
1417             obs.progress(100);
1418             return;
1419         }
1420
1421         try {
1422             if (_digest.validateResource(rsrc, obs)) {
1423                 // if the resource has a _new file, add it to to-install list
1424                 if (rsrc.getLocalNew().exists()) {
1425                     toInstall.add(rsrc);
1426                     return;
1427                 }
1428                 rsrc.applyAttrs();
1429                 unpacked.add(rsrc);
1430                 rsrc.markAsValid();
1431                 return;
1432             }
1433
1434         } catch (Exception e) {
1435             log.info("Failure verifying resource. Requesting redownload...",
1436                      "rsrc", rsrc, "error", e);
1437
1438         } finally {
1439             obs.progress(100);
1440         }
1441         toDownload.add(rsrc);
1442     }
1443
1444     /**
1445      * Unpacks the resources that require it (we know that they're valid).
1446      *
1447      * @param unpacked a set of resources to skip because they're already unpacked.
1448      */
1449     public void unpackResources (ProgressObserver obs, Set<Resource> unpacked)
1450         throws InterruptedException
1451     {
1452         List<Resource> rsrcs = getActiveResources();
1453
1454         // remove resources that we don't want to unpack
1455         for (Iterator<Resource> it = rsrcs.iterator(); it.hasNext(); ) {
1456             Resource rsrc = it.next();
1457             if (!rsrc.shouldUnpack() || unpacked.contains(rsrc)) {
1458                 it.remove();
1459             }
1460         }
1461
1462         // obtain the sizes of the resources to unpack
1463         long[] sizes = new long[rsrcs.size()];
1464         for (int ii = 0; ii < sizes.length; ii++) {
1465             sizes[ii] = rsrcs.get(ii).getLocal().length();
1466         }
1467
1468         ProgressAggregator pagg = new ProgressAggregator(obs, sizes);
1469         for (int ii = 0; ii < sizes.length; ii++) {
1470             Resource rsrc = rsrcs.get(ii);
1471             ProgressObserver pobs = pagg.startElement(ii);
1472             try {
1473                 rsrc.unpack();
1474             } catch (IOException ioe) {
1475                 log.warning("Failure unpacking resource", "rsrc", rsrc, ioe);
1476             }
1477             pobs.progress(100);
1478         }
1479     }
1480
1481     /**
1482      * Clears all validation marker files.
1483      */
1484     public void clearValidationMarkers ()
1485     {
1486         clearValidationMarkers(getAllActiveResources().iterator());
1487     }
1488
1489     /**
1490      * Returns the version number for the application.  Should only be called after successful
1491      * return of verifyMetadata.
1492      */
1493     public long getVersion ()
1494     {
1495         return _version;
1496     }
1497
1498     /**
1499      * Creates a versioned application base URL for the specified version.
1500      */
1501     protected URL createVAppBase (long version)
1502         throws MalformedURLException
1503     {
1504         String url = version < 0 ? _appbase : _appbase.replace("%VERSION%", "" + version);
1505         return HostWhitelist.verify(new URL(url));
1506     }
1507
1508     /**
1509      * Clears all validation marker files for the resources in the supplied iterator.
1510      */
1511     protected void clearValidationMarkers (Iterator<Resource> iter)
1512     {
1513         while (iter.hasNext()) {
1514             iter.next().clearMarker();
1515         }
1516     }
1517
1518     /**
1519      * Downloads a new copy of CONFIG_FILE.
1520      */
1521     protected void downloadConfigFile ()
1522         throws IOException
1523     {
1524         downloadControlFile(CONFIG_FILE, 0);
1525     }
1526
1527     /**
1528      * @return true if gettingdown.lock was unlocked, already locked by this application or if
1529      * we're not locking at all.
1530      */
1531     public synchronized boolean lockForUpdates ()
1532     {
1533         if (_lock != null && _lock.isValid()) {
1534             return true;
1535         }
1536         try {
1537             _lockChannel = new RandomAccessFile(getLocalPath("gettingdown.lock"), "rw").getChannel();
1538         } catch (FileNotFoundException e) {
1539             log.warning("Unable to create lock file", "message", e.getMessage(), e);
1540             return false;
1541         }
1542         try {
1543             _lock = _lockChannel.tryLock();
1544         } catch (IOException e) {
1545             log.warning("Unable to create lock", "message", e.getMessage(), e);
1546             return false;
1547         } catch (OverlappingFileLockException e) {
1548             log.warning("The lock is held elsewhere in this JVM", e);
1549             return false;
1550         }
1551         log.info("Able to lock for updates: " + (_lock != null));
1552         return _lock != null;
1553     }
1554
1555     /**
1556      * Release gettingdown.lock
1557      */
1558     public synchronized void releaseLock ()
1559     {
1560         if (_lock != null) {
1561             log.info("Releasing lock");
1562             try {
1563                 _lock.release();
1564             } catch (IOException e) {
1565                 log.warning("Unable to release lock", "message", e.getMessage(), e);
1566             }
1567             try {
1568                 _lockChannel.close();
1569             } catch (IOException e) {
1570                 log.warning("Unable to close lock channel", "message", e.getMessage(), e);
1571             }
1572             _lockChannel = null;
1573             _lock = null;
1574         }
1575     }
1576
1577     /**
1578      * Downloads the digest files and validates their signature.
1579      * @throws IOException
1580      */
1581     protected void downloadDigestFiles ()
1582         throws IOException
1583     {
1584         for (int version = 1; version <= Digest.VERSION; version++) {
1585             downloadControlFile(Digest.digestFile(version), version);
1586         }
1587     }
1588
1589     /**
1590      * Downloads a new copy of the specified control file, optionally validating its signature.
1591      * If the download is successful, moves it over the old file on the filesystem.
1592      *
1593      * <p> TODO: Switch to PKCS #7 or CMS.
1594      *
1595      * @param sigVersion if {@code 0} no validation will be performed, if {@code > 0} then this
1596      * should indicate the version of the digest file being validated which indicates which
1597      * algorithm to use to verify the signature. See {@link Digest#VERSION}.
1598      */
1599     protected void downloadControlFile (String path, int sigVersion)
1600         throws IOException
1601     {
1602         File target = downloadFile(path);
1603
1604         if (sigVersion > 0) {
1605             if (_envc.certs.isEmpty()) {
1606                 log.info("No signing certs, not verifying digest.txt", "path", path);
1607
1608             } else {
1609                 File signatureFile = downloadFile(path + SIGNATURE_SUFFIX);
1610                 byte[] signature = null;
1611                 try (FileInputStream signatureStream = new FileInputStream(signatureFile)) {
1612                     signature = StreamUtil.toByteArray(signatureStream);
1613                 } finally {
1614                     FileUtil.deleteHarder(signatureFile); // delete the file regardless
1615                 }
1616
1617                 byte[] buffer = new byte[8192];
1618                 int length, validated = 0;
1619                 for (Certificate cert : _envc.certs) {
1620                     try (FileInputStream dataInput = new FileInputStream(target)) {
1621                         Signature sig = Signature.getInstance(Digest.sigAlgorithm(sigVersion));
1622                         sig.initVerify(cert);
1623                         while ((length = dataInput.read(buffer)) != -1) {
1624                             sig.update(buffer, 0, length);
1625                         }
1626
1627                         if (!sig.verify(Base64.decode(signature, Base64.DEFAULT))) {
1628                             log.info("Signature does not match", "cert", cert.getPublicKey());
1629                             continue;
1630                         } else {
1631                             log.info("Signature matches", "cert", cert.getPublicKey());
1632                             validated++;
1633                         }
1634
1635                     } catch (IOException ioe) {
1636                         log.warning("Failure validating signature of " + target + ": " + ioe);
1637
1638                     } catch (GeneralSecurityException gse) {
1639                         // no problem!
1640
1641                     }
1642                 }
1643
1644                 // if we couldn't find a key that validates our digest, we are the hosed!
1645                 if (validated == 0) {
1646                     // delete the temporary digest file as we know it is invalid
1647                     FileUtil.deleteHarder(target);
1648                     throw new IOException("m.corrupt_digest_signature_error");
1649                 }
1650             }
1651         }
1652
1653         // now move the temporary file over the original
1654         File original = getLocalPath(path);
1655         if (!FileUtil.renameTo(target, original)) {
1656             throw new IOException("Failed to rename(" + target + ", " + original + ")");
1657         }
1658     }
1659
1660     /**
1661      * Download a path to a temporary file, returning a {@link File} instance with the path
1662      * contents.
1663      */
1664     protected File downloadFile (String path)
1665         throws IOException
1666     {
1667         File target = getLocalPath(path + "_new");
1668
1669         URL targetURL = null;
1670         try {
1671             targetURL = getRemoteURL(path);
1672         } catch (Exception e) {
1673             log.warning("Requested to download invalid control file",
1674                 "appbase", _vappbase, "path", path, "error", e);
1675             throw (IOException) new IOException("Invalid path '" + path + "'.").initCause(e);
1676         }
1677
1678         log.info("Attempting to refetch '" + path + "' from '" + targetURL + "'.");
1679
1680         // stream the URL into our temporary file
1681         URLConnection uconn = ConnectionUtil.open(proxy, targetURL, 0, 0);
1682         // we have to tell Java not to use caches here, otherwise it will cache any request for
1683         // same URL for the lifetime of this JVM (based on the URL string, not the URL object);
1684         // if the getdown.txt file, for example, changes in the meanwhile, we would never hear
1685         // about it; turning off caches is not a performance concern, because when Getdown asks
1686         // to download a file, it expects it to come over the wire, not from a cache
1687         uconn.setUseCaches(false);
1688         uconn.setRequestProperty("Accept-Encoding", "gzip");
1689         try (InputStream fin = uconn.getInputStream()) {
1690             String encoding = uconn.getContentEncoding();
1691             boolean gzip = "gzip".equalsIgnoreCase(encoding);
1692             try (InputStream fin2 = (gzip ? new GZIPInputStream(fin) : fin)) {
1693                 try (FileOutputStream fout = new FileOutputStream(target)) {
1694                     StreamUtil.copy(fin2, fout);
1695                 }
1696             }
1697         }
1698
1699         return target;
1700     }
1701
1702     /** Helper function for creating {@link Resource} instances. */
1703     protected Resource createResource (String path, EnumSet<Resource.Attr> attrs)
1704         throws MalformedURLException
1705     {
1706         return new Resource(path, getRemoteURL(path), getLocalPath(path), attrs);
1707     }
1708
1709     /** Helper function to add all values in {@code values} (if non-null) to {@code target}. */
1710     protected static void addAll (String[] values, List<String> target) {
1711         if (values != null) {
1712             for (String value : values) {
1713                 target.add(value);
1714             }
1715         }
1716     }
1717
1718     /**
1719      * Make an immutable List from the specified int array.
1720      */
1721     public static List<Integer> intsToList (int[] values)
1722     {
1723         List<Integer> list = new ArrayList<>(values.length);
1724         for (int val : values) {
1725             list.add(val);
1726         }
1727         return Collections.unmodifiableList(list);
1728     }
1729
1730     /**
1731      * Make an immutable List from the specified String array.
1732      */
1733     public static List<String> stringsToList (String[] values)
1734     {
1735         return values == null ? null : Collections.unmodifiableList(Arrays.asList(values));
1736     }
1737
1738     /** Used to parse resources with the specified name. */
1739     protected void parseResources (Config config, String name, EnumSet<Resource.Attr> attrs,
1740                                    List<Resource> list)
1741     {
1742         String[] rsrcs = config.getMultiValue(name);
1743         if (rsrcs == null) {
1744             return;
1745         }
1746         for (String rsrc : rsrcs) {
1747             try {
1748                 list.add(createResource(rsrc, attrs));
1749             } catch (Exception e) {
1750                 log.warning("Invalid resource '" + rsrc + "'. " + e);
1751             }
1752         }
1753     }
1754
1755     /** Possibly generates and returns a google analytics tracking cookie. */
1756     protected String getGATrackingCode ()
1757     {
1758         if (_trackingGAHash == null) {
1759             return "";
1760         }
1761         long time = System.currentTimeMillis() / 1000;
1762         if (_trackingStart == 0) {
1763             _trackingStart = time;
1764         }
1765         if (_trackingId == 0) {
1766             int low = 100000000, high = 1000000000;
1767             _trackingId = low + _rando.nextInt(high-low);
1768         }
1769         StringBuilder cookie = new StringBuilder("&utmcc=__utma%3D").append(_trackingGAHash);
1770         cookie.append(".").append(_trackingId);
1771         cookie.append(".").append(_trackingStart).append(".").append(_trackingStart);
1772         cookie.append(".").append(time).append(".1%3B%2B");
1773         cookie.append("__utmz%3D").append(_trackingGAHash).append(".");
1774         cookie.append(_trackingStart).append(".1.1.");
1775         cookie.append("utmcsr%3D(direct)%7Cutmccn%3D(direct)%7Cutmcmd%3D(none)%3B");
1776         int low = 1000000000, high = 2000000000;
1777         cookie.append("&utmn=").append(_rando.nextInt(high-low));
1778         return cookie.toString();
1779     }
1780
1781     /**
1782      * Encodes a path for use in a URL.
1783      */
1784     protected static String encodePath (String path)
1785     {
1786         try {
1787             // we want to keep slashes because we're encoding an entire path; also we need to turn
1788             // + into %20 because web servers don't like + in paths or file names, blah
1789             return URLEncoder.encode(path, "UTF-8").replace("%2F", "/").replace("+", "%20");
1790         } catch (UnsupportedEncodingException ue) {
1791             log.warning("Failed to URL encode " + path + ": " + ue);
1792             return path;
1793         }
1794     }
1795
1796     protected File getLocalPath (File appdir, String path)
1797     {
1798         return new File(appdir, path);
1799     }
1800
1801     public static void setStartupFilesFromParameterString(String p) {
1802       // multiple files *might* be passed in as space separated quoted filenames
1803       String q = "\"";
1804       if (!StringUtil.isBlank(p)) {
1805         String[] filenames;
1806         // split quoted params or treat as single string array
1807         if (p.startsWith(q) && p.endsWith(q)) {
1808           // this fails if, e.g.
1809           // p=q("stupidfilename\" " "otherfilename")
1810           // let's hope no-one ever ends a filename with '" '
1811           filenames = p.substring(q.length(),p.length()-q.length()).split(q+" "+q);
1812         } else {
1813           // single unquoted filename
1814           filenames = new String[]{p};
1815         }
1816
1817         // check for locator file.  Only allow one locator file to be double clicked (if multiple files opened, ignore locator files)
1818         String locatorFilename = filenames.length >= 1 ? filenames[0] : null;
1819         if (
1820                 !StringUtil.isBlank(locatorFilename)
1821                 && locatorFilename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)
1822                 ) {
1823           setLocatorFile(locatorFilename);
1824           // remove the locator filename from the filenames array
1825           String[] otherFilenames = new String[filenames.length - 1];
1826           System.arraycopy(filenames, 1, otherFilenames, 0, otherFilenames.length);
1827           filenames = otherFilenames;
1828         }
1829
1830         for (int i = 0; i < filenames.length; i++) {
1831           String filename = filenames[i];
1832           // skip any other locator files in a multiple file list
1833           if (! filename.toLowerCase().endsWith("."+Application.LOCATOR_FILE_EXTENSION)) {
1834             addStartupFile(filename);
1835           }
1836         }
1837       }
1838     }
1839     
1840     public static void setLocatorFile(String filename) {
1841       _locatorFile = new File(filename);
1842     }
1843     
1844     public static void addStartupFile(String filename) {
1845       _startupFiles.add(new File(filename));
1846     }
1847
1848     
1849     private Config createLocatorConfig(Config.ParseOpts opts) {
1850       if (_locatorFile == null) {
1851         return null;
1852       }
1853       
1854       Config locatorConfig = null;
1855       
1856       try {
1857         Config tmpConfig = null;
1858         if (_locatorFile.exists()) {
1859           tmpConfig = Config.parseConfig(_locatorFile,  opts);
1860         } else {
1861           log.warning("Given locator file does not exist", "file", _locatorFile);
1862         }
1863         
1864         // appbase is sanitised in HostWhitelist and here!
1865         Map<String, Object> tmpdata = new HashMap<>();
1866         tmpdata.put("appbase", tmpConfig.getString("appbase"));
1867         tmpdata.put("appargs", tmpConfig.getString("appargs"));
1868         tmpdata.put("jvmargs", tmpConfig.getString("jvmargs"));
1869         tmpdata.put(LOCATOR_FILE_EXTENSION+"replace", tmpConfig.getString(LOCATOR_FILE_EXTENSION+"replace"));
1870         tmpdata.put(LOCATOR_FILE_EXTENSION+"merge", tmpConfig.getString(LOCATOR_FILE_EXTENSION+"merge"));
1871         locatorConfig = new Config(tmpdata);
1872         
1873       } catch (Exception e) {
1874         log.warning("Failure reading locator file",  "file", _locatorFile, e);
1875       }
1876       
1877       return locatorConfig;
1878     }
1879     
1880     protected final EnvConfig _envc;
1881     protected File _config;
1882     protected Digest _digest;
1883
1884     protected long _version = -1;
1885     protected long _targetVersion = -1;
1886     protected String _appbase;
1887     protected URL _vappbase;
1888     protected URL _latest;
1889     protected String _class;
1890     protected String _dockName;
1891     protected String _dockIconPath;
1892     protected boolean _strictComments;
1893     protected boolean _windebug;
1894     protected boolean _allowOffline;
1895     protected int _maxConcDownloads;
1896
1897     protected String _trackingURL;
1898     protected Set<Integer> _trackingPcts;
1899     protected String _trackingCookieName;
1900     protected String _trackingCookieProperty;
1901     protected String _trackingURLSuffix;
1902     protected String _trackingGAHash;
1903     protected long _trackingStart;
1904     protected int _trackingId;
1905
1906     protected String _javaVersionProp = "java.version";
1907     protected String _javaVersionRegex = "(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(_\\d+)?)?)?";
1908     protected long _javaMinVersion, _javaMaxVersion;
1909     protected boolean _javaExactVersionRequired;
1910     protected String _javaLocation;
1911
1912     protected List<Resource> _codes = new ArrayList<>();
1913     protected List<Resource> _resources = new ArrayList<>();
1914
1915     protected boolean _useCodeCache;
1916     protected int _codeCacheRetentionDays;
1917
1918     protected Map<String,AuxGroup> _auxgroups = new HashMap<>();
1919     protected Map<String,Boolean> _auxactive = new HashMap<>();
1920
1921     protected List<String> _jvmargs = new ArrayList<>();
1922     protected List<String> _appargs = new ArrayList<>();
1923
1924     protected String[] _optimumJvmArgs;
1925
1926     protected List<String> _txtJvmArgs = new ArrayList<>();
1927
1928     /** If a warning has been issued about not being able to set modtimes. */
1929     protected boolean _warnedAboutSetLastModified;
1930
1931     /** Locks gettingdown.lock in the app dir. Held the entire time updating is going on.*/
1932     protected FileLock _lock;
1933
1934     /** Channel to the file underlying _lock.  Kept around solely so the lock doesn't close. */
1935     protected FileChannel _lockChannel;
1936
1937     protected Random _rando = new Random();
1938
1939     protected static final String[] EMPTY_STRING_ARRAY = new String[0];
1940
1941     protected static final String ENV_VAR_PREFIX = "%ENV.";
1942     protected static final Pattern ENV_VAR_PATTERN = Pattern.compile("%ENV\\.(.*?)%");
1943  
1944     protected static File _locatorFile;
1945     protected static List<File> _startupFiles = new ArrayList<>();
1946     public static final String LOCATOR_FILE_EXTENSION = "jvl";
1947 }