Merge pull request #59 from electronjoe/graceful-SIGTERM-handling
[netsniff-ng-old.git] / pcap_rw.c
blob22d613f7ec004ce2673c2eb9bf17562af2487c63
1 /*
2 * netsniff-ng - the packet sniffing beast
3 * Copyright 2009 - 2013 Daniel Borkmann.
4 * Subject to the GPL, version 2.
5 */
7 #include <stdio.h>
8 #include <stdint.h>
9 #include <stdbool.h>
10 #include <stdlib.h>
11 #include <unistd.h>
12 #include <errno.h>
14 #include "pcap_io.h"
15 #include "built_in.h"
16 #include "xutils.h"
17 #include "xio.h"
18 #include "die.h"
20 static ssize_t pcap_rw_write(int fd, pcap_pkthdr_t *phdr, enum pcap_type type,
21 const uint8_t *packet, size_t len)
23 ssize_t ret, hdrsize = pcap_get_hdr_length(phdr, type), hdrlen = 0;
25 ret = write_or_die(fd, &phdr->raw, hdrsize);
26 if (unlikely(ret != hdrsize))
27 panic("Failed to write pkt header!\n");
29 hdrlen = pcap_get_length(phdr, type);
30 if (unlikely(hdrlen != len))
31 return -EINVAL;
33 ret = write_or_die(fd, packet, hdrlen);
34 if (unlikely(ret != hdrlen))
35 panic("Failed to write pkt payload!\n");
37 return hdrsize + hdrlen;
40 static ssize_t pcap_rw_read(int fd, pcap_pkthdr_t *phdr, enum pcap_type type,
41 uint8_t *packet, size_t len)
43 ssize_t ret, hdrsize = pcap_get_hdr_length(phdr, type), hdrlen = 0;
45 ret = read_or_die(fd, &phdr->raw, hdrsize);
46 if (unlikely(ret != hdrsize))
47 return -EIO;
49 hdrlen = pcap_get_length(phdr, type);
50 if (unlikely(hdrlen == 0 || hdrlen > len))
51 return -EINVAL;
53 ret = read(fd, packet, hdrlen);
54 if (unlikely(ret != hdrlen))
55 return -EIO;
57 return hdrsize + hdrlen;
60 static int pcap_rw_prepare_access(int fd, enum pcap_mode mode, bool jumbo)
62 set_ioprio_rt();
64 return 0;
67 static void pcap_rw_fsync(int fd)
69 fdatasync(fd);
72 const struct pcap_file_ops pcap_rw_ops = {
73 .pull_fhdr_pcap = pcap_generic_pull_fhdr,
74 .push_fhdr_pcap = pcap_generic_push_fhdr,
75 .prepare_access_pcap = pcap_rw_prepare_access,
76 .read_pcap = pcap_rw_read,
77 .write_pcap = pcap_rw_write,
78 .fsync_pcap = pcap_rw_fsync,