#!/bin/bash
#
#    cbq.init v0.6.4
#    Copyright (C) 1999  Pavel Golubev <[email protected]>
#
#    chkconfig:   2345 11 89
#    description: sets up CBQ-based traffic control
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#    You can always get the latest version from
#
#               ftp://ftp.equinox.gu.net/pub/linux/cbq/cbq.init
#
#
# VERSION HISTORY
# ---------------
# v0.6.4- Lubomir Bulej <[email protected]>
#         - added PRIO_* variables to allow easy control of filter priorities
#         - added caching to speed up CBQ start, the cache is invalidated
#           whenever any of the configuration files changes
#         - updated the readme section + some cosmetic fixes
# v0.6.3- Lubomir Bulej <[email protected]>
#         - removed setup of (unnecessary) class 1:1 - all classes
#           now use qdisc's default class 1:0 as their parent
#         - minor fix in the timecheck branch - classes
#           without leaf qdisc were not updated
#         - minor fix to avoid timecheck failure when run
#           at time with minutes 08 or 09
#         - respect CBQ_PATH setting in environment
#         - made PRIO=5 default, rendering it optional in configs
#         - added support for route filter, see notes about REALM keyword
#         - added support for fw filter, see notes about MARK keyword
#         - added filter display to "list" and "stats" commands
#         - readme section update + various cosmetic fixes
# v0.6.2- Catalin Petrescu <[email protected]>
#         - added tunnels interface handling
# v0.6.1- Pavel Golubev <[email protected]>
#         - added sch_prio module loading
#           (thanks [email protected] for reminding)
#         - resolved errors resulting from stricter syntax checking in bash2
#       - Lubomir Bulej <[email protected]>
#         - various cosmetic fixes
# v0.6  - Lubomir Bulej <[email protected]>
#         - attempt to limit number of spawned processes by utilizing
#           more of sed power (use sed instead of grep+cut)
#         - simplified TIME parser, using bash builtins
#         - added initial support for SFQ as leaf qdisc
#         - reworked the documentation part a little
#         - incorporated pending patches and ideas submitted by
#           following people for versions 0.3 into version 0.6
#       - Miguel Freitas <[email protected]>
#         - in case of overlapping TIME parameters, the last match is taken
#       - Juanjo Ciarlante <[email protected]>
#         - chkconfig tags, list + stats startup parameters
#         - optional tc & ip command logging (into /var/run/cbq-*)
#       - Rafal Maszkowski <[email protected]>
#         - PEAK parameter for setting TBF's burst peak rate
#         - fix for many config files (use find instead of ls)
# v0.5.1- Lubomir Bulej <[email protected]>
#         - fixed little but serious bug in RULE parser
# v0.5  - Lubomir Bulej <[email protected]>
#         - added options PARENT, LEAF, ISOLATED and BOUNDED. This allows
#           (with some attention to config file ordering) for creating
#           hierarchical structures of shapers with classes able (or unable)
#           to borrow bandwidth from their parents.
#         - class ID check allows hexadecimal numbers
#         - rewritten & simplified RULE parser
#         - cosmetic changes to improve readability
#         - reorganization to avoid duplicate code (timecheck etc.)
#         - timecheck doesn't check classes without TIME fields anymore
# v0.4  - Lubomir Bulej <[email protected]>
#         - small bugfix in RULE parsing code
#         - simplified configuration parsing code
#         - several small cosmetic changes
#         - TIME parameter can be now specified more than once allowing you to
#           differentiate RATE throughout the whole day. Time overlapping is
#           not checked, first match is taken. Midnight wrap (eg. 20:00-6:00)
#           is allowed and taken care of.
# v0.3a4- fixed small bug in IF operator. Thanks to
#         Rafal Maszkowski <[email protected]>
# v0.3a3- fixed grep bug when using more than 10 eth devices. Thanks to David
#         Trcka <[email protected]>.
# v0.3a2- fixed bug in "if" operator. Thanks [email protected].
# v0.3a - added TIME parameter. Example: TIME=00:00-19:00;64Kbit/6Kbit
#         So, between 00:00 and 19:00 the RATE will be 64Kbit.
#         Just start "cbq.init timecheck" periodically from cron
#         (every 10 minutes for example). DON'T FORGET though, to run
#         "cbq.init start" for CBQ to initialize.
# v0.2  - Some cosmetic changes. Now it is more compatible with old bash
#         version. Thanks to Stanislav V. Voronyi <[email protected]>.
# v0.1  - First public release
#
#
# README
# ------
#
# First of all - this is just a SIMPLE EXAMPLE of CBQ power.
# Don't ask me "why" and "how" :)
#
# This script is meant to simplify setup and management of relatively simple
# CBQ-based traffic control on Linux. Access to advanced networking features
# of Linux kernel is provided by "ip" and "tc" utilities from A. Kuznetsov's
# iproute2 package, available at ftp://ftp.inr.ac.ru/ip-routing. Because the
# utilities serve primarily to translate user wishes to RTNETLINK commands,
# their interface is rather austere, intolerant and requires quite a lot of
# typing. And typing is what this script (hopefully) reduces.
#
# The advanced networking stuff in Linux is _very_ flexible and this script
# aims to bring some of its features to the not-so-hard-core Linux users. Of
# course, there is tradeoff between simplicity and flexibility and you might
# find out that the flexibility suffered too much for your needs -- time to
# face "ip" and "tc" interface :)
#
# To speed up the "start" command, simple caching was introduced in version
# 0.6.4. The caching works so that the sequence of "tc" commands for given
# configuration is stored in a file (/var/run/cbq-cache by default) which
# is used next time "start" command is run to avoid repeated parsing of the
# configuration files. This cache is invalidated whenever any of the CBQ
# configuration files changes. If you want to run "cbq.init start" without
# caching, run it as "cbq.init start nocache". If you want to force cache
# invalidation, run it as "cbq.init start invalidate". Caching is disabled
# if you have logging enabled (ie. LOG_FILE is not empty).
#
# All CBQ parameters are valid for Ethernet interfaces only, The script was
# tested on various Linux kernel versions from series 2.1 to 2.4 and several
# distributions with KSI Linux (Nostromo version) as the premier one.
#
#
# HOW DOES IT WORK?
# -----------------
#
# Every traffic class must be described by a file in the $CBQ_PATH directory
# (/etc/sysconfig/cbq by default) - one file per class.
#
# The config file names must obey mandatory format: cbq-<clsid>.<name> where
# <clsid> is two-byte hexadecimal number in range <0001-FFFF> (which in fact
# is a CBQ class ID) and <name> is the name of the class -- anything to help
# you distinguish the configuration files. For small amount of classes it is
# often possible (and convenient) to let <clsid> resemble bandwidth of the
# class.
#
# Example of valid config name:
#       cbq-1280.My_first_shaper
#
#
# The configuration file may contain the following parameters:
#
### Device parameters
#
# DEVICE=<ifname>,<bandwidth>,<weight>          mandatory
# DEVICE=eth0,10Mbit,1Mbit
#
#       <ifname> is the name of the interface you want to control
#               traffic on, e.g. eth0
#       <bandwidth> is the physical bandwidth of the device, e.g. for
#               ethernet 10Mbit or 100Mbit, for arcnet 2Mbit
#       <weight> is tuning parameter that should be proportional to
#               <bandwidth>. As a rule of thumb: <weight> = <bandwidth> / 10
#
# When you have more classes on one interfaces, it is enough to specify
# <bandwidth> and <weight> only once, therefore in other files you can
# have just DEVICE=<ifname>.
#
### Class parameters
#
# RATE=<speed>                                  mandatory
# RATE=5Mbit
#
#       Bandwidth allocated to class. Traffic going through the class is
#       shaped to conform to the given rate. You can use Kbit, Mbit or
#       bps, Kbps and Mbps as suffices.miting speed of the shaper.
#       You can use Kbit, Mbit or bps, Kbps, Mbps as suffixes.
#
# WEIGHT=<speed>                                mandatory
# WEIGHT=500Kbit
#
#       Tuning parameter that should be proportional to RATE. As a rule
#       of thumb, use WEIGHT ~= RATE / 10.
#
# PRIO=<1-8>                                    optional, default 5
# PRIO=5
#
#       Priority of class traffic. The higher the number, the lesser
#       the priority. Priority of 5 is just fine.
#
# PARENT=<clsid>                                optional, default not set
# PARENT=1280
#
#       Specifies ID of the parent class you want to attach the CBQ
#       class to. You might want to use LEAF=none for the parent class as
#       mentioned below. By using this parameter and carefully ordering the
#       configuration files, it is possible to create simple hierarchical
#       structures of CBQ classes. The ordering is important so that parent
#       classes are constructed prior to their children.
#
# LEAF=none|tbf|sfq                             optional, default "tbf"
#
#       Tells the script to attach specified leaf queueing discipline to CBQ
#       class. By default, TBF is used. Note that attaching TBF to CBQ class
#       shapes the traffic to conform to TBF parameters and prevents the class
#       from borrowing bandwidth from its parent even if you have set BOUNDED
#       to "no". To allow the class to borrow bandwith (provided it is not
#       bounded), you must set LEAF to "none" or "sfq".
#
#       If you want to ensure (approximately) fair sharing of bandwidth among
#       several hosts in the same class, you might want to specify LEAF=sfq to
#       attach SFQ as leaf queueing discipline to that class. Support for more
#       queueing disciplines will be probably added in future.
#
# BOUNDED=yes|no                                optional, default "yes"
#
#       If set to "yes", the class is not allowed to borrow bandwidth from
#       its parent class in overlimit situation. If set to "no", the class
#       will be allowed to borrow bandwidth.
#
# Note: Don't forget to set LEAF to "none" or "sfq", otherwise the class will
#       not be able to borrow bandwith,
#
# ISOLATED=yes|no                               optional, default "no"
#
#       If set to "yes", the class will not lend unused bandwidth to
#       its children.
#
### TBF qdisc parameters
#
# BUFFER=<bytes>[/<bytes>]                      optional, default "10Kb/8"
#
#       This parameter controls the depth of the token bucket. In other
#       words it represents the maximal burst size the class can send.
#       The optional part of parameter is used to determine the length
#       of intervals in packet sizes, for which the transmission times
#       are kept.
#
# LIMIT=<bytes>                                 optional, default "15Kb"
#
#       This parameter determines the maximal length of backlog. If
#       the queue contains more data than specified by LIMIT, the
#       newly arriving packets are dropped. The length of backlog
#       determines queue latency in case of congestion.
#
# PEAK=<speed>                                  optional, default not set
#
#       Maximal peak rate for short-term burst traffic. This allows you
#       to control the absolute peak rate the class can send at, because
#       single TBF that allows 256Kbit/s would of course allow rate of
#       512Kbit for half a second or 1Mbit for a quarter of second.
#
# MTU=<bytes>                                   optional, default "1500"
#
#       Maximum number of bytes that can be sent at once over the
#       physical medium. This parameter is required when you specify
#       PEAK parameter. It defaults to MTU of ethernet - for other
#       media types you might want to change it.
#
# Note: Setting TBF as leaf qdisc will effectively prevent the class from
#       borrowing bandwidth from the ancestor class, because even if the
#       class allows more traffic to pass through, it is then shaped to
#       conform to TBF.
#
### SFQ qdisc parameters
#
# The SFQ queueing discipline is a cheap way for sharing class bandwidth
# among several hosts. As it is stochastic, the fairness is approximate but
# it will do the job in most cases. If you want real fairness, you should
# probably use WRR (weighted round robin) or WFQ queueing disciplines. Note
# that SFQ does not do any traffic shaping - the shaping is done by the CBQ
# class the SFQ is attached to.
#
# QUANTUM=<bytes>                               optional, default not set
#
#       This parameter should not be set lower than link MTU, for ethernet
#       it is 1500b, or (with MAC header) 1514b which is the value used
#       in Alexey Kuznetsov's examples.
#
# PERTURB=<seconds>                             optional, default not set
#
#       Period of hash function perturbation. In Alexey Kuznetsov's
#       examples the value used was 15 seconds.
#
### Filter parameters
#
# RULE=[[saddr[/prefix]][:port],][daddr[/prefix]][:port]
#
#       These parameters make up "u32" filter rules that select traffic for
#       each of the classes. You can use multiple RULE fields per config.
#
# Some examples:
#
#       RULE=10.1.1.0/24:80
#               selects traffic going to port 80 in network 10.1.1.0
#
#       RULE=10.2.2.5
#               selects traffic going to any port on single host 10.2.2.5
#
#       RULE=:25,10.2.2.128/26:5000
#               selects traffic going from anywhere on port 50 to
#               port 5000 in network 10.2.2.128
#
#       RULE=10.5.5.5:80,
#               selects traffic going from port 80 of single host 10.5.5.5
#
#
#
# REALM=[srealm,][drealm]
#
#       These parameters make up "route" filter rules that classify traffic
#       according to packet source/destination realms. For information about
#       realms, see Alexey Kuznetsov's IP Command Reference. This script
#       does not define any realms, it justs builds "tc filter" commands
#       for you if you need to classify traffic this way.
#
#       Realm is either a decimal number or a string referencing entry in
#       /etc/iproute2/rt_realms (usually).
#
# Some examples:
#
#       REALM=russia,internet
#               selects traffic going from realm "russia" to realm "internet"
#
#       REALM=freenet,
#               selects traffic going from realm "freenet"
#
#       REALM=10
#               selects traffic going to realm 10
#
#
# MARK=<mark>
#
#       These parameters make up "fw" filter rules that select traffic for
#       each of the classes accoring to firewall "mark". Mark is a decimal
#       number packets are tagged with if firewall rules say so. You can
#       use multiple MARK fields per config.
#
#
# Note: Rules for different filter types can be combined. Attention must be
#       paid to the priority of filter rules, which can be set below using
#       PRIO_{U32,FW,ROUTE} variables.
#
### Time ranging parameters
#
# TIME=<from>-<till>;<rate>/<weight>[/<peak>]   optional
# TIME=18:00-06:00;256Kbit/25Kbit
#
#       This parameter allows you to differentiate the class bandwidth
#       throughout the day. You can specify multiple TIME parameters, if
#       the times overlap, last match is taken. The fields <rate>, <weight>
#       and <peak> correspond to parameters RATE, WEIGHT and PEAK (which
#       is optional and applies to TBF qdisc only).
#
###
#
# Sample configuration file: cbq-1280.My_first_shaper
#
# --------------------------------------------------------------------------
# DEVICE=eth0,10Mbit,1Mbit
# RATE=128Kbit
# WEIGHT=10Kbit
# PRIO=5
# RULE=192.128.1.0/24
# --------------------------------------------------------------------------
#
# The configuration says that we will control traffic on 10Mbit ethernet
# device eth0 and the traffic going to network 192.168.1.0 will be processed
# with priority 5 and shaped to rate of 128Kbit.
#
# Note that you can control outgoing traffic only. If you want to control
# traffic in both directions, you must set up CBQ for both interfaces.
#
# Consider the following example:
#
#                    +---------+      192.168.1.1
# BACKBONE -----eth0-|  linux  |-eth1------*-[client]
#                    +---------+
#
# Imagine you want to shape traffic from backbone to the client to 28Kbit
# and traffic in the opposite direction to 128Kbit. You need to setup CBQ
# on both eth0 and eth1 interfaces, thus you need two config files:
#
# cbq-28.backbone-client
# --------------------------------------------------------------------------
# DEVICE=eth1,10Mbit,1Mbit
# RATE=28Kbit
# WEIGHT=2Kbit
# PRIO=5
# RULE=192.168.1.1
# --------------------------------------------------------------------------
#
# cbq-128.client-backbone
# --------------------------------------------------------------------------
# DEVICE=eth0,10Mbit,1Mbit
# RATE=128Kbit
# WEIGHT=10Kbit
# PRIO=5
# RULE=192.168.1.1,
# --------------------------------------------------------------------------
#
# Pay attention to comma "," in the RULE field - it denotes source address!
#
# Enjoy.
#
#############################################################################

PATH="/sbin:/usr/sbin:/bin:/usr/bin"

### Filter priorities (must be different)
PRIO_U32=100
PRIO_FW=200
PRIO_ROUTE=300

### Respect external CBQ_PATH & CBQ_CACHE settings
[ -z "$CBQ_PATH" ] && CBQ_PATH="/etc/sysconfig/cbq"
[ -z "$CBQ_CACHE" ] && CBQ_CACHE="/var/run/cbq-cache"

### Uncomment for debugging
#LOG_FILE="/var/run/cbq-$1"

if [ "$2" = "compile" ]; then
       ### echo-only equivalent of "tc" command
       tc () {
               echo -e "tc $@\n"
       } # tc
elif [ -n "$LOG_FILE" ]; then
       echo "# `date`" > $LOG_FILE

       ### Logging equivalent of "ip" command
       ip () {
               echo -e "\nip $@\n" >> $LOG_FILE
               /sbin/ip "$@" 2>&1 | tee -a $LOG_FILE
       } # ip

       ### Logging equivalent of "tc" command
       tc () {
               echo -e "\ntc $@\n" >> $LOG_FILE
               /sbin/tc "$@" 2>&1 | tee -a $LOG_FILE
       } # tc
fi # command logging


### Remove CBQ from all devices
cbq_off () {
       for dev in `ip link| sed -n '/^[0-9]/ { s/^[0-9]\+: \([a-z0-9]\+\)[:@].*/\1/; p; }'`; do
               cbq_device_off $dev
       done
} # cbq_off


### Remove root class from device $1
cbq_device_off () {
       tc qdisc del dev $1 root 2> /dev/null
} # cbq_device_off


### Display CBQ setup
cbq_show () {
       for dev in $DEVICES; do
               echo ---[ $dev: queueing disciplines ]-------------------------
               echo; tc $1 qdisc show dev $dev; echo

               echo ---[ $dev: configured classes ]---------------------------
               echo; tc $1 class show dev $dev; echo

               [ "$1" = "-s" ] && continue
               echo ---[ $dev: filtering rules ]------------------------------
               echo; tc $1 filter show dev $dev; echo
       done
} # cbq_show


### Check configuration and load DEVFIELDS/CLASSLIST
cbq_init () {

       ### Check configuration in $CBQ_PATH directory and get CLASSLIST
       CLASSLIST=`find $CBQ_PATH -name 'cbq-*' -maxdepth 1 -printf "%f\n"| sort`
       if [ -z "$CLASSLIST" ]; then
               echo "**CBQ: not configured in $CBQ_PATH!"
               exit
       fi

       ### Collect all DEVICE fields from $CBQ_PATH/cbq-*
       DEVFIELDS=`find $CBQ_PATH -name 'cbq-*' -maxdepth 1 -exec sed -ne\
                  's/#.*//; s/ //g; /^DEVICE=.*,.*,.*/ { s/.*=//; p; q; }; \
                  /^DEVICE=/ q' {} \;| sort -u`

       ### Check if there are any devices to set up
       if [ -z "$DEVFIELDS" ]; then
               echo "**CBQ: can't find any DEVICE field in $CBQ_PATH/cbq-*!"
               exit
       fi

       ### Extract all device names from DEVICE fields in $CBQ_PATH/cbq-*
       DEVICES=`echo "$DEVFIELDS"| sed 's/,.*//'| sort -u`

       ### Check for multiple devices with different DEVICE fields
       if [ `echo "$DEVICES"| wc -l` -ne `echo "$DEVFIELDS"| wc -l` ]; then
               echo "**CBQ: multiple (different) DEVICE fields for the same device found!"
               echo "$DEVFIELDS"
               exit
       fi
} # cbq_init


### Load class configuration from file $1
cbq_load_class () {
       CNAME="$CBQ_PATH/$1"
       CFILE=`sed -e 's/#.*//; s/ //g; /^$/ d' $CNAME`

       CLASS=`echo $1| sed 's/^cbq-0*//; s/\..*//'`
       IDVAL=`/usr/bin/printf "%d" 0x$CLASS 2> /dev/null`
       if [ $? -ne 0 -o $IDVAL -eq 0 -o $IDVAL -gt 65535 ]; then
               echo "**CBQ: class ID of $1 must be in range <0001-FFFF>!"
               cbq_off
               exit
       fi

       ### Device parameters
       DEVICE=`echo "$CFILE"| sed -n '/^DEVICE=/ { s/.*=//; s/,.*//; p; q; }'`
       BANDWIDTH=`echo "$DEVFIELDS"| sed -n "/^$DEVICE,/ { s/.*,\(.*\),.*/\1/; p; q; }"`

       ### Class parameters
       CLASSID="1:$CLASS"
       PARENT=`echo "$CFILE"| sed -n '/^PARENT=/ { s/.*=0*//; p; q; }'`
       [ -z "$PARENT" ] && PARENT="1:0" || PARENT="1:$PARENT"

       LEAF=`echo "$CFILE"| sed -n '/^LEAF=/ { s/.*=//; p; q; }'`
       [ -z "$LEAF" ] && LEAF="tbf"

       BOUNDED=`echo "$CFILE"| sed -n '/^BOUNDED=/ { s/.*=//; p; q; }'`
       [ "$BOUNDED" = "no" ] && BOUNDED="" || BOUNDED="bounded"

       ISOLATED=`echo "$CFILE"| sed -n '/^ISOLATED=/ { s/.*=//; p; q; }'`
       [ "$ISOLATED" = "yes" ] && ISOLATED="isolated" || ISOLATED=""

       PRIO=`echo "$CFILE"| sed -n '/^PRIO=/ { s/.*=//; p; q; }'`
       [ -z "$PRIO" ] && PRIO="5"

       RATE=`echo "$CFILE"| sed -n '/^RATE=/ { s/.*=//; p; q; }'`
       WEIGHT=`echo "$CFILE"| sed -n '/^WEIGHT=/ { s/.*=//; p; q; }'`
       if [ -z "$RATE" -o -z "$WEIGHT" ]; then
               echo "**CBQ: missing RATE or WEIGHT field(s) in $1!"
               cbq_off
               exit
       fi

       ### Leaf qdisc parameters for TBF
       if [ "$LEAF" = "tbf" ]; then
               BUFFER=`echo "$CFILE"| sed -n '/^BUFFER=/ { s/.*=//; p; q; }'`
               [ -z "$BUFFER" ] && BUFFER="10Kb/8"

               LIMIT=`echo "$CFILE"| sed -n '/^LIMIT=/ { s/.*=//; p; q; }'`
               [ -z "$LIMIT" ] && LIMIT="15Kb"

               PEAK=`echo "$CFILE"| sed -n '/^PEAK=/ { s/.*=//; p; q; }'`
               [ -n "$PEAK" ] && PEAK="peakrate $PEAK"

               MTU=`echo "$CFILE"| sed -n '/^MTU=/ { s/.*=//; p; q; }'`
               [ -z "$MTU" ] && MTU="1500"

       ### Leaf qdisc parameters for SFQ
       elif [ "$LEAF" = "sfq" ]; then
               PERTURB=`echo "$CFILE"| sed -n '/^PERTURB=/ { s/.*=//; p; q; }'`
               [ -n "$PERTURB" ] && PERTURB="perturb $PERTURB"

               QUANTUM=`echo "$CFILE"| sed -n '/^QUANTUM=/ { s/.*=//; p; q; }'`
               [ -n "$QUANTUM" ] && QUANTUM="quantum $QUANTUM"
       fi
} # cbq_load_class


### Convert time to absolute value
cbq_time2abs () {
       _min=${1##*:}
       _min=${_min##0}
       echo $[${1%%:*}*60 + _min]
} # cbq_time2abs


### Check if ip-route is installed
if [ ! -f /sbin/tc -o ! -f /sbin/ip ]; then
       echo "**CBQ: ip-route2 utilities not installed!"
       exit
fi


########################################################################
# See how were we called                                               #
########################################################################

case "$1" in

       ### START ###
       start)

### If you have cbq, tbf, sfq and u32 compiled into kernel,
### make the following test condition fail...
if /bin/true; then
       for module in sch_{cbq,tbf,sfq,prio} cls_{fw,u32,route}; do
               if ! modprobe $module; then
                       echo "**CBQ: could not load module $module"
                       exit
               fi
       done
fi


### if we are in compile/nocache/logging mode, don't bother with cache
if [ "$2" != "compile" -a "$2" != "nocache" -a -z "$LOG_FILE" ]; then
       ### if we don't have cache or the cache is old, (re)create it
       if [ ! -f $CBQ_CACHE -o "$2" = "invalidate" ]; then
               $0 start compile > $CBQ_CACHE
       elif [ `find $CBQ_PATH -maxdepth 1 -newer $CBQ_CACHE| wc -l` -gt 0 ]; then
               $0 start compile > $CBQ_CACHE
       fi

       ### run the cached commands
       exec /bin/sh $CBQ_CACHE 2> /dev/null
fi

########################################################################
# Get all devices from configuration files $CBQ_PATH/cbq-*             #
# and setup CBQ root classes for them (if it is possible).             #
########################################################################

### Load DEVICES, DEVFIELDS and CLASSLIST
cbq_init

### Try to discover interface bandwidth from DEVICE
### field and if OK - setup root class for this one

for dev in $DEVICES; do
       ### Retrieve device bandwidth and weight
       DEVTEMP=`echo "$DEVFIELDS"| sed -n "/^$dev,/ { s/.*,\(.*\),\(.*\)/\1,\2/; p; q; }"`
       DEVBWDT=${DEVTEMP%%,*}
       DEVWGHT=${DEVTEMP##*,}

       ### If correctly set and the device is up, setup root class
       if [ -n "$DEVBWDT" -a -n "$DEVWGHT" ]; then
               if ! ip link | grep -q "$dev[:@].*UP"; then
                       echo "**CBQ: could not find device $dev! CBQ turned off."
                       cbq_off
                       exit
               fi

               ### Remove old root qdisc from device
               cbq_device_off $dev

               ### Setup root class and queueing discipline for device
               tc qdisc add dev $dev root handle 1: cbq \
               bandwidth $DEVBWDT avpkt 1000 cell 8
       else
               echo "**CBQ: could not determine bandwidth or weight for device $dev!"
               echo "**CBQ: set the DEVICE field properly!"
               exit
       fi
done # device


#######################################################################
# Set up all classes configured in $CBQ_PATH/cbq-*                    #
#######################################################################

for classfile in $CLASSLIST; do

       cbq_load_class $classfile

       ### Create class and setup leaf qdisc
       tc class add dev $DEVICE parent $PARENT classid $CLASSID cbq \
       bandwidth $BANDWIDTH rate $RATE weight $WEIGHT prio $PRIO \
       allot 1514 cell 8 maxburst 20 avpkt 1000 $BOUNDED $ISOLATED

       ### Setup leaf queueing discipline
       if [ "$LEAF" = "tbf" ]; then
               tc qdisc add dev $DEVICE parent $CLASSID tbf \
               rate $RATE buffer $BUFFER limit $LIMIT mtu $MTU $PEAK
       elif [ "$LEAF" = "sfq" ]; then
               tc qdisc add dev $DEVICE parent $CLASSID sfq \
               $PERTURB $QUANTUM
       fi


       ### Create fw filter for MARK fields
       MARKSET=`echo "$CFILE"| sed -n '/^MARK/ { s/.*=//; p; }'`
       if [ -n "$MARKSET" ]; then
               for mark in $MARKSET; do
                       ### Attach fw filter to root class
                       tc filter add dev $DEVICE parent 1:0 protocol ip \
                       prio $PRIO_FW handle $mark fw classid $CLASSID
               done ### mark
       fi


       ### Create route filter for REALM fields
       REALMSET=`echo "$CFILE"| sed -n '/^REALM/ { s/.*=//; p; }'`
       if [ -n "$REALMSET" ]; then
               for realm in $REALMSET; do
                       ### Separate source/destination realms
                       DREALM=${realm##*,}; SREALM=""
                       [ "$DREALM" != "$realm" ] && SREALM=${realm%%,*}

                       [ "$DREALM" = "*" ] && DREALM=""
                       [ "$SREALM" = "*" ] && SREALM=""

                       [ -n "$SREALM" ] && SREALM="from $SREALM"
                       [ -n "$DREALM" ] && DREALM="to $DREALM"

                       ### Attach route filter to the root class
                       tc filter add dev $DEVICE parent 1:0 protocol ip \
                       prio $PRIO_ROUTE route $SREALM $DREALM classid $CLASSID
               done ### realm
       fi


       ### Create u32 filter for addresses specified by RULE fields
       RULESET=`echo "$CFILE"| sed -n '/^RULE/ { s/.*=//; p; }'`
       [ -z "$RULESET" ] && continue

       ### Rules present, parse them
       for rule in $RULESET; do
               u32_s=""; u32_d=""
               SADDR=""; SPORT=""

               ### Split up destination
               DST=${rule##*,}
               DADDR=${DST%%:*}

               [ "$DADDR" != "$DST" ] && DPORT=${DST##*:} || DPORT=""
               [ "$DADDR" = "*" ] && DADDR=""

               ### Split up source (if specified)
               if [ "$DST" != "$rule" ]; then
                       SRC=${rule%%,*}
                       SADDR=${SRC%%:*}

                       [ "$SADDR" != "$SRC" ] && SPORT=${SRC##*:}
                       [ "$SADDR" = "*" ] && SADDR=""
               fi

               ### Compose the u32 filter rules
               [ -n "$SPORT" ] && u32_s="match ip sport $SPORT 0xffff"
               [ -n "$SADDR" ] && u32_s="match ip src $SADDR $u32_s"
               [ -n "$DPORT" ] && u32_d="match ip dport $DPORT 0xffff"
               [ -n "$DADDR" ] && u32_d="match ip dst $DADDR $u32_d"

               ### Uncomment the following if you want to see parsed rules
               #echo "$rule: $u32_s $u32_d"

               ### Attach u32 filter to the appropriate class
               tc filter add dev $DEVICE parent 1:0 protocol ip \
               prio $PRIO_U32 u32 $u32_s $u32_d flowid $CLASSID
       done ### rule

done ### class file
       ;;

       ### TIMECHECK ###
       timecheck)

### Load DEVICES, DEVFIELDS and CLASSLIST
cbq_init

### Current time in hh:mm format
TIME_NOW=`date +%k:%M`
TIME_ABS=`cbq_time2abs $TIME_NOW`

### Check every config file for TIME parameter
for classfile in $CLASSLIST; do

       TIMERATES=`sed -ne 's/#.*//; s/ //g; /^TIME/ { s/.*=//; p; }' $CBQ_PATH/$classfile`
       [ -z "$TIMERATES" ] && continue

       MATCH=0; CHANGE=0;
       for timerate in $TIMERATES; do

               ### Split up TIME parameter
               INTERVAL=${timerate%%;*}; PARAMS=${timerate##*;}
               BEG_TIME=${INTERVAL%%-*}; END_TIME=${INTERVAL##*-}

               ### Compute interval boundaries
               BEG_ABS=`cbq_time2abs $BEG_TIME`
               END_ABS=`cbq_time2abs $END_TIME`

               ### Midnight wrap fixup
               if [ $BEG_ABS -gt $END_ABS ]; then
                       [ $TIME_ABS -le $END_ABS ] && TIME_ABS=$[TIME_ABS + 24*60]
                       END_ABS=$[END_ABS + 24*60]
               fi

               ### If the time matches, remember params and set MATCH flag
               if [ $TIME_ABS -ge $BEG_ABS -a $TIME_ABS -lt $END_ABS ]; then
                       TMP_RATE=${PARAMS%%/*}
                       TMP_WGHT=${PARAMS#*/}
                       TMP_PEAK=${TMP_WGHT#*/}

                       [ "$TMP_PEAK" = "$TMP_WGHT" ] && TMP_PEAK="" || TMP_WGHT={$TMP_WGHT%%/*}

                       [ -n "$TMP_PEAK" ] && TMP_PEAK="peakrate $TMP_PEAK"
                       MATCH=1
               fi
       done ### timerate

       cbq_load_class $classfile

       ### Get current RATE of CBQ class
       RATE_NOW=`tc class show dev $DEVICE| sed -n \
                 "/cbq $CLASSID / { s/.*rate //; s/ .*//; p; q; }"`
       [  -z "$RATE_NOW" ] && continue

       ### Time interval match is found
       if [ $MATCH -ne 0 ]; then

               ### Check if there is any change in class RATE
               if [ "$RATE_NOW" != "$TMP_RATE" ]; then
                       NEW_RATE="$TMP_RATE"
                       NEW_WGHT="$TMP_WGHT"
                       NEW_PEAK="$TMP_PEAK"
                       CHANGE=1
               fi

       ### Match not found, reset to default RATE if necessary
       elif [ "$RATE_NOW" != "$RATE" ]; then
               NEW_WGHT="$WEIGHT"
               NEW_RATE="$RATE"
               NEW_PEAK="$PEAK"
               CHANGE=1
       fi

       ### If there's a change, replace CBQ class and leaf qdisc
       [ $CHANGE -ne 1 ] && continue

       ### Replace CBQ class
       tc class replace dev $DEVICE classid $CLASSID cbq \
       bandwidth $BANDWIDTH rate $NEW_RATE weight $NEW_WGHT prio $PRIO \
       allot 1514 cell 8 maxburst 20 avpkt 1000 $BOUNDED $ISOLATED

       echo "**CBQ: $TIME_NOW: class $CLASS on $DEVICE changed rate ($RATE_NOW -> $NEW_RATE)"


       ### Get leaf qdisc handle
       LEAF_HND=`tc class show dev $DEVICE| sed -n \
                 "/cbq $CLASSID .* leaf / { s/.*leaf //; s/ .*//; p; q; }"`
       [ -z "$LEAF_HND" ] && continue

       ### Replace leaf qdisc (if any)
       if [ "$LEAF" = "tbf" ]; then
               tc qdisc replace dev $DEVICE handle $LEAF_HND tbf \
               rate $NEW_RATE buffer $BUFFER limit $LIMIT mtu $MTU $NEW_PEAK
       fi
done ### class file

       ;;

       ### STOP ###
       stop)
               cbq_off
       ;;

       ### RESTART ###
       restart)
               $0 stop
               $0 start
       ;;

       ### LIST ###
       list)
               cbq_init
               cbq_show
       ;;

       ### STATS ###
       stats)
               cbq_init
               cbq_show -s
       ;;

       ### default ###
       *)
               echo "Usage: " `basename $0` "{start [nocache|invalidate]|stop|restart|timecheck|list|stats}"
esac