xmalloc: put __hidden behind signature
[netsniff-ng.git] / pcap_rw.c
blobc8ff55e77f350e2c57ead373590b45d8b19d874a
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2009 - 2013 Daniel Borkmann.
5 * Subject to the GPL, version 2.
6 */
8 #include <stdio.h>
9 #include <stdint.h>
10 #include <stdbool.h>
11 #include <stdlib.h>
12 #include <unistd.h>
13 #include <errno.h>
15 #include "pcap.h"
16 #include "built_in.h"
17 #include "xutils.h"
18 #include "xio.h"
19 #include "die.h"
21 static ssize_t pcap_rw_write(int fd, pcap_pkthdr_t *phdr, enum pcap_type type,
22 const uint8_t *packet, size_t len)
24 ssize_t ret, hdrlen = 0, hdrsize = 0;
26 switch (type) {
27 #define PCAP_HDR_WRITE(__member__) do { \
28 hdrlen = phdr->__member__.caplen; \
29 hdrsize = sizeof(phdr->__member__); \
30 ret = write_or_die(fd, &phdr->__member__, hdrsize); \
31 } while (0)
32 #define CASE_HDR_WRITE(what, member) \
33 case (what): \
34 PCAP_HDR_WRITE(member); \
35 break
36 CASE_HDR_WRITE(DEFAULT, ppo);
37 CASE_HDR_WRITE(NSEC, ppn);
38 CASE_HDR_WRITE(KUZNETZOV, ppk);
39 CASE_HDR_WRITE(BORKMANN, ppb);
40 default:
41 bug();
44 if (unlikely(ret != hdrsize))
45 panic("Failed to write pkt header!\n");
46 if (unlikely(hdrlen != len))
47 return -EINVAL;
49 ret = write_or_die(fd, packet, hdrlen);
50 if (unlikely(ret != hdrlen))
51 panic("Failed to write pkt payload!\n");
53 return hdrsize + hdrlen;
56 static ssize_t pcap_rw_read(int fd, pcap_pkthdr_t *phdr, enum pcap_type type,
57 uint8_t *packet, size_t len)
59 ssize_t ret, hdrlen = 0, hdrsize = 0;
61 switch (type) {
62 #define PCAP_HDR_READ(__member__) do { \
63 hdrsize = sizeof(phdr->__member__); \
64 ret = read_or_die(fd, &phdr->__member__, hdrsize); \
65 if (unlikely(ret != hdrsize)) \
66 return -EIO; \
67 hdrlen = phdr->__member__.caplen; \
68 } while (0)
69 #define CASE_HDR_READ(what, member) \
70 case (what): \
71 PCAP_HDR_READ(member); \
72 break
73 CASE_HDR_READ(DEFAULT, ppo);
74 CASE_HDR_READ(NSEC, ppn);
75 CASE_HDR_READ(KUZNETZOV, ppk);
76 CASE_HDR_READ(BORKMANN, ppb);
77 default:
78 bug();
81 if (unlikely(hdrlen == 0 || hdrlen > len))
82 return -EINVAL;
84 ret = read(fd, packet, hdrlen);
85 if (unlikely(ret != hdrlen))
86 return -EIO;
88 return hdrsize + hdrlen;
91 static int pcap_rw_prepare_access(int fd, enum pcap_mode mode, bool jumbo)
93 set_ioprio_rt();
95 return 0;
98 static void pcap_rw_fsync(int fd)
100 fdatasync(fd);
103 const struct pcap_file_ops pcap_rw_ops = {
104 .pull_fhdr_pcap = pcap_generic_pull_fhdr,
105 .push_fhdr_pcap = pcap_generic_push_fhdr,
106 .prepare_access_pcap = pcap_rw_prepare_access,
107 .read_pcap = pcap_rw_read,
108 .write_pcap = pcap_rw_write,
109 .fsync_pcap = pcap_rw_fsync,