internal.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package dialer
  7. import (
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "time"
  12. "golang.org/x/net/proxy"
  13. )
  14. var (
  15. noFallback = os.Getenv("ALL_PROXY_NO_FALLBACK") != ""
  16. )
  17. func init() {
  18. proxy.RegisterDialerType("socks", socksDialerFunction)
  19. if proxyDialer := proxy.FromEnvironment(); proxyDialer != proxy.Direct {
  20. http.DefaultTransport = &http.Transport{
  21. DialContext: DialContext,
  22. Proxy: http.ProxyFromEnvironment,
  23. TLSHandshakeTimeout: 10 * time.Second,
  24. }
  25. // Defer this, so that logging gets setup.
  26. go func() {
  27. time.Sleep(500 * time.Millisecond)
  28. l.Infoln("Proxy settings detected")
  29. if noFallback {
  30. l.Infoln("Proxy fallback disabled")
  31. }
  32. }()
  33. } else {
  34. go func() {
  35. time.Sleep(500 * time.Millisecond)
  36. l.Debugln("Dialer logging disabled, as no proxy was detected")
  37. }()
  38. }
  39. }
  40. // This is a rip off of proxy.FromURL for "socks" URL scheme
  41. func socksDialerFunction(u *url.URL, forward proxy.Dialer) (proxy.Dialer, error) {
  42. var auth *proxy.Auth
  43. if u.User != nil {
  44. auth = new(proxy.Auth)
  45. auth.User = u.User.Username()
  46. if p, ok := u.User.Password(); ok {
  47. auth.Password = p
  48. }
  49. }
  50. return proxy.SOCKS5("tcp", u.Host, auth, forward)
  51. }