internal.go 2.1 KB

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