]> git.ipfire.org Git - people/ms/network.git/blob - src/functions/functions.util
Allow renaming zones
[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 three functions are kept for backwards
86 # compatibility. The need to be dropped at some time.
87 listsort() {
88 list_sort $@
89 }
90
91 listmatch() {
92 list_match $@
93 }
94
95 listlength() {
96 list_length $@
97 }
98
99 # Speedup function to avoid a call of the basename binary
100 basename() {
101 echo "${1##*/}"
102 }
103
104 format() {
105 local key=${1}
106 assert isset key
107
108 local format=${2}
109 assert isset format
110
111 shift 2
112
113 printf -v "${key}" "${format}" "$@"
114 }
115
116 assign() {
117 local key=${1}
118 assert isset key
119 shift
120
121 format "${key}" "%s" "$@"
122 }
123
124 fread() {
125 local file=${1}
126 assert isset file
127
128 [ -r "${file}" ] || return ${EXIT_ERROR}
129
130 print "$(<${file})"
131 }
132
133 fwrite() {
134 local file=${1}
135 assert isset file
136 shift
137
138 if [ ! -w "${file}" ]; then
139 log ERROR "${file}: No such file"
140 return ${EXIT_ERROR}
141 fi
142
143 print "%s" "$@" >> ${file} 2>/dev/null
144 }
145
146 make_parent_dir() {
147 local path="${1}"
148
149 local dirname="$(dirname "${path}")"
150 mkdir -p "${dirname}"
151 }
152
153 enabled() {
154 local param=${1}
155
156 list_match "${!param}" yes on true 1
157 }
158
159 mac_generate() {
160 local b="$(random 12)"
161
162 # Remove multicast bit
163 # and set address is software assigned
164 local first_byte=$(( 0x${b:0:2} & 0xfe ))
165 first_byte=$(( ${first_byte} | 0x02 ))
166
167 local output
168 printf -v output "%02x" "${first_byte}"
169
170 output="${output}:${b:2:2}:${b:4:2}:${b:6:2}:${b:8:2}:${b:10:2}"
171
172 # Check if output is valid
173 assert mac_is_valid "${output}"
174
175 echo "${output}"
176 }
177
178 mac_format() {
179 local mac=${1}
180 assert isset mac
181
182 # Remove all colons and make the rest lowercase.
183 mac=${mac//:/}
184 mac=${mac,,}
185
186 local output
187 if [ "${#mac}" = "12" ]; then
188 # Add colons (:) to mac address
189 output=${mac:0:2}
190 local i
191 for i in 2 4 6 8 10; do
192 output="${output}:${mac:${i}:2}"
193 done
194 else
195 output=${mac}
196 fi
197
198 assert mac_is_valid ${output}
199
200 print "${output}"
201 }
202
203 mac_is_valid() {
204 local mac=${1}
205
206 [[ ${mac} =~ ^([0-9a-f]{2}\:){5}[0-9a-f]{2}$ ]]
207 }
208
209 uuid() {
210 echo $(</proc/sys/kernel/random/uuid)
211 }
212
213 rand() {
214 local uuid="$(uuid)"
215 echo "${uuid//-/}"
216 }
217
218 random() {
219 local length="${1:-8}"
220
221 local random
222 while [ ${#random} -lt ${length} ]; do
223 random="${random}$(rand)"
224 done
225
226 echo "${random:0:${length}}"
227 }
228
229 isset() {
230 local var=${1}
231
232 [ -n "${!var}" ]
233 }
234
235 isoneof() {
236 local var=${!1}
237 shift
238
239 list_match "${var}" "$@"
240 }
241
242 isbool() {
243 local var=${1}
244
245 isoneof ${var} 0 1 no yes on off
246 }
247
248 isinteger() {
249 local var=${!1}
250
251 [[ ${var} =~ ^[0-9]+$ ]]
252 }
253
254 ismac() {
255 local mac=${!1}
256
257 mac_is_valid ${mac}
258 }
259
260 isipaddress() {
261 local addr=${!1}
262
263 ip_is_valid ${addr}
264 }
265
266 backtrace() {
267 local start=1
268
269 echo # Empty line
270 error_log "Backtrace (most recent call in first line):"
271
272 local i source
273 for i in $(seq ${start} ${#BASH_SOURCE[*]}); do
274 [ -z "${FUNCNAME[${i}]}" ] && continue
275
276 # Print called binary with arguments.
277 if [ "${FUNCNAME[${i}]}" == "main" ]; then
278 local args="$(list_reverse ${BASH_ARGV[*]})"
279 printf -v source "%20s" "$0"
280 error_log " ${source} ${args}"
281 continue
282 fi
283
284 source=${BASH_SOURCE[$(( ${i} + 1 ))]}
285 error_log " $(printf "%20s" "'${FUNCNAME[${i}]}'") called from ${source:-<shell>}:${BASH_LINENO[${i}]}"
286 done
287 }
288
289 assert() {
290 local assertion="$@"
291
292 if ! ${assertion}; then
293 error_log "Assertion '${assertion}' failed."
294 backtrace
295 exit ${EXIT_ERROR_ASSERT}
296 fi
297
298 return ${EXIT_OK}
299 }
300
301 # This function checks, if the given argument is an assert error
302 # exit code. If this is the case, the script will halt immediately.
303 assert_check_retval() {
304 local ret=${1}
305
306 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
307 exit ${EXIT_ERROR_ASSERT}
308 fi
309
310 return ${ret}
311 }
312
313 # This function executes the given command and inverses the return code
314 not() {
315 local command="$@"
316
317 ${command} && return ${EXIT_FALSE} || return ${EXIT_TRUE}
318 }
319
320 exec_cmd() {
321 local cmd=$@
322
323 log DEBUG "Running command: ${cmd}"
324
325 DEBUG=${DEBUG} \
326 LOG_DISABLE_STDOUT="${LOG_DISABLE_STDOUT}" \
327 LOG_FACILITY="${LOG_FACILITY}" \
328 ${SHELL} ${cmd}
329 local ret=$?
330
331 #log DEBUG "Returned with code '${ret}'"
332
333 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
334 error_log "Stopping parent process due to assertion error in child process: ${cmd}"
335 exit ${EXIT_ERROR_ASSERT}
336 fi
337
338 return ${ret}
339 }
340
341 cmd() {
342 local cmd=$@
343
344 log DEBUG "Running command: ${cmd}"
345
346 ${cmd}
347 local ret=$?
348
349 log DEBUG "Returned with code '${ret}'"
350
351 return ${ret}
352 }
353
354 cmd_quiet() {
355 cmd $@ &>/dev/null
356 }
357
358 cmd_exec() {
359 local cmd=$@
360
361 log DEBUG "Exec'ing command: ${cmd}"
362
363 exec ${cmd}
364
365 log ERROR "Could not exec-ute: ${cmd}"
366 exit ${EXIT_ERROR}
367 }
368
369 cmd_not_implemented() {
370 assert false "not implemented"
371 }
372
373 # Runs a command in a clean environment so that no confidential information
374 # is leaked to any untrusted commands.
375 cmd_clean_environment() {
376 local cmd=$@
377
378 log DEBUG "Running command in a clean environment: ${cmd}"
379 env -i -- ${cmd}
380 local ret=${?}
381
382 log DEBUG "Returned with code '${ret}'"
383 return ${ret}
384 }
385
386 # Increase security of the read command
387 read() {
388 builtin read -r $@
389 }
390
391 seq() {
392 if [ $# -eq 2 ]; then
393 eval echo {${1}..${2}}
394 elif [ $# -eq 3 ]; then
395 eval echo {${1}..${3}..${2}}
396 fi
397 }
398
399 which() {
400 type -P $@
401 }
402
403 # Prints the number of seconds since epoch.
404 timestamp() {
405 date -u "+%s"
406 }
407
408 beautify_time() {
409 local value=${1}
410
411 local unit
412 local limit
413 for unit in s m h d w; do
414 case "${unit}" in
415 s|m|h)
416 limit=60
417 ;;
418 d)
419 limit=24
420 ;;
421 w)
422 limit=7
423 ;;
424 esac
425
426 [ ${value} -lt ${limit} ] && break
427
428 value=$(( ${value} / ${limit} ))
429 done
430
431 echo "${value}${unit}"
432 }
433
434 beautify_bytes() {
435 local value=${1}
436
437 local unit
438 local limit=1024
439 for unit in B k M G T; do
440 [ ${value} -lt ${limit} ] && break
441 value=$(( ${value} / ${limit} ))
442 done
443
444 echo "${value}${unit}"
445 }
446
447 module_load() {
448 local module=${1}
449
450 if ! grep -q "^${module}" /proc/modules; then
451 log DEBUG "Loading module '${module}'."
452 modprobe ${module}
453 fi
454 }
455
456 binary_exists() {
457 local binary=${1}
458
459 if [ -n "$(type -p ${binary})" ]; then
460 return ${EXIT_OK}
461 fi
462
463 return ${EXIT_ERROR}
464 }
465
466 function_exists() {
467 local function="${1}"
468
469 if [ "$(type -t "${function}")" = "function" ]; then
470 return ${EXIT_TRUE}
471 fi
472
473 return ${EXIT_FALSE}
474 }
475
476 process_kill() {
477 local process=${1}
478
479 if ! isinteger process; then
480 process=$(pidof ${process})
481 fi
482
483 local pid
484 local sig
485 for pid in ${process}; do
486 for sig in 15 9; do
487 [ -d "/proc/${pid}" ] || break
488
489 kill -${sig} ${pid}
490 sleep 1
491 done
492 done
493 }
494
495 dec() {
496 local hex=${1}
497
498 if [ "${hex:0:2}" != "0x" ]; then
499 hex="0x${hex}"
500 fi
501
502 printf "%d\n" "${hex}"
503 }
504
505 chr() {
506 local char="${1}"
507
508 [ ${char} -lt 256 ] || return ${EXIT_ERROR}
509
510 printf "\\$(( ${char} / 64 * 100 + ${char} % 64 / 8 * 10 + ${char} % 8 ))\n"
511 }
512
513 ord() {
514 LC_CTYPE="C" printf "%d\n" "'${1}"
515 }
516
517 hex() {
518 printf "%X\n" "${1}"
519 }
520
521 network_is_running() {
522 # Check, if the network service is running.
523 service_is_active network
524 }
525
526 contains_spaces() {
527 local var="$@"
528
529 # Eliminate spaces.
530 local var2=${var// /}
531
532 if [ ${#var} -ne ${#var2} ]; then
533 return ${EXIT_TRUE}
534 fi
535
536 return ${EXIT_FALSE}
537 }
538
539 string_split() {
540 local string="$@"
541
542 local pos=0
543 while [ ${pos} -lt ${#string} ]; do
544 print "${string:${pos}:1}"
545 pos=$(( ${pos} + 1 ))
546 done
547
548 return ${EXIT_OK}
549 }
550
551 string_reverse() {
552 local string="$@"
553
554 local output
555 local pos=0
556 while [ ${pos} -lt ${#string} ]; do
557 output="${string:${pos}:1}${output}"
558 pos=$(( ${pos} + 1 ))
559 done
560
561 print "${output}"
562 return ${EXIT_OK}
563 }
564
565 dec2bin() {
566 local number="${1}"
567
568 local output
569
570 local i div
571 for i in 7 6 5 4 3 2 1; do
572 div=$(( 2 ** ${i} ))
573
574 if [ $(( ${number} / ${div} )) -eq 1 ]; then
575 output="${output}1"
576 else
577 output="${output}0"
578 fi
579 number="$(( ${number} % ${div} ))"
580 done
581
582 if [ $(( ${number} % 2 )) -eq 1 ]; then
583 output="${output}1"
584 else
585 output="${output}0"
586 fi
587
588 print "${output}"
589 }
590
591 bin2dec() {
592 local string="${1}"
593 local number=0
594
595 local pos=0 char
596 while [ ${pos} -lt ${#string} ]; do
597 char="${string:${pos}:1}"
598 pos=$(( ${pos} + 1 ))
599
600 number=$(( ${number} << 1 ))
601
602 case "${char}" in
603 0) ;;
604 1)
605 number=$(( ${number} + 1 ))
606 ;;
607 *)
608 assert false "Invalid character: ${char}"
609 ;;
610 esac
611 done
612
613 print "${number}"
614 return ${EXIT_OK}
615 }
616
617 char2bin() {
618 local dec="$(ord "${1}")"
619
620 dec2bin "${dec}"
621 }
622
623 bin2char() {
624 local dec="$(bin2dec "$@")"
625
626 chr "${dec}"
627 }
628
629 bin2hex() {
630 local dec="$(bin2dec "$@")"
631
632 dec2hex "${dec}"
633 }
634
635 hex2bin() {
636 local dec="$(hex2dec "$@")"
637
638 dec2bin "${dec}"
639 }
640
641 hex2dec() {
642 local hex="${1}"
643
644 # Prepend 0x if necessary.
645 [ "${hex:0:2}" = "0x" ] || hex="0x${hex}"
646
647 printf "%d\n" "${hex}"
648 }
649
650 dec2hex() {
651 printf "%02x\n" "${1}"
652 }