Project

General

Profile

Bug #16426 » startup_gif.sh

Danilo Zrenjanin, 09/13/2025 01:13 PM

 
1
#!/bin/sh
2
#
3
# create_gif_fix.sh
4
# This script creates or configures a GIF (Generic Interface) tunnel interface based on settings
5
# in /cf/conf/config.xml,in pfSense systems. It ensures that 'ifconfig' output
6
# for the GIF interface aligns with the pfSense GUI, including proper tunnel configuration and
7
# RUNNING status when an outer IPv6 address is present.
8
#
9
# Usage: sh create_gif_fix.sh [gif_ifname]
10
# If no interface name is provided, defaults to 'gif0'.
11

    
12
# -----------------------------------------------------------------------------------------------------------
13
# Configuration
14

    
15
set -eu 									# Enable strict error handling: exit on error (-e) and treat unset variables as errors (-u).
16
 
17
GIF_INTERFACE_ID="${1:-gif0}"				# Set the GIF interface name, defaulting to 'gif0' if not provided as an argument.
18
AFTR_HOST_FQDN="aftr.fra.purtel.com"   		# Address Family Transition Router of ISP Deustche Giganetz
19

    
20
PFSENSE_CONFIG_FILE="/cf/conf/config.xml"	# Define the path to the pfSense configuration file.
21

    
22
DEBUG_OUTPUT_TO_PFSENSE_LOG=0      			# 1 to enable logging to syslog
23
DEBUG_OUTPUT_TO_CONSOLE=1     				# 1 to enable console output
24

    
25
# -----------------------------------------------------------------------------------------------------------
26
# Helper Functions
27

    
28
# -----------------------------------------------
29
# Write Data to console or to pfsense logger (or both)
30
debug_out() {
31
    local message="StartupGifAfterBoot-->DEBUG: $1"
32
    [ "$DEBUG_OUTPUT_TO_PFSENSE_LOG" = "1" ] && logger -t StartupGifAfterBoot "$message"
33
    [ "$DEBUG_OUTPUT_TO_CONSOLE" = "1" ] && echo "$message"
34
}
35

    
36
# -----------------------------------------------
37
# Helper functions for XML parsing, IP handling, and interface queries.
38
# Check if 'xmllint' is installed; required for XML parsing. Exit with error if missing.
39
command -v xmllint >/dev/null 2>&1 || { debug_out "xmllint required"; exit 1; }
40

    
41
# -----------------------------------------------
42
# Extract a string value from the XML config using an XPath expression.
43
# Parameters: $1 - XPath expression.
44
# Returns: The value or an empty string if not found or an error occurs.
45
get_xml() {
46
  xpath="$1"
47
  xmllint --xpath "string($xpath)" "$PFSENSE_CONFIG_FILE" 2>/dev/null || echo ""
48
}
49

    
50
# -----------------------------------------------
51
# Count the number of XML nodes matching an XPath expression.
52
# Parameters: $1 - XPath expression.
53
# Returns: The count or 0 if an error occurs.
54
xml_count() {
55
  xpath="$1"
56
  xmllint --xpath "count($xpath)" "$PFSENSE_CONFIG_FILE" 2>/dev/null || echo 0
57
}
58

    
59
# -----------------------------------------------
60
# Convert a CIDR prefix length to a dotted decimal netmask (e.g., 24 to 255.255.255.0).
61
# Parameters: $1 - CIDR value.
62
# Returns: The netmask or an empty string if the input is invalid.
63
cidr2dotted() {
64
  cidr="$1"
65
  # Return empty if CIDR is unset.
66
  [ -n "$cidr" ] || { debug_out ""; return; }
67
  # Check if CIDR is a valid number; return empty if not.
68
  case "$cidr" in *[!0-9]*|'') debug_out ""; return ;; esac
69
  # Validate CIDR range (0-32); return empty if invalid.
70
  if [ "$cidr" -lt 0 ] || [ "$cidr" -gt 32 ]; then debug_out ""; return; fi
71
  out=""
72
  # Process each octet (4 total).
73
  for _ in 1 2 3 4; do
74
    # If CIDR >= 8, use 255 for the octet.
75
    if [ "$cidr" -ge 8 ]; then
76
      out="${out}255."
77
      cidr=$((cidr-8))
78
    else
79
      # Calculate partial octet if CIDR > 0, else use 0.
80
      if [ "$cidr" -gt 0 ]; then
81
        oct=$((256 - (1 << (8 - cidr))))
82
      else
83
        oct=0
84
      fi
85
      out="${out}${oct}."
86
      cidr=0
87
    fi
88
  done
89
  # Remove trailing dot and output the netmask.
90
  printf "%s" "${out%?}"
91
}
92

    
93
# -----------------------------------------------
94
# Check if an address is IPv6 based on the presence of colons.
95
# Parameters: $1 - IP address.
96
# Returns: 0 if IPv6, 1 if not.
97
is_ipv6() {
98
  case "$1" in *:*) return 0;; *) return 1;; esac
99
}
100

    
101
# -----------------------------------------------
102
# Get the first global (non-link-local) IPv6 address from an interface.
103
# Parameters: $1 - Interface name.
104
# Returns: The IPv6 address or empty if none found or interface doesn't exist.
105
get_if_ipv6_global() {
106
  ifname="$1"
107
  # Check if the interface exists; return empty if not.
108
  if ! ifconfig "$ifname" >/dev/null 2>&1; then debug_out ""; return; fi
109
  # Extract the first non-link-local (not fe80) IPv6 address from ifconfig output.
110
  ifconfig "$ifname" | awk '/inet6/ && $2 !~ /^fe80/ {print $2; exit}' | cut -d'/' -f1 || true
111
}
112

    
113
# -----------------------------------------------
114
# Get any IPv6 address (including link-local) from an interface.
115
# Parameters: $1 - Interface name.
116
# Returns: The first IPv6 address or empty if none found or interface doesn't exist.
117
get_if_ipv6_any() {
118
  ifname="$1"
119
  # Check if the interface exists; return empty if not.
120
  if ! ifconfig "$ifname" >/dev/null 2>&1; then debug_out ""; return; fi
121
  # Extract the first IPv6 address from ifconfig output.
122
  ifconfig "$ifname" | awk '/inet6/ {print $2; exit}' | cut -d'/' -f1 || true
123
}
124

    
125
# -----------------------------------------------
126
# Check, if an interface is up and running
127
check_interface_ready() {
128
    local iface=$1
129
    # Check if interface is UP and RUNNING (flags)
130
    if ifconfig "$iface" 2>/dev/null | grep -q "<.*UP.*RUNNING.*>"; then
131
        # Check if interface has inet (IPv4) or inet6
132
        if ifconfig "$iface" 2>/dev/null | grep -q -e "inet " -e "inet6 "; then
133
            return 0  # interface is ready
134
        fi
135
    fi
136
    return 1  # not ready
137
}
138

    
139

    
140

    
141

    
142
# -----------------------------------------------------------------------------------------------------------
143
# Reentrancy or double start protection
144

    
145
# -----------------------------------------------
146
# Reentrancy or double start protection
147
PIDFILE="/var/run/$(basename $0).pid"
148
if [ -f "$PIDFILE" ]; then
149
    debug_out "Another instance is already running. Exiting."
150
    exit 0
151
fi
152
echo $$ > "$PIDFILE"
153
trap 'rm -f "$PIDFILE"; exit' INT TERM EXIT
154

    
155

    
156

    
157
# -----------------------------------------------------------------------------------------------------------
158
# Main functionality
159

    
160
# -----------------------------------------------
161
# Read Configuration from config.xml 
162
# Extract relevant GIF and interface settings from the pfSense XML configuration.
163

    
164
# Define XPath to locate the GIF configuration for the specified interface.
165
GIF_XPATH="/pfsense/gifs/gif[gifif='$GIF_INTERFACE_ID']"
166
# Verify that a GIF entry exists for the interface; exit if not found.
167
[ "$(xml_count "$GIF_XPATH")" != "0" ] || { debug_out "No <gif> entry for $GIF_INTERFACE_ID in $PFSENSE_CONFIG_FILE"; exit 1; }
168
# Extract tunnel local address (inner local IP).
169
INNER_LOCAL="$(get_xml "$GIF_XPATH/tunnel-local-addr")"
170
# Extract tunnel remote address (inner remote IP).
171
INNER_REMOTE="$(get_xml "$GIF_XPATH/tunnel-remote-addr")"
172
# Extract tunnel remote network CIDR (inner netmask).
173
INNER_REMOTE_NET="$(get_xml "$GIF_XPATH/tunnel-remote-net")"
174
# Extract outer remote address (remote tunnel endpoint).
175
OUTER_REMOTE="$(get_xml "$GIF_XPATH/remote-addr")"
176
# Extract logical parent interface name.
177
PARENT_LOGICAL="$(get_xml "$GIF_XPATH/if")"
178
# Extract GIF description.
179
GIF_DESCR="$(get_xml "$GIF_XPATH/descr")"
180
# Define XPath for the interface configuration.
181
IFACE_XPATH="/pfsense/interfaces/*[if='$GIF_INTERFACE_ID']"
182
# Extract interface description.
183
IFACE_DESCR="$(get_xml "$IFACE_XPATH/descr")"
184
# Extract MTU setting.
185
IFACE_MTU="$(get_xml "$IFACE_XPATH/mtu")"
186
# Extract MSS setting (though not used later in the script).
187
IFACE_MSS="$(get_xml "$IFACE_XPATH/mss")"
188
# Extract the descriptive name of the gif interface
189
GIF_DESCRIPTIVE_NAME="$(get_xml "$GIF_XPATH/descr")"
190

    
191
# Set description: use interface description if available, else fall back to GIF description.
192
[ -n "$IFACE_DESCR" ] && DESC="$IFACE_DESCR" || DESC="$GIF_DESCR"
193

    
194

    
195
# Determine the physical parent interface.
196
PHYS_PARENT=""
197
# If a logical parent is specified and exists in the interfaces section.
198
if [ -n "$PARENT_LOGICAL" ] && [ "$(xml_count "/pfsense/interfaces/$PARENT_LOGICAL")" != "0" ]; then
199
  # Get the physical interface name from the logical parent's config.
200
  PHYS_PARENT="$(get_xml "/pfsense/interfaces/$PARENT_LOGICAL/if")"
201
else
202
  # Use the logical parent as the physical parent if no mapping exists.
203
  PHYS_PARENT="$PARENT_LOGICAL"
204
fi
205

    
206
# Display extracted configuration for debugging and verification.
207
debug_out "Config:"
208
debug_out "  gif node:                 $GIF_XPATH"
209
debug_out "  gifif:                    $GIF_INTERFACE_ID"
210
debug_out "  parent logical:           $PARENT_LOGICAL -> physical: $PHYS_PARENT"
211
debug_out "  outer remote:             $OUTER_REMOTE"
212
debug_out "  inner local:              $INNER_LOCAL"
213
debug_out "  inner remote:             $INNER_REMOTE"
214
debug_out "  inner /CIDR:              $INNER_REMOTE_NET"
215
debug_out "  GIF Interface name:       $DESC"
216
debug_out "  GIF tunnel description:   $GIF_DESCRIPTIVE_NAME"
217
debug_out "  mtu:                      $IFACE_MTU"
218

    
219

    
220
# -----------------------------------------------
221
# Ensure the outer remote address is set; exit if missing.
222
if [ -z "$OUTER_REMOTE" ]; then
223
  debug_out "ERROR: remote-addr (outer remote) missing in gif config"
224
  exit 1
225
fi
226

    
227

    
228
# -----------------------------------------------
229
# Wait for All Interfaces to be Ready
230
debug_out "Waiting for necessary interfaces to come up for GIF startup..."
231

    
232
# List expected interfaces (excluding the GIF you're about to create)
233
#EXPECTED_INTERFACES=$(xmllint --xpath "//interfaces/*[not(enable) or enable != 'false']/if[not(starts-with(text(),'gif'))]/text()" /cf/conf/config.xml 2>/dev/null | tr '\n' ' ')
234
EXPECTED_INTERFACES="igc3 igc2 pppoe0 lagg0.10 lagg0.20 lagg0.30 lagg0.40 lagg0.50 lagg0.60"
235

    
236
max_wait=120  # 2 minutes timeout
237
wait_time=0
238

    
239
while [ $wait_time -lt $max_wait ]; do
240
    all_ready=true
241
    
242
    for iface in $EXPECTED_INTERFACES; do
243
        if ! check_interface_ready "$iface"; then
244
            all_ready=false
245
            debug_out "Interface $iface not ready yet..."
246
            break
247
        fi
248
    done
249
    
250
    if [ "$all_ready" = true ]; then
251
        debug_out "All interfaces are ready for GIF Startup"
252
        break
253
    fi
254
    
255
    sleep 5
256
    wait_time=$((wait_time + 5))
257
done
258

    
259
if [ $wait_time -ge $max_wait ]; then
260
    debug_out "Warning: Timeout waiting for all interfaces"
261
fi
262

    
263

    
264

    
265
# -----------------------------------------------
266
# Determine and Wait for Local Outer Address
267
# Determine the local outer IP address, waiting for an IPv6 address if needed.
268

    
269
# Initialize the local outer address variable.
270
LOCAL_OUTER=""
271
# If the outer remote address is IPv6.
272
if is_ipv6 "$OUTER_REMOTE"; then
273
  # Set retry parameters for waiting on a global IPv6 address.
274
  retries=25
275
  attempt=0
276
  # Attempt to find a global IPv6 address, retrying up to 25 times.
277
  while [ "$attempt" -lt "$retries" ]; do
278
    attempt=$((attempt+1))
279
    LOCAL_OUTER="$(get_if_ipv6_global "$PHYS_PARENT")"
280
    # Break if a global IPv6 address is found.
281
    if [ -n "$LOCAL_OUTER" ]; then break; fi
282
    # debug_out retry attempt and wait 5 seconds.
283
    debug_out "Waiting for global IPv6 on $PHYS_PARENT (attempt $attempt/$retries)..."
284
    sleep 5
285
  done
286

    
287
  # If no global IPv6 is found, fall back to any IPv6 (including link-local).
288
  if [ -z "$LOCAL_OUTER" ]; then
289
    debug_out "No global IPv6 — falling back to any IPv6 (possibly link-local)"
290
    LOCAL_OUTER="$(get_if_ipv6_any "$PHYS_PARENT")"
291
    # If a link-local address (fe80), append the interface scope.
292
    if [ -n "$LOCAL_OUTER" ]; then
293
      case "$LOCAL_OUTER" in fe80:*) LOCAL_OUTER="${LOCAL_OUTER}%${PHYS_PARENT}" ;; esac
294
    fi
295
  fi
296

    
297
  # Exit if no IPv6 address is found.
298
  if [ -z "$LOCAL_OUTER" ]; then
299
    debug_out "ERROR: no IPv6 address found on $PHYS_PARENT"
300
    exit 1
301
  fi
302
else
303
  # For IPv4: extract the first non-loopback IPv4 address from the parent interface.
304
  if ifconfig "$PHYS_PARENT" >/dev/null 2>&1; then
305
    LOCAL_OUTER="$(ifconfig "$PHYS_PARENT" | awk '/inet / && $2 != "127.0.0.1" {print $2; exit}')"
306
  fi
307
  # Exit if no IPv4 address is found.
308
  [ -n "$LOCAL_OUTER" ] || { debug_out "ERROR: no IPv4 on $PHYS_PARENT"; exit 1; }
309
fi
310

    
311
# -----------------------------------------------------------------------------------------------------------
312
# -----------------------------------------------
313
# AFTR IP Updater
314
debug_out "=== pfSense DS-Lite AFTR Address Updater ==="
315

    
316
# -----------------------------------------------
317
#Get tunnel remote address
318
debug_out "Checking AFTR address for: $GIF_DESCRIPTIVE_NAME"
319
AFTR_IPv6=$(dig +short AAAA "$AFTR_HOST_FQDN" | head -n1 | tr -d '\r')
320
if [ -z "$AFTR_IPv6" ]; then
321
    debug_out "Error: Could not resolve AFTR FQDN address for '$AFTR_HOST_FQDN'"
322
    exit 1
323
fi
324
debug_out "FQDN resolved AFTR address: $AFTR_IPv6"
325

    
326
# -----------------------------------------------
327
#Check and handle potential updated AFTR IP
328
if [ "$OUTER_REMOTE" = "$AFTR_IPv6" ]; then
329
    debug_out "OK: Addresses match - no update needed"
330
else
331
	debug_out "Mismatch: Addresses differ - update required"
332
	debug_out "Current: $OUTER_REMOTE | resolved: $AFTR_IPv6"
333
	# Backup and update configuration
334
	debug_out "Creating backup: $CONFIG_BACKUP"
335
	cp "$PFSENSE_CONFIG_FILE" "$CONFIG_BACKUP" || { debug_out "Error: Backup failed"; rm -f "$PIDFILE"; exit 1; }
336

    
337
	debug_out "Updating configuration..."
338
	# BSD sed -i '' usage; escape possible slashes in addresses by using | delimiter
339
	sed -i '' "s|<remote-addr>$GIF_REMOTE</remote-addr>|<remote-addr>$AFTR_IPv6</remote-addr>|g" "$PFSENSE_CONFIG_FILE"
340
	NEW_AFTR_IP="$(get_xml "$GIF_XPATH/remote-addr")"
341
	if [ "$NEW_AFTR_IP" != "$AFTR_IPv6" ]; then
342
		debug_out "Error: Update failed, restoring backup"
343
		cp "$CONFIG_BACKUP" "$PFSENSE_CONFIG_FILE"
344
		exit 1
345
	fi
346
	debug_out "OK: Configuration updated successfully"
347
	debug_out "Old: $GIF_REMOTE | New: $NEW_AFTR_IP"
348
fi
349
debug_out "=== AFTR IP Update Complete ==="	
350

    
351
# debug_out the determined local outer address and parent interface.
352
debug_out "Using outer local: $LOCAL_OUTER (parent $PHYS_PARENT)"
353

    
354
# -----------------------------------------------------------------------------------------------------------
355
# -----------------------------------------------
356
# Destroy and Recreate GIF Interface
357

    
358
# Destroy any existing GIF interface and create a new one.
359
# Check if the GIF interface already exists.
360
if ifconfig "$GIF_INTERFACE_ID" >/dev/null 2>&1; then
361
  # Attempt to destroy the existing interface.
362
  debug_out "Destroying existing $GIF_INTERFACE_ID ..."
363
  ifconfig "$GIF_INTERFACE_ID" destroy || debug_out "Warning: failed to destroy"
364
fi
365

    
366
# -----------------------------------------------
367
# Create a new GIF interface.
368
debug_out "Creating $GIF_INTERFACE_ID ..."
369
# Exit if creation fails.
370
if ! ifconfig "$GIF_INTERFACE_ID" create; then debug_out "ERROR: create failed"; exit 1; fi
371

    
372
# -----------------------------------------------
373
# Configure the outer tunnel endpoints (local and remote).
374

    
375
debug_out "Configuring outer tunnel..."
376
# If the outer remote is IPv6, configure an IPv6 tunnel.
377
if is_ipv6 "$OUTER_REMOTE"; then
378
  if ! ifconfig "$GIF_INTERFACE_ID" inet6 tunnel "$LOCAL_OUTER" "$OUTER_REMOTE"; then
379
    # On failure, debug_out error, destroy interface, and exit.
380
    debug_out "ERROR: failed tunnel $LOCAL_OUTER -> $OUTER_REMOTE"
381
    ifconfig "$GIF_INTERFACE_ID" destroy >/dev/null 2>&1 || true
382
    exit 1
383
  fi
384
else
385
  # Configure an IPv4 tunnel.
386
  if ! ifconfig "$GIF_INTERFACE_ID" tunnel "$LOCAL_OUTER" "$OUTER_REMOTE"; then
387
    # On failure, debug_out error, destroy interface, and exit.
388
    debug_out "ERROR: failed tunnel $LOCAL_OUTER -> $OUTER_REMOTE"
389
    ifconfig "$GIF_INTERFACE_ID" destroy >/dev/null 2>&1 || true
390
    exit 1
391
  fi
392
fi
393

    
394
# -----------------------------------------------
395
# Configure inner IPv4 addresses for the tunnel if specified.
396

    
397
# If either inner local or remote address is set.
398
if [ -n "$INNER_LOCAL" ] || [ -n "$INNER_REMOTE" ]; then
399
  # If both inner local and remote are set (point-to-point).
400
  if [ -n "$INNER_LOCAL" ] && [ -n "$INNER_REMOTE" ]; then
401
    NETMASK=""
402
    # Convert CIDR to netmask if provided and valid.
403
    if printf "%s" "$INNER_REMOTE_NET" | grep -qE '^[0-9]+$'; then
404
      NETMASK="$(cidr2dotted "$INNER_REMOTE_NET")"
405
    fi
406
    # If a valid netmask exists, configure with netmask.
407
    if [ -n "$NETMASK" ]; then
408
      debug_out "Assigning inner IPv4 p2p: $INNER_LOCAL <-> $INNER_REMOTE netmask $NETMASK"
409
      ifconfig "$GIF_INTERFACE_ID" "$INNER_LOCAL" "$INNER_REMOTE" netmask "$NETMASK" || true
410
    else
411
      # Configure without netmask if none provided.
412
      debug_out "Assigning inner IPv4 p2p: $INNER_LOCAL <-> $INNER_REMOTE"
413
      ifconfig "$GIF_INTERFACE_ID" "$INNER_LOCAL" "$INNER_REMOTE" || true
414
    fi
415
  else
416
    # If only one address is provided, assign it as a single address.
417
    ONE="$( [ -n "$INNER_LOCAL" ] && echo "$INNER_LOCAL" || echo "$INNER_REMOTE" )"
418
    debug_out "Assigning single inner address $ONE"
419
    ifconfig "$GIF_INTERFACE_ID" "$ONE" || true
420
  fi
421
fi
422
# -----------------------------------------------
423
# Set the interface description, MTU
424

    
425
# Set the interface description if available.
426
[ -n "$DESC" ] && { echo "Setting description: $DESC"; ifconfig "$GIF_INTERFACE_ID" description "$DESC" || true; }
427

    
428
# Set MTU if provided and valid.
429
if [ -n "$IFACE_MTU" ]; then
430
  case "$IFACE_MTU" in
431
    # Skip if MTU contains non-numeric characters.
432
    *[!0-9]*) echo "Skipping invalid MTU: $IFACE_MTU" ;;
433
    # Set valid MTU.
434
    *) echo "Setting MTU: $IFACE_MTU"; ifconfig "$GIF_INTERFACE_ID" mtu "$IFACE_MTU" || true ;;
435
  esac
436
fi
437

    
438
# -----------------------------------------------
439
# Bring the GIF interface up.
440
debug_out "Bringing $GIF_INTERFACE_ID up..."
441
ifconfig "$GIF_INTERFACE_ID" up || true
442

    
443
# ---- Restart pfSense WAN Interfaces ---------------------------------------
444
# Restart all WAN interfaces to register the new gateway in pfSense.
445

    
446
# Execute pfSense command to restart all WAN interfaces.
447
/usr/local/sbin/pfSsh.php playback restartallwan
448

    
449
# Exit with success status.
450
exit 0
(5-5/5)