Автор Тема: CentOS и Bandwidth Quotas с iptables  (Прочетена 2768 пъти)

mrowcp

  • Напреднали
  • *****
  • Публикации: 450
    • Профил
CentOS и Bandwidth Quotas с iptables
« -: Feb 28, 2015, 15:47 »
Здравейте,
Исках да огранича скороста за сваляне на файлове през http, та реших да сложа някаква квота. Намерих си аз един менюал, но се оказа, че patch-o-matic-ng вече не се съпортва и хората ме пращат към xtables-addons.
Свалих си аз xtables-addons и после  ??? Превъртях нета да търся някакви примери, но или изобщо не се ползва за лимитиране или е баси табуто...
Гледам, че има възможност това да стане с httpd mod_bw.conf, но ми се иска да ползвам iptables, за да мога после да лимитирам и други неща (ftp и т.н.)

П.С. CentOS release 6.2 с 2.6.32-220.el6.i686
Активен

Some Things Just Are The Way They Are

daniel_vulchev

  • Напреднали
  • *****
  • Публикации: 177
  • Distribution: NetBSD, Slackware, Debian
  • Window Manager: Console/Gnome
    • Профил
    • WWW
Re: CentOS и Bandwidth Quotas с iptables
« Отговор #1 -: Feb 28, 2015, 17:26 »
1 пример
tc filter add dev eth0 parent 1:0 protocol ip u32 match ip sport 80 0xffff classid 1:10
tc filter add dev eth0 parent 1:0 protocol ip u32 match ip dport 22 0xffff \
  match ip dst 192.168.0.70/32 classid 1:20

iptables -t mangle -A POSTROUTING -o eth2 -p tcp --sport 80 -j CLASSIFY --set-class 1:10

2 пример

iptables -t mangle -A POSTROUTING -o eth2 -p tcp --sport 80 -j MARK --set-mark 1

tc filter add dev eth0 protocol ip parent 1:0 prio 1 handle 1 fw classid 1:10

тия неща ли бяха с  patch-o-matic-ng ? Не съм ги ползвал от десетина години  да си припомня  ;D
Активен

daniel_vulchev

  • Напреднали
  • *****
  • Публикации: 177
  • Distribution: NetBSD, Slackware, Debian
  • Window Manager: Console/Gnome
    • Профил
    • WWW
Re: CentOS и Bandwidth Quotas с iptables
« Отговор #2 -: Feb 28, 2015, 17:38 »
/sbin/tc qdisc add dev eth0 root handle 1: htb
/sbin/tc class add dev eth0 parent 1: classid 1:1 htb rate 1024kbps
/sbin/tc class add dev eth0 parent 1:1 classid 1:5 htb rate 512kbps ceil 640kbps prio 1
/sbin/tc class add dev eth0 parent 1:1 classid 1:6 htb rate 100kbps ceil 160kbps prio 0
/sbin/tc filter add dev eth0 parent 1:0 prio 1 protocol ip handle 5 fw flowid 1:5
/sbin/tc filter add dev eth0 parent 1:0 prio 0 protocol ip handle 6 fw flowid 1:6
/sbin/iptables -A OUTPUT -t mangle -p tcp --sport 80 -j MARK --set-mark 5
/sbin/iptables -A OUTPUT -t mangle -p tcp --sport 22 -j MARK --set-mark 6

до колкото помня май с CLASSIFY --set-class  работеше по бързо
не съм ползвал iptables от няколко години  има примери доста най-вероятно и за тая новост има не си задаваш въпроса в гугле правилно  [_]3
Активен

mrowcp

  • Напреднали
  • *****
  • Публикации: 450
    • Профил
Re: CentOS и Bandwidth Quotas с iptables
« Отговор #3 -: Feb 28, 2015, 18:07 »
/sbin/tc qdisc add dev eth0 root handle 1: htb
/sbin/tc class add dev eth0 parent 1: classid 1:1 htb rate 1024kbps
/sbin/tc class add dev eth0 parent 1:1 classid 1:5 htb rate 512kbps ceil 640kbps prio 1
/sbin/tc class add dev eth0 parent 1:1 classid 1:6 htb rate 100kbps ceil 160kbps prio 0
/sbin/tc filter add dev eth0 parent 1:0 prio 1 protocol ip handle 5 fw flowid 1:5
/sbin/tc filter add dev eth0 parent 1:0 prio 0 protocol ip handle 6 fw flowid 1:6
/sbin/iptables -A OUTPUT -t mangle -p tcp --sport 80 -j MARK --set-mark 5
/sbin/iptables -A OUTPUT -t mangle -p tcp --sport 22 -j MARK --set-mark 6

до колкото помня май с CLASSIFY --set-class  работеше по бързо
не съм ползвал iptables от няколко години  има примери доста най-вероятно и за тая новост има не си задаваш въпроса в гугле правилно  [_]3

Абе уж тествах всякакви комбинации с въпросния адон, но...
Нямам конкретни предпочитания, така че може и да ползвам tc , само ако може жокер за 1вите два реда:

/sbin/tc qdisc add dev eth0 root handle 1: htb
/sbin/tc class add dev eth0 parent 1: classid 1:1 htb rate 1024kbps

 Останалите ги "прочитам" :)
Активен

Some Things Just Are The Way They Are

daniel_vulchev

  • Напреднали
  • *****
  • Публикации: 177
  • Distribution: NetBSD, Slackware, Debian
  • Window Manager: Console/Gnome
    • Профил
    • WWW
Re: CentOS и Bandwidth Quotas с iptables
« Отговор #4 -: Feb 28, 2015, 18:44 »
общата скорост имаш 10 мегабита и я дефинираш оттам останалото разпределяш в рамките на тия мегабити
Активен

daniel_vulchev

  • Напреднали
  • *****
  • Публикации: 177
  • Distribution: NetBSD, Slackware, Debian
  • Window Manager: Console/Gnome
    • Профил
    • WWW
Re: CentOS и Bandwidth Quotas с iptables
« Отговор #5 -: Feb 28, 2015, 18:47 »
http://lartc.org/howto/lartc.cookbook.fullnat.intro.html
ето едно примерче
Активен

daniel_vulchev

  • Напреднали
  • *****
  • Публикации: 177
  • Distribution: NetBSD, Slackware, Debian
  • Window Manager: Console/Gnome
    • Профил
    • WWW
Re: CentOS и Bandwidth Quotas с iptables
« Отговор #6 -: Feb 28, 2015, 18:56 »
може и други опции да добавиш  освен скорости приоритет също е добре да предвидиш
Активен

mrowcp

  • Напреднали
  • *****
  • Публикации: 450
    • Профил
Re: CentOS и Bandwidth Quotas с iptables
« Отговор #7 -: Feb 28, 2015, 19:26 »
Ахаа... знаех си аз, че това е "големината на тунела" :)
Мерси, ще разгледам, тествам и ако имам въпроси ще пиша.
Активен

Some Things Just Are The Way They Are

programings

  • Напреднали
  • *****
  • Публикации: 221
  • Distribution: Arch Linux, BunsenLabs Linux, FreeBSD
  • Window Manager: XFCE, MATE, Openbox
    • Профил
Активен

mrowcp

  • Напреднали
  • *****
  • Публикации: 450
    • Профил
Активен

Some Things Just Are The Way They Are

daniel_vulchev

  • Напреднали
  • *****
  • Публикации: 177
  • Distribution: NetBSD, Slackware, Debian
  • Window Manager: Console/Gnome
    • Профил
    • WWW
Re: CentOS и Bandwidth Quotas с iptables
« Отговор #10 -: Mar 01, 2015, 15:07 »
В тоя пример който дава колегата лимитираш като цяло скорост up/down , а в горните примери са ти по портове можеш да комбинираш от на колегата примера и от моите и да си направиш филтъра лититирай и icmp трафика.
Ще е добре да го направиш трафика по http  при теглене към клиентите да си има определена скорост а не цялата зададена от htb имаше няква тъпотия в апаче дето правеше това
Активен

BRADATA

  • Напреднали
  • *****
  • Публикации: 833
  • Distribution: Slackware/Mint/CentOS
  • Window Manager: console/KDE/LXDE
    • Профил
    • WWW
Re: CentOS и Bandwidth Quotas с iptables
« Отговор #11 -: Mar 01, 2015, 19:34 »
Ето ти нещо работещо:
1. скрипта htb.init чете конфигурацията в /etc/sysconfig/htb и генерира шейпинг правилата.
2. скрипта generate.sh генерира въпросните конфигурационни файлове. В този случай генерира опашки за всички IP адреси от 192.168.44.0/23 със следните параметри:
Общ канал: 15Mbps симетричен
Специални правила за SSH и SNMP 1Mbps симетричен
За всеки клиент Upload до 256Kbps Download до 1024Kbps
Неописан трафик - 128Kbps

Като променяш скрипта имай предвид, че имената на интерфейсите са от значение.
Това е работеща конфигурация на един хотелски рутер с центос. За повече информация - http://lartc.org/

/etc/init.d/htb.init
Код
GeSHi (Bash):
  1. #!/bin/bash
  2. #
  3. #    htb.init v0.8.5
  4. #    Copyright (C) 2002-2004  Lubomir Bulej <pallas@kadan.cz>
  5. #
  6. #    chkconfig:   2345 11 89
  7. #    description: script to set up HTB traffic control
  8. #
  9. #    This program is free software; you can redistribute it and/or modify
  10. #    it under the terms of the GNU General Public License as published by
  11. #    the Free Software Foundation; either version 2 of the License, or
  12. #    (at your option) any later version.
  13. #
  14. #    This program is distributed in the hope that it will be useful,
  15. #    but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. #    GNU General Public License for more details.
  18. #
  19. #    You should have received a copy of the GNU General Public License
  20. #    along with this program; if not, write to the Free Software
  21. #    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  22. #
  23. #    To get the latest version, check on Freshmeat for actual location:
  24. #
  25. #               http://freshmeat.net/projects/htb.init
  26. #
  27. #
  28. # VERSION HISTORY
  29. # ---------------
  30. # v0.8.5- Nathan Shafer <nicodemus at users.sourceforge.net>
  31. #         - allow symlins to class files
  32. #       - Seth J. Blank <antifreeze at users.sourceforge.net>
  33. #         - replace hardcoded ip/tc location with variables
  34. #       - Mark Davis <mark.davis at gmx.de>
  35. #         - allow setting of PRIO_{MARK,RULE,REALM} in class file
  36. # v0.8.4- Lubomir Bulej <pallas at kadan.cz>
  37. #         - fixed small bug in RULE parser to correctly parse
  38. #           rules with identical source and destination fields
  39. #         - removed the experimental INJECT keyword
  40. #         - ignore *~ backup files when looking for classes
  41. #       - Mike Boyer <boyer at administrative.com>
  42. #         - fix to allow arguments to be passed to "restart" command
  43. #       - <face at pos.sk>
  44. #         - fix to preserve class priority after timecheck
  45. # v0.8.3- Lubomir Bulej <pallas at kadan.cz>
  46. #         - use LC_COLLATE="C" when sorting class files
  47. #       - Paulo Sedrez
  48. #         - fix time2abs to allow hours with leading zero in TIME rules
  49. # v0.8.2- Lubomir Bulej <pallas at kadan.cz>
  50. #         - thanks to Hasso Tepper for reporting the following problems
  51. #         - allow dots in interface names for use with VLAN interfaces
  52. #         - fixed a thinko resulting from "cosmetic overdosage"
  53. # v0.8.1- Lubomir Bulej <pallas at kadan.cz>
  54. #         - added function alternatives for sed/find with less features. To
  55. #           enable them, you need to set HTB_BASIC to nonempty string.
  56. #         - added posibility to refer to RATE/CEIL of parent class when
  57. #           setting RATE/CEIL for child class. Look for "prate" or "pceil"
  58. #           in the documentation.
  59. #         - fixed broken "timecheck" invocation
  60. # v0.8  - Lubomir Bulej <pallas at kadan.cz>
  61. #         - simplified and converted CBQ.init 0.7 into HTB.init
  62. #         - changed configuration file naming conventions
  63. #         - lots of HTB specific changes
  64. #
  65. #
  66. # INTRODUCTION
  67. # ------------
  68. #
  69. # This script is a clone of CBQ.init and is meant to simplify setup of HTB
  70. # based traffic control. HTB setup itself is pretty simple compared to CBQ,
  71. # so the purpose of this script is to allow the administrator of large HTB
  72. # configurations to manage individual classes using simple, human readable
  73. # files.
  74. #
  75. # The "H" in HTB stands for "hierarchical", so while many people did not use
  76. # (or know about) the possibility to build hierarchical structures using
  77. # CBQ.init, it should be obvious thing to expect from HTB.init :-)
  78. #
  79. # In HTB.init this is done differently, compared to CBQ.init: the usage of
  80. # PARENT keyword was dropped and instead, class file naming convetion was
  81. # introduced. This convention allows the child class to determine ID of its
  82. # parent class from the filename and also (if not abused enforces file
  83. # ordering so that the parent classes are created before their children.
  84. #
  85. # HTB.init uses simple caching mechanism to speed up "start" invocation if the
  86. # configuration is unchanged. When invoked for the first time, it compiles the
  87. # configuration files into simple shell script containing the sequence of "tc"
  88. # commands required to setup the traffic control. This cache-script is stored
  89. # in /var/cache/htb.init by default and is invalidated either by presence of
  90. # younger class config file, or by invoking HTB.init with "start invalidate".
  91. #
  92. # If you want to HTB.init to setup the traffic control directly without the
  93. # cache, invoke it with "start nocache" parameters. Caching is also disabled
  94. # if you have logging enabled (ie. HTB_DEBUG is not empty).
  95. #
  96. # If you only want HTB.init to translate your configuration to "tc" commands,
  97. # invoke it using the "compile" command. Bear in mind that "compile" does not
  98. # check if the "tc" commands were successful - this is done (in certain places)
  99. # only when invoked with "start nocache" command. When you are testing your
  100. # configuration, you should use it to check whether it is completely valid.
  101. #
  102. # In case you are getting strange sed/find errors, try to uncomment line with
  103. # HTB_BASIC setting, or set the variable to nonempty string. This will enable
  104. # function alternatives which require less advanced sed/find functionality. As
  105. # a result, the script will run slower but will probably run. Also the caching
  106. # will not work as expected and you will have to invalidate the cache manually
  107. # by invoking HTB.init with "start invalidate".
  108. #
  109. #
  110. # CONFIGURATION
  111. # -------------
  112. #
  113. # Every traffic class is described by a single file in placed in $HTB_PATH
  114. # directory, /etc/sysconfig/htb by default. The naming convention is different
  115. # compared to CBQ.init. First notable change is missing 'htb-' prefix. This
  116. # was replaced by interface name to improve human readability and to separate
  117. # qdisc-only configuration.
  118. #
  119. # Global qdisc options are placed in $HTB_PATH/<ifname>, where <ifname> is
  120. # (surprisingly) name of the interface, made of characters and numbers. This
  121. # file must be present if you want to setup HTB on that interface. If you
  122. # don't have any options to put into it, leave it empty, but present.
  123. #
  124. # Class options belong to files with names matching this expression:
  125. # $HTB_PATH/<ifname>-<clsid>(:<clsid>)*<description>
  126. #
  127. # <clsid> is class ID which is hexadecimal number in range 0x2-0xFFFF, without
  128. # the "0x" prefix. If a colon-delimited list of class IDs is specified, the
  129. # last <clsid> in the list represents ID of the class in the config file.
  130. #
  131. # <clsid> preceding the last <clsid> is class ID of the parent class. To keep
  132. # ordering so that parent classes are always created before their children, it
  133. # is recommended to include full <clsid> path from root class to the leaf one.
  134. #
  135. # <description> is (almost) arbitrary string where you can put symbolic
  136. # class names for better readability.
  137. #
  138. # Examples of valid names:
  139. #
  140. #       eth0-2          root class with ID 2, on device eth0
  141. #       eth0-2:3        child class with ID 3 and parent 2, on device eth0
  142. #       eth0-2:3:4      child class with ID 4 and parent 3, on device eth0
  143. #       eth1-2.root     root class with ID 2, on device eth1
  144. #
  145. #
  146. # The configuration files may contain the following parameters. For detailed
  147. # description of HTB parameters see http://luxik.cdi.cz/~devik/qos/htb.
  148. #
  149. ### HTB qdisc parameters
  150. #
  151. # The following parameters apply to HTB root queuening discipline only and
  152. # are expected to be put into $HTB_PATH/<ifname> files. These files must
  153. # exist (even empty) if you want to configure HTB on given interface.
  154. #
  155. # DEFAULT=<clsid>                               optional, default 0
  156. # DEFAULT=30
  157. #
  158. #       <dclsid> is ID of the default class where UNCLASSIFIED traffic goes.
  159. #       Unlike HTB qdisc, HTB.init uses 0 as default class ID, which is
  160. #       internal FIFO queue that will pass packets along at FULL speed!
  161. #
  162. #       If you want to avoid surprises, always define default class and
  163. #       allocate minimal portion of bandwidth to it.
  164. #
  165. # R2Q=<number>                                  optional, default 10
  166. # R2Q=100
  167. #
  168. #       This allows you to set coefficient for computing DRR (Deficit
  169. #       Round Robin) quanta. The default value of 10 is good for rates
  170. #       from 5-500kbps and should be increased for higher rates.
  171. #
  172. # DCACHE=yes|no                                 optional, default "no"
  173. #
  174. #       This parameters turns on "dequeue cache" which results in degraded
  175. #       fairness but allows HTB to be used on very fast network devices.
  176. #       This is turned off by default.
  177. #
  178. ### HTB class parameters
  179. #
  180. # The following are parameters for HTB classes and are expected
  181. # to be put into $HTB_PATH/<ifname>-<clsid>(:<clsid>)*.* files.
  182. #
  183. # RATE=<speed>|prate|pceil                      mandatory
  184. # RATE=5Mbit
  185. #
  186. #       Bandwidth allocated to the class. Traffic going through the class is
  187. #       shaped to conform to specified rate. You can use Kbit, Mbit or bps,
  188. #       Kbps and Mbps as suffices. If you don't specify any unit, bits/sec
  189. #       are used. Also note that "bps" means "bytes per second", not bits.
  190. #
  191. #       The "prate" or "pceil" values will resolve to RATE or CEIL of parent
  192. #       class. This feature is meant to help humans to keep configuration
  193. #       files consistent.
  194. #
  195. # CEIL=<speed>|prate|pceil                      optional, default $RATE
  196. # CEIL=6MBit
  197. #
  198. #       The maximum bandwidth that can be used by the class. The difference
  199. #       between CEIL and RATE amounts to bandwidth the class can borrow, if
  200. #       there is unused bandwidth left.
  201. #
  202. #       By default, CEIL is equal to RATE so the class cannot borrow bandwidth
  203. #       from its parent. If you want the class to borrow unused bandwidth, you
  204. #       must specify the maximal amount it can use, if available.
  205. #
  206. #       When several classes compete for the unused bandwidth, each of the
  207. #       classes is given share proportional to their RATE.
  208. #
  209. # BURST=<bytes>                                 optional, default computed
  210. # BURST=10Kb
  211. #
  212. # CBURST=<bytes>                                optional, default computed
  213. # CBURST=2Kb
  214. #
  215. #       BURST and CBURST parameters control the amount of data that can
  216. #       be sent from one class at maximum (hardware) speed before trying
  217. #       to service other class.
  218. #
  219. #       If CBURST is small (one packet size) it shapes bursts not to
  220. #       exceed CEIL rate the same way PEAK works for TBF.
  221. #
  222. # PRIO=<number>                                 optional, default 0
  223. # PRIO=5
  224. #
  225. #       Priority of class traffic. The higher the number, the lesser the
  226. #       priority. Also, classes with higher priority are offered excess
  227. #       bandwidth first.
  228. #
  229. # LEAF=none|sfq|pfifo|bfifo                     optional, default "none"
  230. #
  231. #       Tells the script to attach specified leaf queueing discipline to HTB
  232. #       class. By default, no leaf qdisc is used.
  233. #
  234. #       If you want to ensure (approximately) fair sharing of bandwidth among
  235. #       several hosts in the same class, you should specify LEAF=sfq to attach
  236. #       SFQ as leaf queueing discipline to the class.
  237. #
  238. # MTU=<bytes>                                   optional, default "1600"
  239. #
  240. #       Maximum packet size HTB creates rate maps for. The default should
  241. #       be sufficient for most cases, it certainly is for Ethernet.
  242. #
  243. ### SFQ qdisc parameters
  244. #
  245. # The SFQ queueing discipline is a cheap way to fairly share class bandwidth
  246. # among several hosts. The fairness is approximate because it is stochastic,
  247. # but is not CPU intensive and will do the job in most cases. If you desire
  248. # real fairness, you should probably use WRR (weighted round robin) or WFQ
  249. # queueing disciplines. Note that SFQ does not do any traffic shaping - the
  250. # shaping is done by the HTB class the SFQ is attached to.
  251. #
  252. # QUANTUM=<bytes>                               optional, qdisc default
  253. #
  254. #       Amount of data in bytes a stream is allowed to dequeue before next
  255. #       queue gets a turn. Defaults to one MTU-sized packet. Do not set
  256. #       this parameter below the MTU!
  257. #
  258. # PERTURB=<seconds>                             optional, default "10"
  259. #
  260. #       Period of hash function perturbation. If unset, hash reconfiguration
  261. #       will never take place which is what you probably don't want. The
  262. #       default value of 10 seconds is probably a good value.
  263. #
  264. ### PFIFO/BFIFO qdisc parameters
  265. #
  266. # Those are simple FIFO queueing disciplines. They only have one parameter
  267. # which determines their length in bytes or packets.
  268. #
  269. # LIMIT=<packets>|<bytes>                       optional, qdisc default
  270. # LIMIT=1000
  271. #
  272. #       Number of packets/bytes the queue can hold. The unit depends on
  273. #       the type of queue used.
  274. #
  275. ### Filtering parameters
  276. #
  277. # RULE=[[saddr[/prefix]][:port[/mask]],][daddr[/prefix]][:port[/mask]]
  278. #
  279. #       These parameters make up "u32" filter rules that select traffic for
  280. #       each of the classes. You can use multiple RULE fields per config.
  281. #
  282. #       The optional port mask should only be used by advanced users who
  283. #       understand how the u32 filter works.
  284. #
  285. # Some examples:
  286. #
  287. #       RULE=10.1.1.0/24:80
  288. #               selects traffic going to port 80 in network 10.1.1.0
  289. #
  290. #       RULE=10.2.2.5
  291. #               selects traffic going to any port on single host 10.2.2.5
  292. #
  293. #       RULE=10.2.2.5:20/0xfffe
  294. #               selects traffic going to ports 20 and 21 on host 10.2.2.5
  295. #
  296. #       RULE=:25,10.2.2.128/26:5000
  297. #               selects traffic going from anywhere on port 50 to
  298. #               port 5000 in network 10.2.2.128
  299. #
  300. #       RULE=10.5.5.5:80,
  301. #               selects traffic going from port 80 of single host 10.5.5.5
  302. #
  303. #
  304. #
  305. # REALM=[srealm,][drealm]
  306. #
  307. #       These parameters make up "route" filter rules that classify traffic
  308. #       according to packet source/destination realms. For information about
  309. #       realms, see Alexey Kuznetsov's IP Command Reference. This script
  310. #       does not define any realms, it justs builds "tc filter" commands
  311. #       for you if you need to classify traffic this way.
  312. #
  313. #       Realm is either a decimal number or a string referencing entry in
  314. #       /etc/iproute2/rt_realms (usually).
  315. #
  316. # Some examples:
  317. #
  318. #       REALM=russia,internet
  319. #               selects traffic going from realm "russia" to realm "internet"
  320. #
  321. #       REALM=freenet,
  322. #               selects traffic going from realm "freenet"
  323. #
  324. #       REALM=10
  325. #               selects traffic going to realm 10
  326. #
  327. #
  328. #
  329. # MARK=<mark>
  330. #
  331. #       These parameters make up "fw" filter rules that select traffic for
  332. #       each of the classes accoring to firewall "mark". Mark is a decimal
  333. #       number packets are tagged with if firewall rules say so. You can
  334. #       use multiple MARK fields per config.
  335. #
  336. #
  337. # Note: Rules for different filter types can be combined. Attention must be
  338. #       paid to the priority of filter rules, which can be set below through
  339. #       the PRIO_{RULE,MARK,REALM} variables.
  340. #
  341. ### Time ranging parameters
  342. #
  343. # TIME=[<dow><dow>.../]<from>-<till>;<rate>[/<burst>][,<ceil>[/<cburst>]]
  344. # TIME=60123/18:00-06:00;256Kbit/10Kb,384Kbit
  345. # TIME=18:00-06:00;256Kbit
  346. #
  347. #       This parameter allows you to change class bandwidth during the day or
  348. #       week. You can use multiple TIME rules. If there are several rules with
  349. #       overlapping time periods, the last match is taken. The <rate>, <burst>,
  350. #       <ceil> and <cburst> fields correspond to parameters RATE, BURST, CEIL
  351. #       and CBURST.
  352. #
  353. #       <dow> is single digit in range 0-6 and represents day of week as
  354. #       returned by date(1). To specify several days, just concatenate the
  355. #       digits together.
  356. #
  357. #
  358. #
  359. # TRIVIAL EXAMPLE
  360. # ---------------
  361. #
  362. # Consider the following example:
  363. # (taken from Linux Advanced Routing & Traffic Control HOWTO)
  364. #
  365. # You have a Linux server with total of 5Mbit available bandwidth. On this
  366. # machine, you want to limit webserver traffic to 5Mbit, SMTP traffic to 3Mbit
  367. # and everything else (unclassified traffic) to 1Kbit. In case there is unused
  368. # bandwidth, you want to share it between SMTP and unclassified traffic.
  369. #
  370. # The "total bandwidth" implies one top-level class with maximum bandwidth
  371. # of 5Mbit. Under the top-level class, there are three child classes.
  372. #
  373. # First, the class for webserver traffic is allowed to use 5Mbit of bandwidth.
  374. #
  375. # Second, the class for SMTP traffic is allowed to use 3Mbit of bandwidth and
  376. # if there is unused bandwidth left, it can use it but must not exceed 5Mbit
  377. # in total.
  378. #
  379. # And finally third, the class for unclassified traffic is allowed to use
  380. # 1Kbit of bandwidth and borrow unused bandwith, but must not exceed 5Mbit.
  381. #
  382. # If there is demand in all classes, each of them gets share of bandwidth
  383. # proportional to its default rate. If there unused is bandwidth left, they
  384. # (again) get share proportional to their default rate.
  385. #
  386. # Configuration files for this scenario:
  387. # ---------------------------------------------------------------------------
  388. # eth0          eth0-2.root     eth0-2:10.www   eth0-2:20.smtp  eth0-2:30.dfl
  389. # ----          -----------     -------------   --------------  -------------
  390. # DEFAULT=30    RATE=5Mbit      RATE=5Mbit      RATE=3Mbit      RATE=1Kbit
  391. #               BURST=15k       BURST=15k       CEIL=5Mbit      CEIL=5Mbit
  392. #                               LEAF=sfq        BURST=15k       BURST=15k
  393. #                               RULE=*:80,      LEAF=sfq        LEAF=sfq
  394. #                                               RULE=*:25
  395. # ---------------------------------------------------------------------------
  396. #
  397. # Remember that you can only control traffic going out of your linux machine.
  398. # If you have a host connected to network and want to control its traffic on
  399. # the gateway in both directions (with respect to the host), you need to setup
  400. # traffic control for that host on both (or all) gateway interfaces.
  401. #
  402. # Enjoy.
  403. #
  404. #############################################################################
  405.  
  406. export LC_ALL=C
  407.  
  408. ### Command locations
  409. TC=/sbin/tc
  410. IP=/sbin/ip
  411. MP=/sbin/modprobe
  412.  
  413. ### Default filter priorities (must be different)
  414. PRIO_RULE_DEFAULT=${PRIO_RULE:-100}
  415. PRIO_MARK_DEFAULT=${PRIO_MARK:-200}
  416. PRIO_REALM_DEFAULT=${PRIO_REALM:-300}
  417.  
  418. ### Default HTB_PATH & HTB_CACHE settings
  419. HTB_PATH=${HTB_PATH:-/etc/sysconfig/htb}
  420. HTB_CACHE=${HTB_CACHE:-/var/cache/htb.init}
  421.  
  422. ### Uncomment for sed/find with less features (useful for busybox)
  423. #HTB_BASIC="yes"
  424.  
  425. ### Uncomment to enable logfile for debugging
  426. #HTB_DEBUG="/var/run/htb-$1"
  427.  
  428. ### Modules to probe for. Uncomment the last HTB_PROBE
  429. ### line if you have QoS support compiled into kernel
  430. HTB_PROBE="sch_htb sch_sfq cls_fw cls_u32 cls_route"
  431. #HTB_PROBE=""
  432.  
  433. ### Config keywords
  434. HTB_QDISC="DEFAULT|DCACHE|R2Q"
  435. HTB_CLASS="RATE|CEIL|BURST|CBURST|PRIO|LEAF|MTU"
  436. HTB_CLASS="$HTB_CLASS|PRIO_RULE|PRIO_MARK|PRIO_REALM"
  437. HTB_CLASS="$HTB_CLASS|LIMIT|QUANTUM|PERTURB"
  438.  
  439.  
  440. #############################################################################
  441. ############################# SUPPORT FUNCTIONS #############################
  442. #############################################################################
  443.  
  444. if [ -z "$HTB_BASIC" ]; then
  445.        ### List of network devices
  446.        all_device_list () {
  447.                ip link show
  448.                | sed -n "/^[0-9]/ { s/[[:space:]]//g;
  449.                s/^[0-9]+:([^@-]+)(@.+)?:<.*//; p; }"
  450.        } # all_device_list
  451.  
  452.  
  453.        ### Load & filter file $HTB_PATH/$1
  454.        htb_filter_file () {
  455.                sed -n "s/#.*//; s/[^a-zA-Z0-9.,;:=/*-_]+//g;
  456.                /^[a-zA-Z0-9]+=[a-zA-Z0-9.,:;/*-_]+$/ p" $HTB_PATH/$1
  457.        } # htb_filter_file
  458.  
  459.  
  460.        ### Parse class ID chain from file name
  461.        htb_clsid_chain () {
  462.                echo "${1#*-}"
  463.                | sed -n "/^[0-9a-fA-F]/ { s/^([0-9a-fA-F:]+).*//;
  464.                s/::/:/g; s/:$//; p; }"
  465.        } # htb_clsid_chain
  466.  
  467.  
  468.        ### List of classes in $HTB_PATH
  469.        htb_class_list () {
  470.                for dev in `htb_device_list`; do
  471.                        find $HTB_PATH -maxdepth 1 ( -type f -or -type l )
  472.                        -name "$dev-*" -not -name '*~'
  473.                        -printf "%f "| sort
  474.                done
  475.        } # htb_class_list
  476.  
  477.        ### Gather $1 rules from $CFILE
  478.        htb_cfile_rules () {
  479.                echo "$CFILE"| sed -n "/^$1=/ { s/.*=//; p; }"
  480.        } # htb_cfile_rules
  481.  
  482.  
  483.        ### Validate cache against config files
  484.        htb_valid_cache () {
  485.                for dev in `htb_device_list`; do
  486.                        [ `find $HTB_PATH -maxdepth 1 ( -type f -or -type l )
  487.                          -name "$dev*" -newer $HTB_CACHE|
  488.                          wc -l` -gt 0 ] && VALID=0
  489.                        [ $VALID -ne 1 ] && break
  490.                done
  491.        } # htb_valid_cache
  492.  
  493.  
  494.        ### Find class config for device $1, which is newer than cache
  495.        htb_cache_older () {
  496.                [ `find $HTB_PATH -maxdepth 1 -type f -name "$1*"
  497.                   -newer $HTB_CACHE| wc -l` -gt 0 ] && return 0
  498.                return 1
  499.        } # htb_cache_older
  500.  
  501.  
  502.        ### Get current RATE and CEIL
  503.        htb_class_state () {
  504.                tc class show dev $1
  505.                | sed -n "s/[[:space:]]+/ /g; /^class htb 1:$2 /
  506.                { s/.*rate (.+) burst.*//; p; q; }"
  507.        } # htb_class_state
  508.  
  509. else ### Less feature-hungry versions of above functions
  510.  
  511.        all_device_list () {
  512.                ip link show
  513.                | grep "^[0-9]"
  514.                | sed "s/[[:space:]]//g;
  515.                s/^[0-9]+:([^@-]+)(@.+)?:<.*//"
  516.        } # all_device_list
  517.  
  518.        htb_filter_file () {
  519.                sed 's/#.*//; s/[^a-zA-Z0-9.,;:=/*-_]+//g' $HTB_PATH/$1
  520.                | grep '^[a-zA-Z0-9]+=[a-zA-Z0-9.,;:/*-_]+$'
  521.        } # htb_filter_file
  522.  
  523.        htb_clsid_chain () {
  524.                echo "${1#*-}"
  525.                | grep '^[a-fA-F0-9]'
  526.                | sed 's/^([a-fA-F0-9:]+).*//; s/::/:/g; s/:$//'
  527.        } # htb_clsid_chain
  528.  
  529.        htb_class_list () {
  530.                PFX=`echo "$HTB_PATH"| sed 's/////g'`
  531.                for dev in `htb_device_list`; do
  532.                        find $HTB_PATH -type f -name "$dev-*"
  533.                        | grep "^$HTB_PATH/$dev-[^/]+[^~]$"
  534.                        | sed "s/$PFX///"
  535.                        | sort
  536.                done
  537.        } # htb_class_list
  538.  
  539.        htb_cfile_rules () {
  540.                echo "$CFILE"| grep "^$1="| cut -d"=" -f2
  541.        } # htb_cfile_rules
  542.  
  543.        htb_cache_older () {
  544.                ### cache is always up-to-date
  545.                return 1
  546.        } # htb_cache_older
  547.  
  548.        htb_class_state () {
  549.                tc class show dev $1
  550.                | sed 's/[[:space:]]+/ /g'
  551.                | grep "^class htb 1:$2 "
  552.                | sed 's/.*rate (.+) burst.*//'
  553.        } # htb_class_state
  554. fi # HTB_BASIC
  555.  
  556.  
  557. ### List of HTB devices
  558. htb_device_list () {
  559.        for dev in `all_device_list`; do
  560.                [ -f $HTB_PATH/$dev ] && echo $dev
  561.        done
  562. } # htb_device_list
  563.  
  564.  
  565. ### Remove root class from device $1
  566. htb_device_off () {
  567.        tc qdisc del dev $1 root 2> /dev/null
  568. } # htb_device_off
  569.  
  570.  
  571. ### Remove HTB from all devices
  572. htb_off () {
  573.        for dev in `htb_device_list`; do
  574.                htb_device_off $dev
  575.        done
  576. } # htb_off
  577.  
  578.  
  579. ### Prefixed message
  580. htb_message () {
  581.        echo -e "**HTB: $@"
  582. } # htb_message
  583.  
  584. ### Failure message
  585. htb_failure () {
  586.        htb_message "$@"
  587.        exit 1
  588. } # htb_failure
  589.  
  590. ### Failure w/htb_off
  591. htb_fail_off () {
  592.        htb_message "$@"
  593.        htb_off
  594.        exit 1
  595. } # htb_fail_off
  596.  
  597.  
  598. ### Convert time to absolute value
  599. htb_time2abs () {
  600.        local min=${1##*:}; min=${min##0}
  601.        local hrs=${1%%:*}; hrs=${hrs##0}
  602.        echo $[hrs*60 + min]
  603. } # htb_time2abs
  604.  
  605.  
  606. ### Display traffic control setup
  607. htb_show () {
  608.        for dev in `all_device_list`; do
  609.                [ `tc qdisc show dev $dev| wc -l` -eq 0 ] && continue
  610.                echo -e "### $dev: queueing disciplines "
  611.                tc $1 qdisc show dev $dev; echo
  612.  
  613.                [ `tc class show dev $dev| wc -l` -eq 0 ] && continue
  614.                echo -e "### $dev: traffic classes "
  615.                tc $1 class show dev $dev; echo
  616.  
  617.                [ `tc filter show dev $dev| wc -l` -eq 0 ] && continue
  618.                echo -e "### $dev: filtering rules "
  619.                tc $1 filter show dev $dev; echo
  620.        done
  621. } # htb_show
  622.  
  623.  
  624.  
  625. ### Derive DEVICE, CLASS and PARENT from $1
  626. ### Check validity of CLASS and PARENT class IDs
  627. ### Load class configuration from $HTP_PATH/$1
  628. ### Configure class parameters from CFILE
  629. htb_load_class () {
  630.        DEVICE=${1%%-*}
  631.        CLSIDS=`htb_clsid_chain $1`
  632.        CLASS=${CLSIDS##*:}; [ -z "$CLASS" ] &&
  633.                htb_fail_off "$1 has invalid class ID!"
  634.  
  635.        [ $[0x$CLASS] -lt 2 -o $[0x$CLASS] -gt 65535 ] &&
  636.                htb_fail_off "class ID of $1 must be in range 0x2-0xFFFF!"
  637.  
  638.        CLSIDS=${CLSIDS%$CLASS}; CLSIDS=${CLSIDS%:}
  639.        PARENT=${CLSIDS##*:}; [ -n "$PARENT" ] &&
  640.                [ $[0x$PARENT] -lt 2 -o $[0x$PARENT] -gt 65535 ] &&
  641.                        htb_fail_off "parent ID of $1 must be in range 0x2-0xFFFF!"
  642.  
  643.        CFILE=`htb_filter_file $1`
  644.  
  645.  
  646.        ### Set defaults & load class
  647.        MTU=""; LEAF=none; PERTURB=10
  648.        RATE=""; BURST=""; CEIL=""; CBURST=""
  649.        PRIO=""; LIMIT=""; QUANTUM=""
  650.  
  651.        PRIO_RULE=$PRIO_RULE_DEFAULT
  652.        PRIO_MARK=$PRIO_MARK_DEFAULT
  653.        PRIO_REALM=$PRIO_REALM_DEFAULT
  654.  
  655.        eval `echo "$CFILE"| grep "^($HTB_CLASS)="`
  656.        RNAME=""; CNAME=""
  657.  
  658.        ### Resolve RATE if needed
  659.        [ "$RATE" = "prate" ] && RNAME=RATE_$PARENT
  660.        [ "$RATE" = "pceil" ] && RNAME=CEIL_$PARENT
  661.        [ -n "$RNAME" ] && RATE=${!RNAME}
  662.  
  663.        ### RATE is required
  664.        [ -z "$RATE" ] &&
  665.                htb_fail_off "missing or unresolvable RATE in $1!"
  666.  
  667.        ### Resolve CEIL if needed
  668.        [ "$CEIL" = "prate" ] && CNAME=RATE_$PARENT
  669.        [ "$CEIL" = "pceil" ] && CNAME=CEIL_$PARENT
  670.        [ -n "$CNAME" ] && CEIL=${!CNAME}
  671.  
  672.        ### Store CEIL & RATE for children
  673.        eval RATE_$CLASS=$RATE
  674.        eval CEIL_$CLASS=${CEIL:-$RATE}
  675. } # htb_load_class
  676.  
  677.  
  678. #############################################################################
  679. #################################### INIT ###################################
  680. #############################################################################
  681.  
  682. ### Check iproute2 tools
  683. [ -x $TC -a -x $IP ] ||
  684.        htb_failure "iproute2 utilities not installed or executable!"
  685.  
  686. ### Check $HTB_PATH directory
  687. [ -d $HTB_PATH -a -r $HTB_PATH -a -x $HTB_PATH ] ||
  688.        htb_failure "$HTB_PATH does not exist or is not readable!"
  689.  
  690. ### ip/tc wrappers
  691. if [ "$1" = "compile" ]; then
  692.        ### no module probing
  693.        HTB_PROBE=""
  694.  
  695.        ip () {
  696.                $IP "$@"
  697.        } # ip
  698.  
  699.        ### echo-only version of "tc" command
  700.        tc () {
  701.                echo "$TC $@"
  702.        } # tc
  703.  
  704. elif [ -n "$HTB_DEBUG" ]; then
  705.        echo -e "# `date`" > $HTB_DEBUG
  706.  
  707.        ### Logging version of "ip" command
  708.        ip () {
  709.                echo -e " # ip $@" >> $HTB_DEBUG
  710.                $IP "$@" 2>&1 | tee -a $HTB_DEBUG
  711.        } # ip
  712.  
  713.        ### Logging version of "tc" command
  714.        tc () {
  715.                echo -e " # tc $@" >> $HTB_DEBUG
  716.                $TC "$@" 2>&1 | tee -a $HTB_DEBUG
  717.        } # tc
  718. else
  719.        # default wrappers
  720.  
  721.        ip () {
  722.                $IP "$@"
  723.        } # ip
  724.  
  725.        tc () {
  726.                $TC "$@"
  727.        } # tc
  728. fi # ip/tc wrappers
  729.  
  730.  
  731. case "$1" in
  732.  
  733. #############################################################################
  734. ############################### START/COMPILE ###############################
  735. #############################################################################
  736.  
  737. start|compile)
  738.  
  739. ### Probe QoS modules (start only)
  740. for module in $HTB_PROBE; do
  741.        $MP $module || htb_failure "failed to load module $module"
  742. done
  743.  
  744. ### If we are in compile/nocache/logging mode, don't bother with cache
  745. if [ "$1" != "compile" -a "$2" != "nocache" -a -z "$HTB_DEBUG" ]; then
  746.        VALID=1
  747.  
  748.        ### validate the cache
  749.        [ "$2" = "invalidate" -o ! -f $HTB_CACHE ] && VALID=0
  750.        [ $VALID -eq 1 ] && for dev in `htb_device_list`; do
  751.                htb_cache_older $dev && VALID=0
  752.                [ $VALID -ne 1 ] && break
  753.        done
  754.  
  755.        ### compile the config if the cache is invalid
  756.        if [ $VALID -ne 1 ]; then
  757.                $0 compile > $HTB_CACHE ||
  758.                        htb_fail_off "failed to compile HTB configuration!"
  759.        fi
  760.  
  761.        ### run the cached commands
  762.        exec /bin/sh $HTB_CACHE 2> /dev/null
  763. fi
  764.  
  765.  
  766. ### Setup root qdisc on all configured devices
  767. DEVICES=`htb_device_list`
  768. [ -z "$DEVICES" ] && htb_failure "no configured devices found!"
  769.  
  770. for dev in $DEVICES; do
  771.        ### Retrieve root qdisc options
  772.        DEFAULT=""; DCACHE=""; R2Q=""
  773.        eval `htb_filter_file $dev| grep "^($HTB_QDISC)="`
  774.        [ "$DCACHE" = "yes" ] && DCACHE="dcache" || DCACHE=""
  775.  
  776.        ### Remove old root qdisc from device
  777.        htb_device_off $dev
  778.  
  779.        ### Setup root qdisc for the device
  780.        tc qdisc add dev $dev root handle 1 htb
  781.        default ${DEFAULT:-0} ${R2Q:+r2q $R2Q} $DCACHE ||
  782.                htb_fail_off "failed to set root qdisc on $dev!"
  783.  
  784.        [ "$1" = "compile" ] && echo
  785. done # dev
  786.  
  787.  
  788. ### Setup traffic classes (if configured)
  789. for classfile in `htb_class_list`; do
  790.        htb_load_class $classfile
  791.  
  792.        ### Create the class
  793.        tc class add dev $DEVICE parent 1:$PARENT classid 1:$CLASS
  794.        htb rate $RATE ${CEIL:+ceil $CEIL} ${BURST:+burst $BURST}
  795.        ${PRIO:+prio $PRIO} ${CBURST:+cburst $CBURST} ${MTU:+mtu $MTU} ||
  796.                htb_fail_off "failed to add class $CLASS with parent $PARENT on $DEVICE!"
  797.  
  798.        ### Create leaf qdisc if set
  799.        if [ "$LEAF" != "none" ]; then
  800.                if [ "$LEAF" = "sfq" ]; then
  801.                        LEAFPARM="${PERTURB:+perturb $PERTURB} ${QUANTUM:+quantum $QUANTUM}"
  802.                elif [ "$LEAF" = "pfifo" -o "$LEAF" = "bfifo" ]; then
  803.                        LEAFPARM="${LIMIT:+limit $LIMIT}"
  804.                else
  805.                        htb_fail_off "unknown leaf qdisc ($LEAF) in $classfile!"
  806.                fi
  807.  
  808.                tc qdisc add dev $DEVICE
  809.                parent 1:$CLASS handle $CLASS $LEAF $LEAFPARM ||
  810.                        htb_fail_off "failed to add leaf qdisc to class $CLASS on $DEVICE!"
  811.        fi
  812.  
  813.  
  814.        ### Create fw filter for MARK fields
  815.        for mark in `htb_cfile_rules MARK`; do
  816.                ### Attach fw filter to root class
  817.                tc filter add dev $DEVICE parent 1:0 protocol ip
  818.                prio $PRIO_MARK handle $mark fw classid 1:$CLASS
  819.        done ### mark
  820.  
  821.        ### Create route filter for REALM fields
  822.        for realm in `htb_cfile_rules REALM`; do
  823.                ### Split realm into source & destination realms
  824.                SREALM=${realm%%,*}; DREALM=${realm##*,}
  825.                [ "$SREALM" = "$DREALM" ] && SREALM=""
  826.  
  827.                ### Convert asterisks to empty strings
  828.                SREALM=${SREALM#*}; DREALM=${DREALM#*}
  829.  
  830.                ### Attach route filter to the root class
  831.                tc filter add dev $DEVICE parent 1:0 protocol ip
  832.                prio $PRIO_REALM route ${SREALM:+from $SREALM}
  833.                ${DREALM:+to $DREALM} classid 1:$CLASS
  834.        done ### realm
  835.  
  836.        ### Create u32 filter for RULE fields
  837.        for rule in `htb_cfile_rules RULE`; do
  838.                ### Split rule into source & destination
  839.                SRC=${rule%%,*}; DST=${rule##*,}
  840.                [ "$SRC" = "$rule" ] && SRC=""
  841.  
  842.  
  843.                ### Split destination into address, port & mask fields
  844.                DADDR=${DST%%:*}; DTEMP=${DST##*:}
  845.                [ "$DADDR" = "$DST" ] && DTEMP=""
  846.  
  847.                DPORT=${DTEMP%%/*}; DMASK=${DTEMP##*/}
  848.                [ "$DPORT" = "$DTEMP" ] && DMASK="0xffff"
  849.  
  850.  
  851.                ### Split up source (if specified)
  852.                SADDR=""; SPORT=""
  853.                if [ -n "$SRC" ]; then
  854.                        SADDR=${SRC%%:*}; STEMP=${SRC##*:}
  855.                        [ "$SADDR" = "$SRC" ] && STEMP=""
  856.  
  857.                        SPORT=${STEMP%%/*}; SMASK=${STEMP##*/}
  858.                        [ "$SPORT" = "$STEMP" ] && SMASK="0xffff"
  859.                fi
  860.  
  861.  
  862.                ### Convert asterisks to empty strings
  863.                SADDR=${SADDR#*}; DADDR=${DADDR#*}
  864.  
  865.                ### Compose u32 filter rules
  866.                u32_s="${SPORT:+match ip sport $SPORT $SMASK}"
  867.                u32_s="${SADDR:+match ip src $SADDR} $u32_s"
  868.                u32_d="${DPORT:+match ip dport $DPORT $DMASK}"
  869.                u32_d="${DADDR:+match ip dst $DADDR} $u32_d"
  870.  
  871.                ### Uncomment the following if you want to see parsed rules
  872.                #echo "$rule: $u32_s $u32_d"
  873.  
  874.                ### Attach u32 filter to the appropriate class
  875.                tc filter add dev $DEVICE parent 1:0 protocol ip
  876.                prio $PRIO_RULE u32 $u32_s $u32_d classid 1:$CLASS
  877.        done ### rule
  878.  
  879.        [ "$1" = "compile" ] && echo
  880. done ### classfile
  881. ;;
  882.  
  883.  
  884. #############################################################################
  885. ################################# TIME CHECK ################################
  886. #############################################################################
  887.  
  888. timecheck)
  889.  
  890. ### Get time + weekday
  891. TIME_TMP=`date +%w/%k:%M`
  892. TIME_DOW=${TIME_TMP%%/*}
  893. TIME_NOW=${TIME_TMP##*/}
  894. TIME_ABS=`htb_time2abs $TIME_NOW`
  895.  
  896. ### Check all classes (if configured)
  897. for classfile in `htb_class_list`; do
  898.        ### Load class and gather all TIME rules
  899.        htb_load_class $classfile
  900.        TIMESET=`htb_cfile_rules TIME`
  901.        [ -z "$TIMESET" ] && continue
  902.  
  903.        MATCH=0; CHANGE=0
  904.        for timerule in $TIMESET; do
  905.                ### Split TIME rule to pieces
  906.                TIMESPEC=${timerule%%;*}; PARAMS=${timerule##*;}
  907.                WEEKDAYS=${TIMESPEC%%/*}; INTERVAL=${TIMESPEC##*/}
  908.                BEG_TIME=${INTERVAL%%-*}; END_TIME=${INTERVAL##*-}
  909.  
  910.                ### Check the day-of-week (if present)
  911.                [ "$WEEKDAYS" != "$INTERVAL" -a
  912.                  -n "${WEEKDAYS##*$TIME_DOW*}" ] && continue
  913.  
  914.                ### Compute interval boundaries
  915.                BEG_ABS=`htb_time2abs $BEG_TIME`
  916.                END_ABS=`htb_time2abs $END_TIME`
  917.  
  918.                ### Midnight wrap fixup
  919.                if [ $BEG_ABS -gt $END_ABS ]; then
  920.                        [ $TIME_ABS -le $END_ABS ] &&
  921.                                TIME_ABS=$[TIME_ABS + 24*60]
  922.  
  923.                        END_ABS=$[END_ABS + 24*60]
  924.                fi
  925.  
  926.                ### If time period matches, remember params and set MATCH flag
  927.                if [ $TIME_ABS -ge $BEG_ABS -a $TIME_ABS -lt $END_ABS ]; then
  928.                        RATESPEC=${PARAMS%%,*}; CEILSPEC=${PARAMS##*,}
  929.                        [ "$RATESPEC" = "$CEILSPEC" ] && CEILSPEC=""
  930.  
  931.                        NEW_RATE=${RATESPEC%%/*}; NEW_BURST=${RATESPEC##*/}
  932.                        [ "$NEW_RATE" = "$NEW_BURST" ] && NEW_BURST=""
  933.  
  934.                        NEW_CEIL=${CEILSPEC%%/*}; NEW_CBURST=${CEILSPEC##*/}
  935.                        [ "$NEW_CEIL" = "$NEW_CBURST" ] && NEW_CBURST=""
  936.  
  937.                        MATCH=1
  938.                fi
  939.        done ### timerule
  940.  
  941.  
  942.        ### Get current RATE and CEIL of a class
  943.        read RATE_NOW JUNK CEIL_NOW <<-EOT
  944.        `htb_class_state $DEVICE $CLASS`
  945.        EOT
  946.  
  947.        [ -z "$RATE_NOW" -o -z "$CEIL_NOW" ] && continue
  948.  
  949.  
  950.        ### Fill empty values if matched
  951.        if [ $MATCH -ne 0 ]; then
  952.                NEW_RATE=${NEW_RATE:-$RATE_NOW}
  953.                NEW_CEIL=${NEW_CEIL:-$CEIL_NOW}
  954.  
  955.                NEW_BURST=${NEW_BURST:-$BURST}
  956.                NEW_CBURST=${NEW_CBURST:-$CBURST}
  957.  
  958.        ### Force configured values if not matched
  959.        else
  960.                NEW_RATE=$RATE; NEW_CEIL=$CEIL
  961.                NEW_BURST=$BURST; NEW_CBURST=$CBURST
  962.        fi
  963.  
  964.  
  965.  
  966.        ### Check for RATE and CEIL changes
  967.        [ "$RATE_NOW" != "$NEW_RATE" ] && CHANGE=1
  968.        [ "$CEIL_NOW" != "$NEW_CEIL" ] && CHANGE=1
  969.  
  970.        ### If there are no changes, go for next class
  971.        [ $CHANGE -eq 0 ] && continue
  972.  
  973.  
  974.        ### Replace HTB class
  975.        tc class change dev $DEVICE classid 1:$CLASS htb
  976.        prio $PRIO rate $NEW_RATE ${NEW_CEIL:+ceil $NEW_CEIL}
  977.        ${NEW_BURST:+burst $NEW_BURST} ${NEW_CBURST:+cburst $NEW_CBURST}
  978.  
  979.        htb_message "$TIME_NOW: change on $DEVICE:$CLASS ($RATE_NOW/$CEIL_NOW -> $NEW_RATE/$NEW_CEIL)"
  980. done ### class file
  981. ;;
  982.  
  983.  
  984. #############################################################################
  985. ################################## THE REST #################################
  986. #############################################################################
  987.  
  988. stop)
  989.        htb_off
  990.        ;;
  991.  
  992. list)
  993.        htb_show
  994.        ;;
  995.  
  996. stats)
  997.        htb_show -s
  998.        ;;
  999.  
  1000. restart)
  1001.        shift
  1002.        $0 stop
  1003.        $0 start "$@"
  1004.        ;;
  1005.  
  1006. *)
  1007.        echo "Usage: `basename $0` {start|compile|stop|restart|timecheck|list|stats}"
  1008. esac
  1009.  

/root/generate.sh
Код
GeSHi (Bash):
  1. #!/bin/bash
  2. BASENET="192.168"
  3. BASEDIR="/etc/sysconfig/htb"
  4.  
  5. LANIF="eth0.751"
  6. WANIF="eth0.600"
  7.  
  8. ISPUP="15Mbit"
  9. ISPDOWN="15Mbit"
  10.  
  11. CLUP_MIN="128Kbit"
  12. CLDOWN_MIN="256Kbit"
  13.  
  14. CLUP_MAX="256kbit"
  15. CLDOWN_MAX="1024kbit"
  16.  
  17. CLPRIO="5"
  18. CLLEAF="sfq"
  19.  
  20. DEFIF="DEFAULT=FFFF R2Q=100"
  21. DEFLAST="RATE=128Kbit CEIL=128Kbit PRIO=7 LEAF=sfq"
  22.  
  23. DEFSSH="RATE=1Mbit CEIL=1Mbit PRIO=1 RULE=*:22, RULE=*:22 LEAF=sfq"
  24. DEFSNMP="RATE=1Mbit CEIL=1Mbit PRIO=1 RULE=*:161, RULE=*:161 LEAF=sfq"
  25.  
  26.  
  27. rm -f $BASEDIR/*
  28. iptables -t mangle -F
  29.  
  30. echo -e $DEFIF > $BASEDIR/$LANIF
  31. echo -e $DEFIF > $BASEDIR/$WANIF
  32.  
  33. echo -e $DEFLAST > $BASEDIR/$LANIF-2:FFFF.default
  34. echo -e $DEFLAST > $BASEDIR/$WANIF-2:FFFF.default
  35.  
  36. echo -e $DEFSSH > $BASEDIR/$LANIF-2:FFFE.ssh
  37. echo -e $DEFSSH > $BASEDIR/$WANIF-2:FFFE.ssh
  38.  
  39. echo -e $DEFSNMP > $BASEDIR/$LANIF-2:FFFD.snmp
  40. echo -e $DEFSNMP > $BASEDIR/$WANIF-2:FFFD.snmp
  41.  
  42. echo -e "RATE=$ISPDOWN CEIL=$ISPDOWN" > $BASEDIR/$LANIF-2.root
  43. echo -e "RATE=$ISPUP CEIL=$ISPUP" > $BASEDIR/$WANIF-2.root
  44.  
  45. for j in 44 45
  46. do
  47.    for i in {1..254}
  48.    do
  49.        MARK=`printf '%x ' $j$i`        
  50.  
  51.        echo "RATE=$CLDOWN_MIN" > $BASEDIR/$LANIF-2:$MARK.$BASENET.$j.$i
  52.        echo "CEIL=$CLDOWN_MAX" >> $BASEDIR/$LANIF-2:$MARK.$BASENET.$j.$i
  53.        echo "PRIO=$CLPRIO" >> $BASEDIR/$LANIF-2:$MARK.$BASENET.$j.$i
  54.        echo "LEAF=$CLLEAF" >> $BASEDIR/$LANIF-2:$MARK.$BASENET.$j.$i
  55.        echo "RULE=$BASENET.$j.$i" >> $BASEDIR/$LANIF-2:$MARK.$BASENET.$j.$i
  56.  
  57.        echo "RATE=$CLUP_MIN" > $BASEDIR/$WANIF-2:$MARK.$BASENET.$j.$i
  58.        echo "CEIL=$CLUP_MAX" >> $BASEDIR/$WANIF-2:$MARK.$BASENET.$j.$i
  59.        echo "PRIO=$CLPRIO" >> $BASEDIR/$WANIF-2:$MARK.$BASENET.$j.$i
  60.        echo "LEAF=$CLLEAF" >> $BASEDIR/$WANIF-2:$MARK.$BASENET.$j.$i
  61.        echo "MARK=0x$MARK" >> $BASEDIR/$WANIF-2:$MARK.$BASENET.$j.$i
  62.  
  63.        iptables -t mangle -A PREROUTING -s $BASENET.$j.$i -j MARK --set-mark 0x$MARK
  64.        iptables -t mangle -A PREROUTING -s $BASENET.$j.$i -j RETURN
  65.    done
  66. done
  67.  
  68. echo "Restarting HTB..."
  69. service htb.init restart
  70.  

/etc/sysconfig/iptables
Код
GeSHi (Bash):
  1. *filter
  2. :INPUT ACCEPT [0:0]
  3. :FORWARD ACCEPT [0:0]
  4. :OUTPUT ACCEPT [0:0]
  5.  
  6. # ACCEPT TRAFFIC FORWARDING
  7. -A FORWARD -j ACCEPT
  8. COMMIT
  9.  
  10. *nat
  11. -A POSTROUTING -s 192.168.44.0/23 -j MASQUERADE
  12.  
  13. COMMIT
  14.  
« Последна редакция: Mar 01, 2015, 19:50 от BRADATA »
Активен

Подобни теми
Заглавие Започната от Отговора Прегледи Последна публикация
Bandwidth при Download
Настройка на програми
DBoy 1 1032 Последна публикация Jan 17, 2005, 15:50
от
Проблем с видеото centos
Настройка на програми
svemat 3 3470 Последна публикация Sep 10, 2007, 13:58
от Kalin
Centos 5.1
Настройка на програми
svetoslav27 4 6159 Последна публикация Mar 10, 2008, 01:06
от dedmin
bandwidth limit
Настройка на програми
Hijack 1 1176 Последна публикация Jun 26, 2009, 11:14
от VladSun
Iptables - iptables-restore: line 36 failed
Сървъри
sianbg 5 6351 Последна публикация Nov 26, 2013, 13:04
от petar258