{
    my $pf_chain = "PortForwarding_\$\$";
    $OUT .= "# Create a new PortForwarding chain\n";
    $OUT .= "PFC=\$(/sbin/iptables --table nat ";
    $OUT .= "--numeric --list PortForwarding |\\\n";
    $OUT .= "   sed -n '3s/ .*//p')\n";
    $OUT .= "    /sbin/iptables --table nat --new-chain $pf_chain\n";

    foreach my $protocol (qw(tcp udp))
    {
        my $uproto = uc $protocol;
        my $propname = $uproto . "Forwards";
        my %forwards = split(/,/, $masq{$propname} || '');
        foreach my $port (keys %forwards)
        {
            my ($ip, $dport) = split(/:/, $forwards{$port});
            $port =~ s/-/:/;

	    # Map canonical localhost back to our current external IP	
            $ip = $ExternalInterface{IPAddress} if ($ip eq 'localhost');

            $OUT .= "    /sbin/iptables --table nat --append $pf_chain " .
                "--protocol $protocol \\\n".
            # Set up local port to forward
            "         --destination-port ${port} -j DNAT " .
            # Set up the remote port to forward to
                "--to-destination $ip";
            # Append the dport if any. 
            $OUT .= ":$dport" if $dport;
            $OUT .= "\n";
            # And accept the incoming packets. Use the dport if there is one.
            ($port = $dport) =~ s/-/:/ if $dport;

            # If this rule is forwarding to localhost, ExternalIP or LocalIP,
            # then we must allow it on the INPUT chain instead of the FORWARD
            # chain.
            $OUT .= "    adjust_${protocol}_in $port ACCEPT " .
			(($ip eq $ExternalInterface{IPAddress}) ?
			    "Inbound${uproto}_\$\$\n" :
			    "Forwarded${uproto}_\$\$ $ip/32\n");
        }
    }

    # having created a new PortForwarding chain, activate it and destroy
    # the old.
    $OUT .= "    /sbin/iptables --table nat --replace PortForwarding 1 " .
                "--destination \$OUTERNET --jump $pf_chain\n";
    $OUT .= "    /sbin/iptables --table nat --flush \$PFC\n";
    $OUT .= "    /sbin/iptables --table nat --delete-chain \$PFC\n";
}
