ipmatch.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2019 Yunion
  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 rbacutils
  15. import (
  16. "strings"
  17. "yunion.io/x/pkg/util/netutils"
  18. )
  19. const (
  20. IP_PREFIX_SEP = ","
  21. )
  22. func getPrefixes(prefstr string) []netutils.IPV4Prefix {
  23. if len(prefstr) == 0 {
  24. return nil
  25. }
  26. prefs := strings.Split(prefstr, IP_PREFIX_SEP)
  27. ret := make([]netutils.IPV4Prefix, 0)
  28. for _, pref := range prefs {
  29. p, err := netutils.NewIPV4Prefix(pref)
  30. if err != nil {
  31. continue
  32. }
  33. ret = append(ret, p)
  34. }
  35. return ret
  36. }
  37. func MatchIPStrings(prefstr string, ipstr string) bool {
  38. prefs := getPrefixes(prefstr)
  39. return matchIP(prefs, ipstr)
  40. }
  41. func matchIP(prefs []netutils.IPV4Prefix, ipstr string) bool {
  42. if len(prefs) == 0 {
  43. return true
  44. }
  45. ip, err := netutils.NewIPV4Addr(ipstr)
  46. if err != nil {
  47. return false
  48. }
  49. for _, pref := range prefs {
  50. if pref.Contains(ip) {
  51. return true
  52. }
  53. }
  54. return false
  55. }