1 /*
   2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.jpackager.internal.builders.windows;
  27 
  28 import jdk.jpackager.internal.BundlerParamInfo;
  29 import jdk.jpackager.internal.Log;
  30 import jdk.jpackager.internal.RelativeFileSet;
  31 import jdk.jpackager.internal.IOUtils;
  32 import jdk.jpackager.internal.StandardBundlerParam;
  33 import jdk.jpackager.internal.resources.windows.WinResources;
  34 import jdk.jpackager.internal.windows.WindowsBundlerParam;
  35 import jdk.jpackager.internal.builders.AbstractAppImageBuilder;
  36 import jdk.jpackager.internal.windows.WindowsDefender;
  37 
  38 import java.io.File;
  39 import java.io.FileOutputStream;
  40 import java.io.FileInputStream;
  41 import java.io.IOException;
  42 import java.io.InputStream;
  43 import java.io.OutputStream;
  44 import java.io.OutputStreamWriter;
  45 import java.io.UncheckedIOException;
  46 import java.io.Writer;
  47 import java.io.BufferedWriter;
  48 import java.io.FileWriter;
  49 import java.nio.file.Files;
  50 import java.nio.file.Path;
  51 import java.nio.file.attribute.PosixFilePermission;
  52 import java.text.MessageFormat;
  53 import java.util.HashMap;
  54 import java.util.List;
  55 import java.util.Map;
  56 import java.util.Objects;
  57 import java.util.ResourceBundle;
  58 import java.util.Set;
  59 import java.util.concurrent.atomic.AtomicReference;
  60 import java.util.regex.Pattern;
  61 import java.util.stream.Stream;
  62 import jdk.jpackager.internal.Arguments;
  63 
  64 import static jdk.jpackager.internal.StandardBundlerParam.*;
  65 
  66 public class WindowsAppImageBuilder extends AbstractAppImageBuilder {
  67 
  68     private static final ResourceBundle I18N =
  69             ResourceBundle.getBundle(
  70             "jdk.jpackager.internal.resources.builders.windows.WindowsAppImageBuilder");
  71 
  72     private static final String MODULES_FILENAME =
  73             "jdk/jpackager/internal/resources/windows/windows.jre.list";
  74 
  75     protected static final String WINDOWS_BUNDLER_PREFIX =
  76             BUNDLER_PREFIX + "windows" + File.separator;
  77 
  78     private final static String EXECUTABLE_NAME = "WinLauncher.exe";
  79     private final static String LIBRARY_NAME = "jpackager.dll";
  80     private final static String REDIST_MSVCR = "vcruntimeVS_VER.dll";
  81     private final static String REDIST_MSVCP = "msvcpVS_VER.dll";
  82 
  83     private final static String TEMPLATE_APP_ICON ="javalogo_white_48.ico";
  84 
  85     private static final String EXECUTABLE_PROPERTIES_TEMPLATE =
  86             "WinLauncher.properties";
  87 
  88     private final Path root;
  89     private final Path appDir;
  90     private final Path runtimeDir;
  91     private final Path mdir;
  92 
  93     private final Map<String, ? super Object> params;
  94 
  95     public static final BundlerParamInfo<File> CONFIG_ROOT =
  96             new WindowsBundlerParam<>(
  97             I18N.getString("param.config-root.name"),
  98             I18N.getString("param.config-root.description"),
  99             "configRoot",
 100             File.class,
 101             params -> {
 102                 File imagesRoot =
 103                         new File(BUILD_ROOT.fetchFrom(params), "windows");
 104                 imagesRoot.mkdirs();
 105                 return imagesRoot;
 106             },
 107             (s, p) -> null);
 108 
 109     public static final BundlerParamInfo<Boolean> REBRAND_EXECUTABLE =
 110             new WindowsBundlerParam<>(
 111             I18N.getString("param.rebrand-executable.name"),
 112             I18N.getString("param.rebrand-executable.description"),
 113             "win.launcher.rebrand",
 114             Boolean.class,
 115             params -> Boolean.TRUE,
 116             (s, p) -> Boolean.valueOf(s));
 117 
 118     public static final BundlerParamInfo<File> ICON_ICO =
 119             new StandardBundlerParam<>(
 120             I18N.getString("param.icon-ico.name"),
 121             I18N.getString("param.icon-ico.description"),
 122             "icon.ico",
 123             File.class,
 124             params -> {
 125                 File f = ICON.fetchFrom(params);
 126                 if (f != null && !f.getName().toLowerCase().endsWith(".ico")) {
 127                     Log.error(MessageFormat.format(
 128                             I18N.getString("message.icon-not-ico"), f));
 129                     return null;
 130                 }
 131                 return f;
 132             },
 133             (s, p) -> new File(s));
 134 
 135     public static final StandardBundlerParam<Boolean> CONSOLE_HINT =
 136             new WindowsBundlerParam<>(
 137             I18N.getString("param.console-hint.name"),
 138             I18N.getString("param.console-hint.description"),
 139             Arguments.CLIOptions.WIN_CONSOLE_HINT.getId(),
 140             Boolean.class,
 141             params -> false,
 142             // valueOf(null) is false,
 143             // and we actually do want null in some cases
 144             (s, p) -> (s == null
 145             || "null".equalsIgnoreCase(s)) ? true : Boolean.valueOf(s));
 146 
 147     public WindowsAppImageBuilder(Map<String, Object> config, Path imageOutDir)
 148             throws IOException {
 149         super(config,
 150                 imageOutDir.resolve(APP_NAME.fetchFrom(config) + "/runtime"));
 151 
 152         Objects.requireNonNull(imageOutDir);
 153 
 154         this.params = config;
 155 
 156         this.root = imageOutDir.resolve(APP_NAME.fetchFrom(params));
 157         this.appDir = root.resolve("app");
 158         this.runtimeDir = root.resolve("runtime");
 159         this.mdir = runtimeDir.resolve("lib");
 160         Files.createDirectories(appDir);
 161         Files.createDirectories(runtimeDir);
 162     }
 163 
 164     public WindowsAppImageBuilder(String jreName, Path imageOutDir)
 165             throws IOException {
 166         super(null, imageOutDir.resolve(jreName));
 167 
 168         Objects.requireNonNull(imageOutDir);
 169 
 170         this.params = null;
 171         this.root = imageOutDir.resolve(jreName);
 172         this.appDir = null;
 173         this.runtimeDir = root;
 174         this.mdir = runtimeDir.resolve("lib");
 175         Files.createDirectories(runtimeDir);
 176     }
 177 
 178     private Path destFile(String dir, String filename) {
 179         return runtimeDir.resolve(dir).resolve(filename);
 180     }
 181 
 182     private void writeEntry(InputStream in, Path dstFile) throws IOException {
 183         Files.createDirectories(dstFile.getParent());
 184         Files.copy(in, dstFile);
 185     }
 186 
 187     private void writeSymEntry(Path dstFile, Path target) throws IOException {
 188         Files.createDirectories(dstFile.getParent());
 189         Files.createLink(dstFile, target);
 190     }
 191 
 192     /**
 193      * chmod ugo+x file
 194      */
 195     private void setExecutable(Path file) {
 196         try {
 197             Set<PosixFilePermission> perms =
 198                 Files.getPosixFilePermissions(file);
 199             perms.add(PosixFilePermission.OWNER_EXECUTE);
 200             perms.add(PosixFilePermission.GROUP_EXECUTE);
 201             perms.add(PosixFilePermission.OTHERS_EXECUTE);
 202             Files.setPosixFilePermissions(file, perms);
 203         } catch (IOException ioe) {
 204             throw new UncheckedIOException(ioe);
 205         }
 206     }
 207 
 208     private static void createUtf8File(File file, String content)
 209             throws IOException {
 210         try (OutputStream fout = new FileOutputStream(file);
 211              Writer output = new OutputStreamWriter(fout, "UTF-8")) {
 212             output.write(content);
 213         }
 214     }
 215 
 216     public static String getLauncherName(Map<String, ? super Object> p) {
 217         return APP_FS_NAME.fetchFrom(p) + ".exe";
 218     }
 219 
 220     // Returns launcher resource name for launcher we need to use.
 221     public static String getLauncherResourceName(Map<String, ? super Object> p) {
 222         if (CONSOLE_HINT.fetchFrom(p)) {
 223             return "papplauncherc.exe";
 224         }
 225 
 226         return "papplauncher.exe";
 227     }
 228 
 229     public static String getLauncherCfgName(Map<String, ? super Object> p) {
 230         return "app/" + APP_FS_NAME.fetchFrom(p) +".cfg";
 231     }
 232 
 233     private File getConfig_AppIcon(Map<String, ? super Object> params) {
 234         return new File(getConfigRoot(params),
 235                 APP_FS_NAME.fetchFrom(params) + ".ico");
 236     }
 237 
 238     private File getConfig_ExecutableProperties(
 239            Map<String, ? super Object> params) {
 240         return new File(getConfigRoot(params),
 241                 APP_FS_NAME.fetchFrom(params) + ".properties");
 242     }
 243 
 244     File getConfigRoot(Map<String, ? super Object> params) {
 245         return CONFIG_ROOT.fetchFrom(params);
 246     }
 247 
 248     protected void cleanupConfigFiles(Map<String, ? super Object> params) {
 249         getConfig_AppIcon(params).delete();
 250         getConfig_ExecutableProperties(params).delete();
 251     }
 252 
 253     @Override
 254     public InputStream getResourceAsStream(String name) {
 255         return WinResources.class.getResourceAsStream(name);
 256     }
 257 
 258     @Override
 259     public void prepareApplicationFiles() throws IOException {
 260         Map<String, ? super Object> originalParams = new HashMap<>(params);
 261         File rootFile = root.toFile();
 262         if (!rootFile.isDirectory() && !rootFile.mkdirs()) {
 263             throw new RuntimeException(MessageFormat.format(I18N.getString(
 264                 "error.cannot-create-output-dir"), rootFile.getAbsolutePath()));
 265         }
 266         if (!rootFile.canWrite()) {
 267             throw new RuntimeException(MessageFormat.format(
 268                     I18N.getString("error.cannot-write-to-output-dir"),
 269                     rootFile.getAbsolutePath()));
 270         }
 271         try {
 272             // create the .exe launchers
 273             createLauncherForEntryPoint(params);
 274 
 275             // copy the jars
 276             copyApplication(params);
 277 
 278             // copy in the needed libraries
 279             try (InputStream is_lib = getResourceAsStream("jpackager.dll")) {
 280                 Files.copy(is_lib, root.resolve(LIBRARY_NAME));
 281             }
 282 
 283             copyMSVCDLLs();
 284 
 285             // create the secondary launchers, if any
 286             List<Map<String, ? super Object>> entryPoints =
 287                     StandardBundlerParam.SECONDARY_LAUNCHERS.fetchFrom(params);
 288             for (Map<String, ? super Object> entryPoint : entryPoints) {
 289                 Map<String, ? super Object> tmp = new HashMap<>(originalParams);
 290                 tmp.putAll(entryPoint);
 291                 createLauncherForEntryPoint(tmp);
 292             }
 293 
 294         } catch (IOException ex) {
 295             Log.error("Exception: "+ex);
 296             Log.verbose(ex);
 297         } finally {
 298             cleanupConfigFiles(params);
 299         }
 300     }
 301 
 302     @Override
 303     public void prepareServerJreFiles() throws IOException {}
 304 
 305     private void copyMSVCDLLs() throws IOException {
 306         AtomicReference<IOException> ioe = new AtomicReference<>();
 307         try (Stream<Path> files = Files.list(runtimeDir.resolve("bin"))) {
 308             files.filter(p -> Pattern.matches(
 309                     "^(vcruntime|msvcp|msvcr|ucrtbase|api-ms-win-).*\\.dll$",
 310                     p.toFile().getName().toLowerCase()))
 311                  .forEach(p -> {
 312                     try {
 313                         Files.copy(p, root.resolve((p.toFile().getName())));
 314                     } catch (IOException e) {
 315                         ioe.set(e);
 316                     }
 317                 });
 318         }
 319 
 320         IOException e = ioe.get();
 321         if (e != null) {
 322             throw e;
 323         }
 324     }
 325 
 326     // TODO: do we still need this?
 327     private boolean copyMSVCDLLs(String VS_VER) throws IOException {
 328         final InputStream REDIST_MSVCR_URL =
 329                 WinResources.class.getResourceAsStream(
 330                 REDIST_MSVCR.replaceAll("VS_VER", VS_VER));
 331         final InputStream REDIST_MSVCP_URL =
 332                 WinResources.class.getResourceAsStream(
 333                 REDIST_MSVCP.replaceAll("VS_VER", VS_VER));
 334 
 335         if (REDIST_MSVCR_URL != null && REDIST_MSVCP_URL != null) {
 336             Files.copy(
 337                     REDIST_MSVCR_URL,
 338                     root.resolve(REDIST_MSVCR.replaceAll("VS_VER", VS_VER)));
 339             Files.copy(
 340                     REDIST_MSVCP_URL,
 341                     root.resolve(REDIST_MSVCP.replaceAll("VS_VER", VS_VER)));
 342             return true;
 343         }
 344 
 345         return false;
 346     }
 347 
 348     private void validateValueAndPut(
 349             Map<String, String> data, String key,
 350             BundlerParamInfo<String> param,
 351             Map<String, ? super Object> params) {
 352         String value = param.fetchFrom(params);
 353         if (value.contains("\r") || value.contains("\n")) {
 354             Log.error("Configuration Parameter " + param.getID()
 355                     + " contains multiple lines of text, ignore it");
 356             data.put(key, "");
 357             return;
 358         }
 359         data.put(key, value);
 360     }
 361 
 362     protected void prepareExecutableProperties(
 363            Map<String, ? super Object> params) throws IOException {
 364         Map<String, String> data = new HashMap<>();
 365 
 366         // mapping Java parameters in strings for version resource
 367         data.put("COMMENTS", "");
 368         validateValueAndPut(data, "COMPANY_NAME", VENDOR, params);
 369         validateValueAndPut(data, "FILE_DESCRIPTION", DESCRIPTION, params);
 370         validateValueAndPut(data, "FILE_VERSION", VERSION, params);
 371         data.put("INTERNAL_NAME", getLauncherName(params));
 372         validateValueAndPut(data, "LEGAL_COPYRIGHT", COPYRIGHT, params);
 373         data.put("LEGAL_TRADEMARK", "");
 374         data.put("ORIGINAL_FILENAME", getLauncherName(params));
 375         data.put("PRIVATE_BUILD", "");
 376         validateValueAndPut(data, "PRODUCT_NAME", APP_NAME, params);
 377         validateValueAndPut(data, "PRODUCT_VERSION", VERSION, params);
 378         data.put("SPECIAL_BUILD", "");
 379 
 380         Writer w = new BufferedWriter(
 381                 new FileWriter(getConfig_ExecutableProperties(params)));
 382         String content = preprocessTextResource(WINDOWS_BUNDLER_PREFIX
 383                 + getConfig_ExecutableProperties(params).getName(),
 384                 I18N.getString("resource.executable-properties-template"),
 385                 EXECUTABLE_PROPERTIES_TEMPLATE, data,
 386                 VERBOSE.fetchFrom(params),
 387                 DROP_IN_RESOURCES_ROOT.fetchFrom(params));
 388         w.write(content);
 389         w.close();
 390     }
 391 
 392     private void createLauncherForEntryPoint(
 393             Map<String, ? super Object> p) throws IOException {
 394 
 395         File launcherIcon = ICON_ICO.fetchFrom(p);
 396         File icon = launcherIcon != null ?
 397                 launcherIcon : ICON_ICO.fetchFrom(params);
 398         File iconTarget = getConfig_AppIcon(p);
 399 
 400         InputStream in = locateResource(
 401                "package/windows/" + APP_NAME.fetchFrom(params) + ".ico",
 402                 "icon",
 403                 TEMPLATE_APP_ICON,
 404                 icon,
 405                 VERBOSE.fetchFrom(params),
 406                 DROP_IN_RESOURCES_ROOT.fetchFrom(params));
 407         Files.copy(in, iconTarget.toPath());
 408 
 409         writeCfgFile(p, root.resolve(
 410                 getLauncherCfgName(p)).toFile(), "$APPDIR\\runtime");
 411 
 412         prepareExecutableProperties(p);
 413 
 414         // Copy executable root folder
 415         Path executableFile = root.resolve(getLauncherName(p));
 416         try (InputStream is_launcher =
 417                 getResourceAsStream(getLauncherResourceName(p))) {
 418             writeEntry(is_launcher, executableFile);
 419         }
 420 
 421         File launcher = executableFile.toFile();
 422         launcher.setWritable(true, true);
 423 
 424         // Update branding of EXE file
 425         if (REBRAND_EXECUTABLE.fetchFrom(p)) {
 426             File tool = new File(
 427                 System.getProperty("java.home") + "\\bin\\jpackager.exe");
 428 
 429             // Run tool on launcher file to change the icon and the metadata.
 430             try {
 431                 if (WindowsDefender.isThereAPotentialWindowsDefenderIssue()) {
 432                     Log.error(MessageFormat.format(I18N.getString(
 433                             "message.potential.windows.defender.issue"),
 434                             WindowsDefender.getUserTempDirectory()));
 435                 }
 436 
 437                 launcher.setWritable(true);
 438 
 439                 if (iconTarget.exists()) {
 440                     ProcessBuilder pb = new ProcessBuilder(
 441                             tool.getAbsolutePath(),
 442                             "--icon-swap",
 443                             iconTarget.getAbsolutePath(),
 444                             launcher.getAbsolutePath());
 445                     IOUtils.exec(pb, false);
 446                 }
 447 
 448                 File executableProperties = getConfig_ExecutableProperties(p);
 449 
 450                 if (executableProperties.exists()) {
 451                     ProcessBuilder pb = new ProcessBuilder(
 452                             tool.getAbsolutePath(),
 453                             "--version-swap",
 454                             executableProperties.getAbsolutePath(),
 455                             launcher.getAbsolutePath());
 456                     IOUtils.exec(pb, false);
 457                 }
 458             }
 459             finally {
 460                 executableFile.toFile().setReadOnly();
 461             }
 462         }
 463 
 464         Files.copy(iconTarget.toPath(),
 465                 root.resolve(APP_NAME.fetchFrom(p) + ".ico"));
 466     }
 467 
 468     private void copyApplication(Map<String, ? super Object> params)
 469             throws IOException {
 470         List<RelativeFileSet> appResourcesList =
 471                 APP_RESOURCES_LIST.fetchFrom(params);
 472         if (appResourcesList == null) {
 473             throw new RuntimeException("Null app resources?");
 474         }
 475         for (RelativeFileSet appResources : appResourcesList) {
 476             if (appResources == null) {
 477                 throw new RuntimeException("Null app resources?");
 478             }
 479             File srcdir = appResources.getBaseDirectory();
 480             for (String fname : appResources.getIncludedFiles()) {
 481                 copyEntry(appDir, srcdir, fname);
 482             }
 483         }
 484     }
 485 
 486     @Override
 487     public String getPlatformSpecificModulesFile() {
 488         return MODULES_FILENAME;
 489     }
 490 
 491 }