Thread: pf file format
View Single Post
  #2  
Old 03-16-2005, 05:11 PM
fathernitwit
Developer
 
Join Date: Jul 2004
Posts: 773
Default

Code:
//constants used in the packet file header
#define PACKET_FILE_MAGIC 0x93a7b6f7

#pragma pack(1)
struct PacketFileHeader {
	uint32 packet_file_magic;
	uint32 packet_file_stamp;
};

struct PacketFileSection {
	uint16 opcode;
	uint32 len;
};
#pragma pack()

class PacketFileReader {
public:
	PacketFileReader();
	~PacketFileReader();
	
	bool OpenFile(const char *name);
	void CloseFile();
	
	bool ReadPacket(uint16 &eq_op, uint32 &packlen, unsigned char *packet);
	
	time_t GetStamp() { return(time_t(packet_file_stamp)); }
	
protected:
	
	uint32 packet_file_stamp;
	
	//gzFile in;
	FILE *in;	
};

PacketFileReader::PacketFileReader() {
	in = NULL;
	packet_file_stamp = 0;
}

PacketFileReader::~PacketFileReader() {
	CloseFile();
}
	
bool PacketFileReader::OpenFile(const char *name) {
	CloseFile();
	
	printf("Opening packet file: %s\n", name);
	
	in = fopen(name, "rb");
	if(in == NULL) {
		fprintf(stderr, "Error opening packet file '%s': %s\n", name, strerror(errno));
		return(false);
	}
	
	PacketFileHeader head;
	
	if(fread(&head, sizeof(head), 1, in) != 1) {
		fprintf(stderr, "Error writting header to packet file: %s\n", strerror(errno));
		fclose(in);
		return(false);
	}
	
	if(head.packet_file_magic != PACKET_FILE_MAGIC) {
		fclose(in);
		if(head.packet_file_magic == (PACKET_FILE_MAGIC+1)) {
			fprintf(stderr, "Error: this is a build file, not a packet file, its allready processed!\n");
		} else {
			fprintf(stderr, "Error: this is not a packet file!\n");
		}
		return(false);
	}
	
	uint32 now = time(NULL);
	if(head.packet_file_stamp > now) {
		fprintf(stderr, "Error: invalid timestamp in file. Your clock or the collector's is wrong.");
		fclose(in);
		return(false);
	}
	
	packet_file_stamp = head.packet_file_stamp;
	
	return(true);
}

void PacketFileReader::CloseFile() {
	if(in != NULL) {
		fclose(in);
		in = NULL;
		printf("Closed packet file.\n");
	}
}

bool PacketFileReader::ReadPacket(uint16 &eq_op, uint32 &packlen, unsigned char *packet) {
	if(in == NULL)
		return(false);
	if(feof(in))
		return(false);
	
	PacketFileSection s;
	
	if(fread(&s, sizeof(s), 1, in) != 1) {
		if(!feof(in))
			fprintf(stderr, "Error reading section header: %s\n", strerror(errno));
		return(false);
	}
	
	eq_op = s.opcode;
	
	if(packlen < s.len) {
		fprintf(stderr, "Packet buffer is too small! %d < %d, skipping\n", packlen, s.len);
		fseek(in, s.len, SEEK_CUR);
		return(false);
	}
	
	if(fread(packet, 1, s.len, in) != s.len) {
		if(feof(in))
			fprintf(stderr, "Error: EOF encountered when expecting packet data.\n");
		else
			fprintf(stderr, "Error reading packet body: %s\n", strerror(errno));
		return(false);
	}
	
	packlen = s.len;
	
	return(true);
}
Reply With Quote