Compare commits

..

16 Commits

Author SHA1 Message Date
6e8391545b fix: do not return negative quotas 2026-07-11 21:13:48 +02:00
e5c985fe00 feat: remove time. Improve README. 2026-07-11 21:12:36 +02:00
42676e5b51 feat: update new default config values 2026-05-28 16:52:49 +02:00
062b6da045 Fix config and README 2026-05-18 19:54:27 +02:00
d571db9700 Fix config and README 2026-05-18 19:43:10 +02:00
144f20be81 feat: improved README and set 1 as starting day 2026-05-18 19:29:58 +02:00
dfcb1698e6 Add reboot button 2022-08-06 19:20:06 +02:00
28dc5f542d Time limitation re-enabled 2022-08-06 18:47:18 +02:00
ac5366b49c Deleted time references in index.html 2021-07-09 11:59:21 +02:00
33eaaa5b28 --wait in all iptables calls 2021-07-09 11:33:59 +02:00
7fcb2d09f6 Deleted time frame option. Changed web from megas to gigas. 2021-07-09 11:30:44 +02:00
7e576663b8 EXCLUDE_NETWORK3 2021-07-09 11:14:38 +02:00
f11d8ade11 fix for last bugfix... 2021-04-19 18:13:19 +02:00
8d97b2ad32 bugfix: iptables wait for lock 2021-04-19 18:08:22 +02:00
Eneko Nieto
12b8bdbc25 Fixed README 2021-02-08 22:32:02 +01:00
Eneko Nieto
a6188c7064 README and added second excluded network 2021-02-07 16:18:51 +01:00
9 changed files with 134 additions and 218 deletions

32
README.md Normal file
View File

@@ -0,0 +1,32 @@
# Limitator
## Monthly quota for OpenWRT
### Install
1) Copy `limitator` to `/etc/init.d/`
```
scp -O limitator root@ROUTER:/etc/init.d
```
2) Run `chmod +x /etc/init.d/limitator`
3) Copy `config/limitator` to `/etc/config/`
```
scp -O config/limitator root@ROUTER:/etc/config
```
4) Edit `/etc/config/limitator` if needed.
5) Copy `www/*` to `/www/`
```
scp -rO www root@ROUTER:/
```
6) Run `chmod +x /www/cgi-bin/limitator.json`
7) Run `opkg update && opkg install iptables-mod-extra coreutils-date`
8) Run `opkg install iptables-mod-extra`
9) Run `opkg install coreutils-date`
10) Run `mkdir ~/limitator`
11) Run `crontab -e` and copy&paste contents in `crontab` file.
12) Run `/etc/init.d/limitator enable`
13) Reboot.
### Additional steps for Backfire 10.03
1) Change packages source in /etc/opkg.conf putting http://web.archive.org/web/20260213065024id_/ before the URL. For example: http://web.archive.org/web/20260213065024id_/https://archive.openwrt.org/backfire/10.03.1/brcm-2.4/packages
2) Install iptables-mod-ipopt (NO ESTOY SEGURO, SIN PONERLO FUNCIONA Y EN EL WRT54G DABA ERROR EL COMANDO IPTABLES CON EL MODULO QUOTA Y LO TENÍA INSTALADO)
3) Delete /bin/date link
4) Cannot scp files, you need to paste but vi messes with idents. Use `:set noai` command in vi. Other option is using wget from other routers (not an option for limitator.json).

View File

@@ -1,6 +1,9 @@
config limitator 'limitator'
option quota '150'
option wan_dev 'eth1.1'
option exclude_network '10.0.2.0/24'
option exclude_network '10.0.1.0/24'
option exclude_network2 '10.0.3.0/24'
option exclude_network3 '10.0.0.0/24'
option iptables_forward 'FORWARD'
option iptables_input 'INPUT'
option iptables_output 'OUTPUT'
option iptables_output 'OUTPUT'

12
crontab
View File

@@ -1,7 +1,15 @@
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# Limitator
# Save used bytes to local file
*/10 7-23 * * * /etc/init.d/limitator save &
# Restart at midnight
1 0 1-12,14-31 * * /etc/init.d/limitator restart &
# Reset the quota monthly
1 0 13 * * /etc/init.d/limitator reset &
# Reset the quota monthly (MUST BE START DAY!)
1 0 1 * * /etc/init.d/limitator reset &
# Reboot at 4:30am every day
# Note: To avoid infinite reboot loop, wait 70 seconds
# and touch a file in /etc so clock will be set
# properly to 4:31 on reboot before cron starts.
30 4 * * * sleep 70 && touch /etc/banner && reboot

View File

@@ -11,13 +11,13 @@ EXTRA_HELP=<<EOF
EOF
config_load "limitator"
config_get MONTHLY_QUOTA limitator quota 15 # Monthly quota in GB
config_get MONTHLY_QUOTA limitator quota 120 # Monthly quota in GB
config_get WAN_DEV limitator wan_dev 'wlan0' # Interface name for WAN
config_get FIRST_DAY limitator first_day 13 # Day of month when internet plan starts accounting.
config_get START_TIME limitator start_time '07:00' # Starting time of internet plan limited hours.
config_get END_TIME limitator end_time '23:00' # Ending time of internet plan limited hours.
config_get FIRST_DAY limitator first_day 1 # Day of month when internet plan starts accounting.
config_get INTRANET limitator intranet '10.0.0.0/8' # Traffic in Intranet does not count for quota.
config_get EXCLUDE_NETWORK limitator exclude_network # Traffic originated in specified network does not count for quota.
config_get EXCLUDE_NETWORK2 limitator exclude_network2 # Traffic originated in specified network does not count for quota.
config_get EXCLUDE_NETWORK3 limitator exclude_network3 # Traffic originated in specified network does not count for quota.
config_get USED_BYTES_FILE limitator used_bytes_file '/root/limitator/used_bytes' # A persistent file to save used bytes value.
config_get LOG_FILE limitator log_file '/root/limitator/log' # A persistent file to log.
config_get IPTABLES_CHAIN limitator iptables_chain 'LIMITATOR' # Name of iptables chain.
@@ -25,13 +25,6 @@ config_get IPTABLES_FORWARD limitator iptables_forward 'forwarding_rule' # Name
config_get IPTABLES_INPUT limitator iptables_input 'input_rule' # Name of iptables rule for input.
config_get IPTABLES_OUTPUT limitator iptables_output 'output_rule' # Name of iptables rule for output.
check_environment(){
# Detect if iptables-mod-extra module is installed
[ -z "$(opkg info iptables-mod-extra|grep installed)" ] && echo "iptables-mod-extra module is not installed." && opkg update && opkg install iptables-mod-extra
# Detect if xt_quota module is loaded
[ -z "$(lsmod|grep xt_quota)" ] && echo "xt_quota module is not loaded" && modprobe xt_quota
}
get_saved_used_bytes(){
local used_bytes
if [ -s "$USED_BYTES_FILE" ];then
@@ -44,14 +37,22 @@ get_saved_used_bytes(){
get_iptables_quota_rule_num(){
if [ -n "$EXCLUDE_NETWORK" ];then
echo -n 3
if [ -n "$EXCLUDE_NETWORK2" ];then
if [ -n "$EXCLUDE_NETWORK3" ];then
echo -n 7
else
echo -n 5
fi
else
echo -n 3
fi
else
echo -n 1
fi
}
get_current_used_bytes(){
local used_bytes=$(iptables -vnxL $IPTABLES_CHAIN $(get_iptables_quota_rule_num) | awk '{print $2}')
local used_bytes=$(iptables --wait -vnxL $IPTABLES_CHAIN $(get_iptables_quota_rule_num) | awk '{print $2}')
if [ -n "$used_bytes" ];then
echo -n $used_bytes
else
@@ -86,7 +87,12 @@ get_total_quota_until_today(){
}
get_remaining_quota(){
echo -n $(($(get_total_quota_until_today) - $(get_current_used_bytes)))
local remaining_quota=$(($(get_total_quota_until_today) - $(get_current_used_bytes)))
if [ $remaining_quota -lt 0 ]; then
echo 0
else
echo -n $remaining_quota
fi
}
show_remaining_quota(){
@@ -99,40 +105,46 @@ get_json(){
}
reset_quota(){
iptables -Z $IPTABLES_CHAIN $(get_iptables_quota_rule_num)
iptables --wait -Z $IPTABLES_CHAIN $(get_iptables_quota_rule_num)
echo -n 0 > ${USED_BYTES_FILE}
}
del_iptables_rule(){
iptables -F $IPTABLES_CHAIN
iptables --wait -F $IPTABLES_CHAIN
for chain_name in $IPTABLES_FORWARD $IPTABLES_INPUT $IPTABLES_OUTPUT
do
while true
do
line=$(iptables -L $chain_name|sed -e '1,2d'|grep -n $IPTABLES_CHAIN|head -1|cut -d : -f 1 2>/dev/null)
[ -n "$(echo $line|grep -E ^[[:digit:]]+$)" ] && iptables -D $chain_name $line || break
line=$(iptables --wait -L $chain_name|sed -e '1,2d'|grep -n $IPTABLES_CHAIN|head -1|cut -d : -f 1 2>/dev/null)
[ -n "$(echo $line|grep -E ^[[:digit:]]+$)" ] && iptables --wait -D $chain_name $line || break
done
done
iptables -X $IPTABLES_CHAIN
iptables --wait -D $IPTABLES_FORWARD 1
iptables --wait -X $IPTABLES_CHAIN
}
set_iptables_rule(){
iptables -N $IPTABLES_CHAIN
iptables --wait -N $IPTABLES_CHAIN
if [ -n "$EXCLUDE_NETWORK" ];then
iptables -I $IPTABLES_CHAIN 1 -s $EXCLUDE_NETWORK -j ACCEPT
iptables -I $IPTABLES_CHAIN 2 -d $EXCLUDE_NETWORK -j ACCEPT
iptables --wait -I $IPTABLES_CHAIN 1 -s $EXCLUDE_NETWORK -j ACCEPT
iptables --wait -I $IPTABLES_CHAIN 2 -d $EXCLUDE_NETWORK -j ACCEPT
fi
iptables -I $IPTABLES_CHAIN $(get_iptables_quota_rule_num) -c 0 $(get_saved_used_bytes) -m quota --quota $(get_remaining_quota) -j ACCEPT
iptables -I $IPTABLES_CHAIN $(($(get_iptables_quota_rule_num) + 1)) -j REJECT
if [ -n "$EXCLUDE_NETWORK2" ];then
iptables --wait -I $IPTABLES_CHAIN 3 -s $EXCLUDE_NETWORK2 -j ACCEPT
iptables --wait -I $IPTABLES_CHAIN 4 -d $EXCLUDE_NETWORK2 -j ACCEPT
fi
if [ -n "$EXCLUDE_NETWORK3" ];then
iptables --wait -I $IPTABLES_CHAIN 5 -s $EXCLUDE_NETWORK3 -j ACCEPT
iptables --wait -I $IPTABLES_CHAIN 6 -d $EXCLUDE_NETWORK3 -j ACCEPT
fi
iptables --wait -I $IPTABLES_CHAIN $(get_iptables_quota_rule_num) -c 0 $(get_saved_used_bytes) -m quota --quota $(get_remaining_quota) -j ACCEPT 2>> $LOG_FILE
iptables --wait -I $IPTABLES_CHAIN $(($(get_iptables_quota_rule_num) + 1)) -j REJECT 2>> $LOG_FILE
# Iptables requires UTC time
local start_time_utc=$(date -u +%H:%M --date=@$(date -d "today $START_TIME" +%s))
local end_time_utc=$(date -u +%H:%M --date=@$(date -d "today $END_TIME" +%s))
iptables -I $IPTABLES_FORWARD -i $WAN_DEV ! -s $INTRANET -m time --timestart $start_time_utc --timestop $end_time_utc -j $IPTABLES_CHAIN
iptables -I $IPTABLES_FORWARD -o $WAN_DEV ! -d $INTRANET -m time --timestart $start_time_utc --timestop $end_time_utc -j $IPTABLES_CHAIN
iptables -I $IPTABLES_INPUT -i $WAN_DEV ! -s $INTRANET -m time --timestart $start_time_utc --timestop $end_time_utc -j $IPTABLES_CHAIN
iptables -I $IPTABLES_OUTPUT -o $WAN_DEV ! -d $INTRANET -m time --timestart $start_time_utc --timestop $end_time_utc -j $IPTABLES_CHAIN
iptables --wait -I $IPTABLES_FORWARD 1 -d $INTRANET -s $INTRANET -j ACCEPT
iptables -I $IPTABLES_FORWARD 2 -j $IPTABLES_CHAIN
iptables -I $IPTABLES_INPUT -i $WAN_DEV ! -s $INTRANET -j $IPTABLES_CHAIN
iptables -I $IPTABLES_OUTPUT -o $WAN_DEV ! -d $INTRANET -j $IPTABLES_CHAIN
}
start() {

View File

@@ -1,168 +0,0 @@
#!/bin/sh /etc/rc.common
START=95
STOP=01
EXTRA_COMMANDS="save reset show json"
EXTRA_HELP=<<EOF
reset Resets quota
save Saves counters to persistent storage
show Shows remaining quota
json Print data in JSON format
EOF
config_load "limitator"
config_get MONTHLY_QUOTA limitator quota 15 # Monthly quota in GB
config_get WAN_DEV limitator wan_dev 'wlan0' # Interface name for WAN
config_get FIRST_DAY limitator first_day 13 # Day of month when internet plan starts accounting.
config_get START_TIME limitator start_time '07:00' # Starting time of internet plan limited hours.
config_get END_TIME limitator end_time '23:00' # Ending time of internet plan limited hours.
config_get INTRANET limitator intranet '10.0.0.0/8' # Traffic in Intranet does not count for quota.
config_get EXCLUDE_NETWORK limitator exclude_network # Traffic originated in specified network does not count for quota.
config_get USED_BYTES_FILE limitator used_bytes_file '/root/limitator/used_bytes' # A persistent file to save used bytes value.
config_get LOG_FILE limitator log_file '/root/limitator/log' # A persistent file to log.
config_get IPTABLES_CHAIN limitator iptables_chain 'LIMITATOR' # Name of iptables chain.
config_get IPTABLES_FORWARD limitator iptables_forward 'forwarding_rule' # Name of iptables rule for forward.
config_get IPTABLES_INPUT limitator iptables_input 'input_rule' # Name of iptables rule for input.
config_get IPTABLES_OUTPUT limitator iptables_output 'output_rule' # Name of iptables rule for output.
check_environment(){
# Detect if iptables-mod-extra module is installed
[ -z "$(opkg info iptables-mod-extra|grep installed)" ] && echo "iptables-mod-extra module is not installed." && opkg update && opkg install iptables-mod-extra
# Detect if xt_quota module is loaded
[ -z "$(lsmod|grep xt_quota)" ] && echo "xt_quota module is not loaded" && modprobe xt_quota
}
get_saved_used_bytes(){
local used_bytes
if [ -s "$USED_BYTES_FILE" ];then
used_bytes=$(cat $USED_BYTES_FILE 2>/dev/null)
else
used_bytes=0
fi
echo -n $used_bytes
}
get_iptables_quota_rule_num(){
if [ -n "$EXCLUDE_NETWORK" ];then
echo -n 3
else
echo -n 1
fi
}
get_current_used_bytes(){
local used_bytes=$(iptables -vnxL $IPTABLES_CHAIN $(get_iptables_quota_rule_num) | awk '{print $2}')
if [ -n "$used_bytes" ];then
echo -n $used_bytes
else
get_saved_used_bytes
fi
}
set_saved_used_bytes(){
local used_bytes=$(get_current_used_bytes)
if [ $used_bytes -gt 0 ];then
echo -n $used_bytes > $USED_BYTES_FILE
fi
}
get_total_quota_until_today(){
local current_time=$(date +'%s')
local first_day=$(date -d $(date +"%Y-%m-$FIRST_DAY") +'%s')
local next_first_day
if [ $current_time -ge $first_day ]; then
next_first_day=$(date -d $(date -d "1 month" +"%Y-%m-$FIRST_DAY") +'%s')
else
next_first_day=$first_day
first_day=$(date -d $(date -d "1 month ago" +"%Y-%m-$FIRST_DAY") +'%s')
fi
local seconds_in_month=$(($next_first_day - $first_day))
local montly_quota_bytes=$(($MONTHLY_QUOTA * 1024 * 1024 * 1024))
local elapsed_seconds_tomorrow=$(($(date -d $(date -d "1 day" +'%Y-%m-%d') +'%s') - $first_day))
echo -n $(($montly_quota_bytes * $elapsed_seconds_tomorrow / $seconds_in_month))
}
get_remaining_quota(){
echo -n $(($(get_total_quota_until_today) - $(get_current_used_bytes)))
}
show_remaining_quota(){
echo Remaining: $(($(get_remaining_quota) / 1024 / 1024)) MB
echo Total quota until today: $(($(get_total_quota_until_today) / 1024 / 1024)) MB
}
get_json(){
echo -n "{ \"remaining\": $(get_remaining_quota), \"used_bytes\": $(get_current_used_bytes), \"current_quota\": $(get_total_quota_until_today), \"total_quota\": $(($MONTHLY_QUOTA * 1024 * 1024 * 1024)) }"
}
reset_quota(){
iptables -Z $IPTABLES_CHAIN $(get_iptables_quota_rule_num)
echo -n 0 > ${USED_BYTES_FILE}
}
del_iptables_rule(){
iptables -F $IPTABLES_CHAIN
for chain_name in $IPTABLES_FORWARD $IPTABLES_INPUT $IPTABLES_OUTPUT
do
while true
do
line=$(iptables -L $chain_name|sed -e '1,2d'|grep -n $IPTABLES_CHAIN|head -1|cut -d : -f 1 2>/dev/null)
[ -n "$(echo $line|grep -E ^[[:digit:]]+$)" ] && iptables -D $chain_name $line || break
done
done
iptables -X $IPTABLES_CHAIN
}
set_iptables_rule(){
iptables -N $IPTABLES_CHAIN
if [ -n "$EXCLUDE_NETWORK" ];then
iptables -I $IPTABLES_CHAIN 1 -s $EXCLUDE_NETWORK -j ACCEPT
iptables -I $IPTABLES_CHAIN 2 -d $EXCLUDE_NETWORK -j ACCEPT
fi
iptables -I $IPTABLES_CHAIN $(get_iptables_quota_rule_num) -c 0 $(get_saved_used_bytes) -m quota --quota $(get_remaining_quota) -j ACCEPT
iptables -I $IPTABLES_CHAIN $(($(get_iptables_quota_rule_num) + 1)) -j REJECT
# Iptables requires UTC time
local start_time_utc=$(date -u +%H:%M --date=@$(date -d "today $START_TIME" +%s))
local end_time_utc=$(date -u +%H:%M --date=@$(date -d "today $END_TIME" +%s))
iptables -I $IPTABLES_FORWARD -i $WAN_DEV ! -s $INTRANET -m time --timestart $start_time_utc --timestop $end_time_utc -j $IPTABLES_CHAIN
iptables -I $IPTABLES_FORWARD -o $WAN_DEV ! -d $INTRANET -m time --timestart $start_time_utc --timestop $end_time_utc -j $IPTABLES_CHAIN
iptables -I $IPTABLES_INPUT -i $WAN_DEV ! -s $INTRANET -m time --timestart $start_time_utc --timestop $end_time_utc -j $IPTABLES_CHAIN
iptables -I $IPTABLES_OUTPUT -o $WAN_DEV ! -d $INTRANET -m time --timestart $start_time_utc --timestop $end_time_utc -j $IPTABLES_CHAIN
}
start() {
set_iptables_rule
}
stop() {
set_saved_used_bytes
echo $(date +'%F %H:%M') used_bytes=$(get_current_used_bytes) >> $LOG_FILE
del_iptables_rule
}
restart() {
stop
start
}
save() {
set_saved_used_bytes
}
reset() {
reset_quota
restart
}
show() {
show_remaining_quota
}
json() {
get_json
}

7
www/cgi-bin/reboot Normal file
View File

@@ -0,0 +1,7 @@
#!/bin/sh
echo "Content-Type: text/html"
echo ""
echo "<h1>Ciao!</h1>"
/sbin/reboot

View File

@@ -23,23 +23,20 @@
<br><br>
<h3>Descripción</h3>
<p>El periodo de facturación de internet comienza el día 13. La cuota mensual se divide entre la cantidad de días
<p>El periodo de facturación de internet comienza el día 1. La cuota mensual se divide entre la cantidad de días
del periodo de facturación y se va asignando según transcurren los días. Si se sobrepasa la cuota asignada se
corta la conexión a internet y hay que esperar a que transcurra el día para que se asigne la cuota del próximo
día.</p>
<p>Entre las 23h y 7h es la franja gratuita, la conexión a Internet siempre está disponible y el consumo no cuenta
para la cuota.</p>
<br><br>
<h3>Leyenda</h3>
<p>Cuota restante: megas restantes antes de cortarse la conexión a Internet.</p>
<p>Velocidad actual: velocidad de transferencia en este mismo instante, en Kilobytes por segundo. Solo cuenta la cuota
consumida, por lo que de 23h a 7h marca 0 KB/s.</p>
<p>Usado: megas usados en el periodo de facturación actual.</p>
<p>Cuota asignada hasta hoy: megas totales asignados hasta el día de hoy. El último día será igual a la cuota
<p>Cuota restante: gigas restantes antes de cortarse la conexión a Internet.</p>
<p>Velocidad actual: velocidad de transferencia en este mismo instante, en Kilobytes por segundo.</p>
<p>Usado: gigas usados en el periodo de facturación actual.</p>
<p>Cuota asignada hasta hoy: gigas totales asignados hasta el día de hoy. El último día será igual a la cuota
mensual total.</p>
<p>Cuota mensual total: megas totales disponibles para todo el mes.</p>
<p>Cuota mensual total: gigas totales disponibles para todo el mes.</p>
<br><br>
@@ -50,4 +47,4 @@
<script src="js/main.js"></script>
</body>
</html>
</html>

View File

@@ -50,10 +50,10 @@ function getCounters(funcToParse) {
function parseCounters(data) {
let counters = JSON.parse(data);
document.getElementById("remaining").innerHTML = bytesToMegas(counters.remaining);
document.getElementById("used_bytes").innerHTML = bytesToMegas(counters.used_bytes);
document.getElementById("current_quota").innerHTML = bytesToMegas(counters.current_quota);
document.getElementById("total_quota").innerHTML = bytesToMegas(counters.total_quota);
document.getElementById("remaining").innerHTML = bytesToGigas(counters.remaining);
document.getElementById("used_bytes").innerHTML = bytesToGigas(counters.used_bytes);
document.getElementById("current_quota").innerHTML = bytesToGigas(counters.current_quota);
document.getElementById("total_quota").innerHTML = bytesToGigas(counters.total_quota);
updateSpeed(counters.used_bytes);
}
@@ -77,6 +77,10 @@ function updateSpeed(used_bytes) {
chart.update();
}
function bytesToGigas(number) {
return (number / 1024 / 1024 / 1024).toFixed(1) + ' GB';
}
function bytesToMegas(number) {
return (number / 1024 / 1024).toFixed(1) + ' MB';
}

21
www/reboot.html Normal file
View File

@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta charset="UTF-8">
</head>
<body style="background-color: white">
<div style="padding: 40px">
<input type="button" onclick="location.href='/cgi-bin/reboot'" value="Reiniciar router" />
</div>
<div style="padding: 40px">
<a style="color: black; font-family: arial, helvetica, sans-serif;" href="/cgi-bin/luci/">LuCI - Lua
Configuration Interface</a>
</div>
</body>
</html>