[OpenWrt-Devel] [PATCH][opkg-lede] libopkg: Detect gzipped pkg lists by magic number

Patrick McDermott patrick.mcdermott at libiquity.com
Wed Apr 17 13:56:11 EDT 2019


Signed-off-by: Patrick McDermott <patrick.mcdermott at libiquity.com>
---
 libbb/gzip.h       |  2 ++
 libopkg/pkg_hash.c | 27 ++++++++++++++++++++-------
 2 files changed, 22 insertions(+), 7 deletions(-)

diff --git a/libbb/gzip.h b/libbb/gzip.h
index 3a61a1d..28e3a50 100644
--- a/libbb/gzip.h
+++ b/libbb/gzip.h
@@ -22,6 +22,8 @@
 #include <signal.h>
 #include <pthread.h>
 
+#define GZIP_MAGIC "\037\213" /* gzip magic number, 1F 8B */
+
 struct gzip_handle {
 	FILE *file;
 	struct gzip_handle *gzip;
diff --git a/libopkg/pkg_hash.c b/libopkg/pkg_hash.c
index 611f3b9..b536db7 100644
--- a/libopkg/pkg_hash.c
+++ b/libopkg/pkg_hash.c
@@ -99,21 +99,34 @@ pkg_hash_add_from_file(const char *file_name,
 {
 	pkg_t *pkg;
 	FILE *fp;
+	char magic[2];
+	int is_gzip = 0;
 	char *buf;
 	const size_t len = 4096;
 	int ret = 0;
 	struct gzip_handle zh;
 
-	if (src && src->gzip) {
-		fp = gzip_fdopen(&zh, file_name);
-	} else {
-		fp = fopen(file_name, "r");
-	}
-
+	fp = fopen(file_name, "r");
 	if (fp == NULL) {
 		opkg_perror(ERROR, "Failed to open %s", file_name);
 		return -1;
 	}
+	if (fread(magic, 1, 2, fp) != 2) {
+		opkg_perror(ERROR, "Failed to read %s", file_name);
+		fclose(fp);
+		return -1;
+	}
+	(void)fseek(fp, 0L, SEEK_SET);
+
+	if (src && src->gzip && memcmp(magic, GZIP_MAGIC, 2) == 0) {
+		fclose(fp);
+		fp = gzip_fdopen(&zh, file_name);
+		if (fp == NULL) {
+			opkg_perror(ERROR, "Failed to open %s", file_name);
+			return -1;
+		}
+		is_gzip = 1;
+	}
 
 	buf = xmalloc(len);
 
@@ -165,7 +178,7 @@ pkg_hash_add_from_file(const char *file_name,
 	free(buf);
 	fclose(fp);
 
-	if (src && src->gzip)
+	if (is_gzip)
 		gzip_close(&zh);
 
 	return ret;
-- 
2.11.0


_______________________________________________
openwrt-devel mailing list
openwrt-devel at lists.openwrt.org
https://lists.openwrt.org/mailman/listinfo/openwrt-devel



More information about the openwrt-devel mailing list