-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwrite.c
144 lines (109 loc) · 2.29 KB
/
write.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/time.h>
#include "snoop.h"
#include "bele.h"
int
packglobalhdr(GlobalHdr *hdr, uint8_t *buf, unsigned int size)
{
uint8_t *p;
if (size < GlobalHdrSize)
return -1;
p = buf;
p += be32put(p, hdr->magic);
p += be16put(p, hdr->version_major);
p += be16put(p, hdr->version_minor);
p += be32put(p, hdr->thiszone);
p += be32put(p, hdr->snaplen);
p += be32put(p, hdr->sigfigs);
p += be32put(p, hdr->linktype);
return p-buf;
}
int
packrecordhdr(RecordHdr *hdr, uint8_t *buf, unsigned int size)
{
uint8_t *p;
if (size < RecordHdrSize)
return -1;
p = buf;
p += be32put(p, hdr->ts_sec);
p += be32put(p, hdr->ts_usec);
p += be32put(p, hdr->caplen);
p += be32put(p, hdr->len);
return p-buf;
}
int
writeglobalhdr(FILE *f)
{
GlobalHdr hdr;
uint8_t buf[GlobalHdrSize];
hdr.magic = PcapMagic;
hdr.version_major = PcapVersionMajor;
hdr.version_minor = PcapVersionMinor;
hdr.thiszone = 0;
hdr.snaplen = MaxSnapLen;
hdr.sigfigs = 0;
hdr.linktype = LINKTYPE_ETHERNET;
if (packglobalhdr(&hdr, buf, sizeof(buf)) < 0)
return -1;
if (fwrite(buf, sizeof(buf), 1, f) != 1)
return -1;
return 0;
}
int
writerecordhdr(FILE *f, int len)
{
RecordHdr hdr;
struct timeval tv;
uint8_t buf[RecordHdrSize];
if (gettimeofday(&tv, NULL) < 0)
return -1;
hdr.ts_sec = tv.tv_sec;
hdr.ts_usec = tv.tv_usec;
hdr.caplen = len;
hdr.len = len;
if (packrecordhdr(&hdr, buf, sizeof(buf)) < 0)
return -1;
if (fwrite(buf, sizeof(buf), 1, f) != 1)
return -1;
return 0;
}
int
writerecord(FILE *f, uint8_t *buf, int len)
{
if (len > MaxSnapLen)
return -1;
if (writerecordhdr(f, len) < 0)
return -1;
if (fwrite(buf, len, 1, f) != 1)
return -1;
return 0;
}
int
writerecordhdrts(FILE *f, int len, uint32_t sec, uint32_t usec)
{
RecordHdr hdr;
uint8_t buf[RecordHdrSize];
hdr.ts_sec = sec;
hdr.ts_usec = usec;
hdr.caplen = len;
hdr.len = len;
if (packrecordhdr(&hdr, buf, sizeof(buf)) < 0)
return -1;
if (fwrite(buf, sizeof(buf), 1, f) != 1)
return -1;
return 0;
}
int
writerecordts(FILE *f, uint8_t *buf, int len, uint32_t sec, uint32_t usec)
{
if (len > MaxSnapLen)
return -1;
if (writerecordhdrts(f, len, sec, usec) < 0)
return -1;
if (fwrite(buf, len, 1, f) != 1)
return -1;
return 0;
}