userAgentPicker.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 common
  20. import (
  21. "net/http"
  22. "sync/atomic"
  23. )
  24. var registeredUserAgentPicker atomic.Value
  25. func RegisterUserAgentPicker(picker func() string) {
  26. registeredUserAgentPicker.Store(picker)
  27. }
  28. func pickUserAgent() string {
  29. picker := registeredUserAgentPicker.Load()
  30. if picker != nil {
  31. return picker.(func() string)()
  32. }
  33. return ""
  34. }
  35. // UserAgentIfUnset returns an http.Header object and a boolean
  36. // representing whether or not its User-Agent header was modified.
  37. // Any modifications are made to a copy of the original header map
  38. func UserAgentIfUnset(h http.Header) (http.Header, bool) {
  39. var dialHeaders http.Header
  40. if _, ok := h["User-Agent"]; !ok {
  41. dialHeaders = make(map[string][]string)
  42. if h != nil {
  43. for k, v := range h {
  44. dialHeaders[k] = make([]string, len(v))
  45. copy(dialHeaders[k], v)
  46. }
  47. }
  48. if FlipCoin() {
  49. dialHeaders.Set("User-Agent", pickUserAgent())
  50. } else {
  51. dialHeaders.Set("User-Agent", "")
  52. }
  53. return dialHeaders, true
  54. }
  55. return h, false
  56. }