minitar/src/tar.c

69 lines
1.8 KiB
C
Raw Normal View History

2022-11-05 19:10:48 +00:00
#include "tar.h"
2022-11-06 10:02:26 +00:00
#include "minitar.h"
#include <stdlib.h>
2022-11-05 19:10:48 +00:00
int minitar_read_header(struct minitar* mp, struct tar_header* hdr);
int minitar_validate_header(struct tar_header* hdr);
void minitar_parse_tar_header(struct tar_header* hdr, struct minitar_entry_metadata* metadata);
struct minitar_entry* minitar_dup_entry(struct minitar_entry* original);
char* minitar_read_file(struct minitar_entry_metadata* metadata, struct minitar* mp);
2022-11-05 17:52:51 +00:00
struct minitar* minitar_open(const char* path)
{
FILE* fp = fopen(path, "rb"); // On some systems, this might be necessary to read the file properly.
2022-11-06 10:02:26 +00:00
if (!fp) return NULL;
2022-11-05 17:52:51 +00:00
struct minitar* mp = malloc(sizeof(struct minitar));
2022-11-06 10:02:26 +00:00
if (!mp)
{
fclose(fp);
return NULL;
}
2022-11-05 17:52:51 +00:00
mp->stream = fp;
return mp;
}
int minitar_close(struct minitar* mp)
{
int rc = fclose(mp->stream);
free(mp);
2022-11-06 10:02:26 +00:00
if (rc) return rc;
2022-11-05 17:52:51 +00:00
return 0;
2022-11-05 19:10:48 +00:00
}
static struct minitar_entry* minitar_attempt_read_entry(struct minitar* mp, int* valid)
{
struct minitar_entry entry;
struct tar_header hdr;
2022-11-06 10:02:26 +00:00
if (!minitar_read_header(mp, &hdr))
2022-11-05 19:10:48 +00:00
{
*valid = 1; // we are at end-of-file
return NULL;
}
2022-11-06 10:02:26 +00:00
if (!minitar_validate_header(&hdr))
2022-11-05 19:10:48 +00:00
{
*valid = 0;
return NULL;
}
*valid = 1;
minitar_parse_tar_header(&hdr, &entry.metadata);
char* buf = minitar_read_file(&entry.metadata, mp);
2022-11-06 10:02:26 +00:00
if (!buf) return NULL;
entry.ptr = buf;
2022-11-05 19:10:48 +00:00
return minitar_dup_entry(&entry);
}
struct minitar_entry* minitar_read_entry(struct minitar* mp)
{
int valid;
struct minitar_entry* result;
do {
result = minitar_attempt_read_entry(mp, &valid);
2022-11-06 10:02:26 +00:00
} while (!valid);
2022-11-05 19:10:48 +00:00
return result;
}
void minitar_free_entry(struct minitar_entry* entry)
{
free(entry->ptr);
free(entry);
2022-11-05 17:52:51 +00:00
}