quic_misc.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (C) 2019 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. //go:build go1.15 && !noquic
  7. // +build go1.15,!noquic
  8. package connections
  9. import (
  10. "crypto/tls"
  11. "net"
  12. "net/url"
  13. "time"
  14. "github.com/lucas-clemente/quic-go"
  15. "github.com/syncthing/syncthing/lib/osutil"
  16. )
  17. var (
  18. quicConfig = &quic.Config{
  19. ConnectionIDLength: 4,
  20. MaxIdleTimeout: 30 * time.Second,
  21. KeepAlivePeriod: 15 * time.Second,
  22. }
  23. )
  24. func quicNetwork(uri *url.URL) string {
  25. switch uri.Scheme {
  26. case "quic4":
  27. return "udp4"
  28. case "quic6":
  29. return "udp6"
  30. default:
  31. return "udp"
  32. }
  33. }
  34. type quicTlsConn struct {
  35. quic.Connection
  36. quic.Stream
  37. // If we created this connection, we should be the ones closing it.
  38. createdConn net.PacketConn
  39. }
  40. func (q *quicTlsConn) Close() error {
  41. sterr := q.Stream.Close()
  42. seerr := q.Connection.CloseWithError(0, "closing")
  43. var pcerr error
  44. if q.createdConn != nil {
  45. pcerr = q.createdConn.Close()
  46. }
  47. if sterr != nil {
  48. return sterr
  49. }
  50. if seerr != nil {
  51. return seerr
  52. }
  53. return pcerr
  54. }
  55. func (q *quicTlsConn) ConnectionState() tls.ConnectionState {
  56. return q.Connection.ConnectionState().TLS.ConnectionState
  57. }
  58. func packetConnUnspecified(conn interface{}) bool {
  59. addr := conn.(net.PacketConn).LocalAddr()
  60. ip, err := osutil.IPFromAddr(addr)
  61. return err == nil && ip.IsUnspecified()
  62. }