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