From 9bea60d43abaa6f325df4a428cd4a164711ae857 Mon Sep 17 00:00:00 2001 From: hyung-hwan Date: Mon, 5 Dec 2022 16:04:11 +0000 Subject: [PATCH] untar - improved EOF marker handling --- bin/untar.c | 4 ++-- lib/hio-tar.h | 3 ++- lib/tar.c | 20 +++++++++++++------- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/bin/untar.c b/bin/untar.c index 5b184cf..e907ab5 100644 --- a/bin/untar.c +++ b/bin/untar.c @@ -34,7 +34,7 @@ int main (int argc, char* argv[]) if (!fp) { fprintf (stderr, "Error: unable to open file %s\n", argv[1]); - hio_tar_close (hio); + hio_tar_close (untar); hio_close (hio); return -1; } @@ -43,7 +43,7 @@ int main (int argc, char* argv[]) while (!feof(fp) && !ferror(fp)) { int n; - char buf[99]; /* TODO: use a different buffer size???*/ + char buf[512]; /* TODO: use a different buffer size???*/ n = fread(buf, 1, sizeof(buf), fp); if (n > 0) { diff --git a/lib/hio-tar.h b/lib/hio-tar.h index 60fbae8..0791548 100644 --- a/lib/hio-tar.h +++ b/lib/hio-tar.h @@ -75,7 +75,8 @@ enum hio_tar_state_t { HIO_TAR_STATE_START, HIO_TAR_STATE_FILE, - HIO_TAR_STATE_END + HIO_TAR_STATE_END_1, + HIO_TAR_STATE_END_2 }; typedef enum hio_tar_state_t hio_tar_state_t; diff --git a/lib/tar.c b/lib/tar.c index 3cb0c54..dc04de4 100644 --- a/lib/tar.c +++ b/lib/tar.c @@ -245,9 +245,8 @@ printf("process_header...\n"); /* all-zero byte block ends the archive */ if (HIO_MEMCMP(hdr, _end_block, HIO_TAR_BLKSIZE) == 0) { -/* TODO: is it correct? */ -printf ("end of input\n"); - tar->state = HIO_TAR_STATE_END; + /* two all-zero blocks are expected as the EOF indicator */ + tar->state = HIO_TAR_STATE_END_1; } else { @@ -362,11 +361,10 @@ static int process_content (hio_tar_t* tar) int hio_tar_feed (hio_tar_t* tar, const void* ptr, hio_oow_t len) { -printf ("feed len = %d\n", len); if (!ptr) { /* EOF indicator */ - if (tar->state != HIO_TAR_STATE_END || tar->blk.len > 0) + if ((tar->state != HIO_TAR_STATE_END_1 && tar->state != HIO_TAR_STATE_END_2) || tar->blk.len > 0) { /* ERROR - premature end of file */ hio_seterrbfmt (tar->hio, HIO_EINVAL, "premature end of feed"); @@ -393,17 +391,25 @@ printf ("feed len = %d\n", len); { case HIO_TAR_STATE_START: if (process_header(tar) <= -1) return -1; - if (tar->state == HIO_TAR_STATE_END) printf ("remaining data len %d\n", len); break; case HIO_TAR_STATE_FILE: if (process_content(tar) <= -1) return -1; break; - case HIO_TAR_STATE_END: + case HIO_TAR_STATE_END_1: + if (HIO_MEMCMP(tar->blk.buf, _end_block, HIO_TAR_BLKSIZE) == 0) + { + tar->state = HIO_TAR_STATE_END_2; + break; + } + /* fall thru here for the trailing garbage error */ + + case HIO_TAR_STATE_END_2: /* garbage after the final ending block */ hio_seterrbfmt (tar->hio, HIO_EINVAL, "trailing garbage at the end of feed"); return -1; + break; } tar->blk.len = 0;