nathole.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 sub
  15. import (
  16. "fmt"
  17. "net"
  18. "os"
  19. "strconv"
  20. "github.com/spf13/cobra"
  21. "github.com/fatedier/frp/pkg/config"
  22. "github.com/fatedier/frp/pkg/nathole"
  23. )
  24. func init() {
  25. RegisterCommonFlags(natholeCmd)
  26. rootCmd.AddCommand(natholeCmd)
  27. natholeCmd.AddCommand(natholeDiscoveryCmd)
  28. }
  29. var natholeCmd = &cobra.Command{
  30. Use: "nathole",
  31. Short: "Actions about nathole",
  32. }
  33. var natholeDiscoveryCmd = &cobra.Command{
  34. Use: "discover",
  35. Short: "Discover nathole information by frps and stun server",
  36. RunE: func(cmd *cobra.Command, args []string) error {
  37. cfg, _, _, err := config.ParseClientConfig(cfgFile)
  38. if err != nil {
  39. fmt.Println(err)
  40. os.Exit(1)
  41. }
  42. if err := validateForNatHoleDiscovery(cfg); err != nil {
  43. fmt.Println(err)
  44. os.Exit(1)
  45. }
  46. serverAddr := ""
  47. if cfg.ServerUDPPort != 0 {
  48. serverAddr = net.JoinHostPort(cfg.ServerAddr, strconv.Itoa(cfg.ServerUDPPort))
  49. }
  50. addresses, err := nathole.Discover(
  51. serverAddr,
  52. []string{cfg.NatHoleSTUNServer},
  53. []byte(cfg.Token),
  54. )
  55. if err != nil {
  56. fmt.Println("discover error:", err)
  57. os.Exit(1)
  58. }
  59. if len(addresses) < 2 {
  60. fmt.Printf("discover error: can not get enough addresses, need 2, got: %v\n", addresses)
  61. os.Exit(1)
  62. }
  63. natType, behavior, err := nathole.ClassifyNATType(addresses)
  64. if err != nil {
  65. fmt.Println("classify nat type error:", err)
  66. os.Exit(1)
  67. }
  68. fmt.Println("Your NAT type is:", natType)
  69. fmt.Println("Behavior is:", behavior)
  70. fmt.Println("External address is:", addresses)
  71. return nil
  72. },
  73. }
  74. func validateForNatHoleDiscovery(cfg config.ClientCommonConf) error {
  75. if cfg.NatHoleSTUNServer == "" {
  76. return fmt.Errorf("nat_hole_stun_server can not be empty")
  77. }
  78. return nil
  79. }