/
link-balancer
executable file
·1955 lines (1588 loc) · 46.5 KB
/
link-balancer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
#
# Link Balancer - Policy Based Routing for humans...
#
# Copyright
#
# Copyright (C) 2015 Costa Tsaousis <costa@tsaousis.gr>
# Copyright (C) 2015 Phil Whineray <phil@sanewall.org>
#
# License
#
# 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 2 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/>.
#
# See the file COPYING for details.
#
READLINK_CMD=${READLINK_CMD:-readlink}
BASENAME_CMD=${BASENAME_CMD:-basename}
DIRNAME_CMD=${DIRNAME_CMD:-dirname}
function realdir {
local r="$1"; local t=$($READLINK_CMD "$r")
while [ "$t" ]; do
r=$(cd $($DIRNAME_CMD "$r") && cd $($DIRNAME_CMD "$t") && pwd -P)/$($BASENAME_CMD "$t")
t=$($READLINK_CMD "$r")
done
$DIRNAME_CMD "$r"
}
PROGRAM_FILE="$0"
PROGRAM_DIR="${FIREHOL_OVERRIDE_PROGRAM_DIR:-$(realdir "$0")}"
PROGRAM_PWD="${PWD}"
declare -a PROGRAM_ORIGINAL_ARGS=("${@}")
for functions_file in install.config functions.common
do
if [ -r "$PROGRAM_DIR/$functions_file" ]
then
source "$PROGRAM_DIR/$functions_file"
else
1>&2 echo "Cannot access $PROGRAM_DIR/$functions_file"
exit 1
fi
done
common_disable_localization || exit
common_private_umask || exit
common_require_root || exit
# make sure sbin is included in the path
# it seems that pppd ip-up.d script need this
export PATH="$PATH:/sbin:/usr/sbin:/usr/local/sbin"
if [ "$LB_DEBUGGING" ]; then set -v; set -x; fi
# link-balancer temporary directory.
# every instance of link-balancer creates a random directory
# within this one.
LB_RUN_DIR="$LOCALSTATEDIR/run/link-balancer"
# If this is set to 1, no checks will be made if the gateways are available.
# All gateways will be assumed active, if their interfaces are found
# operational.
# WHY: When we have a multi-ppp environment the default gateway of the system
# will be composed my multiple 'nexthop' routes. When a ppp device fails
# the kernel will remove the entire default gateway, not just the 'nexthop'
# that is not available any more.
# By calling link-balancer with option '-f' will enable this option.
# This option will make link-balancer restore the default gateway as soon
# as possible.
# 'link-balancer -f' should thus by called by ppp/ip-down scripts.
FORCE_ALWAYSON=0
# If set to 1, link-balancer will not change anything. It will just show
# what it will execute if run without it.
DRY_RUN=0
# If set to 1, link-balancer will output to standard-error all temporary files
# it generates during its execution.
DEBUG_ALL_DATA=0
# The step which increments the priority of the rules for each rule statement
# in the configuration file.
LB_RULE_STEP=100
# Keeps a list of all tables that have been altered during its run.
declare -A LB_ALTERED=()
# Where is the link-balancer configuration files?
LB_CONFIG_DIR="${FIREHOL_CONFIG_DIR}"
# Link-balancer main configuration file.
LB_CONFIG="${LB_CONFIG_DIR}/link-balancer.conf"
# takes either 4 or 6 to switch the functions in ipv4 or ipv6
LB_DEFAULT_IPV=4
marksreset() { :; }
markdef() { :; }
if [ -r "${FIREHOL_CONFIG_DIR}/firehol-defaults.conf" ]
then
source "${FIREHOL_CONFIG_DIR}/firehol-defaults.conf" || exit 1
fi
# temporary variable (default LB_DEFAULT_IPV=4)
LB_IPV=
RUNNING_ON_TERMINAL=0
if [ "z$1" = "z-nc" ]
then
shift
else
common_setup_terminal && RUNNING_ON_TERMINAL=1
fi
# if called with the parameter 'boot', create a new screen that
# will run forever.
if [ "$1" = "boot" ]
then
shift
common_require_cmd $PROGRAM_FILE SCREEN_CMD
$SCREEN_CMD -S 'link-balancer' -d -m "$0" loop "${@}"
exit 0
fi
# if called with the parameter 'loop', run forever.
if [ "$1" = "loop" ]
then
shift
secs="${1}"
secs=$[ secs + 1 - 1 ]
test "${secs}" = "0" && secs=300
shift
while [ 1 ]
do
$0 "${@}"
echo "Waiting for $secs secs..."
$SLEEP_CMD $secs
done
exit 0
fi
if [ ! -d "${LB_RUN_DIR}" ]
then
$MKDIR_CMD -p "${LB_RUN_DIR}" || exit 1
$CHOWN_CMD root:root "${LB_RUN_DIR}" || exit 1
$CHMOD_CMD 700 "${LB_RUN_DIR}" || exit 1
fi
# get an exclusive lock or wait for it to be available
LOCKFILE="${LB_RUN_DIR}/link-balancer.lock"
[ "${FLOCKER}" != "${LOCKFILE}" ] && exec $ENV_CMD FLOCKER="${LOCKFILE}" $FLOCK_CMD -e "${LOCKFILE}" "$0" "$@" || :
cd "${LB_RUN_DIR}" || exit 1
LB_DIR="`$MKTEMP_CMD -d "${LB_RUN_DIR}/temp-XXXXXXXXXX"`" || exit 1
# -----------------------------------------------------------------------------
# Default FireHOL marks
declare -A MARKS_BITS='([connmark]="6" [usermark]="7" )'
declare -A MARKS_MASKS='([connmark]="0x0000003f" [usermark]="0x00001fc0" )'
declare -A MARKS_MAX='([connmark]="63" [usermark]="127" )'
declare -A MARKS_SHIFT='([connmark]="0" [usermark]="6" )'
FIREHOL_SPOOL_DIR="${FIREHOL_SPOOL_DIR-$LOCALSTATEDIR/spool/firehol}"
if [ -f "${FIREHOL_SPOOL_DIR}/marks.conf" ]
then
source "${FIREHOL_SPOOL_DIR}/marks.conf" || exit 1
fi
mark_value() {
local name="${1}"; shift
local x=
if [ -z "${name}" ]
then
error "Cannot find the value of mark with name '${name}'."
return 1
fi
if [ -z "${1}" ]
then
error "Empty mark value given for mark ${name}."
return 1
fi
if [ -z "${MARKS_MASKS[$name]}" ]
then
error "Mark $name does not exist."
return 1
fi
for x in ${@//,/ }
do
local x=$[ x + 1 - 1 ]
if [ $x -gt ${MARKS_MAX[$name]} -o $x -lt 0 ]
then
error "Cannot get mark $name of value $x. Mark $name is configured to get values from 0 to ${MARKS_MAX[$name]}. Change firehol-defaults.conf to add more."
return 1
fi
#echo "$[ x << ${MARKS_SHIFT[$name]} ]/${MARKS_MASKS[$name]}"
printf "0x%08x/${MARKS_MASKS[$name]}\n" "$[ x << ${MARKS_SHIFT[$name]} ]"
done
return 0
}
# -----------------------------------------------------------------------------
# Find in the BASH execution stack, the line and the source file that has called us.
# Before first use the variable PROGRAM_FILE should be set to the file to be excluded.
# It also sets the variable LAST_CONFIG_LINE on each run.
FORCE_CONFIG_LINEID=
LAST_CONFIG_LINE=
config_line() {
if [ ! -z "${FORCE_CONFIG_LINEID}" ]
then
LAST_CONFIG_LINE="${FORCE_CONFIG_LINEID}"
else
# find the config line in the BASH stack
# start from 2
# 0 is this line
# 1 is the caller - our line for sure
# 2 is the caller's caller - possibly a config file line
local i= all=${#BASH_SOURCE}
for (( i = 2; i < $all; i++ ))
do
[ ! "${BASH_SOURCE[$i]}" = "${PROGRAM_FILE}" ] && break
done
LAST_CONFIG_LINE="${BASH_LINENO[$[i-1]]}@${BASH_SOURCE[$i]}: ${FUNCNAME[$[i-1]]}:"
fi
test ! "z$1" = "z-ne" && echo "${LAST_CONFIG_LINE}"
}
LB_RESULT_CODE=1
lb_exit() {
cd /tmp
if [ ${DEBUG_ALL_DATA} -eq 1 ]
then
echo >&2
echo >&2
echo >&2 "---------------------------------------------------------------------"
echo >&2 "Temporary folder contents:"
$LS_CMD -l "${LB_DIR}/" >&2
for x in "${LB_DIR}"/*
do
echo >&2
echo >&2
echo >&2 "---------------------------------------------------------------------"
echo >&2 "${x}"
echo >&2
$CAT_CMD >&2 "${x}"
done
fi
if [ ! -z "${LB_DIR}" -a -d "${LB_DIR}" ]
then
$RM_CMD -rf "${LB_DIR}"
fi
enable trap
enable exit
trap exit EXIT
exit ${LB_RESULT_CODE}
}
trap lb_exit EXIT
trap lb_exit SIGHUP
trap lb_exit INT
# -----------------------------------------------------------------------------
# COMMON FUNCTIONS
syslog() {
if [ ${DRY_RUN} -eq 0 ]
then
$LOGGER_CMD -p daemon.info -t "LinkBalancer" "${*}"
fi
}
last_debug_depth=0
DEBUGCMDNNL() {
local prefix="${1}"; shift
local name="${1}"; shift
local depth="${1}"; shift
test "$depth" = "" && local depth=$last_debug_depth
last_debug_depth=$depth
# printf >&2 "`date`"
printf >&2 "% $((depth))s ${prefix} %s " " " "${name}"
printf >&2 " ${*} "
}
DEBUGCMD() {
DEBUGCMDNNL "-" "${@}"
printf >&2 "\n"
}
warning() {
local line="$(config_line)"
syslog "WARNING ${line} ${@}"
echo >&2
echo >&2 -e "${COLOR_YELLOW}${COLOR_BOLD}WARNING ${line} $@ ${COLOR_RESET}"
echo >&2
return 0
}
error() {
local line="$(config_line)"
syslog "ERROR ${line} ${@}"
echo >&2
echo >&2 -e "${COLOR_RED}${COLOR_BOLD}ERROR ${line} $@ ${COLOR_RESET}"
echo >&2
exit 1
}
run() {
printf >&2 "${COLOR_BOLD}"
DEBUGCMDNNL "#" "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}" " ... "
local tmp="`$MKTEMP_CMD "${LB_DIR}/run-$$-${RANDOM}-XXXXXXXXXX"`"
"${@}" >"$tmp" 2>"$tmp.err"
local ret=$?
if [ $ret -eq 0 ]
then
printf >&2 "${COLOR_RESET}${COLOR_BGGREEN}${COLOR_BLACK}${COLOR_BOLD} OK ${COLOR_RESET}\n"
else
printf >&2 "${COLOR_RESET}${COLOR_BGRED}${COLOR_WHITE}${COLOR_BOLD}${COLOR_BLINK} FAILED ${COLOR_RESET}\n"
fi
$CAT_CMD >&2 "$tmp.err"
$CAT_CMD "$tmp"
$RM_CMD "$tmp" "$tmp.err"
return $ret
}
action() {
if [ ${DRY_RUN} -eq 0 ]
then
printf >&2 "${COLOR_YELLOW}"
run "${@}"
local ret=$?
if [ $ret -ne 0 ]
then
warning "Command: '${@}' exited with code $ret."
else
syslog "Successfuly run: '${@}'."
fi
return $ret
fi
DEBUGCMDNNL "#" "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}" " ... "
printf >&2 "DEFERRED\n"
return 0
}
trim_spaces() {
$SED_CMD -e "s/[\t\\ ]\+/ /g" -e "s/ \+$//g" -e "s/^ \+//g"
}
loadfile() {
local file="$1"; shift
cd "${LB_CONFIG_DIR}"
test ! -f "${file}" && syslog "WARNING: file '${file}' does not exist."
$CAT_CMD "${file}" | $SED_CMD -e "s/#.*$//g" | trim_spaces | $TR_CMD '\n' ' '
local ret=$?
cd "${LB_RUN_DIR}"
return $ret
}
ipv4() {
DEBUGCMD "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}"
local cmd="${1}"; shift
case "${cmd}" in
gateway|table|rules|mark|fwmark|connmark|src|dst|from|to|tos|not)
"${cmd}" ipv4 "${@}"
return $?
;;
default)
error "Command '${cmd}' inherits IP version from its parent. Do not give ${FUNCNAME} for '${cmd}'."
exit 1
;;
*)
error "Command '${cmd}' cannot change IP version."
exit 1
;;
esac
}
ipv6() {
DEBUGCMD "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}"
local cmd="${1}"; shift
case "${cmd}" in
gateway|table|rules|mark|fwmark|connmark|src|dst|from|to|tos|not)
"${cmd}" ipv6 "${@}"
return $?
;;
default)
error "Command '${cmd}' inherits IP version from its parent. Do not give ${FUNCNAME} for '${cmd}'."
exit 1
;;
*)
error "Command '${cmd}' cannot change IP version."
exit 1
;;
esac
}
# -----------------------------------------------------------------------------
# gateway section
get_interface_ips() {
local ipv="4"
test "${LB_IPV}" = "6" && local ipv="6"
local inet="inet"
test "${LB_IPV}" = "6" && local inet="inet6"
run $IP_CMD -${ipv} addr show dev "$1" |\
trim_spaces |\
$GREP_CMD "${inet} " |\
$CUT_CMD -d ' ' -f 2 |\
$CUT_CMD -d '/' -f 1 |\
$TR_CMD '\n' ' '
}
get_interface_routes() {
local dev="${1}"; shift
local ipv=4
test "${LB_IPV}" = "6" && local ipv=6
local hostnet="/32"
test "${LB_IPV}" = "6" && local hostnet="/128"
local i=
for i in ${@}
do
run $IP_CMD -${ipv} route show dev "${dev}" scope link src "${i}" |\
trim_spaces |\
$CUT_CMD -d ' ' -f 1 |\
$SED_CMD "s|/${hostnet}||g" |\
$GREP_CMD -v "/" |\
$TR_CMD '\n' ' '
done
}
CHECK_PING_COUNT=3
CHECK_PING_WAIT=10
check_ping() {
DEBUGCMD "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}"
local dev="$1"
local src="$2"
local dst="$3"
local cmd="$PING_CMD"
test "${LB_IPV}" = "6" && local cmd="$PING6_CMD"
run $cmd -I ${src} -c ${CHECK_PING_COUNT} -w ${CHECK_PING_WAIT} ${dst} >/dev/null
return $?
}
CHECK_TRACEROUTE_PORT=80
CHECK_TRACEROUTE_WAIT=2
check_traceroute() {
DEBUGCMD "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}"
local dev="$1"
local src="$2"
local dst="$3"
local cmd="$TRACEROUTE_CMD -4"
test "${LB_IPV}" = "6" && local cmd="$TRACEROUTE_CMD -6"
local found="`run $cmd -i "${dev}" -r -s ${src} -w ${CHECK_TRACEROUTE_WAIT} -Tn -p ${CHECK_TRACEROUTE_PORT} ${dst} | $GREP_CMD ${dst}`"
test ! -z "${found}" && return 0
return 1
}
check_alwayson() {
DEBUGCMD "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}"
local dev="$1"
local src="$2"
local dst="$3"
return 0
}
# this array has one entry per gateway.
# - the array index is the gateway name
# - the array value is the number of distinct gateways alive
declare -A LB_GATEWAYS=()
# keep track of the gateways IP version
declare -A LB_GATEWAYS_IPV=()
gateway4() { gateway ipv4 "${@}"; }
gateway6() { gateway ipv6 "${@}"; }
gateway() {
printf >&2 "\n-------------------------------------------------------------------------------\n"
DEBUGCMD "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}"
LB_IPV=${LB_DEFAULT_IPV}
if [ ! -z "${work_route}" ]
then
local name="${work_route}"
else
local name="${1}"
shift
fi
local gw=
local dev=
local src=
local dst="gateway"
local check="ping"
while [ ! -z "${1}" ]
do
case "${1}" in
ipv4)
LB_IPV=4
;;
ipv6)
LB_IPV=6
;;
on|dev)
local dev="${2}"
shift
;;
gateway|gw|via)
local gw="${2//,/ }"
shift
;;
src|from)
local src="${2//,/ }"
shift
;;
check)
local check="${2}"
local dst="${3//,/ }"
shift 2
;;
*)
error "${FUNCNAME} '${name}': cannot understand parameter '${1}'."
return 1
;;
esac
shift
done
LB_GATEWAYS[$name]=0
LB_GATEWAYS_IPV[$name]=${LB_IPV}
# if we don't have source IPs, find them from the interface
if [ -z "${src}" -o "${src}" = "auto" ]
then
local src="`get_interface_ips "${dev}" | $SORT_CMD -u`"
fi
# if we don't have source IPs, cannot proceed
if [ -z "${src}" ]
then
warning "Cannot find gateway ${name} IPs."
return 1
fi
# if we don't have a gateway, cannot proceed
if [ -z "${dev}" ]
then
error "${FUNCNAME} '${name}': cannot add a gateway without a device."
return 2
fi
# if we don't have gateway IPs, find them from the interface
test -z "${gw}" -o "${gw}" = "auto" -o "${gw}" = "detect" && local gw="`get_interface_routes "${dev}" ${src}`"
# if we don't have a gateway, cannot proceed
if [ -z "${gw}" ]
then
warning "Cannot find ${name} gateway IPs."
return 3
fi
# if we don't have a destination, use the gateway
test -z "${dst}" -o "${dst}" = "auto" -o "${dst}" = "detect" -o "${dst}" = "gateway" && local dst="${gw}"
test $FORCE_ALWAYSON -eq 1 && local check="alwayson"
$CAT_CMD <<EOF_GW
--- GATEWAY CONFIGURATION ----
Gateway : ${name}
Via IP : ${gw}
Source IPs: ${src}
Check : ${check} ${dst}
IP VERSION: ${LB_IPV}
EOF_GW
echo "${src}" >"${LB_DIR}/gateway.${name}.source-ips"
# -------------------------------------------------------------------------
# Check if the gateway is alive
echo " CHECKING IF GATEWAY ${name} IS ALIVE"
local alive=0
local s=
for s in ${src}
do
local d=
for d in ${dst}
do
test $alive -ne 0 && break
check_${check} ${dev} ${s} ${d}
test $? -eq 0 && local alive=1
done
done
if [ ${alive} -eq 0 ]
then
echo
echo " Gateway ${name} is not alive."
return 99
fi
local count=0
local g=
for g in ${gw}
do
local count=$[count + 1]
echo "via ${g} dev ${dev}" >>"${LB_DIR}/gateway.${name}.paths"
done
LB_GATEWAYS[$name]="${count}"
echo >&2
echo >&2 -e " ${COLOR_GREEN}${COLOR_BOLD}IPv${LB_IPV} gateway '${name}' is alive, having ${count} active path(s).${COLOR_RESET}"
return 0
}
# -----------------------------------------------------------------------------
# table section
# this array has one entry per table.
# - the array index is the table name
# - the array value is the number of default gateways available
declare -A LB_TABLES=()
declare -A LB_TABLES_FALLBACK=()
# keep track of the IP version per table
# if a table is used by both IPv4 and IPv6, '46' should be stored
declare -A LB_TABLES_IPV=()
# keep track of all origin tables
# if a table is used by both IPv4 and IPv6, '46' should be stored
declare -A LB_ORIGIN_TABLES=()
get_existing_routing_table() {
DEBUGCMD "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}"
local table="${1}"
if [ "${LB_IPV}" = "6" ]
then
run $IP_CMD -6 -o route show table "${table}" |\
trim_spaces |\
$SORT_CMD
else
run $IP_CMD -4 -o route show table "${table}" |\
$GREP_CMD -v " via 127.0.0.1 dev lo" |\
trim_spaces |\
$SORT_CMD
fi
}
work_table=
work_ipv=
table4() { table ipv4 "${@}"; }
table6() { table ipv6 "${@}"; }
table() {
printf >&2 "\n-------------------------------------------------------------------------------\n"
DEBUGCMD "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}"
LB_IPV=${LB_DEFAULT_IPV}
local table="$1"; shift
if [ -z "${table}" ]
then
error "${FUNCNAME} needs a name."
return 1
fi
local origin="main"
local copy_default=1
while [ ! -z "${1}" ]
do
case "${1}" in
ipv4)
LB_IPV=4
;;
ipv6)
LB_IPV=6
;;
from|copy|duplicate)
local origin="${2}"
shift
;;
nodefault|keepdefault|nodef)
local copy_default=0
;;
*)
error "${FUNCNAME} '${table}': Cannot understand option '${1}'."
return 1
;;
esac
shift
done
# set LB_TABLES_IPV
if [ -z "${LB_TABLES_IPV[$table]}" ]
then
LB_TABLES_IPV[$table]="${LB_IPV}"
elif [ "${LB_TABLES_IPV[$table]}" = "${LB_IPV}" ]
then
error "${FUNCNAME}: table ${table} already exists in IPv${LB_IPV}."
exit 1
else
LB_TABLES_IPV[$table]="46"
fi
if [ "${table}" = "${origin}" -o -z "${origin}" -o "${origin}" = "none" ]
then
local origin="none"
fi
# give a summary to the user
$CAT_CMD <<EOF_TABLE
--- TABLE CONFIGURATION ---
Table : ${table}
Copy from : ${origin}
IP VERSION : ${LB_IPV}
EOF_TABLE
if [ ! "${origin}" = "none" ]
then
# just link it
# The source file may not exist yet. This is OK.
# Later, at finizize_tables() we will check the links to find
# the dependencies between the tables so that they will be
# activated in the correct order, so that in one pass all
# tables will get the final routes.
# We will also check if the user requested a circular
# dependency, and stop processing in this case.
$LN_CMD -s "${LB_DIR}/table.${origin}.routes.${LB_IPV}" "${LB_DIR}/table.${table}.origin_routes.${LB_IPV}"
test $copy_default -eq 1 && $LN_CMD -s "${LB_DIR}/table.${origin}.default.${LB_IPV}" "${LB_DIR}/table.${table}.origin_default.${LB_IPV}"
fi
work_table="${table}"
work_ipv="${LB_IPV}"
LB_TABLES[$table]=0
LB_TABLES_FALLBACK[$table]=0
if [ ! "${origin}" = "none" ]
then
# set LB_ORIGIN_TABLES
if [ -z "${LB_ORIGIN_TABLES[$origin]}" ]
then
LB_ORIGIN_TABLES[$origin]="${LB_IPV}"
elif [ ! "${LB_ORIGIN_TABLES[$origin]}" = "${LB_IPV}" ]
then
LB_ORIGIN_TABLES[$origin]="46"
fi
fi
# instruct the finalizer to run IPvX tables
$TOUCH_CMD "${LB_DIR}/tables.${LB_IPV}"
}
fallback() {
DEBUGCMD "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}"
default "${@}" weight 0
}
default() {
DEBUGCMD "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}"
if [ -z "${work_table}" ]
then
error "Statement 'default' should appear after a 'table'."
exit 1
fi
# check IPvX is as it should
LB_IPV=${work_ipv}
if [ ! "${LB_TABLES_IPV[${work_table}]}" = "${LB_IPV}" -a ! "${LB_TABLES_IPV[${work_table}]}" = "46" ]
then
error "${FUNCNAME} INTERNAL ERROR: Inheritted IPv${LB_IPV} but table is IPv${LB_TABLES_IPV[${work_table}]}."
exit 1
fi
local gw=
local weight=100
while [ ! -z "${1}" ]
do
case "${1}" in
via|gateway|gw)
gw="${2}"
shift
;;
weight)
local weight="${2}"
shift
;;
*)
error "${FUNCNAME} on '${work_table}': Cannot understand option '${1}'."
return 1
;;
esac
shift
done
if [ -z "${gw}" ]
then
error "${FUNCNAME} on '${work_table}': Cannot work without a gateway."
return 1
fi
if [ -z "${LB_GATEWAYS[$gw]}" ]
then
warning "'${gw}' on '${work_table}': Unknown gateway '${gw}' requested."
return 1
fi
if [ ! "${LB_GATEWAYS_IPV[$gw]}" = "${LB_IPV}" ]
then
error "${FUNCNAME} '${gw}' on '${work_table}': Cannot assign an IPv${LB_GATEWAYS_IPV[$gw]} gateway to an IPv${LB_IPV} table."
exit 1
fi
if [ "${LB_GATEWAYS[$gw]}" = "0" ]
then
warning "'${gw}' on '${work_table}': Ignoring gateway '${gw}', it is not alive."
return 1
fi
if [ ! -s "${LB_DIR}/gateway.${gw}.paths" ]
then
warning "'${gw}' on '${work_table}': Gateway '${gw}' does not have any routes."
return 1
fi
local context="default"
if [ "${weight}" = "0" ]
then
local context="fallback"
local weight="100"
local count=${LB_TABLES_FALLBACK[${work_table}]}
else
local count=${LB_TABLES[${work_table}]}
fi
while read
do
count=$[count + 1]
echo "nexthop ${REPLY} weight ${weight}" >>"${LB_DIR}/table.${work_table}.${context}.${LB_IPV}"
done <"${LB_DIR}/gateway.${gw}.paths"
if [ "${context}" = "default" ]
then
LB_TABLES[${work_table}]=$count
else
LB_TABLES_FALLBACK[${work_table}]=$count
fi
}
lb_diff_route() {
local cmd="$1"; shift
local table="$1"; shift
case "${cmd}" in
add)
action $IP_CMD -${LB_IPV} route add table ${table} "${@}" || action $IP_CMD -${LB_IPV} route append table ${table} "${@}"
return $?
;;
delete)
action $IP_CMD -${LB_IPV} route del table ${table} "${@}"
return $?
;;
same)
return 0
;;
esac
return 1
}
update_table() {
printf >&2 "\n -----------------------------------------------\n"
DEBUGCMD "${FUNCNAME}" "${#FUNCNAME[*]}" "${@}"
LB_IPV="${1}"; shift
local table="${1}"; shift
# check IPvX is as it should
if [ ! "${LB_TABLES_IPV[${table}]}" = "${LB_IPV}" -a ! "${LB_TABLES_IPV[${table}]}" = "46" ]
then
error "${FUNCNAME} INTERNAL ERROR: Inheritted IPv${LB_IPV} but table is IPv${LB_TABLES_IPV[${work_table}]}."
exit 1
fi
# ---------------------------------------------------------------------
# unit testing - make sure it works right
if [ -h "${LB_DIR}/table.${table}.origin_routes.${LB_IPV}" -a ! -f "${LB_DIR}/table.${table}.origin_routes.${LB_IPV}" ]
then
error "INTERNAL ERROR: table.${table}.origin_routes.${LB_IPV} is an unresolvable link!"
exit 1
fi
if [ -h "${LB_DIR}/table.${table}.origin_default.${LB_IPV}" -a ! -f "${LB_DIR}/table.${table}.origin_default.${LB_IPV}" ]
then
error "INTERNAL ERROR: table.${table}.origin_default.${LB_IPV} is an unresolvable link!"
exit 1
fi
# ---------------------------------------------------------------------
# decide what will be done for this table
# 1. if 'table.${table}.origin_routes' exists, we copy the routing table
# 2. if 'table.${table}.default' or 'table.${table}.origin_default' exist, we set the default gateway
# 3. if none of the above is present, we do nothing
local routing_filter_cmd="$CAT_CMD"
if [ -f "${LB_DIR}/table.${table}.origin_routes.${LB_IPV}" -a \( -f "${LB_DIR}/table.${table}.default.${LB_IPV}" -o -f "${LB_DIR}/table.${table}.fallback.${LB_IPV}" -o -f "${LB_DIR}/table.${table}.origin_default.${LB_IPV}" \) ]
then
# we do both routes copy and set default gateway
routing_filter_cmd="$CAT_CMD"
elif [ -f "${LB_DIR}/table.${table}.default.${LB_IPV}" -o -f "${LB_DIR}/table.${table}.origin_default.${LB_IPV}" ]
then
# we should only process default gateway
routing_filter_cmd="$GREP_CMD ^default"
elif [ -f "${LB_DIR}/table.${table}.origin_routes.${LB_IPV}" ]
then
# we should only copy the routing table without the default gateway
routing_filter_cmd="$GREP_CMD -v ^default"