#! @PYTHON3@
#
# Copyright (c) 2010 Nicira, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import binascii
import getopt
import struct
import sys


class PcapException(Exception):
    pass


class PcapReader(object):
    def __init__(self, file_name):
        self.file = open(file_name, "rb")
        header = self.file.read(24)
        if len(header) != 24:
            raise PcapException("end of file reading pcap header")
        magic, version, thiszone, sigfigs, snaplen, network = \
            struct.unpack(">6I", header)
        if magic == 0xa1b2c3d4 or magic == 0xa1b23c4d:
            self.header_format = ">4I"
        elif magic == 0xd4c3b2a1 or magic == 0x4d3cb2a1:
            self.header_format = "<4I"
        else:
            raise PcapException("bad magic %u reading pcap file "
                        "(expected 0xa1b2c3d4, 0xa1b23c4d, 0x4d3cb2a1 or "
                        "0xd4c3b2a1)" % magic)

    def read(self):
        header = self.file.read(16)
        if len(header) == 0:
            return None
        elif len(header) != 16:
            raise PcapException("end of file within pcap record header")

        ts_sec, ts_usec, incl_len, orig_len = struct.unpack(self.header_format,
                                                            header)
        packet = self.file.read(incl_len)
        if len(packet) != incl_len:
            raise PcapException("end of file reading pcap packet data")
        return packet


argv0 = sys.argv[0]


def usage():
    print("""\
%(argv0)s: print pcap file packet data as hex
usage: %(argv0)s FILE
where FILE is a PCAP file.

The following options are also available:
  -h, --help                  display this help message
  -V, --version               display version information\
""" % {'argv0': argv0})
    sys.exit(0)


if __name__ == "__main__":
    try:
        try:
            options, args = getopt.gnu_getopt(sys.argv[1:], 'hV',
                                              ['help', 'version'])
        except getopt.GetoptError as geo:
            sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
            sys.exit(1)

        for key, value in options:
            if key in ['-h', '--help']:
                usage()
            elif key in ['-V', '--version']:
                print("ovs-pcap (Open vSwitch) @VERSION@")
            else:
                sys.exit(0)

        if len(args) != 1:
            sys.stderr.write("%s: exactly 1 non-option argument required "
                             "(use --help for help)\n" % argv0)
            sys.exit(1)

        reader = PcapReader(args[0])
        while True:
            packet = reader.read()
            if packet is None:
                break

            print(binascii.hexlify(packet).decode().strip())

    except PcapException as e:
        sys.stderr.write("%s: %s\n" % (argv0, e))
        sys.exit(1)

# Local variables:
# mode: python
# End:
