tcp_dial.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 http://mozilla.org/MPL/2.0/.
  6. package connections
  7. import (
  8. "crypto/tls"
  9. "net"
  10. "net/url"
  11. "time"
  12. "github.com/syncthing/syncthing/lib/config"
  13. "github.com/syncthing/syncthing/lib/dialer"
  14. "github.com/syncthing/syncthing/lib/protocol"
  15. )
  16. const tcpPriority = 10
  17. func init() {
  18. for _, scheme := range []string{"tcp", "tcp4", "tcp6"} {
  19. dialers[scheme] = tcpDialerFactory{}
  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) (IntermediateConnection, error) {
  27. uri = fixupPort(uri)
  28. raddr, err := net.ResolveTCPAddr(uri.Scheme, uri.Host)
  29. if err != nil {
  30. l.Debugln(err)
  31. return IntermediateConnection{}, err
  32. }
  33. conn, err := dialer.DialTimeout(raddr.Network(), raddr.String(), 10*time.Second)
  34. if err != nil {
  35. l.Debugln(err)
  36. return IntermediateConnection{}, err
  37. }
  38. tc := tls.Client(conn, d.tlsCfg)
  39. err = tc.Handshake()
  40. if err != nil {
  41. tc.Close()
  42. return IntermediateConnection{}, err
  43. }
  44. return IntermediateConnection{tc, "TCP (Client)", tcpPriority}, nil
  45. }
  46. func (tcpDialer) Priority() int {
  47. return tcpPriority
  48. }
  49. func (d *tcpDialer) RedialFrequency() time.Duration {
  50. return time.Duration(d.cfg.Options().ReconnectIntervalS) * time.Second
  51. }
  52. func (d *tcpDialer) String() string {
  53. return "TCP Dialer"
  54. }
  55. type tcpDialerFactory struct{}
  56. func (tcpDialerFactory) New(cfg *config.Wrapper, tlsCfg *tls.Config) genericDialer {
  57. return &tcpDialer{
  58. cfg: cfg,
  59. tlsCfg: tlsCfg,
  60. }
  61. }
  62. func (tcpDialerFactory) Priority() int {
  63. return tcpPriority
  64. }