]> git.ipfire.org Git - people/ms/network.git/blob - src/functions/functions.util
80354f4d3778ae63c5a1f0f78e25a551b30f9571
[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_parent_dir() {
252 local path="${1}"
253
254 local dirname="$(dirname "${path}")"
255 mkdir -p "${dirname}"
256 }
257
258 enabled() {
259 local param=${1}
260
261 list_match "${!param}" yes on true 1
262 }
263
264 mac_generate() {
265 local b="$(random 12)"
266
267 # Remove multicast bit
268 # and set address is software assigned
269 local first_byte=$(( 0x${b:0:2} & 0xfe ))
270 first_byte=$(( ${first_byte} | 0x02 ))
271
272 local output
273 printf -v output "%02x" "${first_byte}"
274
275 output="${output}:${b:2:2}:${b:4:2}:${b:6:2}:${b:8:2}:${b:10:2}"
276
277 # Check if output is valid
278 assert mac_is_valid "${output}"
279
280 echo "${output}"
281 }
282
283 mac_format() {
284 local mac=${1}
285 assert isset mac
286
287 # Remove all colons and make the rest lowercase.
288 mac=${mac//:/}
289 mac=${mac,,}
290
291 local output
292 if [ "${#mac}" = "12" ]; then
293 # Add colons (:) to mac address
294 output=${mac:0:2}
295 local i
296 for i in 2 4 6 8 10; do
297 output="${output}:${mac:${i}:2}"
298 done
299 else
300 output=${mac}
301 fi
302
303 assert mac_is_valid ${output}
304
305 print "${output}"
306 }
307
308 mac_is_valid() {
309 local mac=${1}
310
311 [[ ${mac} =~ ^([0-9a-f]{2}\:){5}[0-9a-f]{2}$ ]]
312 }
313
314 uuid() {
315 echo $(</proc/sys/kernel/random/uuid)
316 }
317
318 abs() {
319 local val=${1}
320
321 if [ ${val} -lt 0 ]; then
322 (( val *= -1 ))
323 fi
324
325 echo ${val}
326 }
327
328 rand() {
329 local uuid="$(uuid)"
330 echo "${uuid//-/}"
331 }
332
333 random() {
334 local length="${1:-8}"
335
336 local random
337 while [ ${#random} -lt ${length} ]; do
338 random="${random}$(rand)"
339 done
340
341 echo "${random:0:${length}}"
342 }
343
344 isset() {
345 local var=${1}
346
347 [ -n "${!var}" ]
348 }
349
350 isoneof() {
351 local var=${!1}
352 shift
353
354 list_match "${var}" "$@"
355 }
356
357 isbool() {
358 local var=${1}
359
360 isoneof ${var} 0 1 no yes on off true false
361 }
362
363 isinteger() {
364 local var=${!1}
365
366 [[ ${var} =~ ^[0-9]+$ ]]
367 }
368
369 ismac() {
370 local mac=${!1}
371
372 mac_is_valid ${mac}
373 }
374
375 isipaddress() {
376 local addr=${!1}
377
378 ip_is_valid ${addr}
379 }
380
381 mtu_is_valid() {
382 local proto=${1}
383 local mtu=${2}
384
385 case ${proto} in
386 ipv4)
387 [ ${mtu} -ge 576 ] && [ ${mtu} -le 9000 ]
388 ;;
389 ipv6)
390 [ ${mtu} -ge 1280 ] && [ ${mtu} -le 9000 ]
391 ;;
392 *)
393 error "${proto} is not a valid proto"
394 return ${EXIT_ERROR}
395 ;;
396 esac
397 }
398
399 backtrace() {
400 local start=1
401
402 echo # Empty line
403 error_log "Backtrace (most recent call in first line):"
404
405 local i source
406 for i in $(seq ${start} ${#BASH_SOURCE[*]}); do
407 [ -z "${FUNCNAME[${i}]}" ] && continue
408
409 # Print called binary with arguments.
410 if [ "${FUNCNAME[${i}]}" == "main" ]; then
411 local args="$(list_reverse ${BASH_ARGV[*]})"
412 printf -v source "%20s" "$0"
413 error_log " ${source} ${args}"
414 continue
415 fi
416
417 source=${BASH_SOURCE[$(( ${i} + 1 ))]}
418 error_log " $(printf "%20s" "'${FUNCNAME[${i}]}'") called from ${source:-<shell>}:${BASH_LINENO[${i}]}"
419 done
420 }
421
422 assert() {
423 local assertion="$@"
424
425 if ! ${assertion}; then
426 error_log "Assertion '${assertion}' failed."
427 backtrace
428 exit ${EXIT_ERROR_ASSERT}
429 fi
430
431 return ${EXIT_OK}
432 }
433
434 # This function checks, if the given argument is an assert error
435 # exit code. If this is the case, the script will halt immediately.
436 assert_check_retval() {
437 local ret=${1}
438
439 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
440 exit ${EXIT_ERROR_ASSERT}
441 fi
442
443 return ${ret}
444 }
445
446 # This function executes the given command and inverses the return code
447 not() {
448 local command="$@"
449
450 ${command} && return ${EXIT_FALSE} || return ${EXIT_TRUE}
451 }
452
453 exec_cmd() {
454 local cmd=$@
455
456 log DEBUG "Running command: ${cmd}"
457
458 DEBUG=${DEBUG} \
459 LOG_DISABLE_STDOUT="${LOG_DISABLE_STDOUT}" \
460 LOG_FACILITY="${LOG_FACILITY}" \
461 ${SHELL} ${cmd}
462 local ret=$?
463
464 #log DEBUG "Returned with code '${ret}'"
465
466 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
467 error_log "Stopping parent process due to assertion error in child process: ${cmd}"
468 exit ${EXIT_ERROR_ASSERT}
469 fi
470
471 return ${ret}
472 }
473
474 cmd() {
475 local cmd=$@
476
477 log DEBUG "Running command: ${cmd}"
478
479 env -i -- \
480 HOME="${HOME}" \
481 PATH="${PATH}" \
482 TERM="${TERM}" \
483 ${cmd}
484 local ret=$?
485
486 case "${ret}" in
487 ${EXIT_OK})
488 return ${EXIT_OK}
489 ;;
490 *)
491 log DEBUG "Returned with code '${ret}'"
492 return ${ret}
493 ;;
494 esac
495 }
496
497 cmd_quiet() {
498 cmd $@ &>/dev/null
499 }
500
501 cmd_exec() {
502 local cmd=$@
503
504 log DEBUG "Exec'ing command: ${cmd}"
505
506 exec ${cmd}
507
508 log ERROR "Could not exec-ute: ${cmd}"
509 exit ${EXIT_ERROR}
510 }
511
512 cmd_not_implemented() {
513 assert false "not implemented"
514 }
515
516 # Runs a command in a clean environment so that no confidential information
517 # is leaked to any untrusted commands.
518 cmd_clean_environment() {
519 local cmd=$@
520
521 log DEBUG "Running command in a clean environment: ${cmd}"
522 env -i -- ${cmd}
523 local ret=${?}
524
525 log DEBUG "Returned with code '${ret}'"
526 return ${ret}
527 }
528
529 # Executes the given command in background
530 cmd_background() {
531 cmd_quiet $@ &
532 }
533
534 # Prints the PID of the process that was started last
535 cmd_background_get_pid() {
536 print "${!}"
537 }
538
539 cmd_background_result() {
540 local pids=$@
541
542 wait ${pids}
543 }
544
545 # Increase security of the read command
546 read() {
547 builtin read -r $@
548 }
549
550 seq() {
551 if [ $# -eq 2 ]; then
552 eval echo {${1}..${2}}
553 elif [ $# -eq 3 ]; then
554 eval echo {${1}..${3}..${2}}
555 fi
556 }
557
558 range() {
559 eval echo {0..$(( ${1} - 1 ))}
560 }
561
562 count() {
563 local i=0
564
565 while read; do
566 ((i++))
567 done
568
569 echo ${i}
570 }
571
572 which() {
573 type -P $@
574 }
575
576 # Prints the number of seconds since epoch.
577 timestamp() {
578 date -u "+%s"
579 }
580
581 beautify_time() {
582 local value=${1}
583
584 local unit
585 local limit
586 for unit in s m h d w; do
587 case "${unit}" in
588 s|m|h)
589 limit=60
590 ;;
591 d)
592 limit=24
593 ;;
594 w)
595 limit=7
596 ;;
597 esac
598
599 [ ${value} -lt ${limit} ] && break
600
601 value=$(( ${value} / ${limit} ))
602 done
603
604 echo "${value}${unit}"
605 }
606
607 beautify_bytes() {
608 local value=${1}
609
610 local unit
611 local limit=1024
612 for unit in B k M G T; do
613 [ ${value} -lt ${limit} ] && break
614 value=$(( ${value} / ${limit} ))
615 done
616
617 echo "${value}${unit}"
618 }
619
620 module_load() {
621 local module=${1}
622
623 if ! grep -q "^${module}" /proc/modules; then
624 log DEBUG "Loading module '${module}'."
625 modprobe ${module}
626 fi
627 }
628
629 binary_exists() {
630 local binary=${1}
631
632 if [ -n "$(type -p ${binary})" ]; then
633 return ${EXIT_OK}
634 fi
635
636 return ${EXIT_ERROR}
637 }
638
639 function_exists() {
640 local function="${1}"
641
642 if [ "$(type -t "${function}")" = "function" ]; then
643 return ${EXIT_TRUE}
644 fi
645
646 return ${EXIT_FALSE}
647 }
648
649 process_kill() {
650 local process=${1}
651
652 if ! isinteger process; then
653 process=$(pidof ${process})
654 fi
655
656 local pid
657 local sig
658 for pid in ${process}; do
659 for sig in 15 9; do
660 [ -d "/proc/${pid}" ] || break
661
662 kill -${sig} ${pid}
663 sleep 1
664 done
665 done
666 }
667
668 dec() {
669 local hex=${1}
670
671 if [ "${hex:0:2}" != "0x" ]; then
672 hex="0x${hex}"
673 fi
674
675 printf "%d\n" "${hex}"
676 }
677
678 chr() {
679 local char="${1}"
680
681 [ ${char} -lt 256 ] || return ${EXIT_ERROR}
682
683 printf "\\$(( ${char} / 64 * 100 + ${char} % 64 / 8 * 10 + ${char} % 8 ))\n"
684 }
685
686 ord() {
687 LC_CTYPE="C" printf "%d\n" "'${1}"
688 }
689
690 hex() {
691 printf "%X\n" "${1}"
692 }
693
694 network_is_running() {
695 # Check, if the network service is running.
696 service_is_active network
697 }
698
699 contains_spaces() {
700 local var="$@"
701
702 # Eliminate spaces.
703 local var2=${var// /}
704
705 if [ ${#var} -ne ${#var2} ]; then
706 return ${EXIT_TRUE}
707 fi
708
709 return ${EXIT_FALSE}
710 }
711
712 string_match() {
713 local match=${1}
714 local string=${2}
715
716 [[ ${string} =~ ${match} ]] && return ${EXIT_TRUE} || return ${EXIT_FALSE}
717 }
718
719 string_split() {
720 local string="$@"
721
722 local pos=0
723 while [ ${pos} -lt ${#string} ]; do
724 print "${string:${pos}:1}"
725 pos=$(( ${pos} + 1 ))
726 done
727
728 return ${EXIT_OK}
729 }
730
731 string_reverse() {
732 local string="$@"
733
734 local output
735 local pos=0
736 while [ ${pos} -lt ${#string} ]; do
737 output="${string:${pos}:1}${output}"
738 pos=$(( ${pos} + 1 ))
739 done
740
741 print "${output}"
742 return ${EXIT_OK}
743 }
744
745 dec2bin() {
746 local number="${1}"
747
748 local output
749
750 local i div
751 for i in 7 6 5 4 3 2 1; do
752 div=$(( 2 ** ${i} ))
753
754 if [ $(( ${number} / ${div} )) -eq 1 ]; then
755 output="${output}1"
756 else
757 output="${output}0"
758 fi
759 number="$(( ${number} % ${div} ))"
760 done
761
762 if [ $(( ${number} % 2 )) -eq 1 ]; then
763 output="${output}1"
764 else
765 output="${output}0"
766 fi
767
768 print "${output}"
769 }
770
771 bin2dec() {
772 local string="${1}"
773 local number=0
774
775 local pos=0 char
776 while [ ${pos} -lt ${#string} ]; do
777 char="${string:${pos}:1}"
778 pos=$(( ${pos} + 1 ))
779
780 number=$(( ${number} << 1 ))
781
782 case "${char}" in
783 0) ;;
784 1)
785 number=$(( ${number} + 1 ))
786 ;;
787 *)
788 assert false "Invalid character: ${char}"
789 ;;
790 esac
791 done
792
793 print "${number}"
794 return ${EXIT_OK}
795 }
796
797 char2bin() {
798 local dec="$(ord "${1}")"
799
800 dec2bin "${dec}"
801 }
802
803 bin2char() {
804 local dec="$(bin2dec "$@")"
805
806 chr "${dec}"
807 }
808
809 bin2hex() {
810 local dec="$(bin2dec "$@")"
811
812 dec2hex "${dec}"
813 }
814
815 hex2bin() {
816 local dec="$(hex2dec "$@")"
817
818 dec2bin "${dec}"
819 }
820
821 hex2dec() {
822 local hex="${1}"
823
824 # Prepend 0x if necessary.
825 [ "${hex:0:2}" = "0x" ] || hex="0x${hex}"
826
827 printf "%d\n" "${hex}"
828 }
829
830 dec2hex() {
831 printf "%02x\n" "${1}"
832 }
833
834 # This function just copy config files
835 copy() {
836 assert [ $# -eq 2 ]
837
838 local src=${1}
839 local dst=${2}
840
841 # Check if we can read from the source
842 if [ ! -r "${src}" ]; then
843 log ERROR "Cannot read ${src}"
844 return ${EXIT_ERROR}
845 fi
846
847 # Check if ${dst} is a directory
848 if [ -d "${dst}" ]; then
849 log ERROR "${dst} is a directory"
850 return ${EXIT_ERROR}
851 fi
852
853 if ! fread "${src}" > "${dst}"; then
854 log ERROR "Could not copy data from ${src} to ${dst}"
855 return ${EXIT_ERROR}
856 fi
857 }