tcp_dial.go 1.9 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. commonDialer
  24. }
  25. func (d *tcpDialer) Dial(_ 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.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. type tcpDialerFactory struct{}
  48. func (tcpDialerFactory) New(opts config.OptionsConfiguration, tlsCfg *tls.Config) genericDialer {
  49. return &tcpDialer{commonDialer{
  50. trafficClass: opts.TrafficClass,
  51. reconnectInterval: time.Duration(opts.ReconnectIntervalS) * time.Second,
  52. tlsCfg: tlsCfg,
  53. }}
  54. }
  55. func (tcpDialerFactory) Priority() int {
  56. return tcpPriority
  57. }
  58. func (tcpDialerFactory) AlwaysWAN() bool {
  59. return false
  60. }
  61. func (tcpDialerFactory) Valid(_ config.Configuration) error {
  62. // Always valid
  63. return nil
  64. }
  65. func (tcpDialerFactory) String() string {
  66. return "TCP Dialer"
  67. }