From 60ce64c1f379851847764bd5fb2c5b41febc95d9 Mon Sep 17 00:00:00 2001 From: Dominik Roth Date: Tue, 21 May 2024 17:17:27 +0200 Subject: [PATCH] Detect and fix port forwarding collisions --- main.py | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/main.py b/main.py index c37d4c2..46bb13e 100644 --- a/main.py +++ b/main.py @@ -71,7 +71,7 @@ def readMyIP(): s.connect(("8.8.8.8", 80)) return s.getsockname()[0] -def addPortMapping(fc, extPort, intPort, name=None, protocol='TCP', active=True): +def upsertPortMapping(fc, extPort, intPort, name=None, protocol='TCP', active=True): mapping = { 'NewRemoteHost': '0.0.0.0', 'NewExternalPort': extPort, @@ -87,9 +87,6 @@ def addPortMapping(fc, extPort, intPort, name=None, protocol='TCP', active=True) return fc.call_action("WANPPPConnection1", "AddPortMapping", **mapping ) -def deletePortMapping(fc, extPort, intPort, protocol='TCP', name=None): - addPortMapping(fc, extPort, intPort, name=name, protocol=protocol, active=False) - def load_config(): with open('config.yaml', 'r') as f: conf = yaml.safe_load(f) @@ -166,19 +163,19 @@ def read_paths(conf, fc): ms = readPortmappings(fc) path_indices = {} for route in conf['routes']: + found_map = False for path in route['paths']: # Lets see if we have such a path active fstFwd = path['forwards'][0] - found_map = False for m in ms: if m['NewEnabled'] and m['NewInternalClient'] == path['ip'] and m['NewPortMappingDescription'] == fstFwd['name'] and m['NewExternalPort'] == fstFwd['external'] and m['NewInternalPort'] == fstFwd['internal'] and m['NewProtocol'] == fstFwd['protocol'].upper(): # This path is (at least partially) active - path_indices[route['name']] = path['name'] - found_map = True - break - if found_map: - break - else: + if found_map: # Collision!!! + path_indices[route['name']] = 'COLLISION' + else: + path_indices[route['name']] = path['name'] + found_map = True + if not found_map: # All paths are down path_indices[route['name']] = None alert('We found no active path for route {route["name"]}.') @@ -203,7 +200,7 @@ def flush_paths(conf, fc, active_paths): def flush_forwards(path, make_active, fc): for forward in path['forwards']: - addPortMapping(fc, forward['external'], forward['internal'], name=forward['name'], protocol=forward['protocol'], active=make_active) + upsertPortMapping(fc, forward['external'], forward['internal'], name=forward['name'], protocol=forward['protocol'], active=make_active) def check_avail(path): ip = path['ip']