#!/usr/bin/env awk
#
# Returns true if the protocol number is equal to 'p' (int or hex)
# If 'p' is omitted, returns the protocol number
#
# Parameters:
#   - [p] : the protocol number(s) to test (comma or semicolon separated)
#           (ranges may also be specified using a dash (see examples below))
#
# Dependencies:
#   - basicFlow
#
# See Also:
#   - proto2str: string representation of a protocol
#   - icmp     : alias for proto(1)
#   - igmp     : alias for proto(2)
#   - tcp      : alias for proto(6)
#   - udp      : alias for proto(17)
#   - rsvp     : alias for proto(46)
#   - gre      : alias for proto(47)
#   - esp      : alias for proto(50)
#   - ah       : alias for proto(51)
#   - icmp6    : alias for proto(58)
#   - sctp     : alias for proto(132)
#
# Examples:
#   - tawk 'proto(6)' file.txt            # test for TCP
#   - tawk 'proto("6;17")' file.txt       # test for TCP or UDP
#   - tawk 'proto("1-6")' file.txt        # test for ICMP(1), IGMP(2), ..., or  TCP(6)
#   - tawk 'proto("1-3;5;7-9")' file.txt  # test for protocols 1 to 3, 5, or 7 to 9
#   - tawk '{ print proto() }' file.txt   # print the protocol

@include "hdr"
@include "_validate_col"

function proto(p,        _i, _l, _pr, _protocols, _rng) {
    _pr = _validate_col("l4Proto", _my_l4Proto)
    if (!p || (__PRIHDR__ && hdr())) return $_pr
    _pr = strtonum($_pr)
    if (isnum(p)) return (_pr == p)
    _l = split(p, _protocols, /[,;]/)
    for (_i = 1; _i <= _l; _i++) {
        if (match(_protocols[_i], /^(0x[[:xdigit:]]+|[0-9]+)-(0x[[:xdigit:]]+|[0-9]+)$/, _rng)) { # range
            if (_pr >= strtonum(_rng[1]) && _pr <= strtonum(_rng[2])) {
                return 1
            }
        } else if (_pr == strtonum(_protocols[_i])) {
            return 1
        }
    }
    return 0
}
