| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package knftables |
| 18 |
|
| 19 |
import ( |
| 20 |
"errors" |
| 21 |
"fmt" |
| 22 |
"os/exec" |
| 23 |
"strings" |
| 24 |
"syscall" |
| 25 |
) |
| 26 |
|
| 27 |
type nftablesError struct { |
| 28 |
wrapped error |
| 29 |
msg string |
| 30 |
errno syscall.Errno |
| 31 |
} |
| 32 |
|
| 33 |
|
| 34 |
func wrapError(err error) error { |
| 35 |
nerr := &nftablesError{wrapped: err, msg: err.Error()} |
| 36 |
ee := &exec.ExitError{} |
| 37 |
if errors.As(err, &ee) { |
| 38 |
if len(ee.Stderr) > 0 { |
| 39 |
nerr.msg = string(ee.Stderr) |
| 40 |
eol := strings.Index(nerr.msg, "\n") |
| 41 |
|
| 42 |
|
| 43 |
enoent := strings.Index(nerr.msg, "No such file or directory") |
| 44 |
eexist := strings.Index(nerr.msg, "File exists") |
| 45 |
if enoent != -1 && (enoent < eol || eol == -1) { |
| 46 |
nerr.errno = syscall.ENOENT |
| 47 |
} else if eexist != -1 && (eexist < eol || eol == -1) { |
| 48 |
nerr.errno = syscall.EEXIST |
| 49 |
} |
| 50 |
} |
| 51 |
} |
| 52 |
return nerr |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
func notFoundError(format string, args ...interface{}) error { |
| 58 |
return &nftablesError{msg: fmt.Sprintf(format, args...), errno: syscall.ENOENT} |
| 59 |
} |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
func existsError(format string, args ...interface{}) error { |
| 64 |
return &nftablesError{msg: fmt.Sprintf(format, args...), errno: syscall.EEXIST} |
| 65 |
} |
| 66 |
|
| 67 |
func (nerr *nftablesError) Error() string { |
| 68 |
return nerr.msg |
| 69 |
} |
| 70 |
|
| 71 |
func (nerr *nftablesError) Unwrap() error { |
| 72 |
return nerr.wrapped |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
func IsNotFound(err error) bool { |
| 79 |
var nerr *nftablesError |
| 80 |
if errors.As(err, &nerr) { |
| 81 |
return nerr.errno == syscall.ENOENT |
| 82 |
} |
| 83 |
return false |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
func IsAlreadyExists(err error) bool { |
| 89 |
var nerr *nftablesError |
| 90 |
if errors.As(err, &nerr) { |
| 91 |
return nerr.errno == syscall.EEXIST |
| 92 |
} |
| 93 |
return false |
| 94 |
} |