#!/usr/bin/env awk
#
# Returns true if the source port is equal to 'p' (int or hex)
# If 'p' is omitted, returns the source port
#
# Parameters:
#   - [p] : the port number(s) to test (comma or semicolon separated)
#           (ranges may also be specified using a dash (see examples below))
#
# Dependencies:
#   - basicFlow
#
# See Also:
#   - dport: destination port
#   - port : source or destination port
#
# Examples:
#   - tawk 'sport(80)' file.txt           # test for source port 80
#   - tawk 'sport("53;80")' file.txt      # test for source ports 53 or 80
#   - tawk 'sport("6000-6008")' file.txt  # test for source ports 6000, 6001, ... or 6008
#   - tawk 'sport("1-3;5;7-9")' file.txt  # test for source ports 1 to 3, 5, or 7 to 9
#   - tawk '{ print sport() }' file.txt   # print the source port

@include "hdr"
@include "isnum"
@include "_validate_col"

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