Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 12 additions & 14 deletions src/nftables.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
# Class to interact with nftables
# Not linked to libnftables, but calls out to the `nft` binary
class Nftables
def run_cmd(cmd : String) : Nil
def self.run_cmd(cmd : String) : Nil
status = Process.run("nft", {cmd}, output: Process::Redirect::Inherit, error: Process::Redirect::Inherit)
status.success? || raise Error.new("nftables command '#{cmd}' failed")
end

def run_file(file : String) : Nil
def self.run_file(file : String) : Nil
status = Process.run("nft", {"-f", file}, output: Process::Redirect::Inherit, error: Process::Redirect::Inherit)
status.success? || raise Error.new("nftables file '#{file}' failed")
end
Expand All @@ -18,28 +18,26 @@
# Class to interact with nftables
# All output is printed to stdout/stderr
class Nftables
def initialize
@nft = LibNftables.nft_ctx_new(LibNftables::NFT_CTX_DEFAULT)
end

def finalize
LibNftables.nft_ctx_free(@nft)
end

# Execute a nft command, eg. 'list ruleset'
def run_cmd(cmd : String) : Nil
def self.run_cmd(cmd : String) : Nil
nft = LibNftables.nft_ctx_new(LibNftables::NFT_CTX_DEFAULT)
buf = Bytes.new(cmd.bytesize + 1) # null terminated string
buf.copy_from(cmd.to_slice)
LibNftables.nft_run_cmd_from_buffer(@nft, buf).zero? ||
LibNftables.nft_run_cmd_from_buffer(nft, buf).zero? ||
raise Error.new("nftables command '#{cmd}' failed")
ensure
LibNftables.nft_ctx_free(nft) if nft
end

# Execute a nft script in a file
def run_file(file : String) : Nil
def self.run_file(file : String) : Nil
nft = LibNftables.nft_ctx_new(LibNftables::NFT_CTX_DEFAULT)
buf = Bytes.new(file.bytesize + 1) # null terminated string
buf.copy_from(file.to_slice)
LibNftables.nft_run_cmd_from_filename(@nft, buf).zero? ||
LibNftables.nft_run_cmd_from_filename(nft, buf).zero? ||
raise Error.new("nftables file '#{file}' failed")
ensure
LibNftables.nft_ctx_free(nft) if nft
end

class Error < Exception; end
Expand Down
5 changes: 2 additions & 3 deletions src/server-cli.cr
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ begin
puts "HMAC keys: #{c.hmac_keys.size}"
if c.nftables_cmd.bytesize > 0
puts "nftables command: #{c.nftables_cmd}"
nft = Nftables.new
on_accept = ->(ip_str : String) {
nft.run_cmd sprintf(c.nftables_cmd, ip_str)
on_accept = ->(ip_str : String) : Nil {
Nftables.run_cmd sprintf(c.nftables_cmd, ip_str)
}
else
puts "Open command: #{c.open_cmd}"
Expand Down