From 7bff96adafbcb335deaedb858c87eeae339b512a Mon Sep 17 00:00:00 2001 From: Marco Paganini Date: Sat, 20 Nov 2021 12:13:34 -0800 Subject: [PATCH] Add option to call external command on port change. Add support for the PF_POST_COMMAND environment variable in port_forwarding.sh. This will cause an external command to be called with the new forwarding port and the original forwarding port (as command-line arguments) every time the forwarding port changes. Use cases: - Update firewall configuration. - Update configuration of anything that needs to bind to the correct port. --- port_forwarding.sh | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/port_forwarding.sh b/port_forwarding.sh index 2e48198..4706196 100755 --- a/port_forwarding.sh +++ b/port_forwarding.sh @@ -130,6 +130,8 @@ Trying to bind the port... " # We will repeat this request every 15 minutes, in order to keep the port # alive. The servers have no mechanism to track your activity, so they # will just delete the port forwarding if you don't send keepalives. + +old_port=0 while true; do bind_port_response="$(curl -Gs -m 5 \ --connect-to "$PF_HOSTNAME::$PF_GATEWAY:" \ @@ -146,6 +148,15 @@ while true; do echo -e "${RED}The API did not return OK when trying to bind port... Exiting." exit 1 fi + + if [[ "${PF_POST_COMMAND}" ]] && [[ "${port}" != "${old_port}" ]]; then + echo -e "${GREEN}Note: Port has changed from ${old_port} to ${port}. Running PF_POST_COMMAND.${NC}" + if ! "${PF_POST_COMMAND}" "${port}" "${old_port}"; then + echo -e "${RED}Warning: "${PF_POST_COMMAND}" returned non-zero.${NC}" + fi + old_port="${port}" + fi + echo -e Forwarded port'\t'${GREEN}$port${NC} echo -e Refreshed on'\t'${GREEN}$(date)${NC} echo -e Expires on'\t'${RED}$(date --date="$expires_at")${NC}