classify.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2023 The frp 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 nathole
  15. import (
  16. "fmt"
  17. "net"
  18. )
  19. const (
  20. EasyNAT = "EasyNAT"
  21. HardNAT = "HardNAT"
  22. BehaviorNoChange = "BehaviorNoChange"
  23. BehaviorIPChanged = "BehaviorIPChanged"
  24. BehaviorPortChanged = "BehaviorPortChanged"
  25. BehaviorBothChanged = "BehaviorBothChanged"
  26. )
  27. // ClassifyNATType classify NAT type by given addresses.
  28. func ClassifyNATType(addresses []string) (string, string, error) {
  29. if len(addresses) <= 1 {
  30. return "", "", fmt.Errorf("not enough addresses")
  31. }
  32. ipChanged := false
  33. portChanged := false
  34. var baseIP, basePort string
  35. for _, addr := range addresses {
  36. ip, port, err := net.SplitHostPort(addr)
  37. if err != nil {
  38. return "", "", err
  39. }
  40. if baseIP == "" {
  41. baseIP = ip
  42. basePort = port
  43. continue
  44. }
  45. if baseIP != ip {
  46. ipChanged = true
  47. }
  48. if basePort != port {
  49. portChanged = true
  50. }
  51. if ipChanged && portChanged {
  52. break
  53. }
  54. }
  55. switch {
  56. case ipChanged && portChanged:
  57. return HardNAT, BehaviorBothChanged, nil
  58. case ipChanged:
  59. return HardNAT, BehaviorIPChanged, nil
  60. case portChanged:
  61. return HardNAT, BehaviorPortChanged, nil
  62. default:
  63. return EasyNAT, BehaviorNoChange, nil
  64. }
  65. }