1 
2 #include "pcapFileHandle.h"
3 
4 /**************************************************************************
5  **SA Network Connection Profiler [sancp] - A TCP/IP statistical/collection tool
6  * ************************************************************************
7  * * Copyright (C) 2003 John Curry <john.curry@metre.net>
8  * *
9  * * This program is distributed under the terms of version 1.0 of the
10  * * Q Public License.  See LICENSE.QPL for further details.
11  * *
12  * * This program is distributed in the hope that it will be useful,
13  * * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15  * *
16  * ***********************************************************************/
17 
pcapFileHandle()18 pcapFileHandle::pcapFileHandle() { }
19 
pcapFileHandle(const char * newfilename)20 pcapFileHandle::pcapFileHandle(const char *newfilename)
21 {
22 	setFileName(newfilename);
23 }
24 
stat()25 int pcapFileHandle::stat()
26 {
27 	struct stat buffer;
28 	if(::stat(getFileName(),&buffer)||(buffer.st_size < 24))
29 	{
30 		return 0;
31 	}
32 	return 1;
33 }
34 
open()35 int pcapFileHandle::open()
36 {
37 	if(isOpen()){ return 1; }
38 	if(getFileName()==0){
39 		//No filename set!
40 		return 0;
41 	}
42 	// Check if file is present and that it has a minimum header size
43 	if(!stat())
44 	{
45 		// Open file in write mode
46 		fileHandle::setMode(WRITE_MODE);
47 		fileHandle::open();
48 		fileHandle::write( pcap_header ,PCAP_HEADER_SIZE);
49 	}else{
50 		// Open file in append mode
51 		fileHandle::setMode(APPEND_MODE);
52 		fileHandle::open();
53 	}
54 	return 1;
55 }
56 
57 
write(const char * data,int len,struct timeval * timeptr)58 ssize_t pcapFileHandle::write(const char *data, int len, struct timeval *timeptr)
59 {
60 	char tmp[5];
61 	ssize_t bytes=0;
62 	tmp[4]=0;
63 	u_int32_t num;
64 
65  	if(open())
66 	{
67 		num = ((timeptr->tv_sec));
68 		bytes=fileHandle::write((const char *)&num,4);
69 		num = ((timeptr->tv_usec));
70 		bytes+=fileHandle::write((const char *)&num,4);
71 		num = 0x00000000;
72 		num = len;
73 		bytes+=fileHandle::write((const char *)&num,4);
74 		bytes+=fileHandle::write((const char *)&num,4);
75 		bytes+=fileHandle::write(data,len);
76 	}else{
77 		//Unable to print to file
78 		return -1;
79 	}
80 	return bytes;
81 }
82 
attach()83 pcapFileHandle * pcapFileHandle::attach()
84 {
85 	fileHandle::attach();
86 	return this;
87 }
88 
~pcapFileHandle()89 pcapFileHandle::~pcapFileHandle() { }
90