docs: fixed minor typo
[netsniff-ng.git] / src / pcap_rw.c
blobd3170349b19b3225ca6ea949a5a494934a88abc1
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 "compiler.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;
27 pcap_validate_header_maybe_die(&hdr);
29 return 0;
32 static int pcap_rw_push_file_header(int fd)
34 ssize_t ret;
35 struct pcap_filehdr hdr;
37 memset(&hdr, 0, sizeof(hdr));
38 pcap_prepare_header(&hdr, LINKTYPE_EN10MB, 0,
39 PCAP_DEFAULT_SNAPSHOT_LEN);
40 ret = write_or_die(fd, &hdr, sizeof(hdr));
41 if (unlikely(ret != sizeof(hdr))) {
42 whine("Failed to write pkt file header!\n");
43 return -EIO;
46 return 0;
49 static ssize_t pcap_rw_write_pcap_pkt(int fd, struct pcap_pkthdr *hdr,
50 uint8_t *packet, size_t len)
52 ssize_t ret;
53 ret = write_or_die(fd, hdr, sizeof(*hdr));
54 if (unlikely(ret != sizeof(*hdr))) {
55 whine("Failed to write pkt header!\n");
56 return -EIO;
58 if (unlikely(hdr->len != len))
59 return -EINVAL;
60 ret = write_or_die(fd, packet, hdr->len);
61 if (unlikely(ret != hdr->len)) {
62 whine("Failed to write pkt payload!\n");
63 return -EIO;
65 return sizeof(*hdr) + hdr->len;
68 static ssize_t pcap_rw_read_pcap_pkt(int fd, struct pcap_pkthdr *hdr,
69 uint8_t *packet, size_t len)
71 ssize_t ret;
72 ret = read(fd, hdr, sizeof(*hdr));
73 if (unlikely(ret != sizeof(*hdr)))
74 return -EIO;
75 if (unlikely(hdr->len > len))
76 return -ENOMEM;
77 ret = read(fd, packet, hdr->len);
78 if (unlikely(ret != hdr->len))
79 return -EIO;
80 if (unlikely(hdr->len == 0))
81 return -EINVAL; /* Bogus packet */
82 return sizeof(*hdr) + hdr->len;
85 static void pcap_rw_fsync_pcap(int fd)
87 fdatasync(fd);
90 struct pcap_file_ops pcap_rw_ops __read_mostly = {
91 .name = "READ/WRITE",
92 .pull_file_header = pcap_rw_pull_file_header,
93 .push_file_header = pcap_rw_push_file_header,
94 .write_pcap_pkt = pcap_rw_write_pcap_pkt,
95 .read_pcap_pkt = pcap_rw_read_pcap_pkt,
96 .fsync_pcap = pcap_rw_fsync_pcap,
99 int init_pcap_rw(int jumbo_support)
101 return pcap_ops_group_register(&pcap_rw_ops, PCAP_OPS_RW);
104 void cleanup_pcap_rw(void)
106 pcap_ops_group_unregister(PCAP_OPS_RW);