问题
Let me explain what I'm trying to realize:
I have a encrypted tar file. I can decrypt it in memory, but obviously I can't write the decrypted data back to hard disk as a real file. The decrypted data is structured as a char* buffer in memory; how can I untar it in memory?
I can't find answer with libtar library.
I also tried to untar it with execlp("tar", "tar", "-xvO", (void*)0)
.
But it didn't work as I thought.
Anyone can give me a hint of the best solution? Thanks!
回答1:
I made an example, how to read file contents from an in-memory tar. The is_file_in_tar()
function returns the length
and the start
ing position of the name
d file if it is stored in the tar
:
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
struct tar {
char name[100]; char _unused[24];
char size[12]; char _padding[376];
} *tar;
int is_file_in_tar( struct tar *tar, char *name, char **start, int *length ){
for( ; tar->name[0]; tar+=1+(*length+511)/512 ){
sscanf( tar->size, "%o", length);
if( !strcmp(tar->name,name) ){ *start = (char*)(tar+1); return 1; }
}
return 0;
}
int main(){
int fd=open( "libtar-1.2.11.tar", O_RDONLY );
tar=mmap(NULL, 808960, PROT_READ, MAP_PRIVATE, fd, 0);
char *start; int length; char name[]="libtar-1.2.11/TODO";
if( is_file_in_tar(tar,name,&start,&length) ) printf("%.*s",length,start);
}
回答2:
I suspect that libtar is the answer.
Using libtar, you can specify your own functions for opening/closing, reading and writing. From the manpage:
int tar_open(TAR **t, char *pathname, tartype_t *type, int oflags,
int mode, int options);
The
tar_open()
function opens a tar archive file corresponding to the filename named by thepathname
argument. Theoflags
argument must be eitherO_RDONLY
orO_WRONLY
.The type argument specifies the access methods for the given file type. The
tartype_t
structure has members namedopenfunc()
,closefunc()
,readfunc()
andwritefunc()
, which are pointers to the functions for opening, closing, reading, and writing the file, respectively. If type isNULL
, the file type defaults to a normal file, and the standardopen()
,close()
,read()
, andwrite()
functions are used.
回答3:
You can execute tar utility redirected to stdout. (tar --to-stdout
). You should run it using forkpty()
or popen()
in order to read the output.
回答4:
I've done for that with this code. Try it!
FILE*fp;
if( fp = popen("/bin/tar -xv -C /target/dir", "w") )
{
fwrite(tar_buffer,1,tar_size,fp);
pclose(fp);
printf("Untar End %d Save file\n", tar_size);
}
回答5:
Just untar to in-memory tmpfs using a normal untar operation.
来源:https://stackoverflow.com/questions/1553653/how-to-untar-file-in-memory-c-programming