实现说明
逻辑集中在类 UploadGatekeeper里。
本示例的循环部分是 for (int read; (read = zip.read(buffer)) != -1; )。try-with-resources 保证即使方法体抛出,声明的资源也会被关闭。守卫条件成立时抛出 IOException,而不是返回一个假值。
使用要点
- 直接运行文件,输出会带上标签,比如
declared size =、guard fired:——输出的每一行都能指回产生它的那次调用。
常见问题
坏输入有失败路径吗?
守卫处(入口)会抛出 IOException,非法状态到不了主逻辑。
运行「ZIP 条目流式预算防护」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 declared size =、guard fired: 标签标明各步骤。
核心语句
throw new IOException("entry crossed the " + MAX_ENTRY_BUDGET + " byte budget");
throw new IOException("declared size " + declared + " breaks the budget");
return out.toString(StandardCharsets.UTF_8);
代码示例
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class UploadGatekeeper {
static final long MAX_ENTRY_BUDGET = 64 * 1024;
// 流式预算:边读边记账,条目一旦超限立即中止
static String readEntry(ZipInputStream zip, ZipEntry entry) throws IOException {
long declared = entry.getSize();
if (declared >= 0 && declared > MAX_ENTRY_BUDGET) {
throw new IOException("declared size " + declared + " breaks the budget");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
long total = 0;
for (int read; (read = zip.read(buffer)) != -1; ) {
total += read;
if (total > MAX_ENTRY_BUDGET) {
throw new IOException("entry crossed the " + MAX_ENTRY_BUDGET + " byte budget");
}
out.write(buffer, 0, read);
}
return out.toString(StandardCharsets.UTF_8);
}
public static void main(String[] args) throws IOException {
ByteArrayOutputStream archive = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(archive)) {
zip.putNextEntry(new ZipEntry("payload.txt"));
zip.write(new byte[1_000_000]); // 全 0 明文,DEFLATED 后只有约 1KB
zip.closeEntry();
}
try (ZipInputStream unzip =
new ZipInputStream(new ByteArrayInputStream(archive.toByteArray()))) {
ZipEntry entry = unzip.getNextEntry();
System.out.println("declared size = " + entry.getSize()); // 流式读取时通常未知
try {
readEntry(unzip, entry);
} catch (IOException overBudget) {
System.out.println("guard fired: " + overBudget.getMessage());
}
}
}
}