1
0

connections_tcp.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright (C) 2015 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. "strings"
  12. "github.com/syncthing/syncthing/lib/dialer"
  13. "github.com/syncthing/syncthing/lib/model"
  14. "github.com/syncthing/syncthing/lib/osutil"
  15. )
  16. func init() {
  17. dialers["tcp"] = tcpDialer
  18. listeners["tcp"] = tcpListener
  19. }
  20. func tcpDialer(uri *url.URL, tlsCfg *tls.Config) (*tls.Conn, error) {
  21. host, port, err := net.SplitHostPort(uri.Host)
  22. if err != nil && strings.HasPrefix(err.Error(), "missing port") {
  23. // addr is on the form "1.2.3.4"
  24. uri.Host = net.JoinHostPort(uri.Host, "22000")
  25. } else if err == nil && port == "" {
  26. // addr is on the form "1.2.3.4:"
  27. uri.Host = net.JoinHostPort(host, "22000")
  28. }
  29. raddr, err := net.ResolveTCPAddr("tcp", uri.Host)
  30. if err != nil {
  31. l.Debugln(err)
  32. return nil, err
  33. }
  34. conn, err := dialer.Dial(raddr.Network(), raddr.String())
  35. if err != nil {
  36. l.Debugln(err)
  37. return nil, err
  38. }
  39. tc := tls.Client(conn, tlsCfg)
  40. err = tc.Handshake()
  41. if err != nil {
  42. tc.Close()
  43. return nil, err
  44. }
  45. return tc, nil
  46. }
  47. func tcpListener(uri *url.URL, tlsCfg *tls.Config, conns chan<- model.IntermediateConnection) {
  48. tcaddr, err := net.ResolveTCPAddr("tcp", uri.Host)
  49. if err != nil {
  50. l.Fatalln("listen (BEP/tcp):", err)
  51. return
  52. }
  53. listener, err := net.ListenTCP("tcp", tcaddr)
  54. if err != nil {
  55. l.Fatalln("listen (BEP/tcp):", err)
  56. return
  57. }
  58. for {
  59. conn, err := listener.Accept()
  60. if err != nil {
  61. l.Warnln("Accepting connection (BEP/tcp):", err)
  62. continue
  63. }
  64. l.Debugln("connect from", conn.RemoteAddr())
  65. err = osutil.SetTCPOptions(conn.(*net.TCPConn))
  66. if err != nil {
  67. l.Infoln(err)
  68. }
  69. tc := tls.Server(conn, tlsCfg)
  70. err = tc.Handshake()
  71. if err != nil {
  72. l.Infoln("TLS handshake (BEP/tcp):", err)
  73. tc.Close()
  74. continue
  75. }
  76. conns <- model.IntermediateConnection{
  77. tc, model.ConnectionTypeDirectAccept,
  78. }
  79. }
  80. }