]> git.ipfire.org Git - people/ms/network.git/blob - src/functions/functions.util
port: ethernet: Correctly create new configurations
[people/ms/network.git] / src / functions / functions.util
1 #!/bin/bash
2 ###############################################################################
3 # #
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2010 Michael Tremer & Christian Schmidt #
6 # #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
11 # #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
16 # #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
19 # #
20 ###############################################################################
21
22 # A simple print statement
23 print() {
24 local fmt=${1}; shift
25
26 printf -- "${fmt}\n" "$@"
27 }
28
29 print_indent() {
30 local i=${1}
31 shift
32
33 while (( i-- )); do
34 printf "\t"
35 done
36
37 print "%s" "$@"
38 }
39
40 # The args() function takes a number of arguments like
41 # var1="abc d" var2="abc" var3="abcd e"
42 # and splits them into several arguments, devided by newline
43 args() {
44 echo "$@" | xargs printf "%s\n"
45 }
46
47 unquote() {
48 local var="$@"
49
50 if [ "${var:0:1}" = "\"" ]; then
51 var=${var:1}
52 fi
53
54 local last=$(( ${#var} - 1 ))
55 if [ ${last} -ge 0 ] && [ "${var:${last}:1}" = "\"" ]; then
56 var=${var:0:${last}}
57 fi
58
59 print "${var}"
60 }
61
62 quote() {
63 print "\"%s\"" "$@"
64 }
65
66 strip() {
67 local value="$@"
68
69 # remove leading whitespace characters
70 value="${value#"${value%%[![:space:]]*}"}"
71
72 # remove trailing whitespace characters
73 value="${value%"${value##*[![:space:]]}"}"
74
75 print "${value}"
76 }
77
78 # Print a pretty error message
79 error() {
80 echo -e " ${CLR_RED_B}ERROR${CLR_RESET} : $@" >&2
81 }
82
83 error_log() {
84 log ERROR "$@"
85 }
86
87 # Print a pretty warn message
88 warning() {
89 echo -e " ${CLR_YELLOW_B}WARNING${CLR_RESET}: $@" >&2
90 }
91
92 warning_log() {
93 log WARNING "$@"
94 }
95
96 # Speedup function to avoid a call of the basename binary
97 basename() {
98 echo "${1##*/}"
99 }
100
101 format() {
102 local key=${1}
103 assert isset key
104
105 local format=${2}
106 assert isset format
107
108 shift 2
109
110 printf -v "${key}" "${format}" "$@"
111 }
112
113 format_time() {
114 local s=${1}
115 local ret m
116
117 local units="s m h"
118
119 local unit
120 for unit in ${units}; do
121 m=$(( ${s} % 60 ))
122 s=$(( ${s} / 60 ))
123
124 if [ ${m} -gt 0 ]; then
125 ret="${m}${unit} ${ret}"
126 fi
127 done
128
129 # Remove whitespace
130 echo ${ret}
131 }
132
133 parse_time() {
134 local ret=0
135
136 local arg
137 for arg in "$@"; do
138 local unit
139
140 case "${arg}" in
141 *h|*m|*s)
142 # Store unit
143 unit="${arg: -1}"
144
145 # Remove unit
146 arg="${arg:0:-1}"
147 ;;
148 esac
149
150 if ! isinteger arg; then
151 return ${EXIT_ERROR}
152 fi
153
154 # Convert hours and minutes into seconds
155 case "${unit}" in
156 h)
157 arg=$(( ${arg} * 3600 ))
158 ;;
159 m)
160 arg=$(( ${arg} * 60 ))
161 ;;
162 esac
163
164 # Add up everything
165 ret=$(( ${ret} + ${arg} ))
166 done
167
168 print "${ret}"
169 }
170
171 assign() {
172 local key=${1}
173 assert isset key
174 shift
175
176 format "${key}" "%s" "$@"
177 }
178
179 fread() {
180 local file=${1}
181 assert isset file
182
183 [ -r "${file}" ] || return ${EXIT_ERROR}
184
185 print "$(<${file})"
186 }
187
188 fwrite() {
189 local file=${1}
190 assert isset file
191 shift
192
193 if ! print "%s" "$@" > ${file} 2>/dev/null; then
194 error "Could not write to file: ${file}"
195 return ${EXIT_ERROR}
196 fi
197
198 return ${EXIT_OK}
199 }
200
201 fappend() {
202 local file=${1}
203 assert isset file
204 shift
205
206 if [ -e "${file}" ] && [ ! -w "${file}" ]; then
207 log ERROR "${file}: No such file"
208 return ${EXIT_ERROR}
209 fi
210
211 print "%s" "$@" >> ${file} 2>/dev/null
212 }
213
214 file_delete() {
215 local file=${1}
216
217 unlink "${file}" 2>/dev/null
218 }
219
220 file_exists() {
221 local file=${1}
222
223 [ -e "${file}" ] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
224 }
225
226 file_is_newer_than() {
227 local file1="${1}"
228 local file2="${2}"
229
230 local age1=$(file_get_age "${file1}")
231 local age2=$(file_get_age "${file2}")
232
233 if [ ${age1} -gt ${age2} ]; then
234 return ${EXIT_TRUE}
235 else
236 return ${EXIT_FALSE}
237 fi
238 }
239
240 file_get_age() {
241 local file="${1}"
242
243 if [ -e "${file}" ]; then
244 stat --format="%Y" "${file}"
245 return $?
246 fi
247
248 return ${EXIT_ERROR}
249 }
250
251 make_directory() {
252 local path="${1}"
253
254 if ! mkdir -p "${path}"; then
255 log ERROR "Could not create directory ${path}"
256 return ${EXIT_ERROR}
257 fi
258
259 log DEBUG "Created directory ${path}"
260 return ${EXIT_OK}
261 }
262
263 make_parent_directory() {
264 local path="${1}"
265
266 make_directory "$(dirname "${path}")"
267 }
268
269 enabled() {
270 local param=${1}
271
272 list_match "${!param}" yes on true 1
273 }
274
275 disabled() {
276 local param="${1}"
277
278 list_match "${!param}" no off false 0
279 }
280
281 mac_generate() {
282 local b="$(random 12)"
283
284 # Remove multicast bit
285 # and set address is software assigned
286 local first_byte=$(( 0x${b:0:2} & 0xfe ))
287 first_byte=$(( ${first_byte} | 0x02 ))
288
289 local output
290 printf -v output "%02x" "${first_byte}"
291
292 output="${output}:${b:2:2}:${b:4:2}:${b:6:2}:${b:8:2}:${b:10:2}"
293
294 # Check if output is valid
295 assert mac_is_valid "${output}"
296
297 echo "${output}"
298 }
299
300 mac_format() {
301 local mac=${1}
302 assert isset mac
303
304 # Remove all colons and make the rest lowercase.
305 mac=${mac//:/}
306 mac=${mac,,}
307
308 local output
309 if [ "${#mac}" = "12" ]; then
310 # Add colons (:) to mac address
311 output=${mac:0:2}
312 local i
313 for i in 2 4 6 8 10; do
314 output="${output}:${mac:${i}:2}"
315 done
316 else
317 output=${mac}
318 fi
319
320 assert mac_is_valid ${output}
321
322 print "${output}"
323 }
324
325 mac_is_valid() {
326 local mac=${1}
327
328 [[ ${mac} =~ ^([0-9a-f]{2}\:){5}[0-9a-f]{2}$ ]]
329 }
330
331 # Converts the given string to lowercase and returns true if it is a valid FQDN
332 fqdn_is_valid() {
333 local fqdn="${1}"
334
335 if grep -qP "^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$" <<< "${fqdn,,}"; then
336 return ${EXIT_TRUE}
337 fi
338
339 return ${EXIT_FALSE}
340 }
341
342 uuid() {
343 echo $(</proc/sys/kernel/random/uuid)
344 }
345
346 abs() {
347 local val=${1}
348
349 if [ ${val} -lt 0 ]; then
350 (( val *= -1 ))
351 fi
352
353 echo ${val}
354 }
355
356 rand() {
357 local uuid="$(uuid)"
358 echo "${uuid//-/}"
359 }
360
361 random() {
362 local length="${1:-8}"
363
364 local random
365 while [ ${#random} -lt ${length} ]; do
366 random="${random}$(rand)"
367 done
368
369 echo "${random:0:${length}}"
370 }
371
372 isset() {
373 local var=${1}
374
375 [ -n "${!var}" ]
376 }
377
378 isoneof() {
379 local var=${!1}
380 shift
381
382 list_match "${var}" "$@"
383 }
384
385 isbool() {
386 local var=${1}
387
388 isoneof ${var} 0 1 no yes on off true false
389 }
390
391 isinteger() {
392 local var=${!1}
393
394 [[ ${var} =~ ^[0-9]+$ ]]
395 }
396
397 ismac() {
398 local mac=${!1}
399
400 mac_is_valid ${mac}
401 }
402
403 isipaddress() {
404 local addr=${!1}
405
406 ip_is_valid ${addr}
407 }
408
409 mtu_is_valid() {
410 local proto=${1}
411 local mtu=${2}
412
413 case ${proto} in
414 ethernet|ipv4)
415 [ ${mtu} -ge 576 ] && [ ${mtu} -le 9000 ]
416 ;;
417 ipv6)
418 [ ${mtu} -ge 1280 ] && [ ${mtu} -le 9000 ]
419 ;;
420 *)
421 error "${proto} is not a valid proto"
422 return ${EXIT_ERROR}
423 ;;
424 esac
425 }
426
427 backtrace() {
428 local start=1
429
430 echo # Empty line
431 error_log "Backtrace (most recent call in first line):"
432
433 local i source
434 for i in $(seq ${start} ${#BASH_SOURCE[*]}); do
435 [ -z "${FUNCNAME[${i}]}" ] && continue
436
437 # Print called binary with arguments.
438 if [ "${FUNCNAME[${i}]}" == "main" ]; then
439 local args="$(list_reverse ${BASH_ARGV[*]})"
440 printf -v source "%20s" "$0"
441 error_log " ${source} ${args}"
442 continue
443 fi
444
445 source=${BASH_SOURCE[$(( ${i} + 1 ))]}
446 error_log " $(printf "%20s" "'${FUNCNAME[${i}]}'") called from ${source:-<shell>}:${BASH_LINENO[${i}]}"
447 done
448 }
449
450 assert() {
451 local assertion="$@"
452
453 if ! ${assertion}; then
454 error_log "Assertion '${assertion}' failed."
455 backtrace
456 exit ${EXIT_ERROR_ASSERT}
457 fi
458
459 return ${EXIT_OK}
460 }
461
462 # This function checks, if the given argument is an assert error
463 # exit code. If this is the case, the script will halt immediately.
464 assert_check_retval() {
465 local ret=${1}
466
467 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
468 exit ${EXIT_ERROR_ASSERT}
469 fi
470
471 return ${ret}
472 }
473
474 # This function executes the given command and inverses the return code
475 not() {
476 local command="$@"
477
478 ${command} && return ${EXIT_FALSE} || return ${EXIT_TRUE}
479 }
480
481 exec_cmd() {
482 local cmd=$@
483
484 log DEBUG "Running command: ${cmd}"
485
486 DEBUG=${DEBUG} \
487 LOG_DISABLE_STDOUT="${LOG_DISABLE_STDOUT}" \
488 LOG_FACILITY="${LOG_FACILITY}" \
489 ${SHELL} ${cmd}
490 local ret=$?
491
492 #log DEBUG "Returned with code '${ret}'"
493
494 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
495 error_log "Stopping parent process due to assertion error in child process: ${cmd}"
496 exit ${EXIT_ERROR_ASSERT}
497 fi
498
499 return ${ret}
500 }
501
502 cmd() {
503 local cmd=$@
504
505 log DEBUG "Running command: ${cmd}"
506
507 env -i -- \
508 HOME="${HOME}" \
509 PATH="${PATH}" \
510 TERM="${TERM}" \
511 ${cmd}
512 local ret=$?
513
514 case "${ret}" in
515 ${EXIT_OK})
516 return ${EXIT_OK}
517 ;;
518 *)
519 log DEBUG "Returned with code '${ret}'"
520 return ${ret}
521 ;;
522 esac
523 }
524
525 cmd_quiet() {
526 cmd "$@" &>/dev/null
527 }
528
529 cmd_exec() {
530 local cmd=$@
531
532 log DEBUG "Exec'ing command: ${cmd}"
533
534 exec ${cmd}
535
536 log ERROR "Could not exec-ute: ${cmd}"
537 exit ${EXIT_ERROR}
538 }
539
540 cmd_not_implemented() {
541 assert false "not implemented"
542 }
543
544 # Executes the given command in background
545 cmd_background() {
546 cmd_quiet "$@" &
547 }
548
549 # Prints the PID of the process that was started last
550 cmd_background_get_pid() {
551 print "${!}"
552 }
553
554 cmd_background_result() {
555 local pids=$@
556
557 wait ${pids}
558 }
559
560 # Increase security of the read command
561 read() {
562 builtin read -r "$@"
563 }
564
565 seq() {
566 if [ $# -eq 2 ]; then
567 eval echo {${1}..${2}}
568 elif [ $# -eq 3 ]; then
569 eval echo {${1}..${3}..${2}}
570 fi
571 }
572
573 range() {
574 eval echo {0..$(( ${1} - 1 ))}
575 }
576
577 count() {
578 local i=0
579
580 while read; do
581 ((i++))
582 done
583
584 echo ${i}
585 }
586
587 which() {
588 type -P "$@"
589 }
590
591 # Prints the number of seconds since epoch.
592 timestamp() {
593 date -u "+%s"
594 }
595
596 beautify_time() {
597 local value=${1}
598
599 local unit
600 local limit
601 for unit in s m h d w; do
602 case "${unit}" in
603 s|m|h)
604 limit=60
605 ;;
606 d)
607 limit=24
608 ;;
609 w)
610 limit=7
611 ;;
612 esac
613
614 [ ${value} -lt ${limit} ] && break
615
616 value=$(( ${value} / ${limit} ))
617 done
618
619 echo "${value}${unit}"
620 }
621
622 beautify_bytes() {
623 local value=${1}
624
625 local unit
626 local limit=1024
627 for unit in B k M G T; do
628 [ ${value} -lt ${limit} ] && break
629 value=$(( ${value} / ${limit} ))
630 done
631
632 echo "${value}${unit}"
633 }
634
635 module_load() {
636 local module=${1}
637
638 # Do nothing if the module is already loaded
639 if [ -d "/sys/module/${module//-/_}" ]; then
640 return ${EXIT_OK}
641 fi
642
643 log DEBUG "Loading kernel module ${module}"
644 modprobe "${module}"
645 }
646
647 binary_exists() {
648 local binary=${1}
649
650 if [ -n "$(type -p ${binary})" ]; then
651 return ${EXIT_OK}
652 fi
653
654 return ${EXIT_ERROR}
655 }
656
657 function_exists() {
658 local function="${1}"
659
660 if [ "$(type -t "${function}")" = "function" ]; then
661 return ${EXIT_TRUE}
662 fi
663
664 return ${EXIT_FALSE}
665 }
666
667 process_kill() {
668 local process=${1}
669
670 if ! isinteger process; then
671 process=$(pidof ${process})
672 fi
673
674 local pid
675 local sig
676 for pid in ${process}; do
677 for sig in 15 9; do
678 [ -d "/proc/${pid}" ] || break
679
680 kill -${sig} ${pid}
681 sleep 1
682 done
683 done
684 }
685
686 dec() {
687 local hex=${1}
688
689 if [ "${hex:0:2}" != "0x" ]; then
690 hex="0x${hex}"
691 fi
692
693 printf "%d\n" "${hex}"
694 }
695
696 chr() {
697 local char="${1}"
698
699 [ ${char} -lt 256 ] || return ${EXIT_ERROR}
700
701 printf "\\$(( ${char} / 64 * 100 + ${char} % 64 / 8 * 10 + ${char} % 8 ))\n"
702 }
703
704 ord() {
705 LC_CTYPE="C" printf "%d\n" "'${1}"
706 }
707
708 hex() {
709 printf "%X\n" "${1}"
710 }
711
712 network_is_running() {
713 # Check, if the network service is running.
714 service_is_active network
715 }
716
717 contains_spaces() {
718 local var="$@"
719
720 # Eliminate spaces.
721 local var2=${var// /}
722
723 if [ ${#var} -ne ${#var2} ]; then
724 return ${EXIT_TRUE}
725 fi
726
727 return ${EXIT_FALSE}
728 }
729
730 string_match() {
731 local match=${1}
732 local string=${2}
733
734 [[ ${string} =~ ${match} ]] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
735 }
736
737 string_split() {
738 local string="$@"
739
740 local pos=0
741 while [ ${pos} -lt ${#string} ]; do
742 print "${string:${pos}:1}"
743 pos=$(( ${pos} + 1 ))
744 done
745
746 return ${EXIT_OK}
747 }
748
749 string_reverse() {
750 local string="$@"
751
752 local output
753 local pos=0
754 while [ ${pos} -lt ${#string} ]; do
755 output="${string:${pos}:1}${output}"
756 pos=$(( ${pos} + 1 ))
757 done
758
759 print "${output}"
760 return ${EXIT_OK}
761 }
762
763 dec2bin() {
764 local number="${1}"
765
766 local output
767
768 local i div
769 for i in 7 6 5 4 3 2 1; do
770 div=$(( 2 ** ${i} ))
771
772 if [ $(( ${number} / ${div} )) -eq 1 ]; then
773 output="${output}1"
774 else
775 output="${output}0"
776 fi
777 number="$(( ${number} % ${div} ))"
778 done
779
780 if [ $(( ${number} % 2 )) -eq 1 ]; then
781 output="${output}1"
782 else
783 output="${output}0"
784 fi
785
786 print "${output}"
787 }
788
789 bin2dec() {
790 local string="${1}"
791 local number=0
792
793 local pos=0 char
794 while [ ${pos} -lt ${#string} ]; do
795 char="${string:${pos}:1}"
796 pos=$(( ${pos} + 1 ))
797
798 number=$(( ${number} << 1 ))
799
800 case "${char}" in
801 0) ;;
802 1)
803 number=$(( ${number} + 1 ))
804 ;;
805 *)
806 assert false "Invalid character: ${char}"
807 ;;
808 esac
809 done
810
811 print "${number}"
812 return ${EXIT_OK}
813 }
814
815 char2bin() {
816 local dec="$(ord "${1}")"
817
818 dec2bin "${dec}"
819 }
820
821 bin2char() {
822 local dec="$(bin2dec "$@")"
823
824 chr "${dec}"
825 }
826
827 bin2hex() {
828 local dec="$(bin2dec "$@")"
829
830 dec2hex "${dec}"
831 }
832
833 hex2bin() {
834 local dec="$(hex2dec "$@")"
835
836 dec2bin "${dec}"
837 }
838
839 hex2dec() {
840 local hex="${1}"
841
842 # Prepend 0x if necessary.
843 [ "${hex:0:2}" = "0x" ] || hex="0x${hex}"
844
845 printf "%d\n" "${hex}"
846 }
847
848 dec2hex() {
849 printf "%02x\n" "${1}"
850 }
851
852 # This function just copy config files
853 copy() {
854 assert [ $# -eq 2 ]
855
856 local src=${1}
857 local dst=${2}
858
859 # Check if we can read from the source
860 if [ ! -r "${src}" ]; then
861 log ERROR "Cannot read ${src}"
862 return ${EXIT_ERROR}
863 fi
864
865 # Check if ${dst} is a directory
866 if [ -d "${dst}" ]; then
867 log ERROR "${dst} is a directory"
868 return ${EXIT_ERROR}
869 fi
870
871 if ! fread "${src}" > "${dst}"; then
872 log ERROR "Could not copy data from ${src} to ${dst}"
873 return ${EXIT_ERROR}
874 fi
875 }
876
877 normalize() {
878 local string="$@"
879
880 tr -sc [:alnum:] "-" < <(printf "%s" "${string,,}")
881 }