Fix ZipCentralDirectoryFileHeaderRecord entry comment read offset

Update `ZipCentralDirectoryFileHeaderRecord.copyTo` comment read offset
to account for the record position.

Fixes gh-39166
This commit is contained in:
Phillip Webb 2024-01-17 13:14:09 -08:00
parent fee359ff5e
commit eb0040c225
2 changed files with 45 additions and 2 deletions

View File

@ -97,8 +97,8 @@ record ZipCentralDirectoryFileHeaderRecord(short versionMadeBy, short versionNee
dataBlock.readFully(buffer, extraPos);
zipEntry.setExtra(buffer.array());
}
if ((fileCommentLength() & 0xFFFF) > 0) {
long commentPos = MINIMUM_SIZE + fileNameLength + extraLength;
if (commentLength > 0) {
long commentPos = pos + MINIMUM_SIZE + fileNameLength + extraLength;
zipEntry.setComment(ZipString.readString(dataBlock, commentPos, commentLength));
}
}

View File

@ -23,10 +23,15 @@ import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.Cleaner.Cleanable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.assertj.core.extractor.Extractors;
@ -386,4 +391,42 @@ class NestedJarFileTests {
}
}
@Test // gh-39166
void getCommentAlignsWithJdkJar() throws Exception {
File file = new File(this.tempDir, "testcomments.jar");
try (JarOutputStream jar = new JarOutputStream(new FileOutputStream(file))) {
jar.putNextEntry(new ZipEntry("BOOT-INF/"));
jar.closeEntry();
jar.putNextEntry(new ZipEntry("BOOT-INF/classes/"));
jar.closeEntry();
for (int i = 0; i < 5; i++) {
ZipEntry entry = new ZipEntry("BOOT-INF/classes/T" + i + ".class");
entry.setComment("T" + i);
jar.putNextEntry(entry);
jar.write(UUID.randomUUID().toString().getBytes());
jar.closeEntry();
}
}
List<String> jdk = collectComments(new JarFile(file));
List<String> nested = collectComments(new NestedJarFile(file, "BOOT-INF/classes/"));
assertThat(nested).isEqualTo(jdk);
}
private List<String> collectComments(JarFile jarFile) throws IOException {
try {
List<String> comments = new ArrayList<>();
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
String comment = entries.nextElement().getComment();
if (comment != null) {
comments.add(comment);
}
}
return comments;
}
finally {
jarFile.close();
}
}
}