]> git.ipfire.org Git - people/ms/network.git/blob - src/functions/functions.util
util: Silence fwrite on error
[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 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 function seq() {
360 if [ $# -eq 2 ]; then
361 eval echo {${1}..${2}}
362 elif [ $# -eq 3 ]; then
363 eval echo {${1}..${3}..${2}}
364 fi
365 }
366
367 function which() {
368 type -P $@
369 }
370
371 # Prints the number of seconds since epoch.
372 function timestamp() {
373 date -u "+%s"
374 }
375
376 function beautify_time() {
377 local value=${1}
378
379 local unit
380 local limit
381 for unit in s m h d w; do
382 case "${unit}" in
383 s|m|h)
384 limit=60
385 ;;
386 d)
387 limit=24
388 ;;
389 w)
390 limit=7
391 ;;
392 esac
393
394 [ ${value} -lt ${limit} ] && break
395
396 value=$(( ${value} / ${limit} ))
397 done
398
399 echo "${value}${unit}"
400 }
401
402 function beautify_bytes() {
403 local value=${1}
404
405 local unit
406 local limit=1024
407 for unit in B k M G T; do
408 [ ${value} -lt ${limit} ] && break
409 value=$(( ${value} / ${limit} ))
410 done
411
412 echo "${value}${unit}"
413 }
414
415 function module_load() {
416 local module=${1}
417
418 if ! grep -q "^${module}" /proc/modules; then
419 log DEBUG "Loading module '${module}'."
420 modprobe ${module}
421 fi
422 }
423
424 function binary_exists() {
425 local binary=${1}
426
427 if [ -n "$(type -p ${binary})" ]; then
428 return ${EXIT_OK}
429 fi
430
431 return ${EXIT_ERROR}
432 }
433
434 function process_kill() {
435 local process=${1}
436
437 if ! isinteger process; then
438 process=$(pidof ${process})
439 fi
440
441 local pid
442 local sig
443 for pid in ${process}; do
444 for sig in 15 9; do
445 [ -d "/proc/${pid}" ] || break
446
447 kill -${sig} ${pid}
448 sleep 1
449 done
450 done
451 }
452
453 function dec() {
454 local hex=${1}
455
456 if [ "${hex:0:2}" != "0x" ]; then
457 hex="0x${hex}"
458 fi
459
460 printf "%d\n" "${hex}"
461 }
462
463 function chr() {
464 local char="${1}"
465
466 [ ${char} -lt 256 ] || return ${EXIT_ERROR}
467
468 printf "\\$(( ${char} / 64 * 100 + ${char} % 64 / 8 * 10 + ${char} % 8 ))\n"
469 }
470
471 function ord() {
472 LC_CTYPE="C" printf "%d\n" "'${1}"
473 }
474
475 function hex() {
476 printf "%X\n" "${1}"
477 }
478
479 function network_is_running() {
480 # Check, if the network service is running.
481 service_is_active network
482 }
483
484 function contains_spaces() {
485 local var="$@"
486
487 # Eliminate spaces.
488 local var2=${var// /}
489
490 if [ ${#var} -ne ${#var2} ]; then
491 return ${EXIT_TRUE}
492 fi
493
494 return ${EXIT_FALSE}
495 }
496
497 function string_split() {
498 local string="$@"
499
500 local pos=0
501 while [ ${pos} -lt ${#string} ]; do
502 print "${string:${pos}:1}"
503 pos=$(( ${pos} + 1 ))
504 done
505
506 return ${EXIT_OK}
507 }
508
509 function string_reverse() {
510 local string="$@"
511
512 local output
513 local pos=0
514 while [ ${pos} -lt ${#string} ]; do
515 output="${string:${pos}:1}${output}"
516 pos=$(( ${pos} + 1 ))
517 done
518
519 print "${output}"
520 return ${EXIT_OK}
521 }
522
523 function dec2bin() {
524 local number="${1}"
525
526 local output
527
528 local i div
529 for i in 7 6 5 4 3 2 1; do
530 div=$(( 2 ** ${i} ))
531
532 if [ $(( ${number} / ${div} )) -eq 1 ]; then
533 output="${output}1"
534 else
535 output="${output}0"
536 fi
537 number="$(( ${number} % ${div} ))"
538 done
539
540 if [ $(( ${number} % 2 )) -eq 1 ]; then
541 output="${output}1"
542 else
543 output="${output}0"
544 fi
545
546 print "${output}"
547 }
548
549 function bin2dec() {
550 local string="${1}"
551 local number=0
552
553 local pos=0 char
554 while [ ${pos} -lt ${#string} ]; do
555 char="${string:${pos}:1}"
556 pos=$(( ${pos} + 1 ))
557
558 number=$(( ${number} << 1 ))
559
560 case "${char}" in
561 0) ;;
562 1)
563 number=$(( ${number} + 1 ))
564 ;;
565 *)
566 assert false "Invalid character: ${char}"
567 ;;
568 esac
569 done
570
571 print "${number}"
572 return ${EXIT_OK}
573 }
574
575 function char2bin() {
576 local dec="$(ord "${1}")"
577
578 dec2bin "${dec}"
579 }
580
581 function bin2char() {
582 local dec="$(bin2dec "$@")"
583
584 chr "${dec}"
585 }
586
587 function bin2hex() {
588 local dec="$(bin2dec "$@")"
589
590 dec2hex "${dec}"
591 }
592
593 function hex2bin() {
594 local dec="$(hex2dec "$@")"
595
596 dec2bin "${dec}"
597 }
598
599 function hex2dec() {
600 local hex="${1}"
601
602 # Prepend 0x if necessary.
603 [ "${hex:0:2}" = "0x" ] || hex="0x${hex}"
604
605 printf "%d\n" "${hex}"
606 }
607
608 function dec2hex() {
609 printf "%02x\n" "${1}"
610 }