dissector: if no printing, then don't alloc
[netsniff-ng.git] / src / pcap_rw.c
blob8e3b5c95fa79df1e505ef3adc018d178de42d221
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 ret = pcap_validate_header(&hdr);
30 if (ret < 0)
31 lseek(fd, -sizeof(hdr), SEEK_CUR);
33 return 0;
36 static int pcap_rw_push_file_header(int fd)
38 ssize_t ret;
39 struct pcap_filehdr hdr;
41 memset(&hdr, 0, sizeof(hdr));
42 pcap_prepare_header(&hdr, LINKTYPE_EN10MB, 0,
43 PCAP_DEFAULT_SNAPSHOT_LEN);
45 ret = write_or_die(fd, &hdr, sizeof(hdr));
46 if (unlikely(ret != sizeof(hdr))) {
47 whine("Failed to write pkt file header!\n");
48 return -EIO;
51 return 0;
54 static ssize_t pcap_rw_write_pcap_pkt(int fd, struct pcap_pkthdr *hdr,
55 uint8_t *packet, size_t len)
57 ssize_t ret = write_or_die(fd, hdr, sizeof(*hdr));
58 if (unlikely(ret != sizeof(*hdr))) {
59 whine("Failed to write pkt header!\n");
60 return -EIO;
63 if (unlikely(hdr->len != len))
64 return -EINVAL;
66 ret = write_or_die(fd, packet, hdr->len);
67 if (unlikely(ret != hdr->len)) {
68 whine("Failed to write pkt payload!\n");
69 return -EIO;
72 return sizeof(*hdr) + hdr->len;
75 static ssize_t pcap_rw_read_pcap_pkt(int fd, struct pcap_pkthdr *hdr,
76 uint8_t *packet, size_t len)
78 ssize_t ret = read(fd, hdr, sizeof(*hdr));
79 if (unlikely(ret != sizeof(*hdr)))
80 return -EIO;
82 if (unlikely(hdr->len > len))
83 return -ENOMEM;
85 ret = read(fd, packet, hdr->len);
86 if (unlikely(ret != hdr->len))
87 return -EIO;
89 if (unlikely(hdr->len == 0))
90 return -EINVAL; /* Bogus packet */
92 return sizeof(*hdr) + hdr->len;
95 static void pcap_rw_fsync_pcap(int fd)
97 fdatasync(fd);
100 static int pcap_rw_prepare_writing_pcap(int fd)
102 set_ioprio_rt();
103 return 0;
106 static int pcap_rw_prepare_reading_pcap(int fd)
108 set_ioprio_rt();
109 return 0;
112 struct pcap_file_ops pcap_rw_ops __read_mostly = {
113 .name = "read-write",
114 .pull_file_header = pcap_rw_pull_file_header,
115 .push_file_header = pcap_rw_push_file_header,
116 .write_pcap_pkt = pcap_rw_write_pcap_pkt,
117 .read_pcap_pkt = pcap_rw_read_pcap_pkt,
118 .fsync_pcap = pcap_rw_fsync_pcap,
119 .prepare_writing_pcap = pcap_rw_prepare_writing_pcap,
120 .prepare_reading_pcap = pcap_rw_prepare_reading_pcap,
123 int init_pcap_rw(int jumbo_support)
125 return pcap_ops_group_register(&pcap_rw_ops, PCAP_OPS_RW);
128 void cleanup_pcap_rw(void)
130 pcap_ops_group_unregister(PCAP_OPS_RW);