Fix speed limits of peers inside a limited network and require profile values

This commit is contained in:
Eduardo Silva
2026-11-24 19:41:20 -03:00
parent 3f2da7e545
commit 7d4b083854
7 changed files with 191 additions and 75 deletions
+56 -16
View File
@@ -28,8 +28,12 @@ def ifb_name(interface):
return f'ifb{interface}'[:15] return f'ifb{interface}'[:15]
def parse_speed_limits(config_content): def parse_peers(config_content):
"""Return a list of {'networks': [...], 'download_kbit': int, ...} for each limited peer of the configuration.""" """Return a list of {'networks': [...], 'download_kbit': int, ...} for each peer of the configuration.
Peers without limits are included (with no limit keys): their networks may be inside the networks of a limited
peer and must not be shaped with it.
"""
peers = [] peers = []
current = None current = None
for raw_line in config_content.splitlines(): for raw_line in config_content.splitlines():
@@ -57,13 +61,14 @@ def parse_speed_limits(config_content):
if current is not None: if current is not None:
peers.append(current) peers.append(current)
limited_peers = [] return [{'networks': peer['networks'], **peer['limits']} for peer in peers if peer['networks']]
for peer in peers:
limits = peer['limits']
if not peer['networks'] or not (limits.get('download_kbit') or limits.get('upload_kbit')): def parse_speed_limits(config_content):
continue """Return the peers of the configuration that have at least one limit."""
limited_peers.append({'networks': peer['networks'], **limits}) return [
return limited_peers peer for peer in parse_peers(config_content) if peer.get('download_kbit') or peer.get('upload_kbit')
]
def _filter_priority(network): def _filter_priority(network):
@@ -90,17 +95,52 @@ def _htb_commands(device, peers, direction, match):
return commands return commands
def build_tc_commands(interface, limited_peers, upload=True): def _unlimited_networks(peers, limited_peers):
"""tc batch commands that install the limits on a clean interface (and on a clean ifb for the upload).""" """Networks of the other peers that are inside a network of a limited peer.
WireGuard sends their traffic to the peer with the most specific network, but a tc filter of the broader network
would also match it. These networks get their own filter, checked first, that lets the traffic pass.
"""
limited_networks = [network for peer in limited_peers for network in peer['networks']]
networks = []
for peer in peers:
if any(peer is limited_peer for limited_peer in limited_peers):
continue
for network in peer['networks']:
if any(
network != limited_network and network.subnet_of(limited_network)
for limited_network in limited_networks
):
networks.append(network)
return networks
def build_tc_commands(interface, peers, upload=True):
"""tc batch commands that install the limits on a clean interface (and on a clean ifb for the upload).
peers may include the peers without limits, so their traffic is not shaped with a limited peer whose networks
contain theirs.
"""
commands = [] commands = []
download_peers = [peer for peer in limited_peers if peer.get('download_kbit')] download_peers = [peer for peer in peers if peer.get('download_kbit')]
upload_peers = [peer for peer in limited_peers if peer.get('upload_kbit')] if upload else [] upload_peers = [peer for peer in peers if peer.get('upload_kbit')] if upload else []
if download_peers: if download_peers:
commands += _htb_commands(interface, download_peers, 'download', 'dst') commands += _htb_commands(interface, download_peers, 'download', 'dst')
for network in _unlimited_networks(peers, download_peers):
# flowid 1: is the htb itself: the packet is sent without a class, like unclassified traffic
commands.append(
f'filter add dev {interface} parent 1: protocol ip prio {_filter_priority(network)} '
f'u32 match ip dst {network} flowid 1:'
)
if upload_peers: if upload_peers:
ifb = ifb_name(interface) ifb = ifb_name(interface)
commands.append(f'qdisc add dev {interface} handle ffff: ingress') commands.append(f'qdisc add dev {interface} handle ffff: ingress')
for network in _unlimited_networks(peers, upload_peers):
commands.append(
f'filter add dev {interface} parent ffff: protocol ip prio {_filter_priority(network)} '
f'u32 match ip src {network} action ok'
)
# Only the traffic of limited peers goes through the ifb; the rest is not touched # Only the traffic of limited peers goes through the ifb; the rest is not touched
for peer in upload_peers: for peer in upload_peers:
for network in peer['networks']: for network in peer['networks']:
@@ -139,7 +179,7 @@ def apply_speed_limits(interface, config_path, run=None):
run = run or subprocess.run run = run or subprocess.run
try: try:
with open(config_path) as config_file: with open(config_path) as config_file:
limited_peers = parse_speed_limits(config_file.read()) peers = parse_peers(config_file.read())
except OSError as error: except OSError as error:
return [f'{config_path}: {error}'] return [f'{config_path}: {error}']
@@ -147,7 +187,7 @@ def apply_speed_limits(interface, config_path, run=None):
for parent in ('root', 'ingress'): for parent in ('root', 'ingress'):
run(['tc', 'qdisc', 'del', 'dev', interface, parent], capture_output=True, text=True) run(['tc', 'qdisc', 'del', 'dev', interface, parent], capture_output=True, text=True)
upload = any(peer.get('upload_kbit') for peer in limited_peers) upload = any(peer.get('upload_kbit') for peer in peers)
if upload: if upload:
ifb_error = _prepare_ifb(interface, run) ifb_error = _prepare_ifb(interface, run)
if ifb_error: if ifb_error:
@@ -157,7 +197,7 @@ def apply_speed_limits(interface, config_path, run=None):
else: else:
run(['ip', 'link', 'delete', ifb_name(interface)], capture_output=True, text=True) run(['ip', 'link', 'delete', ifb_name(interface)], capture_output=True, text=True)
commands = build_tc_commands(interface, limited_peers, upload=upload) commands = build_tc_commands(interface, peers, upload=upload)
if not commands: if not commands:
return errors return errors
result = run(['tc', '-batch', '-'], input='\n'.join(commands) + '\n', capture_output=True, text=True) result = run(['tc', '-batch', '-'], input='\n'.join(commands) + '\n', capture_output=True, text=True)
+12 -14
View File
@@ -1,5 +1,3 @@
from decimal import Decimal
from crispy_forms.helper import FormHelper from crispy_forms.helper import FormHelper
from crispy_forms.layout import Button, Div, Layout, Submit from crispy_forms.layout import Button, Div, Layout, Submit
from django import forms from django import forms
@@ -7,8 +5,6 @@ from django.utils.translation import gettext_lazy as _
from speed_profiles.models import SpeedProfile from speed_profiles.models import SpeedProfile
MIN_LIMIT = Decimal('0.001')
class SpeedProfileForm(forms.ModelForm): class SpeedProfileForm(forms.ModelForm):
class Meta: class Meta:
@@ -22,16 +18,16 @@ class SpeedProfileForm(forms.ModelForm):
'upload_burst': _('Upload burst (MB)'), 'upload_burst': _('Upload burst (MB)'),
} }
help_texts = { help_texts = {
'download_limit': _('Traffic that reaches the peer. Leave empty for no download limit.'), 'download_limit': _('Traffic that reaches the peer. 0 disables the download limit.'),
'upload_limit': _('Traffic that the peer sends. Leave empty for no upload limit.'), 'upload_limit': _('Traffic that the peer sends. 0 disables the upload limit.'),
'download_burst': _('Optional. Data that may pass at full speed before the limit applies.'), 'download_burst': _('Data that may pass at full speed before the limit applies. 0 disables the burst.'),
'upload_burst': _('Optional. Data that may pass at full speed before the limit applies.'), 'upload_burst': _('Data that may pass at full speed before the limit applies. 0 disables the burst.'),
} }
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
for field_name in ('download_limit', 'download_burst', 'upload_limit', 'upload_burst'): for field_name in ('download_limit', 'download_burst', 'upload_limit', 'upload_burst'):
self.fields[field_name].widget.attrs.update({'min': str(MIN_LIMIT), 'step': 'any'}) self.fields[field_name].widget.attrs.update({'min': '0', 'step': 'any'})
self.helper = FormHelper() self.helper = FormHelper()
self.helper.form_method = 'post' self.helper.form_method = 'post'
self.helper.layout = Layout( self.helper.layout = Layout(
@@ -57,13 +53,15 @@ class SpeedProfileForm(forms.ModelForm):
cleaned_data = super().clean() cleaned_data = super().clean()
for field_name in ('download_limit', 'download_burst', 'upload_limit', 'upload_burst'): for field_name in ('download_limit', 'download_burst', 'upload_limit', 'upload_burst'):
value = cleaned_data.get(field_name) value = cleaned_data.get(field_name)
if value is not None and value < MIN_LIMIT: if value is not None and value < 0:
self.add_error(field_name, _('Enter a value greater than zero.')) self.add_error(field_name, _('Enter a value greater than or equal to zero.'))
if self.errors:
return cleaned_data
if cleaned_data.get('download_limit') is None and cleaned_data.get('upload_limit') is None: if not cleaned_data.get('download_limit') and not cleaned_data.get('upload_limit'):
raise forms.ValidationError(_('Set at least a download or an upload limit.')) raise forms.ValidationError(_('Set at least a download or an upload limit.'))
if cleaned_data.get('download_burst') and cleaned_data.get('download_limit') is None: if cleaned_data.get('download_burst') and not cleaned_data.get('download_limit'):
self.add_error('download_burst', _('The burst requires a download limit.')) self.add_error('download_burst', _('The burst requires a download limit.'))
if cleaned_data.get('upload_burst') and cleaned_data.get('upload_limit') is None: if cleaned_data.get('upload_burst') and not cleaned_data.get('upload_limit'):
self.add_error('upload_burst', _('The burst requires an upload limit.')) self.add_error('upload_burst', _('The burst requires an upload limit.'))
return cleaned_data return cleaned_data
+5 -4
View File
@@ -1,6 +1,7 @@
# Generated by Django 5.2.19 on 2026-11-24 15:57 # Generated by Django 5.2.19 on 2026-11-24 15:57
import uuid import uuid
from decimal import Decimal
from django.db import migrations, models from django.db import migrations, models
@@ -18,10 +19,10 @@ class Migration(migrations.Migration):
fields=[ fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=64, unique=True)), ('name', models.CharField(max_length=64, unique=True)),
('download_limit', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)), ('download_limit', models.DecimalField(decimal_places=3, default=Decimal('0'), max_digits=9)),
('upload_limit', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)), ('upload_limit', models.DecimalField(decimal_places=3, default=Decimal('0'), max_digits=9)),
('download_burst', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)), ('download_burst', models.DecimalField(decimal_places=3, default=Decimal('0'), max_digits=9)),
('upload_burst', models.DecimalField(blank=True, decimal_places=3, max_digits=9, null=True)), ('upload_burst', models.DecimalField(decimal_places=3, default=Decimal('0'), max_digits=9)),
('created', models.DateTimeField(auto_now_add=True)), ('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)), ('updated', models.DateTimeField(auto_now=True)),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), ('uuid', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
+6 -6
View File
@@ -13,14 +13,14 @@ def megabytes_to_bytes(value):
class SpeedProfile(models.Model): class SpeedProfile(models.Model):
"""Bandwidth limit applied to each peer that uses the profile. Empty limits mean no limit in that direction.""" """Bandwidth limit applied to each peer that uses the profile. Zero disables a limit or a burst."""
name = models.CharField(max_length=64, unique=True) name = models.CharField(max_length=64, unique=True)
# Mbit/s. Download is the traffic that reaches the peer, upload the traffic the peer sends. # Mbit/s. Download is the traffic that reaches the peer, upload the traffic the peer sends.
download_limit = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True) download_limit = models.DecimalField(max_digits=9, decimal_places=3, default=Decimal('0'))
upload_limit = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True) upload_limit = models.DecimalField(max_digits=9, decimal_places=3, default=Decimal('0'))
# MB that may pass at full speed before the limit applies. Empty means the automatic minimum. # MB that may pass at full speed before the limit applies. Zero means the automatic minimum.
download_burst = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True) download_burst = models.DecimalField(max_digits=9, decimal_places=3, default=Decimal('0'))
upload_burst = models.DecimalField(max_digits=9, decimal_places=3, blank=True, null=True) upload_burst = models.DecimalField(max_digits=9, decimal_places=3, default=Decimal('0'))
created = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True) updated = models.DateTimeField(auto_now=True)
+48 -10
View File
@@ -20,7 +20,7 @@ from user_manager.models import UserAcl
from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance from wireguard.models import Peer, PeerAllowedIP, WireGuardInstance
from wireguard_peer.functions import func_create_new_peer from wireguard_peer.functions import func_create_new_peer
from wireguard_tools import functions from wireguard_tools import functions
from wireguard_tools.speed_limits import apply_speed_limits, build_tc_commands, parse_speed_limits from wireguard_tools.speed_limits import apply_speed_limits, build_tc_commands, parse_peers, parse_speed_limits
from wireguard_tools.tests import FakeNetwork, load_cluster_worker from wireguard_tools.tests import FakeNetwork, load_cluster_worker
from wireguard_tools.views import export_wireguard_configuration from wireguard_tools.views import export_wireguard_configuration
@@ -43,22 +43,24 @@ def create_peer(instance, number, speed_profile=None, networks=(), endpoint=''):
class SpeedProfileFormTests(TestCase): class SpeedProfileFormTests(TestCase):
def form(self, **data): def form(self, **data):
return SpeedProfileForm(data={'name': 'Basic', **data}) values = {'download_limit': '0', 'download_burst': '0', 'upload_limit': '0', 'upload_burst': '0'}
return SpeedProfileForm(data={'name': 'Basic', **values, **data})
def test_accepts_optional_and_decimal_limits(self): def test_accepts_decimal_limits_and_zero_disables_a_limit_or_burst(self):
self.assertTrue(self.form(download_limit='0.5').is_valid()) self.assertTrue(self.form(download_limit='0.5').is_valid())
self.assertTrue(self.form(upload_limit='10').is_valid()) self.assertTrue(self.form(upload_limit='10').is_valid())
form = self.form(download_limit='10', download_burst='5', upload_limit='2.5', upload_burst='0.25') form = self.form(download_limit='10', download_burst='5', upload_limit='2.5', upload_burst='0.25')
self.assertTrue(form.is_valid(), form.errors) self.assertTrue(form.is_valid(), form.errors)
profile = self.form(download_limit='10').save()
self.assertEqual(profile.config_comment(), 'download_kbit=10000')
self.assertEqual(profile.summary, '↓ 10 Mbit/s')
def test_refuses_zero_and_negative_values(self): def test_refuses_empty_and_negative_values(self):
for field_name in ('download_limit', 'upload_limit'): for field_name in ('download_limit', 'download_burst', 'upload_limit', 'upload_burst'):
for value in ('0', '-1'): for value in ('', '-1'):
form = self.form(**{field_name: value}) form = self.form(**{'download_limit': '10', 'upload_limit': '5', field_name: value})
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertIn(field_name, form.errors) self.assertIn(field_name, form.errors)
form = self.form(download_limit='10', download_burst='0')
self.assertIn('download_burst', form.errors)
def test_refuses_repeated_name(self): def test_refuses_repeated_name(self):
SpeedProfile.objects.create(name='Basic', download_limit=10) SpeedProfile.objects.create(name='Basic', download_limit=10)
@@ -127,7 +129,8 @@ class SpeedProfileDeleteTests(SpeedProfileViewMixin, TestCase):
class SpeedProfileEditTests(SpeedProfileViewMixin, TestCase): class SpeedProfileEditTests(SpeedProfileViewMixin, TestCase):
def edit(self): def edit(self):
return self.client.post( return self.client.post(
f'/speed_profiles/manage/?uuid={self.profile.uuid}', {'name': 'Basic', 'download_limit': '20', 'upload_limit': '5'} f'/speed_profiles/manage/?uuid={self.profile.uuid}',
{'name': 'Basic', 'download_limit': '20', 'download_burst': '0', 'upload_limit': '5', 'upload_burst': '0'},
) )
@patch('speed_profiles.views._auto_apply', return_value=True) @patch('speed_profiles.views._auto_apply', return_value=True)
@@ -209,6 +212,11 @@ class ExportedConfigMixin:
with open(os.path.join(self.wireguard_dir, f'wg{instance_id}.conf')) as config_file: with open(os.path.join(self.wireguard_dir, f'wg{instance_id}.conf')) as config_file:
return parse_speed_limits(config_file.read()) return parse_speed_limits(config_file.read())
def exported_peers(self, instance_id=0):
export_wireguard_configuration()
with open(os.path.join(self.wireguard_dir, f'wg{instance_id}.conf')) as config_file:
return parse_peers(config_file.read())
class SpeedLimitRuleTests(ExportedConfigMixin, TestCase): class SpeedLimitRuleTests(ExportedConfigMixin, TestCase):
def setUp(self): def setUp(self):
@@ -262,6 +270,36 @@ class SpeedLimitRuleTests(ExportedConfigMixin, TestCase):
self.assertNotIn('burst', download_classes[1]) self.assertNotIn('burst', download_classes[1])
self.assertNotIn('burst', upload_classes[1]) self.assertNotIn('burst', upload_classes[1])
def test_peers_inside_the_network_of_a_limited_peer_are_not_limited_with_it(self):
create_peer(self.instance, 10, SpeedProfile.objects.create(name='Full', download_limit=10, upload_limit=5),
networks=['0.0.0.0/0'], endpoint='remote.example.test:51820')
create_peer(self.instance, 11)
create_peer(self.instance, 12, SpeedProfile.objects.create(name='Down', download_limit=20))
commands = build_tc_commands('wg0', self.exported_peers())
download_pass = [command for command in commands if command.endswith('flowid 1:')]
upload_pass = [command for command in commands if command.endswith('action ok')]
# Peer 11 has no limit in both directions; peer 12 has its own download class and no upload limit
self.assertEqual([command.split('ip dst ')[1].split()[0] for command in download_pass], ['10.188.0.11/32'])
self.assertEqual(
sorted(command.split('ip src ')[1].split()[0] for command in upload_pass),
['10.188.0.11/32', '10.188.0.12/32'],
)
# The pass filters are checked before the filters of the broader network
broad_priority = int(next(
command for command in commands if 'match ip dst 0.0.0.0/0' in command
).split(' prio ')[1].split()[0])
self.assertTrue(all(int(command.split(' prio ')[1].split()[0]) < broad_priority for command in download_pass))
self.assertEqual(len([command for command in commands if command.startswith('class add dev wg0 ')]), 2)
def test_peers_outside_the_networks_of_limited_peers_get_no_extra_filters(self):
create_peer(self.instance, 10, SpeedProfile.objects.create(name='Basic', download_limit=10, upload_limit=5),
networks=['192.168.50.0/24'])
create_peer(self.instance, 11, networks=['192.168.60.0/24'])
commands = build_tc_commands('wg0', self.exported_peers())
self.assertEqual(commands, build_tc_commands('wg0', self.exported_limits()))
self.assertTrue(all('10.188.0.11' not in command and '192.168.60.0' not in command for command in commands))
def test_peer_with_endpoint_gets_the_same_rules(self): def test_peer_with_endpoint_gets_the_same_rules(self):
profile = SpeedProfile.objects.create(name='Basic', download_limit=10, upload_limit=5) profile = SpeedProfile.objects.create(name='Basic', download_limit=10, upload_limit=5)
create_peer(self.instance, 10, profile, networks=['192.168.70.0/24'], endpoint='remote.example.test:51820') create_peer(self.instance, 10, profile, networks=['192.168.70.0/24'], endpoint='remote.example.test:51820')
+8 -9
View File
@@ -56,19 +56,18 @@ def view_manage_speed_profile(request):
form_description = { form_description = {
'size': 'col-lg-6', 'size': 'col-lg-6',
'content': _(''' 'content': _('''
<h5>Speed profile</h5>
<p>Each peer that uses this profile gets its own limit: a profile of 10 Mbit/s does not share 10 Mbit/s among
its peers. Peers without a profile have no limit.</p>
<h5>Download and upload</h5> <h5>Download and upload</h5>
<p><strong>Download</strong> is the traffic that reaches the peer and <strong>upload</strong> the traffic that <p><strong>Download</strong> is the traffic that reaches the peer and <strong>upload</strong> the traffic that
it sends. Each limit is optional, so a profile may limit only one direction. The limit covers all the it sends. The limit covers all the addresses and networks of the peer. Use 0 to leave a direction without
addresses and networks of the peer.</p> limit. Peers without a profile have no limit.</p>
<h5>Burst</h5> <h5>Burst</h5>
<p>The amount of data that may pass at full speed before the limit applies, refilled while the peer uses less <p>The amount of data that may pass at full speed before the limit applies. It refills while the peer uses
than its limit. A burst of a few MB keeps browsing fast without allowing large downloads at full speed. For less than its limit.</p>
reference, 10 Mbit/s is about 1.25 MB per second. Leave it empty for the automatic minimum.</p> <p>Web pages and most apps transfer a few MB at a time, so, depending on the case, a burst of 5 or 10 MB may
improve browsing considerably: pages load at full speed, while long downloads and streams still run at the
configured limit. For reference, 10 Mbit/s is about 1.25 MB per second.</p>
<p>Use 0 to disable the burst.</p>
'''), '''),
} }
return render(request, 'generic_form.html', { return render(request, 'generic_form.html', {
+56 -16
View File
@@ -28,8 +28,12 @@ def ifb_name(interface):
return f'ifb{interface}'[:15] return f'ifb{interface}'[:15]
def parse_speed_limits(config_content): def parse_peers(config_content):
"""Return a list of {'networks': [...], 'download_kbit': int, ...} for each limited peer of the configuration.""" """Return a list of {'networks': [...], 'download_kbit': int, ...} for each peer of the configuration.
Peers without limits are included (with no limit keys): their networks may be inside the networks of a limited
peer and must not be shaped with it.
"""
peers = [] peers = []
current = None current = None
for raw_line in config_content.splitlines(): for raw_line in config_content.splitlines():
@@ -57,13 +61,14 @@ def parse_speed_limits(config_content):
if current is not None: if current is not None:
peers.append(current) peers.append(current)
limited_peers = [] return [{'networks': peer['networks'], **peer['limits']} for peer in peers if peer['networks']]
for peer in peers:
limits = peer['limits']
if not peer['networks'] or not (limits.get('download_kbit') or limits.get('upload_kbit')): def parse_speed_limits(config_content):
continue """Return the peers of the configuration that have at least one limit."""
limited_peers.append({'networks': peer['networks'], **limits}) return [
return limited_peers peer for peer in parse_peers(config_content) if peer.get('download_kbit') or peer.get('upload_kbit')
]
def _filter_priority(network): def _filter_priority(network):
@@ -90,17 +95,52 @@ def _htb_commands(device, peers, direction, match):
return commands return commands
def build_tc_commands(interface, limited_peers, upload=True): def _unlimited_networks(peers, limited_peers):
"""tc batch commands that install the limits on a clean interface (and on a clean ifb for the upload).""" """Networks of the other peers that are inside a network of a limited peer.
WireGuard sends their traffic to the peer with the most specific network, but a tc filter of the broader network
would also match it. These networks get their own filter, checked first, that lets the traffic pass.
"""
limited_networks = [network for peer in limited_peers for network in peer['networks']]
networks = []
for peer in peers:
if any(peer is limited_peer for limited_peer in limited_peers):
continue
for network in peer['networks']:
if any(
network != limited_network and network.subnet_of(limited_network)
for limited_network in limited_networks
):
networks.append(network)
return networks
def build_tc_commands(interface, peers, upload=True):
"""tc batch commands that install the limits on a clean interface (and on a clean ifb for the upload).
peers may include the peers without limits, so their traffic is not shaped with a limited peer whose networks
contain theirs.
"""
commands = [] commands = []
download_peers = [peer for peer in limited_peers if peer.get('download_kbit')] download_peers = [peer for peer in peers if peer.get('download_kbit')]
upload_peers = [peer for peer in limited_peers if peer.get('upload_kbit')] if upload else [] upload_peers = [peer for peer in peers if peer.get('upload_kbit')] if upload else []
if download_peers: if download_peers:
commands += _htb_commands(interface, download_peers, 'download', 'dst') commands += _htb_commands(interface, download_peers, 'download', 'dst')
for network in _unlimited_networks(peers, download_peers):
# flowid 1: is the htb itself: the packet is sent without a class, like unclassified traffic
commands.append(
f'filter add dev {interface} parent 1: protocol ip prio {_filter_priority(network)} '
f'u32 match ip dst {network} flowid 1:'
)
if upload_peers: if upload_peers:
ifb = ifb_name(interface) ifb = ifb_name(interface)
commands.append(f'qdisc add dev {interface} handle ffff: ingress') commands.append(f'qdisc add dev {interface} handle ffff: ingress')
for network in _unlimited_networks(peers, upload_peers):
commands.append(
f'filter add dev {interface} parent ffff: protocol ip prio {_filter_priority(network)} '
f'u32 match ip src {network} action ok'
)
# Only the traffic of limited peers goes through the ifb; the rest is not touched # Only the traffic of limited peers goes through the ifb; the rest is not touched
for peer in upload_peers: for peer in upload_peers:
for network in peer['networks']: for network in peer['networks']:
@@ -139,7 +179,7 @@ def apply_speed_limits(interface, config_path, run=None):
run = run or subprocess.run run = run or subprocess.run
try: try:
with open(config_path) as config_file: with open(config_path) as config_file:
limited_peers = parse_speed_limits(config_file.read()) peers = parse_peers(config_file.read())
except OSError as error: except OSError as error:
return [f'{config_path}: {error}'] return [f'{config_path}: {error}']
@@ -147,7 +187,7 @@ def apply_speed_limits(interface, config_path, run=None):
for parent in ('root', 'ingress'): for parent in ('root', 'ingress'):
run(['tc', 'qdisc', 'del', 'dev', interface, parent], capture_output=True, text=True) run(['tc', 'qdisc', 'del', 'dev', interface, parent], capture_output=True, text=True)
upload = any(peer.get('upload_kbit') for peer in limited_peers) upload = any(peer.get('upload_kbit') for peer in peers)
if upload: if upload:
ifb_error = _prepare_ifb(interface, run) ifb_error = _prepare_ifb(interface, run)
if ifb_error: if ifb_error:
@@ -157,7 +197,7 @@ def apply_speed_limits(interface, config_path, run=None):
else: else:
run(['ip', 'link', 'delete', ifb_name(interface)], capture_output=True, text=True) run(['ip', 'link', 'delete', ifb_name(interface)], capture_output=True, text=True)
commands = build_tc_commands(interface, limited_peers, upload=upload) commands = build_tc_commands(interface, peers, upload=upload)
if not commands: if not commands:
return errors return errors
result = run(['tc', '-batch', '-'], input='\n'.join(commands) + '\n', capture_output=True, text=True) result = run(['tc', '-batch', '-'], input='\n'.join(commands) + '\n', capture_output=True, text=True)