Initial import
[openvswitch] / datapath / tests / gen_forward_t.pl
1 #! /usr/bin/perl
2
3 use warnings;
4 use strict;
5
6 if (@ARGV != 1) {
7     print "usage: $0 input.pcap > output.h\n";
8     print "where input.pcap is a packet capture in pcap format\n";
9     print "and output.c is a C header file containing the packets\n";
10     exit(1);
11 }
12 my ($in_file_name) = $ARGV[0];
13 open(INPUT, '<', $in_file_name) or die "$in_file_name: open: $!\n";
14
15 my ($file_header);
16 if (read(INPUT, $file_header, 24) != 24) {
17     die "$in_file_name: could not read pcap header\n";
18 }
19
20 my ($s, $l);
21 if (substr($file_header, 0, 4) eq pack('V', 0xa1b2c3d4)) {
22     ($s, $l) = ('v', 'V');
23 } elsif (substr($file_header, 0, 4) eq pack('N', 0xa1b2c3d4)) {
24     ($s, $l) = ('n', 'N');
25 } else {
26     die "$in_file_name: not a pcap file\n";
27 }
28
29 print <<'EOF';
30 #ifndef DP_TEST_PACKETS_H
31 #define DP_TEST_PACKETS_H 1
32
33 struct pkt {
34         unsigned char *data;
35         unsigned int len;
36 };
37 EOF
38
39 my ($n_packets) = 0;
40 for (;;) {
41     my ($pkt_hdr) = must_read(16);
42     last if $pkt_hdr eq '';
43
44     my ($ts_sec, $ts_usec, $incl_len, $orig_len) = unpack("${l}4", $pkt_hdr);
45     print STDERR "warning: captured less than len %u\n"
46       if $incl_len < $orig_len;
47
48     my ($pkt) = must_read($incl_len);
49     die "$in_file_name: unexpected end of file\n" if !$pkt;
50
51     print "\nstatic unsigned char p${n_packets}[] = {";
52     my ($line_bytes) = 0;
53     for my $c (map(ord($_), split(//, $pkt))) {
54         if ($line_bytes++ % 13 == 0) {
55             print "\n";
56         }
57         printf " 0x%02x,", $c;
58     }
59     print "\n};\n";
60     $n_packets++;
61 }
62
63 print "\nstatic int num_packets = $n_packets;\n";
64 print "\nstatic struct pkt packets[] = {\n";
65 for my $i (0..$n_packets - 1) {
66     print "  { p$i, sizeof p$i },\n";
67 }
68 print "};\n";
69
70 print "\n#endif\n";
71
72 sub must_read {
73     my ($rq_bytes) = @_;
74     my ($data);
75     my ($nbytes) = read(INPUT, $data, $rq_bytes);
76     die "$in_file_name: read: $!\n" if !defined $nbytes;
77     die "$in_file_name: unexpected end of file\n"
78       if $nbytes && $nbytes != $rq_bytes;
79     return $data;
80 }