unacceptAddressOnTCPPort method
Future<bool>
unacceptAddressOnTCPPort(
- String address,
- int? port, {
- bool sudo = false,
- required Set<
int> ? allowedPorts, - required bool allowAllPorts,
override
Reverses the acceptance ("unaccept") of an address on a specified TCP port.
This method is used to revoke a previously accepted address on a given
TCP port. Optionally, it can be executed with elevated privileges using sudo.
address: The IP address or hostname to unaccept.port: The TCP port from which the address will be unaccepted. Ifnullwill remove from all ports.sudo: Indicates whether the operation should be executed with sudo privileges. Defaults tofalse.allowedPorts: A set of ports that are allowed for this operation. Ifnull, no port restrictions apply.allowAllPorts: A flag to overrideallowedPortsand allow all ports to be unaccepted.
Returns:
- A
Future<bool>indicating whether the operation was successful.
Implementation
@override
Future<bool> unacceptAddressOnTCPPort(String address, int? port,
{bool sudo = false,
required Set<int>? allowedPorts,
required bool allowAllPorts}) async {
address = _checkAddress(address);
final iptablesBin = await resolveBinaryPathCached('iptables');
final iptablesArgs = <String>['-L', 'INPUT', '-n', '-v', '--line-numbers'];
var output = await runCommand(
iptablesBin,
iptablesArgs,
sudo: sudo,
expectedExitCode: 0,
);
if (output == null || output.isEmpty) return false;
final regExpAddress =
RegExp(r'ACCEPT\s+(?:tcp|6|4)\s+--\s+\*\s+\*\s+(\S+)');
final regExpPort = RegExp(r'dpt:(\d\d+)');
var anyCmdOK = false;
for (final line in output.split('\n')) {
if (line.contains('ACCEPT')) {
final matchAddress = regExpAddress.firstMatch(line);
final matchPort = regExpPort.firstMatch(line);
if (matchAddress != null && matchPort != null) {
var a = matchAddress.group(1)!;
var g1 = matchPort.group(1)!;
var p = int.tryParse(g1.trim());
if (a == address && p != null && (port == null || p == port)) {
var lineN = line.trim().split(RegExp(r'\s+'))[0];
var n = int.tryParse(lineN);
if (n != null && n > 0) {
final iptablesDelArgs = <String>['-D', 'INPUT', '$n'];
var output = await runCommand(
iptablesBin,
iptablesDelArgs,
sudo: sudo,
expectedExitCode: 0,
);
var cmdOk = output != null;
if (cmdOk) {
anyCmdOK = true;
}
}
}
}
}
}
if (!anyCmdOK) return false;
bool accepted;
if (port != null) {
accepted = await isAcceptedAddressOnPort(address, port,
sudo: sudo,
allowedPorts: allowAllPorts ? null : (allowedPorts ?? {}));
} else {
accepted = await isAcceptedAddress(address,
sudo: sudo,
allowedPorts: allowAllPorts ? null : (allowedPorts ?? {}));
}
return !accepted;
}