d4402c3a148ae1f7aede36d6bdc1c8775ec38116
[openwrt/openwrt.git] / package / base-files / files / lib / functions / system.sh
1 # Copyright (C) 2006-2013 OpenWrt.org
2
3 get_mac_binary() {
4 local path="$1"
5 local offset="$2"
6
7 if [ -z "$path" ]; then
8 echo "get_mac_binary: file $path not found!" >&2
9 return
10 fi
11
12 hexdump -v -n 6 -s $offset -e '5/1 "%02x:" 1/1 "%02x"' $path 2>/dev/null
13 }
14
15 find_mtd_chardev() {
16 local INDEX=$(find_mtd_index "$1")
17 local PREFIX=/dev/mtd
18
19 [ -d /dev/mtd ] && PREFIX=/dev/mtd/
20 echo "${INDEX:+$PREFIX$INDEX}"
21 }
22
23 mtd_get_mac_ascii()
24 {
25 local mtdname="$1"
26 local key="$2"
27 local part
28 local mac_dirty
29
30 part=$(find_mtd_part "$mtdname")
31 if [ -z "$part" ]; then
32 echo "mtd_get_mac_ascii: partition $mtdname not found!" >&2
33 return
34 fi
35
36 mac_dirty=$(strings "$part" | sed -n 's/^'"$key"'=//p')
37
38 # "canonicalize" mac
39 [ -n "$mac_dirty" ] && macaddr_canonicalize "$mac_dirty"
40 }
41
42 mtd_get_mac_binary() {
43 local mtdname="$1"
44 local offset="$2"
45 local part
46
47 part=$(find_mtd_part "$mtdname")
48 get_mac_binary "$part" "$offset"
49 }
50
51 mtd_get_mac_binary_ubi() {
52 local mtdname="$1"
53 local offset="$2"
54
55 . /lib/upgrade/nand.sh
56
57 local ubidev=$(nand_find_ubi $CI_UBIPART)
58 local part=$(nand_find_volume $ubidev $1)
59
60 if [ -z "$part" ]; then
61 echo "mtd_get_mac_binary: ubi volume $mtdname not found!" >&2
62 return
63 fi
64
65 hexdump -v -n 6 -s $offset -e '5/1 "%02x:" 1/1 "%02x"' /dev/$part 2>/dev/null
66 }
67
68 mtd_get_part_size() {
69 local part_name=$1
70 local first dev size erasesize name
71 while read dev size erasesize name; do
72 name=${name#'"'}; name=${name%'"'}
73 if [ "$name" = "$part_name" ]; then
74 echo $((0x$size))
75 break
76 fi
77 done < /proc/mtd
78 }
79
80 macaddr_add() {
81 local mac=$1
82 local val=$2
83 local oui=${mac%:*:*:*}
84 local nic=${mac#*:*:*:}
85
86 nic=$(printf "%06x" $((0x${nic//:/} + $val & 0xffffff)) | sed 's/^\(.\{2\}\)\(.\{2\}\)\(.\{2\}\)/\1:\2:\3/')
87 echo $oui:$nic
88 }
89
90 macaddr_setbit_la()
91 {
92 local mac=$1
93
94 printf "%02x:%s" $((0x${mac%%:*} | 0x02)) ${mac#*:}
95 }
96
97 macaddr_2bin()
98 {
99 local mac=$1
100
101 echo -ne \\x${mac//:/\\x}
102 }
103
104 macaddr_canonicalize()
105 {
106 local mac="$1"
107 local canon=""
108
109 mac=$(echo -n $mac | tr -d \")
110 [ ${#mac} -gt 17 ] && return
111 [ -n "${mac//[a-fA-F0-9\.: -]/}" ] && return
112
113 for octet in ${mac//[\.:-]/ }; do
114 case "${#octet}" in
115 1)
116 octet="0${octet}"
117 ;;
118 2)
119 ;;
120 4)
121 octet="${octet:0:2} ${octet:2:2}"
122 ;;
123 12)
124 octet="${octet:0:2} ${octet:2:2} ${octet:4:2} ${octet:6:2} ${octet:8:2} ${octet:10:2}"
125 ;;
126 *)
127 return
128 ;;
129 esac
130 canon=${canon}${canon:+ }${octet}
131 done
132
133 [ ${#canon} -ne 17 ] && return
134
135 printf "%02x:%02x:%02x:%02x:%02x:%02x" 0x${canon// / 0x} 2>/dev/null
136 }