Skip to content

Instantly share code, notes, and snippets.

@JRHeaton
Created May 17, 2011 23:13
Show Gist options
  • Save JRHeaton/977627 to your computer and use it in GitHub Desktop.
Save JRHeaton/977627 to your computer and use it in GitHub Desktop.
List files in a zip archive
#include <stdio.h>
#include <stdint.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
int main(int argc, const char *argv[]) {
struct stat st;
int fd;
void *filebuf, *eof_addr, *eof_entry, *central_dir;
uint32_t fsize, fcde_offset;
uint16_t records;
if(argc < 2) {
printf("Specify a file\n");
return -1;
}
if(stat(argv[1], &st) != 0) {
printf("File not found.\n");
return -1;
}
fsize = st.st_size;
fd = open(argv[1], O_RDONLY);
filebuf = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
if(*(uint32_t *)filebuf != 0x04034b50) {
printf("File isn't zip.\n");
munmap(filebuf, fsize);
close(fd);
return -1;
}
eof_addr = (filebuf+fsize);
eof_entry = (eof_addr - 22);
records = (uint16_t)*((char *)eof_entry + 10);
fcde_offset = *(uint32_t *)(eof_entry+16);
central_dir = (void *)(filebuf + fcde_offset);
int i;
for(i=0;i<records;++i) {
uint32_t magic = *(uint32_t *)central_dir;
while(magic != 0x02014b50) {
central_dir += 1;
magic = *(uint32_t *)central_dir;
}
void *cdentry = (void *)central_dir;
short x = *(short *)(cdentry+28);
char namebuf[x+1];
namebuf[x] = 0;
memcpy((void *)namebuf, cdentry+46, x);
printf("[%d] %s\n", i, namebuf);
central_dir += 1;
}
munmap(filebuf, fsize);
close(fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment