1 /*
   2  * Copyright (c) 2015, 2016, 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 package jdk.packager.builders.windows;
  26 
  27 
  28 import com.oracle.tools.packager.BundlerParamInfo;
  29 import com.oracle.tools.packager.Log;
  30 import com.oracle.tools.packager.RelativeFileSet;
  31 import com.oracle.tools.packager.IOUtils;
  32 import com.oracle.tools.packager.StandardBundlerParam;
  33 import com.oracle.tools.packager.windows.WinResources;
  34 import com.oracle.tools.packager.windows.WindowsBundlerParam;
  35 import jdk.packager.builders.AbstractAppImageBuilder;
  36 
  37 import java.io.File;
  38 import java.io.FileOutputStream;
  39 import java.io.IOException;
  40 import java.io.InputStream;
  41 import java.io.OutputStream;
  42 import java.io.OutputStreamWriter;
  43 import java.io.UncheckedIOException;
  44 import java.io.Writer;
  45 import java.io.BufferedWriter;
  46 import java.io.FileWriter;
  47 import java.nio.file.Files;
  48 import java.nio.file.Path;
  49 import java.nio.file.attribute.PosixFilePermission;
  50 import java.text.MessageFormat;
  51 import java.util.HashMap;
  52 import java.util.List;
  53 import java.util.Map;
  54 import java.util.Objects;
  55 import java.util.ResourceBundle;
  56 import java.util.Set;
  57 import java.util.concurrent.atomic.AtomicReference;
  58 import java.util.regex.Pattern;
  59 
  60 import static com.oracle.tools.packager.StandardBundlerParam.*;
  61 
  62 /**
  63  *
  64  */
  65 public class WindowsAppImageBuilder extends AbstractAppImageBuilder {
  66 
  67     private static final ResourceBundle I18N =
  68             ResourceBundle.getBundle(WindowsAppImageBuilder.class.getName());
  69 
  70     protected static final String WINDOWS_BUNDLER_PREFIX =
  71             BUNDLER_PREFIX + "windows" + File.separator;
  72 
  73     private final static String EXECUTABLE_NAME = "WinLauncher.exe";
  74     private final static String LIBRARY_NAME = "packager.dll";
  75 
  76     private final static String[] VS_VERS = {"100", "110", "120"};
  77     private final static String REDIST_MSVCR = "msvcrVS_VER.dll";
  78     private final static String REDIST_MSVCP = "msvcpVS_VER.dll";
  79 
  80     private final static String TEMPLATE_APP_ICON ="javalogo_white_48.ico";
  81     private static final String TOOL_ICON_SWAP="IconSwap.exe";
  82     private static final String TOOL_VERSION_INFO_SWAP="VersionInfoSwap.exe";
  83 
  84     private static final String EXECUTABLE_PROPERTIES_TEMPLATE = "WinLauncher.properties";
  85 
  86     private final Path root;
  87     private final Path appDir;
  88     private final Path runtimeDir;
  89     private final Path mdir;
  90 
  91     private final Map<String, ? super Object> params;
  92 
  93     public static final BundlerParamInfo<File> CONFIG_ROOT = new WindowsBundlerParam<>(
  94             I18N.getString("param.config-root.name"),
  95             I18N.getString("param.config-root.description"),
  96             "configRoot",
  97             File.class,
  98             params -> {
  99                 File imagesRoot = new File(BUILD_ROOT.fetchFrom(params), "windows");
 100                 imagesRoot.mkdirs();
 101                 return imagesRoot;
 102             },
 103             (s, p) -> null);
 104 
 105     public static final BundlerParamInfo<Boolean> REBRAND_EXECUTABLE = new WindowsBundlerParam<>(
 106             I18N.getString("param.rebrand-executable.name"),
 107             I18N.getString("param.rebrand-executable.description"),
 108             "win.launcher.rebrand",
 109             Boolean.class,
 110             params -> Boolean.TRUE,
 111             (s, p) -> Boolean.valueOf(s));
 112 
 113     public static final BundlerParamInfo<File> ICON_ICO = new StandardBundlerParam<>(
 114             I18N.getString("param.icon-ico.name"),
 115             I18N.getString("param.icon-ico.description"),
 116             "icon.ico",
 117             File.class,
 118             params -> {
 119                 File f = ICON.fetchFrom(params);
 120                 if (f != null && !f.getName().toLowerCase().endsWith(".ico")) {
 121                     Log.info(MessageFormat.format(I18N.getString("message.icon-not-ico"), f));
 122                     return null;
 123                 }
 124                 return f;
 125             },
 126             (s, p) -> new File(s));
 127 
 128 
 129 
 130     public WindowsAppImageBuilder(Map<String, Object> config, Path imageOutDir) throws IOException {
 131         super(config, imageOutDir.resolve(APP_NAME.fetchFrom(config) + "/runtime"));
 132 
 133         Objects.requireNonNull(imageOutDir);
 134 
 135         //@SuppressWarnings("unchecked")
 136         //String img = (String) config.get("jimage.name"); // FIXME constant
 137 
 138         this.params = config;
 139 
 140         this.root = imageOutDir.resolve(APP_NAME.fetchFrom(params));
 141         this.appDir = root.resolve("app");
 142         this.runtimeDir = root.resolve("runtime");
 143         this.mdir = runtimeDir.resolve("lib");
 144         Files.createDirectories(appDir);
 145         Files.createDirectories(runtimeDir);
 146     }
 147 
 148     private Path destFile(String dir, String filename) {
 149         return runtimeDir.resolve(dir).resolve(filename);
 150     }
 151 
 152     private void writeEntry(InputStream in, Path dstFile) throws IOException {
 153         Files.createDirectories(dstFile.getParent());
 154         Files.copy(in, dstFile);
 155     }
 156 
 157     private void writeSymEntry(Path dstFile, Path target) throws IOException {
 158         Files.createDirectories(dstFile.getParent());
 159         Files.createLink(dstFile, target);
 160     }
 161 
 162     /**
 163      * chmod ugo+x file
 164      */
 165     private void setExecutable(Path file) {
 166         try {
 167             Set<PosixFilePermission> perms = Files.getPosixFilePermissions(file);
 168             perms.add(PosixFilePermission.OWNER_EXECUTE);
 169             perms.add(PosixFilePermission.GROUP_EXECUTE);
 170             perms.add(PosixFilePermission.OTHERS_EXECUTE);
 171             Files.setPosixFilePermissions(file, perms);
 172         } catch (IOException ioe) {
 173             throw new UncheckedIOException(ioe);
 174         }
 175     }
 176 
 177     private static void createUtf8File(File file, String content) throws IOException {
 178         try (OutputStream fout = new FileOutputStream(file);
 179              Writer output = new OutputStreamWriter(fout, "UTF-8")) {
 180             output.write(content);
 181         }
 182     }
 183 
 184 
 185 
 186     //it is static for the sake of sharing with "installer" bundlers
 187     // that may skip calls to validate/bundle in this class!
 188     public static File getRootDir(File outDir, Map<String, ? super Object> p) {
 189         return new File(outDir, APP_FS_NAME.fetchFrom(p));
 190     }
 191 
 192     public static String getLauncherName(Map<String, ? super Object> p) {
 193         return APP_FS_NAME.fetchFrom(p) + ".exe";
 194     }
 195 
 196     public static String getLauncherCfgName(Map<String, ? super Object> p) {
 197         return "app/" + APP_FS_NAME.fetchFrom(p) +".cfg";
 198     }
 199 
 200     private File getConfig_AppIcon(Map<String, ? super Object> params) {
 201         return new File(getConfigRoot(params), APP_FS_NAME.fetchFrom(params) + ".ico");
 202     }
 203 
 204     private File getConfig_ExecutableProperties(Map<String, ? super Object> params) {
 205         return new File(getConfigRoot(params), APP_FS_NAME.fetchFrom(params) + ".properties");
 206     }
 207 
 208     File getConfigRoot(Map<String, ? super Object> params) {
 209         return CONFIG_ROOT.fetchFrom(params);
 210     }
 211 
 212     protected void cleanupConfigFiles(Map<String, ? super Object> params) {
 213         getConfig_AppIcon(params).delete();
 214         getConfig_ExecutableProperties(params).delete();
 215     }
 216 
 217     @Override
 218     public InputStream getResourceAsStream(String name) {
 219         return WinResources.class.getResourceAsStream(name);
 220     }
 221 
 222     @Override
 223     public void prepareApplicationFiles() throws IOException {
 224         Map<String, ? super Object> originalParams = new HashMap<>(params);
 225         File rootFile = root.toFile();
 226         if (!rootFile.isDirectory() && !rootFile.mkdirs()) {
 227             throw new RuntimeException(MessageFormat.format(I18N.getString("error.cannot-create-output-dir"), rootFile.getAbsolutePath()));
 228         }
 229         if (!rootFile.canWrite()) {
 230             throw new RuntimeException(MessageFormat.format(I18N.getString("error.cannot-write-to-output-dir"), rootFile.getAbsolutePath()));
 231         }
 232         try {
 233 //            if (!dependentTask) {
 234 //                Log.info(MessageFormat.format(I18N.getString("message.creating-app-bundle"), APP_NAME.fetchFrom(p), outputDirectory.getAbsolutePath()));
 235 //            }
 236 
 237             // Create directory structure
 238 //            IOUtils.deleteRecursive(rootDirectory);
 239 //            rootDirectory.mkdirs();
 240 
 241 
 242             // create the .exe launchers
 243             createLauncherForEntryPoint(params);
 244 
 245             // copy the jars
 246             copyApplication(params);
 247 
 248             // copy in the needed libraries
 249             Files.copy(WinResources.class.getResourceAsStream(LIBRARY_NAME),
 250                     root.resolve(LIBRARY_NAME));
 251 
 252             copyMSVCDLLs();
 253 
 254             // create the secondary launchers, if any
 255             List<Map<String, ? super Object>> entryPoints = StandardBundlerParam.SECONDARY_LAUNCHERS.fetchFrom(params);
 256             for (Map<String, ? super Object> entryPoint : entryPoints) {
 257                 Map<String, ? super Object> tmp = new HashMap<>(originalParams);
 258                 tmp.putAll(entryPoint);
 259                 createLauncherForEntryPoint(tmp);
 260             }
 261 
 262         } catch (IOException ex) {
 263             Log.info("Exception: "+ex);
 264             Log.debug(ex);
 265         } finally {
 266 
 267             if (VERBOSE.fetchFrom(params)) {
 268                 Log.info(MessageFormat.format(I18N.getString("message.config-save-location"), getConfigRoot(params).getAbsolutePath()));
 269             } else {
 270                 cleanupConfigFiles(params);
 271             }
 272         }
 273 
 274     }
 275 
 276     private void copyMSVCDLLs() throws IOException {
 277         String vsVer = null;
 278 
 279         // first copy the ones needed for the launcher
 280         for (String thisVer : VS_VERS) {
 281             if (copyMSVCDLLs(thisVer)) {
 282                 vsVer = thisVer;
 283                 break;
 284             }
 285         }
 286         if (vsVer == null) {
 287             throw new RuntimeException("Not found MSVC dlls");
 288         }
 289 
 290         AtomicReference<IOException> ioe = new AtomicReference<>();
 291         final String finalVsVer = vsVer;
 292         Files.list(runtimeDir.resolve("bin"))
 293                 .filter(p -> Pattern.matches("msvc(r|p)\\d\\d\\d.dll", p.toFile().getName().toLowerCase()))
 294                 .filter(p -> !p.toString().toLowerCase().endsWith(finalVsVer + ".dll"))
 295                 .forEach(p -> {
 296                     try {
 297                         Files.copy(p, root.resolve((p.toFile().getName())));
 298                     } catch (IOException e) {
 299                         ioe.set(e);
 300                     }
 301                 });
 302 
 303         IOException e = ioe.get();
 304         if (e != null) {
 305             throw e;
 306         }
 307     }
 308 
 309     private boolean copyMSVCDLLs(String VS_VER) throws IOException {
 310         final InputStream REDIST_MSVCR_URL = WinResources.class.getResourceAsStream(
 311                 REDIST_MSVCR.replaceAll("VS_VER", VS_VER));
 312         final InputStream REDIST_MSVCP_URL = WinResources.class.getResourceAsStream(
 313                 REDIST_MSVCP.replaceAll("VS_VER", VS_VER));
 314 
 315         if (REDIST_MSVCR_URL != null && REDIST_MSVCP_URL != null) {
 316             Files.copy(
 317                     REDIST_MSVCR_URL,
 318                     root.resolve(REDIST_MSVCR.replaceAll("VS_VER", VS_VER)));
 319             Files.copy(
 320                     REDIST_MSVCP_URL,
 321                     root.resolve(REDIST_MSVCP.replaceAll("VS_VER", VS_VER)));
 322             return true;
 323         }
 324 
 325         return false; // not found
 326     }
 327 
 328     private void validateValueAndPut(Map<String, String> data, String key,
 329                                      BundlerParamInfo<String> param, Map<String, ? super Object> params)
 330     {
 331         String value = param.fetchFrom(params);
 332         if (value.contains("\r") || value.contains("\n")) {
 333             Log.info("Configuration Parameter " + param.getID() + " contains multiple lines of text, ignore it");
 334             data.put(key, "");
 335             return;
 336         }
 337         data.put(key, value);
 338     }
 339 
 340     protected void prepareExecutableProperties(Map<String, ? super Object> params)
 341             throws IOException
 342     {
 343         Map<String, String> data = new HashMap<>();
 344 
 345         // mapping Java parameters in strings for version resource
 346         data.put("COMMENTS", "");
 347         validateValueAndPut(data, "COMPANY_NAME", VENDOR, params);
 348         validateValueAndPut(data, "FILE_DESCRIPTION", DESCRIPTION, params);
 349         validateValueAndPut(data, "FILE_VERSION", VERSION, params);
 350         data.put("INTERNAL_NAME", getLauncherName(params));
 351         validateValueAndPut(data, "LEGAL_COPYRIGHT", COPYRIGHT, params);
 352         data.put("LEGAL_TRADEMARK", "");
 353         data.put("ORIGINAL_FILENAME", getLauncherName(params));
 354         data.put("PRIVATE_BUILD", "");
 355         validateValueAndPut(data, "PRODUCT_NAME", APP_NAME, params);
 356         validateValueAndPut(data, "PRODUCT_VERSION", VERSION, params);
 357         data.put("SPECIAL_BUILD", "");
 358 
 359         Writer w = new BufferedWriter(new FileWriter(getConfig_ExecutableProperties(params)));
 360         String content = preprocessTextResource(
 361                 WINDOWS_BUNDLER_PREFIX + getConfig_ExecutableProperties(params).getName(),
 362                 I18N.getString("resource.executable-properties-template"), EXECUTABLE_PROPERTIES_TEMPLATE, data,
 363                 VERBOSE.fetchFrom(params),
 364                 DROP_IN_RESOURCES_ROOT.fetchFrom(params));
 365         w.write(content);
 366         w.close();
 367     }
 368 
 369     private void createLauncherForEntryPoint(Map<String, ? super Object> p) throws IOException {
 370 
 371         File icon = ICON_ICO.fetchFrom(params);
 372         File iconTarget = getConfig_AppIcon(params);
 373 
 374         InputStream in = locateResource("package/windows/" + APP_NAME.fetchFrom(params) + ".ico",
 375                 "icon",
 376                 TEMPLATE_APP_ICON,
 377                 icon,
 378                 VERBOSE.fetchFrom(params),
 379                 DROP_IN_RESOURCES_ROOT.fetchFrom(params));
 380         Files.copy(in, iconTarget.toPath());
 381 
 382         writeCfgFile(p, root.resolve(getLauncherCfgName(p)).toFile(), "$APPDIR\\runtime");
 383 
 384         prepareExecutableProperties(p);
 385 
 386         // Copy executable root folder
 387         Path executableFile = root.resolve(getLauncherName(p));
 388         writeEntry(WinResources.class.getResourceAsStream(EXECUTABLE_NAME), executableFile);
 389         executableFile.toFile().setWritable(true, true);
 390 
 391         //Update branding of exe file
 392         if (REBRAND_EXECUTABLE.fetchFrom(p) && iconTarget.exists()) {
 393             //extract IconSwap helper tool
 394             File iconSwapTool = File.createTempFile("iconswap", ".exe");
 395             IOUtils.copyFromURL(
 396                     WinResources.class.getResource(TOOL_ICON_SWAP),
 397                     iconSwapTool,
 398                     true);
 399             iconSwapTool.setExecutable(true, false);
 400             iconSwapTool.deleteOnExit();
 401 
 402             //run it on launcher file
 403             executableFile.toFile().setWritable(true);
 404             ProcessBuilder pb = new ProcessBuilder(
 405                     iconSwapTool.getAbsolutePath(),
 406                     getConfig_AppIcon(p).getAbsolutePath(),
 407                     executableFile.toFile().getAbsolutePath());
 408             IOUtils.exec(pb, VERBOSE.fetchFrom(p));
 409             executableFile.toFile().setReadOnly();
 410             iconSwapTool.delete();
 411         }
 412 
 413         Files.copy(iconTarget.toPath(), root.resolve(APP_NAME.fetchFrom(p) + ".ico"));
 414 
 415         if (REBRAND_EXECUTABLE.fetchFrom(p) && getConfig_ExecutableProperties(p).exists()) {
 416             // extract VersionInfoHelper tool
 417             File versionInfoTool = File.createTempFile("versioninfoswap", ".exe");
 418             IOUtils.copyFromURL(
 419                     WinResources.class.getResource(TOOL_VERSION_INFO_SWAP),
 420                     versionInfoTool,
 421                     true);
 422             versionInfoTool.setExecutable(true, false);
 423             versionInfoTool.deleteOnExit();
 424 
 425             // run it on launcher file
 426             executableFile.toFile().setWritable(true);
 427             ProcessBuilder pb = new ProcessBuilder(
 428                     versionInfoTool.getAbsolutePath(),
 429                     getConfig_ExecutableProperties(p).getAbsolutePath(),
 430                     executableFile.toFile().getAbsolutePath());
 431             IOUtils.exec(pb, VERBOSE.fetchFrom(p));
 432             executableFile.toFile().setReadOnly();
 433             versionInfoTool.delete();
 434         }
 435     }
 436 
 437     private void copyApplication(Map<String, ? super Object> params) throws IOException {
 438         List<RelativeFileSet> appResourcesList = APP_RESOURCES_LIST.fetchFrom(params);
 439         if (appResourcesList == null) {
 440             throw new RuntimeException("Null app resources?");
 441         }
 442         for (RelativeFileSet appResources : appResourcesList) {
 443             if (appResources == null) {
 444                 throw new RuntimeException("Null app resources?");
 445             }
 446             File srcdir = appResources.getBaseDirectory();
 447             for (String fname : appResources.getIncludedFiles()) {
 448                 Files.copy(new File(srcdir, fname).toPath(), new File(appDir.toFile(), fname).toPath());
 449             }
 450         }
 451     }
 452 
 453     @Override
 454     protected String getCacheLocation(Map<String, ? super Object> params) {
 455         return "$CACHEDIR/";
 456     }
 457 
 458 }