added unlikely statement
[netsniff-ng.git] / src / rw_pcap.c
blob5f53b76009fe0f12d4983637f42e05eea25b332b
1 /*
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.
6 * Subject to the GPL.
7 */
9 #include <stdio.h>
10 #include <stdint.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <errno.h>
15 #include "pcap.h"
16 #include "compiler.h"
17 #include "write_or_die.h"
18 #include "die.h"
20 __must_check int pcap_write_file_header(int fd, uint32_t linktype,
21 int32_t thiszone, uint32_t snaplen)
23 ssize_t ret;
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;
30 hdr.sigfigs = 0;
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");
37 return -EIO;
40 return 0;
43 __must_check ssize_t pcap_write_pkt(int fd, struct pcap_pkthdr *hdr,
44 uint8_t *packet)
46 ssize_t ret;
48 ret = write_or_die(fd, hdr, sizeof(*hdr));
49 if (unlikely(ret != sizeof(*hdr))) {
50 whine("Failed to write pkt header!\n");
51 return -EIO;
54 ret = write_or_die(fd, packet, hdr->len);
55 if (unlikely(ret != hdr->len)) {
56 whine("Failed to write pkt payload!\n");
57 return -EIO;
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)
66 ssize_t ret;
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");
72 return -EIO;
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");
80 return -EIO;
83 return 0;
86 __must_check int pcap_read_still_has_packets(int fd)
88 ssize_t ret;
89 off_t pos;
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");
95 return -EIO;
98 ret = read(fd, &hdr, sizeof(hdr));
99 if (unlikely(ret != sizeof(hdr)))
100 return 0;
102 if (unlikely(lseek(fd, pos + hdr.len, SEEK_SET) < 0))
103 return 0;
104 if (unlikely(lseek(fd, pos, SEEK_SET) < 0)) {
105 whine("Cannot rewind the pcap file!\n");
106 return -EIO;
109 return 1;
112 __must_check ssize_t pcap_read_packet(int fd, struct pcap_pkthdr *hdr,
113 uint8_t *packet, size_t len)
115 ssize_t ret;
116 ret = read(fd, hdr, sizeof(*hdr));
117 if (unlikely(ret != sizeof(*hdr)))
118 return -EIO;
119 if (unlikely(hdr->len > len))
120 return -ENOMEM;
121 ret = read(fd, packet, hdr->len);
122 if (unlikely(ret != hdr->len))
123 return -EIO;
124 return hdr->len;