tcp_dial.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright (C) 2016 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 connections
  7. import (
  8. "context"
  9. "crypto/tls"
  10. "net/url"
  11. "time"
  12. "github.com/syncthing/syncthing/lib/config"
  13. "github.com/syncthing/syncthing/lib/connections/registry"
  14. "github.com/syncthing/syncthing/lib/dialer"
  15. "github.com/syncthing/syncthing/lib/protocol"
  16. )
  17. const tcpPriority = 10
  18. func init() {
  19. factory := &tcpDialerFactory{}
  20. for _, scheme := range []string{"tcp", "tcp4", "tcp6"} {
  21. dialers[scheme] = factory
  22. }
  23. }
  24. type tcpDialer struct {
  25. commonDialer
  26. registry *registry.Registry
  27. }
  28. func (d *tcpDialer) Dial(ctx context.Context, _ protocol.DeviceID, uri *url.URL) (internalConn, error) {
  29. uri = fixupPort(uri, config.DefaultTCPPort)
  30. timeoutCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
  31. defer cancel()
  32. conn, err := dialer.DialContextReusePortFunc(d.registry)(timeoutCtx, uri.Scheme, uri.Host)
  33. if err != nil {
  34. return internalConn{}, err
  35. }
  36. err = dialer.SetTCPOptions(conn)
  37. if err != nil {
  38. l.Debugln("Dial (BEP/tcp): setting tcp options:", err)
  39. }
  40. err = dialer.SetTrafficClass(conn, d.trafficClass)
  41. if err != nil {
  42. l.Debugln("Dial (BEP/tcp): setting traffic class:", err)
  43. }
  44. tc := tls.Client(conn, d.tlsCfg)
  45. err = tlsTimedHandshake(tc)
  46. if err != nil {
  47. tc.Close()
  48. return internalConn{}, err
  49. }
  50. return newInternalConn(tc, connTypeTCPClient, tcpPriority), nil
  51. }
  52. type tcpDialerFactory struct{}
  53. func (tcpDialerFactory) New(opts config.OptionsConfiguration, tlsCfg *tls.Config, registry *registry.Registry) genericDialer {
  54. return &tcpDialer{
  55. commonDialer: commonDialer{
  56. trafficClass: opts.TrafficClass,
  57. reconnectInterval: time.Duration(opts.ReconnectIntervalS) * time.Second,
  58. tlsCfg: tlsCfg,
  59. },
  60. registry: registry,
  61. }
  62. }
  63. func (tcpDialerFactory) Priority() int {
  64. return tcpPriority
  65. }
  66. func (tcpDialerFactory) AlwaysWAN() bool {
  67. return false
  68. }
  69. func (tcpDialerFactory) Valid(_ config.Configuration) error {
  70. // Always valid
  71. return nil
  72. }
  73. func (tcpDialerFactory) String() string {
  74. return "TCP Dialer"
  75. }