connections_tcp.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. )
  15. func init() {
  16. for _, network := range []string{"tcp", "tcp4", "tcp6"} {
  17. dialers[network] = makeTCPDialer(network)
  18. listeners[network] = makeTCPListener(network)
  19. }
  20. }
  21. func makeTCPDialer(network string) DialerFactory {
  22. return func(uri *url.URL, tlsCfg *tls.Config) (*tls.Conn, error) {
  23. // Check that there is a port number in uri.Host, otherwise add one.
  24. host, port, err := net.SplitHostPort(uri.Host)
  25. if err != nil && strings.HasPrefix(err.Error(), "missing port") {
  26. // addr is on the form "1.2.3.4"
  27. uri.Host = net.JoinHostPort(uri.Host, "22000")
  28. } else if err == nil && port == "" {
  29. // addr is on the form "1.2.3.4:"
  30. uri.Host = net.JoinHostPort(host, "22000")
  31. }
  32. // Don't try to resolve the address before dialing. The dialer may be a
  33. // proxy, and we should let the proxy do the resolving in that case.
  34. conn, err := dialer.Dial(network, uri.Host)
  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. }
  48. func makeTCPListener(network string) ListenerFactory {
  49. return func(uri *url.URL, tlsCfg *tls.Config, conns chan<- model.IntermediateConnection) {
  50. tcaddr, err := net.ResolveTCPAddr(network, uri.Host)
  51. if err != nil {
  52. l.Fatalln("listen (BEP/tcp):", err)
  53. return
  54. }
  55. listener, err := net.ListenTCP(network, tcaddr)
  56. if err != nil {
  57. l.Fatalln("listen (BEP/tcp):", err)
  58. return
  59. }
  60. for {
  61. conn, err := listener.Accept()
  62. if err != nil {
  63. l.Warnln("Accepting connection (BEP/tcp):", err)
  64. continue
  65. }
  66. l.Debugln("connect from", conn.RemoteAddr())
  67. err = dialer.SetTCPOptions(conn.(*net.TCPConn))
  68. if err != nil {
  69. l.Infoln(err)
  70. }
  71. tc := tls.Server(conn, tlsCfg)
  72. err = tc.Handshake()
  73. if err != nil {
  74. l.Infoln("TLS handshake (BEP/tcp):", err)
  75. tc.Close()
  76. continue
  77. }
  78. conns <- model.IntermediateConnection{
  79. tc, model.ConnectionTypeDirectAccept,
  80. }
  81. }
  82. }
  83. }