iptables.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. // Copyright 2015 CoreOS, Inc.
  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 ip
  15. import (
  16. "bytes"
  17. "fmt"
  18. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  19. "os/exec"
  20. "regexp"
  21. "strconv"
  22. "strings"
  23. "syscall"
  24. )
  25. type IPTables struct {
  26. path string
  27. }
  28. func NewIPTables() (*IPTables, error) {
  29. path, err := exec.LookPath("iptables")
  30. if err != nil {
  31. return nil, err
  32. }
  33. return &IPTables{path}, nil
  34. }
  35. func (ipt *IPTables) Exists(table string, args ...string) (bool, error) {
  36. checkPresent, err := getIptablesHasCheckCommand()
  37. if err != nil {
  38. log.Warningf("Error checking iptables version, assuming version at least 1.4.11: %v\n", err)
  39. checkPresent = true
  40. }
  41. if !checkPresent {
  42. cmd := append([]string{"-A"}, args...)
  43. return existsForOldIpTables(table, strings.Join(cmd, " "))
  44. } else {
  45. cmd := append([]string{"-t", table, "-C"}, args...)
  46. err = exec.Command(ipt.path, cmd...).Run()
  47. }
  48. switch {
  49. case err == nil:
  50. return true, nil
  51. case err.(*exec.ExitError).Sys().(syscall.WaitStatus).ExitStatus() == 1:
  52. return false, nil
  53. default:
  54. return false, err
  55. }
  56. }
  57. func (ipt *IPTables) Append(table string, args ...string) error {
  58. cmd := append([]string{"-t", table, "-A"}, args...)
  59. return exec.Command(ipt.path, cmd...).Run()
  60. }
  61. // AppendUnique acts like Append except that it won't add a duplicate
  62. func (ipt *IPTables) AppendUnique(table string, args ...string) error {
  63. exists, err := ipt.Exists(table, args...)
  64. if err != nil {
  65. return err
  66. }
  67. if !exists {
  68. return ipt.Append(table, args...)
  69. }
  70. return nil
  71. }
  72. func (ipt *IPTables) ClearChain(table, chain string) error {
  73. cmd := append([]string{"-t", table, "-N", chain})
  74. err := exec.Command(ipt.path, cmd...).Run()
  75. switch {
  76. case err == nil:
  77. return nil
  78. case err.(*exec.ExitError).Sys().(syscall.WaitStatus).ExitStatus() == 1:
  79. // chain already exists. Flush (clear) it.
  80. cmd := append([]string{"-t", table, "-F", chain})
  81. return exec.Command(ipt.path, cmd...).Run()
  82. default:
  83. return err
  84. }
  85. }
  86. // Checks if iptables has the "-C" flag
  87. func getIptablesHasCheckCommand() (bool, error) {
  88. vstring, err := getIptablesVersionString()
  89. if err != nil {
  90. return false, err
  91. }
  92. v1, v2, v3, err := extractIptablesVersion(vstring)
  93. if err != nil {
  94. return false, err
  95. }
  96. return iptablesHasCheckCommand(v1, v2, v3), nil
  97. }
  98. // getIptablesVersion returns the first three components of the iptables version.
  99. // e.g. "iptables v1.3.66" would return (1, 3, 66, nil)
  100. func extractIptablesVersion(str string) (int, int, int, error) {
  101. versionMatcher := regexp.MustCompile("v([0-9]+)\\.([0-9]+)\\.([0-9]+)")
  102. result := versionMatcher.FindStringSubmatch(str)
  103. if result == nil {
  104. return 0, 0, 0, fmt.Errorf("no iptables version found in string: %s", str)
  105. }
  106. v1, err := strconv.Atoi(result[1])
  107. if err != nil {
  108. return 0, 0, 0, err
  109. }
  110. v2, err := strconv.Atoi(result[2])
  111. if err != nil {
  112. return 0, 0, 0, err
  113. }
  114. v3, err := strconv.Atoi(result[3])
  115. if err != nil {
  116. return 0, 0, 0, err
  117. }
  118. return v1, v2, v3, nil
  119. }
  120. // Runs "iptables --version" to get the version string
  121. func getIptablesVersionString() (string, error) {
  122. cmd := exec.Command("iptables", "--version")
  123. var out bytes.Buffer
  124. cmd.Stdout = &out
  125. err := cmd.Run()
  126. if err != nil {
  127. return "", err
  128. }
  129. return out.String(), nil
  130. }
  131. // Checks if an iptables version is after 1.4.11, when --check was added
  132. func iptablesHasCheckCommand(v1 int, v2 int, v3 int) bool {
  133. if v1 > 1 {
  134. return true
  135. }
  136. if v1 == 1 && v2 > 4 {
  137. return true
  138. }
  139. if v1 == 1 && v2 == 4 && v3 >= 11 {
  140. return true
  141. }
  142. return false
  143. }
  144. // Checks if a rule specification exists for a table
  145. func existsForOldIpTables(table string, ruleSpec string) (bool, error) {
  146. cmd := exec.Command("iptables", "-t", table, "-S")
  147. var out bytes.Buffer
  148. cmd.Stdout = &out
  149. err := cmd.Run()
  150. if err != nil {
  151. return false, err
  152. }
  153. rules := out.String()
  154. return strings.Contains(rules, ruleSpec), nil
  155. }