From e87ff77171376dca31941cacac97db7458fedc93 Mon Sep 17 00:00:00 2001 From: Patrick McDermott Date: Sat, 6 Apr 2019 12:40:05 -0400 Subject: [PATCH 5/6] libopkg: Detect gzipped pkg lists by magic number Signed-off-by: Patrick McDermott --- 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 #include +#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