main.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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/ptutil/safelog"
  13. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/event"
  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. metricsAddress := flag.String("metrics-address", "localhost", "set listen address for metrics service")
  36. metricsPort := flag.Int("metrics-port", 9999, "set port for the metrics service")
  37. verboseLogging := flag.Bool("verbose", false, "increase log verbosity")
  38. ephemeralPortsRangeFlag := flag.String("ephemeral-ports-range", "", "ICE UDP ephemeral ports range (format:\"<min>:<max>\")")
  39. versionFlag := flag.Bool("version", false, "display version info to stderr and quit")
  40. var ephemeralPortsRange []uint16 = []uint16{0, 0}
  41. flag.Parse()
  42. if *versionFlag {
  43. fmt.Fprintf(os.Stderr, "snowflake-proxy %s", version.ConstructResult())
  44. os.Exit(0)
  45. }
  46. if *outboundAddress != "" && *keepLocalAddresses {
  47. log.Fatal("Cannot keep local address candidates when outbound address is specified")
  48. }
  49. eventLogger := event.NewSnowflakeEventDispatcher()
  50. if *ephemeralPortsRangeFlag != "" {
  51. ephemeralPortsRangeParts := strings.Split(*ephemeralPortsRangeFlag, ":")
  52. if len(ephemeralPortsRangeParts) == 2 {
  53. ephemeralMinPort, err := strconv.ParseUint(ephemeralPortsRangeParts[0], 10, 16)
  54. if err != nil {
  55. log.Fatal(err)
  56. }
  57. ephemeralMaxPort, err := strconv.ParseUint(ephemeralPortsRangeParts[1], 10, 16)
  58. if err != nil {
  59. log.Fatal(err)
  60. }
  61. if ephemeralMinPort == 0 || ephemeralMaxPort == 0 {
  62. log.Fatal("Ephemeral port cannot be zero")
  63. }
  64. if ephemeralMinPort > ephemeralMaxPort {
  65. log.Fatal("Invalid port range: min > max")
  66. }
  67. ephemeralPortsRange = []uint16{uint16(ephemeralMinPort), uint16(ephemeralMaxPort)}
  68. } else {
  69. log.Fatalf("Bad range port format: %v", *ephemeralPortsRangeFlag)
  70. }
  71. }
  72. proxy := sf.SnowflakeProxy{
  73. Capacity: uint(*capacity),
  74. STUNURL: *stunURL,
  75. BrokerURL: *rawBrokerURL,
  76. KeepLocalAddresses: *keepLocalAddresses,
  77. RelayURL: *relayURL,
  78. NATProbeURL: *probeURL,
  79. OutboundAddress: *outboundAddress,
  80. EphemeralMinPort: ephemeralPortsRange[0],
  81. EphemeralMaxPort: ephemeralPortsRange[1],
  82. NATTypeMeasurementInterval: *NATTypeMeasurementInterval,
  83. EventDispatcher: eventLogger,
  84. RelayDomainNamePattern: *allowedRelayHostNamePattern,
  85. AllowNonTLSRelay: *allowNonTLSRelay,
  86. SummaryInterval: *summaryInterval,
  87. }
  88. var logOutput = io.Discard
  89. var eventlogOutput io.Writer = os.Stderr
  90. log.SetFlags(log.LstdFlags | log.LUTC)
  91. if *verboseLogging {
  92. logOutput = os.Stderr
  93. }
  94. if *logFilename != "" {
  95. f, err := os.OpenFile(*logFilename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
  96. if err != nil {
  97. log.Fatal(err)
  98. }
  99. defer f.Close()
  100. if *verboseLogging {
  101. logOutput = io.MultiWriter(logOutput, f)
  102. }
  103. eventlogOutput = io.MultiWriter(eventlogOutput, f)
  104. }
  105. if *unsafeLogging {
  106. log.SetOutput(logOutput)
  107. } else {
  108. log.SetOutput(&safelog.LogScrubber{Output: logOutput})
  109. }
  110. proxyEventLogger := sf.NewProxyEventLogger(eventlogOutput, *disableStatsLogger)
  111. eventLogger.AddSnowflakeEventListener(proxyEventLogger)
  112. if *enableMetrics {
  113. metrics := sf.NewMetrics()
  114. err := metrics.Start(net.JoinHostPort(*metricsAddress, strconv.Itoa(*metricsPort)))
  115. if err != nil {
  116. log.Fatalf("could not enable metrics: %v", err)
  117. }
  118. eventLogger.AddSnowflakeEventListener(sf.NewEventMetrics(metrics))
  119. }
  120. log.Printf("snowflake-proxy %s\n", version.GetVersion())
  121. err := proxy.Start()
  122. if err != nil {
  123. log.Fatal(err)
  124. }
  125. }