]> git.ipfire.org Git - people/stevee/network.git/blob - src/functions/functions.util
util: add function mtu_is_valid
[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 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 mtu_is_valid() {
325 local proto=${1}
326 local mtu=${2}
327
328 case ${proto} in
329 ipv4)
330 [ ${mtu} -ge 576 ] && [ ${mtu} -le 9000 ]
331 ;;
332 ipv6)
333 [ ${mtu} -ge 1280 ] && [ ${mtu} -le 9000 ]
334 ;;
335 *)
336 error "${proto} is not a valid proto"
337 return ${EXIT_ERROR}
338 ;;
339 esac
340 }
341
342 backtrace() {
343 local start=1
344
345 echo # Empty line
346 error_log "Backtrace (most recent call in first line):"
347
348 local i source
349 for i in $(seq ${start} ${#BASH_SOURCE[*]}); do
350 [ -z "${FUNCNAME[${i}]}" ] && continue
351
352 # Print called binary with arguments.
353 if [ "${FUNCNAME[${i}]}" == "main" ]; then
354 local args="$(list_reverse ${BASH_ARGV[*]})"
355 printf -v source "%20s" "$0"
356 error_log " ${source} ${args}"
357 continue
358 fi
359
360 source=${BASH_SOURCE[$(( ${i} + 1 ))]}
361 error_log " $(printf "%20s" "'${FUNCNAME[${i}]}'") called from ${source:-<shell>}:${BASH_LINENO[${i}]}"
362 done
363 }
364
365 assert() {
366 local assertion="$@"
367
368 if ! ${assertion}; then
369 error_log "Assertion '${assertion}' failed."
370 backtrace
371 exit ${EXIT_ERROR_ASSERT}
372 fi
373
374 return ${EXIT_OK}
375 }
376
377 # This function checks, if the given argument is an assert error
378 # exit code. If this is the case, the script will halt immediately.
379 assert_check_retval() {
380 local ret=${1}
381
382 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
383 exit ${EXIT_ERROR_ASSERT}
384 fi
385
386 return ${ret}
387 }
388
389 # This function executes the given command and inverses the return code
390 not() {
391 local command="$@"
392
393 ${command} && return ${EXIT_FALSE} || return ${EXIT_TRUE}
394 }
395
396 exec_cmd() {
397 local cmd=$@
398
399 log DEBUG "Running command: ${cmd}"
400
401 DEBUG=${DEBUG} \
402 LOG_DISABLE_STDOUT="${LOG_DISABLE_STDOUT}" \
403 LOG_FACILITY="${LOG_FACILITY}" \
404 ${SHELL} ${cmd}
405 local ret=$?
406
407 #log DEBUG "Returned with code '${ret}'"
408
409 if [ ${ret} -eq ${EXIT_ERROR_ASSERT} ]; then
410 error_log "Stopping parent process due to assertion error in child process: ${cmd}"
411 exit ${EXIT_ERROR_ASSERT}
412 fi
413
414 return ${ret}
415 }
416
417 cmd() {
418 local cmd=$@
419
420 log DEBUG "Running command: ${cmd}"
421
422 ${cmd}
423 local ret=$?
424
425 log DEBUG "Returned with code '${ret}'"
426
427 return ${ret}
428 }
429
430 cmd_quiet() {
431 cmd $@ &>/dev/null
432 }
433
434 cmd_exec() {
435 local cmd=$@
436
437 log DEBUG "Exec'ing command: ${cmd}"
438
439 exec ${cmd}
440
441 log ERROR "Could not exec-ute: ${cmd}"
442 exit ${EXIT_ERROR}
443 }
444
445 cmd_not_implemented() {
446 assert false "not implemented"
447 }
448
449 # Runs a command in a clean environment so that no confidential information
450 # is leaked to any untrusted commands.
451 cmd_clean_environment() {
452 local cmd=$@
453
454 log DEBUG "Running command in a clean environment: ${cmd}"
455 env -i -- ${cmd}
456 local ret=${?}
457
458 log DEBUG "Returned with code '${ret}'"
459 return ${ret}
460 }
461
462 # Executes the given command in background
463 cmd_background() {
464 cmd_quiet $@ &
465 }
466
467 # Prints the PID of the process that was started last
468 cmd_background_get_pid() {
469 print "${!}"
470 }
471
472 cmd_background_result() {
473 local pids=$@
474
475 wait ${pids}
476 }
477
478 # Increase security of the read command
479 read() {
480 builtin read -r $@
481 }
482
483 seq() {
484 if [ $# -eq 2 ]; then
485 eval echo {${1}..${2}}
486 elif [ $# -eq 3 ]; then
487 eval echo {${1}..${3}..${2}}
488 fi
489 }
490
491 range() {
492 eval echo {0..$(( ${1} - 1 ))}
493 }
494
495 count() {
496 local i=0
497
498 while read; do
499 ((i++))
500 done
501
502 echo ${i}
503 }
504
505 which() {
506 type -P $@
507 }
508
509 # Prints the number of seconds since epoch.
510 timestamp() {
511 date -u "+%s"
512 }
513
514 beautify_time() {
515 local value=${1}
516
517 local unit
518 local limit
519 for unit in s m h d w; do
520 case "${unit}" in
521 s|m|h)
522 limit=60
523 ;;
524 d)
525 limit=24
526 ;;
527 w)
528 limit=7
529 ;;
530 esac
531
532 [ ${value} -lt ${limit} ] && break
533
534 value=$(( ${value} / ${limit} ))
535 done
536
537 echo "${value}${unit}"
538 }
539
540 beautify_bytes() {
541 local value=${1}
542
543 local unit
544 local limit=1024
545 for unit in B k M G T; do
546 [ ${value} -lt ${limit} ] && break
547 value=$(( ${value} / ${limit} ))
548 done
549
550 echo "${value}${unit}"
551 }
552
553 module_load() {
554 local module=${1}
555
556 if ! grep -q "^${module}" /proc/modules; then
557 log DEBUG "Loading module '${module}'."
558 modprobe ${module}
559 fi
560 }
561
562 binary_exists() {
563 local binary=${1}
564
565 if [ -n "$(type -p ${binary})" ]; then
566 return ${EXIT_OK}
567 fi
568
569 return ${EXIT_ERROR}
570 }
571
572 function_exists() {
573 local function="${1}"
574
575 if [ "$(type -t "${function}")" = "function" ]; then
576 return ${EXIT_TRUE}
577 fi
578
579 return ${EXIT_FALSE}
580 }
581
582 process_kill() {
583 local process=${1}
584
585 if ! isinteger process; then
586 process=$(pidof ${process})
587 fi
588
589 local pid
590 local sig
591 for pid in ${process}; do
592 for sig in 15 9; do
593 [ -d "/proc/${pid}" ] || break
594
595 kill -${sig} ${pid}
596 sleep 1
597 done
598 done
599 }
600
601 dec() {
602 local hex=${1}
603
604 if [ "${hex:0:2}" != "0x" ]; then
605 hex="0x${hex}"
606 fi
607
608 printf "%d\n" "${hex}"
609 }
610
611 chr() {
612 local char="${1}"
613
614 [ ${char} -lt 256 ] || return ${EXIT_ERROR}
615
616 printf "\\$(( ${char} / 64 * 100 + ${char} % 64 / 8 * 10 + ${char} % 8 ))\n"
617 }
618
619 ord() {
620 LC_CTYPE="C" printf "%d\n" "'${1}"
621 }
622
623 hex() {
624 printf "%X\n" "${1}"
625 }
626
627 network_is_running() {
628 # Check, if the network service is running.
629 service_is_active network
630 }
631
632 contains_spaces() {
633 local var="$@"
634
635 # Eliminate spaces.
636 local var2=${var// /}
637
638 if [ ${#var} -ne ${#var2} ]; then
639 return ${EXIT_TRUE}
640 fi
641
642 return ${EXIT_FALSE}
643 }
644
645 string_split() {
646 local string="$@"
647
648 local pos=0
649 while [ ${pos} -lt ${#string} ]; do
650 print "${string:${pos}:1}"
651 pos=$(( ${pos} + 1 ))
652 done
653
654 return ${EXIT_OK}
655 }
656
657 string_reverse() {
658 local string="$@"
659
660 local output
661 local pos=0
662 while [ ${pos} -lt ${#string} ]; do
663 output="${string:${pos}:1}${output}"
664 pos=$(( ${pos} + 1 ))
665 done
666
667 print "${output}"
668 return ${EXIT_OK}
669 }
670
671 dec2bin() {
672 local number="${1}"
673
674 local output
675
676 local i div
677 for i in 7 6 5 4 3 2 1; do
678 div=$(( 2 ** ${i} ))
679
680 if [ $(( ${number} / ${div} )) -eq 1 ]; then
681 output="${output}1"
682 else
683 output="${output}0"
684 fi
685 number="$(( ${number} % ${div} ))"
686 done
687
688 if [ $(( ${number} % 2 )) -eq 1 ]; then
689 output="${output}1"
690 else
691 output="${output}0"
692 fi
693
694 print "${output}"
695 }
696
697 bin2dec() {
698 local string="${1}"
699 local number=0
700
701 local pos=0 char
702 while [ ${pos} -lt ${#string} ]; do
703 char="${string:${pos}:1}"
704 pos=$(( ${pos} + 1 ))
705
706 number=$(( ${number} << 1 ))
707
708 case "${char}" in
709 0) ;;
710 1)
711 number=$(( ${number} + 1 ))
712 ;;
713 *)
714 assert false "Invalid character: ${char}"
715 ;;
716 esac
717 done
718
719 print "${number}"
720 return ${EXIT_OK}
721 }
722
723 char2bin() {
724 local dec="$(ord "${1}")"
725
726 dec2bin "${dec}"
727 }
728
729 bin2char() {
730 local dec="$(bin2dec "$@")"
731
732 chr "${dec}"
733 }
734
735 bin2hex() {
736 local dec="$(bin2dec "$@")"
737
738 dec2hex "${dec}"
739 }
740
741 hex2bin() {
742 local dec="$(hex2dec "$@")"
743
744 dec2bin "${dec}"
745 }
746
747 hex2dec() {
748 local hex="${1}"
749
750 # Prepend 0x if necessary.
751 [ "${hex:0:2}" = "0x" ] || hex="0x${hex}"
752
753 printf "%d\n" "${hex}"
754 }
755
756 dec2hex() {
757 printf "%02x\n" "${1}"
758 }