proto_ipv6_mobility_hdr.h: Headerfixing
[netsniff-ng.git] / src / pcap_rw.c
blobc8e836863c8314e7362e6a89ddaff6ba4a92d454
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * By Daniel Borkmann <daniel@netsniff-ng.org>
4 * Copyright 2009, 2010, 2011 Daniel Borkmann.
5 * Subject to the GPL, version 2.
6 */
8 #include <stdio.h>
9 #include <stdint.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <errno.h>
14 #include "pcap.h"
15 #include "built_in.h"
16 #include "xio.h"
17 #include "die.h"
19 static int pcap_rw_pull_file_header(int fd)
21 ssize_t ret;
22 struct pcap_filehdr hdr;
24 ret = read(fd, &hdr, sizeof(hdr));
25 if (unlikely(ret != sizeof(hdr)))
26 return -EIO;
28 pcap_validate_header_maybe_die(&hdr);
30 return 0;
33 static int pcap_rw_push_file_header(int fd)
35 ssize_t ret;
36 struct pcap_filehdr hdr;
38 memset(&hdr, 0, sizeof(hdr));
39 pcap_prepare_header(&hdr, LINKTYPE_EN10MB, 0,
40 PCAP_DEFAULT_SNAPSHOT_LEN);
42 ret = write_or_die(fd, &hdr, sizeof(hdr));
43 if (unlikely(ret != sizeof(hdr))) {
44 whine("Failed to write pkt file header!\n");
45 return -EIO;
48 return 0;
51 static ssize_t pcap_rw_write_pcap_pkt(int fd, struct pcap_pkthdr *hdr,
52 uint8_t *packet, size_t len)
54 ssize_t ret = write_or_die(fd, hdr, sizeof(*hdr));
55 if (unlikely(ret != sizeof(*hdr))) {
56 whine("Failed to write pkt header!\n");
57 return -EIO;
60 if (unlikely(hdr->len != len))
61 return -EINVAL;
63 ret = write_or_die(fd, packet, hdr->len);
64 if (unlikely(ret != hdr->len)) {
65 whine("Failed to write pkt payload!\n");
66 return -EIO;
69 return sizeof(*hdr) + hdr->len;
72 static ssize_t pcap_rw_read_pcap_pkt(int fd, struct pcap_pkthdr *hdr,
73 uint8_t *packet, size_t len)
75 ssize_t ret = read(fd, hdr, sizeof(*hdr));
76 if (unlikely(ret != sizeof(*hdr)))
77 return -EIO;
79 if (unlikely(hdr->len > len))
80 return -ENOMEM;
82 ret = read(fd, packet, hdr->len);
83 if (unlikely(ret != hdr->len))
84 return -EIO;
86 if (unlikely(hdr->len == 0))
87 return -EINVAL; /* Bogus packet */
89 return sizeof(*hdr) + hdr->len;
92 static void pcap_rw_fsync_pcap(int fd)
94 fdatasync(fd);
97 struct pcap_file_ops pcap_rw_ops __read_mostly = {
98 .name = "read-write",
99 .pull_file_header = pcap_rw_pull_file_header,
100 .push_file_header = pcap_rw_push_file_header,
101 .write_pcap_pkt = pcap_rw_write_pcap_pkt,
102 .read_pcap_pkt = pcap_rw_read_pcap_pkt,
103 .fsync_pcap = pcap_rw_fsync_pcap,
106 int init_pcap_rw(int jumbo_support)
108 return pcap_ops_group_register(&pcap_rw_ops, PCAP_OPS_RW);
111 void cleanup_pcap_rw(void)
113 pcap_ops_group_unregister(PCAP_OPS_RW);