how to untar file in memory (c programming)?

不羁的心 提交于 2019-12-18 03:48:36

问题


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 starting position of the named 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 the pathname argument. The oflags argument must be either O_RDONLY or O_WRONLY.

The type argument specifies the access methods for the given file type. The tartype_t structure has members named openfunc(), closefunc(), readfunc() and writefunc(), which are pointers to the functions for opening, closing, reading, and writing the file, respectively. If type is NULL, the file type defaults to a normal file, and the standard open(), close(), read(), and write() 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!