git: 836f1da80eb3 - stable/14 - pkg: refactor out a pkg_read_fd()

From: Kyle Evans <kevans_at_FreeBSD.org>
Date: Sat, 11 Jan 2025 02:48:57 UTC
The branch stable/14 has been updated by kevans:

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

commit 836f1da80eb3d3c502d42a18411ba2e083e65e26
Author:     Kyle Evans <kevans@FreeBSD.org>
AuthorDate: 2025-01-01 21:10:28 +0000
Commit:     Kyle Evans <kevans@FreeBSD.org>
CommitDate: 2025-01-11 02:48:25 +0000

    pkg: refactor out a pkg_read_fd()
    
    We already have to do this for reading the pubkey, just pull it out for
    other uses.  The ECC signer will use this to verify the bootstrap if
    the PUBKEY mechanism is used.
    
    Reviewed by:    bapt, emaste
    
    (cherry picked from commit 2ecfc040a09f8c42f67bbfdcc4bd02ef84dac8b7)
---
 usr.sbin/pkg/pkg.c | 40 +++++++++++++++++++++++++++-------------
 usr.sbin/pkg/pkg.h |  2 ++
 2 files changed, 29 insertions(+), 13 deletions(-)

diff --git a/usr.sbin/pkg/pkg.c b/usr.sbin/pkg/pkg.c
index 4cadff155516..9b7938c97211 100644
--- a/usr.sbin/pkg/pkg.c
+++ b/usr.sbin/pkg/pkg.c
@@ -386,32 +386,46 @@ load_fingerprints(const char *path, int *count)
 	return (fingerprints);
 }
 
+char *
+pkg_read_fd(int fd, size_t *osz)
+{
+	char *obuf;
+	char buf[4096];
+	FILE *fp;
+	ssize_t r;
+
+	obuf = NULL;
+	*osz = 0;
+	fp = open_memstream(&obuf, osz);
+	if (fp == NULL)
+		err(EXIT_FAILURE, "open_memstream()");
+
+	while ((r = read(fd, buf, sizeof(buf))) >0) {
+		fwrite(buf, 1, r, fp);
+	}
+
+	if (ferror(fp))
+		errx(EXIT_FAILURE, "reading file");
+
+	fclose(fp);
+
+	return (obuf);
+}
+
 static struct pubkey *
 read_pubkey(int fd)
 {
 	struct pubkey *pk;
 	char *sigb;
 	size_t sigsz;
-	FILE *sig;
-	char buf[4096];
-	int r;
 
 	if (lseek(fd, 0, 0) == -1) {
 		warn("lseek");
 		return (NULL);
 	}
 
-	sigsz = 0;
-	sigb = NULL;
-	sig = open_memstream(&sigb, &sigsz);
-	if (sig == NULL)
-		err(EXIT_FAILURE, "open_memstream()");
-
-	while ((r = read(fd, buf, sizeof(buf))) >0) {
-		fwrite(buf, 1, r, sig);
-	}
+	sigb = pkg_read_fd(fd, &sigsz);
 
-	fclose(sig);
 	pk = calloc(1, sizeof(struct pubkey));
 	pk->siglen = sigsz;
 	pk->sig = calloc(1, pk->siglen);
diff --git a/usr.sbin/pkg/pkg.h b/usr.sbin/pkg/pkg.h
index 01f69f5a825b..faa2be6c8376 100644
--- a/usr.sbin/pkg/pkg.h
+++ b/usr.sbin/pkg/pkg.h
@@ -47,4 +47,6 @@ struct pubkey {
 bool rsa_verify_cert(int, const char *, const unsigned char *, int,
     unsigned char *, int);
 
+char *pkg_read_fd(int fd, size_t *osz);
+
 #endif /* _PKG_H */