All pastes #2004153 Raw Edit

Anonymous

public text v1 · immutable
#2004153 ·published 2010-11-27 22:27 UTC
rendered paste body
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/mman.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <dirent.h>

int main(int argc, char **argv)
{
	int fd;
	struct stat sbuf;
	void *ptr;
	unsigned long numfiles, offset, nextoffset = 0, n;
	unsigned char *buf, filename[13], cbuf[65536];
	DIR *dir;
	struct dirent *de;

	if (argc != 1)
	{
		fputs("usage: dat\n", stderr);
		return 1;
	}
	
	dir = opendir("/mnt/windows/Program Files/KRU/NexusTK/Data/");
	if (dir == NULL)
	{
		perror("opendir");
		return 1;
	}
	
	while ((de = readdir(dir)) != NULL)
	{
		if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
			continue;

		snprintf(cbuf, 65536, "/mnt/windows/Program Files/KRU/NexusTK/Data/%s", de->d_name);
		
		if (stat(cbuf, &sbuf) == -1)
		{
			perror("stat");
			closedir(dir);
			return 1;
		}
	
		fd = open(cbuf, O_RDONLY);
		if (fd == -1)
		{
			perror("open");
			closedir(dir);
			return 1;
		}

		ptr = mmap(NULL, sbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
		if (ptr == MAP_FAILED)
		{
			perror("mmap");
			close(fd);
			closedir(dir);
			return 1;
		}

		buf = (unsigned char*)ptr;

		if (close(fd) == -1)
		{
			perror("close");
			closedir(dir);
			munmap(ptr, sbuf.st_size);
			return 1;
		}

		numfiles = (buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24)) - 1;
	
		for (n = 0; n < numfiles; ++n)
		{
			//if (nextoffset == 0)
				offset = buf[(n * 17) + 4] | (buf[(n * 17) + 5] << 8) | (buf[(n * 17) + 6] << 16) | (buf[(n * 17) + 7] << 24);
			//else
				//offset = nextoffset;

			memcpy(filename, buf + (n * 17) + 8, 13);

			nextoffset = buf[(n * 17) + 21] | (buf[(n * 17) + 22] << 8) | (buf[(n * 17) + 23] << 16) | (buf[(n * 17) + 24] << 24);

			/*snprintf(cbuf, 65536, "/home/brandon/nexus/%s", de->d_name);
		
			if (mkdir(cbuf, S_IRWXU | S_IRWXG | S_IRWXO) == -1)
			{
				if (errno =! EEXIST)
				{	
					perror("mkdir");
					closedir(dir);
					munmap(ptr, sbuf.st_size);
					return 1;
				}
			}
		
			snprintf(cbuf, 65536, "/home/brandon/nexus/%s/%s", de->d_name, filename);*/
			
			snprintf(cbuf, 65536, "/home/brandon/nexus/%s", filename);
		
			fd = open(cbuf, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
			if (fd == -1)
			{
				perror("open");
				closedir(dir);
				munmap(ptr, sbuf.st_size);
				return 1;
			}
		
			if (write(fd, buf + offset, nextoffset - offset) != nextoffset - offset)
			{
				perror("write");
				close(fd);
				closedir(dir);
				munmap(ptr, sbuf.st_size);
				return 1;
			}
		
			if (close(fd) == -1)
			{
				perror("close");
				closedir(dir);
				munmap(ptr, sbuf.st_size);
				return 1;
			}

		}

		if (munmap(ptr, sbuf.st_size) == -1)
		{
			perror("munmap");
			closedir(dir);
			return 1;
		}
	}
	
	if (closedir(dir) == -1)
	{
		perror("closedir");
		return 1;
	}
	
	return 0;
}