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