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