+my $format_rules = sub {
+ my ($rules, $need_iface) = @_;
+
+ my $raw = '';
+
+ foreach my $rule (@$rules) {
+ if ($rule->{type} eq 'in' || $rule->{type} eq 'out' || $rule->{type} eq 'group') {
+ $raw .= '|' if defined($rule->{enable}) && !$rule->{enable};
+ $raw .= uc($rule->{type});
+ if ($rule->{macro}) {
+ $raw .= " $rule->{macro}($rule->{action})";
+ } else {
+ $raw .= " " . $rule->{action};
+ }
+ $raw .= " " . ($rule->{iface} || '-') if $need_iface;
+
+ if ($rule->{type} ne 'group') {
+ $raw .= " " . ($rule->{source} || '-');
+ $raw .= " " . ($rule->{dest} || '-');
+ $raw .= " " . ($rule->{proto} || '-');
+ $raw .= " " . ($rule->{dport} || '-');
+ $raw .= " " . ($rule->{sport} || '-');
+ }
+
+ $raw .= " # " . encode('utf8', $rule->{comment})
+ if $rule->{comment} && $rule->{comment} !~ m/^\s*$/;
+ $raw .= "\n";
+ } else {
+ die "unknown rule type '$rule->{type}'";
+ }
+ }
+
+ return $raw;
+};
+
+my $format_options = sub {
+ my ($options) = @_;
+
+ my $raw = '';
+
+ $raw .= "[OPTIONS]\n\n";
+ foreach my $opt (keys %$options) {
+ $raw .= "$opt: $options->{$opt}\n";
+ }
+ $raw .= "\n";
+
+ return $raw;
+};
+
+my $format_aliases = sub {
+ my ($aliases) = @_;
+
+ my $raw = '';
+
+ $raw .= "[ALIASES]\n\n";
+ foreach my $k (keys %$aliases) {
+ my $e = $aliases->{$k};
+ $raw .= "$e->{name} $e->{cidr}";
+ $raw .= " # " . encode('utf8', $e->{comment})
+ if $e->{comment} && $e->{comment} !~ m/^\s*$/;
+ $raw .= "\n";
+ }
+ $raw .= "\n";
+
+ return $raw;
+};
+
+my $format_ipset = sub {
+ my ($options) = @_;
+
+ my $raw = '';
+
+ my $nethash = {};
+ foreach my $entry (@$options) {
+ $nethash->{$entry->{cidr}} = $entry;
+ }
+
+ foreach my $cidr (sort keys %$nethash) {
+ my $entry = $nethash->{$cidr};
+ my $line = $entry->{nomatch} ? '!' : '';
+ $line .= $entry->{cidr};
+ $line .= " # " . encode('utf8', $entry->{comment})
+ if $entry->{comment} && $entry->{comment} !~ m/^\s*$/;
+ $raw .= "$line\n";
+ }
+
+ return $raw;
+};
+
+sub save_vmfw_conf {
+ my ($vmid, $vmfw_conf) = @_;
+
+ my $raw = '';
+
+ my $options = $vmfw_conf->{options};
+ $raw .= &$format_options($options) if scalar(keys %$options);
+
+ my $rules = $vmfw_conf->{rules} || [];
+ if (scalar(@$rules)) {
+ $raw .= "[RULES]\n\n";
+ $raw .= &$format_rules($rules, 1);
+ $raw .= "\n";
+ }
+
+ my $filename = "/etc/pve/firewall/$vmid.fw";
+ PVE::Tools::file_set_contents($filename, $raw);
+}
+