From 33a964ec6703eeed0ed90c0556f742faa7d11418 Mon Sep 17 00:00:00 2001 From: rillig Date: Sun, 22 May 2022 21:39:44 +0000 Subject: [PATCH] uncompress: if the source is broken, don't delete the target Fixes the second half of PR bin/19722, reported by Giorgos Keramidas. --- tests/usr.bin/compress/t_pr_19722.sh | 9 ++++++--- usr.bin/compress/compress.c | 21 +++++++++++++++------ 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/tests/usr.bin/compress/t_pr_19722.sh b/tests/usr.bin/compress/t_pr_19722.sh index b94f05909e40..bd3fabf3a6ef 100644 --- a/tests/usr.bin/compress/t_pr_19722.sh +++ b/tests/usr.bin/compress/t_pr_19722.sh @@ -1,4 +1,4 @@ -# $NetBSD: t_pr_19722.sh,v 1.3 2022/05/22 21:16:50 rillig Exp $ +# $NetBSD: t_pr_19722.sh,v 1.4 2022/05/22 21:39:44 rillig Exp $ # # Copyright (c) 2022 The NetBSD Foundation, Inc. # All rights reserved. @@ -148,6 +148,10 @@ atf_test_case 'uncompress_broken_source_existing_target' uncompress_broken_source_existing_target_body() { # PR 19722: uncompressing a broken source removes existing target + # + # Before compress.c 1.29 from 2022-05-22, uncompress removed an + # existing target before checking that the source has the correct + # format. echo 'broken' > file.Z echo 'before' > file @@ -158,8 +162,7 @@ uncompress_broken_source_existing_target_body() uncompress -f file.Z atf_check -o 'inline:broken\n' cat file.Z - # FIXME: Must not be modified. - atf_check test ! -f file + atf_check -o 'inline:before\n' cat file } diff --git a/usr.bin/compress/compress.c b/usr.bin/compress/compress.c index 5a983579ac10..e772f8ac2e01 100644 --- a/usr.bin/compress/compress.c +++ b/usr.bin/compress/compress.c @@ -1,4 +1,4 @@ -/* $NetBSD: compress.c,v 1.28 2022/05/22 21:16:50 rillig Exp $ */ +/* $NetBSD: compress.c,v 1.29 2022/05/22 21:39:44 rillig Exp $ */ /*- * Copyright (c) 1992, 1993 @@ -39,7 +39,7 @@ __COPYRIGHT("@(#) Copyright (c) 1992, 1993\ #if 0 static char sccsid[] = "@(#)compress.c 8.2 (Berkeley) 1/7/94"; #else -__RCSID("$NetBSD: compress.c,v 1.28 2022/05/22 21:16:50 rillig Exp $"); +__RCSID("$NetBSD: compress.c,v 1.29 2022/05/22 21:39:44 rillig Exp $"); #endif #endif /* not lint */ @@ -318,10 +318,6 @@ decompress(const char *in, const char *out, int bits) cwarn("%s", in); goto err; } - if ((ofp = fopen(out, "w")) == NULL) { - cwarn("%s", out); - goto err; - } if (!isstdin) { if (stat(in, &sb)) { cwarn("%s", in); @@ -333,6 +329,19 @@ decompress(const char *in, const char *out, int bits) isreg = 1; } else isreg = 0; + if ((nr = fread(buf, 1, sizeof(buf), ifp)) == 0) { + cwarn("%s", in); + goto err; + } + + if ((ofp = fopen(out, "w")) == NULL) { + cwarn("%s", out); + goto err; + } + if (fwrite(buf, 1, nr, ofp) != nr) { + cwarn("%s", out); + goto err; + } oreg <<= 1; while ((nr = fread(buf, 1, sizeof(buf), ifp)) != 0)