2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2009, 2010 Daniel Borkmann.
5 * Copyright 2010 Emmanuel Roullit.
17 #include "write_or_die.h"
20 __must_check
int pcap_write_file_header(int fd
, uint32_t linktype
,
21 int32_t thiszone
, uint32_t snaplen
)
24 struct pcap_filehdr hdr
;
26 hdr
.magic
= TCPDUMP_MAGIC
;
27 hdr
.version_major
= PCAP_VERSION_MAJOR
;
28 hdr
.version_minor
= PCAP_VERSION_MINOR
;
29 hdr
.thiszone
= thiszone
;
31 hdr
.snaplen
= snaplen
;
32 hdr
.linktype
= linktype
;
34 ret
= write_or_die(fd
, &hdr
, sizeof(hdr
));
35 if (unlikely(ret
!= sizeof(hdr
))) {
36 whine("Failed to write pcap header!\n");
43 __must_check ssize_t
pcap_write_pkt(int fd
, struct pcap_pkthdr
*hdr
,
48 ret
= write_or_die(fd
, hdr
, sizeof(*hdr
));
49 if (unlikely(ret
!= sizeof(*hdr
))) {
50 whine("Failed to write pkt header!\n");
54 ret
= write_or_die(fd
, packet
, hdr
->len
);
55 if (unlikely(ret
!= hdr
->len
)) {
56 whine("Failed to write pkt payload!\n");
60 fsync_or_die(fd
, "Syncing packet buffer");
61 return (sizeof(*hdr
) + hdr
->len
);
64 __must_check
int pcap_read_and_validate_file_header(int fd
)
67 struct pcap_filehdr hdr
;
69 ret
= read(fd
, &hdr
, sizeof(hdr
));
70 if (unlikely(ret
!= sizeof(hdr
))) {
71 whine("Failed to read pcap header!\n");
75 if (unlikely(hdr
.magic
!= TCPDUMP_MAGIC
||
76 hdr
.version_major
!= PCAP_VERSION_MAJOR
||
77 hdr
.version_minor
!= PCAP_VERSION_MINOR
||
78 hdr
.linktype
!= LINKTYPE_EN10MB
)) {
79 whine("This file has not a valid pcap header!\n");
86 __must_check
int pcap_read_still_has_packets(int fd
)
90 struct pcap_pkthdr hdr
;
92 pos
= lseek(fd
, (off_t
) 0, SEEK_CUR
);
93 if (unlikely(pos
< 0)) {
94 whine("Cannot seek offset of pcap file!\n");
98 ret
= read(fd
, &hdr
, sizeof(hdr
));
99 if (unlikely(ret
!= sizeof(hdr
)))
102 if (unlikely(lseek(fd
, pos
+ hdr
.len
, SEEK_SET
) < 0))
104 if (unlikely(lseek(fd
, pos
, SEEK_SET
) < 0)) {
105 whine("Cannot rewind the pcap file!\n");
112 __must_check ssize_t
pcap_read_packet(int fd
, struct pcap_pkthdr
*hdr
,
113 uint8_t *packet
, size_t len
)
116 ret
= read(fd
, hdr
, sizeof(*hdr
));
117 if (unlikely(ret
!= sizeof(*hdr
)))
119 if (unlikely(hdr
->len
> len
))
121 ret
= read(fd
, packet
, hdr
->len
);
122 if (unlikely(ret
!= hdr
->len
))