1
0

nathole.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. addresses, err := nathole.Discover(
  47. net.JoinHostPort(cfg.ServerAddr, strconv.Itoa(cfg.ServerUDPPort)),
  48. []string{cfg.NatHoleSTUNServer},
  49. []byte(cfg.Token),
  50. )
  51. if err != nil {
  52. fmt.Println("discover error:", err)
  53. os.Exit(1)
  54. }
  55. natType, behavior, err := nathole.ClassifyNATType(addresses)
  56. if err != nil {
  57. fmt.Println("classify nat type error:", err)
  58. os.Exit(1)
  59. }
  60. fmt.Println("Your NAT type is:", natType)
  61. fmt.Println("Behavior is:", behavior)
  62. fmt.Println("External address is:", addresses)
  63. return nil
  64. },
  65. }
  66. func validateForNatHoleDiscovery(cfg config.ClientCommonConf) error {
  67. if cfg.NatHoleSTUNServer == "" {
  68. return fmt.Errorf("nat_hole_stun_server can not be empty")
  69. }
  70. if cfg.ServerUDPPort == 0 {
  71. return fmt.Errorf("server udp port can not be empty")
  72. }
  73. return nil
  74. }