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