#!/bin/bash

## Copyright (C) 2012 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

check_ip_forwarding_disabled() {
   if [ ! -f "/usr/share/anon-gw-base-files/gateway" ]; then
      local MSG="<p>IP Forwarding Result: not running on Whonix-Gatway, skipping, ok.</p>"
      if [ "$verbose" -ge "1" ]; then
         $output_x ${output_opts[@]} --messagex --typex "info" --message "$MSG"
         $output_cli ${output_opts[@]} --messagecli --typecli "info" --message "$MSG"
      fi
      return 0
   fi

   local file_list file_name
   file_list="/proc/sys/net/ipv4/ip_forward /proc/sys/net/ipv6/ip_forward"

   for file_name in $file_list; do
      local ip_forwarding=""
      local temp=""
      local MSG=""

      if [ ! -f "$file_name" ]; then
         local temp="$file_name does not exist."
         if [ "$file_name" = "/proc/sys/net/ipv6/ip_forward" ]; then
            ## If /proc/sys/net/ipv4/ip_forward would not exist, systemcheck
            ## would probably run on an unsupported platform.
            ## /proc/sys/net/ipv6/ip_forward not existing is expected, because
            ## Whonix does not enable IPv6 by default yet, because the Tor
            ## network does not yet support IPv6.
            continue
         fi
      else
         ip_forwarding="$(cat "$file_name")"

         if [ "$ip_forwarding" = "0" ]; then
            local MSG="<p>IP Forwarding Result: $file_name is 0, ok.</p>"
            if [ "$verbose" -ge "1" ]; then
               $output_x ${output_opts[@]} --messagex --typex "info" --message "$MSG"
               $output_cli ${output_opts[@]} --messagecli --typecli "info" --message "$MSG"
            fi
            continue
         else
            local temp="$file_name is $ip_forwarding."
         fi
      fi

      if [ "$NO_EXIT_ON_IP_FORWARDING_DETECTION" = "1" ]; then
         local MSG="IP Forwarding Result: $temp"

         $output_x ${output_opts[@]} --messagex --typex "info" --message "$MSG"
         $output_cli ${output_opts[@]} --messagecli --typecli "info" --message "$MSG"
         continue
      else
         local if_you_know_what_you_are_doing_msg
         if_you_know_what_you_are_doing_msg="$(if_you_know_what_you_are_doing_funct "$FUNCNAME")"
         ## "IP Forwarding Result:$temp    ## was in MSG below
         local MSG="<p><b>IP Forwarding enabled! This is unsupported by $PROJECT_NAME developers! systemcheck aborted!</b>
<br></br>Using IP Forwarding on Whonix-Gateway is recommended against, due to risks of leaks.
<br></br>This might endanger your anonymity.
<br />
<br />$if_you_know_what_you_are_doing_msg</p>"

         $output_x ${output_opts[@]} --messagex --typex "error" --message "$MSG"
         $output_cli ${output_opts[@]} --messagecli --typecli "error" --message "$MSG"
         EXIT_CODE="1"
         cleanup "1"
         continue
      fi

   done
}
