tcp_dial.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. return internalConn{}, err
  30. }
  31. err = dialer.SetTCPOptions(conn)
  32. if err != nil {
  33. l.Debugln("Dial (BEP/tcp): setting tcp options:", err)
  34. }
  35. err = dialer.SetTrafficClass(conn, d.cfg.Options().TrafficClass)
  36. if err != nil {
  37. l.Debugln("Dial (BEP/tcp): setting traffic class:", err)
  38. }
  39. tc := tls.Client(conn, d.tlsCfg)
  40. err = tlsTimedHandshake(tc)
  41. if err != nil {
  42. tc.Close()
  43. return internalConn{}, err
  44. }
  45. return internalConn{tc, connTypeTCPClient, tcpPriority}, nil
  46. }
  47. func (d *tcpDialer) RedialFrequency() time.Duration {
  48. return time.Duration(d.cfg.Options().ReconnectIntervalS) * time.Second
  49. }
  50. type tcpDialerFactory struct{}
  51. func (tcpDialerFactory) New(cfg config.Wrapper, tlsCfg *tls.Config) genericDialer {
  52. return &tcpDialer{
  53. cfg: cfg,
  54. tlsCfg: tlsCfg,
  55. }
  56. }
  57. func (tcpDialerFactory) Priority() int {
  58. return tcpPriority
  59. }
  60. func (tcpDialerFactory) AlwaysWAN() bool {
  61. return false
  62. }
  63. func (tcpDialerFactory) Valid(_ config.Configuration) error {
  64. // Always valid
  65. return nil
  66. }
  67. func (tcpDialerFactory) String() string {
  68. return "TCP Dialer"
  69. }