]> git.ipfire.org Git - people/stevee/network.git/blob - src/functions/functions.util
f627d99dd0c779cca3efc1180ec45ba752cd983a
[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 function 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 function args() {
33 echo "$@" | xargs printf "%s\n"
34 }
35
36 function 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 function quote() {
52 print "\"%s\"" "$@"
53 }
54
55 function 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 function error() {
69 echo -e " ${CLR_RED_B}ERROR${CLR_RESET} : $@" >&2
70 }
71
72 function error_log() {
73 log ERROR "$@"
74 }
75
76 # Print a pretty warn message
77 function warning() {
78 echo -e " ${CLR_YELLOW_B}WARNING${CLR_RESET}: $@" >&2
79 }
80
81 function 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 function listsort() {
88 list_sort $@
89 }
90
91 function listmatch() {
92 list_match $@
93 }
94
95 function listlength() {
96 list_length $@
97 }
98
99 # Speedup function to avoid a call of the basename binary
100 function basename() {
101 echo "${1##*/}"
102 }
103
104 function 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 function assign() {
117 local key=${1}
118 assert isset key
119 shift
120
121 format "${key}" "%s" "$@"
122 }
123
124 function fread() {
125 local file=${1}
126 assert isset file
127
128 [ -r "${file}" ] || return ${EXIT_ERROR}
129
130 print "$(<${file})"
131 }
132
133 function 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 function enabled() {
147 local param=${1}
148
149 list_match "${!param}" yes on true 1
150 }
151
152 function 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 function 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 function mac_is_valid() {
213 local mac=${1}
214
215 [[ ${mac} =~ ^([0-9a-f]{2}\:){5}[0-9a-f]{2}$ ]]
216 }
217
218 function uuid() {
219 echo $(</proc/sys/kernel/random/uuid)
220 }
221
222 function isset() {
223 local var=${1}
224
225 [ -n "${!var}" ]
226 }
227
228 function isoneof() {
229 local var=${!1}
230 shift
231
232 list_match "${var}" "$@"
233 }
234
235 function isbool() {
236 local var=${1}
237
238 isoneof ${var} 0 1 no yes on off
239 }
240
241 function isinteger() {
242 local var=${!1}
243
244 [[ ${var} =~ ^[0-9]+$ ]]
245 }
246
247 function ismac() {
248 local mac=${!1}
249
250 mac_is_valid ${mac}
251 }
252
253 function isipaddress() {
254 local addr=${!1}
255
256 ip_is_valid ${addr}
257 }
258
259 function 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 function 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 function 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 function 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 function 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 function cmd_quiet() {
341 cmd $@ &>/dev/null
342 }
343
344 function 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 function cmd_not_implemented() {
356 assert false "not implemented"
357 }
358
359 # Increase security of the read command
360 function read() {
361 builtin read -r $@
362 }
363
364 function 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 function which() {
373 type -P $@
374 }
375
376 # Prints the number of seconds since epoch.
377 function timestamp() {
378 date -u "+%s"
379 }
380
381 function 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 function 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 function 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 function 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 process_kill() {
440 local process=${1}
441
442 if ! isinteger process; then
443 process=$(pidof ${process})
444 fi
445
446 local pid
447 local sig
448 for pid in ${process}; do
449 for sig in 15 9; do
450 [ -d "/proc/${pid}" ] || break
451
452 kill -${sig} ${pid}
453 sleep 1
454 done
455 done
456 }
457
458 function dec() {
459 local hex=${1}
460
461 if [ "${hex:0:2}" != "0x" ]; then
462 hex="0x${hex}"
463 fi
464
465 printf "%d\n" "${hex}"
466 }
467
468 function chr() {
469 local char="${1}"
470
471 [ ${char} -lt 256 ] || return ${EXIT_ERROR}
472
473 printf "\\$(( ${char} / 64 * 100 + ${char} % 64 / 8 * 10 + ${char} % 8 ))\n"
474 }
475
476 function ord() {
477 LC_CTYPE="C" printf "%d\n" "'${1}"
478 }
479
480 function hex() {
481 printf "%X\n" "${1}"
482 }
483
484 function network_is_running() {
485 # Check, if the network service is running.
486 service_is_active network
487 }
488
489 function contains_spaces() {
490 local var="$@"
491
492 # Eliminate spaces.
493 local var2=${var// /}
494
495 if [ ${#var} -ne ${#var2} ]; then
496 return ${EXIT_TRUE}
497 fi
498
499 return ${EXIT_FALSE}
500 }
501
502 function string_split() {
503 local string="$@"
504
505 local pos=0
506 while [ ${pos} -lt ${#string} ]; do
507 print "${string:${pos}:1}"
508 pos=$(( ${pos} + 1 ))
509 done
510
511 return ${EXIT_OK}
512 }
513
514 function string_reverse() {
515 local string="$@"
516
517 local output
518 local pos=0
519 while [ ${pos} -lt ${#string} ]; do
520 output="${string:${pos}:1}${output}"
521 pos=$(( ${pos} + 1 ))
522 done
523
524 print "${output}"
525 return ${EXIT_OK}
526 }
527
528 function dec2bin() {
529 local number="${1}"
530
531 local output
532
533 local i div
534 for i in 7 6 5 4 3 2 1; do
535 div=$(( 2 ** ${i} ))
536
537 if [ $(( ${number} / ${div} )) -eq 1 ]; then
538 output="${output}1"
539 else
540 output="${output}0"
541 fi
542 number="$(( ${number} % ${div} ))"
543 done
544
545 if [ $(( ${number} % 2 )) -eq 1 ]; then
546 output="${output}1"
547 else
548 output="${output}0"
549 fi
550
551 print "${output}"
552 }
553
554 function bin2dec() {
555 local string="${1}"
556 local number=0
557
558 local pos=0 char
559 while [ ${pos} -lt ${#string} ]; do
560 char="${string:${pos}:1}"
561 pos=$(( ${pos} + 1 ))
562
563 number=$(( ${number} << 1 ))
564
565 case "${char}" in
566 0) ;;
567 1)
568 number=$(( ${number} + 1 ))
569 ;;
570 *)
571 assert false "Invalid character: ${char}"
572 ;;
573 esac
574 done
575
576 print "${number}"
577 return ${EXIT_OK}
578 }
579
580 function char2bin() {
581 local dec="$(ord "${1}")"
582
583 dec2bin "${dec}"
584 }
585
586 function bin2char() {
587 local dec="$(bin2dec "$@")"
588
589 chr "${dec}"
590 }
591
592 function bin2hex() {
593 local dec="$(bin2dec "$@")"
594
595 dec2hex "${dec}"
596 }
597
598 function hex2bin() {
599 local dec="$(hex2dec "$@")"
600
601 dec2bin "${dec}"
602 }
603
604 function hex2dec() {
605 local hex="${1}"
606
607 # Prepend 0x if necessary.
608 [ "${hex:0:2}" = "0x" ] || hex="0x${hex}"
609
610 printf "%d\n" "${hex}"
611 }
612
613 function dec2hex() {
614 printf "%02x\n" "${1}"
615 }