tcp_dial.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. func init() {
  16. factory := &tcpDialerFactory{}
  17. for _, scheme := range []string{"tcp", "tcp4", "tcp6"} {
  18. dialers[scheme] = factory
  19. }
  20. }
  21. type tcpDialer struct {
  22. cfg *config.Wrapper
  23. tlsCfg *tls.Config
  24. }
  25. func (d *tcpDialer) Dial(id protocol.DeviceID, uri *url.URL) (internalConn, error) {
  26. uri = fixupPort(uri, config.DefaultTCPPort)
  27. conn, err := dialer.DialTimeout(uri.Scheme, uri.Host, 10*time.Second)
  28. if err != nil {
  29. l.Debugln(err)
  30. return internalConn{}, err
  31. }
  32. err = dialer.SetTCPOptions(conn)
  33. if err != nil {
  34. l.Infoln(err)
  35. }
  36. err = dialer.SetTrafficClass(conn, d.cfg.Options().TrafficClass)
  37. if err != nil {
  38. l.Debugf("failed to set traffic class: %s", 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) Enabled(cfg config.Configuration) bool {
  62. return true
  63. }
  64. func (tcpDialerFactory) String() string {
  65. return "TCP Dialer"
  66. }