main.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "io"
  6. "log"
  7. "net"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/event"
  13. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/safelog"
  14. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/version"
  15. sf "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/proxy/lib"
  16. )
  17. func main() {
  18. capacity := flag.Uint("capacity", 0, "maximum concurrent clients (default is to accept an unlimited number of clients)")
  19. stunURL := flag.String("stun", sf.DefaultSTUNURL, "STUN URL")
  20. logFilename := flag.String("log", "", "log filename")
  21. rawBrokerURL := flag.String("broker", sf.DefaultBrokerURL, "broker URL")
  22. unsafeLogging := flag.Bool("unsafe-logging", false, "prevent logs from being scrubbed")
  23. keepLocalAddresses := flag.Bool("keep-local-addresses", false, "keep local LAN address ICE candidates")
  24. relayURL := flag.String("relay", sf.DefaultRelayURL, "websocket relay URL")
  25. probeURL := flag.String("nat-probe-server", sf.DefaultNATProbeURL, "NAT check probe server URL")
  26. outboundAddress := flag.String("outbound-address", "", "prefer the given address as outbound address")
  27. allowedRelayHostNamePattern := flag.String("allowed-relay-hostname-pattern", "snowflake.torproject.net$", "a pattern to specify allowed hostname pattern for relay URL.")
  28. allowNonTLSRelay := flag.Bool("allow-non-tls-relay", false, "allow relay without tls encryption")
  29. NATTypeMeasurementInterval := flag.Duration("nat-retest-interval", time.Hour*24,
  30. "the time interval in second before NAT type is retested, 0s disables retest. Valid time units are \"s\", \"m\", \"h\". ")
  31. summaryInterval := flag.Duration("summary-interval", time.Hour,
  32. "the time interval to output summary, 0s disables summaries. Valid time units are \"s\", \"m\", \"h\". ")
  33. disableStatsLogger := flag.Bool("disable-stats-logger", false, "disable the exposing mechanism for stats using logs")
  34. enableMetrics := flag.Bool("metrics", false, "enable the exposing mechanism for stats using metrics")
  35. metricsPort := flag.Int("metrics-port", 9999, "set port for the metrics service")
  36. verboseLogging := flag.Bool("verbose", false, "increase log verbosity")
  37. ephemeralPortsRangeFlag := flag.String("ephemeral-ports-range", "", "ICE UDP ephemeral ports range (format:\"<min>:<max>\")")
  38. versionFlag := flag.Bool("version", false, "display version info to stderr and quit")
  39. var ephemeralPortsRange []uint16 = []uint16{0, 0}
  40. flag.Parse()
  41. if *versionFlag {
  42. fmt.Fprintf(os.Stderr, "snowflake-proxy %s", version.ConstructResult())
  43. os.Exit(0)
  44. }
  45. if *outboundAddress != "" && *keepLocalAddresses {
  46. log.Fatal("Cannot keep local address candidates when outbound address is specified")
  47. }
  48. eventLogger := event.NewSnowflakeEventDispatcher()
  49. if *ephemeralPortsRangeFlag != "" {
  50. ephemeralPortsRangeParts := strings.Split(*ephemeralPortsRangeFlag, ":")
  51. if len(ephemeralPortsRangeParts) == 2 {
  52. ephemeralMinPort, err := strconv.ParseUint(ephemeralPortsRangeParts[0], 10, 16)
  53. if err != nil {
  54. log.Fatal(err)
  55. }
  56. ephemeralMaxPort, err := strconv.ParseUint(ephemeralPortsRangeParts[1], 10, 16)
  57. if err != nil {
  58. log.Fatal(err)
  59. }
  60. if ephemeralMinPort == 0 || ephemeralMaxPort == 0 {
  61. log.Fatal("Ephemeral port cannot be zero")
  62. }
  63. if ephemeralMinPort > ephemeralMaxPort {
  64. log.Fatal("Invalid port range: min > max")
  65. }
  66. ephemeralPortsRange = []uint16{uint16(ephemeralMinPort), uint16(ephemeralMaxPort)}
  67. } else {
  68. log.Fatalf("Bad range port format: %v", *ephemeralPortsRangeFlag)
  69. }
  70. }
  71. proxy := sf.SnowflakeProxy{
  72. Capacity: uint(*capacity),
  73. STUNURL: *stunURL,
  74. BrokerURL: *rawBrokerURL,
  75. KeepLocalAddresses: *keepLocalAddresses,
  76. RelayURL: *relayURL,
  77. NATProbeURL: *probeURL,
  78. OutboundAddress: *outboundAddress,
  79. EphemeralMinPort: ephemeralPortsRange[0],
  80. EphemeralMaxPort: ephemeralPortsRange[1],
  81. NATTypeMeasurementInterval: *NATTypeMeasurementInterval,
  82. EventDispatcher: eventLogger,
  83. RelayDomainNamePattern: *allowedRelayHostNamePattern,
  84. AllowNonTLSRelay: *allowNonTLSRelay,
  85. SummaryInterval: *summaryInterval,
  86. }
  87. var logOutput = io.Discard
  88. var eventlogOutput io.Writer = os.Stderr
  89. log.SetFlags(log.LstdFlags | log.LUTC)
  90. if *verboseLogging {
  91. logOutput = os.Stderr
  92. }
  93. if *logFilename != "" {
  94. f, err := os.OpenFile(*logFilename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  95. if err != nil {
  96. log.Fatal(err)
  97. }
  98. defer f.Close()
  99. if *verboseLogging {
  100. logOutput = io.MultiWriter(logOutput, f)
  101. }
  102. eventlogOutput = io.MultiWriter(eventlogOutput, f)
  103. }
  104. if *unsafeLogging {
  105. log.SetOutput(logOutput)
  106. } else {
  107. log.SetOutput(&safelog.LogScrubber{Output: logOutput})
  108. }
  109. proxyEventLogger := sf.NewProxyEventLogger(eventlogOutput, *disableStatsLogger)
  110. eventLogger.AddSnowflakeEventListener(proxyEventLogger)
  111. if *enableMetrics {
  112. metrics := sf.NewMetrics()
  113. err := metrics.Start(net.JoinHostPort("localhost", strconv.Itoa(*metricsPort)))
  114. if err != nil {
  115. log.Fatalf("could not enable metrics: %v", err)
  116. }
  117. eventLogger.AddSnowflakeEventListener(sf.NewEventMetrics(metrics))
  118. }
  119. log.Printf("snowflake-proxy %s\n", version.GetVersion())
  120. err := proxy.Start()
  121. if err != nil {
  122. log.Fatal(err)
  123. }
  124. }