userAgentPicker.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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"
  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 returns an http.Header object and a boolean
  37. // representing whether or not its User-Agent header was modified.
  38. // Any modifications are made to a copy of the original header map
  39. func UserAgentIfUnset(h http.Header) (http.Header, bool) {
  40. var dialHeaders http.Header
  41. if _, ok := h["User-Agent"]; !ok {
  42. dialHeaders = make(map[string][]string)
  43. if h != nil {
  44. for k, v := range h {
  45. dialHeaders[k] = make([]string, len(v))
  46. copy(dialHeaders[k], v)
  47. }
  48. }
  49. if common.FlipCoin() {
  50. dialHeaders.Set("User-Agent", pickUserAgent())
  51. } else {
  52. dialHeaders.Set("User-Agent", "")
  53. }
  54. return dialHeaders, true
  55. }
  56. return h, false
  57. }