quic_misc.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. "github.com/lucas-clemente/quic-go"
  14. )
  15. var (
  16. quicConfig = &quic.Config{
  17. ConnectionIDLength: 4,
  18. KeepAlive: true,
  19. }
  20. )
  21. func quicNetwork(uri *url.URL) string {
  22. switch uri.Scheme {
  23. case "quic4":
  24. return "udp4"
  25. case "quic6":
  26. return "udp6"
  27. default:
  28. return "udp"
  29. }
  30. }
  31. type quicTlsConn struct {
  32. quic.Session
  33. quic.Stream
  34. // If we created this connection, we should be the ones closing it.
  35. createdConn net.PacketConn
  36. }
  37. func (q *quicTlsConn) Close() error {
  38. sterr := q.Stream.Close()
  39. seerr := q.Session.CloseWithError(0, "closing")
  40. var pcerr error
  41. if q.createdConn != nil {
  42. pcerr = q.createdConn.Close()
  43. }
  44. if sterr != nil {
  45. return sterr
  46. }
  47. if seerr != nil {
  48. return seerr
  49. }
  50. return pcerr
  51. }
  52. func (q *quicTlsConn) ConnectionState() tls.ConnectionState {
  53. return q.Session.ConnectionState().TLS.ConnectionState
  54. }
  55. func packetConnUnspecified(conn interface{}) bool {
  56. // Since QUIC connections are wrapped, we can't do a simple typecheck
  57. // on *net.UDPAddr here.
  58. addr := conn.(net.PacketConn).LocalAddr()
  59. host, _, err := net.SplitHostPort(addr.String())
  60. return err == nil && net.ParseIP(host).IsUnspecified()
  61. }