cleanups in networking scripts, fix for pptp and pppoe
[openwrt/svn-archive/archive.git] / openwrt / package / base-files / default / etc / functions.sh
1 #!/bin/ash
2
3 alias debug=${DEBUG:-:}
4
5 # allow env to override nvram
6 nvram () {
7 case $1 in
8 get) eval "echo \${NVRAM_$2:-\$(command nvram get $2)}";;
9 *) command nvram $*;;
10 esac
11 }
12 [ "$FAILSAFE" = "true" ] && . /etc/nvram.overrides
13
14 # valid interface?
15 if_valid () (
16 ifconfig "$1" >&- 2>&- ||
17 [ "${1%%[0-9]}" = "br" ] ||
18 {
19 [ "${1%%[0-9]}" = "vlan" ] && (
20 i=${1#vlan}
21 hwname=$(nvram get vlan${i}hwname)
22 hwaddr=$(nvram get ${hwname}macaddr)
23 [ -z "$hwaddr" ] && return 1
24
25 vif=$(ifconfig -a | awk '/^eth.*'$hwaddr'/ {print $1; exit}' IGNORECASE=1)
26 debug "# vlan$i => $vif"
27
28 $DEBUG ifconfig $vif up
29 $DEBUG vconfig add $vif $i 2>&-
30 )
31 } ||
32 { debug "# missing interface '$1' ignored"; false; }
33 )
34
35 do_ifup() {
36 if_proto=$(nvram get ${2}_proto)
37 if=$(nvram get ${2}_ifname)
38 [ "${if%%[0-9]}" = "ppp" ] && if=$(nvram get ${if_proto}_ifname)
39
40 pidfile=/var/run/${if}.pid
41 [ -f $pidfile ] && $DEBUG kill $(cat $pidfile)
42
43 case "$1" in
44 static)
45 ip=$(nvram get ${2}_ipaddr)
46 netmask=$(nvram get ${2}_netmask)
47 gateway=$(nvram get ${2}_gateway)
48
49 $DEBUG ifconfig $if $ip ${netmask:+netmask $netmask} broadcast + up
50 ${gateway:+$DEBUG route add default gw $gateway}
51
52 [ -f /etc/resolv.conf ] && return
53
54 debug "# --- creating /etc/resolv.conf ---"
55 for dns in $(nvram get ${2}_dns); do
56 echo "nameserver $dns" >> /etc/resolv.conf
57 done
58 ;;
59 dhcp)
60 DHCP_IP=$(nvram get ${2}_ipaddr)
61 DHCP_NETMASK=$(nvram get ${2}_netmask)
62 $DEBUG ifconfig $if $ip ${netmask:+netmask $netmask} broadcast + up
63
64 DHCP_ARGS="-i $if ${DHCP_IP:+-r $DHCP_IP} -b -p $pidfile"
65 DHCP_HOSTNAME=$(nvram get ${2}_hostname)
66 DHCP_HOSTNAME=${DHCP_HOSTNAME%%.*}
67 [ -z $DHCP_HOSTNAME ] || DHCP_ARGS="$DHCP_ARGS -H $DHCP_HOSTNAME"
68 [ "$if_proto" = "pptp" ] && DHCP_ARGS="$DHCP_ARGS -n -q" || DHCP_ARGS="$DHCP_ARGS -R &"
69 ${DEBUG:-eval} "udhcpc $DHCP_ARGS"
70 ;;
71 none|"")
72 ;;
73 *)
74 [ -x "/sbin/ifup.$1" ] && { $DEBUG /sbin/ifup.$1 ${2}; exit; }
75 echo "### ifup ${2}: ignored ${2}_proto=\"$1\" (not supported)"
76 ;;
77 esac
78 }
79
80 bitcount () {
81 local c=$1
82 echo $((
83 c=((c>> 1)&0x55555555)+(c&0x55555555),
84 c=((c>> 2)&0x33333333)+(c&0x33333333),
85 c=((c>> 4)&0x0f0f0f0f)+(c&0x0f0f0f0f),
86 c=((c>> 8)&0x00ff00ff)+(c&0x00ff00ff),
87 c=((c>>16)&0x0000ffff)+(c&0x0000ffff)
88 ))
89 }
90
91 valid_netmask () {
92 return $((-($1)&~$1))
93 }
94
95 ip2int () (
96 set $(echo $1 | tr '\.' ' ')
97 echo $(($1<<24|$2<<16|$3<<8|$4))
98 )
99
100 int2ip () {
101 echo $(($1>>24&255)).$(($1>>16&255)).$(($1>>8&255)).$(($1&255))
102 }