tcp_dial.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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(id protocol.DeviceID, uri *url.URL) (internalConn, error) {
  27. uri = fixupPort(uri)
  28. conn, err := dialer.DialTimeout(uri.Scheme, uri.Host, 10*time.Second)
  29. if err != nil {
  30. l.Debugln(err)
  31. return internalConn{}, err
  32. }
  33. err = dialer.SetTCPOptions(conn)
  34. if err != nil {
  35. l.Infoln(err)
  36. }
  37. err = dialer.SetTrafficClass(conn, d.cfg.Options().TrafficClass)
  38. if err != nil {
  39. l.Debugf("failed to set traffic class: %s", err)
  40. }
  41. tc := tls.Client(conn, d.tlsCfg)
  42. err = tlsTimedHandshake(tc)
  43. if err != nil {
  44. tc.Close()
  45. return internalConn{}, err
  46. }
  47. return internalConn{tc, connTypeTCPClient, tcpPriority}, nil
  48. }
  49. func (d *tcpDialer) RedialFrequency() time.Duration {
  50. return time.Duration(d.cfg.Options().ReconnectIntervalS) * time.Second
  51. }
  52. type tcpDialerFactory struct{}
  53. func (tcpDialerFactory) New(cfg *config.Wrapper, tlsCfg *tls.Config) genericDialer {
  54. return &tcpDialer{
  55. cfg: cfg,
  56. tlsCfg: tlsCfg,
  57. }
  58. }
  59. func (tcpDialerFactory) Priority() int {
  60. return tcpPriority
  61. }
  62. func (tcpDialerFactory) Enabled(cfg config.Configuration) bool {
  63. return true
  64. }
  65. func (tcpDialerFactory) String() string {
  66. return "TCP Dialer"
  67. }