internal.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "time"
  13. "golang.org/x/net/proxy"
  14. )
  15. var (
  16. noFallback = os.Getenv("ALL_PROXY_NO_FALLBACK") != ""
  17. )
  18. func init() {
  19. proxy.RegisterDialerType("socks", socksDialerFunction)
  20. if proxyDialer := proxy.FromEnvironment(); proxyDialer != proxy.Direct {
  21. http.DefaultTransport = &http.Transport{
  22. DialContext: DialContext,
  23. Proxy: http.ProxyFromEnvironment,
  24. TLSHandshakeTimeout: 10 * time.Second,
  25. }
  26. // Defer this, so that logging gets setup.
  27. go func() {
  28. time.Sleep(500 * time.Millisecond)
  29. l.Infoln("Proxy settings detected")
  30. if noFallback {
  31. l.Infoln("Proxy fallback disabled")
  32. }
  33. }()
  34. } else {
  35. go func() {
  36. time.Sleep(500 * time.Millisecond)
  37. l.Debugln("Dialer logging disabled, as no proxy was detected")
  38. }()
  39. }
  40. }
  41. // This is a rip off of proxy.FromURL for "socks" URL scheme
  42. func socksDialerFunction(u *url.URL, forward proxy.Dialer) (proxy.Dialer, error) {
  43. var auth *proxy.Auth
  44. if u.User != nil {
  45. auth = new(proxy.Auth)
  46. auth.User = u.User.Username()
  47. if p, ok := u.User.Password(); ok {
  48. auth.Password = p
  49. }
  50. }
  51. return proxy.SOCKS5("tcp", u.Host, auth, forward)
  52. }
  53. // dialerConn is needed because proxy dialed connections have RemoteAddr() pointing at the proxy,
  54. // which then screws up various things such as IsLAN checks, and "let's populate the relay invitation address from
  55. // existing connection" shenanigans.
  56. type dialerConn struct {
  57. net.Conn
  58. addr net.Addr
  59. }
  60. func (c dialerConn) RemoteAddr() net.Addr {
  61. return c.addr
  62. }
  63. func newDialerAddr(network, addr string) net.Addr {
  64. netAddr, err := net.ResolveIPAddr(network, addr)
  65. if err == nil {
  66. return netAddr
  67. }
  68. return fallbackAddr{network, addr}
  69. }
  70. type fallbackAddr struct {
  71. network string
  72. addr string
  73. }
  74. func (a fallbackAddr) Network() string {
  75. return a.network
  76. }
  77. func (a fallbackAddr) String() string {
  78. return a.addr
  79. }