fake.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright 2019 the Kilo authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package iptables
  15. import (
  16. "fmt"
  17. "strings"
  18. "github.com/coreos/go-iptables/iptables"
  19. )
  20. type statusExiter interface {
  21. ExitStatus() int
  22. }
  23. var _ statusExiter = (*iptables.Error)(nil)
  24. var _ statusExiter = statusError(0)
  25. type statusError int
  26. func (s statusError) Error() string {
  27. return fmt.Sprintf("%d", s)
  28. }
  29. func (s statusError) ExitStatus() int {
  30. return int(s)
  31. }
  32. type fakeClient map[string]Rule
  33. var _ iptablesClient = fakeClient(nil)
  34. func (f fakeClient) AppendUnique(table, chain string, spec ...string) error {
  35. r := &rule{table, chain, spec, nil}
  36. f[r.String()] = r
  37. return nil
  38. }
  39. func (f fakeClient) Delete(table, chain string, spec ...string) error {
  40. r := &rule{table, chain, spec, nil}
  41. delete(f, r.String())
  42. return nil
  43. }
  44. func (f fakeClient) Exists(table, chain string, spec ...string) (bool, error) {
  45. r := &rule{table, chain, spec, nil}
  46. _, ok := f[r.String()]
  47. return ok, nil
  48. }
  49. func (f fakeClient) ClearChain(table, name string) error {
  50. c := &chain{table, name, nil}
  51. for k := range f {
  52. if strings.HasPrefix(k, c.String()) {
  53. delete(f, k)
  54. }
  55. }
  56. f[c.String()] = c
  57. return nil
  58. }
  59. func (f fakeClient) DeleteChain(table, name string) error {
  60. c := &chain{table, name, nil}
  61. for k := range f {
  62. if strings.HasPrefix(k, c.String()) {
  63. return fmt.Errorf("cannot delete chain %s; rules exist", name)
  64. }
  65. }
  66. delete(f, c.String())
  67. return nil
  68. }
  69. func (f fakeClient) NewChain(table, name string) error {
  70. c := &chain{table, name, nil}
  71. if _, ok := f[c.String()]; ok {
  72. return statusError(1)
  73. }
  74. f[c.String()] = c
  75. return nil
  76. }