]> git.ipfire.org Git - people/ms/network.git/blob - src/functions/functions.util
Drop deprecated listsort function
[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 # The args() function takes a number of arguments like
30 # var1="abc d" var2="abc" var3="abcd e"
31 # and splits them into several arguments, devided by newline
32 args() {
33 echo "$@" | xargs printf "%s\n"
34 }
35
36 unquote() {
37 local var="$@"
38
39 if [ "${var:0:1}" = "\"" ]; then
40 var=${var:1}
41 fi
42
43 local last=$(( ${#var} - 1 ))
44 if [ ${last} -ge 0 ] && [ "${var:${last}:1}" = "\"" ]; then
45 var=${var:0:${last}}
46 fi
47
48 print "${var}"
49 }
50
51 quote() {
52 print "\"%s\"" "$@"
53 }
54
55 strip() {
56 local value="$@"
57
58 # remove leading whitespace characters
59 value="${value#"${value%%[![:space:]]*}"}"
60
61 # remove trailing whitespace characters
62 value="${value%"${value##*[![:space:]]}"}"
63
64 print "${value}"
65 }
66
67 # Print a pretty error message
68 error() {
69 echo -e " ${CLR_RED_B}ERROR${CLR_RESET} : $@" >&2
70 }
71
72 error_log() {
73 log ERROR "$@"
74 }
75
76 # Print a pretty warn message
77 warning() {
78 echo -e " ${CLR_YELLOW_B}WARNING${CLR_RESET}: $@" >&2
79 }
80
81 warning_log() {
82 log WARNING "$@"
83 }
84
85 # The next two functions are kept for backwards
86 # compatibility. The need to be dropped at some time.
87 listmatch() {
88 list_match $@
89 }
90
91 listlength() {
92 list_length $@
93 }
94
95 # Speedup function to avoid a call of the basename binary
96 basename() {
97 echo "${1##*/}"
98 }
99
100 format() {
101 local key=${1}
102 assert isset key
103
104 local format=${2}
105 assert isset format
106
107 shift 2
108
109 printf -v "${key}" "${format}" "$@"
110 }
111
112 format_time() {
113 local s=${1}
114 local ret m
115
116 local units="s m h"
117
118 local unit
119 for unit in ${units}; do
120 m=$(( ${s} % 60 ))
121 s=$(( ${s} / 60 ))
122
123 if [ ${m} -gt 0 ]; then
124 ret="${m}${unit} ${ret}"
125 fi
126 done
127
128 # Remove whitespace
129 echo ${ret}
130 }
131
132 parse_time() {
133 local ret=0
134
135 local arg
136 for arg in $@; do
137 local unit
138
139 case "${arg}" in
140 *h|*m|*s)
141 # Store unit
142 unit="${arg: -1}"
143
144 # Remove unit
145 arg="${arg:0:-1}"
146 ;;
147 esac
148
149 if ! isinteger arg; then
150 return ${EXIT_ERROR}
151 fi
152
153 # Convert hours and minutes into seconds
154 case "${unit}" in
155 h)
156 arg=$(( ${arg} * 3600 ))
157 ;;
158 m)
159 arg=$(( ${arg} * 60 ))
160 ;;
161 esac
162
163 # Add up everything
164 ret=$(( ${ret} + ${arg} ))
165 done
166
167 print "${ret}"
168 }
169
170 assign() {
171 local key=${1}
172 assert isset key
173 shift
174
175 format "${key}" "%s" "$@"
176 }
177
178 fread() {
179 local file=${1}
180 assert isset file
181
182 [ -r "${file}" ] || return ${EXIT_ERROR}
183
184 print "$(<${file})"
185 }
186
187 fwrite() {
188 local file=${1}
189 assert isset file
190 shift
191
192 if [ ! -w "${file}" ]; then
193 log ERROR "${file}: No such file"
194 return ${EXIT_ERROR}
195 fi
196
197 print "%s" "$@" >> ${file} 2>/dev/null
198 }
199
200 make_parent_dir() {
201 local path="${1}"
202
203 local dirname="$(dirname "${path}")"
204 mkdir -p "${dirname}"
205 }
206
207 enabled() {
208 local param=${1}
209
210 list_match "${!param}" yes on true 1
211 }
212
213 mac_generate() {
214 local b="$(random 12)"
215
216 # Remove multicast bit
217 # and set address is software assigned
218 local first_byte=$(( 0x${b:0:2} & 0xfe ))
219 first_byte=$(( ${first_byte} | 0x02 ))
220
221 local output
222 printf -v output "%02x" "${first_byte}"
223
224 output="${output}:${b:2:2}:${b:4:2}:${b:6:2}:${b:8:2}:${b:10:2}"
225
226 # Check if output is valid
227 assert mac_is_valid "${output}"
228
229 echo "${output}"
230 }
231
232 mac_format() {
233 local mac=${1}
234 assert isset mac
235
236 # Remove all colons and make the rest lowercase.
237 mac=${mac//:/}
238 mac=${mac,,}
239
240 local output
241 if [ "${#mac}" = "12" ]; then
242 # Add colons (:) to mac address
243 output=${mac:0:2}
244 local i
245 for i in 2 4 6 8 10; do
246 output="${output}:${mac:${i}:2}"
247 done
248 else
249 output=${mac}
250 fi
251
252 assert mac_is_valid ${output}
253
254 print "${output}"
255 }
256
257 mac_is_valid() {
258 local mac=${1}
259
260 [[ ${mac} =~ ^([0-9a-f]{2}\:){5}[0-9a-f]{2}$ ]]
261 }
262
263 uuid() {
264 echo $(</proc/sys/kernel/random/uuid)
265 }
266
267 abs() {
268 local val=${1}
269
270 if [ ${val} -lt 0 ]; then
271 (( val *= -1 ))
272 fi
273
274 echo ${val}
275 }
276
277 rand() {
278 local uuid="$(uuid)"
279 echo "${uuid//-/}"
280 }
281
282 random() {
283 local length="${1:-8}"
284
285 local random
286 while [ ${#random} -lt ${length} ]; do
287 random="${random}$(rand)"
288 done
289
290 echo "${random:0:${length}}"
291 }
292
293 isset() {
294 local var=${1}
295
296 [ -n "${!var}" ]
297 }
298
299 isoneof() {
300 local var=${!1}
301 shift
302
303 list_match "${var}" "$@"
304 }
305
306 isbool() {
307 local var=${1}
308
309 isoneof ${var} 0 1 no yes on off true false
310 }
311
312 isinteger() {
313 local var=${!1}
314
315 [[ ${var} =~ ^[0-9]+$ ]]
316 }
317
318 ismac() {
319 local mac=${!1}
320
321 mac_is_valid ${mac}
322 }
323
324 isipaddress() {
325 local addr=${!1}
326
327 ip_is_valid ${addr}
328 }
329
330 mtu_is_valid() {
331 local proto=${1}
332 local mtu=${2}
333
334 case ${proto} in
335 ipv4)
336 [ ${mtu} -ge 576 ] && [ ${mtu} -le 9000 ]
337 ;;
338 ipv6)
339 [ ${mtu} -ge 1280 ] && [ ${mtu} -le 9000 ]
340 ;;
341 *)
342 error "${proto} is not a valid proto"
343 return ${EXIT_ERROR}
344 ;;
345 esac
346 }
347
348 backtrace() {
349 local start=1
350
351 echo # Empty line
352 error_log "Backtrace (most recent call in first line):"
353
354 local i source
355 for i in $(seq ${start} ${#BASH_SOURCE[*]}); do
356 [ -z "${FUNCNAME[${i}]}" ] && continue
357
358 # Print called binary with arguments.
359 if [ "${FUNCNAME[${i}]}" == "main" ]; then
360 local args="$(list_reverse ${BASH_ARGV[*]})"
361 printf -v source "%20s" "$0"
362 error_log " ${source} ${args}"
363 continue
364 fi
365
366 source=${BASH_SOURCE[$(( ${i} + 1 ))]}
367 error_log " $(printf "%20s" "'${FUNCNAME[${i}]}'") called from ${source:-<shell>}:${BASH_LINENO[${i}]}"
368 done
369 }
370
371 assert() {
372 local assertion="$@"
373
374 if ! ${assertion}; then
375 error_log "Assertion '${assertion}' failed."
376 backtrace
377 exit ${EXIT_ERROR_ASSERT}
378 fi
379
380 return ${EXIT_OK}
381 }
382
383 # This function checks, if the given argument is an assert error
384 # exit code. If this is the case, the script will halt immediately.
385 assert_check_retval() {
386 local ret=${1}
387
388 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
389 exit ${EXIT_ERROR_ASSERT}
390 fi
391
392 return ${ret}
393 }
394
395 # This function executes the given command and inverses the return code
396 not() {
397 local command="$@"
398
399 ${command} && return ${EXIT_FALSE} || return ${EXIT_TRUE}
400 }
401
402 exec_cmd() {
403 local cmd=$@
404
405 log DEBUG "Running command: ${cmd}"
406
407 DEBUG=${DEBUG} \
408 LOG_DISABLE_STDOUT="${LOG_DISABLE_STDOUT}" \
409 LOG_FACILITY="${LOG_FACILITY}" \
410 ${SHELL} ${cmd}
411 local ret=$?
412
413 #log DEBUG "Returned with code '${ret}'"
414
415 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
416 error_log "Stopping parent process due to assertion error in child process: ${cmd}"
417 exit ${EXIT_ERROR_ASSERT}
418 fi
419
420 return ${ret}
421 }
422
423 cmd() {
424 local cmd=$@
425
426 log DEBUG "Running command: ${cmd}"
427
428 ${cmd}
429 local ret=$?
430
431 log DEBUG "Returned with code '${ret}'"
432
433 return ${ret}
434 }
435
436 cmd_quiet() {
437 cmd $@ &>/dev/null
438 }
439
440 cmd_exec() {
441 local cmd=$@
442
443 log DEBUG "Exec'ing command: ${cmd}"
444
445 exec ${cmd}
446
447 log ERROR "Could not exec-ute: ${cmd}"
448 exit ${EXIT_ERROR}
449 }
450
451 cmd_not_implemented() {
452 assert false "not implemented"
453 }
454
455 # Runs a command in a clean environment so that no confidential information
456 # is leaked to any untrusted commands.
457 cmd_clean_environment() {
458 local cmd=$@
459
460 log DEBUG "Running command in a clean environment: ${cmd}"
461 env -i -- ${cmd}
462 local ret=${?}
463
464 log DEBUG "Returned with code '${ret}'"
465 return ${ret}
466 }
467
468 # Executes the given command in background
469 cmd_background() {
470 cmd_quiet $@ &
471 }
472
473 # Prints the PID of the process that was started last
474 cmd_background_get_pid() {
475 print "${!}"
476 }
477
478 cmd_background_result() {
479 local pids=$@
480
481 wait ${pids}
482 }
483
484 # Increase security of the read command
485 read() {
486 builtin read -r $@
487 }
488
489 seq() {
490 if [ $# -eq 2 ]; then
491 eval echo {${1}..${2}}
492 elif [ $# -eq 3 ]; then
493 eval echo {${1}..${3}..${2}}
494 fi
495 }
496
497 range() {
498 eval echo {0..$(( ${1} - 1 ))}
499 }
500
501 count() {
502 local i=0
503
504 while read; do
505 ((i++))
506 done
507
508 echo ${i}
509 }
510
511 which() {
512 type -P $@
513 }
514
515 # Prints the number of seconds since epoch.
516 timestamp() {
517 date -u "+%s"
518 }
519
520 beautify_time() {
521 local value=${1}
522
523 local unit
524 local limit
525 for unit in s m h d w; do
526 case "${unit}" in
527 s|m|h)
528 limit=60
529 ;;
530 d)
531 limit=24
532 ;;
533 w)
534 limit=7
535 ;;
536 esac
537
538 [ ${value} -lt ${limit} ] && break
539
540 value=$(( ${value} / ${limit} ))
541 done
542
543 echo "${value}${unit}"
544 }
545
546 beautify_bytes() {
547 local value=${1}
548
549 local unit
550 local limit=1024
551 for unit in B k M G T; do
552 [ ${value} -lt ${limit} ] && break
553 value=$(( ${value} / ${limit} ))
554 done
555
556 echo "${value}${unit}"
557 }
558
559 module_load() {
560 local module=${1}
561
562 if ! grep -q "^${module}" /proc/modules; then
563 log DEBUG "Loading module '${module}'."
564 modprobe ${module}
565 fi
566 }
567
568 binary_exists() {
569 local binary=${1}
570
571 if [ -n "$(type -p ${binary})" ]; then
572 return ${EXIT_OK}
573 fi
574
575 return ${EXIT_ERROR}
576 }
577
578 function_exists() {
579 local function="${1}"
580
581 if [ "$(type -t "${function}")" = "function" ]; then
582 return ${EXIT_TRUE}
583 fi
584
585 return ${EXIT_FALSE}
586 }
587
588 process_kill() {
589 local process=${1}
590
591 if ! isinteger process; then
592 process=$(pidof ${process})
593 fi
594
595 local pid
596 local sig
597 for pid in ${process}; do
598 for sig in 15 9; do
599 [ -d "/proc/${pid}" ] || break
600
601 kill -${sig} ${pid}
602 sleep 1
603 done
604 done
605 }
606
607 dec() {
608 local hex=${1}
609
610 if [ "${hex:0:2}" != "0x" ]; then
611 hex="0x${hex}"
612 fi
613
614 printf "%d\n" "${hex}"
615 }
616
617 chr() {
618 local char="${1}"
619
620 [ ${char} -lt 256 ] || return ${EXIT_ERROR}
621
622 printf "\\$(( ${char} / 64 * 100 + ${char} % 64 / 8 * 10 + ${char} % 8 ))\n"
623 }
624
625 ord() {
626 LC_CTYPE="C" printf "%d\n" "'${1}"
627 }
628
629 hex() {
630 printf "%X\n" "${1}"
631 }
632
633 network_is_running() {
634 # Check, if the network service is running.
635 service_is_active network
636 }
637
638 contains_spaces() {
639 local var="$@"
640
641 # Eliminate spaces.
642 local var2=${var// /}
643
644 if [ ${#var} -ne ${#var2} ]; then
645 return ${EXIT_TRUE}
646 fi
647
648 return ${EXIT_FALSE}
649 }
650
651 string_split() {
652 local string="$@"
653
654 local pos=0
655 while [ ${pos} -lt ${#string} ]; do
656 print "${string:${pos}:1}"
657 pos=$(( ${pos} + 1 ))
658 done
659
660 return ${EXIT_OK}
661 }
662
663 string_reverse() {
664 local string="$@"
665
666 local output
667 local pos=0
668 while [ ${pos} -lt ${#string} ]; do
669 output="${string:${pos}:1}${output}"
670 pos=$(( ${pos} + 1 ))
671 done
672
673 print "${output}"
674 return ${EXIT_OK}
675 }
676
677 dec2bin() {
678 local number="${1}"
679
680 local output
681
682 local i div
683 for i in 7 6 5 4 3 2 1; do
684 div=$(( 2 ** ${i} ))
685
686 if [ $(( ${number} / ${div} )) -eq 1 ]; then
687 output="${output}1"
688 else
689 output="${output}0"
690 fi
691 number="$(( ${number} % ${div} ))"
692 done
693
694 if [ $(( ${number} % 2 )) -eq 1 ]; then
695 output="${output}1"
696 else
697 output="${output}0"
698 fi
699
700 print "${output}"
701 }
702
703 bin2dec() {
704 local string="${1}"
705 local number=0
706
707 local pos=0 char
708 while [ ${pos} -lt ${#string} ]; do
709 char="${string:${pos}:1}"
710 pos=$(( ${pos} + 1 ))
711
712 number=$(( ${number} << 1 ))
713
714 case "${char}" in
715 0) ;;
716 1)
717 number=$(( ${number} + 1 ))
718 ;;
719 *)
720 assert false "Invalid character: ${char}"
721 ;;
722 esac
723 done
724
725 print "${number}"
726 return ${EXIT_OK}
727 }
728
729 char2bin() {
730 local dec="$(ord "${1}")"
731
732 dec2bin "${dec}"
733 }
734
735 bin2char() {
736 local dec="$(bin2dec "$@")"
737
738 chr "${dec}"
739 }
740
741 bin2hex() {
742 local dec="$(bin2dec "$@")"
743
744 dec2hex "${dec}"
745 }
746
747 hex2bin() {
748 local dec="$(hex2dec "$@")"
749
750 dec2bin "${dec}"
751 }
752
753 hex2dec() {
754 local hex="${1}"
755
756 # Prepend 0x if necessary.
757 [ "${hex:0:2}" = "0x" ] || hex="0x${hex}"
758
759 printf "%d\n" "${hex}"
760 }
761
762 dec2hex() {
763 printf "%02x\n" "${1}"
764 }