# frozen_string_literal: true module Puffy module Formatters # :nodoc: module Base # :nodoc: # Returns the loopback IPv4 IPAddr # # @return [IPAddr] def self.loopback_ipv4 IPAddr.new('127.0.0.1') end # Returns the loopback IPv6 IPAddr # # @return [IPAddr] def self.loopback_ipv6 IPAddr.new('::1') end # Returns a list of loopback addresses # # @return [Array] def self.loopback_addresses [nil, loopback_ipv4, loopback_ipv6] end # Base class for Puffy Formatter Rulesets class Ruleset def initialize @rule_formatter = Class.const_get(self.class.name.sub(/set$/, '')).new end def emit_header ["# Generated by puffy v#{Puffy::VERSION} on #{Time.now.strftime('%c')}"] end # Returns a String representation of the provided +rules+ Array of Puffy::Rule with the +policy+ policy. # # @param rules [Array] array of Puffy::Rule. # @param _policy [Symbol] ruleset policy. # @return [String] def emit_ruleset(rules, _policy = nil) rules.collect { |rule| @rule_formatter.emit_rule(rule) }.join("\n") end # Filename for a firewall configuration fragment emitted by the formatter. # # @return [Array] def filename_fragment raise 'Formatters#filename_fragment MUST be overriden' end end # Base class for Puffy Formatter Rulesets class Rule protected # Returns the loopback IPAddr of the given +address_family+ # # @param address_family [Symbol] the address family, +:inet+ or +:inet6+ # @return [IPAddr,nil] def loopback_address(address_family) case address_family when nil then nil when :inet then Puffy::Formatters::Base.loopback_ipv4 when :inet6 then Puffy::Formatters::Base.loopback_ipv6 else raise "Unsupported address family #{address_family.inspect}" end end # Return a string representation of the +host+ IPAddr as a host or network. # @param host [IPAddr] # @return [String] IP address def emit_address(host) if (host.ipv4? && host.prefix.to_i == 32) || (host.ipv6? && host.prefix.to_i == 128) host.to_s else "#{host}/#{host.prefix}" end end # Return a string representation of the +port+ port. # #param port [Integer,Range] # @return [String] Port def emit_port(port) case port when Integer then port.to_s when Range then "#{port.begin}:#{port.end}" else raise "Unexpected #{port.class.name}" end end end end end end