|
18 | 18 | */ |
19 | 19 | package co.elastic.apm.agent.common.util; |
20 | 20 |
|
21 | | -import java.io.File; |
22 | | -import java.io.FileInputStream; |
23 | | -import java.io.FileOutputStream; |
24 | 21 | import java.io.IOException; |
25 | 22 | import java.io.InputStream; |
26 | 23 | import java.math.BigInteger; |
| 24 | +import java.nio.channels.Channels; |
27 | 25 | import java.nio.channels.FileChannel; |
28 | 26 | import java.nio.channels.FileLock; |
| 27 | +import java.nio.file.FileAlreadyExistsException; |
| 28 | +import java.nio.file.Files; |
| 29 | +import java.nio.file.Path; |
| 30 | +import java.nio.file.Paths; |
| 31 | +import java.nio.file.attribute.FileAttribute; |
| 32 | +import java.nio.file.attribute.PosixFilePermissions; |
| 33 | +import java.nio.file.attribute.UserPrincipal; |
29 | 34 | import java.security.DigestInputStream; |
30 | 35 | import java.security.MessageDigest; |
31 | 36 | import java.security.NoSuchAlgorithmException; |
| 37 | +import java.util.EnumSet; |
| 38 | + |
| 39 | +import static java.nio.file.LinkOption.NOFOLLOW_LINKS; |
| 40 | +import static java.nio.file.StandardOpenOption.CREATE_NEW; |
| 41 | +import static java.nio.file.StandardOpenOption.READ; |
| 42 | +import static java.nio.file.StandardOpenOption.WRITE; |
| 43 | +import static java.nio.file.attribute.PosixFilePermission.OWNER_READ; |
| 44 | +import static java.nio.file.attribute.PosixFilePermission.OWNER_WRITE; |
32 | 45 |
|
33 | 46 | public class ResourceExtractionUtil { |
34 | 47 |
|
35 | 48 | /** |
36 | 49 | * Extracts a classpath resource to {@code ${System.getProperty("java.io.tmpdir")}/$prefix-$hash.$suffix}. |
37 | 50 | * If the file has already been extracted it will not be extracted again. |
38 | 51 | * |
39 | | - * @param resource The classpath resource to extract. |
40 | | - * @param prefix The prefix of the extracted file. |
41 | | - * @param suffix The suffix of the extracted file. |
| 52 | + * @param resource The classpath resource to extract. |
| 53 | + * @param prefix The prefix of the extracted file. |
| 54 | + * @param suffix The suffix of the extracted file. |
42 | 55 | * @return the extracted file. |
43 | 56 | */ |
44 | | - public static synchronized File extractResourceToTempDirectory(String resource, String prefix, String suffix) { |
45 | | - return extractResourceToDirectory(resource, prefix, suffix, System.getProperty("java.io.tmpdir")); |
| 57 | + public static synchronized Path extractResourceToTempDirectory(String resource, String prefix, String suffix) { |
| 58 | + return extractResourceToDirectory(resource, prefix, suffix, Paths.get(System.getProperty("java.io.tmpdir"))); |
46 | 59 | } |
47 | 60 |
|
48 | 61 | /** |
49 | 62 | * Extracts a classpath resource to {@code $directory/$prefix-$userHash-$hash.$suffix}. |
50 | 63 | * If the file has already been extracted it will not be extracted again. |
51 | 64 | * |
52 | | - * @param resource The classpath resource to extract. |
53 | | - * @param prefix The prefix of the extracted file. |
54 | | - * @param suffix The suffix of the extracted file. |
55 | | - * @param directory The directory in which the file is to be created, or null if the default temporary-file directory is to be used. |
| 65 | + * @param resource The classpath resource to extract. |
| 66 | + * @param prefix The prefix of the extracted file. |
| 67 | + * @param suffix The suffix of the extracted file. |
| 68 | + * @param directory The directory in which the file is to be created, or null if the default temporary-file directory is to be used. |
56 | 69 | * @return the extracted file. |
57 | 70 | */ |
58 | 71 | /* |
59 | 72 | * Why it's synchronized : if the same JVM try to lock file, we got an java.nio.channels.OverlappingFileLockException. |
60 | 73 | * So we need to block until the file is totally written. |
61 | 74 | */ |
62 | | - public static synchronized File extractResourceToDirectory(String resource, String prefix, String suffix, String directory) { |
| 75 | + public static synchronized Path extractResourceToDirectory(String resource, String prefix, String suffix, Path directory) { |
63 | 76 | try (InputStream resourceStream = ResourceExtractionUtil.class.getResourceAsStream("/" + resource)) { |
64 | 77 | if (resourceStream == null) { |
65 | 78 | throw new IllegalStateException(resource + " not found"); |
66 | 79 | } |
67 | | - String userHash = ""; |
68 | | - if (System.getProperties().contains("user.name")) { |
69 | | - // we have to include current user name as multiple copies of the same agent could be attached |
70 | | - // to multiple JVMs, each running under a different user. Also, we have to make it path-friendly. |
71 | | - userHash = md5Hash(System.getProperty("user.name")); |
72 | | - userHash += "-"; |
73 | | - } |
74 | | - String resourceHash = md5Hash(ResourceExtractionUtil.class.getResourceAsStream("/" + resource)); |
| 80 | + UserPrincipal currentUserPrincipal = getCurrentUserPrincipal(); |
| 81 | + // we have to include current user name as multiple copies of the same agent could be attached |
| 82 | + // to multiple JVMs, each running under a different user. Hashing makes the name path-friendly. |
| 83 | + String userHash = hash(currentUserPrincipal.getName()); |
| 84 | + // to guard against re-using previous versions |
| 85 | + String resourceHash = hash(ResourceExtractionUtil.class.getResourceAsStream("/" + resource)); |
75 | 86 |
|
76 | | - File tempFile = new File(directory, prefix + "-" + userHash + resourceHash + suffix); |
77 | | - if (!tempFile.exists()) { |
78 | | - try (FileOutputStream out = new FileOutputStream(tempFile)) { |
79 | | - FileChannel channel = out.getChannel(); |
80 | | - // If multiple JVM start on same compute, they can write in same file |
81 | | - // and this file will be corrupted. |
82 | | - try (FileLock ignored = channel.lock()) { |
83 | | - if (tempFile.length() == 0) { |
84 | | - byte[] buffer = new byte[1024]; |
85 | | - for (int length; (length = resourceStream.read(buffer)) != -1; ) { |
86 | | - out.write(buffer, 0, length); |
87 | | - } |
| 87 | + Path tempFile = directory.resolve(prefix + "-" + userHash.substring(0, 32) + "-" + resourceHash.substring(0, 32) + suffix); |
| 88 | + try { |
| 89 | + FileAttribute<?>[] attr; |
| 90 | + if (tempFile.getFileSystem().supportedFileAttributeViews().contains("posix")) { |
| 91 | + attr = new FileAttribute[]{PosixFilePermissions.asFileAttribute(EnumSet.of(OWNER_WRITE, OWNER_READ))}; |
| 92 | + } else { |
| 93 | + attr = new FileAttribute[0]; |
| 94 | + } |
| 95 | + try (FileChannel channel = FileChannel.open(tempFile, EnumSet.of(CREATE_NEW, WRITE), attr)) { |
| 96 | + // make other JVM instances wait until fully written |
| 97 | + try (FileLock writeLock = channel.lock()) { |
| 98 | + channel.transferFrom(Channels.newChannel(resourceStream), 0, Long.MAX_VALUE); |
| 99 | + } |
| 100 | + } |
| 101 | + } catch (FileAlreadyExistsException e) { |
| 102 | + try (FileChannel channel = FileChannel.open(tempFile, READ, NOFOLLOW_LINKS)) { |
| 103 | + // wait until other JVM instances have fully written the file |
| 104 | + // multiple JVMs can read the file at the same time |
| 105 | + try (FileLock readLock = channel.lock(0, Long.MAX_VALUE, true)) { |
| 106 | + if (!hash(Files.newInputStream(tempFile)).equals(resourceHash)) { |
| 107 | + throw new IllegalStateException("Invalid checksum of " + tempFile + ". Please delete this file."); |
| 108 | + } else if (!Files.getOwner(tempFile).equals(currentUserPrincipal)) { |
| 109 | + throw new IllegalStateException("File " + tempFile + " is not owned by '" + currentUserPrincipal.getName() + "'. Please delete this file."); |
88 | 110 | } |
89 | 111 | } |
90 | 112 | } |
91 | | - } else if (!md5Hash(new FileInputStream(tempFile)).equals(resourceHash)) { |
92 | | - throw new IllegalStateException("Invalid MD5 checksum of " + tempFile + ". Please delete this file."); |
93 | 113 | } |
94 | | - return tempFile; |
| 114 | + return tempFile.toAbsolutePath(); |
95 | 115 | } catch (NoSuchAlgorithmException | IOException e) { |
96 | 116 | throw new IllegalStateException(e); |
97 | 117 | } |
98 | 118 | } |
99 | 119 |
|
100 | | - private static String md5Hash(InputStream resourceAsStream) throws IOException, NoSuchAlgorithmException { |
| 120 | + private static UserPrincipal getCurrentUserPrincipal() throws IOException { |
| 121 | + Path whoami = Files.createTempFile("whoami", ".tmp"); |
| 122 | + try { |
| 123 | + return Files.getOwner(whoami); |
| 124 | + } finally { |
| 125 | + Files.delete(whoami); |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + private static String hash(InputStream resourceAsStream) throws IOException, NoSuchAlgorithmException { |
101 | 130 | try (InputStream is = resourceAsStream) { |
102 | | - MessageDigest md = MessageDigest.getInstance("MD5"); |
| 131 | + MessageDigest md = MessageDigest.getInstance("SHA-256"); |
103 | 132 | byte[] buffer = new byte[1024]; |
104 | 133 | DigestInputStream dis = new DigestInputStream(is, md); |
105 | 134 | while (dis.read(buffer) != -1) {} |
106 | | - return String.format("%032x", new BigInteger(1, md.digest())); |
| 135 | + return new BigInteger(1, md.digest()).toString(16); |
107 | 136 | } |
108 | 137 | } |
109 | 138 |
|
110 | | - private static String md5Hash(String s) throws NoSuchAlgorithmException { |
111 | | - MessageDigest md = MessageDigest.getInstance("MD5"); |
| 139 | + private static String hash(String s) throws NoSuchAlgorithmException { |
| 140 | + MessageDigest md = MessageDigest.getInstance("SHA-256"); |
112 | 141 | md.update(s.getBytes()); |
113 | | - return String.format("%032x", new BigInteger(1, md.digest())); |
| 142 | + return new BigInteger(1, md.digest()).toString(16); |
114 | 143 | } |
115 | 144 | } |
0 commit comments