#!/usr/bin/env bash
# find-socket-functions: Grep for socket API function calls
#
# Copyright (C) 2017-2026 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: dreibh@simula.no

DIRECTORIES=$@
FUNCTION_NAMES="accept accept4 bind close connect creat dup dup2 dup3 epoll_create epoll_create1 epoll_ctl epoll_pwait epoll_wait fchown fcntl fdatasync flock fpathconf fstat fsync ftruncate ftruncate64 getpeername getsockname getsockopt ioctl listen lockf lseek lseek64 open pipe poll pread pread64 preadv preadv64 pwrite pwrite64 pwritev pwritev64 read readv recv recvfrom recvmsg recvv select send sendmsg sendto sendv setsockopt shutdown socket syncfs write writev"
RULES_FILE="rules.grep"

# echo "$FUNCTION_NAMES" | xargs -n1 | sort -u | xargs >f.out

rm -f $RULES_FILE
for fname in $FUNCTION_NAMES ; do
   echo "[^a-zA-Z0-9_\.>]${fname}[[:space:]]*\([[:space:]]*[^)]" >>$RULES_FILE
done

for directory in $DIRECTORIES ; do
   # NOTE:
   # - The first grep for the rule set filters without colours.
   # - The last grep for the rule set colorises the output.
   grep -n -r -H -E -f $RULES_FILE $directory |\
      grep -v -E "^[^:]*:[0-9]+:[[:space:]]*virtual[[:space:]]*.*=[[:space:]]*0[[:space:]]*;" |\
      grep -v -E "^[^:]*:[0-9]+:[[:space:]]*(int |virtual |static |bool |size_t |ssize_t |void |string |srs_error_t )[^=]*$" |\
      grep --color=auto -E -f $RULES_FILE
done
