internal.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. "log/slog"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "time"
  14. "golang.org/x/net/proxy"
  15. )
  16. var noFallback = os.Getenv("ALL_PROXY_NO_FALLBACK") != ""
  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 set up.
  26. go func() {
  27. time.Sleep(500 * time.Millisecond)
  28. slog.Info("Proxy settings detected")
  29. if noFallback {
  30. slog.Info("Proxy fallback disabled")
  31. }
  32. }()
  33. } else {
  34. go func() {
  35. time.Sleep(500 * time.Millisecond)
  36. slog.Debug("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. }
  52. // dialerConn is needed because proxy dialed connections have RemoteAddr() pointing at the proxy,
  53. // which then screws up various things such as IsLAN checks, and "let's populate the relay invitation address from
  54. // existing connection" shenanigans.
  55. type dialerConn struct {
  56. net.Conn
  57. addr net.Addr
  58. }
  59. func (c dialerConn) RemoteAddr() net.Addr {
  60. return c.addr
  61. }
  62. func newDialerAddr(network, addr string) net.Addr {
  63. netAddr, err := net.ResolveIPAddr(network, addr)
  64. if err == nil {
  65. return netAddr
  66. }
  67. return fallbackAddr{network, addr}
  68. }
  69. type fallbackAddr struct {
  70. network string
  71. addr string
  72. }
  73. func (a fallbackAddr) Network() string {
  74. return a.network
  75. }
  76. func (a fallbackAddr) String() string {
  77. return a.addr
  78. }