dissector_fuzz: removed printing opts to make for usage with diff
[netsniff-ng.git] / src / pcap_rw.c
blob4fc0505fd101ca8dedc4fca7428a593c026d6ac8
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 "xsys.h"
17 #include "xio.h"
18 #include "die.h"
20 static int pcap_rw_pull_file_header(int fd)
22 ssize_t ret;
23 struct pcap_filehdr hdr;
25 ret = read(fd, &hdr, sizeof(hdr));
26 if (unlikely(ret != sizeof(hdr)))
27 return -EIO;
29 pcap_validate_header(&hdr);
31 return 0;
34 static int pcap_rw_push_file_header(int fd)
36 ssize_t ret;
37 struct pcap_filehdr hdr;
39 memset(&hdr, 0, sizeof(hdr));
40 pcap_prepare_header(&hdr, LINKTYPE_EN10MB, 0,
41 PCAP_DEFAULT_SNAPSHOT_LEN);
43 ret = write_or_die(fd, &hdr, sizeof(hdr));
44 if (unlikely(ret != sizeof(hdr))) {
45 whine("Failed to write pkt file header!\n");
46 return -EIO;
49 return 0;
52 static ssize_t pcap_rw_write_pcap_pkt(int fd, struct pcap_pkthdr *hdr,
53 uint8_t *packet, size_t len)
55 ssize_t ret = write_or_die(fd, hdr, sizeof(*hdr));
56 if (unlikely(ret != sizeof(*hdr))) {
57 whine("Failed to write pkt header!\n");
58 return -EIO;
61 if (unlikely(hdr->len != len))
62 return -EINVAL;
64 ret = write_or_die(fd, packet, hdr->len);
65 if (unlikely(ret != hdr->len)) {
66 whine("Failed to write pkt payload!\n");
67 return -EIO;
70 return sizeof(*hdr) + hdr->len;
73 static ssize_t pcap_rw_read_pcap_pkt(int fd, struct pcap_pkthdr *hdr,
74 uint8_t *packet, size_t len)
76 ssize_t ret = read(fd, hdr, sizeof(*hdr));
77 if (unlikely(ret != sizeof(*hdr)))
78 return -EIO;
80 if (unlikely(hdr->len > len))
81 return -ENOMEM;
83 if (unlikely(hdr->len == 0))
84 return -EINVAL; /* Bogus packet */
86 ret = read(fd, packet, hdr->len);
87 if (unlikely(ret != hdr->len))
88 return -EIO;
90 return sizeof(*hdr) + hdr->len;
93 static void pcap_rw_fsync_pcap(int fd)
95 fdatasync(fd);
98 static int pcap_rw_prepare_writing_pcap(int fd)
100 set_ioprio_rt();
101 return 0;
104 static int pcap_rw_prepare_reading_pcap(int fd)
106 set_ioprio_rt();
107 return 0;
110 struct pcap_file_ops pcap_rw_ops __read_mostly = {
111 .name = "read-write",
112 .pull_file_header = pcap_rw_pull_file_header,
113 .push_file_header = pcap_rw_push_file_header,
114 .write_pcap_pkt = pcap_rw_write_pcap_pkt,
115 .read_pcap_pkt = pcap_rw_read_pcap_pkt,
116 .fsync_pcap = pcap_rw_fsync_pcap,
117 .prepare_writing_pcap = pcap_rw_prepare_writing_pcap,
118 .prepare_reading_pcap = pcap_rw_prepare_reading_pcap,
121 int init_pcap_rw(int jumbo_support)
123 return pcap_ops_group_register(&pcap_rw_ops, PCAP_OPS_RW);
126 void cleanup_pcap_rw(void)
128 pcap_ops_group_unregister(PCAP_OPS_RW);