tcp_dial.go 1.9 KB

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