userAgentPicker.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (c) 2017, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package psiphon
  20. import (
  21. "net/http"
  22. "sync/atomic"
  23. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
  24. )
  25. var registeredUserAgentPicker atomic.Value
  26. func RegisterUserAgentPicker(picker func() string) {
  27. registeredUserAgentPicker.Store(picker)
  28. }
  29. func pickUserAgent() string {
  30. picker := registeredUserAgentPicker.Load()
  31. if picker != nil {
  32. return picker.(func() string)()
  33. }
  34. return ""
  35. }
  36. // UserAgentIfUnset selects and sets a User-Agent header if one is not set.
  37. func UserAgentIfUnset(
  38. clientParameters *parameters.ClientParameters, headers http.Header) bool {
  39. if _, ok := headers["User-Agent"]; !ok {
  40. if clientParameters.Get().WeightedCoinFlip(parameters.PickUserAgentProbability) {
  41. headers.Set("User-Agent", pickUserAgent())
  42. } else {
  43. headers.Set("User-Agent", "")
  44. }
  45. return true
  46. }
  47. return false
  48. }