git: c7f1512739c7 - stable/14 - MFC: mkimg(1): process non-seekable output gracefully

From: Eugene Grosbein <eugen_at_FreeBSD.org>
Date: Tue, 19 Mar 2024 06:51:57 UTC
The branch stable/14 has been updated by eugen:

URL: https://cgit.FreeBSD.org/src/commit/?id=c7f1512739c729cd82042cf229a3ab7c56920b70

commit c7f1512739c729cd82042cf229a3ab7c56920b70
Author:     Eugene Grosbein <eugen@FreeBSD.org>
AuthorDate: 2024-03-12 15:55:42 +0000
Commit:     Eugene Grosbein <eugen@FreeBSD.org>
CommitDate: 2024-03-19 06:51:13 +0000

    MFC: mkimg(1): process non-seekable output gracefully
    
    mkimg may make severe load only to fail in the end
    if output is non-seekable pipe, socket or FIFO
    unless output format is raw disk image.
    
    Check it out and fail early. Make it clear in the manual.
    
    (cherry picked from commit 7f0dc6e2cdfa0317c9917dd46e9da9d3897a8fbb)
---
 usr.bin/mkimg/mkimg.1 |  3 ++-
 usr.bin/mkimg/mkimg.c | 14 +++++++++++++-
 2 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/usr.bin/mkimg/mkimg.1 b/usr.bin/mkimg/mkimg.1
index 28ed0ca03ccf..333b8b8a5ecb 100644
--- a/usr.bin/mkimg/mkimg.1
+++ b/usr.bin/mkimg/mkimg.1
@@ -22,7 +22,7 @@
 .\" (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 .\" THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 .\"
-.Dd February 28, 2024
+.Dd March 12, 2024
 .Dt MKIMG 1
 .Os
 .Sh NAME
@@ -64,6 +64,7 @@ The image file is a raw disk image by default, but the format of the
 image file can be specified with the
 .Ar format
 argument.
+Most formats require seekable output, except of raw disk image.
 .Pp
 The disk image can be made bootable by specifying the scheme-specific boot
 block contents with the
diff --git a/usr.bin/mkimg/mkimg.c b/usr.bin/mkimg/mkimg.c
index bcf500cd675f..f3bb9cb05708 100644
--- a/usr.bin/mkimg/mkimg.c
+++ b/usr.bin/mkimg/mkimg.c
@@ -556,6 +556,7 @@ mkimg(void)
 int
 main(int argc, char *argv[])
 {
+	const char *format_name;
 	int bcfd, outfd;
 	int c, error;
 
@@ -700,6 +701,7 @@ main(int argc, char *argv[])
 			errc(EX_DATAERR, error, "boot code");
 	}
 
+	format_name = format_selected()->name;
 	if (verbose) {
 		fprintf(stderr, "Logical sector size: %u\n", secsz);
 		fprintf(stderr, "Physical block size: %u\n", blksz);
@@ -710,10 +712,20 @@ main(int argc, char *argv[])
 			fprintf(stderr, "Partitioning scheme: %s\n",
 			    scheme_selected()->name);
 		fprintf(stderr, "Output file format:  %s\n",
-		    format_selected()->name);
+		    format_name);
 		fputc('\n', stderr);
 	}
 
+#if defined(SPARSE_WRITE)
+	/*
+	 * sparse_write() fails if output is not seekable so fail early
+	 * not wasting some load unless output format is raw
+	 */
+	if (strcmp("raw", format_name) &&
+	    lseek(outfd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE)
+		errx(EX_USAGE, "%s: output must be seekable", format_name);
+#endif
+
 	error = image_init();
 	if (error)
 		errc(EX_OSERR, error, "cannot initialize");