test: tolerate ENOMEM on packet mmap creation.
[dabba.git] / libdabba / tests / test-pcap.c
blob4cc848a2d8b419edda94d5ffe15afdd24f905456
2 #include <stdlib.h>
3 #include <string.h>
4 #include <unistd.h>
5 #include <assert.h>
6 #include <fcntl.h>
7 #include <byteswap.h>
9 #include <sys/time.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
13 #include <libdabba/pcap.h>
14 #include <libdabba/macros.h>
15 #include <linux/if_link.h>
17 static const uint8_t icmp_dns[] = {
18 0x00, 0x1e, 0x65, 0x93, 0x1b, 0x6c, 0x00, 0x1d,
19 0x19, 0x84, 0x9c, 0xdc, 0x08, 0x00, 0x45, 0x00,
20 0x00, 0x54, 0xdb, 0x46, 0x00, 0x00, 0x38, 0x01,
21 0x4d, 0x41, 0x08, 0x08, 0x08, 0x08, 0xc0, 0xa8,
22 0x89, 0x69, 0x00, 0x00, 0xce, 0x1a, 0x12, 0x2d,
23 0x00, 0x02, 0xb7, 0xeb, 0xba, 0x4c, 0x00, 0x00,
24 0x00, 0x00, 0xee, 0xaa, 0x00, 0x00, 0x00, 0x00,
25 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
26 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
27 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25,
28 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d,
29 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
30 0x36, 0x37
33 static const char test_path[] = "res.pcap";
35 void swapped_pcap_file_header_init(struct pcap_file_header *pcap_hdr)
37 assert(pcap_hdr);
39 memset(pcap_hdr, 0, sizeof(*pcap_hdr));
41 pcap_hdr->magic = bswap_32(TCPDUMP_MAGIC);
42 pcap_hdr->version_major = bswap_16(PCAP_VERSION_MAJOR);
43 pcap_hdr->version_minor = bswap_16(PCAP_VERSION_MINOR);
44 pcap_hdr->thiszone = 0;
45 pcap_hdr->sigfigs = 0;
46 pcap_hdr->snaplen = bswap_32(PCAP_DEFAULT_SNAPSHOT_LEN);
47 pcap_hdr->linktype = bswap_32(LINKTYPE_EN10MB);
50 int test_pcap_write(const int fd, const uint8_t * const payload,
51 const ssize_t len)
53 struct timeval tv;
55 gettimeofday(&tv, NULL);
57 if (ldab_pcap_write(fd, payload, len, len, tv.tv_sec, tv.tv_usec) != len) {
58 return (-1);
61 return (0);
64 int main(void)
66 struct pcap_file_header pcap_hdr;
67 int fd;
69 swapped_pcap_file_header_init(&pcap_hdr);
71 assert((fd = ldab_pcap_create(test_path, LINKTYPE_EN10MB)) > 0);
72 assert(test_pcap_write(fd, icmp_dns, sizeof(icmp_dns)) == 0);
73 assert(ldab_pcap_close(fd) == 0);
75 assert((fd = ldab_pcap_open(test_path, O_RDONLY)) > 0);
76 assert(ldab_pcap_close(fd) == 0);
78 assert((fd = ldab_pcap_open(test_path, O_RDWR | O_APPEND)) > 0);
79 assert(test_pcap_write(fd, icmp_dns, sizeof(icmp_dns)) == 0);
80 assert(ldab_pcap_close(fd) == 0);
82 assert((fd = ldab_pcap_open(test_path, O_RDONLY)) > 0);
83 assert(ldab_pcap_close(fd) == 0);
85 /* Test swapped PCAP file header support */
86 assert((fd = open(test_path, O_WRONLY)) > 0);
87 assert(write(fd, &pcap_hdr, sizeof(pcap_hdr)) == sizeof(pcap_hdr));
88 assert(test_pcap_write(fd, icmp_dns, sizeof(icmp_dns)) == 0);
89 assert(close(fd) == 0);
91 assert((fd = ldab_pcap_open(test_path, O_RDONLY)) > 0);
92 assert(ldab_pcap_close(fd) == 0);
94 ldab_pcap_destroy(fd, test_path);
96 return (EXIT_SUCCESS);