From 926f6a3c72c11f36376e8e94012e0dd4ff381e53 Mon Sep 17 00:00:00 2001 From: Siddarth Kumar Date: Fri, 19 Jan 2024 00:24:54 +0530 Subject: [PATCH] Revert "test: bump go-libp2p" This reverts commit d0ca4447c6c5642830354740d045f453eb3e77e8. --- Makefile | 4 +- VERSION | 2 +- api/backend_test.go | 8 +- api/defaults.go | 2 +- api/geth_backend.go | 22 +- eth-node/bridge/geth/wakuv2.go | 7 +- go.mod | 97 +- go.sum | 213 +- images/decode_test.go | 4 +- mailserver/mailserver_test.go | 2 - multiaccounts/accounts/database_test.go | 10 +- multiaccounts/accounts/keycard_database.go | 9 +- .../accounts/keycard_database_test.go | 4 +- protocol/activity_center_persistence.go | 4 +- protocol/communities/manager.go | 8 +- protocol/communities/persistence.go | 6 +- protocol/message_persistence.go | 2 +- protocol/messenger_testing_utils.go | 4 +- protocol/transport/filters_manager.go | 3 - protocol/transport/topic.go | 4 +- rpc/route_test.go | 8 +- server/handlers_linkpreview.go | 4 +- server/handlers_test.go | 4 +- server/pairing/server_pairing_test.go | 6 +- server/server_test.go | 24 +- services/mailservers/database.go | 2 +- services/wallet/balance/balance_cache.go | 6 +- services/wallet/balance/nonce_range.go | 6 +- services/wallet/balance/simple_cache.go | 2 +- services/wallet/balance/ttl_cache.go | 2 +- services/wallet/on_ramp_test.go | 4 +- services/wallet/transfer/database.go | 1 - .../transaction_manager_multitransaction.go | 4 +- shell.nix | 21 +- transactions/transactor_test.go | 1 - .../golang}/mock/mockgen/mockgen.go | 303 +-- .../golang}/mock/mockgen/model/model.go | 70 +- .../golang}/mock/mockgen/parse.go | 346 +-- .../golang}/mock/mockgen/reflect.go | 15 +- .../golang/mock/mockgen/version.1.11.go | 26 + .../golang/mock/mockgen/version.1.12.go} | 6 +- .../hashicorp/golang-lru/v2/.golangci.yml | 25 +- .../github.com/hashicorp/golang-lru/v2/2q.go | 10 - .../hashicorp/golang-lru/v2/README.md | 74 +- .../github.com/hashicorp/golang-lru/v2/arc.go | 259 +++ .../github.com/hashicorp/golang-lru/v2/doc.go | 20 +- .../hashicorp/golang-lru/v2/internal/list.go | 142 -- .../github.com/hashicorp/golang-lru/v2/lru.go | 8 - .../hashicorp/golang-lru/v2/simplelru/list.go | 128 ++ .../hashicorp/golang-lru/v2/simplelru/lru.go | 70 +- .../golang-lru/v2/simplelru/lru_interface.go | 3 - .../hashicorp/golang-lru/v2/testing.go | 19 + vendor/github.com/huin/goupnp/goupnp.go | 5 +- vendor/github.com/huin/goupnp/httpu/httpu.go | 64 +- .../huin/goupnp/httpu/multiclient.go | 66 +- vendor/github.com/huin/goupnp/network.go | 6 +- vendor/github.com/huin/goupnp/ssdp/ssdp.go | 77 +- .../klauspost/compress/.goreleaser.yml | 20 +- .../github.com/klauspost/compress/README.md | 19 - .../klauspost/compress/fse/bitwriter.go | 3 +- .../klauspost/compress/fse/compress.go | 3 +- .../klauspost/compress/huff0/bitwriter.go | 3 +- .../klauspost/compress/huff0/compress.go | 20 +- .../klauspost/compress/zstd/bitreader.go | 34 +- .../klauspost/compress/zstd/bitwriter.go | 3 +- .../klauspost/compress/zstd/blockenc.go | 29 +- .../klauspost/compress/zstd/dict.go | 379 +--- .../klauspost/compress/zstd/enc_best.go | 11 +- .../klauspost/compress/zstd/encoder.go | 13 +- .../klauspost/compress/zstd/frameenc.go | 4 +- .../klauspost/compress/zstd/seqdec.go | 17 +- .../klauspost/compress/zstd/seqdec_amd64.s | 128 +- .../klauspost/compress/zstd/seqdec_generic.go | 2 +- .../klauspost/compress/zstd/snappy.go | 5 +- .../libp2p/go-libp2p-mplex/.gitignore | 1 - .../libp2p/go-libp2p-mplex/README.md | 11 - .../libp2p/go-libp2p-mplex/version.json | 3 - .../libp2p/go-libp2p-pubsub/gossipsub.go | 2 +- vendor/github.com/libp2p/go-libp2p/README.md | 30 +- .../libp2p/go-libp2p/config/config.go | 15 - .../{quic.go => quic_stateless_reset.go} | 18 +- .../libp2p/go-libp2p/core/connmgr/manager.go | 10 - .../libp2p/go-libp2p/core/connmgr/null.go | 1 - .../libp2p/go-libp2p/core/crypto/ecdsa.go | 3 +- .../libp2p/go-libp2p/core/crypto/rsa_go.go | 3 +- .../libp2p/go-libp2p/core/crypto/secp256k1.go | 2 +- .../libp2p/go-libp2p/core/peer/addrinfo.go | 4 +- .../libp2p/go-libp2p/core/peer/peer.go | 16 + .../libp2p/go-libp2p/core/peer/peer_serde.go | 4 +- .../libp2p/go-libp2p/core/sec/security.go | 12 - .../go-libp2p/core/transport/transport.go | 45 - .../github.com/libp2p/go-libp2p/defaults.go | 2 + .../go-libp2p/internal/sha256/post_go1_21.go | 23 - .../go-libp2p/internal/sha256/pre_go1_21.go | 24 - vendor/github.com/libp2p/go-libp2p/options.go | 1 - .../libp2p/go-libp2p/p2p/host/autonat/svc.go | 10 +- .../p2p/host/autorelay/relay_finder.go | 2 +- .../go-libp2p/p2p/host/basic/basic_host.go | 22 +- .../libp2p/go-libp2p/p2p/host/basic/mocks.go | 2 +- .../libp2p/go-libp2p/p2p/host/blank/blank.go | 2 +- .../p2p/host/resource-manager/README.md | 4 +- .../p2p/host/resource-manager/extapi.go | 4 - .../go-libp2p/p2p/metricshelper/conn.go | 2 +- .../p2p/muxer/mplex}/conn.go | 0 .../p2p/muxer/mplex}/stream.go | 0 .../p2p/muxer/mplex}/transport.go | 2 - .../go-libp2p/p2p/net/connmgr/connmgr.go | 12 - .../libp2p/go-libp2p/p2p/net/connmgr/decay.go | 4 +- .../libp2p/go-libp2p/p2p/net/swarm/addrs.go | 39 + .../p2p/net/swarm/black_hole_detector.go | 7 +- .../go-libp2p/p2p/net/swarm/dial_error.go | 25 +- .../go-libp2p/p2p/net/swarm/dial_ranker.go | 105 +- .../go-libp2p/p2p/net/swarm/dial_sync.go | 46 +- .../go-libp2p/p2p/net/swarm/dial_worker.go | 145 +- .../libp2p/go-libp2p/p2p/net/swarm/limiter.go | 18 +- .../libp2p/go-libp2p/p2p/net/swarm/swarm.go | 149 +- .../go-libp2p/p2p/net/swarm/swarm_conn.go | 11 +- .../go-libp2p/p2p/net/swarm/swarm_dial.go | 203 +- .../go-libp2p/p2p/net/swarm/swarm_metrics.go | 24 +- .../go-libp2p/p2p/net/swarm/swarm_stream.go | 37 +- .../go-libp2p/p2p/net/upgrader/upgrader.go | 39 +- .../protocol/circuitv2/relay/constraints.go | 5 +- .../go-libp2p/p2p/protocol/identify/id.go | 2 +- .../p2p/protocol/identify/obsaddr.go | 13 +- .../go-libp2p/p2p/security/noise/handshake.go | 5 +- .../go-libp2p/p2p/security/tls/crypto.go | 3 +- .../go-libp2p/p2p/transport/quic/listener.go | 3 + .../go-libp2p/p2p/transport/quic/transport.go | 4 +- .../p2p/transport/quicreuse/config.go | 4 +- .../p2p/transport/quicreuse/connmgr.go | 76 +- .../p2p/transport/quicreuse/listener.go | 12 +- .../p2p/transport/quicreuse/options.go | 10 + .../p2p/transport/quicreuse/quic_multiaddr.go | 8 +- .../p2p/transport/quicreuse/reuse.go | 33 +- .../p2p/transport/quicreuse/tracer.go | 2 +- .../p2p/transport/quicreuse/tracer_metrics.go | 372 ++++ .../go-libp2p/p2p/transport/tcp/metrics.go | 2 +- .../p2p/transport/tcp/metrics_general.go | 2 +- .../{metrics_none.go => metrics_windows.go} | 4 +- .../libp2p/go-libp2p/p2p/transport/tcp/tcp.go | 16 +- .../p2p/transport/websocket/websocket.go | 4 +- .../p2p/transport/webtransport/multiaddr.go | 28 +- .../libp2p/go-libp2p/package-list.json | 82 + vendor/github.com/libp2p/go-libp2p/tools.go | 2 +- .../github.com/libp2p/go-libp2p/version.json | 2 +- .../libp2p/go-reuseport/control_freebsd.go | 27 - .../libp2p/go-reuseport/control_unix.go | 2 +- .../libp2p/go-reuseport/version.json | 2 +- .../github.com/mattn/go-isatty/isatty_bsd.go | 3 +- .../mattn/go-isatty/isatty_others.go | 5 +- .../mattn/go-isatty/isatty_tcgets.go | 3 +- vendor/github.com/miekg/dns/README.md | 1 - vendor/github.com/miekg/dns/defaults.go | 13 +- vendor/github.com/miekg/dns/msg.go | 33 +- vendor/github.com/miekg/dns/types.go | 10 +- vendor/github.com/miekg/dns/version.go | 2 +- .../multiformats/go-multiaddr/multiaddr.go | 2 +- .../multiformats/go-multiaddr/net/private.go | 67 +- .../multiformats/go-multiaddr/version.json | 2 +- .../multiformats/go-multistream/client.go | 213 ++ .../onsi/ginkgo/v2/ginkgo/outline/ginkgo.go | 4 +- .../github.com/onsi/ginkgo/v2/types/config.go | 1 - .../github.com/onsi/ginkgo/v2/types/errors.go | 4 +- .../github.com/onsi/ginkgo/v2/types/types.go | 4 +- .../onsi/ginkgo/v2/types/version.go | 2 +- .../runtime-spec/specs-go/config.go | 221 +- .../runtime-spec/specs-go/version.go | 6 +- vendor/github.com/pion/datachannel/.gitignore | 1 - .../github.com/pion/datachannel/.golangci.yml | 34 +- .../github.com/pion/datachannel/AUTHORS.txt | 1 - .../pion/datachannel/datachannel.go | 14 +- .../pion/datachannel/message_channel_open.go | 5 +- .../github.com/pion/datachannel/renovate.json | 3 +- vendor/github.com/pion/dtls/v2/.editorconfig | 2 - vendor/github.com/pion/dtls/v2/.gitignore | 4 - vendor/github.com/pion/dtls/v2/.golangci.yml | 60 +- .../github.com/pion/dtls/v2/.goreleaser.yml | 5 - vendor/github.com/pion/dtls/v2/AUTHORS.txt | 14 +- vendor/github.com/pion/dtls/v2/LICENSE | 20 +- vendor/github.com/pion/dtls/v2/Makefile | 6 + vendor/github.com/pion/dtls/v2/README.md | 47 +- vendor/github.com/pion/dtls/v2/certificate.go | 134 +- .../github.com/pion/dtls/v2/cipher_suite.go | 54 +- .../pion/dtls/v2/cipher_suite_go114.go | 3 - vendor/github.com/pion/dtls/v2/codecov.yml | 2 - .../pion/dtls/v2/compression_method.go | 3 - vendor/github.com/pion/dtls/v2/config.go | 54 +- vendor/github.com/pion/dtls/v2/conn.go | 120 +- vendor/github.com/pion/dtls/v2/crypto.go | 13 +- vendor/github.com/pion/dtls/v2/dtls.go | 3 - vendor/github.com/pion/dtls/v2/errors.go | 52 +- .../github.com/pion/dtls/v2/errors_errno.go | 14 +- .../github.com/pion/dtls/v2/errors_noerrno.go | 3 - vendor/github.com/pion/dtls/v2/flight.go | 3 - .../github.com/pion/dtls/v2/flight0handler.go | 25 +- .../github.com/pion/dtls/v2/flight1handler.go | 20 +- .../github.com/pion/dtls/v2/flight2handler.go | 7 +- .../github.com/pion/dtls/v2/flight3handler.go | 38 +- .../pion/dtls/v2/flight4bhandler.go | 9 +- .../github.com/pion/dtls/v2/flight4handler.go | 89 +- .../pion/dtls/v2/flight5bhandler.go | 9 +- .../github.com/pion/dtls/v2/flight5handler.go | 57 +- .../github.com/pion/dtls/v2/flight6handler.go | 9 +- .../github.com/pion/dtls/v2/flighthandler.go | 3 - .../pion/dtls/v2/fragment_buffer.go | 23 +- vendor/github.com/pion/dtls/v2/fuzz.go | 39 + .../pion/dtls/v2/handshake_cache.go | 23 +- vendor/github.com/pion/dtls/v2/handshaker.go | 10 - .../v2/internal/ciphersuite/aes_128_ccm.go | 105 +- .../v2/internal/ciphersuite/aes_256_ccm.go | 33 - .../dtls/v2/internal/ciphersuite/aes_ccm.go | 113 - .../v2/internal/ciphersuite/ciphersuite.go | 53 +- .../tls_ecdhe_ecdsa_with_aes_128_ccm.go | 5 +- .../tls_ecdhe_ecdsa_with_aes_128_ccm8.go | 5 +- ...tls_ecdhe_ecdsa_with_aes_128_gcm_sha256.go | 25 +- .../tls_ecdhe_ecdsa_with_aes_256_cbc_sha.go | 25 +- ...tls_ecdhe_ecdsa_with_aes_256_gcm_sha384.go | 3 - .../tls_ecdhe_psk_with_aes_128_cbc_sha256.go | 118 -- .../tls_ecdhe_rsa_with_aes_128_gcm_sha256.go | 3 - .../tls_ecdhe_rsa_with_aes_256_cbc_sha.go | 3 - .../tls_ecdhe_rsa_with_aes_256_gcm_sha384.go | 3 - .../tls_psk_with_aes_128_cbc_sha256.go | 27 +- .../ciphersuite/tls_psk_with_aes_128_ccm.go | 5 +- .../ciphersuite/tls_psk_with_aes_128_ccm8.go | 5 +- .../tls_psk_with_aes_128_gcm_sha256.go | 8 - .../ciphersuite/tls_psk_with_aes_256_ccm8.go | 14 - .../ciphersuite/types/authentication_type.go | 14 - .../types/key_exchange_algorithm.go | 20 - .../pion/dtls/v2/internal/closer/closer.go | 3 - .../pion/dtls/v2/internal/util/util.go | 3 - vendor/github.com/pion/dtls/v2/listener.go | 5 +- vendor/github.com/pion/dtls/v2/packet.go | 3 - .../pion/dtls/v2/pkg/crypto/ccm/ccm.go | 3 - .../dtls/v2/pkg/crypto/ciphersuite/cbc.go | 17 +- .../dtls/v2/pkg/crypto/ciphersuite/ccm.go | 5 +- .../v2/pkg/crypto/ciphersuite/ciphersuite.go | 4 - .../dtls/v2/pkg/crypto/ciphersuite/gcm.go | 5 +- .../clientcertificate/client_certificate.go | 5 +- .../dtls/v2/pkg/crypto/elliptic/elliptic.go | 18 +- .../v2/pkg/crypto/fingerprint/fingerprint.go | 3 - .../dtls/v2/pkg/crypto/fingerprint/hash.go | 6 +- .../pion/dtls/v2/pkg/crypto/hash/hash.go | 3 - .../pion/dtls/v2/pkg/crypto/prf/prf.go | 41 +- .../dtls/v2/pkg/crypto/signature/signature.go | 3 - .../v2/pkg/crypto/signaturehash/errors.go | 3 - .../pkg/crypto/signaturehash/signaturehash.go | 9 +- .../pion/dtls/v2/pkg/protocol/alert/alert.go | 3 - .../dtls/v2/pkg/protocol/application_data.go | 3 - .../v2/pkg/protocol/change_cipher_spec.go | 3 - .../v2/pkg/protocol/compression_method.go | 3 - .../pion/dtls/v2/pkg/protocol/content.go | 3 - .../pion/dtls/v2/pkg/protocol/errors.go | 11 +- .../dtls/v2/pkg/protocol/extension/alpn.go | 3 - .../dtls/v2/pkg/protocol/extension/errors.go | 3 - .../v2/pkg/protocol/extension/extension.go | 3 - .../protocol/extension/renegotiation_info.go | 3 - .../v2/pkg/protocol/extension/server_name.go | 3 - .../extension/srtp_protection_profile.go | 3 - .../extension/supported_elliptic_curves.go | 3 - .../extension/supported_point_formats.go | 3 - .../supported_signature_algorithms.go | 3 - .../protocol/extension/use_master_secret.go | 3 - .../v2/pkg/protocol/extension/use_srtp.go | 3 - .../v2/pkg/protocol/handshake/cipher_suite.go | 3 - .../dtls/v2/pkg/protocol/handshake/errors.go | 3 - .../v2/pkg/protocol/handshake/handshake.go | 10 +- .../dtls/v2/pkg/protocol/handshake/header.go | 3 - .../protocol/handshake/message_certificate.go | 3 - .../handshake/message_certificate_request.go | 50 +- .../handshake/message_certificate_verify.go | 3 - .../handshake/message_client_hello.go | 3 - .../handshake/message_client_key_exchange.go | 57 +- .../protocol/handshake/message_finished.go | 3 - .../handshake/message_hello_verify_request.go | 27 +- .../handshake/message_server_hello.go | 8 +- .../handshake/message_server_hello_done.go | 5 +- .../handshake/message_server_key_exchange.go | 51 +- .../dtls/v2/pkg/protocol/handshake/random.go | 3 - .../v2/pkg/protocol/recordlayer/errors.go | 3 - .../v2/pkg/protocol/recordlayer/header.go | 3 - .../pkg/protocol/recordlayer/recordlayer.go | 3 - .../pion/dtls/v2/pkg/protocol/version.go | 3 - vendor/github.com/pion/dtls/v2/renovate.json | 25 +- vendor/github.com/pion/dtls/v2/resume.go | 3 - vendor/github.com/pion/dtls/v2/session.go | 3 - .../pion/dtls/v2/srtp_protection_profile.go | 11 +- vendor/github.com/pion/dtls/v2/state.go | 33 +- vendor/github.com/pion/dtls/v2/util.go | 5 +- vendor/github.com/pion/ice/v2/.gitignore | 4 - vendor/github.com/pion/ice/v2/.golangci.yml | 60 +- vendor/github.com/pion/ice/v2/.goreleaser.yml | 5 - vendor/github.com/pion/ice/v2/AUTHORS.txt | 18 +- vendor/github.com/pion/ice/v2/LICENSE | 20 +- vendor/github.com/pion/ice/v2/README.md | 13 +- vendor/github.com/pion/ice/v2/addr.go | 71 - vendor/github.com/pion/ice/v2/agent.go | 309 +-- vendor/github.com/pion/ice/v2/agent_config.go | 51 +- .../github.com/pion/ice/v2/agent_handlers.go | 60 - vendor/github.com/pion/ice/v2/agent_stats.go | 17 +- vendor/github.com/pion/ice/v2/candidate.go | 3 - .../github.com/pion/ice/v2/candidate_base.go | 114 +- .../github.com/pion/ice/v2/candidate_host.go | 20 +- .../pion/ice/v2/candidate_peer_reflexive.go | 5 - .../github.com/pion/ice/v2/candidate_relay.go | 17 - .../pion/ice/v2/candidate_server_reflexive.go | 6 +- .../github.com/pion/ice/v2/candidatepair.go | 16 +- .../pion/ice/v2/candidatepair_state.go | 3 - .../pion/ice/v2/candidaterelatedaddress.go | 3 - .../github.com/pion/ice/v2/candidatetype.go | 3 - vendor/github.com/pion/ice/v2/codecov.yml | 2 - vendor/github.com/pion/ice/v2/context.go | 5 +- vendor/github.com/pion/ice/v2/errors.go | 30 +- .../pion/ice/v2/external_ip_mapper.go | 20 +- vendor/github.com/pion/ice/v2/gather.go | 500 ++--- vendor/github.com/pion/ice/v2/ice.go | 19 +- vendor/github.com/pion/ice/v2/icecontrol.go | 3 - .../pion/ice/v2/internal/atomic/atomic.go | 23 - .../pion/ice/v2/internal/fakenet/mock_conn.go | 23 - .../ice/v2/internal/fakenet/packet_conn.go | 29 - .../pion/ice/v2/internal/stun/stun.go | 72 - vendor/github.com/pion/ice/v2/mdns.go | 12 +- vendor/github.com/pion/ice/v2/net.go | 137 -- vendor/github.com/pion/ice/v2/networktype.go | 19 +- vendor/github.com/pion/ice/v2/priority.go | 3 - vendor/github.com/pion/ice/v2/rand.go | 3 - vendor/github.com/pion/ice/v2/renovate.json | 25 +- vendor/github.com/pion/ice/v2/role.go | 3 - vendor/github.com/pion/ice/v2/selection.go | 48 +- vendor/github.com/pion/ice/v2/stats.go | 7 +- vendor/github.com/pion/ice/v2/stun.go | 24 + vendor/github.com/pion/ice/v2/tcp_mux.go | 238 +-- .../github.com/pion/ice/v2/tcp_mux_multi.go | 81 - .../github.com/pion/ice/v2/tcp_packet_conn.go | 118 +- vendor/github.com/pion/ice/v2/tcptype.go | 5 +- vendor/github.com/pion/ice/v2/test_utils.go | 79 - vendor/github.com/pion/ice/v2/transport.go | 15 +- vendor/github.com/pion/ice/v2/udp_mux.go | 188 +- .../github.com/pion/ice/v2/udp_mux_multi.go | 228 -- .../pion/ice/v2/udp_mux_universal.go | 271 --- .../github.com/pion/ice/v2/udp_muxed_conn.go | 94 +- vendor/github.com/pion/ice/v2/url.go | 255 ++- vendor/github.com/pion/ice/v2/usecandidate.go | 3 - vendor/github.com/pion/ice/v2/util.go | 233 ++ vendor/github.com/pion/interceptor/.gitignore | 4 - .../github.com/pion/interceptor/.golangci.yml | 60 +- .../pion/interceptor/.goreleaser.yml | 5 - .../github.com/pion/interceptor/AUTHORS.txt | 16 +- vendor/github.com/pion/interceptor/LICENSE | 20 +- vendor/github.com/pion/interceptor/README.md | 22 +- .../github.com/pion/interceptor/attributes.go | 3 - vendor/github.com/pion/interceptor/chain.go | 3 - .../github.com/pion/interceptor/codecov.yml | 2 - vendor/github.com/pion/interceptor/errors.go | 7 +- .../pion/interceptor/interceptor.go | 4 +- .../pion/interceptor/internal/ntp/ntp.go | 30 - vendor/github.com/pion/interceptor/noop.go | 3 - .../pion/interceptor/pkg/nack/errors.go | 9 +- .../pkg/nack/generator_interceptor.go | 9 +- .../interceptor/pkg/nack/generator_option.go | 3 - .../pion/interceptor/pkg/nack/nack.go | 3 - .../pion/interceptor/pkg/nack/receive_log.go | 6 +- .../pkg/nack/responder_interceptor.go | 28 +- .../interceptor/pkg/nack/responder_option.go | 12 - .../interceptor/pkg/nack/retainable_packet.go | 31 +- .../pion/interceptor/pkg/nack/send_buffer.go | 3 - .../pkg/report/receiver_interceptor.go | 22 +- .../interceptor/pkg/report/receiver_option.go | 3 - .../interceptor/pkg/report/receiver_stream.go | 3 - .../pion/interceptor/pkg/report/report.go | 3 - .../pkg/report/sender_interceptor.go | 35 +- .../interceptor/pkg/report/sender_option.go | 3 - .../interceptor/pkg/report/sender_stream.go | 22 +- .../pkg/twcc/header_extension_interceptor.go | 11 +- .../pkg/twcc/sender_interceptor.go | 22 +- .../pion/interceptor/pkg/twcc/twcc.go | 12 +- .../github.com/pion/interceptor/registry.go | 3 - .../github.com/pion/interceptor/renovate.json | 25 +- .../github.com/pion/interceptor/streaminfo.go | 3 - vendor/github.com/pion/mdns/.gitignore | 1 - vendor/github.com/pion/mdns/.golangci.yml | 37 +- vendor/github.com/pion/mdns/.goreleaser.yml | 2 - vendor/github.com/pion/mdns/AUTHORS.txt | 17 - vendor/github.com/pion/mdns/README.md | 8 +- vendor/github.com/pion/mdns/conn.go | 95 +- vendor/github.com/pion/mdns/errors.go | 1 - vendor/github.com/pion/mdns/renovate.json | 13 +- vendor/github.com/pion/rtcp/.gitignore | 1 - vendor/github.com/pion/rtcp/.golangci.yml | 34 +- vendor/github.com/pion/rtcp/AUTHORS.txt | 1 - vendor/github.com/pion/rtcp/fuzz.go | 1 - vendor/github.com/pion/rtcp/header.go | 1 - vendor/github.com/pion/rtcp/packet.go | 2 - .../rtcp/rapid_resynchronization_request.go | 4 - vendor/github.com/pion/rtcp/rfc8888.go | 325 --- .../pion/rtcp/source_description.go | 23 +- vendor/github.com/pion/rtcp/util.go | 6 +- vendor/github.com/pion/rtp/.gitignore | 1 - vendor/github.com/pion/rtp/AUTHORS.txt | 2 - .../pion/rtp/abssendtimeextension.go | 2 +- .../pion/rtp/audiolevelextension.go | 2 +- .../github.com/pion/rtp/codecs/av1_packet.go | 158 -- vendor/github.com/pion/rtp/codecs/error.go | 3 - .../github.com/pion/rtp/codecs/g711_packet.go | 2 +- .../github.com/pion/rtp/codecs/h265_packet.go | 16 - .../github.com/pion/rtp/header_extension.go | 350 --- vendor/github.com/pion/rtp/packet.go | 31 +- vendor/github.com/pion/rtp/pkg/obu/leb128.go | 66 - vendor/github.com/pion/rtp/renovate.json | 3 +- .../pion/rtp/transportccextension.go | 2 +- vendor/github.com/pion/sctp/.gitignore | 1 - vendor/github.com/pion/sctp/.golangci.yml | 37 +- vendor/github.com/pion/sctp/.goreleaser.yml | 2 - vendor/github.com/pion/sctp/AUTHORS.txt | 11 +- vendor/github.com/pion/sctp/DESIGN.md | 20 + vendor/github.com/pion/sctp/README.md | 15 +- vendor/github.com/pion/sctp/association.go | 234 +- vendor/github.com/pion/sctp/chunk_abort.go | 27 +- .../github.com/pion/sctp/chunk_cookie_ack.go | 17 +- .../github.com/pion/sctp/chunk_cookie_echo.go | 23 +- vendor/github.com/pion/sctp/chunk_error.go | 49 +- .../github.com/pion/sctp/chunk_forward_tsn.go | 13 +- .../github.com/pion/sctp/chunk_heartbeat.go | 42 +- .../pion/sctp/chunk_heartbeat_ack.go | 38 +- vendor/github.com/pion/sctp/chunk_init.go | 53 +- vendor/github.com/pion/sctp/chunk_init_ack.go | 53 +- .../github.com/pion/sctp/chunk_init_common.go | 13 +- .../pion/sctp/chunk_payload_data.go | 63 +- vendor/github.com/pion/sctp/chunk_reconfig.go | 15 +- .../pion/sctp/chunk_selective_ack.go | 13 +- vendor/github.com/pion/sctp/chunk_shutdown.go | 9 +- .../pion/sctp/chunk_shutdown_ack.go | 7 +- .../pion/sctp/chunk_shutdown_complete.go | 7 +- vendor/github.com/pion/sctp/chunkheader.go | 31 +- vendor/github.com/pion/sctp/error_cause.go | 10 +- .../sctp/error_cause_protocol_violation.go | 35 +- .../sctp/error_cause_user_initiated_abort.go | 46 - vendor/github.com/pion/sctp/packet.go | 66 +- vendor/github.com/pion/sctp/param.go | 5 +- .../pion/sctp/param_outgoing_reset_request.go | 7 +- .../pion/sctp/param_reconfig_response.go | 7 +- .../sctp/param_requested_hmac_algorithm.go | 5 +- vendor/github.com/pion/sctp/paramheader.go | 17 +- vendor/github.com/pion/sctp/paramtype.go | 7 +- vendor/github.com/pion/sctp/pending_queue.go | 17 +- vendor/github.com/pion/sctp/renovate.json | 25 +- vendor/github.com/pion/sctp/stream.go | 173 +- vendor/github.com/pion/sctp/util.go | 4 +- vendor/github.com/pion/sdp/v3/.gitignore | 1 - vendor/github.com/pion/sdp/v3/.golangci.yml | 34 +- vendor/github.com/pion/sdp/v3/AUTHORS.txt | 32 - vendor/github.com/pion/sdp/v3/README.md | 24 + vendor/github.com/pion/sdp/v3/base_lexer.go | 14 +- vendor/github.com/pion/sdp/v3/jsep.go | 37 +- vendor/github.com/pion/sdp/v3/renovate.json | 14 +- vendor/github.com/pion/sdp/v3/unmarshal.go | 7 +- vendor/github.com/pion/sdp/v3/util.go | 12 +- vendor/github.com/pion/srtp/v2/.gitignore | 4 - vendor/github.com/pion/srtp/v2/.golangci.yml | 60 +- .../github.com/pion/srtp/v2/.goreleaser.yml | 5 - vendor/github.com/pion/srtp/v2/AUTHORS.txt | 14 +- vendor/github.com/pion/srtp/v2/DESIGN.md | 20 + vendor/github.com/pion/srtp/v2/LICENSE | 20 +- vendor/github.com/pion/srtp/v2/README.md | 13 +- vendor/github.com/pion/srtp/v2/codecov.yml | 2 - vendor/github.com/pion/srtp/v2/context.go | 49 +- vendor/github.com/pion/srtp/v2/crypto.go | 45 - vendor/github.com/pion/srtp/v2/errors.go | 11 +- .../github.com/pion/srtp/v2/key_derivation.go | 30 +- vendor/github.com/pion/srtp/v2/keying.go | 3 - vendor/github.com/pion/srtp/v2/option.go | 13 +- .../pion/srtp/v2/protection_profile.go | 49 +- vendor/github.com/pion/srtp/v2/renovate.json | 24 +- vendor/github.com/pion/srtp/v2/session.go | 25 +- .../github.com/pion/srtp/v2/session_srtcp.go | 30 +- .../github.com/pion/srtp/v2/session_srtp.go | 54 +- vendor/github.com/pion/srtp/v2/srtcp.go | 31 +- vendor/github.com/pion/srtp/v2/srtp.go | 32 +- vendor/github.com/pion/srtp/v2/srtp_cipher.go | 8 +- .../pion/srtp/v2/srtp_cipher_aead_aes_gcm.go | 67 +- .../srtp/v2/srtp_cipher_aes_cm_hmac_sha1.go | 84 +- vendor/github.com/pion/srtp/v2/stream.go | 3 - .../github.com/pion/srtp/v2/stream_srtcp.go | 11 +- vendor/github.com/pion/srtp/v2/stream_srtp.go | 11 +- vendor/github.com/pion/srtp/v2/util.go | 3 - vendor/github.com/pion/stun/.codecov.yml | 9 + vendor/github.com/pion/stun/.gitignore | 43 +- vendor/github.com/pion/stun/.golangci.yml | 198 +- vendor/github.com/pion/stun/.goreleaser.yml | 40 +- vendor/github.com/pion/stun/.travis.yml | 135 ++ vendor/github.com/pion/stun/AUTHORS | 10 + vendor/github.com/pion/stun/AUTHORS.txt | 40 - vendor/github.com/pion/stun/Dockerfile | 5 + .../pion/stun/{LICENSE => LICENSE.md} | 4 +- vendor/github.com/pion/stun/Makefile | 30 +- vendor/github.com/pion/stun/README.md | 196 +- vendor/github.com/pion/stun/addr.go | 45 +- vendor/github.com/pion/stun/agent.go | 9 +- vendor/github.com/pion/stun/appveyor.yml | 22 + vendor/github.com/pion/stun/attributes.go | 98 +- .../github.com/pion/stun/attributes_debug.go | 4 - vendor/github.com/pion/stun/checks.go | 14 +- vendor/github.com/pion/stun/checks_debug.go | 4 - vendor/github.com/pion/stun/client.go | 127 +- vendor/github.com/pion/stun/codecov.yml | 22 - vendor/github.com/pion/stun/errorcode.go | 6 +- vendor/github.com/pion/stun/errors.go | 6 +- vendor/github.com/pion/stun/fingerprint.go | 9 +- .../github.com/pion/stun/fingerprint_debug.go | 4 - vendor/github.com/pion/stun/fuzz.go | 140 ++ vendor/github.com/pion/stun/go.test.sh | 24 + vendor/github.com/pion/stun/helpers.go | 24 +- vendor/github.com/pion/stun/integrity.go | 12 +- .../github.com/pion/stun/integrity_debug.go | 4 - .../pion/stun/internal/hmac/hmac.go | 93 +- .../pion/stun/internal/hmac/pool.go | 50 +- .../pion/stun/internal/hmac/vendor.sh | 7 +- vendor/github.com/pion/stun/message.go | 74 +- vendor/github.com/pion/stun/renovate.json | 13 +- vendor/github.com/pion/stun/stun.go | 11 +- vendor/github.com/pion/stun/textattrs.go | 3 - vendor/github.com/pion/stun/uattrs.go | 3 - vendor/github.com/pion/stun/uri.go | 257 --- vendor/github.com/pion/stun/xor.go | 62 + vendor/github.com/pion/stun/xoraddr.go | 35 +- .../pion/transport/{v2 => }/AUTHORS.txt | 11 +- .../transport}/LICENSE | 12 +- .../transport/{v2 => }/connctx/connctx.go | 11 +- .../pion/transport/{v2 => }/connctx/pipe.go | 3 - .../transport/{v2 => }/deadline/deadline.go | 9 +- .../transport/{v2 => }/packetio/buffer.go | 66 +- .../transport/{v2 => }/packetio/errors.go | 3 - .../pion/transport/packetio/hardlimit.go | 5 + .../pion/transport/packetio/no_hardlimit.go | 5 + .../{v2 => }/replaydetector/fixedbig.go | 3 - .../{v2 => }/replaydetector/replaydetector.go | 5 +- .../pion/transport/v2/.goreleaser.yml | 5 - vendor/github.com/pion/transport/v2/LICENSE | 9 - vendor/github.com/pion/transport/v2/README.md | 34 - vendor/github.com/pion/transport/v2/net.go | 418 ---- .../pion/transport/v2/packetio/hardlimit.go | 9 - .../transport/v2/packetio/no_hardlimit.go | 9 - .../pion/transport/v2/renovate.json | 6 - .../pion/transport/v2/stdnet/net.go | 167 -- .../pion/transport/v2/utils/xor/xor_amd64.go | 29 - .../pion/transport/v2/utils/xor/xor_amd64.s | 56 - .../pion/transport/v2/utils/xor/xor_arm.go | 60 - .../pion/transport/v2/utils/xor/xor_arm.s | 116 - .../pion/transport/v2/utils/xor/xor_arm64.go | 31 - .../pion/transport/v2/utils/xor/xor_arm64.s | 69 - .../transport/v2/utils/xor/xor_generic.go | 78 - .../pion/transport/v2/utils/xor/xor_ppc64x.go | 29 - .../pion/transport/v2/utils/xor/xor_ppc64x.s | 87 - .../pion/transport/v2/vnet/.gitignore | 4 - .../github.com/pion/transport/v2/vnet/vnet.go | 5 - .../github.com/pion/transport/vnet/.gitignore | 1 + .../pion/transport/{v2 => }/vnet/README.md | 74 +- .../pion/transport/{v2 => }/vnet/chunk.go | 9 +- .../transport/{v2 => }/vnet/chunk_queue.go | 3 - .../pion/transport/{v2 => }/vnet/conn.go | 230 +- .../pion/transport/{v2 => }/vnet/conn_map.go | 15 +- .../transport/{v2 => }/vnet/delay_filter.go | 5 +- .../pion/transport/{v2 => }/vnet/errors.go | 3 - .../pion/transport/vnet/interface.go | 40 + .../transport/{v2 => }/vnet/loss_filter.go | 3 - .../pion/transport/{v2 => }/vnet/nat.go | 28 +- .../pion/transport/{v2 => }/vnet/net.go | 401 ++-- .../pion/transport/{v2 => }/vnet/resolver.go | 7 +- .../pion/transport/{v2 => }/vnet/router.go | 45 +- .../pion/transport/{v2 => }/vnet/tbf.go | 54 +- .../pion/transport/{v2 => }/vnet/udpproxy.go | 44 +- .../{v2 => }/vnet/udpproxy_direct.go | 12 +- vendor/github.com/pion/transport/vnet/vnet.go | 2 + vendor/github.com/pion/turn/v2/.gitignore | 1 - vendor/github.com/pion/turn/v2/.golangci.yml | 37 +- .../github.com/pion/turn/v2/.goreleaser.yml | 109 +- vendor/github.com/pion/turn/v2/AUTHORS.txt | 11 +- vendor/github.com/pion/turn/v2/FAQ.md | 17 - vendor/github.com/pion/turn/v2/README.md | 5 +- vendor/github.com/pion/turn/v2/client.go | 44 +- .../turn/v2/internal/allocation/allocation.go | 38 +- .../internal/allocation/allocation_manager.go | 18 - .../turn/v2/internal/allocation/errors.go | 1 - .../pion/turn/v2/internal/client/binding.go | 7 +- .../pion/turn/v2/internal/client/conn.go | 64 +- .../pion/turn/v2/internal/client/errors.go | 2 +- .../turn/v2/internal/client/transaction.go | 2 +- .../pion/turn/v2/internal/client/trylock.go | 2 +- .../pion/turn/v2/internal/ipnet/util.go | 2 +- .../pion/turn/v2/internal/proto/chandata.go | 2 +- .../turn/v2/internal/proto/connection_id.go | 39 - .../pion/turn/v2/internal/proto/dontfrag.go | 37 +- .../pion/turn/v2/internal/proto/fuzz.go | 111 + .../pion/turn/v2/internal/proto/reqtrans.go | 2 +- .../pion/turn/v2/internal/server/turn.go | 36 +- .../pion/turn/v2/internal/server/util.go | 9 +- vendor/github.com/pion/turn/v2/lt_cred.go | 2 +- .../turn/v2/relay_address_generator_none.go | 14 +- .../turn/v2/relay_address_generator_range.go | 23 +- .../turn/v2/relay_address_generator_static.go | 20 +- vendor/github.com/pion/turn/v2/renovate.json | 25 +- vendor/github.com/pion/turn/v2/server.go | 130 +- .../github.com/pion/turn/v2/server_config.go | 25 +- .../pion/{transport/v2 => udp}/.gitignore | 4 - .../pion/{transport/v2 => udp}/.golangci.yml | 60 +- vendor/github.com/pion/udp/LICENSE | 21 + vendor/github.com/pion/udp/README.md | 41 + .../pion/{transport/v2 => udp}/codecov.yml | 2 - .../pion/{transport/v2 => }/udp/conn.go | 53 +- vendor/github.com/pion/udp/renovate.json | 15 + vendor/github.com/pion/webrtc/v3/.codacy.yaml | 3 - vendor/github.com/pion/webrtc/v3/.gitignore | 4 - .../github.com/pion/webrtc/v3/.golangci.yml | 60 +- .../github.com/pion/webrtc/v3/.goreleaser.yml | 5 - vendor/github.com/pion/webrtc/v3/AUTHORS.txt | 40 +- vendor/github.com/pion/webrtc/v3/LICENSE | 20 +- vendor/github.com/pion/webrtc/v3/README.md | 17 +- vendor/github.com/pion/webrtc/v3/api.go | 5 - vendor/github.com/pion/webrtc/v3/api_js.go | 3 - .../github.com/pion/webrtc/v3/atomicbool.go | 5 +- .../github.com/pion/webrtc/v3/bundlepolicy.go | 3 - .../github.com/pion/webrtc/v3/certificate.go | 5 - vendor/github.com/pion/webrtc/v3/codecov.yml | 2 - .../pion/webrtc/v3/configuration.go | 3 - .../pion/webrtc/v3/configuration_common.go | 3 - .../pion/webrtc/v3/configuration_js.go | 3 - vendor/github.com/pion/webrtc/v3/constants.go | 5 +- .../github.com/pion/webrtc/v3/datachannel.go | 46 +- .../pion/webrtc/v3/datachannel_js.go | 3 - .../pion/webrtc/v3/datachannel_js_detach.go | 3 - .../pion/webrtc/v3/datachannelinit.go | 3 - .../pion/webrtc/v3/datachannelmessage.go | 3 - .../pion/webrtc/v3/datachannelparameters.go | 3 - .../pion/webrtc/v3/datachannelstate.go | 3 - .../pion/webrtc/v3/dtlsfingerprint.go | 3 - .../pion/webrtc/v3/dtlsparameters.go | 3 - vendor/github.com/pion/webrtc/v3/dtlsrole.go | 3 - .../pion/webrtc/v3/dtlstransport.go | 46 +- .../pion/webrtc/v3/dtlstransport_js.go | 3 - .../pion/webrtc/v3/dtlstransportstate.go | 3 - vendor/github.com/pion/webrtc/v3/errors.go | 23 +- .../webrtc/v3/gathering_complete_promise.go | 3 - vendor/github.com/pion/webrtc/v3/ice_go.go | 3 - .../github.com/pion/webrtc/v3/icecandidate.go | 3 - .../pion/webrtc/v3/icecandidateinit.go | 3 - .../pion/webrtc/v3/icecandidatepair.go | 3 - .../pion/webrtc/v3/icecandidatetype.go | 3 - .../github.com/pion/webrtc/v3/icecomponent.go | 3 - .../pion/webrtc/v3/iceconnectionstate.go | 3 - .../pion/webrtc/v3/icecredentialtype.go | 37 +- .../github.com/pion/webrtc/v3/icegatherer.go | 40 +- .../pion/webrtc/v3/icegathererstate.go | 3 - .../pion/webrtc/v3/icegatheringstate.go | 3 - .../pion/webrtc/v3/icegatheroptions.go | 3 - vendor/github.com/pion/webrtc/v3/icemux.go | 3 - .../pion/webrtc/v3/iceparameters.go | 3 - .../github.com/pion/webrtc/v3/iceprotocol.go | 3 - vendor/github.com/pion/webrtc/v3/icerole.go | 3 - vendor/github.com/pion/webrtc/v3/iceserver.go | 125 +- .../github.com/pion/webrtc/v3/iceserver_js.go | 3 - .../github.com/pion/webrtc/v3/icetransport.go | 27 +- .../pion/webrtc/v3/icetransport_js.go | 3 - .../pion/webrtc/v3/icetransportpolicy.go | 3 - .../pion/webrtc/v3/icetransportstate.go | 3 - .../github.com/pion/webrtc/v3/interceptor.go | 9 +- .../pion/webrtc/v3/internal/fmtp/fmtp.go | 5 +- .../pion/webrtc/v3/internal/fmtp/h264.go | 24 +- .../pion/webrtc/v3/internal/mux/endpoint.go | 11 +- .../pion/webrtc/v3/internal/mux/mux.go | 28 +- .../pion/webrtc/v3/internal/mux/muxfunc.go | 5 +- .../pion/webrtc/v3/internal/util/util.go | 7 +- vendor/github.com/pion/webrtc/v3/js_utils.go | 3 - .../github.com/pion/webrtc/v3/mediaengine.go | 40 +- .../github.com/pion/webrtc/v3/networktype.go | 3 - .../pion/webrtc/v3/oauthcredential.go | 3 - .../pion/webrtc/v3/offeransweroptions.go | 3 - .../github.com/pion/webrtc/v3/operations.go | 8 +- .../pion/webrtc/v3/peerconnection.go | 265 +-- .../pion/webrtc/v3/peerconnection_js.go | 62 +- .../pion/webrtc/v3/peerconnectionstate.go | 3 - .../pion/webrtc/v3/pkg/media/media.go | 3 - .../pion/webrtc/v3/pkg/rtcerr/errors.go | 3 - .../github.com/pion/webrtc/v3/renovate.json | 25 +- .../github.com/pion/webrtc/v3/rtcpfeedback.go | 3 - .../pion/webrtc/v3/rtcpmuxpolicy.go | 3 - .../pion/webrtc/v3/rtpcapabilities.go | 3 - vendor/github.com/pion/webrtc/v3/rtpcodec.go | 3 - .../pion/webrtc/v3/rtpcodingparameters.go | 3 - .../pion/webrtc/v3/rtpdecodingparameters.go | 3 - .../pion/webrtc/v3/rtpencodingparameters.go | 3 - .../pion/webrtc/v3/rtpreceiveparameters.go | 3 - .../github.com/pion/webrtc/v3/rtpreceiver.go | 8 +- .../pion/webrtc/v3/rtpreceiver_go.go | 3 - .../pion/webrtc/v3/rtpreceiver_js.go | 3 - vendor/github.com/pion/webrtc/v3/rtpsender.go | 264 +-- .../github.com/pion/webrtc/v3/rtpsender_js.go | 3 - .../pion/webrtc/v3/rtpsendparameters.go | 3 - .../pion/webrtc/v3/rtptransceiver.go | 46 +- .../pion/webrtc/v3/rtptransceiver_js.go | 3 - .../pion/webrtc/v3/rtptransceiverdirection.go | 9 +- .../pion/webrtc/v3/rtptransceiverinit.go | 3 - .../pion/webrtc/v3/sctpcapabilities.go | 3 - .../pion/webrtc/v3/sctptransport.go | 15 +- .../pion/webrtc/v3/sctptransport_js.go | 3 - .../pion/webrtc/v3/sctptransportstate.go | 3 - vendor/github.com/pion/webrtc/v3/sdp.go | 132 +- .../github.com/pion/webrtc/v3/sdpsemantics.go | 3 - vendor/github.com/pion/webrtc/v3/sdptype.go | 3 - .../pion/webrtc/v3/sessiondescription.go | 3 - .../pion/webrtc/v3/settingengine.go | 163 +- .../pion/webrtc/v3/settingengine_js.go | 3 - .../pion/webrtc/v3/signalingstate.go | 3 - .../pion/webrtc/v3/srtp_writer_future.go | 26 +- vendor/github.com/pion/webrtc/v3/stats.go | 3 - vendor/github.com/pion/webrtc/v3/stats_go.go | 3 - .../github.com/pion/webrtc/v3/track_local.go | 22 +- .../pion/webrtc/v3/track_local_static.go | 37 +- .../github.com/pion/webrtc/v3/track_remote.go | 3 - vendor/github.com/pion/webrtc/v3/webrtc.go | 3 - vendor/github.com/pion/webrtc/v3/yarn.lock | 2 - vendor/github.com/quic-go/qtls-go1-19/LICENSE | 27 + .../github.com/quic-go/qtls-go1-19/README.md | 6 + .../github.com/quic-go/qtls-go1-19/alert.go | 102 + vendor/github.com/quic-go/qtls-go1-19/auth.go | 293 +++ .../quic-go/qtls-go1-19/cipher_suites.go | 693 ++++++ .../github.com/quic-go/qtls-go1-19/common.go | 1513 +++++++++++++ vendor/github.com/quic-go/qtls-go1-19/conn.go | 1649 +++++++++++++++ vendor/github.com/quic-go/qtls-go1-19/cpu.go | 22 + .../quic-go/qtls-go1-19/cpu_other.go | 12 + .../quic-go/qtls-go1-19/handshake_client.go | 1131 ++++++++++ .../qtls-go1-19/handshake_client_tls13.go | 755 +++++++ .../quic-go/qtls-go1-19/handshake_messages.go | 1875 +++++++++++++++++ .../quic-go/qtls-go1-19/handshake_server.go | 926 ++++++++ .../qtls-go1-19/handshake_server_tls13.go | 903 ++++++++ .../quic-go/qtls-go1-19/key_agreement.go | 357 ++++ .../quic-go/qtls-go1-19/key_schedule.go | 216 ++ .../quic-go/qtls-go1-19/notboring.go | 18 + vendor/github.com/quic-go/qtls-go1-19/prf.go | 283 +++ .../github.com/quic-go/qtls-go1-19/ticket.go | 277 +++ vendor/github.com/quic-go/qtls-go1-19/tls.go | 362 ++++ .../github.com/quic-go/qtls-go1-19/unsafe.go | 96 + .../github.com/quic-go/qtls-go1-20/alert.go | 13 +- .../quic-go/qtls-go1-20/cipher_suites.go | 30 +- .../github.com/quic-go/qtls-go1-20/common.go | 104 +- vendor/github.com/quic-go/qtls-go1-20/conn.go | 225 +- vendor/github.com/quic-go/qtls-go1-20/cpu.go | 22 + .../quic-go/qtls-go1-20/cpu_other.go | 12 + .../quic-go/qtls-go1-20/handshake_client.go | 124 +- .../qtls-go1-20/handshake_client_tls13.go | 86 +- .../quic-go/qtls-go1-20/handshake_messages.go | 51 +- .../quic-go/qtls-go1-20/handshake_server.go | 38 +- .../qtls-go1-20/handshake_server_tls13.go | 170 +- .../quic-go/qtls-go1-20/key_schedule.go | 1 - vendor/github.com/quic-go/qtls-go1-20/quic.go | 418 ---- .../github.com/quic-go/qtls-go1-20/ticket.go | 76 +- vendor/github.com/quic-go/qtls-go1-20/tls.go | 44 +- .../github.com/quic-go/qtls-go1-20/unsafe.go | 5 - .../github.com/quic-go/quic-go/.golangci.yml | 2 - vendor/github.com/quic-go/quic-go/README.md | 15 +- vendor/github.com/quic-go/quic-go/client.go | 22 +- vendor/github.com/quic-go/quic-go/codecov.yml | 10 +- vendor/github.com/quic-go/quic-go/config.go | 52 +- .../quic-go/quic-go/conn_id_manager.go | 10 +- .../github.com/quic-go/quic-go/connection.go | 499 ++--- .../quic-go/quic-go/crypto_stream.go | 14 +- .../quic-go/quic-go/crypto_stream_manager.go | 35 +- .../quic-go/quic-go/datagram_queue.go | 5 +- vendor/github.com/quic-go/quic-go/framer.go | 37 +- .../github.com/quic-go/quic-go/http3/body.go | 5 +- .../quic-go/quic-go/http3/client.go | 105 +- .../github.com/quic-go/quic-go/http3/error.go | 58 - .../quic-go/quic-go/http3/error_codes.go | 12 +- .../quic-go/quic-go/http3/frames.go | 2 +- .../quic-go/quic-go/http3/headers.go | 198 -- .../quic-go/quic-go/http3/http_stream.go | 48 - .../quic-go/quic-go/http3/mockgen.go | 4 +- .../quic-go/quic-go/http3/request.go | 111 + .../quic-go/quic-go/http3/response_writer.go | 141 +- .../quic-go/quic-go/http3/roundtrip.go | 2 +- .../quic-go/quic-go/http3/server.go | 43 +- .../github.com/quic-go/quic-go/interface.go | 35 +- .../quic-go/internal/ackhandler/ackhandler.go | 5 +- .../quic-go/internal/ackhandler/ecn.go | 296 --- .../quic-go/internal/ackhandler/interfaces.go | 9 +- .../quic-go/internal/ackhandler/mockgen.go | 5 +- .../ackhandler/received_packet_handler.go | 15 +- .../ackhandler/received_packet_tracker.go | 46 +- .../ackhandler/sent_packet_handler.go | 117 +- .../internal/congestion/cubic_sender.go | 12 +- .../quic-go/internal/congestion/interface.go | 2 +- .../quic-go/internal/handshake/aead.go | 69 +- .../internal/handshake/cipher_suite.go | 104 - .../quic-go/internal/handshake/conn.go | 21 - .../internal/handshake/crypto_setup.go | 694 +++--- .../internal/handshake/header_protector.go | 7 +- .../internal/handshake/initial_aead.go | 22 +- .../quic-go/internal/handshake/interface.go | 54 +- .../quic-go/internal/handshake/mockgen.go | 6 + .../quic-go/internal/handshake/retry.go | 25 +- .../internal/handshake/session_ticket.go | 19 +- .../handshake/tls_extension_handler.go | 68 + .../internal/handshake/token_generator.go | 13 +- .../internal/handshake/token_protector.go | 33 +- .../internal/handshake/updatable_aead.go | 21 +- .../quic-go/internal/protocol/params.go | 6 + .../quic-go/internal/protocol/protocol.go | 57 +- .../quic-go/internal/protocol/version.go | 6 +- .../quic-go/internal/qerr/error_codes.go | 2 +- .../quic-go/quic-go/internal/qerr/errors.go | 14 +- .../internal/qtls/cipher_suite_go121.go | 66 - .../internal/qtls/client_session_cache.go | 61 - .../quic-go/quic-go/internal/qtls/go119.go | 145 ++ .../quic-go/quic-go/internal/qtls/go120.go | 144 +- .../quic-go/quic-go/internal/qtls/go121.go | 156 +- .../quic-go/internal/qtls/go_oldversion.go | 2 +- .../quic-go/quic-go/internal/wire/header.go | 6 +- .../internal/wire/transport_parameters.go | 22 - .../internal/wire/version_negotiation.go | 5 +- .../quic-go/logging/connection_tracer.go | 255 --- .../quic-go/quic-go/logging/interface.go | 58 +- .../quic-go/quic-go/logging/mockgen.go | 4 + .../quic-go/quic-go/logging/multiplex.go | 226 ++ .../quic-go/quic-go/logging/null_tracer.go | 58 + .../quic-go/quic-go/logging/tracer.go | 43 - .../quic-go/quic-go/logging/types.go | 34 - vendor/github.com/quic-go/quic-go/mockgen.go | 52 +- vendor/github.com/quic-go/quic-go/oss-fuzz.sh | 42 - .../quic-go/quic-go/packet_handler_map.go | 17 +- .../quic-go/quic-go/packet_packer.go | 29 +- .../github.com/quic-go/quic-go/qlog/event.go | 22 - .../github.com/quic-go/quic-go/qlog/qlog.go | 134 +- .../github.com/quic-go/quic-go/qlog/types.go | 58 - .../github.com/quic-go/quic-go/send_conn.go | 95 +- .../github.com/quic-go/quic-go/send_queue.go | 15 +- .../github.com/quic-go/quic-go/send_stream.go | 10 +- vendor/github.com/quic-go/quic-go/server.go | 114 +- vendor/github.com/quic-go/quic-go/sys_conn.go | 32 +- .../github.com/quic-go/quic-go/sys_conn_df.go | 9 +- .../quic-go/quic-go/sys_conn_df_darwin.go | 74 - .../quic-go/quic-go/sys_conn_df_linux.go | 45 +- .../quic-go/quic-go/sys_conn_df_windows.go | 7 +- .../quic-go/quic-go/sys_conn_helper_darwin.go | 31 +- .../quic-go/sys_conn_helper_freebsd.go | 30 +- .../quic-go/quic-go/sys_conn_helper_linux.go | 72 +- .../quic-go/sys_conn_helper_nonlinux.go | 3 - .../quic-go/quic-go/sys_conn_no_gso.go | 8 + .../quic-go/quic-go/sys_conn_oob.go | 134 +- vendor/github.com/quic-go/quic-go/tools.go | 2 +- .../github.com/quic-go/quic-go/transport.go | 244 +-- .../quic-go/webtransport-go/client.go | 2 +- .../quic-go/webtransport-go/errors.go | 4 +- .../quic-go/webtransport-go/version.json | 2 +- .../status-im/rendezvous/server/server.go | 2 +- .../waku-org/go-libp2p-rendezvous/svc.go | 2 +- .../go-waku/waku/v2/node/wakunode2.go | 13 +- .../go-waku/waku/v2/node/wakuoptions.go | 40 +- .../waku/v2/peermanager/connection_gater.go | 22 +- .../go-waku/waku/v2/protocol/enr/enr.go | 2 +- .../go-waku/waku/v2/protocol/filter/client.go | 2 +- .../waku/v2/protocol/filter/pb/validation.go | 4 +- .../waku/v2/protocol/relay/subscription.go | 2 +- .../waku/v2/protocol/rln/waku_rln_relay.go | 9 +- .../waku-org/go-waku/waku/v2/rendezvous/db.go | 6 +- .../go-waku/waku/v2/utils/multiaddr.go | 25 +- vendor/go.uber.org/dig/CHANGELOG.md | 17 +- vendor/go.uber.org/dig/constructor.go | 5 - vendor/go.uber.org/dig/doc.go | 2 +- vendor/go.uber.org/dig/error.go | 22 - vendor/go.uber.org/dig/param.go | 2 +- vendor/go.uber.org/dig/scope.go | 7 +- vendor/go.uber.org/dig/version.go | 2 +- vendor/go.uber.org/fx/CHANGELOG.md | 7 - vendor/go.uber.org/fx/app.go | 3 +- vendor/go.uber.org/fx/app_wasm.go | 4 +- vendor/go.uber.org/fx/fxevent/event.go | 12 - vendor/go.uber.org/fx/fxevent/zap.go | 8 - vendor/go.uber.org/fx/module.go | 27 +- vendor/go.uber.org/fx/version.go | 2 +- vendor/go.uber.org/mock/AUTHORS | 12 - vendor/go.uber.org/mock/CONTRIBUTORS | 37 - vendor/go.uber.org/mock/LICENSE | 202 -- .../go.uber.org/mock/mockgen/generic_go118.go | 116 - .../mock/mockgen/generic_notgo118.go | 41 - vendor/go.uber.org/zap/.golangci.yml | 77 - vendor/go.uber.org/zap/CHANGELOG.md | 242 +-- vendor/go.uber.org/zap/Makefile | 83 +- vendor/go.uber.org/zap/README.md | 62 +- vendor/go.uber.org/zap/array.go | 127 -- vendor/go.uber.org/zap/array_go118.go | 156 ++ vendor/go.uber.org/zap/buffer/buffer.go | 5 - vendor/go.uber.org/zap/buffer/pool.go | 20 +- vendor/go.uber.org/zap/config.go | 84 +- vendor/go.uber.org/zap/error.go | 14 +- vendor/go.uber.org/zap/field.go | 194 +- vendor/go.uber.org/zap/http_handler.go | 19 +- .../go.uber.org/zap/internal/level_enabler.go | 2 - vendor/go.uber.org/zap/internal/pool/pool.go | 58 - vendor/go.uber.org/zap/level.go | 9 +- vendor/go.uber.org/zap/logger.go | 48 +- vendor/go.uber.org/zap/sink.go | 5 +- .../stacktrace/stack.go => stacktrace.go} | 81 +- vendor/go.uber.org/zap/sugar.go | 69 +- vendor/go.uber.org/zap/writer.go | 12 +- .../zap/zapcore/console_encoder.go | 14 +- vendor/go.uber.org/zap/zapcore/core.go | 6 +- vendor/go.uber.org/zap/zapcore/entry.go | 22 +- vendor/go.uber.org/zap/zapcore/error.go | 14 +- .../go.uber.org/zap/zapcore/json_encoder.go | 159 +- vendor/go.uber.org/zap/zapcore/lazy_with.go | 54 - vendor/go.uber.org/zap/zapcore/sampler.go | 9 +- .../x/crypto/chacha20/chacha_arm64.go | 4 +- .../x/crypto/chacha20/chacha_arm64.s | 4 +- .../x/crypto/chacha20/chacha_noasm.go | 4 +- .../golang.org/x/crypto/cryptobyte/builder.go | 5 - .../golang.org/x/crypto/cryptobyte/string.go | 11 - vendor/golang.org/x/crypto/sha3/sha3.go | 14 +- vendor/golang.org/x/crypto/sha3/sha3_s390x.go | 10 +- vendor/golang.org/x/crypto/sha3/shake.go | 29 +- vendor/golang.org/x/exp/rand/exp.go | 221 -- vendor/golang.org/x/exp/rand/normal.go | 156 -- vendor/golang.org/x/exp/rand/rand.go | 372 ---- vendor/golang.org/x/exp/rand/rng.go | 91 - vendor/golang.org/x/exp/rand/zipf.go | 77 - vendor/golang.org/x/exp/slices/cmp.go | 44 - vendor/golang.org/x/exp/slices/slices.go | 353 +--- vendor/golang.org/x/exp/slices/sort.go | 115 +- .../slices/{zsortanyfunc.go => zsortfunc.go} | 154 +- .../golang.org/x/exp/slices/zsortordered.go | 34 +- vendor/golang.org/x/mod/modfile/rule.go | 4 +- .../x/net/dns/dnsmessage/message.go | 131 +- .../x/net/publicsuffix/data/children | Bin 2976 -> 2876 bytes .../golang.org/x/net/publicsuffix/data/nodes | Bin 46610 -> 48280 bytes .../golang.org/x/net/publicsuffix/data/text | 2 +- vendor/golang.org/x/net/publicsuffix/table.go | 14 +- .../x/sync/singleflight/singleflight.go | 9 - vendor/golang.org/x/sys/cpu/cpu.go | 5 +- vendor/golang.org/x/sys/cpu/cpu_riscv64.go | 2 +- vendor/golang.org/x/sys/cpu/cpu_x86.go | 7 - vendor/golang.org/x/sys/cpu/hwcap_linux.go | 4 +- .../sys/internal/unsafeheader/unsafeheader.go | 30 + vendor/golang.org/x/sys/unix/mkerrors.sh | 1 - vendor/golang.org/x/sys/unix/ptrace_darwin.go | 6 + vendor/golang.org/x/sys/unix/ptrace_ios.go | 6 + vendor/golang.org/x/sys/unix/syscall_aix.go | 2 + .../golang.org/x/sys/unix/syscall_darwin.go | 186 ++ .../x/sys/unix/syscall_darwin_amd64.go | 1 + .../x/sys/unix/syscall_darwin_arm64.go | 1 + .../x/sys/unix/syscall_dragonfly.go | 198 ++ .../golang.org/x/sys/unix/syscall_freebsd.go | 192 ++ vendor/golang.org/x/sys/unix/syscall_linux.go | 136 +- .../golang.org/x/sys/unix/syscall_netbsd.go | 261 +++ .../golang.org/x/sys/unix/syscall_openbsd.go | 74 + .../golang.org/x/sys/unix/syscall_solaris.go | 18 + vendor/golang.org/x/sys/unix/syscall_unix.go | 3 - .../x/sys/unix/syscall_zos_s390x.go | 1 + vendor/golang.org/x/sys/unix/zerrors_linux.go | 26 - .../x/sys/unix/zerrors_linux_386.go | 2 - .../x/sys/unix/zerrors_linux_amd64.go | 2 - .../x/sys/unix/zerrors_linux_arm.go | 2 - .../x/sys/unix/zerrors_linux_arm64.go | 2 - .../x/sys/unix/zerrors_linux_loong64.go | 4 - .../x/sys/unix/zerrors_linux_mips.go | 2 - .../x/sys/unix/zerrors_linux_mips64.go | 2 - .../x/sys/unix/zerrors_linux_mips64le.go | 2 - .../x/sys/unix/zerrors_linux_mipsle.go | 2 - .../x/sys/unix/zerrors_linux_ppc.go | 2 - .../x/sys/unix/zerrors_linux_ppc64.go | 2 - .../x/sys/unix/zerrors_linux_ppc64le.go | 2 - .../x/sys/unix/zerrors_linux_riscv64.go | 2 - .../x/sys/unix/zerrors_linux_s390x.go | 2 - .../x/sys/unix/zerrors_linux_sparc64.go | 2 - .../golang.org/x/sys/unix/zsyscall_aix_ppc.go | 22 + .../x/sys/unix/zsyscall_aix_ppc64.go | 22 + .../x/sys/unix/zsyscall_darwin_amd64.go | 40 +- .../x/sys/unix/zsyscall_darwin_amd64.s | 149 ++ .../x/sys/unix/zsyscall_darwin_arm64.go | 40 +- .../x/sys/unix/zsyscall_darwin_arm64.s | 149 ++ .../x/sys/unix/zsyscall_dragonfly_amd64.go | 22 + .../x/sys/unix/zsyscall_freebsd_386.go | 22 + .../x/sys/unix/zsyscall_freebsd_amd64.go | 22 + .../x/sys/unix/zsyscall_freebsd_arm.go | 22 + .../x/sys/unix/zsyscall_freebsd_arm64.go | 22 + .../x/sys/unix/zsyscall_freebsd_riscv64.go | 22 + .../x/sys/unix/zsyscall_illumos_amd64.go | 10 +- .../golang.org/x/sys/unix/zsyscall_linux.go | 42 +- .../x/sys/unix/zsyscall_netbsd_386.go | 22 + .../x/sys/unix/zsyscall_netbsd_amd64.go | 22 + .../x/sys/unix/zsyscall_netbsd_arm.go | 22 + .../x/sys/unix/zsyscall_netbsd_arm64.go | 22 + .../x/sys/unix/zsyscall_openbsd_386.go | 32 +- .../x/sys/unix/zsyscall_openbsd_amd64.go | 22 + .../x/sys/unix/zsyscall_openbsd_arm.go | 32 +- .../x/sys/unix/zsyscall_openbsd_arm64.go | 32 +- .../x/sys/unix/zsyscall_openbsd_mips64.go | 32 +- .../x/sys/unix/zsyscall_openbsd_ppc64.go | 32 +- .../x/sys/unix/zsyscall_openbsd_riscv64.go | 32 +- .../x/sys/unix/zsyscall_solaris_amd64.go | 256 +-- .../x/sys/unix/zsyscall_zos_s390x.go | 11 + .../x/sys/unix/zsysnum_linux_386.go | 1 - .../x/sys/unix/zsysnum_linux_amd64.go | 1 - .../x/sys/unix/zsysnum_linux_arm.go | 1 - .../x/sys/unix/zsysnum_linux_arm64.go | 1 - .../x/sys/unix/zsysnum_linux_loong64.go | 1 - .../x/sys/unix/zsysnum_linux_mips.go | 1 - .../x/sys/unix/zsysnum_linux_mips64.go | 1 - .../x/sys/unix/zsysnum_linux_mips64le.go | 1 - .../x/sys/unix/zsysnum_linux_mipsle.go | 1 - .../x/sys/unix/zsysnum_linux_ppc.go | 1 - .../x/sys/unix/zsysnum_linux_ppc64.go | 1 - .../x/sys/unix/zsysnum_linux_ppc64le.go | 1 - .../x/sys/unix/zsysnum_linux_riscv64.go | 1 - .../x/sys/unix/zsysnum_linux_s390x.go | 1 - .../x/sys/unix/zsysnum_linux_sparc64.go | 1 - vendor/golang.org/x/sys/unix/ztypes_linux.go | 23 +- .../x/sys/unix/ztypes_linux_riscv64.go | 4 - .../golang.org/x/sys/windows/exec_windows.go | 89 +- .../x/sys/windows/security_windows.go | 21 +- .../x/sys/windows/syscall_windows.go | 53 +- .../golang.org/x/sys/windows/types_windows.go | 7 - .../x/sys/windows/zsyscall_windows.go | 54 +- vendor/golang.org/x/text/unicode/norm/trie.go | 2 +- .../x/tools/cmd/goimports/goimports.go | 7 +- vendor/golang.org/x/tools/go/packages/doc.go | 2 +- .../golang.org/x/tools/go/packages/golist.go | 7 +- .../x/tools/go/packages/packages.go | 3 +- vendor/golang.org/x/tools/imports/forward.go | 4 +- .../internal/fastwalk/fastwalk_portable.go | 11 +- .../x/tools/internal/gcimporter/gcimporter.go | 3 +- .../x/tools/internal/imports/fix.go | 7 +- .../x/tools/internal/imports/mod.go | 5 +- vendor/golang.org/x/xerrors/LICENSE | 27 + vendor/golang.org/x/xerrors/PATENTS | 22 + vendor/golang.org/x/xerrors/README | 2 + vendor/golang.org/x/xerrors/adaptor.go | 193 ++ vendor/golang.org/x/xerrors/codereview.cfg | 1 + vendor/golang.org/x/xerrors/doc.go | 23 + vendor/golang.org/x/xerrors/errors.go | 33 + vendor/golang.org/x/xerrors/fmt.go | 190 ++ vendor/golang.org/x/xerrors/format.go | 34 + vendor/golang.org/x/xerrors/frame.go | 56 + .../golang.org/x/xerrors/internal/internal.go | 8 + vendor/golang.org/x/xerrors/wrap.go | 112 + vendor/modules.txt | 158 +- wakuv2/waku.go | 4 +- 1043 files changed, 25486 insertions(+), 23086 deletions(-) rename vendor/{go.uber.org => github.com/golang}/mock/mockgen/mockgen.go (64%) rename vendor/{go.uber.org => github.com/golang}/mock/mockgen/model/model.go (87%) rename vendor/{go.uber.org => github.com/golang}/mock/mockgen/parse.go (63%) rename vendor/{go.uber.org => github.com/golang}/mock/mockgen/reflect.go (93%) create mode 100644 vendor/github.com/golang/mock/mockgen/version.1.11.go rename vendor/{go.uber.org/mock/mockgen/version.go => github.com/golang/mock/mockgen/version.1.12.go} (94%) create mode 100644 vendor/github.com/hashicorp/golang-lru/v2/arc.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/v2/internal/list.go create mode 100644 vendor/github.com/hashicorp/golang-lru/v2/simplelru/list.go create mode 100644 vendor/github.com/hashicorp/golang-lru/v2/testing.go delete mode 100644 vendor/github.com/libp2p/go-libp2p-mplex/.gitignore delete mode 100644 vendor/github.com/libp2p/go-libp2p-mplex/README.md delete mode 100644 vendor/github.com/libp2p/go-libp2p-mplex/version.json rename vendor/github.com/libp2p/go-libp2p/config/{quic.go => quic_stateless_reset.go} (53%) delete mode 100644 vendor/github.com/libp2p/go-libp2p/internal/sha256/post_go1_21.go delete mode 100644 vendor/github.com/libp2p/go-libp2p/internal/sha256/pre_go1_21.go rename vendor/github.com/libp2p/{go-libp2p-mplex => go-libp2p/p2p/muxer/mplex}/conn.go (100%) rename vendor/github.com/libp2p/{go-libp2p-mplex => go-libp2p/p2p/muxer/mplex}/stream.go (100%) rename vendor/github.com/libp2p/{go-libp2p-mplex => go-libp2p/p2p/muxer/mplex}/transport.go (81%) create mode 100644 vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/addrs.go create mode 100644 vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/tracer_metrics.go rename vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/{metrics_none.go => metrics_windows.go} (71%) create mode 100644 vendor/github.com/libp2p/go-libp2p/package-list.json delete mode 100644 vendor/github.com/libp2p/go-reuseport/control_freebsd.go delete mode 100644 vendor/github.com/pion/dtls/v2/.goreleaser.yml create mode 100644 vendor/github.com/pion/dtls/v2/Makefile create mode 100644 vendor/github.com/pion/dtls/v2/fuzz.go delete mode 100644 vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_256_ccm.go delete mode 100644 vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_ccm.go delete mode 100644 vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_psk_with_aes_128_cbc_sha256.go delete mode 100644 vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_256_ccm8.go delete mode 100644 vendor/github.com/pion/dtls/v2/internal/ciphersuite/types/authentication_type.go delete mode 100644 vendor/github.com/pion/dtls/v2/internal/ciphersuite/types/key_exchange_algorithm.go delete mode 100644 vendor/github.com/pion/ice/v2/.goreleaser.yml delete mode 100644 vendor/github.com/pion/ice/v2/addr.go delete mode 100644 vendor/github.com/pion/ice/v2/agent_handlers.go delete mode 100644 vendor/github.com/pion/ice/v2/internal/atomic/atomic.go delete mode 100644 vendor/github.com/pion/ice/v2/internal/fakenet/mock_conn.go delete mode 100644 vendor/github.com/pion/ice/v2/internal/fakenet/packet_conn.go delete mode 100644 vendor/github.com/pion/ice/v2/internal/stun/stun.go delete mode 100644 vendor/github.com/pion/ice/v2/net.go create mode 100644 vendor/github.com/pion/ice/v2/stun.go delete mode 100644 vendor/github.com/pion/ice/v2/tcp_mux_multi.go delete mode 100644 vendor/github.com/pion/ice/v2/test_utils.go delete mode 100644 vendor/github.com/pion/ice/v2/udp_mux_multi.go delete mode 100644 vendor/github.com/pion/ice/v2/udp_mux_universal.go create mode 100644 vendor/github.com/pion/ice/v2/util.go delete mode 100644 vendor/github.com/pion/interceptor/.goreleaser.yml delete mode 100644 vendor/github.com/pion/interceptor/internal/ntp/ntp.go delete mode 100644 vendor/github.com/pion/mdns/.goreleaser.yml delete mode 100644 vendor/github.com/pion/mdns/AUTHORS.txt delete mode 100644 vendor/github.com/pion/rtcp/rfc8888.go delete mode 100644 vendor/github.com/pion/rtp/codecs/av1_packet.go delete mode 100644 vendor/github.com/pion/rtp/header_extension.go delete mode 100644 vendor/github.com/pion/rtp/pkg/obu/leb128.go delete mode 100644 vendor/github.com/pion/sctp/.goreleaser.yml create mode 100644 vendor/github.com/pion/sctp/DESIGN.md delete mode 100644 vendor/github.com/pion/sctp/error_cause_user_initiated_abort.go delete mode 100644 vendor/github.com/pion/sdp/v3/AUTHORS.txt delete mode 100644 vendor/github.com/pion/srtp/v2/.goreleaser.yml create mode 100644 vendor/github.com/pion/srtp/v2/DESIGN.md delete mode 100644 vendor/github.com/pion/srtp/v2/crypto.go create mode 100644 vendor/github.com/pion/stun/.codecov.yml create mode 100644 vendor/github.com/pion/stun/.travis.yml create mode 100644 vendor/github.com/pion/stun/AUTHORS delete mode 100644 vendor/github.com/pion/stun/AUTHORS.txt create mode 100644 vendor/github.com/pion/stun/Dockerfile rename vendor/github.com/pion/stun/{LICENSE => LICENSE.md} (93%) create mode 100644 vendor/github.com/pion/stun/appveyor.yml delete mode 100644 vendor/github.com/pion/stun/codecov.yml create mode 100644 vendor/github.com/pion/stun/fuzz.go create mode 100644 vendor/github.com/pion/stun/go.test.sh delete mode 100644 vendor/github.com/pion/stun/uri.go create mode 100644 vendor/github.com/pion/stun/xor.go rename vendor/github.com/pion/transport/{v2 => }/AUTHORS.txt (66%) rename vendor/github.com/{libp2p/go-libp2p-mplex => pion/transport}/LICENSE (86%) rename vendor/github.com/pion/transport/{v2 => }/connctx/connctx.go (91%) rename vendor/github.com/pion/transport/{v2 => }/connctx/pipe.go (60%) rename vendor/github.com/pion/transport/{v2 => }/deadline/deadline.go (90%) rename vendor/github.com/pion/transport/{v2 => }/packetio/buffer.go (85%) rename vendor/github.com/pion/transport/{v2 => }/packetio/errors.go (82%) create mode 100644 vendor/github.com/pion/transport/packetio/hardlimit.go create mode 100644 vendor/github.com/pion/transport/packetio/no_hardlimit.go rename vendor/github.com/pion/transport/{v2 => }/replaydetector/fixedbig.go (93%) rename vendor/github.com/pion/transport/{v2 => }/replaydetector/replaydetector.go (94%) delete mode 100644 vendor/github.com/pion/transport/v2/.goreleaser.yml delete mode 100644 vendor/github.com/pion/transport/v2/LICENSE delete mode 100644 vendor/github.com/pion/transport/v2/README.md delete mode 100644 vendor/github.com/pion/transport/v2/net.go delete mode 100644 vendor/github.com/pion/transport/v2/packetio/hardlimit.go delete mode 100644 vendor/github.com/pion/transport/v2/packetio/no_hardlimit.go delete mode 100644 vendor/github.com/pion/transport/v2/renovate.json delete mode 100644 vendor/github.com/pion/transport/v2/stdnet/net.go delete mode 100644 vendor/github.com/pion/transport/v2/utils/xor/xor_amd64.go delete mode 100644 vendor/github.com/pion/transport/v2/utils/xor/xor_amd64.s delete mode 100644 vendor/github.com/pion/transport/v2/utils/xor/xor_arm.go delete mode 100644 vendor/github.com/pion/transport/v2/utils/xor/xor_arm.s delete mode 100644 vendor/github.com/pion/transport/v2/utils/xor/xor_arm64.go delete mode 100644 vendor/github.com/pion/transport/v2/utils/xor/xor_arm64.s delete mode 100644 vendor/github.com/pion/transport/v2/utils/xor/xor_generic.go delete mode 100644 vendor/github.com/pion/transport/v2/utils/xor/xor_ppc64x.go delete mode 100644 vendor/github.com/pion/transport/v2/utils/xor/xor_ppc64x.s delete mode 100644 vendor/github.com/pion/transport/v2/vnet/.gitignore delete mode 100644 vendor/github.com/pion/transport/v2/vnet/vnet.go create mode 100644 vendor/github.com/pion/transport/vnet/.gitignore rename vendor/github.com/pion/transport/{v2 => }/vnet/README.md (72%) rename vendor/github.com/pion/transport/{v2 => }/vnet/chunk.go (96%) rename vendor/github.com/pion/transport/{v2 => }/vnet/chunk_queue.go (91%) rename vendor/github.com/pion/transport/{v2 => }/vnet/conn.go (73%) rename vendor/github.com/pion/transport/{v2 => }/vnet/conn_map.go (83%) rename vendor/github.com/pion/transport/{v2 => }/vnet/delay_filter.go (90%) rename vendor/github.com/pion/transport/{v2 => }/vnet/errors.go (71%) create mode 100644 vendor/github.com/pion/transport/vnet/interface.go rename vendor/github.com/pion/transport/{v2 => }/vnet/loss_filter.go (86%) rename vendor/github.com/pion/transport/{v2 => }/vnet/nat.go (93%) rename vendor/github.com/pion/transport/{v2 => }/vnet/net.go (62%) rename vendor/github.com/pion/transport/{v2 => }/vnet/resolver.go (87%) rename vendor/github.com/pion/transport/{v2 => }/vnet/router.go (93%) rename vendor/github.com/pion/transport/{v2 => }/vnet/tbf.go (68%) rename vendor/github.com/pion/transport/{v2 => }/vnet/udpproxy.go (73%) rename vendor/github.com/pion/transport/{v2 => }/vnet/udpproxy_direct.go (75%) create mode 100644 vendor/github.com/pion/transport/vnet/vnet.go delete mode 100644 vendor/github.com/pion/turn/v2/FAQ.md delete mode 100644 vendor/github.com/pion/turn/v2/internal/proto/connection_id.go create mode 100644 vendor/github.com/pion/turn/v2/internal/proto/fuzz.go rename vendor/github.com/pion/{transport/v2 => udp}/.gitignore (72%) rename vendor/github.com/pion/{transport/v2 => udp}/.golangci.yml (59%) create mode 100644 vendor/github.com/pion/udp/LICENSE create mode 100644 vendor/github.com/pion/udp/README.md rename vendor/github.com/pion/{transport/v2 => udp}/codecov.yml (78%) rename vendor/github.com/pion/{transport/v2 => }/udp/conn.go (83%) create mode 100644 vendor/github.com/pion/udp/renovate.json delete mode 100644 vendor/github.com/pion/webrtc/v3/.goreleaser.yml create mode 100644 vendor/github.com/quic-go/qtls-go1-19/LICENSE create mode 100644 vendor/github.com/quic-go/qtls-go1-19/README.md create mode 100644 vendor/github.com/quic-go/qtls-go1-19/alert.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/auth.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/cipher_suites.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/common.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/conn.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/cpu.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/cpu_other.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/handshake_client.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/handshake_client_tls13.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/handshake_messages.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/handshake_server.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/handshake_server_tls13.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/key_agreement.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/key_schedule.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/notboring.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/prf.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/ticket.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/tls.go create mode 100644 vendor/github.com/quic-go/qtls-go1-19/unsafe.go create mode 100644 vendor/github.com/quic-go/qtls-go1-20/cpu.go create mode 100644 vendor/github.com/quic-go/qtls-go1-20/cpu_other.go delete mode 100644 vendor/github.com/quic-go/qtls-go1-20/quic.go delete mode 100644 vendor/github.com/quic-go/quic-go/http3/error.go delete mode 100644 vendor/github.com/quic-go/quic-go/http3/headers.go create mode 100644 vendor/github.com/quic-go/quic-go/http3/request.go delete mode 100644 vendor/github.com/quic-go/quic-go/internal/ackhandler/ecn.go delete mode 100644 vendor/github.com/quic-go/quic-go/internal/handshake/cipher_suite.go delete mode 100644 vendor/github.com/quic-go/quic-go/internal/handshake/conn.go create mode 100644 vendor/github.com/quic-go/quic-go/internal/handshake/mockgen.go create mode 100644 vendor/github.com/quic-go/quic-go/internal/handshake/tls_extension_handler.go delete mode 100644 vendor/github.com/quic-go/quic-go/internal/qtls/cipher_suite_go121.go delete mode 100644 vendor/github.com/quic-go/quic-go/internal/qtls/client_session_cache.go create mode 100644 vendor/github.com/quic-go/quic-go/internal/qtls/go119.go delete mode 100644 vendor/github.com/quic-go/quic-go/logging/connection_tracer.go create mode 100644 vendor/github.com/quic-go/quic-go/logging/mockgen.go create mode 100644 vendor/github.com/quic-go/quic-go/logging/multiplex.go create mode 100644 vendor/github.com/quic-go/quic-go/logging/null_tracer.go delete mode 100644 vendor/github.com/quic-go/quic-go/logging/tracer.go delete mode 100644 vendor/github.com/quic-go/quic-go/oss-fuzz.sh delete mode 100644 vendor/github.com/quic-go/quic-go/sys_conn_df_darwin.go create mode 100644 vendor/github.com/quic-go/quic-go/sys_conn_no_gso.go delete mode 100644 vendor/go.uber.org/mock/AUTHORS delete mode 100644 vendor/go.uber.org/mock/CONTRIBUTORS delete mode 100644 vendor/go.uber.org/mock/LICENSE delete mode 100644 vendor/go.uber.org/mock/mockgen/generic_go118.go delete mode 100644 vendor/go.uber.org/mock/mockgen/generic_notgo118.go delete mode 100644 vendor/go.uber.org/zap/.golangci.yml create mode 100644 vendor/go.uber.org/zap/array_go118.go delete mode 100644 vendor/go.uber.org/zap/internal/pool/pool.go rename vendor/go.uber.org/zap/{internal/stacktrace/stack.go => stacktrace.go} (73%) delete mode 100644 vendor/go.uber.org/zap/zapcore/lazy_with.go delete mode 100644 vendor/golang.org/x/exp/rand/exp.go delete mode 100644 vendor/golang.org/x/exp/rand/normal.go delete mode 100644 vendor/golang.org/x/exp/rand/rand.go delete mode 100644 vendor/golang.org/x/exp/rand/rng.go delete mode 100644 vendor/golang.org/x/exp/rand/zipf.go delete mode 100644 vendor/golang.org/x/exp/slices/cmp.go rename vendor/golang.org/x/exp/slices/{zsortanyfunc.go => zsortfunc.go} (64%) create mode 100644 vendor/golang.org/x/sys/internal/unsafeheader/unsafeheader.go create mode 100644 vendor/golang.org/x/xerrors/LICENSE create mode 100644 vendor/golang.org/x/xerrors/PATENTS create mode 100644 vendor/golang.org/x/xerrors/README create mode 100644 vendor/golang.org/x/xerrors/adaptor.go create mode 100644 vendor/golang.org/x/xerrors/codereview.cfg create mode 100644 vendor/golang.org/x/xerrors/doc.go create mode 100644 vendor/golang.org/x/xerrors/errors.go create mode 100644 vendor/golang.org/x/xerrors/fmt.go create mode 100644 vendor/golang.org/x/xerrors/format.go create mode 100644 vendor/golang.org/x/xerrors/frame.go create mode 100644 vendor/golang.org/x/xerrors/internal/internal.go create mode 100644 vendor/golang.org/x/xerrors/wrap.go diff --git a/Makefile b/Makefile index 660ae88af..57a7e20a3 100644 --- a/Makefile +++ b/Makefile @@ -234,7 +234,7 @@ setup: setup-check setup-build setup-dev tidy setup-check: ##@setup Check if Go compiler is installed. ifeq (, $(shell which go)) - $(error "No Go compiler found! Make sure to install 1.20.0 or newer.") + $(error "No Go compiler found! Make sure to install 1.19.0 or newer.") endif setup-dev: ##@setup Install all necessary tools for development @@ -253,7 +253,7 @@ install-gomobile: ##@install Go Mobile Build Tools GO111MODULE=off go get -d golang.org/x/mobile/cmd/gobind install-lint: ##@install Install Linting Tools - GO111MODULE=on go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.55.2 + GO111MODULE=on go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.52.2 install-junit-report: ##@install Install Junit Report Tool for Jenkins integration GO111MODULE=on go install github.com/jstemmer/go-junit-report/v2@latest diff --git a/VERSION b/VERSION index 1f3a6e6ed..da34a74e3 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.172.6 +0.172.5 diff --git a/api/backend_test.go b/api/backend_test.go index f344d9a45..1f4ee4585 100644 --- a/api/backend_test.go +++ b/api/backend_test.go @@ -765,7 +765,7 @@ func TestLoginAccount(t *testing.T) { Password: password, BackupDisabledDataDir: tmpdir, NetworkID: 1, - LogFilePath: tmpdir + "/log", // nolint: goconst + LogFilePath: tmpdir + "/log", } c := make(chan interface{}, 10) signal.SetMobileSignalHandler(func(data []byte) { @@ -918,7 +918,7 @@ func TestConvertAccount(t *testing.T) { const keycardPassword = "222222" // represents password for a keycard user const keycardUID = "1234" const pathEIP1581Root = "m/43'/60'/1581'" - const pathEIP1581Chat = pathEIP1581Root + "/0'/0" // nolint: goconst + const pathEIP1581Chat = pathEIP1581Root + "/0'/0" const pathWalletRoot = "m/44'/60'/0'/0" const pathDefaultWalletAccount = pathWalletRoot + "/0" const customWalletPath1 = pathWalletRoot + "/1" @@ -1314,7 +1314,7 @@ func TestCreateWallet(t *testing.T) { Password: password, BackupDisabledDataDir: tmpdir, NetworkID: 1, - LogFilePath: tmpdir + "/log", // nolint: goconst + LogFilePath: tmpdir + "/log", } c := make(chan interface{}, 10) signal.SetMobileSignalHandler(func(data []byte) { @@ -1374,7 +1374,7 @@ func TestSetFleet(t *testing.T) { Password: password, BackupDisabledDataDir: tmpdir, NetworkID: 1, - LogFilePath: tmpdir + "/log", // nolint: goconst + LogFilePath: tmpdir + "/log", Emoji: "some", } c := make(chan interface{}, 10) diff --git a/api/defaults.go b/api/defaults.go index 6d9bfa3e8..48686d92e 100644 --- a/api/defaults.go +++ b/api/defaults.go @@ -17,7 +17,7 @@ import ( const pathWalletRoot = "m/44'/60'/0'/0" const pathEIP1581 = "m/43'/60'/1581'" -const pathDefaultChat = pathEIP1581 + "/0'/0" // nolint: goconst +const pathDefaultChat = pathEIP1581 + "/0'/0" const pathDefaultWallet = pathWalletRoot + "/0" const defaultMnemonicLength = 12 const shardsTestClusterID = 16 diff --git a/api/geth_backend.go b/api/geth_backend.go index 302d31605..83a77f72a 100644 --- a/api/geth_backend.go +++ b/api/geth_backend.go @@ -73,8 +73,6 @@ var ( ErrConfigNotAvailable = errors.New("NodeConfig is not available") ) -const shm = "-shm" - var _ StatusBackend = (*GethStatusBackend)(nil) // GethStatusBackend implements the Status.im service over go-ethereum @@ -271,11 +269,11 @@ func (b *GethStatusBackend) DeleteMultiaccount(keyUID string, keyStoreDir string filepath.Join(b.rootDataDir, fmt.Sprintf("%s.db-shm", keyUID)), filepath.Join(b.rootDataDir, fmt.Sprintf("%s.db-wal", keyUID)), appDbPath, - appDbPath + shm, - appDbPath + "-wal", // nolint: goconst + appDbPath + "-shm", + appDbPath + "-wal", walletDbPath, - walletDbPath + shm, - walletDbPath + "-wal", // nolint: goconst + walletDbPath + "-shm", + walletDbPath + "-wal", } for _, path := range dbFiles { if _, err := os.Stat(path); err == nil { @@ -334,19 +332,19 @@ func (b *GethStatusBackend) runDBFileMigrations(account multiaccounts.Account, p } // rename journals as well, but ignore errors - _ = os.Rename(unsupportedPath+shm, v3Path+shm) + _ = os.Rename(unsupportedPath+"-shm", v3Path+"-shm") _ = os.Rename(unsupportedPath+"-wal", v3Path+"-wal") } if _, err = os.Stat(v3Path); err == nil { if err := appdatabase.MigrateV3ToV4(v3Path, v4Path, password, account.KDFIterations, signal.SendReEncryptionStarted, signal.SendReEncryptionFinished); err != nil { _ = os.Remove(v4Path) - _ = os.Remove(v4Path + shm) + _ = os.Remove(v4Path + "-shm") _ = os.Remove(v4Path + "-wal") return "", errors.New("Failed to migrate v3 db to v4: " + err.Error()) } _ = os.Remove(v3Path) - _ = os.Remove(v3Path + shm) + _ = os.Remove(v3Path + "-shm") _ = os.Remove(v3Path + "-wal") } @@ -1098,7 +1096,7 @@ func (b *GethStatusBackend) createTempDBFile(pattern string) (tmpDbPath string, _ = file.Close() _ = os.Remove(filePath) _ = os.Remove(filePath + "-wal") - _ = os.Remove(filePath + shm) + _ = os.Remove(filePath + "-shm") _ = os.Remove(filePath + "-journal") } return @@ -1112,9 +1110,9 @@ func replaceDBFile(dbPath string, newDBPath string) (cleanup func(), err error) cleanup = func() { _ = os.Remove(dbPath + "-wal") - _ = os.Remove(dbPath + shm) + _ = os.Remove(dbPath + "-shm") _ = os.Rename(newDBPath+"-wal", dbPath+"-wal") - _ = os.Rename(newDBPath+shm, dbPath+shm) + _ = os.Rename(newDBPath+"-shm", dbPath+"-shm") } return diff --git a/eth-node/bridge/geth/wakuv2.go b/eth-node/bridge/geth/wakuv2.go index 31ad039ff..3449b180a 100644 --- a/eth-node/bridge/geth/wakuv2.go +++ b/eth-node/bridge/geth/wakuv2.go @@ -179,6 +179,11 @@ func (w *gethWakuV2Wrapper) SendMessagesRequest(peerID []byte, r types.MessagesR func (w *gethWakuV2Wrapper) RequestStoreMessages(ctx context.Context, peerID []byte, r types.MessagesRequest, processEnvelopes bool) (*types.StoreRequestCursor, int, error) { var options []store.HistoryRequestOption + peer, err := peer.Decode(string(peerID)) + if err != nil { + return nil, 0, err + } + options = []store.HistoryRequestOption{ store.WithPaging(false, uint64(r.Limit)), } @@ -197,7 +202,7 @@ func (w *gethWakuV2Wrapper) RequestStoreMessages(ctx context.Context, peerID []b contentTopics = append(contentTopics, wakucommon.BytesToTopic(topic)) } - pbCursor, envelopesCount, err := w.waku.Query(ctx, peer.ID(peerID), r.PubsubTopic, contentTopics, uint64(r.From), uint64(r.To), options, processEnvelopes) + pbCursor, envelopesCount, err := w.waku.Query(ctx, peer, r.PubsubTopic, contentTopics, uint64(r.From), uint64(r.To), options, processEnvelopes) if err != nil { return nil, 0, err } diff --git a/go.mod b/go.mod index 9a89af5de..b2478ae4a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/status-im/status-go -go 1.20 +go 1.19 replace github.com/ethereum/go-ethereum v1.10.26 => github.com/status-im/go-ethereum v1.10.25-status.11 @@ -33,11 +33,11 @@ require ( github.com/keighl/metabolize v0.0.0-20150915210303-97ab655d4034 github.com/kilic/bls12-381 v0.0.0-20200607163746-32e1441c8a9f github.com/lib/pq v1.10.4 - github.com/libp2p/go-libp2p v0.32.2 - github.com/libp2p/go-libp2p-pubsub v0.10.0 + github.com/libp2p/go-libp2p v0.29.2 + github.com/libp2p/go-libp2p-pubsub v0.9.3 github.com/lucasb-eyer/go-colorful v1.0.3 github.com/mat/besticon v0.0.0-20210314201728-1579f269edb7 - github.com/multiformats/go-multiaddr v0.12.0 + github.com/multiformats/go-multiaddr v0.10.1 github.com/multiformats/go-multibase v0.2.0 github.com/multiformats/go-multihash v0.2.3 github.com/multiformats/go-varint v0.0.7 @@ -51,7 +51,7 @@ require ( github.com/status-im/doubleratchet v3.0.0+incompatible github.com/status-im/markdown v0.0.0-20231114210825-6c2d15b5dc57 github.com/status-im/migrate/v4 v4.6.2-status.3 - github.com/status-im/rendezvous v1.3.8-0.20240110194857-cc5be22bf83e + github.com/status-im/rendezvous v1.3.7 github.com/status-im/status-go/extkeys v1.1.2 github.com/status-im/tcp-shaker v1.1.1-status github.com/status-im/zxcvbn-go v0.0.0-20220311183720-5e8676676857 @@ -63,8 +63,8 @@ require ( github.com/wealdtech/go-multicodec v1.4.0 github.com/xeipuuv/gojsonschema v1.2.0 github.com/zenthangplus/goccm v0.0.0-20211005163543-2f2e522aca15 - go.uber.org/zap v1.26.0 - golang.org/x/crypto v0.14.0 + go.uber.org/zap v1.24.0 + golang.org/x/crypto v0.12.0 golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb google.golang.org/protobuf v1.31.0 gopkg.in/go-playground/assert.v1 v1.2.1 // indirect @@ -88,14 +88,14 @@ require ( github.com/mutecomm/go-sqlcipher/v4 v4.4.2 github.com/schollz/peerdiscovery v1.7.0 github.com/siphiuel/lc-proxy-wrapper v0.0.0-20230516150924-246507cee8c7 - github.com/waku-org/go-waku v0.8.1-0.20240112174027-faf046e059a5 + github.com/waku-org/go-waku v0.8.1-0.20240104144340-585648c4eefe github.com/wk8/go-ordered-map/v2 v2.1.7 github.com/yeqown/go-qrcode/v2 v2.2.1 github.com/yeqown/go-qrcode/writer/standard v1.2.1 go.uber.org/multierr v1.11.0 - golang.org/x/exp v0.0.0-20231006140011-7918f672742d - golang.org/x/net v0.17.0 - golang.org/x/text v0.13.0 + golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 + golang.org/x/net v0.14.0 + golang.org/x/text v0.12.0 golang.org/x/time v0.0.0-20220922220347-f3bd1da661af ) @@ -161,21 +161,21 @@ require ( github.com/golang/snappy v0.0.4 // indirect github.com/google/btree v1.0.1 // indirect github.com/google/gopacket v1.1.19 // indirect - github.com/google/pprof v0.0.0-20231023181126-ff6d637d2a7b // indirect + github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8 // indirect github.com/gorilla/securecookie v1.1.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/hashicorp/go-bexpr v0.1.10 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d // indirect - github.com/hashicorp/golang-lru/v2 v2.0.5 // indirect + github.com/hashicorp/golang-lru/v2 v2.0.2 // indirect github.com/holiman/bloomfilter/v2 v2.0.3 // indirect github.com/holiman/uint256 v1.2.0 // indirect github.com/huandu/xstrings v1.3.2 // indirect - github.com/huin/goupnp v1.3.0 // indirect + github.com/huin/goupnp v1.2.0 // indirect github.com/jackpal/go-nat-pmp v1.0.2 // indirect github.com/jbenet/go-temp-err-catcher v0.1.0 // indirect - github.com/klauspost/compress v1.17.2 // indirect + github.com/klauspost/compress v1.16.7 // indirect github.com/klauspost/cpuid/v2 v2.2.5 // indirect github.com/koron/go-ssdp v0.0.4 // indirect github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect @@ -185,20 +185,19 @@ require ( github.com/libp2p/go-cidranger v1.1.0 // indirect github.com/libp2p/go-flow-metrics v0.1.0 // indirect github.com/libp2p/go-libp2p-asn-util v0.3.0 // indirect - github.com/libp2p/go-libp2p-mplex v0.9.0 // indirect github.com/libp2p/go-mplex v0.7.0 // indirect github.com/libp2p/go-msgio v0.3.0 // indirect github.com/libp2p/go-nat v0.2.0 // indirect github.com/libp2p/go-netroute v0.2.1 // indirect - github.com/libp2p/go-reuseport v0.4.0 // indirect + github.com/libp2p/go-reuseport v0.3.0 // indirect github.com/libp2p/go-yamux/v4 v4.0.1 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/marten-seemann/tcp v0.0.0-20210406111302-dfbc87cc63fd // indirect github.com/mattn/go-colorable v0.1.8 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect - github.com/miekg/dns v1.1.56 // indirect + github.com/miekg/dns v1.1.55 // indirect github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b // indirect github.com/mikioh/tcpopt v0.0.0-20190314235656-172688c1accc // indirect github.com/minio/sha256-simd v1.0.1 // indirect @@ -211,36 +210,38 @@ require ( github.com/multiformats/go-multiaddr-dns v0.3.1 // indirect github.com/multiformats/go-multiaddr-fmt v0.1.0 // indirect github.com/multiformats/go-multicodec v0.9.0 // indirect - github.com/multiformats/go-multistream v0.5.0 // indirect + github.com/multiformats/go-multistream v0.4.1 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect - github.com/onsi/ginkgo/v2 v2.13.0 // indirect - github.com/opencontainers/runtime-spec v1.1.0 // indirect + github.com/onsi/ginkgo/v2 v2.11.0 // indirect + github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417 // indirect github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect - github.com/pion/datachannel v1.5.5 // indirect - github.com/pion/dtls/v2 v2.2.7 // indirect - github.com/pion/ice/v2 v2.3.6 // indirect - github.com/pion/interceptor v0.1.17 // indirect + github.com/pion/datachannel v1.5.2 // indirect + github.com/pion/dtls/v2 v2.1.2 // indirect + github.com/pion/ice/v2 v2.1.20 // indirect + github.com/pion/interceptor v0.1.7 // indirect github.com/pion/logging v0.2.2 // indirect - github.com/pion/mdns v0.0.7 // indirect + github.com/pion/mdns v0.0.5 // indirect github.com/pion/randutil v0.1.0 // indirect - github.com/pion/rtcp v1.2.10 // indirect - github.com/pion/rtp v1.7.13 // indirect - github.com/pion/sctp v1.8.7 // indirect - github.com/pion/sdp/v3 v3.0.6 // indirect - github.com/pion/srtp/v2 v2.0.15 // indirect - github.com/pion/stun v0.6.0 // indirect - github.com/pion/transport/v2 v2.2.1 // indirect - github.com/pion/turn/v2 v2.1.0 // indirect - github.com/pion/webrtc/v3 v3.2.9 // indirect + github.com/pion/rtcp v1.2.9 // indirect + github.com/pion/rtp v1.7.4 // indirect + github.com/pion/sctp v1.8.2 // indirect + github.com/pion/sdp/v3 v3.0.4 // indirect + github.com/pion/srtp/v2 v2.0.5 // indirect + github.com/pion/stun v0.3.5 // indirect + github.com/pion/transport v0.13.0 // indirect + github.com/pion/turn/v2 v2.0.6 // indirect + github.com/pion/udp v0.1.1 // indirect + github.com/pion/webrtc/v3 v3.1.24-0.20220208053747-94262c1b2b38 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_model v0.4.0 // indirect github.com/prometheus/common v0.42.0 // indirect github.com/prometheus/procfs v0.10.1 // indirect github.com/prometheus/tsdb v0.10.0 // indirect github.com/quic-go/qpack v0.4.0 // indirect - github.com/quic-go/qtls-go1-20 v0.3.4 // indirect - github.com/quic-go/quic-go v0.39.4 // indirect - github.com/quic-go/webtransport-go v0.6.0 // indirect + github.com/quic-go/qtls-go1-19 v0.3.3 // indirect + github.com/quic-go/qtls-go1-20 v0.2.3 // indirect + github.com/quic-go/quic-go v0.36.4 // indirect + github.com/quic-go/webtransport-go v0.5.3 // indirect github.com/raulk/go-watchdog v1.3.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect github.com/rivo/uniseg v0.2.0 // indirect @@ -261,7 +262,7 @@ require ( github.com/tyler-smith/go-bip39 v1.1.0 // indirect github.com/urfave/cli/v2 v2.24.4 // indirect github.com/waku-org/go-discover v0.0.0-20221209174356-61c833f34d98 // indirect - github.com/waku-org/go-libp2p-rendezvous v0.0.0-20240110193335-a67d1cc760a0 // indirect + github.com/waku-org/go-libp2p-rendezvous v0.0.0-20230628220917-7b4e5ae4c0e7 // indirect github.com/waku-org/go-zerokit-rln v0.1.14-0.20240102145250-fa738c0bdf59 // indirect github.com/waku-org/go-zerokit-rln-apple v0.0.0-20230916172309-ee0ee61dde2b // indirect github.com/waku-org/go-zerokit-rln-arm v0.0.0-20230916171929-1dd9494ff065 // indirect @@ -274,14 +275,14 @@ require ( github.com/yusufpapurcu/wmi v1.2.3 // indirect go.etcd.io/bbolt v1.3.6 // indirect go.uber.org/atomic v1.11.0 // indirect - go.uber.org/dig v1.17.1 // indirect - go.uber.org/fx v1.20.1 // indirect - go.uber.org/mock v0.3.0 // indirect - golang.org/x/mod v0.13.0 // indirect - golang.org/x/sync v0.4.0 // indirect - golang.org/x/sys v0.13.0 // indirect - golang.org/x/term v0.13.0 // indirect - golang.org/x/tools v0.14.0 // indirect + go.uber.org/dig v1.17.0 // indirect + go.uber.org/fx v1.20.0 // indirect + golang.org/x/mod v0.12.0 // indirect + golang.org/x/sync v0.3.0 // indirect + golang.org/x/sys v0.11.0 // indirect + golang.org/x/term v0.11.0 // indirect + golang.org/x/tools v0.12.1-0.20230818130535-1517d1a3ba60 // indirect + golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f // indirect gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect gopkg.in/yaml.v3 v3.0.1 // indirect lukechampine.com/blake3 v1.2.1 // indirect diff --git a/go.sum b/go.sum index 980c14f87..8dfe80ef3 100644 --- a/go.sum +++ b/go.sum @@ -1025,8 +1025,8 @@ github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20231023181126-ff6d637d2a7b h1:RMpPgZTSApbPf7xaVel+QkoGPRLFLrwFO89uDUHEGf0= -github.com/google/pprof v0.0.0-20231023181126-ff6d637d2a7b/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik= +github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8 h1:n6vlPhxsA+BW/XsS5+uqi7GyzaLa5MH7qlSLBZtRdiA= +github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8/go.mod h1:Jh3hGz2jkYak8qXPD19ryItVnUgpgeqzdkY/D0EaeuA= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -1114,8 +1114,8 @@ github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d h1:dg1dEPuWpEqDnvIw251EVy4zlP8gWbsGj4BsUKCRpYs= github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= -github.com/hashicorp/golang-lru/v2 v2.0.5 h1:wW7h1TG88eUIJ2i69gaE3uNVtEPIagzhGvHgwfx2Vm4= -github.com/hashicorp/golang-lru/v2 v2.0.5/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/hashicorp/golang-lru/v2 v2.0.2 h1:Dwmkdr5Nc/oBiXgJS3CDHNhJtIHkuZ3DZF5twqnfBdU= +github.com/hashicorp/golang-lru/v2 v2.0.2/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= @@ -1137,8 +1137,8 @@ github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/huin/goupnp v1.0.1-0.20210310174557-0ca763054c88/go.mod h1:nNs7wvRfN1eKaMknBydLNQU6146XQim8t4h+q90biWo= github.com/huin/goupnp v1.0.2/go.mod h1:0dxJBVBHqTMjIUMkESDTNgOOx/Mw5wYIfyFmdzSamkM= -github.com/huin/goupnp v1.3.0 h1:UvLUlWDNpoUdYzb2TCn+MuTWtcjXKSza2n6CBdQ0xXc= -github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8= +github.com/huin/goupnp v1.2.0 h1:uOKW26NG1hsSSbXIZ1IR7XP9Gjd1U8pnLaCMgntmkmY= +github.com/huin/goupnp v1.2.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFckNX8= github.com/huin/goutil v0.0.0-20170803182201-1ca381bf3150/go.mod h1:PpLOETDnJ0o3iZrZfqZzyLl6l7F3c6L1oWn7OICBi6o= github.com/iancoleman/strcase v0.2.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= @@ -1292,8 +1292,8 @@ github.com/klauspost/compress v1.11.13/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdY github.com/klauspost/compress v1.13.1/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/klauspost/compress v1.17.2 h1:RlWWUY/Dr4fL8qk9YG7DTZ7PDgME2V4csBXA8L/ixi4= -github.com/klauspost/compress v1.17.2/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.16.7 h1:2mk3MPGNzKyxErAw8YaohYh69+pa4sIQSC0fPGCFR9I= +github.com/klauspost/compress v1.16.7/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/klauspost/cpuid v0.0.0-20170728055534-ae7887de9fa5/go.mod h1:Pj4uuM528wm8OyEC2QMXAi2YiTZ96dNQPGgoMS4s3ek= github.com/klauspost/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.0.6/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= @@ -1348,14 +1348,12 @@ github.com/libp2p/go-cidranger v1.1.0 h1:ewPN8EZ0dd1LSnrtuwd4709PXVcITVeuwbag38y github.com/libp2p/go-cidranger v1.1.0/go.mod h1:KWZTfSr+r9qEo9OkI9/SIEeAtw+NNoU0dXIXt15Okic= github.com/libp2p/go-flow-metrics v0.1.0 h1:0iPhMI8PskQwzh57jB9WxIuIOQ0r+15PChFGkx3Q3WM= github.com/libp2p/go-flow-metrics v0.1.0/go.mod h1:4Xi8MX8wj5aWNDAZttg6UPmc0ZrnFNsMtpsYUClFtro= -github.com/libp2p/go-libp2p v0.32.2 h1:s8GYN4YJzgUoyeYNPdW7JZeZ5Ee31iNaIBfGYMAY4FQ= -github.com/libp2p/go-libp2p v0.32.2/go.mod h1:E0LKe+diV/ZVJVnOJby8VC5xzHF0660osg71skcxJvk= +github.com/libp2p/go-libp2p v0.29.2 h1:uPw/c8hOxoLP/KhFnzlc5Ejqf+OmAL1dwIsqE31WBtY= +github.com/libp2p/go-libp2p v0.29.2/go.mod h1:OU7nSq0aEZMsV2wY8nXn1+XNNt9q2UiR8LjW3Kmp2UE= github.com/libp2p/go-libp2p-asn-util v0.3.0 h1:gMDcMyYiZKkocGXDQ5nsUQyquC9+H+iLEQHwOCZ7s8s= github.com/libp2p/go-libp2p-asn-util v0.3.0/go.mod h1:B1mcOrKUE35Xq/ASTmQ4tN3LNzVVaMNmq2NACuqyB9w= -github.com/libp2p/go-libp2p-mplex v0.9.0 h1:R58pDRAmuBXkYugbSSXR9wrTX3+1pFM1xP2bLuodIq8= -github.com/libp2p/go-libp2p-mplex v0.9.0/go.mod h1:ro1i4kuwiFT+uMPbIDIFkcLs1KRbNp0QwnUXM+P64Og= -github.com/libp2p/go-libp2p-pubsub v0.10.0 h1:wS0S5FlISavMaAbxyQn3dxMOe2eegMfswM471RuHJwA= -github.com/libp2p/go-libp2p-pubsub v0.10.0/go.mod h1:1OxbaT/pFRO5h+Dpze8hdHQ63R0ke55XTs6b6NwLLkw= +github.com/libp2p/go-libp2p-pubsub v0.9.3 h1:ihcz9oIBMaCK9kcx+yHWm3mLAFBMAUsM4ux42aikDxo= +github.com/libp2p/go-libp2p-pubsub v0.9.3/go.mod h1:RYA7aM9jIic5VV47WXu4GkcRxRhrdElWf8xtyli+Dzc= github.com/libp2p/go-libp2p-testing v0.12.0 h1:EPvBb4kKMWO29qP4mZGyhVzUyR25dvfUIK5WDu6iPUA= github.com/libp2p/go-maddr-filter v0.1.0/go.mod h1:VzZhTXkMucEGGEOSKddrwGiOv0tUhgnKqNEmIAz/bPU= github.com/libp2p/go-mplex v0.7.0 h1:BDhFZdlk5tbr0oyFq/xv/NPGfjbnrsDam1EvutpBDbY= @@ -1366,8 +1364,8 @@ github.com/libp2p/go-nat v0.2.0 h1:Tyz+bUFAYqGyJ/ppPPymMGbIgNRH+WqC5QrT5fKrrGk= github.com/libp2p/go-nat v0.2.0/go.mod h1:3MJr+GRpRkyT65EpVPBstXLvOlAPzUVlG6Pwg9ohLJk= github.com/libp2p/go-netroute v0.2.1 h1:V8kVrpD8GK0Riv15/7VN6RbUQ3URNZVosw7H2v9tksU= github.com/libp2p/go-netroute v0.2.1/go.mod h1:hraioZr0fhBjG0ZRXJJ6Zj2IVEVNx6tDTFQfSmcq7mQ= -github.com/libp2p/go-reuseport v0.4.0 h1:nR5KU7hD0WxXCJbmw7r2rhRYruNRl2koHw8fQscQm2s= -github.com/libp2p/go-reuseport v0.4.0/go.mod h1:ZtI03j/wO5hZVDFo2jKywN6bYKWLOy8Se6DrI2E1cLU= +github.com/libp2p/go-reuseport v0.3.0 h1:iiZslO5byUYZEg9iCwJGf5h+sf1Agmqx2V2FDjPyvUw= +github.com/libp2p/go-reuseport v0.3.0/go.mod h1:laea40AimhtfEqysZ71UpYj4S+R9VpH8PgqLo7L+SwI= github.com/libp2p/go-yamux/v4 v4.0.1 h1:FfDR4S1wj6Bw2Pqbc8Uz7pCxeRBPbwsBbEdfwiCypkQ= github.com/libp2p/go-yamux/v4 v4.0.1/go.mod h1:NWjl8ZTLOGlozrXSOZ/HlfG++39iKNnM5wwmtQP1YB4= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= @@ -1428,8 +1426,8 @@ github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2y github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= -github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= @@ -1460,8 +1458,8 @@ github.com/meirf/gopart v0.0.0-20180520194036-37e9492a85a8/go.mod h1:Uz8uoD6o+eQ github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI= -github.com/miekg/dns v1.1.56 h1:5imZaSeoRNvpM9SzWNhEcP9QliKiz20/dA2QabIGVnE= -github.com/miekg/dns v1.1.56/go.mod h1:cRm6Oo2C8TY9ZS/TqsSrseAcncm74lfK5G+ikN2SWWY= +github.com/miekg/dns v1.1.55 h1:GoQ4hpsj0nFLYe+bWiCToyrBEJXkQfOOIvFGFy0lEgo= +github.com/miekg/dns v1.1.55/go.mod h1:uInx36IzPl7FYnDcMeVWxj9byh7DutNykX4G9Sj60FY= github.com/miekg/pkcs11 v1.0.3/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs= github.com/mikioh/tcp v0.0.0-20190314235350-803a9b46060c h1:bzE/A84HN25pxAuk9Eej1Kz9OUelF97nAc82bDquQI8= github.com/mikioh/tcp v0.0.0-20190314235350-803a9b46060c/go.mod h1:0SQS9kMwD2VsyFEB++InYyBJroV/FRmBgcydeSUcJms= @@ -1528,8 +1526,8 @@ github.com/multiformats/go-multiaddr v0.1.1/go.mod h1:aMKBKNEYmzmDmxfX88/vz+J5IU github.com/multiformats/go-multiaddr v0.2.0/go.mod h1:0nO36NvPpyV4QzvTLi/lafl2y95ncPj0vFwVF6k6wJ4= github.com/multiformats/go-multiaddr v0.2.2/go.mod h1:NtfXiOtHvghW9KojvtySjH5y0u0xW5UouOmQQrn6a3Y= github.com/multiformats/go-multiaddr v0.3.2/go.mod h1:lCKNGP1EQ1eZ35Za2wlqnabm9xQkib3fyB+nZXHLag0= -github.com/multiformats/go-multiaddr v0.12.0 h1:1QlibTFkoXJuDjjYsMHhE73TnzJQl8FSWatk/0gxGzE= -github.com/multiformats/go-multiaddr v0.12.0/go.mod h1:WmZXgObOQOYp9r3cslLlppkrz1FYSHmE834dfz/lWu8= +github.com/multiformats/go-multiaddr v0.10.1 h1:HghtFrWyZEPrpTvgAMFJi6gFdgHfs2cb0pyfDsk+lqU= +github.com/multiformats/go-multiaddr v0.10.1/go.mod h1:jLEZsA61rwWNZQTHHnqq2HNa+4os/Hz54eqiRnsRqYQ= github.com/multiformats/go-multiaddr-dns v0.3.1 h1:QgQgR+LQVt3NPTjbrLLpsaT2ufAA2y0Mkk+QRVJbW3A= github.com/multiformats/go-multiaddr-dns v0.3.1/go.mod h1:G/245BRQ6FJGmryJCrOuTdB37AMA5AMOVuO6NY3JwTk= github.com/multiformats/go-multiaddr-fmt v0.1.0 h1:WLEFClPycPkp4fnIzoFoV9FVd49/eQsuaL3/CWe167E= @@ -1545,8 +1543,8 @@ github.com/multiformats/go-multihash v0.0.14/go.mod h1:VdAWLKTwram9oKAatUcLxBNUj github.com/multiformats/go-multihash v0.0.15/go.mod h1:D6aZrWNLFTV/ynMpKsNtB40mJzmCl4jb1alC0OvHiHg= github.com/multiformats/go-multihash v0.2.3 h1:7Lyc8XfX/IY2jWb/gI7JP+o7JEq9hOa7BFvVU9RSh+U= github.com/multiformats/go-multihash v0.2.3/go.mod h1:dXgKXCXjBzdscBLk9JkjINiEsCKRVch90MdaGiKsvSM= -github.com/multiformats/go-multistream v0.5.0 h1:5htLSLl7lvJk3xx3qT/8Zm9J4K8vEOf/QGkvOGQAyiE= -github.com/multiformats/go-multistream v0.5.0/go.mod h1:n6tMZiwiP2wUsR8DgfDWw1dydlEqV3l6N3/GBsX6ILA= +github.com/multiformats/go-multistream v0.4.1 h1:rFy0Iiyn3YT0asivDUIR05leAdwZq3de4741sbiSdfo= +github.com/multiformats/go-multistream v0.4.1/go.mod h1:Mz5eykRVAjJWckE2U78c6xqdtyNUEhKSM0Lwar2p77Q= github.com/multiformats/go-varint v0.0.1/go.mod h1:3Ls8CIEsrijN6+B7PbrXRPxHRPuXSrVKRY101jdMZYE= github.com/multiformats/go-varint v0.0.5/go.mod h1:3Ls8CIEsrijN6+B7PbrXRPxHRPuXSrVKRY101jdMZYE= github.com/multiformats/go-varint v0.0.6/go.mod h1:3Ls8CIEsrijN6+B7PbrXRPxHRPuXSrVKRY101jdMZYE= @@ -1605,8 +1603,8 @@ github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vv github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE= github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU= github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c= -github.com/onsi/ginkgo/v2 v2.13.0 h1:0jY9lJquiL8fcf3M4LAXN5aMlS/b2BV86HFFPCPMgE4= -github.com/onsi/ginkgo/v2 v2.13.0/go.mod h1:TE309ZR8s5FsKKpuB1YAQYBzCaAfUgatB/xlT/ETL/o= +github.com/onsi/ginkgo/v2 v2.11.0 h1:WgqUCUt/lT6yXoQ8Wef0fsNn5cAuMK7+KT9UFRz2tcU= +github.com/onsi/ginkgo/v2 v2.11.0/go.mod h1:ZhrRA5XmEE3x3rhlzamx/JJvujdZoJ2uvgI7kR0iZvM= github.com/onsi/gomega v0.0.0-20151007035656-2152b45fa28a/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= @@ -1621,7 +1619,7 @@ github.com/onsi/gomega v1.11.0/go.mod h1:azGKhqFUon9Vuj0YmTfLSmx0FUwqXYSTl5re8lQ github.com/onsi/gomega v1.15.0/go.mod h1:cIuvLEne0aoVhAgh/O6ac0Op8WWw9H6eYCriF+tEHG0= github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= -github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI= +github.com/onsi/gomega v1.27.8 h1:gegWiwZjBsf2DgiSbf5hpokZ98JVDMcWkUiigk6/KXc= github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= github.com/opencontainers/go-digest v0.0.0-20170106003457-a6d0ee40d420/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= github.com/opencontainers/go-digest v0.0.0-20180430190053-c9281466c8b2/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= @@ -1646,9 +1644,8 @@ github.com/opencontainers/runtime-spec v1.0.1/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/ github.com/opencontainers/runtime-spec v1.0.2-0.20190207185410-29686dbc5559/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-spec v1.0.2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-spec v1.0.3-0.20200929063507-e6143ca7d51d/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417 h1:3snG66yBm59tKhhSPQrQ/0bCrv1LQbKt40LnUPiUxdc= github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= -github.com/opencontainers/runtime-spec v1.1.0 h1:HHUyrt9mwHUjtasSbXSMvs4cyFxh+Bll4AjJ9odEGpg= -github.com/opencontainers/runtime-spec v1.1.0/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-tools v0.0.0-20181011054405-1d69bd0f9c39/go.mod h1:r3f7wjNzSs2extwzU3Y+6pKfobzPh+kKFJ3ofN+3nfs= github.com/opencontainers/selinux v1.6.0/go.mod h1:VVGKuOLlE7v4PJyT6h7mNWvq1rzqiriPsEqVhc+svHE= github.com/opencontainers/selinux v1.8.0/go.mod h1:RScLhm78qiWa2gbVCcGkC7tCGdgk3ogry1nUQF8Evvo= @@ -1688,39 +1685,34 @@ github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0 github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pierrec/lz4/v4 v4.1.8/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/pion/datachannel v1.4.21/go.mod h1:oiNyP4gHx2DIwRzX/MFyH0Rz/Gz05OgBlayAI2hAWjg= +github.com/pion/datachannel v1.5.2 h1:piB93s8LGmbECrpO84DnkIVWasRMk3IimbcXkTQLE6E= github.com/pion/datachannel v1.5.2/go.mod h1:FTGQWaHrdCwIJ1rw6xBIfZVkslikjShim5yr05XFuCQ= -github.com/pion/datachannel v1.5.5 h1:10ef4kwdjije+M9d7Xm9im2Y3O6A6ccQb0zcqZcJew8= -github.com/pion/datachannel v1.5.5/go.mod h1:iMz+lECmfdCMqFRhXhcA/219B0SQlbpoR2V118yimL0= github.com/pion/dtls/v2 v2.0.1/go.mod h1:uMQkz2W0cSqY00xav7WByQ4Hb+18xeQh2oH2fRezr5U= github.com/pion/dtls/v2 v2.0.2/go.mod h1:27PEO3MDdaCfo21heT59/vsdmZc0zMt9wQPcSlLu/1I= github.com/pion/dtls/v2 v2.0.4/go.mod h1:qAkFscX0ZHoI1E07RfYPoRw3manThveu+mlTDdOxoGI= github.com/pion/dtls/v2 v2.0.7/go.mod h1:QuDII+8FVvk9Dp5t5vYIMTo7hh7uBkra+8QIm7QGm10= github.com/pion/dtls/v2 v2.0.9/go.mod h1:O0Wr7si/Zj5/EBFlDzDd6UtVxx25CE1r7XM7BQKYQho= github.com/pion/dtls/v2 v2.1.1/go.mod h1:qG3gA7ZPZemBqpEFqRKyURYdKEwFZQCGb7gv9T3ON3Y= +github.com/pion/dtls/v2 v2.1.2 h1:22Q1Jk9L++Yo7BIf9130MonNPfPVb+YgdYLeyQotuAA= github.com/pion/dtls/v2 v2.1.2/go.mod h1:o6+WvyLDAlXF7YiPB/RlskRoeK+/JtuaZa5emwQcWus= -github.com/pion/dtls/v2 v2.2.7 h1:cSUBsETxepsCSFSxC3mc/aDo14qQLMSL+O6IjG28yV8= -github.com/pion/dtls/v2 v2.2.7/go.mod h1:8WiMkebSHFD0T+dIU+UeBaoV7kDhOW5oDCzZ7WZ/F9s= github.com/pion/ice v0.7.18/go.mod h1:+Bvnm3nYC6Nnp7VV6glUkuOfToB/AtMRZpOU8ihuf4c= github.com/pion/ice/v2 v2.0.15/go.mod h1:ZIiVGevpgAxF/cXiIVmuIUtCb3Xs4gCzCbXB6+nFkSI= github.com/pion/ice/v2 v2.1.7/go.mod h1:kV4EODVD5ux2z8XncbLHIOtcXKtYXVgLVCeVqnpoeP0= github.com/pion/ice/v2 v2.1.10/go.mod h1:kV4EODVD5ux2z8XncbLHIOtcXKtYXVgLVCeVqnpoeP0= github.com/pion/ice/v2 v2.1.12/go.mod h1:ovgYHUmwYLlRvcCLI67PnQ5YGe+upXZbGgllBDG/ktU= +github.com/pion/ice/v2 v2.1.20 h1:xpxXyX5b4WjCh/D905gzBeW/hbJxMEPx2ptVfrhVE6M= github.com/pion/ice/v2 v2.1.20/go.mod h1:hEAldRzBhTtAfvlU1V/2/nLCMvveQWFKPNCop+63/Iw= -github.com/pion/ice/v2 v2.3.6 h1:Jgqw36cAud47iD+N6rNX225uHvrgWtAlHfVyOQc3Heg= -github.com/pion/ice/v2 v2.3.6/go.mod h1:9/TzKDRwBVAPsC+YOrKH/e3xDrubeTRACU9/sHQarsU= github.com/pion/interceptor v0.0.9/go.mod h1:dHgEP5dtxOTf21MObuBAjJeAayPxLUAZjerGH8Xr07c= github.com/pion/interceptor v0.0.12/go.mod h1:qzeuWuD/ZXvPqOnxNcnhWfkCZ2e1kwwslicyyPnhoK4= github.com/pion/interceptor v0.0.13/go.mod h1:svsW2QoLHLoGLUr4pDoSopGBEWk8FZwlfxId/OKRKzo= github.com/pion/interceptor v0.0.15/go.mod h1:pg3J253eGi5bqyKzA74+ej5Y19ez2jkWANVnF+Z9Dfk= +github.com/pion/interceptor v0.1.7 h1:HThW0tIIKT9RRoDWGURe8rlZVOx0fJHxBHpA0ej0+bo= github.com/pion/interceptor v0.1.7/go.mod h1:Lh3JSl/cbJ2wP8I3ccrjh1K/deRGRn3UlSPuOTiHb6U= -github.com/pion/interceptor v0.1.17 h1:prJtgwFh/gB8zMqGZoOgJPHivOwVAp61i2aG61Du/1w= -github.com/pion/interceptor v0.1.17/go.mod h1:SY8kpmfVBvrbUzvj2bsXz7OJt5JvmVNZ+4Kjq7FcwrI= github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY= github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= github.com/pion/mdns v0.0.4/go.mod h1:R1sL0p50l42S5lJs91oNdUL58nm0QHrhxnSegr++qC0= +github.com/pion/mdns v0.0.5 h1:Q2oj/JB3NqfzY9xGZ1fPzZzK7sDSD8rZPOvcIQ10BCw= github.com/pion/mdns v0.0.5/go.mod h1:UgssrvdD3mxpi8tMxAXbsppL3vJ4Jipw1mTCW+al01g= -github.com/pion/mdns v0.0.7 h1:P0UB4Sr6xDWEox0kTVxF0LmQihtCbSAdW0H2nEgkA3U= -github.com/pion/mdns v0.0.7/go.mod h1:4iP2UbeFhLI/vWju/bw6ZfwjJzk0z8DNValjGxR/dD8= github.com/pion/quic v0.1.1/go.mod h1:zEU51v7ru8Mp4AUBJvj6psrSth5eEFNnVQK5K48oV3k= github.com/pion/quic v0.1.4/go.mod h1:dBhNvkLoQqRwfi6h3Vqj3IcPLgiW7rkZxBbRdp7Vzvk= github.com/pion/randutil v0.0.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8= @@ -1729,41 +1721,33 @@ github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TB github.com/pion/rtcp v1.2.3/go.mod h1:zGhIv0RPRF0Z1Wiij22pUt5W/c9fevqSzT4jje/oK7I= github.com/pion/rtcp v1.2.4/go.mod h1:52rMNPWFsjr39z9B9MhnkqhPLoeHTv1aN63o/42bWE0= github.com/pion/rtcp v1.2.6/go.mod h1:52rMNPWFsjr39z9B9MhnkqhPLoeHTv1aN63o/42bWE0= +github.com/pion/rtcp v1.2.9 h1:1ujStwg++IOLIEoOiIQ2s+qBuJ1VN81KW+9pMPsif+U= github.com/pion/rtcp v1.2.9/go.mod h1:qVPhiCzAm4D/rxb6XzKeyZiQK69yJpbUDJSF7TgrqNo= -github.com/pion/rtcp v1.2.10 h1:nkr3uj+8Sp97zyItdN60tE/S6vk4al5CPRR6Gejsdjc= -github.com/pion/rtcp v1.2.10/go.mod h1:ztfEwXZNLGyF1oQDttz/ZKIBaeeg/oWbRYqzBM9TL1I= github.com/pion/rtp v1.6.0/go.mod h1:QgfogHsMBVE/RFNno467U/KBqfUywEH+HK+0rtnwsdI= github.com/pion/rtp v1.6.1/go.mod h1:bDb5n+BFZxXx0Ea7E5qe+klMuqiBrP+w8XSjiWtCUko= github.com/pion/rtp v1.6.2/go.mod h1:bDb5n+BFZxXx0Ea7E5qe+klMuqiBrP+w8XSjiWtCUko= github.com/pion/rtp v1.6.5/go.mod h1:bDb5n+BFZxXx0Ea7E5qe+klMuqiBrP+w8XSjiWtCUko= github.com/pion/rtp v1.7.0/go.mod h1:bDb5n+BFZxXx0Ea7E5qe+klMuqiBrP+w8XSjiWtCUko= github.com/pion/rtp v1.7.2/go.mod h1:bDb5n+BFZxXx0Ea7E5qe+klMuqiBrP+w8XSjiWtCUko= +github.com/pion/rtp v1.7.4 h1:4dMbjb1SuynU5OpA3kz1zHK+u+eOCQjW3MAeVHf1ODA= github.com/pion/rtp v1.7.4/go.mod h1:bDb5n+BFZxXx0Ea7E5qe+klMuqiBrP+w8XSjiWtCUko= -github.com/pion/rtp v1.7.13 h1:qcHwlmtiI50t1XivvoawdCGTP4Uiypzfrsap+bijcoA= -github.com/pion/rtp v1.7.13/go.mod h1:bDb5n+BFZxXx0Ea7E5qe+klMuqiBrP+w8XSjiWtCUko= github.com/pion/sctp v1.7.10/go.mod h1:EhpTUQu1/lcK3xI+eriS6/96fWetHGCvBi9MSsnaBN0= github.com/pion/sctp v1.7.11/go.mod h1:EhpTUQu1/lcK3xI+eriS6/96fWetHGCvBi9MSsnaBN0= github.com/pion/sctp v1.7.12/go.mod h1:xFe9cLMZ5Vj6eOzpyiKjT9SwGM4KpK/8Jbw5//jc+0s= github.com/pion/sctp v1.8.0/go.mod h1:xFe9cLMZ5Vj6eOzpyiKjT9SwGM4KpK/8Jbw5//jc+0s= +github.com/pion/sctp v1.8.2 h1:yBBCIrUMJ4yFICL3RIvR4eh/H2BTTvlligmSTy+3kiA= github.com/pion/sctp v1.8.2/go.mod h1:xFe9cLMZ5Vj6eOzpyiKjT9SwGM4KpK/8Jbw5//jc+0s= -github.com/pion/sctp v1.8.5/go.mod h1:SUFFfDpViyKejTAdwD1d/HQsCu+V/40cCs2nZIvC3s0= -github.com/pion/sctp v1.8.7 h1:JnABvFakZueGAn4KU/4PSKg+GWbF6QWbKTWZOSGJjXw= -github.com/pion/sctp v1.8.7/go.mod h1:g1Ul+ARqZq5JEmoFy87Q/4CePtKnTJ1QCL9dBBdN6AU= github.com/pion/sdp/v2 v2.4.0/go.mod h1:L2LxrOpSTJbAns244vfPChbciR/ReU1KWfG04OpkR7E= +github.com/pion/sdp/v3 v3.0.4 h1:2Kf+dgrzJflNCSw3TV5v2VLeI0s/qkzy2r5jlR0wzf8= github.com/pion/sdp/v3 v3.0.4/go.mod h1:bNiSknmJE0HYBprTHXKPQ3+JjacTv5uap92ueJZKsRk= -github.com/pion/sdp/v3 v3.0.6 h1:WuDLhtuFUUVpTfus9ILC4HRyHsW6TdugjEX/QY9OiUw= -github.com/pion/sdp/v3 v3.0.6/go.mod h1:iiFWFpQO8Fy3S5ldclBkpXqmWy02ns78NOKoLLL0YQw= github.com/pion/srtp v1.5.1/go.mod h1:B+QgX5xPeQTNc1CJStJPHzOlHK66ViMDWTT0HZTCkcA= github.com/pion/srtp v1.5.2/go.mod h1:NiBff/MSxUwMUwx/fRNyD/xGE+dVvf8BOCeXhjCXZ9U= github.com/pion/srtp/v2 v2.0.1/go.mod h1:c8NWHhhkFf/drmHTAblkdu8++lsISEBBdAuiyxgqIsE= github.com/pion/srtp/v2 v2.0.2/go.mod h1:VEyLv4CuxrwGY8cxM+Ng3bmVy8ckz/1t6A0q/msKOw0= +github.com/pion/srtp/v2 v2.0.5 h1:ks3wcTvIUE/GHndO3FAvROQ9opy0uLELpwHJaQ1yqhQ= github.com/pion/srtp/v2 v2.0.5/go.mod h1:8k6AJlal740mrZ6WYxc4Dg6qDqqhxoRG2GSjlUhDF0A= -github.com/pion/srtp/v2 v2.0.15 h1:+tqRtXGsGwHC0G0IUIAzRmdkHvriF79IHVfZGfHrQoA= -github.com/pion/srtp/v2 v2.0.15/go.mod h1:b/pQOlDrbB0HEH5EUAQXzSYxikFbNcNuKmF8tM0hCtw= +github.com/pion/stun v0.3.5 h1:uLUCBCkQby4S1cf6CGuR9QrVOKcvUwFeemaC865QHDg= github.com/pion/stun v0.3.5/go.mod h1:gDMim+47EeEtfWogA37n6qXZS88L5V6LqFcf+DZA2UA= -github.com/pion/stun v0.4.0/go.mod h1:QPsh1/SbXASntw3zkkrIk3ZJVKz4saBY2G7S10P3wCw= -github.com/pion/stun v0.6.0 h1:JHT/2iyGDPrFWE8NNC15wnddBN8KifsEDw8swQmrEmU= -github.com/pion/stun v0.6.0/go.mod h1:HPqcfoeqQn9cuaet7AOmB5e5xkObu9DwBdurwLKO9oA= github.com/pion/transport v0.6.0/go.mod h1:iWZ07doqOosSLMhZ+FXUTq+TamDoXSllxpbGcfkCmbE= github.com/pion/transport v0.8.10/go.mod h1:tBmha/UCjpum5hqTWhfAEs3CO4/tHSg0MYRhSzR+CZ8= github.com/pion/transport v0.10.0/go.mod h1:BnHnUipd0rZQyTVB2SBGojFHT9CBt5C5TcsJSQGkvSE= @@ -1771,28 +1755,21 @@ github.com/pion/transport v0.10.1/go.mod h1:PBis1stIILMiis0PewDw91WJeLJkyIMcEk+D github.com/pion/transport v0.12.1/go.mod h1:N3+vZQD9HlDP5GWkZ85LohxNsDcNgofQmyL6ojX5d8Q= github.com/pion/transport v0.12.2/go.mod h1:N3+vZQD9HlDP5GWkZ85LohxNsDcNgofQmyL6ojX5d8Q= github.com/pion/transport v0.12.3/go.mod h1:OViWW9SP2peE/HbwBvARicmAVnesphkNkCVZIWJ6q9A= +github.com/pion/transport v0.13.0 h1:KWTA5ZrQogizzYwPEciGtHPLwpAjE91FgXnyu+Hv2uY= github.com/pion/transport v0.13.0/go.mod h1:yxm9uXpK9bpBBWkITk13cLo1y5/ur5VQpG22ny6EP7g= -github.com/pion/transport v0.14.1 h1:XSM6olwW+o8J4SCmOBb/BpwZypkHeyM0PGFCxNQBr40= -github.com/pion/transport v0.14.1/go.mod h1:4tGmbk00NeYA3rUa9+n+dzCCoKkcy3YlYb99Jn2fNnI= -github.com/pion/transport/v2 v2.0.0/go.mod h1:HS2MEBJTwD+1ZI2eSXSvHJx/HnzQqRy2/LXxt6eVMHc= -github.com/pion/transport/v2 v2.1.0/go.mod h1:AdSw4YBZVDkZm8fpoz+fclXyQwANWmZAlDuQdctTThQ= -github.com/pion/transport/v2 v2.2.0/go.mod h1:AdSw4YBZVDkZm8fpoz+fclXyQwANWmZAlDuQdctTThQ= -github.com/pion/transport/v2 v2.2.1 h1:7qYnCBlpgSJNYMbLCKuSY9KbQdBFoETvPNETv0y4N7c= -github.com/pion/transport/v2 v2.2.1/go.mod h1:cXXWavvCnFF6McHTft3DWS9iic2Mftcz1Aq29pGcU5g= github.com/pion/turn/v2 v2.0.4/go.mod h1:1812p4DcGVbYVBTiraUmP50XoKye++AMkbfp+N27mog= github.com/pion/turn/v2 v2.0.5/go.mod h1:APg43CFyt/14Uy7heYUOGWdkem/Wu4PhCO/bjyrTqMw= +github.com/pion/turn/v2 v2.0.6 h1:AsXjSPR6Im15DMTB39NlfdTY9BQfieANPBjdg/aVNwY= github.com/pion/turn/v2 v2.0.6/go.mod h1:+y7xl719J8bAEVpSXBXvTxStjJv3hbz9YFflvkpcGPw= -github.com/pion/turn/v2 v2.1.0 h1:5wGHSgGhJhP/RpabkUb/T9PdsAjkGLS6toYz5HNzoSI= -github.com/pion/turn/v2 v2.1.0/go.mod h1:yrT5XbXSGX1VFSF31A3c1kCNB5bBZgk/uu5LET162qs= github.com/pion/udp v0.1.0/go.mod h1:BPELIjbwE9PRbd/zxI/KYBnbo7B6+oA6YuEaNE8lths= +github.com/pion/udp v0.1.1 h1:8UAPvyqmsxK8oOjloDk4wUt63TzFe9WEJkg5lChlj7o= github.com/pion/udp v0.1.1/go.mod h1:6AFo+CMdKQm7UiA0eUPA8/eVCTx8jBIITLZHc9DWX5M= github.com/pion/webrtc/v2 v2.2.26/go.mod h1:XMZbZRNHyPDe1gzTIHFcQu02283YO45CbiwFgKvXnmc= github.com/pion/webrtc/v3 v3.0.11/go.mod h1:WEvXneGTeqNmiR59v5jTsxMc4yXQyOQcRsrdAbNwSEU= github.com/pion/webrtc/v3 v3.0.27/go.mod h1:QpLDmsU5a/a05n230gRtxZRvfHhFzn9ukGUL2x4G5ic= github.com/pion/webrtc/v3 v3.0.32/go.mod h1:wX3V5dQQUGCifhT1mYftC2kCrDQX6ZJ3B7Yad0R9JK0= +github.com/pion/webrtc/v3 v3.1.24-0.20220208053747-94262c1b2b38 h1:+IEql+S+YAj3S5e7Ftl/u4xPcZGG0WwLFsyFj6NRTz4= github.com/pion/webrtc/v3 v3.1.24-0.20220208053747-94262c1b2b38/go.mod h1:L5S/oAhL0Fzt/rnftVQRrP80/j5jygY7XRZzWwFx6P4= -github.com/pion/webrtc/v3 v3.2.9 h1:U8NSjQDlZZ+Iy/hg42Q/u6mhEVSXYvKrOIZiZwYTfLc= -github.com/pion/webrtc/v3 v3.2.9/go.mod h1:gjQLMZeyN3jXBGdxGmUYCyKjOuYX/c99BDjGqmadq0A= github.com/pkg/browser v0.0.0-20210706143420-7d21f8c997e2/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= @@ -1871,12 +1848,14 @@ github.com/prometheus/tsdb v0.10.0 h1:If5rVCMTp6W2SiRAQFlbpJNgVlgMEd+U2GZckwK38i github.com/prometheus/tsdb v0.10.0/go.mod h1:oi49uRhEe9dPUTlS3JRZOwJuVi6tmh10QSgwXEyGCt4= github.com/quic-go/qpack v0.4.0 h1:Cr9BXA1sQS2SmDUWjSofMPNKmvF6IiIfDRmgU0w1ZCo= github.com/quic-go/qpack v0.4.0/go.mod h1:UZVnYIfi5GRk+zI9UMaCPsmZ2xKJP7XBUvVyT1Knj9A= -github.com/quic-go/qtls-go1-20 v0.3.4 h1:MfFAPULvst4yoMgY9QmtpYmfij/em7O8UUi+bNVm7Cg= -github.com/quic-go/qtls-go1-20 v0.3.4/go.mod h1:X9Nh97ZL80Z+bX/gUXMbipO6OxdiDi58b/fMC9mAL+k= -github.com/quic-go/quic-go v0.39.4 h1:PelfiuG7wXEffUT2yceiqz5V6Pc0TA5ruOd1LcmFc1s= -github.com/quic-go/quic-go v0.39.4/go.mod h1:T09QsDQWjLiQ74ZmacDfqZmhY/NLnw5BC40MANNNZ1Q= -github.com/quic-go/webtransport-go v0.6.0 h1:CvNsKqc4W2HljHJnoT+rMmbRJybShZ0YPFDD3NxaZLY= -github.com/quic-go/webtransport-go v0.6.0/go.mod h1:9KjU4AEBqEQidGHNDkZrb8CAa1abRaosM2yGOyiikEc= +github.com/quic-go/qtls-go1-19 v0.3.3 h1:wznEHvJwd+2X3PqftRha0SUKmGsnb6dfArMhy9PeJVE= +github.com/quic-go/qtls-go1-19 v0.3.3/go.mod h1:ySOI96ew8lnoKPtSqx2BlI5wCpUVPT05RMAlajtnyOI= +github.com/quic-go/qtls-go1-20 v0.2.3 h1:m575dovXn1y2ATOb1XrRFcrv0F+EQmlowTkoraNkDPI= +github.com/quic-go/qtls-go1-20 v0.2.3/go.mod h1:JKtK6mjbAVcUTN/9jZpvLbGxvdWIKS8uT7EiStoU1SM= +github.com/quic-go/quic-go v0.36.4 h1:CXn/ZLN5Vntlk53fjR+kUMC8Jt7flfQe+I5Ty5A+k0o= +github.com/quic-go/quic-go v0.36.4/go.mod h1:qxQumdeKw5GmWs1OsTZZnOxzSI+RJWuhf1O8FN35L2o= +github.com/quic-go/webtransport-go v0.5.3 h1:5XMlzemqB4qmOlgIus5zB45AcZ2kCgCy2EptUrfOPWU= +github.com/quic-go/webtransport-go v0.5.3/go.mod h1:OhmmgJIzTTqXK5xvtuX0oBpLV2GkLWNDA+UeTGJXErU= github.com/raulk/go-watchdog v1.3.0 h1:oUmdlHxdkXRJlwfG0O9omj8ukerm8MEQavSiDTEtBsk= github.com/raulk/go-watchdog v1.3.0/go.mod h1:fIvOnLbF0b0ZwkB9YU4mOW9Did//4vPZtDqv66NfsMU= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= @@ -2028,8 +2007,8 @@ github.com/status-im/migrate/v4 v4.6.2-status.3 h1:Khwjb59NzniloUr5i9s9AtkEyqBbQ github.com/status-im/migrate/v4 v4.6.2-status.3/go.mod h1:c/kc90n47GZu/58nnz1OMLTf7uE4Da4gZP5qmU+A/v8= github.com/status-im/notify v1.0.2-status h1:x8wev0Sh8H8KAf4bVcv+L0dVHldBESOKUlqRqRY7uL8= github.com/status-im/notify v1.0.2-status/go.mod h1:gF3zSOrafR9DQEWSE8TjfI9NkooDxbyT4UgRGKZA0lc= -github.com/status-im/rendezvous v1.3.8-0.20240110194857-cc5be22bf83e h1:pCOHeAYmYttXQBCn+6u01bs5d/W3XslxmplFhru4X1Y= -github.com/status-im/rendezvous v1.3.8-0.20240110194857-cc5be22bf83e/go.mod h1:LEPENTHDBGCxXVZx6FEKNKN+tfPaIK+lmiGv1DxkJW4= +github.com/status-im/rendezvous v1.3.7 h1:rZGWsFCjPV3MWeUkLkZSOGTAvyRf+rxx5hnEGLE4OHg= +github.com/status-im/rendezvous v1.3.7/go.mod h1:r0vCbQJByTteMajN0f+Mcet/Vd7uAXxFPfewNpI2iXQ= github.com/status-im/resize v0.0.0-20201215164250-7c6d9f0d3088 h1:ClCAP2FPCvl8hGMhbUx/tq/sOu2wibztAa5jAvQEe4Q= github.com/status-im/resize v0.0.0-20201215164250-7c6d9f0d3088/go.mod h1:+92j1tN27DypDeBFxkg0uzkqfh1bNHTZe3Bv2PjvxpM= github.com/status-im/status-go/extkeys v1.1.2 h1:FSjARgDathJ3rIapJt851LsIXP9Oyuu2M2jPJKuzloU= @@ -2065,9 +2044,6 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= @@ -2128,10 +2104,10 @@ github.com/vishvananda/netns v0.0.0-20200728191858-db3c7e526aae/go.mod h1:DD4vA1 github.com/vishvananda/netns v0.0.0-20210104183010-2eb08e3e575f/go.mod h1:DD4vA1DwXk04H54A1oHXtwZmA0grkVMdPxx/VGLCah0= github.com/waku-org/go-discover v0.0.0-20221209174356-61c833f34d98 h1:xwY0kW5XZFimdqfZb9cZwT1S3VJP9j3AE6bdNd9boXM= github.com/waku-org/go-discover v0.0.0-20221209174356-61c833f34d98/go.mod h1:eBHgM6T4EG0RZzxpxKy+rGz/6Dw2Nd8DWxS0lm9ESDw= -github.com/waku-org/go-libp2p-rendezvous v0.0.0-20240110193335-a67d1cc760a0 h1:R4YYx2QamhBRl/moIxkDCNW+OP7AHbyWLBygDc/xIMo= -github.com/waku-org/go-libp2p-rendezvous v0.0.0-20240110193335-a67d1cc760a0/go.mod h1:EhZP9fee0DYjKH/IOQvoNSy1tSHp2iZadsHGphcAJgY= -github.com/waku-org/go-waku v0.8.1-0.20240112174027-faf046e059a5 h1:D/IVX11ZKKUoBm9paWQFVyXyXFYAuovuqQzo9gUnqlE= -github.com/waku-org/go-waku v0.8.1-0.20240112174027-faf046e059a5/go.mod h1:nUmz07T/miK91i9b7vCIV4QN+fWElmkClvqd+1Wd9w4= +github.com/waku-org/go-libp2p-rendezvous v0.0.0-20230628220917-7b4e5ae4c0e7 h1:0e1h+p84yBp0IN7AqgbZlV7lgFBjm214lgSOE7CeJmE= +github.com/waku-org/go-libp2p-rendezvous v0.0.0-20230628220917-7b4e5ae4c0e7/go.mod h1:pFvOZ9YTFsW0o5zJW7a0B5tr1owAijRWJctXJ2toL04= +github.com/waku-org/go-waku v0.8.1-0.20240104144340-585648c4eefe h1:2D97fbaKlIQRjWMz/iTjnYcxi2z6ekKvspTGtcuPHgU= +github.com/waku-org/go-waku v0.8.1-0.20240104144340-585648c4eefe/go.mod h1:+b5fPPJ4YUIAPJtPOtwB7bTrOQ9lF15I2LnQjV6NMIA= github.com/waku-org/go-zerokit-rln v0.1.14-0.20240102145250-fa738c0bdf59 h1:jisj+OCI6QydLtFq3Pyhu49wl9ytPN7oAHjMfepHDrA= github.com/waku-org/go-zerokit-rln v0.1.14-0.20240102145250-fa738c0bdf59/go.mod h1:1PdBdPzyTaKt3VnpAHk3zj+r9dXPFOr3IHZP9nFle6E= github.com/waku-org/go-zerokit-rln-apple v0.0.0-20230916172309-ee0ee61dde2b h1:KgZVhsLkxsj5gb/FfndSCQu6VYwALrCOgYI3poR95yE= @@ -2253,16 +2229,14 @@ go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -go.uber.org/dig v1.17.1 h1:Tga8Lz8PcYNsWsyHMZ1Vm0OQOUaJNDyvPImgbAu9YSc= -go.uber.org/dig v1.17.1/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE= -go.uber.org/fx v1.20.1 h1:zVwVQGS8zYvhh9Xxcu4w1M6ESyeMzebzj2NbSayZ4Mk= -go.uber.org/fx v1.20.1/go.mod h1:iSYNbHf2y55acNCwCXKx7LbWb5WG1Bnue5RDXz1OREg= +go.uber.org/dig v1.17.0 h1:5Chju+tUvcC+N7N6EV08BJz41UZuO3BmHcN4A287ZLI= +go.uber.org/dig v1.17.0/go.mod h1:rTxpf7l5I0eBTlE6/9RL+lDybC7WFwY2QH55ZSjy1mU= +go.uber.org/fx v1.20.0 h1:ZMC/pnRvhsthOZh9MZjMq5U8Or3mA9zBSPaLnzs3ihQ= +go.uber.org/fx v1.20.0/go.mod h1:qCUj0btiR3/JnanEr1TYEePfSw6o/4qYJscgvzQ5Ub0= go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/goleak v1.1.12/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= -go.uber.org/mock v0.3.0 h1:3mUxI1No2/60yUYax92Pt8eNOEecx2D3lcXZh2NEZJo= -go.uber.org/mock v0.3.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= @@ -2275,8 +2249,8 @@ go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo= go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= -go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo= -go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so= +go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= +go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= golang.org/x/build v0.0.0-20190111050920-041ab4dc3f9d/go.mod h1:OWs+y06UdEOHN4y+MfF/py+xQ/tYqIWW03b70/CG9Rw= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= @@ -2324,10 +2298,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20211215153901-e495a2d5b3d3/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220131195533-30dcbda58838/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= -golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= -golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= -golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -2342,8 +2314,8 @@ golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u0 golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= -golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= +golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 h1:MGwJjxBy0HJshjDNfLsYO8xppfqWlA5ZT9OhtUUhTNw= +golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc= golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= @@ -2381,9 +2353,8 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.13.0 h1:I/DsJXRlw/8l/0c24sM9yb0T4z9liZTduXvdAWYiysY= -golang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180524181706-dfa909b99c79/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -2473,15 +2444,9 @@ golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= -golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= -golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= -golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= -golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= -golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/net v0.14.0 h1:BONx9s002vGdD9umnlX1Po8vOZmrgH34qlHcD1MfK14= +golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= golang.org/x/oauth2 v0.0.0-20180227000427-d7d64896b5ff/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -2517,9 +2482,8 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ= -golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= +golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E= +golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sys v0.0.0-20180224232135-f6cff0780e54/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180810173357-98c5dad5d1a0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -2675,30 +2639,19 @@ golang.org/x/sys v0.0.0-20220317061510-51cd9980dadf/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= -golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= -golang.org/x/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ= -golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= -golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= -golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= -golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek= -golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +golang.org/x/term v0.11.0 h1:F9tnn/DA/Im8nCwm+fX+1/eBwi4qFjRT++MhtVC4ZX0= +golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -2708,14 +2661,9 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= -golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -2815,9 +2763,8 @@ golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.14.0 h1:jvNa2pY0M4r62jkRQ6RwEZZyPcymeL9XZMLBbV7U2nc= -golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg= +golang.org/x/tools v0.12.1-0.20230818130535-1517d1a3ba60 h1:o4bs4seAAlSiZQAZbO6/RP5XBCZCooQS3Pgc0AUjWts= +golang.org/x/tools v0.12.1-0.20230818130535-1517d1a3ba60/go.mod h1:Sc0INKfu04TlqNoRA1hgpFZbhYXHPr4V5DzpSBTPqQM= golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -2825,6 +2772,8 @@ golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= +golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f h1:uF6paiQQebLeSXkrTqHqz0MXhXXS1KgF41eUdBNvxK0= +golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= gonum.org/v1/gonum v0.0.0-20181121035319-3f7ecaa7e8ca/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= gonum.org/v1/gonum v0.6.0/go.mod h1:9mxDZsDKxgMAuccQkewq682L+0eCu4dCN2yonUJTCLU= diff --git a/images/decode_test.go b/images/decode_test.go index e6caf292d..7df58ee1e 100644 --- a/images/decode_test.go +++ b/images/decode_test.go @@ -120,7 +120,7 @@ func TestDecodeFromURL(t *testing.T) { }, }, { - s.URL + "/1.webp", // nolint: goconst + s.URL + "/1.webp", false, image.Rectangle{ Min: image.Point{X: 0, Y: 0}, @@ -128,7 +128,7 @@ func TestDecodeFromURL(t *testing.T) { }, }, { - s.URL + "/1.webp", // nolint: goconst + s.URL + "/1.webp", true, image.Rectangle{ Min: image.Point{X: 0, Y: 0}, diff --git a/mailserver/mailserver_test.go b/mailserver/mailserver_test.go index a0e514f0d..6e707e797 100644 --- a/mailserver/mailserver_test.go +++ b/mailserver/mailserver_test.go @@ -108,7 +108,6 @@ func (s *MailserverSuite) TestInit() { } for _, tc := range testCases { - tc := tc s.T().Run(tc.info, func(*testing.T) { mailServer := &WakuMailServer{} shh := waku.New(&waku.DefaultConfig, nil) @@ -301,7 +300,6 @@ func (s *MailserverSuite) TestMailServer() { }, } for _, tc := range testCases { - tc := tc s.T().Run(tc.info, func(*testing.T) { request := s.createRequest(tc.params) src := crypto.FromECDSAPub(&tc.params.key.PublicKey) diff --git a/multiaccounts/accounts/database_test.go b/multiaccounts/accounts/database_test.go index f7371bd69..98ddd5c91 100644 --- a/multiaccounts/accounts/database_test.go +++ b/multiaccounts/accounts/database_test.go @@ -231,9 +231,9 @@ func TestWatchOnlyAccounts(t *testing.T) { require.Equal(t, wo4.Address, dbAcc.Address) // updated watch onl to save the same account after it's saved - wo4.Name = wo4.Name + "updated" // nolint: goconst + wo4.Name = wo4.Name + "updated" wo4.ColorID = common.CustomizationColorCamel - wo4.Emoji = wo4.Emoji + "updated" // nolint: goconst + wo4.Emoji = wo4.Emoji + "updated" err = db.SaveOrUpdateAccounts([]*Account{wo4}, false) require.NoError(t, err) dbAccounts, err = db.GetActiveAccounts() @@ -279,7 +279,7 @@ func TestUpdateKeypairName(t *testing.T) { require.True(t, SameKeypairs(kp, dbKeypairs[0])) // update keypair name - kp.Name = kp.Name + "updated" // nolint: goconst + kp.Name = kp.Name + "updated" kp.Accounts[0].Name = kp.Name err = db.UpdateKeypairName(kp.KeyUID, kp.Name, kp.Clock, true) require.NoError(t, err) @@ -360,9 +360,9 @@ func TestKeypairs(t *testing.T) { require.Equal(t, len(kp.Accounts), len(dbAccounts)) // update an existing account - accToUpdate.Name = accToUpdate.Name + "updated" // nolint: goconst + accToUpdate.Name = accToUpdate.Name + "updated" accToUpdate.ColorID = common.CustomizationColorBrown - accToUpdate.Emoji = accToUpdate.Emoji + "updated" // nolint: goconst + accToUpdate.Emoji = accToUpdate.Emoji + "updated" err = db.SaveOrUpdateAccounts([]*Account{accToUpdate}, false) require.NoError(t, err) diff --git a/multiaccounts/accounts/keycard_database.go b/multiaccounts/accounts/keycard_database.go index a8a852f32..4a0ab98c0 100644 --- a/multiaccounts/accounts/keycard_database.go +++ b/multiaccounts/accounts/keycard_database.go @@ -263,7 +263,14 @@ func (db *Database) deleteKeycardAccounts(tx *sql.Tx, kcUID string, accountAddre } inVector := strings.Repeat(",?", len(accountAddresses)-1) - query := `DELETE FROM keycards_accounts WHERE keycard_uid = ? AND account_address IN (?` + inVector + `)` // nolint: gosec + query := ` + DELETE + FROM + keycards_accounts + WHERE + keycard_uid = ? + AND + account_address IN (?` + inVector + `)` delete, err := tx.Prepare(query) if err != nil { diff --git a/multiaccounts/accounts/keycard_database_test.go b/multiaccounts/accounts/keycard_database_test.go index 4d88e6752..572983227 100644 --- a/multiaccounts/accounts/keycard_database_test.go +++ b/multiaccounts/accounts/keycard_database_test.go @@ -20,7 +20,7 @@ func TestKeycards(t *testing.T) { keycard2Copy := GetKeycardForSeedImportedKeypair1ForTest() keycard2Copy.KeycardUID = keycard2Copy.KeycardUID + "C" - keycard2Copy.KeycardName = keycard2Copy.KeycardName + "Copy" // nolint: goconst + keycard2Copy.KeycardName = keycard2Copy.KeycardName + "Copy" keycard2Copy.Position = keycard2Copy.Position + 1 // Pre-condition @@ -162,7 +162,7 @@ func TestKeycardsRemovalWhenDeletingKeypair(t *testing.T) { keycard2Copy := GetKeycardForSeedImportedKeypair1ForTest() keycard2Copy.KeycardUID = keycard2Copy.KeycardUID + "C" - keycard2Copy.KeycardName = keycard2Copy.KeycardName + "Copy" // nolint: goconst + keycard2Copy.KeycardName = keycard2Copy.KeycardName + "Copy" keycard2Copy.Position = keycard2Copy.Position + 1 // Pre-condition diff --git a/protocol/activity_center_persistence.go b/protocol/activity_center_persistence.go index df8efc0ec..3c14a4d8a 100644 --- a/protocol/activity_center_persistence.go +++ b/protocol/activity_center_persistence.go @@ -813,7 +813,7 @@ func (db sqlitePersistence) MarkActivityCenterNotificationsDeleted(ids []types.H return nil, err } - update := "UPDATE activity_center_notifications SET deleted = 1, updated_at = ? WHERE id IN (" + inVector + ") AND NOT deleted" // nolint: goconst, gosec + update := "UPDATE activity_center_notifications SET deleted = 1, updated_at = ? WHERE id IN (" + inVector + ") AND NOT deleted" _, err = tx.Exec(update, args...) if err != nil { return nil, err @@ -1072,7 +1072,7 @@ func (db sqlitePersistence) AcceptActivityCenterNotifications(ids []types.HexByt } inVector := strings.Repeat("?, ", len(ids)-1) + "?" - query := "UPDATE activity_center_notifications SET read = 1, accepted = 1, updated_at = ? WHERE id IN (" + inVector + ") AND NOT deleted AND updated_at < ?" // nolint: gosec, goconst + query := "UPDATE activity_center_notifications SET read = 1, accepted = 1, updated_at = ? WHERE id IN (" + inVector + ") AND NOT deleted AND updated_at < ?" // nolint: gosec _, err = tx.Exec(query, args...) if err != nil { return nil, err diff --git a/protocol/communities/manager.go b/protocol/communities/manager.go index 5db5be6c8..95665a59b 100644 --- a/protocol/communities/manager.go +++ b/protocol/communities/manager.go @@ -3703,8 +3703,8 @@ func (m *Manager) CreateHistoryArchiveTorrent(communityID types.HexBytes, msgs [ archiveDir := m.torrentConfig.DataDir + "/" + communityID.String() torrentDir := m.torrentConfig.TorrentDir - indexPath := archiveDir + "/index" // nolint: goconst - dataPath := archiveDir + "/data" // nolint: goconst + indexPath := archiveDir + "/index" + dataPath := archiveDir + "/data" wakuMessageArchiveIndexProto := &protobuf.WakuMessageArchiveIndex{} wakuMessageArchiveIndex := make(map[string]*protobuf.WakuMessageArchiveIndexMetadata) @@ -4398,11 +4398,11 @@ func (m *Manager) torrentFile(communityID string) string { } func (m *Manager) archiveIndexFile(communityID string) string { - return m.torrentConfig.DataDir + "/" + communityID + "/index" // nolint: goconst + return m.torrentConfig.DataDir + "/" + communityID + "/index" } func (m *Manager) archiveDataFile(communityID string) string { - return m.torrentConfig.DataDir + "/" + communityID + "/data" // nolint: goconst + return m.torrentConfig.DataDir + "/" + communityID + "/data" } func topicsAsByteArrays(topics []types.TopicType) [][]byte { diff --git a/protocol/communities/persistence.go b/protocol/communities/persistence.go index 399376ec1..d37bfe4af 100644 --- a/protocol/communities/persistence.go +++ b/protocol/communities/persistence.go @@ -923,7 +923,7 @@ func (p *Persistence) SaveWakuMessage(message *types.Message) error { func wakuMessageTimestampQuery(topics []types.TopicType) string { query := " FROM waku_messages WHERE " for i, topic := range topics { - query += `topic = "` + topic.String() + `"` // nolint: goconst + query += `topic = "` + topic.String() + `"` if i < len(topics)-1 { query += OR } @@ -949,10 +949,10 @@ func (p *Persistence) GetLatestWakuMessageTimestamp(topics []types.TopicType) (u func (p *Persistence) GetWakuMessagesByFilterTopic(topics []types.TopicType, from uint64, to uint64) ([]types.Message, error) { - query := "SELECT sig, timestamp, topic, payload, padding, hash, third_party_id FROM waku_messages WHERE timestamp >= " + fmt.Sprint(from) + " AND timestamp < " + fmt.Sprint(to) + " AND (" // nolint: gosec + query := "SELECT sig, timestamp, topic, payload, padding, hash, third_party_id FROM waku_messages WHERE timestamp >= " + fmt.Sprint(from) + " AND timestamp < " + fmt.Sprint(to) + " AND (" for i, topic := range topics { - query += `topic = "` + topic.String() + `"` // nolint: goconst + query += `topic = "` + topic.String() + `"` if i < len(topics)-1 { query += OR } diff --git a/protocol/message_persistence.go b/protocol/message_persistence.go index 2c9490c1c..83e3ac829 100644 --- a/protocol/message_persistence.go +++ b/protocol/message_persistence.go @@ -1483,7 +1483,7 @@ func (db sqlitePersistence) SaveMessages(messages []*common.Message) (err error) allFields := db.tableUserMessagesAllFields() valuesVector := strings.Repeat("?, ", db.tableUserMessagesAllFieldsCount()-1) + "?" - query := "INSERT INTO user_messages(" + allFields + ") VALUES (" + valuesVector + ")" // nolint: gosec, goconst + query := "INSERT INTO user_messages(" + allFields + ") VALUES (" + valuesVector + ")" // nolint: gosec stmt, err := tx.Prepare(query) if err != nil { return diff --git a/protocol/messenger_testing_utils.go b/protocol/messenger_testing_utils.go index 0cb99a00c..5a7476888 100644 --- a/protocol/messenger_testing_utils.go +++ b/protocol/messenger_testing_utils.go @@ -110,7 +110,7 @@ func WaitOnSignaledMessengerResponse(m *Messenger, condition func(*MessengerResp return nil, errors.New(errorMessage) case <-timeoutChan: - return nil, errors.New("timed out: " + errorMessage) // nolint: goconst + return nil, errors.New("timed out: " + errorMessage) default: // No immediate response, rest & loop back to retrieve again time.Sleep(interval) @@ -145,7 +145,7 @@ func WaitOnSignaledCommunityFound(m *Messenger, action func(), condition func(co return nil } case <-timeoutChan: - return errors.New("timed out: " + errorMessage) // nolint: goconst + return errors.New("timed out: " + errorMessage) } } } diff --git a/protocol/transport/filters_manager.go b/protocol/transport/filters_manager.go index c1560a832..8016ca5f9 100644 --- a/protocol/transport/filters_manager.go +++ b/protocol/transport/filters_manager.go @@ -151,8 +151,6 @@ func (f *FiltersManager) InitCommunityFilters(communityFiltersToInitialize []Com defer f.mutex.Unlock() for _, cf := range communityFiltersToInitialize { - cf := cf - if cf.PrivKey == nil { continue } @@ -166,7 +164,6 @@ func (f *FiltersManager) InitCommunityFilters(communityFiltersToInitialize []Com } for _, pubsubTopic := range topics { - pubsubTopic := pubsubTopic pk := &cf.PrivKey.PublicKey identityStr := PublicKeyToStr(pk) rawFilter, err := f.addAsymmetric(identityStr, pubsubTopic, cf.PrivKey, true) diff --git a/protocol/transport/topic.go b/protocol/transport/topic.go index 357221359..e3b74d3b4 100644 --- a/protocol/transport/topic.go +++ b/protocol/transport/topic.go @@ -35,7 +35,7 @@ func PublicKeyToStr(publicKey *ecdsa.PublicKey) string { } func PersonalDiscoveryTopic(publicKey *ecdsa.PublicKey) string { - return "contact-discovery-" + PublicKeyToStr(publicKey) // nolint: goconst + return "contact-discovery-" + PublicKeyToStr(publicKey) } // PartitionedTopic returns the associated partitioned topic string @@ -43,7 +43,7 @@ func PersonalDiscoveryTopic(publicKey *ecdsa.PublicKey) string { func PartitionedTopic(publicKey *ecdsa.PublicKey) string { partition := big.NewInt(0) partition.Mod(publicKey.X, nPartitions) - return "contact-discovery-" + strconv.FormatInt(partition.Int64(), 10) // nolint: goconst + return "contact-discovery-" + strconv.FormatInt(partition.Int64(), 10) } func ContactCodeTopic(publicKey *ecdsa.PublicKey) string { diff --git a/rpc/route_test.go b/rpc/route_test.go index 091273746..2bc3835ca 100644 --- a/rpc/route_test.go +++ b/rpc/route_test.go @@ -13,12 +13,12 @@ func TestRouteWithUpstream(t *testing.T) { router := newRouter(true) for _, method := range remoteMethods { - require.True(t, router.routeRemote(method), "method "+method+" should routed to remote") // nolint: goconst + require.True(t, router.routeRemote(method), "method "+method+" should routed to remote") } for _, method := range localTestMethods { t.Run(method, func(t *testing.T) { - require.False(t, router.routeRemote(method), "method "+method+" should routed to local") // nolint: goconst + require.False(t, router.routeRemote(method), "method "+method+" should routed to local") }) } } @@ -27,11 +27,11 @@ func TestRouteWithoutUpstream(t *testing.T) { router := newRouter(false) for _, method := range remoteMethods { - require.False(t, router.routeRemote(method), "method "+method+" should routed to locally without UpstreamEnabled") // nolint: goconst + require.False(t, router.routeRemote(method), "method "+method+" should routed to locally without UpstreamEnabled") } for _, method := range localTestMethods { - require.False(t, router.routeRemote(method), "method "+method+" should routed to local") // nolint: goconst + require.False(t, router.routeRemote(method), "method "+method+" should routed to local") } } diff --git a/server/handlers_linkpreview.go b/server/handlers_linkpreview.go index acc0337b3..a3af9728e 100644 --- a/server/handlers_linkpreview.go +++ b/server/handlers_linkpreview.go @@ -67,7 +67,7 @@ func handleLinkPreviewThumbnail(db *sql.DB, logger *zap.Logger) http.HandlerFunc return } - w.Header().Set("Content-Type", "image/"+mimeType) // nolint: goconst + w.Header().Set("Content-Type", "image/"+mimeType) w.Header().Set("Cache-Control", "no-store") _, err = w.Write(thumbnail) @@ -198,7 +198,7 @@ func handleStatusLinkPreviewThumbnail(db *sql.DB, logger *zap.Logger) http.Handl return } - w.Header().Set("Content-Type", "image/"+mimeType) // nolint: goconst + w.Header().Set("Content-Type", "image/"+mimeType) w.Header().Set("Cache-Control", "no-store") _, err = w.Write(thumbnail) diff --git a/server/handlers_test.go b/server/handlers_test.go index 2325d58f8..72f3a533c 100644 --- a/server/handlers_test.go +++ b/server/handlers_test.go @@ -195,7 +195,7 @@ func (s *HandlersSuite) TestHandleLinkPreviewThumbnail() { msg.UnfurledLinks[0].ThumbnailPayload = tc.ThumbnailPayload s.saveUserMessage(&msg) - requestURL := "/dummy?" + tc.Parameters.Encode() // nolint: goconst + requestURL := "/dummy?" + tc.Parameters.Encode() rr := s.httpGetReqRecorder(handler, requestURL) s.Require().Equal(tc.ExpectedHTTPStatusCode, rr.Code) if tc.CheckFunc != nil { @@ -534,7 +534,7 @@ func (s *HandlersSuite) TestHandleStatusLinkPreviewThumbnail() { for _, tc := range testCases { s.Run(tc.Name, func() { - requestURL := "/dummy?" + tc.Parameters.Encode() // nolint: goconst + requestURL := "/dummy?" + tc.Parameters.Encode() rr := s.httpGetReqRecorder(handler, requestURL) s.Require().Equal(tc.ExpectedHTTPStatusCode, rr.Code) diff --git a/server/pairing/server_pairing_test.go b/server/pairing/server_pairing_test.go index 9da33d83d..b8dbb87cb 100644 --- a/server/pairing/server_pairing_test.go +++ b/server/pairing/server_pairing_test.go @@ -261,8 +261,6 @@ func (s *PairingServerSuite) TestPairingServer_handlePairingChallengeMiddleware_ s.Require().Equal("[client] status not ok when receiving account data, received '403 Forbidden'", err.Error()) } -const helloMsg = "Hello I like to be a tls server. You said: `" - func testHandler(t *testing.T) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { say, ok := r.URL.Query()["say"] @@ -270,7 +268,7 @@ func testHandler(t *testing.T) func(w http.ResponseWriter, r *http.Request) { say = append(say, "nothing") } - _, err := w.Write([]byte("Hello I like to be a tls server. You said: `" + say[0] + "` " + time.Now().String())) // nolint: goconst + _, err := w.Write([]byte("Hello I like to be a tls server. You said: `" + say[0] + "` " + time.Now().String())) if err != nil { require.NoError(t, err) } @@ -320,5 +318,5 @@ func (s *PairingServerSuite) TestGetOutboundIPWithFullServerE2e() { content, err := ioutil.ReadAll(response.Body) s.Require().NoError(err) - s.Require().Equal(helloMsg+thing+"`", string(content[:109])) + s.Require().Equal("Hello I like to be a tls server. You said: `"+thing+"`", string(content[:109])) } diff --git a/server/server_test.go b/server/server_test.go index 93ceb68c6..7a0074a5d 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -93,55 +93,55 @@ func (s *ServerURLSuite) TestServer_MakeBaseURL() { } func (s *ServerURLSuite) TestServer_MakeImageServerURL() { - s.Require().Equal(baseURLWithCustomPort+"/messages/", s.server.MakeImageServerURL()) // nolint: goconst - s.testNoPort(baseURLWithDefaultPort+"/messages/", s.serverNoPort.MakeImageServerURL()) // nolint: goconst + s.Require().Equal(baseURLWithCustomPort+"/messages/", s.server.MakeImageServerURL()) + s.testNoPort(baseURLWithDefaultPort+"/messages/", s.serverNoPort.MakeImageServerURL()) } func (s *ServerURLSuite) TestServer_MakeImageURL() { s.Require().Equal( - baseURLWithCustomPort+"/messages/images?messageId=0x10aded70ffee", // nolint: goconst + baseURLWithCustomPort+"/messages/images?messageId=0x10aded70ffee", s.server.MakeImageURL("0x10aded70ffee")) s.testNoPort( - baseURLWithDefaultPort+"/messages/images?messageId=0x10aded70ffee", // nolint: goconst + baseURLWithDefaultPort+"/messages/images?messageId=0x10aded70ffee", s.serverNoPort.MakeImageURL("0x10aded70ffee")) } func (s *ServerURLSuite) TestServer_MakeLinkPreviewThumbnailURL() { s.Require().Equal( - baseURLWithCustomPort+"/link-preview/thumbnail?message-id=99&url=https%3A%2F%2Fgithub.com", // nolint: goconst + baseURLWithCustomPort+"/link-preview/thumbnail?message-id=99&url=https%3A%2F%2Fgithub.com", s.server.MakeLinkPreviewThumbnailURL("99", "https://github.com")) s.testNoPort( - baseURLWithDefaultPort+"/link-preview/thumbnail?message-id=99&url=https%3A%2F%2Fgithub.com", // nolint: goconst + baseURLWithDefaultPort+"/link-preview/thumbnail?message-id=99&url=https%3A%2F%2Fgithub.com", s.serverNoPort.MakeLinkPreviewThumbnailURL("99", "https://github.com")) } func (s *ServerURLSuite) TestServer_MakeStatusLinkPreviewThumbnailURL() { s.Require().Equal( - baseURLWithCustomPort+"/status-link-preview/thumbnail?image-id=contact-icon&message-id=99&url=https%3A%2F%2Fstatus.app", // nolint: goconst + baseURLWithCustomPort+"/status-link-preview/thumbnail?image-id=contact-icon&message-id=99&url=https%3A%2F%2Fstatus.app", s.server.MakeStatusLinkPreviewThumbnailURL("99", "https://status.app", common.MediaServerContactIcon)) s.testNoPort( - baseURLWithDefaultPort+"/status-link-preview/thumbnail?image-id=contact-icon&message-id=99&url=https%3A%2F%2Fstatus.app", // nolint: goconst + baseURLWithDefaultPort+"/status-link-preview/thumbnail?image-id=contact-icon&message-id=99&url=https%3A%2F%2Fstatus.app", s.serverNoPort.MakeStatusLinkPreviewThumbnailURL("99", "https://status.app", common.MediaServerContactIcon)) } func (s *ServerURLSuite) TestServer_MakeAudioURL() { s.Require().Equal( - baseURLWithCustomPort+"/messages/audio?messageId=0xde1e7ebee71e", // nolint: goconst + baseURLWithCustomPort+"/messages/audio?messageId=0xde1e7ebee71e", s.server.MakeAudioURL("0xde1e7ebee71e")) s.testNoPort( - baseURLWithDefaultPort+"/messages/audio?messageId=0xde1e7ebee71e", // nolint: goconst + baseURLWithDefaultPort+"/messages/audio?messageId=0xde1e7ebee71e", s.serverNoPort.MakeAudioURL("0xde1e7ebee71e")) } func (s *ServerURLSuite) TestServer_MakeStickerURL() { s.Require().Equal( - baseURLWithCustomPort+"/ipfs?hash=0xdeadbeef4ac0", // nolint: goconst + baseURLWithCustomPort+"/ipfs?hash=0xdeadbeef4ac0", s.server.MakeStickerURL("0xdeadbeef4ac0")) s.testNoPort( - baseURLWithDefaultPort+"/ipfs?hash=0xdeadbeef4ac0", // nolint: goconst + baseURLWithDefaultPort+"/ipfs?hash=0xdeadbeef4ac0", s.serverNoPort.MakeStickerURL("0xdeadbeef4ac0")) } diff --git a/services/mailservers/database.go b/services/mailservers/database.go index 853a692eb..0a9e2e6a0 100644 --- a/services/mailservers/database.go +++ b/services/mailservers/database.go @@ -37,7 +37,7 @@ func (m Mailserver) IDBytes() ([]byte, error) { if err != nil { return nil, err } - return []byte(id), err + return []byte(id.Pretty()), err } node, err := enode.ParseV4(m.Address) diff --git a/services/wallet/balance/balance_cache.go b/services/wallet/balance/balance_cache.go index 2fd079041..4d9bde8e6 100644 --- a/services/wallet/balance/balance_cache.go +++ b/services/wallet/balance/balance_cache.go @@ -56,9 +56,9 @@ type genericCache[B cacheIface[uint64, *big.Int], N cacheIface[uint64, *int64], nonceRangeCache[NR] // balances maps an address and chain to a cache of a block number and the balance of this particular address on the chain - balances addressChainMap[B] // nolint: structcheck - nonces addressChainMap[N] // nolint: structcheck - rw sync.RWMutex // nolint: structcheck + balances addressChainMap[B] + nonces addressChainMap[N] + rw sync.RWMutex } func (b *genericCache[_, _, _]) GetBalance(account common.Address, chainID uint64, blockNumber *big.Int) *big.Int { diff --git a/services/wallet/balance/nonce_range.go b/services/wallet/balance/nonce_range.go index c3ebcd6a0..27b369825 100644 --- a/services/wallet/balance/nonce_range.go +++ b/services/wallet/balance/nonce_range.go @@ -18,9 +18,9 @@ type nonceRange struct { type sortedNonceRangesCacheType addressChainMap[[]nonceRange] // address->chainID->[]nonceRange type nonceRangeCache[T cacheIface[int64, nonceRange]] struct { - nonceRanges addressChainMap[T] // nolint: structcheck - sortedRanges sortedNonceRangesCacheType // nolint: structcheck - rw sync.RWMutex // nolint: structcheck + nonceRanges addressChainMap[T] + sortedRanges sortedNonceRangesCacheType + rw sync.RWMutex } func newNonceRangeCache[T cacheIface[int64, nonceRange]]() *nonceRangeCache[T] { diff --git a/services/wallet/balance/simple_cache.go b/services/wallet/balance/simple_cache.go index 78361f2d5..b071a1c54 100644 --- a/services/wallet/balance/simple_cache.go +++ b/services/wallet/balance/simple_cache.go @@ -11,7 +11,7 @@ func NewSimpleCacher() Cacher { // implements cacheIface for plain map internal storage type mapCache[K comparable, V any] struct { - cache map[K]V // nolint: structcheck + cache map[K]V } func (c *mapCache[K, V]) get(key K) V { diff --git a/services/wallet/balance/ttl_cache.go b/services/wallet/balance/ttl_cache.go index f0c74cd15..a438658bb 100644 --- a/services/wallet/balance/ttl_cache.go +++ b/services/wallet/balance/ttl_cache.go @@ -20,7 +20,7 @@ func NewCacherWithTTL(ttl time.Duration) Cacher { // TTL cache implementation of cacheIface type ttlCache[K comparable, V any] struct { - cache *ttlcache.Cache[K, V] // nolint: structcheck + cache *ttlcache.Cache[K, V] } //nolint:golint,unused // linter does not detect using it via reflect diff --git a/services/wallet/on_ramp_test.go b/services/wallet/on_ramp_test.go index 602669c23..5fa93f15f 100644 --- a/services/wallet/on_ramp_test.go +++ b/services/wallet/on_ramp_test.go @@ -21,7 +21,7 @@ func TestCryptoOnRamps_Get(t *testing.T) { {options: &CryptoOnRampOptions{dataSourceType: DataSourceStatic}}, {options: &CryptoOnRampOptions{ dataSourceType: DataSourceHTTP, - dataSource: s.URL + "/ramps.json", // nolint: goconst + dataSource: s.URL + "/ramps.json", }}, } @@ -40,7 +40,7 @@ func TestCryptoOnRampManager_hasCacheExpired(t *testing.T) { corm := NewCryptoOnRampManager(&CryptoOnRampOptions{ dataSourceType: DataSourceHTTP, - dataSource: s.URL + "/ramps.json", // nolint: goconst + dataSource: s.URL + "/ramps.json", }) nt := time.Time{}.Add(30 * time.Minute) diff --git a/services/wallet/transfer/database.go b/services/wallet/transfer/database.go index 58457cea6..b734ff537 100644 --- a/services/wallet/transfer/database.go +++ b/services/wallet/transfer/database.go @@ -327,7 +327,6 @@ func insertBlocksWithTransactions(chainID uint64, creator statementCreator, head func updateOrInsertTransfers(chainID uint64, creator statementCreator, transfers []Transfer) error { txsDBFields := make([]transferDBFields, 0, len(transfers)) for _, t := range transfers { - t := t var receiptType *uint8 var txHash, blockHash *common.Hash var receiptStatus, cumulativeGasUsed, gasUsed *uint64 diff --git a/services/wallet/transfer/transaction_manager_multitransaction.go b/services/wallet/transfer/transaction_manager_multitransaction.go index 26437665e..729e5010a 100644 --- a/services/wallet/transfer/transaction_manager_multitransaction.go +++ b/services/wallet/transfer/transaction_manager_multitransaction.go @@ -65,14 +65,14 @@ func rowsToMultiTransactions(rows *sql.Rows) ([]*MultiTransaction, error) { if fromAmountDB.Valid { multiTransaction.FromAmount = new(hexutil.Big) if _, ok := (*big.Int)(multiTransaction.FromAmount).SetString(fromAmountDB.String, 0); !ok { - return nil, errors.New("failed to convert fromAmountDB.String to big.Int: " + fromAmountDB.String) // nolint: goconst + return nil, errors.New("failed to convert fromAmountDB.String to big.Int: " + fromAmountDB.String) } } if toAmountDB.Valid { multiTransaction.ToAmount = new(hexutil.Big) if _, ok := (*big.Int)(multiTransaction.ToAmount).SetString(toAmountDB.String, 0); !ok { - return nil, errors.New("failed to convert fromAmountDB.String to big.Int: " + toAmountDB.String) // nolint: goconst + return nil, errors.New("failed to convert fromAmountDB.String to big.Int: " + toAmountDB.String) } } diff --git a/shell.nix b/shell.nix index 6b16dae48..589e52177 100644 --- a/shell.nix +++ b/shell.nix @@ -10,8 +10,8 @@ android_sdk.accept_license = true; }; overlays = [ - (final: prev: { - androidPkgs = prev.androidenv.composeAndroidPackages { + (self: super: { + androidPkgs = pkgs.androidenv.composeAndroidPackages { toolsVersion = "26.1.1"; platformToolsVersion = "33.0.3"; buildToolsVersions = [ "31.0.0" ]; @@ -24,19 +24,6 @@ "extras;google;m2repository" ]; }; - # https://github.com/golang/go/issues/58426 - gomobile = prev.gomobile.override { - buildGoModule = args: prev.buildGo120Module ( args // rec { - version = "unstable-2023-11-27"; - src = prev.fetchgit { - rev = "76ac6878050a2eef81867f2c6c21108e59919e8f"; - name = "gomobile"; - url = "https://go.googlesource.com/mobile"; - sha256 = "sha256-mq7gKccvI7VCBEiQTueWxMPOCgg/MGE8y2+BlwWx5pw="; - }; - vendorSha256 = "sha256-8OBLVd4zs89hoJXzC8BPRgrYjjR7DiA39+7tTaSYUFI="; - }); - }; }) ]; } @@ -62,7 +49,7 @@ in pkgs.mkShell { buildInputs = with pkgs; [ git jq which - go_1_20 golangci-lint go-junit-report gopls go-bindata gomobileMod + go_1_19 golangci-lint go-junit-report gopls go-bindata gomobileMod mockgen protobuf3_20 protoc-gen-go ] ++ lib.optional stdenv.isDarwin xcodeWrapper; @@ -76,4 +63,4 @@ in pkgs.mkShell { # Sandbox causes Xcode issues on MacOS. Requires sandbox=relaxed. # https://github.com/status-im/status-mobile/pull/13912 __noChroot = stdenv.isDarwin; -} \ No newline at end of file +} diff --git a/transactions/transactor_test.go b/transactions/transactor_test.go index b4edca5a7..e3f432c7d 100644 --- a/transactions/transactor_test.go +++ b/transactions/transactor_test.go @@ -267,7 +267,6 @@ func (s *TransactorSuite) TestSendTransactionWithSignature() { } for _, scenario := range scenarios { - scenario := scenario desc := fmt.Sprintf("nonceFromNetwork: %d, tx nonce: %d, expect error: %v", scenario.nonceFromNetwork, scenario.txNonce, scenario.expectError) s.T().Run(desc, func(t *testing.T) { nonce := scenario.txNonce diff --git a/vendor/go.uber.org/mock/mockgen/mockgen.go b/vendor/github.com/golang/mock/mockgen/mockgen.go similarity index 64% rename from vendor/go.uber.org/mock/mockgen/mockgen.go rename to vendor/github.com/golang/mock/mockgen/mockgen.go index feb747fac..50487070e 100644 --- a/vendor/go.uber.org/mock/mockgen/mockgen.go +++ b/vendor/github.com/golang/mock/mockgen/mockgen.go @@ -21,11 +21,11 @@ package main import ( "bytes" "encoding/json" - "errors" "flag" "fmt" "go/token" "io" + "io/ioutil" "log" "os" "os/exec" @@ -36,14 +36,14 @@ import ( "strings" "unicode" + "github.com/golang/mock/mockgen/model" + "golang.org/x/mod/modfile" toolsimports "golang.org/x/tools/imports" - - "go.uber.org/mock/mockgen/model" ) const ( - gomockImportPath = "go.uber.org/mock/gomock" + gomockImportPath = "github.com/golang/mock/gomock" ) var ( @@ -53,19 +53,13 @@ var ( ) var ( - source = flag.String("source", "", "(source mode) Input Go source file; enables source mode.") - destination = flag.String("destination", "", "Output file; defaults to stdout.") - mockNames = flag.String("mock_names", "", "Comma-separated interfaceName=mockName pairs of explicit mock names to use. Mock names default to 'Mock'+ interfaceName suffix.") - packageOut = flag.String("package", "", "Package of the generated code; defaults to the package of the input with a 'mock_' prefix.") - selfPackage = flag.String("self_package", "", "The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.") - writePkgComment = flag.Bool("write_package_comment", true, "Writes package documentation comment (godoc) if true.") - writeSourceComment = flag.Bool("write_source_comment", true, "Writes original file (source mode) or interface names (reflect mode) comment if true.") - writeGenerateDirective = flag.Bool("write_generate_directive", false, "Add //go:generate directive to regenerate the mock") - copyrightFile = flag.String("copyright_file", "", "Copyright file used to add copyright header") - typed = flag.Bool("typed", false, "Generate Type-safe 'Return', 'Do', 'DoAndReturn' function") - imports = flag.String("imports", "", "(source mode) Comma-separated name=path pairs of explicit imports to use.") - auxFiles = flag.String("aux_files", "", "(source mode) Comma-separated pkg=path pairs of auxiliary Go source files.") - excludeInterfaces = flag.String("exclude_interfaces", "", "Comma-separated names of interfaces to be excluded") + source = flag.String("source", "", "(source mode) Input Go source file; enables source mode.") + destination = flag.String("destination", "", "Output file; defaults to stdout.") + mockNames = flag.String("mock_names", "", "Comma-separated interfaceName=mockName pairs of explicit mock names to use. Mock names default to 'Mock'+ interfaceName suffix.") + packageOut = flag.String("package", "", "Package of the generated code; defaults to the package of the input with a 'mock_' prefix.") + selfPackage = flag.String("self_package", "", "The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.") + writePkgComment = flag.Bool("write_package_comment", true, "Writes package documentation comment (godoc) if true.") + copyrightFile = flag.String("copyright_file", "", "Copyright file used to add copyright header") debugParser = flag.Bool("debug_parser", false, "Print out parser results only.") showVersion = flag.Bool("version", false, "Print version.") @@ -113,6 +107,19 @@ func main() { return } + dst := os.Stdout + if len(*destination) > 0 { + if err := os.MkdirAll(filepath.Dir(*destination), os.ModePerm); err != nil { + log.Fatalf("Unable to create directory: %v", err) + } + f, err := os.Create(*destination) + if err != nil { + log.Fatalf("Failed opening destination file: %v", err) + } + defer f.Close() + dst = f + } + outputPackageName := *packageOut if outputPackageName == "" { // pkg.Name in reflect mode is the base name of the import path, @@ -154,7 +161,7 @@ func main() { g.mockNames = parseMockNames(*mockNames) } if *copyrightFile != "" { - header, err := os.ReadFile(*copyrightFile) + header, err := ioutil.ReadFile(*copyrightFile) if err != nil { log.Fatalf("Failed reading copyright file: %v", err) } @@ -164,27 +171,7 @@ func main() { if err := g.Generate(pkg, outputPackageName, outputPackagePath); err != nil { log.Fatalf("Failed generating mock: %v", err) } - output := g.Output() - dst := os.Stdout - if len(*destination) > 0 { - if err := os.MkdirAll(filepath.Dir(*destination), os.ModePerm); err != nil { - log.Fatalf("Unable to create directory: %v", err) - } - existing, err := os.ReadFile(*destination) - if err != nil && !errors.Is(err, os.ErrNotExist) { - log.Fatalf("Failed reading pre-exiting destination file: %v", err) - } - if len(existing) == len(output) && bytes.Equal(existing, output) { - return - } - f, err := os.Create(*destination) - if err != nil { - log.Fatalf("Failed opening destination file: %v", err) - } - defer f.Close() - dst = f - } - if _, err := dst.Write(output); err != nil { + if _, err := dst.Write(g.Output()); err != nil { log.Fatalf("Failed writing to destination: %v", err) } } @@ -201,24 +188,6 @@ func parseMockNames(names string) map[string]string { return mocksMap } -func parseExcludeInterfaces(names string) map[string]struct{} { - splitNames := strings.Split(names, ",") - namesSet := make(map[string]struct{}, len(splitNames)) - for _, name := range splitNames { - if name == "" { - continue - } - - namesSet[name] = struct{}{} - } - - if len(namesSet) == 0 { - return nil - } - - return namesSet -} - func usage() { _, _ = io.WriteString(os.Stderr, usageText) flag.PrintDefaults() @@ -253,7 +222,7 @@ type generator struct { packageMap map[string]string // map from import path to package name } -func (g *generator) p(format string, args ...any) { +func (g *generator) p(format string, args ...interface{}) { fmt.Fprintf(&g.buf, g.indent+format+"\n", args...) } @@ -305,17 +274,12 @@ func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPac } g.p("// Code generated by MockGen. DO NOT EDIT.") - if *writeSourceComment { - if g.filename != "" { - g.p("// Source: %v", g.filename) - } else { - g.p("// Source: %v (interfaces: %v)", g.srcPackage, g.srcInterfaces) - } + if g.filename != "" { + g.p("// Source: %v", g.filename) + } else { + g.p("// Source: %v (interfaces: %v)", g.srcPackage, g.srcInterfaces) } - g.p("//") - g.p("// Generated by this command:") - // only log the name of the executable, not the full path - g.p("// %v", strings.Join(append([]string{filepath.Base(os.Args[0])}, os.Args[1:]...), " ")) + g.p("") // Get all required imports, and generate unique names for them all. im := pkg.Imports() @@ -341,16 +305,6 @@ func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPac packagesName := createPackageMap(sortedPaths) - definedImports := make(map[string]string, len(im)) - if *imports != "" { - for _, kv := range strings.Split(*imports, ",") { - eq := strings.Index(kv, "=") - if k, v := kv[:eq], kv[eq+1:]; k != "." { - definedImports[v] = k - } - } - } - g.packageMap = make(map[string]string, len(im)) localNames := make(map[string]bool, len(im)) for _, pth := range sortedPaths { @@ -362,14 +316,9 @@ func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPac // Local names for an imported package can usually be the basename of the import path. // A couple of situations don't permit that, such as duplicate local names // (e.g. importing "html/template" and "text/template"), or where the basename is - // a keyword (e.g. "foo/case") or when defining a name for that by using the -imports flag. + // a keyword (e.g. "foo/case"). // try base0, base1, ... pkgName := base - - if _, ok := definedImports[base]; ok { - pkgName = definedImports[base] - } - i := 0 for localNames[pkgName] || token.Lookup(pkgName).IsKeyword() { pkgName = base + strconv.Itoa(i) @@ -404,10 +353,6 @@ func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPac g.out() g.p(")") - if *writeGenerateDirective { - g.p("//go:generate %v", strings.Join(os.Args, " ")) - } - for _, intf := range pkg.Interfaces { if err := g.GenerateMockInterface(intf, outputPackagePath); err != nil { return err @@ -426,58 +371,32 @@ func (g *generator) mockName(typeName string) string { return "Mock" + typeName } -// formattedTypeParams returns a long and short form of type param info used for -// printing. If analyzing a interface with type param [I any, O any] the result -// will be: -// "[I any, O any]", "[I, O]" -func (g *generator) formattedTypeParams(it *model.Interface, pkgOverride string) (string, string) { - if len(it.TypeParams) == 0 { - return "", "" - } - var long, short strings.Builder - long.WriteString("[") - short.WriteString("[") - for i, v := range it.TypeParams { - if i != 0 { - long.WriteString(", ") - short.WriteString(", ") - } - long.WriteString(v.Name) - short.WriteString(v.Name) - long.WriteString(fmt.Sprintf(" %s", v.Type.String(g.packageMap, pkgOverride))) - } - long.WriteString("]") - short.WriteString("]") - return long.String(), short.String() -} - func (g *generator) GenerateMockInterface(intf *model.Interface, outputPackagePath string) error { mockType := g.mockName(intf.Name) - longTp, shortTp := g.formattedTypeParams(intf, outputPackagePath) g.p("") g.p("// %v is a mock of %v interface.", mockType, intf.Name) - g.p("type %v%v struct {", mockType, longTp) + g.p("type %v struct {", mockType) g.in() g.p("ctrl *gomock.Controller") - g.p("recorder *%vMockRecorder%v", mockType, shortTp) + g.p("recorder *%vMockRecorder", mockType) g.out() g.p("}") g.p("") g.p("// %vMockRecorder is the mock recorder for %v.", mockType, mockType) - g.p("type %vMockRecorder%v struct {", mockType, longTp) + g.p("type %vMockRecorder struct {", mockType) g.in() - g.p("mock *%v%v", mockType, shortTp) + g.p("mock *%v", mockType) g.out() g.p("}") g.p("") g.p("// New%v creates a new mock instance.", mockType) - g.p("func New%v%v(ctrl *gomock.Controller) *%v%v {", mockType, longTp, mockType, shortTp) + g.p("func New%v(ctrl *gomock.Controller) *%v {", mockType, mockType) g.in() - g.p("mock := &%v%v{ctrl: ctrl}", mockType, shortTp) - g.p("mock.recorder = &%vMockRecorder%v{mock}", mockType, shortTp) + g.p("mock := &%v{ctrl: ctrl}", mockType) + g.p("mock.recorder = &%vMockRecorder{mock}", mockType) g.p("return mock") g.out() g.p("}") @@ -485,13 +404,13 @@ func (g *generator) GenerateMockInterface(intf *model.Interface, outputPackagePa // XXX: possible name collision here if someone has EXPECT in their interface. g.p("// EXPECT returns an object that allows the caller to indicate expected use.") - g.p("func (m *%v%v) EXPECT() *%vMockRecorder%v {", mockType, shortTp, mockType, shortTp) + g.p("func (m *%v) EXPECT() *%vMockRecorder {", mockType, mockType) g.in() g.p("return m.recorder") g.out() g.p("}") - g.GenerateMockMethods(mockType, intf, outputPackagePath, longTp, shortTp, *typed) + g.GenerateMockMethods(mockType, intf, outputPackagePath) return nil } @@ -502,17 +421,13 @@ func (b byMethodName) Len() int { return len(b) } func (b byMethodName) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byMethodName) Less(i, j int) bool { return b[i].Name < b[j].Name } -func (g *generator) GenerateMockMethods(mockType string, intf *model.Interface, pkgOverride, longTp, shortTp string, typed bool) { +func (g *generator) GenerateMockMethods(mockType string, intf *model.Interface, pkgOverride string) { sort.Sort(byMethodName(intf.Methods)) for _, m := range intf.Methods { g.p("") - _ = g.GenerateMockMethod(mockType, m, pkgOverride, shortTp) + _ = g.GenerateMockMethod(mockType, m, pkgOverride) g.p("") - _ = g.GenerateMockRecorderMethod(intf, mockType, m, shortTp, typed) - if typed { - g.p("") - _ = g.GenerateMockReturnCallMethod(intf, m, pkgOverride, longTp, shortTp) - } + _ = g.GenerateMockRecorderMethod(mockType, m) } } @@ -531,9 +446,9 @@ func makeArgString(argNames, argTypes []string) string { // GenerateMockMethod generates a mock method implementation. // If non-empty, pkgOverride is the package in which unqualified types reside. -func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOverride, shortTp string) error { - argNames := g.getArgNames(m, true /* in */) - argTypes := g.getArgTypes(m, pkgOverride, true /* in */) +func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOverride string) error { + argNames := g.getArgNames(m) + argTypes := g.getArgTypes(m, pkgOverride) argString := makeArgString(argNames, argTypes) rets := make([]string, len(m.Out)) @@ -552,7 +467,7 @@ func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOver idRecv := ia.allocateIdentifier("m") g.p("// %v mocks base method.", m.Name) - g.p("func (%v *%v%v) %v(%v)%v {", idRecv, mockType, shortTp, m.Name, argString, retString) + g.p("func (%v *%v) %v(%v)%v {", idRecv, mockType, m.Name, argString, retString) g.in() g.p("%s.ctrl.T.Helper()", idRecv) @@ -562,11 +477,11 @@ func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOver callArgs = ", " + strings.Join(argNames, ", ") } } else { - // Non-trivial. The generated code must build a []any, + // Non-trivial. The generated code must build a []interface{}, // but the variadic argument may be any type. idVarArgs := ia.allocateIdentifier("varargs") idVArg := ia.allocateIdentifier("a") - g.p("%s := []any{%s}", idVarArgs, strings.Join(argNames[:len(argNames)-1], ", ")) + g.p("%s := []interface{}{%s}", idVarArgs, strings.Join(argNames[:len(argNames)-1], ", ")) g.p("for _, %s := range %s {", idVArg, argNames[len(argNames)-1]) g.in() g.p("%s = append(%s, %s)", idVarArgs, idVarArgs, idVArg) @@ -596,8 +511,8 @@ func (g *generator) GenerateMockMethod(mockType string, m *model.Method, pkgOver return nil } -func (g *generator) GenerateMockRecorderMethod(intf *model.Interface, mockType string, m *model.Method, shortTp string, typed bool) error { - argNames := g.getArgNames(m, true) +func (g *generator) GenerateMockRecorderMethod(mockType string, m *model.Method) error { + argNames := g.getArgNames(m) var argString string if m.Variadic == nil { @@ -606,26 +521,21 @@ func (g *generator) GenerateMockRecorderMethod(intf *model.Interface, mockType s argString = strings.Join(argNames[:len(argNames)-1], ", ") } if argString != "" { - argString += " any" + argString += " interface{}" } if m.Variadic != nil { if argString != "" { argString += ", " } - argString += fmt.Sprintf("%s ...any", argNames[len(argNames)-1]) + argString += fmt.Sprintf("%s ...interface{}", argNames[len(argNames)-1]) } ia := newIdentifierAllocator(argNames) idRecv := ia.allocateIdentifier("mr") g.p("// %v indicates an expected call of %v.", m.Name, m.Name) - if typed { - g.p("func (%s *%vMockRecorder%v) %v(%v) *%s%sCall%s {", idRecv, mockType, shortTp, m.Name, argString, intf.Name, m.Name, shortTp) - } else { - g.p("func (%s *%vMockRecorder%v) %v(%v) *gomock.Call {", idRecv, mockType, shortTp, m.Name, argString) - } - + g.p("func (%s *%vMockRecorder) %v(%v) *gomock.Call {", idRecv, mockType, m.Name, argString) g.in() g.p("%s.mock.ctrl.T.Helper()", idRecv) @@ -641,121 +551,42 @@ func (g *generator) GenerateMockRecorderMethod(intf *model.Interface, mockType s } else { // Hard: create a temporary slice. idVarArgs := ia.allocateIdentifier("varargs") - g.p("%s := append([]any{%s}, %s...)", + g.p("%s := append([]interface{}{%s}, %s...)", idVarArgs, strings.Join(argNames[:len(argNames)-1], ", "), argNames[len(argNames)-1]) callArgs = ", " + idVarArgs + "..." } } - if typed { - g.p(`call := %s.mock.ctrl.RecordCallWithMethodType(%s.mock, "%s", reflect.TypeOf((*%s%s)(nil).%s)%s)`, idRecv, idRecv, m.Name, mockType, shortTp, m.Name, callArgs) - g.p(`return &%s%sCall%s{Call: call}`, intf.Name, m.Name, shortTp) - } else { - g.p(`return %s.mock.ctrl.RecordCallWithMethodType(%s.mock, "%s", reflect.TypeOf((*%s%s)(nil).%s)%s)`, idRecv, idRecv, m.Name, mockType, shortTp, m.Name, callArgs) - } + g.p(`return %s.mock.ctrl.RecordCallWithMethodType(%s.mock, "%s", reflect.TypeOf((*%s)(nil).%s)%s)`, idRecv, idRecv, m.Name, mockType, m.Name, callArgs) g.out() g.p("}") return nil } -func (g *generator) GenerateMockReturnCallMethod(intf *model.Interface, m *model.Method, pkgOverride, longTp, shortTp string) error { - argNames := g.getArgNames(m, true /* in */) - retNames := g.getArgNames(m, false /* out */) - argTypes := g.getArgTypes(m, pkgOverride, true /* in */) - retTypes := g.getArgTypes(m, pkgOverride, false /* out */) - argString := strings.Join(argTypes, ", ") - - rets := make([]string, len(m.Out)) - for i, p := range m.Out { - rets[i] = p.Type.String(g.packageMap, pkgOverride) - } - - var retString string - switch { - case len(rets) == 1: - retString = " " + rets[0] - case len(rets) > 1: - retString = " (" + strings.Join(rets, ", ") + ")" - } - - ia := newIdentifierAllocator(argNames) - idRecv := ia.allocateIdentifier("c") - - recvStructName := intf.Name + m.Name - - g.p("// %s%sCall wrap *gomock.Call", intf.Name, m.Name) - g.p("type %s%sCall%s struct{", intf.Name, m.Name, longTp) - g.in() - g.p("*gomock.Call") - g.out() - g.p("}") - - g.p("// Return rewrite *gomock.Call.Return") - g.p("func (%s *%sCall%s) Return(%v) *%sCall%s {", idRecv, recvStructName, shortTp, makeArgString(retNames, retTypes), recvStructName, shortTp) - g.in() - var retArgs string - if len(retNames) > 0 { - retArgs = strings.Join(retNames, ", ") - } - g.p(`%s.Call = %v.Call.Return(%v)`, idRecv, idRecv, retArgs) - g.p("return %s", idRecv) - g.out() - g.p("}") - - g.p("// Do rewrite *gomock.Call.Do") - g.p("func (%s *%sCall%s) Do(f func(%v)%v) *%sCall%s {", idRecv, recvStructName, shortTp, argString, retString, recvStructName, shortTp) - g.in() - g.p(`%s.Call = %v.Call.Do(f)`, idRecv, idRecv) - g.p("return %s", idRecv) - g.out() - g.p("}") - - g.p("// DoAndReturn rewrite *gomock.Call.DoAndReturn") - g.p("func (%s *%sCall%s) DoAndReturn(f func(%v)%v) *%sCall%s {", idRecv, recvStructName, shortTp, argString, retString, recvStructName, shortTp) - g.in() - g.p(`%s.Call = %v.Call.DoAndReturn(f)`, idRecv, idRecv) - g.p("return %s", idRecv) - g.out() - g.p("}") - return nil -} - -func (g *generator) getArgNames(m *model.Method, in bool) []string { - var params []*model.Parameter - if in { - params = m.In - } else { - params = m.Out - } - argNames := make([]string, len(params)) - for i, p := range params { +func (g *generator) getArgNames(m *model.Method) []string { + argNames := make([]string, len(m.In)) + for i, p := range m.In { name := p.Name if name == "" || name == "_" { name = fmt.Sprintf("arg%d", i) } argNames[i] = name } - if m.Variadic != nil && in { + if m.Variadic != nil { name := m.Variadic.Name if name == "" { - name = fmt.Sprintf("arg%d", len(params)) + name = fmt.Sprintf("arg%d", len(m.In)) } argNames = append(argNames, name) } return argNames } -func (g *generator) getArgTypes(m *model.Method, pkgOverride string, in bool) []string { - var params []*model.Parameter - if in { - params = m.In - } else { - params = m.Out - } - argTypes := make([]string, len(params)) - for i, p := range params { +func (g *generator) getArgTypes(m *model.Method, pkgOverride string) []string { + argTypes := make([]string, len(m.In)) + for i, p := range m.In { argTypes[i] = p.Type.String(g.packageMap, pkgOverride) } if m.Variadic != nil { @@ -839,7 +670,7 @@ func parsePackageImport(srcDir string) (string, error) { if moduleMode != "off" { currentDir := srcDir for { - dat, err := os.ReadFile(filepath.Join(currentDir, "go.mod")) + dat, err := ioutil.ReadFile(filepath.Join(currentDir, "go.mod")) if os.IsNotExist(err) { if currentDir == filepath.Dir(currentDir) { // at the root diff --git a/vendor/go.uber.org/mock/mockgen/model/model.go b/vendor/github.com/golang/mock/mockgen/model/model.go similarity index 87% rename from vendor/go.uber.org/mock/mockgen/model/model.go rename to vendor/github.com/golang/mock/mockgen/model/model.go index e2dde5385..2c6a62ceb 100644 --- a/vendor/go.uber.org/mock/mockgen/model/model.go +++ b/vendor/github.com/golang/mock/mockgen/model/model.go @@ -24,7 +24,7 @@ import ( ) // pkgPath is the importable path for package model -const pkgPath = "go.uber.org/mock/mockgen/model" +const pkgPath = "github.com/golang/mock/mockgen/model" // Package is a Go package. It may be a subset. type Package struct { @@ -47,18 +47,14 @@ func (pkg *Package) Imports() map[string]bool { im := make(map[string]bool) for _, intf := range pkg.Interfaces { intf.addImports(im) - for _, tp := range intf.TypeParams { - tp.Type.addImports(im) - } } return im } // Interface is a Go interface. type Interface struct { - Name string - Methods []*Method - TypeParams []*Parameter + Name string + Methods []*Method } // Print writes the interface name and its methods. @@ -147,14 +143,12 @@ type Type interface { } func init() { - // Call gob.RegisterName with pkgPath as prefix to avoid conflicting with - // github.com/golang/mock/mockgen/model 's registration. - gob.RegisterName(pkgPath+".ArrayType", &ArrayType{}) - gob.RegisterName(pkgPath+".ChanType", &ChanType{}) - gob.RegisterName(pkgPath+".FuncType", &FuncType{}) - gob.RegisterName(pkgPath+".MapType", &MapType{}) - gob.RegisterName(pkgPath+".NamedType", &NamedType{}) - gob.RegisterName(pkgPath+".PointerType", &PointerType{}) + gob.Register(&ArrayType{}) + gob.Register(&ChanType{}) + gob.Register(&FuncType{}) + gob.Register(&MapType{}) + gob.Register(&NamedType{}) + gob.Register(&PointerType{}) // Call gob.RegisterName to make sure it has the consistent name registered // for both gob decoder and encoder. @@ -162,7 +156,7 @@ func init() { // For a non-pointer type, gob.Register will try to get package full path by // calling rt.PkgPath() for a name to register. If your project has vendor // directory, it is possible that PkgPath will get a path like this: - // ../../../vendor/go.uber.org/mock/mockgen/model + // ../../../vendor/github.com/golang/mock/mockgen/model gob.RegisterName(pkgPath+".PredeclaredType", PredeclaredType("")) } @@ -265,28 +259,26 @@ func (mt *MapType) addImports(im map[string]bool) { // NamedType is an exported type in a package. type NamedType struct { - Package string // may be empty - Type string - TypeParams *TypeParametersType + Package string // may be empty + Type string } func (nt *NamedType) String(pm map[string]string, pkgOverride string) string { if pkgOverride == nt.Package { - return nt.Type + nt.TypeParams.String(pm, pkgOverride) + return nt.Type } prefix := pm[nt.Package] if prefix != "" { - return prefix + "." + nt.Type + nt.TypeParams.String(pm, pkgOverride) + return prefix + "." + nt.Type } - return nt.Type + nt.TypeParams.String(pm, pkgOverride) + return nt.Type } func (nt *NamedType) addImports(im map[string]bool) { if nt.Package != "" { im[nt.Package] = true } - nt.TypeParams.addImports(im) } // PointerType is a pointer to another type. @@ -305,36 +297,6 @@ type PredeclaredType string func (pt PredeclaredType) String(map[string]string, string) string { return string(pt) } func (pt PredeclaredType) addImports(map[string]bool) {} -// TypeParametersType contains type paramters for a NamedType. -type TypeParametersType struct { - TypeParameters []Type -} - -func (tp *TypeParametersType) String(pm map[string]string, pkgOverride string) string { - if tp == nil || len(tp.TypeParameters) == 0 { - return "" - } - var sb strings.Builder - sb.WriteString("[") - for i, v := range tp.TypeParameters { - if i != 0 { - sb.WriteString(", ") - } - sb.WriteString(v.String(pm, pkgOverride)) - } - sb.WriteString("]") - return sb.String() -} - -func (tp *TypeParametersType) addImports(im map[string]bool) { - if tp == nil { - return - } - for _, v := range tp.TypeParameters { - v.addImports(im) - } -} - // The following code is intended to be called by the program generated by ../reflect.go. // InterfaceFromInterfaceType returns a pointer to an interface for the @@ -469,7 +431,7 @@ func typeFromType(t reflect.Type) (Type, error) { case reflect.Interface: // Two special interfaces. if t.NumMethod() == 0 { - return PredeclaredType("any"), nil + return PredeclaredType("interface{}"), nil } if t == errorType { return PredeclaredType("error"), nil diff --git a/vendor/go.uber.org/mock/mockgen/parse.go b/vendor/github.com/golang/mock/mockgen/parse.go similarity index 63% rename from vendor/go.uber.org/mock/mockgen/parse.go rename to vendor/github.com/golang/mock/mockgen/parse.go index 952140998..bf6902cd5 100644 --- a/vendor/go.uber.org/mock/mockgen/parse.go +++ b/vendor/github.com/golang/mock/mockgen/parse.go @@ -18,6 +18,7 @@ package main import ( "errors" + "flag" "fmt" "go/ast" "go/build" @@ -25,14 +26,19 @@ import ( "go/parser" "go/token" "go/types" + "io/ioutil" "log" - "os" "path" "path/filepath" "strconv" "strings" - "go.uber.org/mock/mockgen/model" + "github.com/golang/mock/mockgen/model" +) + +var ( + imports = flag.String("imports", "", "(source mode) Comma-separated name=path pairs of explicit imports to use.") + auxFiles = flag.String("aux_files", "", "(source mode) Comma-separated pkg=path pairs of auxiliary Go source files.") ) // sourceMode generates mocks via source file. @@ -56,8 +62,8 @@ func sourceMode(source string) (*model.Package, error) { p := &fileParser{ fileSet: fs, imports: make(map[string]importedPackage), - importedInterfaces: newInterfaceCache(), - auxInterfaces: newInterfaceCache(), + importedInterfaces: make(map[string]map[string]*ast.InterfaceType), + auxInterfaces: make(map[string]map[string]*ast.InterfaceType), srcDir: srcDir, } @@ -75,10 +81,6 @@ func sourceMode(source string) (*model.Package, error) { } } - if *excludeInterfaces != "" { - p.excludeNamesSet = parseExcludeInterfaces(*excludeInterfaces) - } - // Handle -aux_files. if err := p.parseAuxFiles(*auxFiles); err != nil { return nil, err @@ -125,55 +127,21 @@ func (d duplicateImport) Error() string { func (d duplicateImport) Path() string { log.Fatal(d.Error()); return "" } func (d duplicateImport) Parser() *fileParser { log.Fatal(d.Error()); return nil } -type interfaceCache struct { - m map[string]map[string]*namedInterface -} - -func newInterfaceCache() *interfaceCache { - return &interfaceCache{ - m: make(map[string]map[string]*namedInterface), - } -} - -func (i *interfaceCache) Set(pkg, name string, it *namedInterface) { - if _, ok := i.m[pkg]; !ok { - i.m[pkg] = make(map[string]*namedInterface) - } - i.m[pkg][name] = it -} - -func (i *interfaceCache) Get(pkg, name string) *namedInterface { - if _, ok := i.m[pkg]; !ok { - return nil - } - return i.m[pkg][name] -} - -func (i *interfaceCache) GetASTIface(pkg, name string) *ast.InterfaceType { - if _, ok := i.m[pkg]; !ok { - return nil - } - it, ok := i.m[pkg][name] - if !ok { - return nil - } - return it.it -} - type fileParser struct { fileSet *token.FileSet - imports map[string]importedPackage // package name => imported package - importedInterfaces *interfaceCache - auxFiles []*ast.File - auxInterfaces *interfaceCache - srcDir string - excludeNamesSet map[string]struct{} + imports map[string]importedPackage // package name => imported package + importedInterfaces map[string]map[string]*ast.InterfaceType // package (or "") => name => interface + + auxFiles []*ast.File + auxInterfaces map[string]map[string]*ast.InterfaceType // package (or "") => name => interface + + srcDir string } -func (p *fileParser) errorf(pos token.Pos, format string, args ...any) error { +func (p *fileParser) errorf(pos token.Pos, format string, args ...interface{}) error { ps := p.fileSet.Position(pos) format = "%s:%d:%d: " + format - args = append([]any{ps.Filename, ps.Line, ps.Column}, args...) + args = append([]interface{}{ps.Filename, ps.Line, ps.Column}, args...) return fmt.Errorf(format, args...) } @@ -200,8 +168,11 @@ func (p *fileParser) parseAuxFiles(auxFiles string) error { } func (p *fileParser) addAuxInterfacesFromFile(pkg string, file *ast.File) { + if _, ok := p.auxInterfaces[pkg]; !ok { + p.auxInterfaces[pkg] = make(map[string]*ast.InterfaceType) + } for ni := range iterInterfaces(file) { - p.auxInterfaces.Set(pkg, ni.name.Name, ni) + p.auxInterfaces[pkg][ni.name.Name] = ni.it } } @@ -228,10 +199,7 @@ func (p *fileParser) parseFile(importPath string, file *ast.File) (*model.Packag var is []*model.Interface for ni := range iterInterfaces(file) { - if _, ok := p.excludeNamesSet[ni.name.String()]; ok { - continue - } - i, err := p.parseInterface(ni.name.String(), importPath, ni) + i, err := p.parseInterface(ni.name.String(), importPath, ni.it) if err != nil { return nil, err } @@ -251,8 +219,8 @@ func (p *fileParser) parsePackage(path string) (*fileParser, error) { newP := &fileParser{ fileSet: token.NewFileSet(), imports: make(map[string]importedPackage), - importedInterfaces: newInterfaceCache(), - auxInterfaces: newInterfaceCache(), + importedInterfaces: make(map[string]map[string]*ast.InterfaceType), + auxInterfaces: make(map[string]map[string]*ast.InterfaceType), srcDir: p.srcDir, } @@ -265,8 +233,11 @@ func (p *fileParser) parsePackage(path string) (*fileParser, error) { for _, pkg := range pkgs { file := ast.MergePackageFiles(pkg, ast.FilterFuncDuplicates|ast.FilterUnassociatedComments|ast.FilterImportDuplicates) + if _, ok := newP.importedInterfaces[path]; !ok { + newP.importedInterfaces[path] = make(map[string]*ast.InterfaceType) + } for ni := range iterInterfaces(file) { - newP.importedInterfaces.Set(path, ni.name.Name, ni) + newP.importedInterfaces[path][ni.name.Name] = ni.it } imports, _ := importsOfFile(file) for pkgName, pkgI := range imports { @@ -276,77 +247,9 @@ func (p *fileParser) parsePackage(path string) (*fileParser, error) { return newP, nil } -func (p *fileParser) constructInstParams(pkg string, params []*ast.Field, instParams []model.Type, embeddedInstParams []ast.Expr, tps map[string]model.Type) ([]model.Type, error) { - pm := make(map[string]int) - var i int - for _, v := range params { - for _, n := range v.Names { - pm[n.Name] = i - instParams = append(instParams, model.PredeclaredType(n.Name)) - i++ - } - } - - var runtimeInstParams []model.Type - for _, instParam := range embeddedInstParams { - switch t := instParam.(type) { - case *ast.Ident: - if idx, ok := pm[t.Name]; ok { - runtimeInstParams = append(runtimeInstParams, instParams[idx]) - continue - } - } - modelType, err := p.parseType(pkg, instParam, tps) - if err != nil { - return nil, err - } - runtimeInstParams = append(runtimeInstParams, modelType) - } - - return runtimeInstParams, nil -} - -func (p *fileParser) constructTps(it *namedInterface) (tps map[string]model.Type) { - tps = make(map[string]model.Type) - n := 0 - for _, tp := range it.typeParams { - for _, tm := range tp.Names { - tps[tm.Name] = nil - if len(it.instTypes) != 0 { - tps[tm.Name] = it.instTypes[n] - n++ - } - } - } - return tps -} - -// parseInterface loads interface specified by pkg and name, parses it and returns -// a new model with the parsed. -func (p *fileParser) parseInterface(name, pkg string, it *namedInterface) (*model.Interface, error) { +func (p *fileParser) parseInterface(name, pkg string, it *ast.InterfaceType) (*model.Interface, error) { iface := &model.Interface{Name: name} - tps := p.constructTps(it) - tp, err := p.parseFieldList(pkg, it.typeParams, tps) - if err != nil { - return nil, fmt.Errorf("unable to parse interface type parameters: %v", name) - } - - iface.TypeParams = tp - for _, field := range it.it.Methods.List { - var methods []*model.Method - if methods, err = p.parseMethod(field, it, iface, pkg, tps); err != nil { - return nil, err - } - for _, m := range methods { - iface.AddMethod(m) - } - } - return iface, nil -} - -func (p *fileParser) parseMethod(field *ast.Field, it *namedInterface, iface *model.Interface, pkg string, tps map[string]model.Type) ([]*model.Method, error) { - // {} for git diff - { + for _, field := range it.Methods.List { switch v := field.Type.(type) { case *ast.FuncType: if nn := len(field.Names); nn != 1 { @@ -356,55 +259,37 @@ func (p *fileParser) parseMethod(field *ast.Field, it *namedInterface, iface *mo Name: field.Names[0].String(), } var err error - m.In, m.Variadic, m.Out, err = p.parseFunc(pkg, v, tps) + m.In, m.Variadic, m.Out, err = p.parseFunc(pkg, v) if err != nil { return nil, err } - return []*model.Method{m}, nil + iface.AddMethod(m) case *ast.Ident: // Embedded interface in this package. - embeddedIfaceType := p.auxInterfaces.Get(pkg, v.String()) + embeddedIfaceType := p.auxInterfaces[pkg][v.String()] if embeddedIfaceType == nil { - embeddedIfaceType = p.importedInterfaces.Get(pkg, v.String()) + embeddedIfaceType = p.importedInterfaces[pkg][v.String()] } var embeddedIface *model.Interface if embeddedIfaceType != nil { var err error - embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) - if err != nil { - return nil, err - } embeddedIface, err = p.parseInterface(v.String(), pkg, embeddedIfaceType) if err != nil { return nil, err } - } else { // This is built-in error interface. if v.String() == model.ErrorInterface.Name { embeddedIface = &model.ErrorInterface } else { - ip, err := p.parsePackage(pkg) - if err != nil { - return nil, p.errorf(v.Pos(), "could not parse package %s: %v", pkg, err) - } - - if embeddedIfaceType = ip.importedInterfaces.Get(pkg, v.String()); embeddedIfaceType == nil { - return nil, p.errorf(v.Pos(), "unknown embedded interface %s.%s", pkg, v.String()) - } - - embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) - if err != nil { - return nil, err - } - embeddedIface, err = ip.parseInterface(v.String(), pkg, embeddedIfaceType) - if err != nil { - return nil, err - } + return nil, p.errorf(v.Pos(), "unknown embedded interface %s", v.String()) } } - return embeddedIface.Methods, nil + // Copy the methods. + for _, m := range embeddedIface.Methods { + iface.AddMethod(m) + } case *ast.SelectorExpr: // Embedded interface in another package. filePkg, sel := v.X.(*ast.Ident).String(), v.Sel.String() @@ -415,12 +300,8 @@ func (p *fileParser) parseMethod(field *ast.Field, it *namedInterface, iface *mo var embeddedIface *model.Interface var err error - embeddedIfaceType := p.auxInterfaces.Get(filePkg, sel) + embeddedIfaceType := p.auxInterfaces[filePkg][sel] if embeddedIfaceType != nil { - embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) - if err != nil { - return nil, err - } embeddedIface, err = p.parseInterface(sel, filePkg, embeddedIfaceType) if err != nil { return nil, err @@ -439,47 +320,46 @@ func (p *fileParser) parseMethod(field *ast.Field, it *namedInterface, iface *mo parser: parser, } } - if embeddedIfaceType = parser.importedInterfaces.Get(path, sel); embeddedIfaceType == nil { + if embeddedIfaceType = parser.importedInterfaces[path][sel]; embeddedIfaceType == nil { return nil, p.errorf(v.Pos(), "unknown embedded interface %s.%s", path, sel) } - - embeddedIfaceType.instTypes, err = p.constructInstParams(pkg, it.typeParams, it.instTypes, it.embeddedInstTypeParams, tps) - if err != nil { - return nil, err - } embeddedIface, err = parser.parseInterface(sel, path, embeddedIfaceType) if err != nil { return nil, err } } + // Copy the methods. // TODO: apply shadowing rules. - return embeddedIface.Methods, nil + for _, m := range embeddedIface.Methods { + iface.AddMethod(m) + } default: - return p.parseGenericMethod(field, it, iface, pkg, tps) + return nil, fmt.Errorf("don't know how to mock method of type %T", field.Type) } } + return iface, nil } -func (p *fileParser) parseFunc(pkg string, f *ast.FuncType, tps map[string]model.Type) (inParam []*model.Parameter, variadic *model.Parameter, outParam []*model.Parameter, err error) { +func (p *fileParser) parseFunc(pkg string, f *ast.FuncType) (inParam []*model.Parameter, variadic *model.Parameter, outParam []*model.Parameter, err error) { if f.Params != nil { regParams := f.Params.List if isVariadic(f) { n := len(regParams) varParams := regParams[n-1:] regParams = regParams[:n-1] - vp, err := p.parseFieldList(pkg, varParams, tps) + vp, err := p.parseFieldList(pkg, varParams) if err != nil { return nil, nil, nil, p.errorf(varParams[0].Pos(), "failed parsing variadic argument: %v", err) } variadic = vp[0] } - inParam, err = p.parseFieldList(pkg, regParams, tps) + inParam, err = p.parseFieldList(pkg, regParams) if err != nil { return nil, nil, nil, p.errorf(f.Pos(), "failed parsing arguments: %v", err) } } if f.Results != nil { - outParam, err = p.parseFieldList(pkg, f.Results.List, tps) + outParam, err = p.parseFieldList(pkg, f.Results.List) if err != nil { return nil, nil, nil, p.errorf(f.Pos(), "failed parsing returns: %v", err) } @@ -487,7 +367,7 @@ func (p *fileParser) parseFunc(pkg string, f *ast.FuncType, tps map[string]model return } -func (p *fileParser) parseFieldList(pkg string, fields []*ast.Field, tps map[string]model.Type) ([]*model.Parameter, error) { +func (p *fileParser) parseFieldList(pkg string, fields []*ast.Field) ([]*model.Parameter, error) { nf := 0 for _, f := range fields { nn := len(f.Names) @@ -502,7 +382,7 @@ func (p *fileParser) parseFieldList(pkg string, fields []*ast.Field, tps map[str ps := make([]*model.Parameter, nf) i := 0 // destination index for _, f := range fields { - t, err := p.parseType(pkg, f.Type, tps) + t, err := p.parseType(pkg, f.Type) if err != nil { return nil, err } @@ -521,27 +401,44 @@ func (p *fileParser) parseFieldList(pkg string, fields []*ast.Field, tps map[str return ps, nil } -func (p *fileParser) parseType(pkg string, typ ast.Expr, tps map[string]model.Type) (model.Type, error) { +func (p *fileParser) parseType(pkg string, typ ast.Expr) (model.Type, error) { switch v := typ.(type) { case *ast.ArrayType: ln := -1 if v.Len != nil { - value, err := p.parseArrayLength(v.Len) - if err != nil { - return nil, err + var value string + switch val := v.Len.(type) { + case (*ast.BasicLit): + value = val.Value + case (*ast.Ident): + // when the length is a const defined locally + value = val.Obj.Decl.(*ast.ValueSpec).Values[0].(*ast.BasicLit).Value + case (*ast.SelectorExpr): + // when the length is a const defined in an external package + usedPkg, err := importer.Default().Import(fmt.Sprintf("%s", val.X)) + if err != nil { + return nil, p.errorf(v.Len.Pos(), "unknown package in array length: %v", err) + } + ev, err := types.Eval(token.NewFileSet(), usedPkg, token.NoPos, val.Sel.Name) + if err != nil { + return nil, p.errorf(v.Len.Pos(), "unknown constant in array length: %v", err) + } + value = ev.Value.String() } - ln, err = strconv.Atoi(value) + + x, err := strconv.Atoi(value) if err != nil { return nil, p.errorf(v.Len.Pos(), "bad array size: %v", err) } + ln = x } - t, err := p.parseType(pkg, v.Elt, tps) + t, err := p.parseType(pkg, v.Elt) if err != nil { return nil, err } return &model.ArrayType{Len: ln, Type: t}, nil case *ast.ChanType: - t, err := p.parseType(pkg, v.Value, tps) + t, err := p.parseType(pkg, v.Value) if err != nil { return nil, err } @@ -555,16 +452,15 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr, tps map[string]model.Ty return &model.ChanType{Dir: dir, Type: t}, nil case *ast.Ellipsis: // assume we're parsing a variadic argument - return p.parseType(pkg, v.Elt, tps) + return p.parseType(pkg, v.Elt) case *ast.FuncType: - in, variadic, out, err := p.parseFunc(pkg, v, tps) + in, variadic, out, err := p.parseFunc(pkg, v) if err != nil { return nil, err } return &model.FuncType{In: in, Out: out, Variadic: variadic}, nil case *ast.Ident: - it, ok := tps[v.Name] - if v.IsExported() && !ok { + if v.IsExported() { // `pkg` may be an aliased imported pkg // if so, patch the import w/ the fully qualified import maybeImportedPkg, ok := p.imports[pkg] @@ -574,22 +470,20 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr, tps map[string]model.Ty // assume type in this package return &model.NamedType{Package: pkg, Type: v.Name}, nil } - if ok && it != nil { - return it, nil - } + // assume predeclared type return model.PredeclaredType(v.Name), nil case *ast.InterfaceType: if v.Methods != nil && len(v.Methods.List) > 0 { return nil, p.errorf(v.Pos(), "can't handle non-empty unnamed interface types") } - return model.PredeclaredType("any"), nil + return model.PredeclaredType("interface{}"), nil case *ast.MapType: - key, err := p.parseType(pkg, v.Key, tps) + key, err := p.parseType(pkg, v.Key) if err != nil { return nil, err } - value, err := p.parseType(pkg, v.Value, tps) + value, err := p.parseType(pkg, v.Value) if err != nil { return nil, err } @@ -602,7 +496,7 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr, tps map[string]model.Ty } return &model.NamedType{Package: pkg.Path(), Type: v.Sel.String()}, nil case *ast.StarExpr: - t, err := p.parseType(pkg, v.X, tps) + t, err := p.parseType(pkg, v.X) if err != nil { return nil, err } @@ -613,61 +507,12 @@ func (p *fileParser) parseType(pkg string, typ ast.Expr, tps map[string]model.Ty } return model.PredeclaredType("struct{}"), nil case *ast.ParenExpr: - return p.parseType(pkg, v.X, tps) - default: - mt, err := p.parseGenericType(pkg, typ, tps) - if err != nil { - return nil, err - } - if mt == nil { - break - } - return mt, nil + return p.parseType(pkg, v.X) } return nil, fmt.Errorf("don't know how to parse type %T", typ) } -func (p *fileParser) parseArrayLength(expr ast.Expr) (string, error) { - switch val := expr.(type) { - case (*ast.BasicLit): - return val.Value, nil - case (*ast.Ident): - // when the length is a const defined locally - return val.Obj.Decl.(*ast.ValueSpec).Values[0].(*ast.BasicLit).Value, nil - case (*ast.SelectorExpr): - // when the length is a const defined in an external package - usedPkg, err := importer.Default().Import(fmt.Sprintf("%s", val.X)) - if err != nil { - return "", p.errorf(expr.Pos(), "unknown package in array length: %v", err) - } - ev, err := types.Eval(token.NewFileSet(), usedPkg, token.NoPos, val.Sel.Name) - if err != nil { - return "", p.errorf(expr.Pos(), "unknown constant in array length: %v", err) - } - return ev.Value.String(), nil - case (*ast.ParenExpr): - return p.parseArrayLength(val.X) - case (*ast.BinaryExpr): - x, err := p.parseArrayLength(val.X) - if err != nil { - return "", err - } - y, err := p.parseArrayLength(val.Y) - if err != nil { - return "", err - } - biExpr := fmt.Sprintf("%s%v%s", x, val.Op, y) - tv, err := types.Eval(token.NewFileSet(), nil, token.NoPos, biExpr) - if err != nil { - return "", p.errorf(expr.Pos(), "invalid expression in array length: %v", err) - } - return tv.Value.String(), nil - default: - return "", p.errorf(expr.Pos(), "invalid expression in array length: %v", val) - } -} - // importsOfFile returns a map of package name to import path // of the imports in file. func importsOfFile(file *ast.File) (normalImports map[string]importedPackage, dotImports []string) { @@ -730,16 +575,13 @@ func importsOfFile(file *ast.File) (normalImports map[string]importedPackage, do } type namedInterface struct { - name *ast.Ident - it *ast.InterfaceType - typeParams []*ast.Field - embeddedInstTypeParams []ast.Expr - instTypes []model.Type + name *ast.Ident + it *ast.InterfaceType } // Create an iterator over all interfaces in file. -func iterInterfaces(file *ast.File) <-chan *namedInterface { - ch := make(chan *namedInterface) +func iterInterfaces(file *ast.File) <-chan namedInterface { + ch := make(chan namedInterface) go func() { for _, decl := range file.Decls { gd, ok := decl.(*ast.GenDecl) @@ -756,7 +598,7 @@ func iterInterfaces(file *ast.File) <-chan *namedInterface { continue } - ch <- &namedInterface{name: ts.Name, it: it, typeParams: getTypeSpecTypeParams(ts)} + ch <- namedInterface{ts.Name, it} } } close(ch) @@ -776,7 +618,7 @@ func isVariadic(f *ast.FuncType) bool { // packageNameOfDir get package import path via dir func packageNameOfDir(srcDir string) (string, error) { - files, err := os.ReadDir(srcDir) + files, err := ioutil.ReadDir(srcDir) if err != nil { log.Fatal(err) } diff --git a/vendor/go.uber.org/mock/mockgen/reflect.go b/vendor/github.com/golang/mock/mockgen/reflect.go similarity index 93% rename from vendor/go.uber.org/mock/mockgen/reflect.go rename to vendor/github.com/golang/mock/mockgen/reflect.go index 8f519f6a5..e24efce0b 100644 --- a/vendor/go.uber.org/mock/mockgen/reflect.go +++ b/vendor/github.com/golang/mock/mockgen/reflect.go @@ -23,6 +23,7 @@ import ( "fmt" "go/build" "io" + "io/ioutil" "log" "os" "os/exec" @@ -31,7 +32,7 @@ import ( "strings" "text/template" - "go.uber.org/mock/mockgen/model" + "github.com/golang/mock/mockgen/model" ) var ( @@ -91,7 +92,7 @@ func writeProgram(importPath string, symbols []string) ([]byte, error) { // run the given program and parse the output as a model.Package. func run(program string) (*model.Package, error) { - f, err := os.CreateTemp("", "") + f, err := ioutil.TempFile("", "") if err != nil { return nil, err } @@ -132,7 +133,7 @@ func run(program string) (*model.Package, error) { // parses the output as a model.Package. func runInDir(program []byte, dir string) (*model.Package, error) { // We use TempDir instead of TempFile so we can control the filename. - tmpDir, err := os.MkdirTemp(dir, "gomock_reflect_") + tmpDir, err := ioutil.TempDir(dir, "gomock_reflect_") if err != nil { return nil, err } @@ -148,7 +149,7 @@ func runInDir(program []byte, dir string) (*model.Package, error) { progBinary += ".exe" } - if err := os.WriteFile(filepath.Join(tmpDir, progSource), program, 0600); err != nil { + if err := ioutil.WriteFile(filepath.Join(tmpDir, progSource), program, 0600); err != nil { return nil, err } @@ -168,8 +169,8 @@ func runInDir(program []byte, dir string) (*model.Package, error) { if err := cmd.Run(); err != nil { sErr := buf.String() if strings.Contains(sErr, `cannot find package "."`) && - strings.Contains(sErr, "go.uber.org/mock/mockgen/model") { - fmt.Fprint(os.Stderr, "Please reference the steps in the README to fix this error:\n\thttps://go.uber.org/mock#reflect-vendoring-error.\n") + strings.Contains(sErr, "github.com/golang/mock/mockgen/model") { + fmt.Fprint(os.Stderr, "Please reference the steps in the README to fix this error:\n\thttps://github.com/golang/mock#reflect-vendoring-error.") return nil, err } return nil, err @@ -197,7 +198,7 @@ import ( "path" "reflect" - "go.uber.org/mock/mockgen/model" + "github.com/golang/mock/mockgen/model" pkg_ {{printf "%q" .ImportPath}} ) diff --git a/vendor/github.com/golang/mock/mockgen/version.1.11.go b/vendor/github.com/golang/mock/mockgen/version.1.11.go new file mode 100644 index 000000000..e6b25db23 --- /dev/null +++ b/vendor/github.com/golang/mock/mockgen/version.1.11.go @@ -0,0 +1,26 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +build !go1.12 + +package main + +import ( + "log" +) + +func printModuleVersion() { + log.Printf("No version information is available for Mockgen compiled with " + + "version 1.11") +} diff --git a/vendor/go.uber.org/mock/mockgen/version.go b/vendor/github.com/golang/mock/mockgen/version.1.12.go similarity index 94% rename from vendor/go.uber.org/mock/mockgen/version.go rename to vendor/github.com/golang/mock/mockgen/version.1.12.go index 6db160ac2..ad121ae63 100644 --- a/vendor/go.uber.org/mock/mockgen/version.go +++ b/vendor/github.com/golang/mock/mockgen/version.1.12.go @@ -1,4 +1,4 @@ -// Copyright 2022 Google LLC +// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,6 +11,9 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +// + +// +build go1.12 package main @@ -28,4 +31,5 @@ func printModuleVersion() { "GO111MODULE=on when running 'go get' in order to use specific " + "version of the binary.") } + } diff --git a/vendor/github.com/hashicorp/golang-lru/v2/.golangci.yml b/vendor/github.com/hashicorp/golang-lru/v2/.golangci.yml index 7e7b8a962..95700902d 100644 --- a/vendor/github.com/hashicorp/golang-lru/v2/.golangci.yml +++ b/vendor/github.com/hashicorp/golang-lru/v2/.golangci.yml @@ -2,13 +2,12 @@ # SPDX-License-Identifier: MPL-2.0 linters: - fast: false - disable-all: true enable: - - revive - megacheck + - revive - govet - unconvert + - megacheck - gas - gocyclo - dupl @@ -17,30 +16,18 @@ linters: - unused - typecheck - ineffassign - # - stylecheck + - stylecheck - exportloopref - gocritic - nakedret - gosimple - prealloc - -# golangci-lint configuration file -linters-settings: - revive: - ignore-generated-header: true - severity: warning - rules: - - name: package-comments - severity: warning - disabled: true - - name: exported - severity: warning - disabled: false - arguments: ["checkPrivateReceivers", "disableStutteringCheck"] + fast: false + disable-all: true issues: - exclude-use-default: false exclude-rules: - path: _test\.go linters: - dupl + exclude-use-default: false diff --git a/vendor/github.com/hashicorp/golang-lru/v2/2q.go b/vendor/github.com/hashicorp/golang-lru/v2/2q.go index 5e00d9a7d..1f0055b7b 100644 --- a/vendor/github.com/hashicorp/golang-lru/v2/2q.go +++ b/vendor/github.com/hashicorp/golang-lru/v2/2q.go @@ -181,16 +181,6 @@ func (c *TwoQueueCache[K, V]) Keys() []K { return append(k1, k2...) } -// Values returns a slice of the values in the cache. -// The frequently used values are first in the returned slice. -func (c *TwoQueueCache[K, V]) Values() []V { - c.lock.RLock() - defer c.lock.RUnlock() - v1 := c.frequent.Values() - v2 := c.recent.Values() - return append(v1, v2...) -} - // Remove removes the provided key from the cache. func (c *TwoQueueCache[K, V]) Remove(key K) { c.lock.Lock() diff --git a/vendor/github.com/hashicorp/golang-lru/v2/README.md b/vendor/github.com/hashicorp/golang-lru/v2/README.md index a942eb539..4c08cc46f 100644 --- a/vendor/github.com/hashicorp/golang-lru/v2/README.md +++ b/vendor/github.com/hashicorp/golang-lru/v2/README.md @@ -9,71 +9,17 @@ Documentation Full docs are available on [Go Packages](https://pkg.go.dev/github.com/hashicorp/golang-lru/v2) -LRU cache example -================= +Example +======= + +Using the LRU is very simple: ```go -package main - -import ( - "fmt" - "github.com/hashicorp/golang-lru/v2" -) - -func main() { - l, _ := lru.New[int, any](128) - for i := 0; i < 256; i++ { - l.Add(i, nil) - } - if l.Len() != 128 { - panic(fmt.Sprintf("bad len: %v", l.Len())) - } -} -``` - -Expirable LRU cache example -=========================== - -```go -package main - -import ( - "fmt" - "time" - - "github.com/hashicorp/golang-lru/v2/expirable" -) - -func main() { - // make cache with 10ms TTL and 5 max keys - cache := expirable.NewLRU[string, string](5, nil, time.Millisecond*10) - - - // set value under key1. - cache.Add("key1", "val1") - - // get value under key1 - r, ok := cache.Get("key1") - - // check for OK value - if ok { - fmt.Printf("value before expiration is found: %v, value: %q\n", ok, r) - } - - // wait for cache to expire - time.Sleep(time.Millisecond * 12) - - // get value under key1 after key expiration - r, ok = cache.Get("key1") - fmt.Printf("value after expiration is found: %v, value: %q\n", ok, r) - - // set value under key2, would evict old entry because it is already expired. - cache.Add("key2", "val2") - - fmt.Printf("Cache len: %d\n", cache.Len()) - // Output: - // value before expiration is found: true, value: "val1" - // value after expiration is found: false, value: "" - // Cache len: 1 +l, _ := New[int, interface{}](128) +for i := 0; i < 256; i++ { + l.Add(i, nil) +} +if l.Len() != 128 { + panic(fmt.Sprintf("bad len: %v", l.Len())) } ``` diff --git a/vendor/github.com/hashicorp/golang-lru/v2/arc.go b/vendor/github.com/hashicorp/golang-lru/v2/arc.go new file mode 100644 index 000000000..a255aae21 --- /dev/null +++ b/vendor/github.com/hashicorp/golang-lru/v2/arc.go @@ -0,0 +1,259 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package lru + +import ( + "sync" + + "github.com/hashicorp/golang-lru/v2/simplelru" +) + +// ARCCache is a thread-safe fixed size Adaptive Replacement Cache (ARC). +// ARC is an enhancement over the standard LRU cache in that tracks both +// frequency and recency of use. This avoids a burst in access to new +// entries from evicting the frequently used older entries. It adds some +// additional tracking overhead to a standard LRU cache, computationally +// it is roughly 2x the cost, and the extra memory overhead is linear +// with the size of the cache. ARC has been patented by IBM, but is +// similar to the TwoQueueCache (2Q) which requires setting parameters. +type ARCCache[K comparable, V any] struct { + size int // Size is the total capacity of the cache + p int // P is the dynamic preference towards T1 or T2 + + t1 simplelru.LRUCache[K, V] // T1 is the LRU for recently accessed items + b1 simplelru.LRUCache[K, struct{}] // B1 is the LRU for evictions from t1 + + t2 simplelru.LRUCache[K, V] // T2 is the LRU for frequently accessed items + b2 simplelru.LRUCache[K, struct{}] // B2 is the LRU for evictions from t2 + + lock sync.RWMutex +} + +// NewARC creates an ARC of the given size +func NewARC[K comparable, V any](size int) (*ARCCache[K, V], error) { + // Create the sub LRUs + b1, err := simplelru.NewLRU[K, struct{}](size, nil) + if err != nil { + return nil, err + } + b2, err := simplelru.NewLRU[K, struct{}](size, nil) + if err != nil { + return nil, err + } + t1, err := simplelru.NewLRU[K, V](size, nil) + if err != nil { + return nil, err + } + t2, err := simplelru.NewLRU[K, V](size, nil) + if err != nil { + return nil, err + } + + // Initialize the ARC + c := &ARCCache[K, V]{ + size: size, + p: 0, + t1: t1, + b1: b1, + t2: t2, + b2: b2, + } + return c, nil +} + +// Get looks up a key's value from the cache. +func (c *ARCCache[K, V]) Get(key K) (value V, ok bool) { + c.lock.Lock() + defer c.lock.Unlock() + + // If the value is contained in T1 (recent), then + // promote it to T2 (frequent) + if val, ok := c.t1.Peek(key); ok { + c.t1.Remove(key) + c.t2.Add(key, val) + return val, ok + } + + // Check if the value is contained in T2 (frequent) + if val, ok := c.t2.Get(key); ok { + return val, ok + } + + // No hit + return +} + +// Add adds a value to the cache. +func (c *ARCCache[K, V]) Add(key K, value V) { + c.lock.Lock() + defer c.lock.Unlock() + + // Check if the value is contained in T1 (recent), and potentially + // promote it to frequent T2 + if c.t1.Contains(key) { + c.t1.Remove(key) + c.t2.Add(key, value) + return + } + + // Check if the value is already in T2 (frequent) and update it + if c.t2.Contains(key) { + c.t2.Add(key, value) + return + } + + // Check if this value was recently evicted as part of the + // recently used list + if c.b1.Contains(key) { + // T1 set is too small, increase P appropriately + delta := 1 + b1Len := c.b1.Len() + b2Len := c.b2.Len() + if b2Len > b1Len { + delta = b2Len / b1Len + } + if c.p+delta >= c.size { + c.p = c.size + } else { + c.p += delta + } + + // Potentially need to make room in the cache + if c.t1.Len()+c.t2.Len() >= c.size { + c.replace(false) + } + + // Remove from B1 + c.b1.Remove(key) + + // Add the key to the frequently used list + c.t2.Add(key, value) + return + } + + // Check if this value was recently evicted as part of the + // frequently used list + if c.b2.Contains(key) { + // T2 set is too small, decrease P appropriately + delta := 1 + b1Len := c.b1.Len() + b2Len := c.b2.Len() + if b1Len > b2Len { + delta = b1Len / b2Len + } + if delta >= c.p { + c.p = 0 + } else { + c.p -= delta + } + + // Potentially need to make room in the cache + if c.t1.Len()+c.t2.Len() >= c.size { + c.replace(true) + } + + // Remove from B2 + c.b2.Remove(key) + + // Add the key to the frequently used list + c.t2.Add(key, value) + return + } + + // Potentially need to make room in the cache + if c.t1.Len()+c.t2.Len() >= c.size { + c.replace(false) + } + + // Keep the size of the ghost buffers trim + if c.b1.Len() > c.size-c.p { + c.b1.RemoveOldest() + } + if c.b2.Len() > c.p { + c.b2.RemoveOldest() + } + + // Add to the recently seen list + c.t1.Add(key, value) +} + +// replace is used to adaptively evict from either T1 or T2 +// based on the current learned value of P +func (c *ARCCache[K, V]) replace(b2ContainsKey bool) { + t1Len := c.t1.Len() + if t1Len > 0 && (t1Len > c.p || (t1Len == c.p && b2ContainsKey)) { + k, _, ok := c.t1.RemoveOldest() + if ok { + c.b1.Add(k, struct{}{}) + } + } else { + k, _, ok := c.t2.RemoveOldest() + if ok { + c.b2.Add(k, struct{}{}) + } + } +} + +// Len returns the number of cached entries +func (c *ARCCache[K, V]) Len() int { + c.lock.RLock() + defer c.lock.RUnlock() + return c.t1.Len() + c.t2.Len() +} + +// Keys returns all the cached keys +func (c *ARCCache[K, V]) Keys() []K { + c.lock.RLock() + defer c.lock.RUnlock() + k1 := c.t1.Keys() + k2 := c.t2.Keys() + return append(k1, k2...) +} + +// Remove is used to purge a key from the cache +func (c *ARCCache[K, V]) Remove(key K) { + c.lock.Lock() + defer c.lock.Unlock() + if c.t1.Remove(key) { + return + } + if c.t2.Remove(key) { + return + } + if c.b1.Remove(key) { + return + } + if c.b2.Remove(key) { + return + } +} + +// Purge is used to clear the cache +func (c *ARCCache[K, V]) Purge() { + c.lock.Lock() + defer c.lock.Unlock() + c.t1.Purge() + c.t2.Purge() + c.b1.Purge() + c.b2.Purge() +} + +// Contains is used to check if the cache contains a key +// without updating recency or frequency. +func (c *ARCCache[K, V]) Contains(key K) bool { + c.lock.RLock() + defer c.lock.RUnlock() + return c.t1.Contains(key) || c.t2.Contains(key) +} + +// Peek is used to inspect the cache value of a key +// without updating recency or frequency. +func (c *ARCCache[K, V]) Peek(key K) (value V, ok bool) { + c.lock.RLock() + defer c.lock.RUnlock() + if val, ok := c.t1.Peek(key); ok { + return val, ok + } + return c.t2.Peek(key) +} diff --git a/vendor/github.com/hashicorp/golang-lru/v2/doc.go b/vendor/github.com/hashicorp/golang-lru/v2/doc.go index 24107ee0e..2474929f7 100644 --- a/vendor/github.com/hashicorp/golang-lru/v2/doc.go +++ b/vendor/github.com/hashicorp/golang-lru/v2/doc.go @@ -3,21 +3,21 @@ // Package lru provides three different LRU caches of varying sophistication. // -// Cache is a simple LRU cache. It is based on the LRU implementation in -// groupcache: https://github.com/golang/groupcache/tree/master/lru +// Cache is a simple LRU cache. It is based on the +// LRU implementation in groupcache: +// https://github.com/golang/groupcache/tree/master/lru // // TwoQueueCache tracks frequently used and recently used entries separately. -// This avoids a burst of accesses from taking out frequently used entries, at -// the cost of about 2x computational overhead and some extra bookkeeping. +// This avoids a burst of accesses from taking out frequently used entries, +// at the cost of about 2x computational overhead and some extra bookkeeping. // -// ARCCache is an adaptive replacement cache. It tracks recent evictions as well -// as recent usage in both the frequent and recent caches. Its computational -// overhead is comparable to TwoQueueCache, but the memory overhead is linear -// with the size of the cache. +// ARCCache is an adaptive replacement cache. It tracks recent evictions as +// well as recent usage in both the frequent and recent caches. Its +// computational overhead is comparable to TwoQueueCache, but the memory +// overhead is linear with the size of the cache. // // ARC has been patented by IBM, so do not use it if that is problematic for -// your program. For this reason, it is in a separate go module contained within -// this repository. +// your program. // // All caches in this package take locks while operating, and are therefore // thread-safe for consumers. diff --git a/vendor/github.com/hashicorp/golang-lru/v2/internal/list.go b/vendor/github.com/hashicorp/golang-lru/v2/internal/list.go deleted file mode 100644 index 5cd74a034..000000000 --- a/vendor/github.com/hashicorp/golang-lru/v2/internal/list.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE_list file. - -package internal - -import "time" - -// Entry is an LRU Entry -type Entry[K comparable, V any] struct { - // Next and previous pointers in the doubly-linked list of elements. - // To simplify the implementation, internally a list l is implemented - // as a ring, such that &l.root is both the next element of the last - // list element (l.Back()) and the previous element of the first list - // element (l.Front()). - next, prev *Entry[K, V] - - // The list to which this element belongs. - list *LruList[K, V] - - // The LRU Key of this element. - Key K - - // The Value stored with this element. - Value V - - // The time this element would be cleaned up, optional - ExpiresAt time.Time - - // The expiry bucket item was put in, optional - ExpireBucket uint8 -} - -// PrevEntry returns the previous list element or nil. -func (e *Entry[K, V]) PrevEntry() *Entry[K, V] { - if p := e.prev; e.list != nil && p != &e.list.root { - return p - } - return nil -} - -// LruList represents a doubly linked list. -// The zero Value for LruList is an empty list ready to use. -type LruList[K comparable, V any] struct { - root Entry[K, V] // sentinel list element, only &root, root.prev, and root.next are used - len int // current list Length excluding (this) sentinel element -} - -// Init initializes or clears list l. -func (l *LruList[K, V]) Init() *LruList[K, V] { - l.root.next = &l.root - l.root.prev = &l.root - l.len = 0 - return l -} - -// NewList returns an initialized list. -func NewList[K comparable, V any]() *LruList[K, V] { return new(LruList[K, V]).Init() } - -// Length returns the number of elements of list l. -// The complexity is O(1). -func (l *LruList[K, V]) Length() int { return l.len } - -// Back returns the last element of list l or nil if the list is empty. -func (l *LruList[K, V]) Back() *Entry[K, V] { - if l.len == 0 { - return nil - } - return l.root.prev -} - -// lazyInit lazily initializes a zero List Value. -func (l *LruList[K, V]) lazyInit() { - if l.root.next == nil { - l.Init() - } -} - -// insert inserts e after at, increments l.len, and returns e. -func (l *LruList[K, V]) insert(e, at *Entry[K, V]) *Entry[K, V] { - e.prev = at - e.next = at.next - e.prev.next = e - e.next.prev = e - e.list = l - l.len++ - return e -} - -// insertValue is a convenience wrapper for insert(&Entry{Value: v, ExpiresAt: ExpiresAt}, at). -func (l *LruList[K, V]) insertValue(k K, v V, expiresAt time.Time, at *Entry[K, V]) *Entry[K, V] { - return l.insert(&Entry[K, V]{Value: v, Key: k, ExpiresAt: expiresAt}, at) -} - -// Remove removes e from its list, decrements l.len -func (l *LruList[K, V]) Remove(e *Entry[K, V]) V { - e.prev.next = e.next - e.next.prev = e.prev - e.next = nil // avoid memory leaks - e.prev = nil // avoid memory leaks - e.list = nil - l.len-- - - return e.Value -} - -// move moves e to next to at. -func (l *LruList[K, V]) move(e, at *Entry[K, V]) { - if e == at { - return - } - e.prev.next = e.next - e.next.prev = e.prev - - e.prev = at - e.next = at.next - e.prev.next = e - e.next.prev = e -} - -// PushFront inserts a new element e with value v at the front of list l and returns e. -func (l *LruList[K, V]) PushFront(k K, v V) *Entry[K, V] { - l.lazyInit() - return l.insertValue(k, v, time.Time{}, &l.root) -} - -// PushFrontExpirable inserts a new expirable element e with Value v at the front of list l and returns e. -func (l *LruList[K, V]) PushFrontExpirable(k K, v V, expiresAt time.Time) *Entry[K, V] { - l.lazyInit() - return l.insertValue(k, v, expiresAt, &l.root) -} - -// MoveToFront moves element e to the front of list l. -// If e is not an element of l, the list is not modified. -// The element must not be nil. -func (l *LruList[K, V]) MoveToFront(e *Entry[K, V]) { - if e.list != l || l.root.next == e { - return - } - // see comment in List.Remove about initialization of l - l.move(e, &l.root) -} diff --git a/vendor/github.com/hashicorp/golang-lru/v2/lru.go b/vendor/github.com/hashicorp/golang-lru/v2/lru.go index a2655f1f3..32d04170d 100644 --- a/vendor/github.com/hashicorp/golang-lru/v2/lru.go +++ b/vendor/github.com/hashicorp/golang-lru/v2/lru.go @@ -233,14 +233,6 @@ func (c *Cache[K, V]) Keys() []K { return keys } -// Values returns a slice of the values in the cache, from oldest to newest. -func (c *Cache[K, V]) Values() []V { - c.lock.RLock() - values := c.lru.Values() - c.lock.RUnlock() - return values -} - // Len returns the number of items in the cache. func (c *Cache[K, V]) Len() int { c.lock.RLock() diff --git a/vendor/github.com/hashicorp/golang-lru/v2/simplelru/list.go b/vendor/github.com/hashicorp/golang-lru/v2/simplelru/list.go new file mode 100644 index 000000000..c39da3c12 --- /dev/null +++ b/vendor/github.com/hashicorp/golang-lru/v2/simplelru/list.go @@ -0,0 +1,128 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE_list file. + +package simplelru + +// entry is an LRU entry +type entry[K comparable, V any] struct { + // Next and previous pointers in the doubly-linked list of elements. + // To simplify the implementation, internally a list l is implemented + // as a ring, such that &l.root is both the next element of the last + // list element (l.Back()) and the previous element of the first list + // element (l.Front()). + next, prev *entry[K, V] + + // The list to which this element belongs. + list *lruList[K, V] + + // The LRU key of this element. + key K + + // The value stored with this element. + value V +} + +// prevEntry returns the previous list element or nil. +func (e *entry[K, V]) prevEntry() *entry[K, V] { + if p := e.prev; e.list != nil && p != &e.list.root { + return p + } + return nil +} + +// lruList represents a doubly linked list. +// The zero value for lruList is an empty list ready to use. +type lruList[K comparable, V any] struct { + root entry[K, V] // sentinel list element, only &root, root.prev, and root.next are used + len int // current list length excluding (this) sentinel element +} + +// init initializes or clears list l. +func (l *lruList[K, V]) init() *lruList[K, V] { + l.root.next = &l.root + l.root.prev = &l.root + l.len = 0 + return l +} + +// newList returns an initialized list. +func newList[K comparable, V any]() *lruList[K, V] { return new(lruList[K, V]).init() } + +// length returns the number of elements of list l. +// The complexity is O(1). +func (l *lruList[K, V]) length() int { return l.len } + +// back returns the last element of list l or nil if the list is empty. +func (l *lruList[K, V]) back() *entry[K, V] { + if l.len == 0 { + return nil + } + return l.root.prev +} + +// lazyInit lazily initializes a zero List value. +func (l *lruList[K, V]) lazyInit() { + if l.root.next == nil { + l.init() + } +} + +// insert inserts e after at, increments l.len, and returns e. +func (l *lruList[K, V]) insert(e, at *entry[K, V]) *entry[K, V] { + e.prev = at + e.next = at.next + e.prev.next = e + e.next.prev = e + e.list = l + l.len++ + return e +} + +// insertValue is a convenience wrapper for insert(&Element{Value: v}, at). +func (l *lruList[K, V]) insertValue(k K, v V, at *entry[K, V]) *entry[K, V] { + return l.insert(&entry[K, V]{value: v, key: k}, at) +} + +// remove removes e from its list, decrements l.len +func (l *lruList[K, V]) remove(e *entry[K, V]) V { + e.prev.next = e.next + e.next.prev = e.prev + e.next = nil // avoid memory leaks + e.prev = nil // avoid memory leaks + e.list = nil + l.len-- + + return e.value +} + +// move moves e to next to at. +func (l *lruList[K, V]) move(e, at *entry[K, V]) { + if e == at { + return + } + e.prev.next = e.next + e.next.prev = e.prev + + e.prev = at + e.next = at.next + e.prev.next = e + e.next.prev = e +} + +// pushFront inserts a new element e with value v at the front of list l and returns e. +func (l *lruList[K, V]) pushFront(k K, v V) *entry[K, V] { + l.lazyInit() + return l.insertValue(k, v, &l.root) +} + +// moveToFront moves element e to the front of list l. +// If e is not an element of l, the list is not modified. +// The element must not be nil. +func (l *lruList[K, V]) moveToFront(e *entry[K, V]) { + if e.list != l || l.root.next == e { + return + } + // see comment in List.Remove about initialization of l + l.move(e, &l.root) +} diff --git a/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru.go b/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru.go index 408239c45..b6731afdd 100644 --- a/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru.go +++ b/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru.go @@ -5,8 +5,6 @@ package simplelru import ( "errors" - - "github.com/hashicorp/golang-lru/v2/internal" ) // EvictCallback is used to get a callback when a cache entry is evicted @@ -15,8 +13,8 @@ type EvictCallback[K comparable, V any] func(key K, value V) // LRU implements a non-thread safe fixed size LRU cache type LRU[K comparable, V any] struct { size int - evictList *internal.LruList[K, V] - items map[K]*internal.Entry[K, V] + evictList *lruList[K, V] + items map[K]*entry[K, V] onEvict EvictCallback[K, V] } @@ -28,8 +26,8 @@ func NewLRU[K comparable, V any](size int, onEvict EvictCallback[K, V]) (*LRU[K, c := &LRU[K, V]{ size: size, - evictList: internal.NewList[K, V](), - items: make(map[K]*internal.Entry[K, V]), + evictList: newList[K, V](), + items: make(map[K]*entry[K, V]), onEvict: onEvict, } return c, nil @@ -39,30 +37,27 @@ func NewLRU[K comparable, V any](size int, onEvict EvictCallback[K, V]) (*LRU[K, func (c *LRU[K, V]) Purge() { for k, v := range c.items { if c.onEvict != nil { - c.onEvict(k, v.Value) + c.onEvict(k, v.value) } delete(c.items, k) } - c.evictList.Init() + c.evictList.init() } // Add adds a value to the cache. Returns true if an eviction occurred. func (c *LRU[K, V]) Add(key K, value V) (evicted bool) { // Check for existing item if ent, ok := c.items[key]; ok { - c.evictList.MoveToFront(ent) - if c.onEvict != nil { - c.onEvict(key, ent.Value) - } - ent.Value = value + c.evictList.moveToFront(ent) + ent.value = value return false } // Add new item - ent := c.evictList.PushFront(key, value) + ent := c.evictList.pushFront(key, value) c.items[key] = ent - evict := c.evictList.Length() > c.size + evict := c.evictList.length() > c.size // Verify size not exceeded if evict { c.removeOldest() @@ -73,8 +68,8 @@ func (c *LRU[K, V]) Add(key K, value V) (evicted bool) { // Get looks up a key's value from the cache. func (c *LRU[K, V]) Get(key K) (value V, ok bool) { if ent, ok := c.items[key]; ok { - c.evictList.MoveToFront(ent) - return ent.Value, true + c.evictList.moveToFront(ent) + return ent.value, true } return } @@ -89,9 +84,9 @@ func (c *LRU[K, V]) Contains(key K) (ok bool) { // Peek returns the key value (or undefined if not found) without updating // the "recently used"-ness of the key. func (c *LRU[K, V]) Peek(key K) (value V, ok bool) { - var ent *internal.Entry[K, V] + var ent *entry[K, V] if ent, ok = c.items[key]; ok { - return ent.Value, true + return ent.value, true } return } @@ -108,46 +103,35 @@ func (c *LRU[K, V]) Remove(key K) (present bool) { // RemoveOldest removes the oldest item from the cache. func (c *LRU[K, V]) RemoveOldest() (key K, value V, ok bool) { - if ent := c.evictList.Back(); ent != nil { + if ent := c.evictList.back(); ent != nil { c.removeElement(ent) - return ent.Key, ent.Value, true + return ent.key, ent.value, true } return } // GetOldest returns the oldest entry func (c *LRU[K, V]) GetOldest() (key K, value V, ok bool) { - if ent := c.evictList.Back(); ent != nil { - return ent.Key, ent.Value, true + if ent := c.evictList.back(); ent != nil { + return ent.key, ent.value, true } return } // Keys returns a slice of the keys in the cache, from oldest to newest. func (c *LRU[K, V]) Keys() []K { - keys := make([]K, c.evictList.Length()) + keys := make([]K, c.evictList.length()) i := 0 - for ent := c.evictList.Back(); ent != nil; ent = ent.PrevEntry() { - keys[i] = ent.Key + for ent := c.evictList.back(); ent != nil; ent = ent.prevEntry() { + keys[i] = ent.key i++ } return keys } -// Values returns a slice of the values in the cache, from oldest to newest. -func (c *LRU[K, V]) Values() []V { - values := make([]V, len(c.items)) - i := 0 - for ent := c.evictList.Back(); ent != nil; ent = ent.PrevEntry() { - values[i] = ent.Value - i++ - } - return values -} - // Len returns the number of items in the cache. func (c *LRU[K, V]) Len() int { - return c.evictList.Length() + return c.evictList.length() } // Resize changes the cache size. @@ -165,16 +149,16 @@ func (c *LRU[K, V]) Resize(size int) (evicted int) { // removeOldest removes the oldest item from the cache. func (c *LRU[K, V]) removeOldest() { - if ent := c.evictList.Back(); ent != nil { + if ent := c.evictList.back(); ent != nil { c.removeElement(ent) } } // removeElement is used to remove a given list element from the cache -func (c *LRU[K, V]) removeElement(e *internal.Entry[K, V]) { - c.evictList.Remove(e) - delete(c.items, e.Key) +func (c *LRU[K, V]) removeElement(e *entry[K, V]) { + c.evictList.remove(e) + delete(c.items, e.key) if c.onEvict != nil { - c.onEvict(e.Key, e.Value) + c.onEvict(e.key, e.value) } } diff --git a/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru_interface.go b/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru_interface.go index 043b8bcc3..3cbf02bc7 100644 --- a/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru_interface.go +++ b/vendor/github.com/hashicorp/golang-lru/v2/simplelru/lru_interface.go @@ -32,9 +32,6 @@ type LRUCache[K comparable, V any] interface { // Returns a slice of the keys in the cache, from oldest to newest. Keys() []K - // Values returns a slice of the values in the cache, from oldest to newest. - Values() []V - // Returns the number of items in the cache. Len() int diff --git a/vendor/github.com/hashicorp/golang-lru/v2/testing.go b/vendor/github.com/hashicorp/golang-lru/v2/testing.go new file mode 100644 index 000000000..3277c2186 --- /dev/null +++ b/vendor/github.com/hashicorp/golang-lru/v2/testing.go @@ -0,0 +1,19 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package lru + +import ( + "crypto/rand" + "math" + "math/big" + "testing" +) + +func getRand(tb testing.TB) int64 { + out, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64)) + if err != nil { + tb.Fatal(err) + } + return out.Int64() +} diff --git a/vendor/github.com/huin/goupnp/goupnp.go b/vendor/github.com/huin/goupnp/goupnp.go index 9fa89636a..93c588b03 100644 --- a/vendor/github.com/huin/goupnp/goupnp.go +++ b/vendor/github.com/huin/goupnp/goupnp.go @@ -85,10 +85,7 @@ func DiscoverDevicesCtx(ctx context.Context, searchTarget string) ([]MaybeRootDe return nil, err } defer hcCleanup() - - searchCtx, cancel := context.WithTimeout(ctx, 2*time.Second) - defer cancel() - responses, err := ssdp.RawSearch(searchCtx, hc, string(searchTarget), 3) + responses, err := ssdp.SSDPRawSearchCtx(ctx, hc, string(searchTarget), 2, 3) if err != nil { return nil, err } diff --git a/vendor/github.com/huin/goupnp/httpu/httpu.go b/vendor/github.com/huin/goupnp/httpu/httpu.go index 5bb8d67b6..808d600ab 100644 --- a/vendor/github.com/huin/goupnp/httpu/httpu.go +++ b/vendor/github.com/huin/goupnp/httpu/httpu.go @@ -3,7 +3,6 @@ package httpu import ( "bufio" "bytes" - "context" "errors" "fmt" "log" @@ -27,27 +26,6 @@ type ClientInterface interface { ) ([]*http.Response, error) } -// ClientInterfaceCtx is the equivalent of ClientInterface, except with methods -// taking a context.Context parameter. -type ClientInterfaceCtx interface { - // DoWithContext performs a request. If the input request has a - // deadline, then that value will be used as the timeout for how long - // to wait before returning the responses that were received. If the - // request's context is canceled, this method will return immediately. - // - // If the request's context is never canceled, and does not have a - // deadline, then this function WILL NEVER RETURN. You MUST set an - // appropriate deadline on the context, or otherwise cancel it when you - // want to finish an operation. - // - // An error is only returned for failing to send the request. Failures - // in receipt simply do not add to the resulting responses. - DoWithContext( - req *http.Request, - numSends int, - ) ([]*http.Response, error) -} - // HTTPUClient is a client for dealing with HTTPU (HTTP over UDP). Its typical // function is for HTTPMU, and particularly SSDP. type HTTPUClient struct { @@ -56,7 +34,6 @@ type HTTPUClient struct { } var _ ClientInterface = &HTTPUClient{} -var _ ClientInterfaceCtx = &HTTPUClient{} // NewHTTPUClient creates a new HTTPUClient, opening up a new UDP socket for the // purpose. @@ -98,25 +75,6 @@ func (httpu *HTTPUClient) Do( req *http.Request, timeout time.Duration, numSends int, -) ([]*http.Response, error) { - ctx := req.Context() - if timeout > 0 { - var cancel func() - ctx, cancel = context.WithTimeout(ctx, timeout) - defer cancel() - req = req.WithContext(ctx) - } - - return httpu.DoWithContext(req, numSends) -} - -// DoWithContext implements ClientInterfaceCtx.DoWithContext. -// -// Make sure to read the documentation on the ClientInterfaceCtx interface -// regarding cancellation! -func (httpu *HTTPUClient) DoWithContext( - req *http.Request, - numSends int, ) ([]*http.Response, error) { httpu.connLock.Lock() defer httpu.connLock.Unlock() @@ -143,28 +101,10 @@ func (httpu *HTTPUClient) DoWithContext( if err != nil { return nil, err } - - // Handle context deadline/timeout - ctx := req.Context() - deadline, ok := ctx.Deadline() - if ok { - if err = httpu.conn.SetDeadline(deadline); err != nil { - return nil, err - } + if err = httpu.conn.SetDeadline(time.Now().Add(timeout)); err != nil { + return nil, err } - // Handle context cancelation - done := make(chan struct{}) - defer close(done) - go func() { - select { - case <-ctx.Done(): - // if context is cancelled, stop any connections by setting time in the past. - httpu.conn.SetDeadline(time.Now().Add(-time.Second)) - case <-done: - } - }() - // Send request. for i := 0; i < numSends; i++ { if n, err := httpu.conn.WriteTo(requestBuf.Bytes(), destAddr); err != nil { diff --git a/vendor/github.com/huin/goupnp/httpu/multiclient.go b/vendor/github.com/huin/goupnp/httpu/multiclient.go index 5cc65e911..463ab7a69 100644 --- a/vendor/github.com/huin/goupnp/httpu/multiclient.go +++ b/vendor/github.com/huin/goupnp/httpu/multiclient.go @@ -49,14 +49,14 @@ func (mc *MultiClient) Do( } func (mc *MultiClient) sendRequests( - results chan<- []*http.Response, + results chan<-[]*http.Response, req *http.Request, timeout time.Duration, numSends int, ) error { tasks := &errgroup.Group{} for _, d := range mc.delegates { - d := d // copy for closure + d := d // copy for closure tasks.Go(func() error { responses, err := d.Do(req, timeout, numSends) if err != nil { @@ -68,65 +68,3 @@ func (mc *MultiClient) sendRequests( } return tasks.Wait() } - -// MultiClientCtx dispatches requests out to all the delegated clients. -type MultiClientCtx struct { - // The HTTPU clients to delegate to. - delegates []ClientInterfaceCtx -} - -var _ ClientInterfaceCtx = &MultiClientCtx{} - -// NewMultiClient creates a new MultiClient that delegates to all the given -// clients. -func NewMultiClientCtx(delegates []ClientInterfaceCtx) *MultiClientCtx { - return &MultiClientCtx{ - delegates: delegates, - } -} - -// DoWithContext implements ClientInterfaceCtx.DoWithContext. -func (mc *MultiClientCtx) DoWithContext( - req *http.Request, - numSends int, -) ([]*http.Response, error) { - tasks, ctx := errgroup.WithContext(req.Context()) - req = req.WithContext(ctx) // so we cancel if the errgroup errors - results := make(chan []*http.Response) - - // For each client, send the request to it and collect results. - tasks.Go(func() error { - defer close(results) - return mc.sendRequestsCtx(results, req, numSends) - }) - - var responses []*http.Response - tasks.Go(func() error { - for rs := range results { - responses = append(responses, rs...) - } - return nil - }) - - return responses, tasks.Wait() -} - -func (mc *MultiClientCtx) sendRequestsCtx( - results chan<- []*http.Response, - req *http.Request, - numSends int, -) error { - tasks := &errgroup.Group{} - for _, d := range mc.delegates { - d := d // copy for closure - tasks.Go(func() error { - responses, err := d.DoWithContext(req, numSends) - if err != nil { - return err - } - results <- responses - return nil - }) - } - return tasks.Wait() -} diff --git a/vendor/github.com/huin/goupnp/network.go b/vendor/github.com/huin/goupnp/network.go index a2c3a45be..e93763a54 100644 --- a/vendor/github.com/huin/goupnp/network.go +++ b/vendor/github.com/huin/goupnp/network.go @@ -10,14 +10,14 @@ import ( // httpuClient creates a HTTPU client that multiplexes to all multicast-capable // IPv4 addresses on the host. Returns a function to clean up once the client is // no longer required. -func httpuClient() (httpu.ClientInterfaceCtx, func(), error) { +func httpuClient() (httpu.ClientInterface, func(), error) { addrs, err := localIPv4MCastAddrs() if err != nil { return nil, nil, ctxError(err, "requesting host IPv4 addresses") } closers := make([]io.Closer, 0, len(addrs)) - delegates := make([]httpu.ClientInterfaceCtx, 0, len(addrs)) + delegates := make([]httpu.ClientInterface, 0, len(addrs)) for _, addr := range addrs { c, err := httpu.NewHTTPUClientAddr(addr) if err != nil { @@ -34,7 +34,7 @@ func httpuClient() (httpu.ClientInterfaceCtx, func(), error) { } } - return httpu.NewMultiClientCtx(delegates), closer, nil + return httpu.NewMultiClient(delegates), closer, nil } // localIPv2MCastAddrs returns the set of IPv4 addresses on multicast-able diff --git a/vendor/github.com/huin/goupnp/ssdp/ssdp.go b/vendor/github.com/huin/goupnp/ssdp/ssdp.go index 2f318f33e..240dfa73d 100644 --- a/vendor/github.com/huin/goupnp/ssdp/ssdp.go +++ b/vendor/github.com/huin/goupnp/ssdp/ssdp.go @@ -35,15 +35,6 @@ type HTTPUClient interface { ) ([]*http.Response, error) } -// HTTPUClientCtx is an optional interface that will be used to perform -// HTTP-over-UDP requests if the client implements it. -type HTTPUClientCtx interface { - DoWithContext( - req *http.Request, - numSends int, - ) ([]*http.Response, error) -} - // SSDPRawSearchCtx performs a fairly raw SSDP search request, and returns the // unique response(s) that it receives. Each response has the requested // searchTarget, a USN, and a valid location. maxWaitSeconds states how long to @@ -58,64 +49,8 @@ func SSDPRawSearchCtx( maxWaitSeconds int, numSends int, ) ([]*http.Response, error) { - req, err := prepareRequest(ctx, searchTarget, maxWaitSeconds) - if err != nil { - return nil, err - } - - allResponses, err := httpu.Do(req, time.Duration(maxWaitSeconds)*time.Second+100*time.Millisecond, numSends) - if err != nil { - return nil, err - } - return processSSDPResponses(searchTarget, allResponses) -} - -// RawSearch performs a fairly raw SSDP search request, and returns the -// unique response(s) that it receives. Each response has the requested -// searchTarget, a USN, and a valid location. If the provided context times out -// or is canceled, the search will be aborted. numSends is the number of -// requests to send - 3 is a reasonable value for this. -// -// The provided context should have a deadline, since the SSDP protocol -// requires the max wait time be included in search requests. If the context -// has no deadline, then a default deadline of 3 seconds will be applied. -func RawSearch( - ctx context.Context, - httpu HTTPUClientCtx, - searchTarget string, - numSends int, -) ([]*http.Response, error) { - // We need a timeout value to include in the SSDP request; get it by - // checking the deadline on the context. - var maxWaitSeconds int - if deadline, ok := ctx.Deadline(); ok { - maxWaitSeconds = int(deadline.Sub(time.Now()) / time.Second) - } else { - // Pick a default timeout of 3 seconds if none was provided. - maxWaitSeconds = 3 - - var cancel func() - ctx, cancel = context.WithTimeout(ctx, time.Duration(maxWaitSeconds)*time.Second) - defer cancel() - } - - req, err := prepareRequest(ctx, searchTarget, maxWaitSeconds) - if err != nil { - return nil, err - } - - allResponses, err := httpu.DoWithContext(req, numSends) - if err != nil { - return nil, err - } - return processSSDPResponses(searchTarget, allResponses) -} - -// prepareRequest checks the provided parameters and constructs a SSDP search -// request to be sent. -func prepareRequest(ctx context.Context, searchTarget string, maxWaitSeconds int) (*http.Request, error) { if maxWaitSeconds < 1 { - return nil, errors.New("ssdp: request timeout must be at least 1s") + return nil, errors.New("ssdp: maxWaitSeconds must be >= 1") } req := (&http.Request{ @@ -132,13 +67,11 @@ func prepareRequest(ctx context.Context, searchTarget string, maxWaitSeconds int "ST": []string{searchTarget}, }, }).WithContext(ctx) - return req, nil -} + allResponses, err := httpu.Do(req, time.Duration(maxWaitSeconds)*time.Second+100*time.Millisecond, numSends) + if err != nil { + return nil, err + } -func processSSDPResponses( - searchTarget string, - allResponses []*http.Response, -) ([]*http.Response, error) { isExactSearch := searchTarget != SSDPAll && searchTarget != UPNPRootDevice seenIDs := make(map[string]bool) diff --git a/vendor/github.com/klauspost/compress/.goreleaser.yml b/vendor/github.com/klauspost/compress/.goreleaser.yml index 4c28dff46..7a008a4d2 100644 --- a/vendor/github.com/klauspost/compress/.goreleaser.yml +++ b/vendor/github.com/klauspost/compress/.goreleaser.yml @@ -3,7 +3,7 @@ before: hooks: - ./gen.sh - - go install mvdan.cc/garble@v0.10.1 + - go install mvdan.cc/garble@v0.9.3 builds: - @@ -92,7 +92,16 @@ builds: archives: - id: s2-binaries - name_template: "s2-{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" + name_template: "s2-{{ .Os }}_{{ .Arch }}_{{ .Version }}" + replacements: + aix: AIX + darwin: OSX + linux: Linux + windows: Windows + 386: i386 + amd64: x86_64 + freebsd: FreeBSD + netbsd: NetBSD format_overrides: - goos: windows format: zip @@ -116,7 +125,7 @@ changelog: nfpms: - - file_name_template: "s2_package__{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" + file_name_template: "s2_package_{{ .Version }}_{{ .Os }}_{{ .Arch }}" vendor: Klaus Post homepage: https://github.com/klauspost/compress maintainer: Klaus Post @@ -125,3 +134,8 @@ nfpms: formats: - deb - rpm + replacements: + darwin: Darwin + linux: Linux + freebsd: FreeBSD + amd64: x86_64 diff --git a/vendor/github.com/klauspost/compress/README.md b/vendor/github.com/klauspost/compress/README.md index 43de48677..4002a16a6 100644 --- a/vendor/github.com/klauspost/compress/README.md +++ b/vendor/github.com/klauspost/compress/README.md @@ -16,18 +16,6 @@ This package provides various compression algorithms. # changelog -* Sept 19th, 2023 - [v1.17.0](https://github.com/klauspost/compress/releases/tag/v1.17.0) - * Add experimental dictionary builder https://github.com/klauspost/compress/pull/853 - * Add xerial snappy read/writer https://github.com/klauspost/compress/pull/838 - * flate: Add limited window compression https://github.com/klauspost/compress/pull/843 - * s2: Do 2 overlapping match checks https://github.com/klauspost/compress/pull/839 - * flate: Add amd64 assembly matchlen https://github.com/klauspost/compress/pull/837 - * gzip: Copy bufio.Reader on Reset by @thatguystone in https://github.com/klauspost/compress/pull/860 - -* July 1st, 2023 - [v1.16.7](https://github.com/klauspost/compress/releases/tag/v1.16.7) - * zstd: Fix default level first dictionary encode https://github.com/klauspost/compress/pull/829 - * s2: add GetBufferCapacity() method by @GiedriusS in https://github.com/klauspost/compress/pull/832 - * June 13, 2023 - [v1.16.6](https://github.com/klauspost/compress/releases/tag/v1.16.6) * zstd: correctly ignore WithEncoderPadding(1) by @ianlancetaylor in https://github.com/klauspost/compress/pull/806 * zstd: Add amd64 match length assembly https://github.com/klauspost/compress/pull/824 @@ -62,9 +50,6 @@ This package provides various compression algorithms. * s2: Support io.ReaderAt in ReadSeeker. https://github.com/klauspost/compress/pull/747 * s2c/s2sx: Use concurrent decoding. https://github.com/klauspost/compress/pull/746 -
- See changes to v1.15.x - * Jan 21st, 2023 (v1.15.15) * deflate: Improve level 7-9 by @klauspost in https://github.com/klauspost/compress/pull/739 * zstd: Add delta encoding support by @greatroar in https://github.com/klauspost/compress/pull/728 @@ -191,8 +176,6 @@ Stream decompression is now faster on asynchronous, since the goroutine allocati While the release has been extensively tested, it is recommended to testing when upgrading. -
-
See changes to v1.14.x @@ -653,8 +636,6 @@ Here are other packages of good quality and pure Go (no cgo wrappers or autoconv * [github.com/dsnet/compress](https://github.com/dsnet/compress) - brotli decompression, bzip2 writer. * [github.com/ronanh/intcomp](https://github.com/ronanh/intcomp) - Integer compression. * [github.com/spenczar/fpc](https://github.com/spenczar/fpc) - Float compression. -* [github.com/minio/zipindex](https://github.com/minio/zipindex) - External ZIP directory index. -* [github.com/ybirader/pzip](https://github.com/ybirader/pzip) - Fast concurrent zip archiver and extractor. # license diff --git a/vendor/github.com/klauspost/compress/fse/bitwriter.go b/vendor/github.com/klauspost/compress/fse/bitwriter.go index e82fa3bb7..43e463611 100644 --- a/vendor/github.com/klauspost/compress/fse/bitwriter.go +++ b/vendor/github.com/klauspost/compress/fse/bitwriter.go @@ -152,11 +152,12 @@ func (b *bitWriter) flushAlign() { // close will write the alignment bit and write the final byte(s) // to the output. -func (b *bitWriter) close() { +func (b *bitWriter) close() error { // End mark b.addBits16Clean(1, 1) // flush until next byte. b.flushAlign() + return nil } // reset and continue writing by appending to out. diff --git a/vendor/github.com/klauspost/compress/fse/compress.go b/vendor/github.com/klauspost/compress/fse/compress.go index 65d777357..dac97e58a 100644 --- a/vendor/github.com/klauspost/compress/fse/compress.go +++ b/vendor/github.com/klauspost/compress/fse/compress.go @@ -199,8 +199,7 @@ func (s *Scratch) compress(src []byte) error { c2.flush(s.actualTableLog) c1.flush(s.actualTableLog) - s.bw.close() - return nil + return s.bw.close() } // writeCount will write the normalized histogram count to header. diff --git a/vendor/github.com/klauspost/compress/huff0/bitwriter.go b/vendor/github.com/klauspost/compress/huff0/bitwriter.go index 0ebc9aaac..b4d7164e3 100644 --- a/vendor/github.com/klauspost/compress/huff0/bitwriter.go +++ b/vendor/github.com/klauspost/compress/huff0/bitwriter.go @@ -94,9 +94,10 @@ func (b *bitWriter) flushAlign() { // close will write the alignment bit and write the final byte(s) // to the output. -func (b *bitWriter) close() { +func (b *bitWriter) close() error { // End mark b.addBits16Clean(1, 1) // flush until next byte. b.flushAlign() + return nil } diff --git a/vendor/github.com/klauspost/compress/huff0/compress.go b/vendor/github.com/klauspost/compress/huff0/compress.go index 518436cf3..4ee4fa18d 100644 --- a/vendor/github.com/klauspost/compress/huff0/compress.go +++ b/vendor/github.com/klauspost/compress/huff0/compress.go @@ -227,10 +227,10 @@ func EstimateSizes(in []byte, s *Scratch) (tableSz, dataSz, reuseSz int, err err } func (s *Scratch) compress1X(src []byte) ([]byte, error) { - return s.compress1xDo(s.Out, src), nil + return s.compress1xDo(s.Out, src) } -func (s *Scratch) compress1xDo(dst, src []byte) []byte { +func (s *Scratch) compress1xDo(dst, src []byte) ([]byte, error) { var bw = bitWriter{out: dst} // N is length divisible by 4. @@ -260,8 +260,8 @@ func (s *Scratch) compress1xDo(dst, src []byte) []byte { bw.encTwoSymbols(cTable, tmp[1], tmp[0]) } } - bw.close() - return bw.out + err := bw.close() + return bw.out, err } var sixZeros [6]byte @@ -283,8 +283,12 @@ func (s *Scratch) compress4X(src []byte) ([]byte, error) { } src = src[len(toDo):] + var err error idx := len(s.Out) - s.Out = s.compress1xDo(s.Out, toDo) + s.Out, err = s.compress1xDo(s.Out, toDo) + if err != nil { + return nil, err + } if len(s.Out)-idx > math.MaxUint16 { // We cannot store the size in the jump table return nil, ErrIncompressible @@ -311,6 +315,7 @@ func (s *Scratch) compress4Xp(src []byte) ([]byte, error) { segmentSize := (len(src) + 3) / 4 var wg sync.WaitGroup + var errs [4]error wg.Add(4) for i := 0; i < 4; i++ { toDo := src @@ -321,12 +326,15 @@ func (s *Scratch) compress4Xp(src []byte) ([]byte, error) { // Separate goroutine for each block. go func(i int) { - s.tmpOut[i] = s.compress1xDo(s.tmpOut[i][:0], toDo) + s.tmpOut[i], errs[i] = s.compress1xDo(s.tmpOut[i][:0], toDo) wg.Done() }(i) } wg.Wait() for i := 0; i < 4; i++ { + if errs[i] != nil { + return nil, errs[i] + } o := s.tmpOut[i] if len(o) > math.MaxUint16 { // We cannot store the size in the jump table diff --git a/vendor/github.com/klauspost/compress/zstd/bitreader.go b/vendor/github.com/klauspost/compress/zstd/bitreader.go index 25ca98394..97299d499 100644 --- a/vendor/github.com/klauspost/compress/zstd/bitreader.go +++ b/vendor/github.com/klauspost/compress/zstd/bitreader.go @@ -17,6 +17,7 @@ import ( // for aligning the input. type bitReader struct { in []byte + off uint // next byte to read is at in[off - 1] value uint64 // Maybe use [16]byte, but shifting is awkward. bitsRead uint8 } @@ -27,6 +28,7 @@ func (b *bitReader) init(in []byte) error { return errors.New("corrupt stream: too short") } b.in = in + b.off = uint(len(in)) // The highest bit of the last byte indicates where to start v := in[len(in)-1] if v == 0 { @@ -67,19 +69,21 @@ func (b *bitReader) fillFast() { if b.bitsRead < 32 { return } - v := b.in[len(b.in)-4:] - b.in = b.in[:len(b.in)-4] + // 2 bounds checks. + v := b.in[b.off-4:] + v = v[:4] low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) b.value = (b.value << 32) | uint64(low) b.bitsRead -= 32 + b.off -= 4 } // fillFastStart() assumes the bitreader is empty and there is at least 8 bytes to read. func (b *bitReader) fillFastStart() { - v := b.in[len(b.in)-8:] - b.in = b.in[:len(b.in)-8] - b.value = binary.LittleEndian.Uint64(v) + // Do single re-slice to avoid bounds checks. + b.value = binary.LittleEndian.Uint64(b.in[b.off-8:]) b.bitsRead = 0 + b.off -= 8 } // fill() will make sure at least 32 bits are available. @@ -87,25 +91,25 @@ func (b *bitReader) fill() { if b.bitsRead < 32 { return } - if len(b.in) >= 4 { - v := b.in[len(b.in)-4:] - b.in = b.in[:len(b.in)-4] + if b.off >= 4 { + v := b.in[b.off-4:] + v = v[:4] low := (uint32(v[0])) | (uint32(v[1]) << 8) | (uint32(v[2]) << 16) | (uint32(v[3]) << 24) b.value = (b.value << 32) | uint64(low) b.bitsRead -= 32 + b.off -= 4 return } - - b.bitsRead -= uint8(8 * len(b.in)) - for len(b.in) > 0 { - b.value = (b.value << 8) | uint64(b.in[len(b.in)-1]) - b.in = b.in[:len(b.in)-1] + for b.off > 0 { + b.value = (b.value << 8) | uint64(b.in[b.off-1]) + b.bitsRead -= 8 + b.off-- } } // finished returns true if all bits have been read from the bit stream. func (b *bitReader) finished() bool { - return len(b.in) == 0 && b.bitsRead >= 64 + return b.off == 0 && b.bitsRead >= 64 } // overread returns true if more bits have been requested than is on the stream. @@ -115,7 +119,7 @@ func (b *bitReader) overread() bool { // remain returns the number of bits remaining. func (b *bitReader) remain() uint { - return 8*uint(len(b.in)) + 64 - uint(b.bitsRead) + return b.off*8 + 64 - uint(b.bitsRead) } // close the bitstream and returns an error if out-of-buffer reads occurred. diff --git a/vendor/github.com/klauspost/compress/zstd/bitwriter.go b/vendor/github.com/klauspost/compress/zstd/bitwriter.go index 1952f175b..78b3c61be 100644 --- a/vendor/github.com/klauspost/compress/zstd/bitwriter.go +++ b/vendor/github.com/klauspost/compress/zstd/bitwriter.go @@ -97,11 +97,12 @@ func (b *bitWriter) flushAlign() { // close will write the alignment bit and write the final byte(s) // to the output. -func (b *bitWriter) close() { +func (b *bitWriter) close() error { // End mark b.addBits16Clean(1, 1) // flush until next byte. b.flushAlign() + return nil } // reset and continue writing by appending to out. diff --git a/vendor/github.com/klauspost/compress/zstd/blockenc.go b/vendor/github.com/klauspost/compress/zstd/blockenc.go index 2cfe925ad..fd4a36f73 100644 --- a/vendor/github.com/klauspost/compress/zstd/blockenc.go +++ b/vendor/github.com/klauspost/compress/zstd/blockenc.go @@ -361,21 +361,14 @@ func (b *blockEnc) encodeLits(lits []byte, raw bool) error { if len(lits) >= 1024 { // Use 4 Streams. out, reUsed, err = huff0.Compress4X(lits, b.litEnc) - } else if len(lits) > 16 { + } else if len(lits) > 32 { // Use 1 stream single = true out, reUsed, err = huff0.Compress1X(lits, b.litEnc) } else { err = huff0.ErrIncompressible } - if err == nil && len(out)+5 > len(lits) { - // If we are close, we may still be worse or equal to raw. - var lh literalsHeader - lh.setSizes(len(out), len(lits), single) - if len(out)+lh.size() >= len(lits) { - err = huff0.ErrIncompressible - } - } + switch err { case huff0.ErrIncompressible: if debugEncoder { @@ -510,7 +503,7 @@ func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { if len(b.literals) >= 1024 && !raw { // Use 4 Streams. out, reUsed, err = huff0.Compress4X(b.literals, b.litEnc) - } else if len(b.literals) > 16 && !raw { + } else if len(b.literals) > 32 && !raw { // Use 1 stream single = true out, reUsed, err = huff0.Compress1X(b.literals, b.litEnc) @@ -518,17 +511,6 @@ func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { err = huff0.ErrIncompressible } - if err == nil && len(out)+5 > len(b.literals) { - // If we are close, we may still be worse or equal to raw. - var lh literalsHeader - lh.setSize(len(b.literals)) - szRaw := lh.size() - lh.setSizes(len(out), len(b.literals), single) - szComp := lh.size() - if len(out)+szComp >= len(b.literals)+szRaw { - err = huff0.ErrIncompressible - } - } switch err { case huff0.ErrIncompressible: lh.setType(literalsBlockRaw) @@ -791,7 +773,10 @@ func (b *blockEnc) encode(org []byte, raw, rawAllLits bool) error { ml.flush(mlEnc.actualTableLog) of.flush(ofEnc.actualTableLog) ll.flush(llEnc.actualTableLog) - wr.close() + err = wr.close() + if err != nil { + return err + } b.output = wr.out // Maybe even add a bigger margin. diff --git a/vendor/github.com/klauspost/compress/zstd/dict.go b/vendor/github.com/klauspost/compress/zstd/dict.go index 8d5567fe6..ca0951452 100644 --- a/vendor/github.com/klauspost/compress/zstd/dict.go +++ b/vendor/github.com/klauspost/compress/zstd/dict.go @@ -1,13 +1,10 @@ package zstd import ( - "bytes" "encoding/binary" "errors" "fmt" "io" - "math" - "sort" "github.com/klauspost/compress/huff0" ) @@ -17,8 +14,9 @@ type dict struct { litEnc *huff0.Scratch llDec, ofDec, mlDec sequenceDec - offsets [3]int - content []byte + //llEnc, ofEnc, mlEnc []*fseEncoder + offsets [3]int + content []byte } const dictMagic = "\x37\xa4\x30\xec" @@ -161,374 +159,3 @@ func InspectDictionary(b []byte) (interface { d, err := loadDict(b) return d, err } - -type BuildDictOptions struct { - // Dictionary ID. - ID uint32 - - // Content to use to create dictionary tables. - Contents [][]byte - - // History to use for all blocks. - History []byte - - // Offsets to use. - Offsets [3]int - - // CompatV155 will make the dictionary compatible with Zstd v1.5.5 and earlier. - // See https://github.com/facebook/zstd/issues/3724 - CompatV155 bool - - // Use the specified encoder level. - // The dictionary will be built using the specified encoder level, - // which will reflect speed and make the dictionary tailored for that level. - // If not set SpeedBestCompression will be used. - Level EncoderLevel - - // DebugOut will write stats and other details here if set. - DebugOut io.Writer -} - -func BuildDict(o BuildDictOptions) ([]byte, error) { - initPredefined() - hist := o.History - contents := o.Contents - debug := o.DebugOut != nil - println := func(args ...interface{}) { - if o.DebugOut != nil { - fmt.Fprintln(o.DebugOut, args...) - } - } - printf := func(s string, args ...interface{}) { - if o.DebugOut != nil { - fmt.Fprintf(o.DebugOut, s, args...) - } - } - print := func(args ...interface{}) { - if o.DebugOut != nil { - fmt.Fprint(o.DebugOut, args...) - } - } - - if int64(len(hist)) > dictMaxLength { - return nil, fmt.Errorf("dictionary of size %d > %d", len(hist), int64(dictMaxLength)) - } - if len(hist) < 8 { - return nil, fmt.Errorf("dictionary of size %d < %d", len(hist), 8) - } - if len(contents) == 0 { - return nil, errors.New("no content provided") - } - d := dict{ - id: o.ID, - litEnc: nil, - llDec: sequenceDec{}, - ofDec: sequenceDec{}, - mlDec: sequenceDec{}, - offsets: o.Offsets, - content: hist, - } - block := blockEnc{lowMem: false} - block.init() - enc := encoder(&bestFastEncoder{fastBase: fastBase{maxMatchOff: int32(maxMatchLen), bufferReset: math.MaxInt32 - int32(maxMatchLen*2), lowMem: false}}) - if o.Level != 0 { - eOpts := encoderOptions{ - level: o.Level, - blockSize: maxMatchLen, - windowSize: maxMatchLen, - dict: &d, - lowMem: false, - } - enc = eOpts.encoder() - } else { - o.Level = SpeedBestCompression - } - var ( - remain [256]int - ll [256]int - ml [256]int - of [256]int - ) - addValues := func(dst *[256]int, src []byte) { - for _, v := range src { - dst[v]++ - } - } - addHist := func(dst *[256]int, src *[256]uint32) { - for i, v := range src { - dst[i] += int(v) - } - } - seqs := 0 - nUsed := 0 - litTotal := 0 - newOffsets := make(map[uint32]int, 1000) - for _, b := range contents { - block.reset(nil) - if len(b) < 8 { - continue - } - nUsed++ - enc.Reset(&d, true) - enc.Encode(&block, b) - addValues(&remain, block.literals) - litTotal += len(block.literals) - seqs += len(block.sequences) - block.genCodes() - addHist(&ll, block.coders.llEnc.Histogram()) - addHist(&ml, block.coders.mlEnc.Histogram()) - addHist(&of, block.coders.ofEnc.Histogram()) - for i, seq := range block.sequences { - if i > 3 { - break - } - offset := seq.offset - if offset == 0 { - continue - } - if offset > 3 { - newOffsets[offset-3]++ - } else { - newOffsets[uint32(o.Offsets[offset-1])]++ - } - } - } - // Find most used offsets. - var sortedOffsets []uint32 - for k := range newOffsets { - sortedOffsets = append(sortedOffsets, k) - } - sort.Slice(sortedOffsets, func(i, j int) bool { - a, b := sortedOffsets[i], sortedOffsets[j] - if a == b { - // Prefer the longer offset - return sortedOffsets[i] > sortedOffsets[j] - } - return newOffsets[sortedOffsets[i]] > newOffsets[sortedOffsets[j]] - }) - if len(sortedOffsets) > 3 { - if debug { - print("Offsets:") - for i, v := range sortedOffsets { - if i > 20 { - break - } - printf("[%d: %d],", v, newOffsets[v]) - } - println("") - } - - sortedOffsets = sortedOffsets[:3] - } - for i, v := range sortedOffsets { - o.Offsets[i] = int(v) - } - if debug { - println("New repeat offsets", o.Offsets) - } - - if nUsed == 0 || seqs == 0 { - return nil, fmt.Errorf("%d blocks, %d sequences found", nUsed, seqs) - } - if debug { - println("Sequences:", seqs, "Blocks:", nUsed, "Literals:", litTotal) - } - if seqs/nUsed < 512 { - // Use 512 as minimum. - nUsed = seqs / 512 - } - copyHist := func(dst *fseEncoder, src *[256]int) ([]byte, error) { - hist := dst.Histogram() - var maxSym uint8 - var maxCount int - var fakeLength int - for i, v := range src { - if v > 0 { - v = v / nUsed - if v == 0 { - v = 1 - } - } - if v > maxCount { - maxCount = v - } - if v != 0 { - maxSym = uint8(i) - } - fakeLength += v - hist[i] = uint32(v) - } - dst.HistogramFinished(maxSym, maxCount) - dst.reUsed = false - dst.useRLE = false - err := dst.normalizeCount(fakeLength) - if err != nil { - return nil, err - } - if debug { - println("RAW:", dst.count[:maxSym+1], "NORM:", dst.norm[:maxSym+1], "LEN:", fakeLength) - } - return dst.writeCount(nil) - } - if debug { - print("Literal lengths: ") - } - llTable, err := copyHist(block.coders.llEnc, &ll) - if err != nil { - return nil, err - } - if debug { - print("Match lengths: ") - } - mlTable, err := copyHist(block.coders.mlEnc, &ml) - if err != nil { - return nil, err - } - if debug { - print("Offsets: ") - } - ofTable, err := copyHist(block.coders.ofEnc, &of) - if err != nil { - return nil, err - } - - // Literal table - avgSize := litTotal - if avgSize > huff0.BlockSizeMax/2 { - avgSize = huff0.BlockSizeMax / 2 - } - huffBuff := make([]byte, 0, avgSize) - // Target size - div := litTotal / avgSize - if div < 1 { - div = 1 - } - if debug { - println("Huffman weights:") - } - for i, n := range remain[:] { - if n > 0 { - n = n / div - // Allow all entries to be represented. - if n == 0 { - n = 1 - } - huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) - if debug { - printf("[%d: %d], ", i, n) - } - } - } - if o.CompatV155 && remain[255]/div == 0 { - huffBuff = append(huffBuff, 255) - } - scratch := &huff0.Scratch{TableLog: 11} - for tries := 0; tries < 255; tries++ { - scratch = &huff0.Scratch{TableLog: 11} - _, _, err = huff0.Compress1X(huffBuff, scratch) - if err == nil { - break - } - if debug { - printf("Try %d: Huffman error: %v\n", tries+1, err) - } - huffBuff = huffBuff[:0] - if tries == 250 { - if debug { - println("Huffman: Bailing out with predefined table") - } - - // Bail out.... Just generate something - huffBuff = append(huffBuff, bytes.Repeat([]byte{255}, 10000)...) - for i := 0; i < 128; i++ { - huffBuff = append(huffBuff, byte(i)) - } - continue - } - if errors.Is(err, huff0.ErrIncompressible) { - // Try truncating least common. - for i, n := range remain[:] { - if n > 0 { - n = n / (div * (i + 1)) - if n > 0 { - huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) - } - } - } - if o.CompatV155 && len(huffBuff) > 0 && huffBuff[len(huffBuff)-1] != 255 { - huffBuff = append(huffBuff, 255) - } - if len(huffBuff) == 0 { - huffBuff = append(huffBuff, 0, 255) - } - } - if errors.Is(err, huff0.ErrUseRLE) { - for i, n := range remain[:] { - n = n / (div * (i + 1)) - // Allow all entries to be represented. - if n == 0 { - n = 1 - } - huffBuff = append(huffBuff, bytes.Repeat([]byte{byte(i)}, n)...) - } - } - } - - var out bytes.Buffer - out.Write([]byte(dictMagic)) - out.Write(binary.LittleEndian.AppendUint32(nil, o.ID)) - out.Write(scratch.OutTable) - if debug { - println("huff table:", len(scratch.OutTable), "bytes") - println("of table:", len(ofTable), "bytes") - println("ml table:", len(mlTable), "bytes") - println("ll table:", len(llTable), "bytes") - } - out.Write(ofTable) - out.Write(mlTable) - out.Write(llTable) - out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[0]))) - out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[1]))) - out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[2]))) - out.Write(hist) - if debug { - _, err := loadDict(out.Bytes()) - if err != nil { - panic(err) - } - i, err := InspectDictionary(out.Bytes()) - if err != nil { - panic(err) - } - println("ID:", i.ID()) - println("Content size:", i.ContentSize()) - println("Encoder:", i.LitEncoder() != nil) - println("Offsets:", i.Offsets()) - var totalSize int - for _, b := range contents { - totalSize += len(b) - } - - encWith := func(opts ...EOption) int { - enc, err := NewWriter(nil, opts...) - if err != nil { - panic(err) - } - defer enc.Close() - var dst []byte - var totalSize int - for _, b := range contents { - dst = enc.EncodeAll(b, dst[:0]) - totalSize += len(dst) - } - return totalSize - } - plain := encWith(WithEncoderLevel(o.Level)) - withDict := encWith(WithEncoderLevel(o.Level), WithEncoderDict(out.Bytes())) - println("Input size:", totalSize) - println("Plain Compressed:", plain) - println("Dict Compressed:", withDict) - println("Saved:", plain-withDict, (plain-withDict)/len(contents), "bytes per input (rounded down)") - } - return out.Bytes(), nil -} diff --git a/vendor/github.com/klauspost/compress/zstd/enc_best.go b/vendor/github.com/klauspost/compress/zstd/enc_best.go index 858f8f43a..9819d4145 100644 --- a/vendor/github.com/klauspost/compress/zstd/enc_best.go +++ b/vendor/github.com/klauspost/compress/zstd/enc_best.go @@ -197,13 +197,12 @@ encodeLoop: // Set m to a match at offset if it looks like that will improve compression. improve := func(m *match, offset int32, s int32, first uint32, rep int32) { - delta := s - offset - if delta >= e.maxMatchOff || delta <= 0 || load3232(src, offset) != first { + if s-offset >= e.maxMatchOff || load3232(src, offset) != first { return } if debugAsserts { - if offset >= s { - panic(fmt.Sprintf("offset: %d - s:%d - rep: %d - cur :%d - max: %d", offset, s, rep, e.cur, e.maxMatchOff)) + if offset <= 0 { + panic(offset) } if !bytes.Equal(src[s:s+4], src[offset:offset+4]) { panic(fmt.Sprintf("first match mismatch: %v != %v, first: %08x", src[s:s+4], src[offset:offset+4], first)) @@ -344,8 +343,8 @@ encodeLoop: if best.rep > 0 { var seq seq seq.matchLen = uint32(best.length - zstdMinMatch) - if debugAsserts && s < nextEmit { - panic("s < nextEmit") + if debugAsserts && s <= nextEmit { + panic("s <= nextEmit") } addLiterals(&seq, best.s) diff --git a/vendor/github.com/klauspost/compress/zstd/encoder.go b/vendor/github.com/klauspost/compress/zstd/encoder.go index 72af7ef0f..4de0aed0d 100644 --- a/vendor/github.com/klauspost/compress/zstd/encoder.go +++ b/vendor/github.com/klauspost/compress/zstd/encoder.go @@ -227,7 +227,10 @@ func (e *Encoder) nextBlock(final bool) error { DictID: e.o.dict.ID(), } - dst := fh.appendTo(tmp[:0]) + dst, err := fh.appendTo(tmp[:0]) + if err != nil { + return err + } s.headerWritten = true s.wWg.Wait() var n2 int @@ -480,7 +483,7 @@ func (e *Encoder) EncodeAll(src, dst []byte) []byte { Checksum: false, DictID: 0, } - dst = fh.appendTo(dst) + dst, _ = fh.appendTo(dst) // Write raw block as last one only. var blk blockHeader @@ -515,7 +518,10 @@ func (e *Encoder) EncodeAll(src, dst []byte) []byte { if len(dst) == 0 && cap(dst) == 0 && len(src) < 1<<20 && !e.o.lowMem { dst = make([]byte, 0, len(src)) } - dst = fh.appendTo(dst) + dst, err := fh.appendTo(dst) + if err != nil { + panic(err) + } // If we can do everything in one block, prefer that. if len(src) <= e.o.blockSize { @@ -575,7 +581,6 @@ func (e *Encoder) EncodeAll(src, dst []byte) []byte { // Add padding with content from crypto/rand.Reader if e.o.pad > 0 { add := calcSkippableFrame(int64(len(dst)), int64(e.o.pad)) - var err error dst, err = skippableFrame(dst, add, rand.Reader) if err != nil { panic(err) diff --git a/vendor/github.com/klauspost/compress/zstd/frameenc.go b/vendor/github.com/klauspost/compress/zstd/frameenc.go index 2f5d5ed45..4ef7f5a3e 100644 --- a/vendor/github.com/klauspost/compress/zstd/frameenc.go +++ b/vendor/github.com/klauspost/compress/zstd/frameenc.go @@ -22,7 +22,7 @@ type frameHeader struct { const maxHeaderSize = 14 -func (f frameHeader) appendTo(dst []byte) []byte { +func (f frameHeader) appendTo(dst []byte) ([]byte, error) { dst = append(dst, frameMagic...) var fhd uint8 if f.Checksum { @@ -88,7 +88,7 @@ func (f frameHeader) appendTo(dst []byte) []byte { default: panic("invalid fcs") } - return dst + return dst, nil } const skippableFrameHeader = 4 + 4 diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec.go b/vendor/github.com/klauspost/compress/zstd/seqdec.go index d7fe6d82d..9405fcf10 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec.go @@ -245,7 +245,7 @@ func (s *sequenceDecs) decodeSync(hist []byte) error { return io.ErrUnexpectedEOF } var ll, mo, ml int - if len(br.in) > 4+((maxOffsetBits+16+16)>>3) { + if br.off > 4+((maxOffsetBits+16+16)>>3) { // inlined function: // ll, mo, ml = s.nextFast(br, llState, mlState, ofState) @@ -452,13 +452,18 @@ func (s *sequenceDecs) next(br *bitReader, llState, mlState, ofState decSymbol) // extra bits are stored in reverse order. br.fill() - mo += br.getBits(moB) - if s.maxBits > 32 { + if s.maxBits <= 32 { + mo += br.getBits(moB) + ml += br.getBits(mlB) + ll += br.getBits(llB) + } else { + mo += br.getBits(moB) br.fill() + // matchlength+literal length, max 32 bits + ml += br.getBits(mlB) + ll += br.getBits(llB) + } - // matchlength+literal length, max 32 bits - ml += br.getBits(mlB) - ll += br.getBits(llB) mo = s.adjustOffset(mo, ll, moB) return } diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s index 974b99725..b6f4ba6fc 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.s @@ -5,11 +5,11 @@ // func sequenceDecs_decode_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: CMOV TEXT ·sequenceDecs_decode_amd64(SB), $8-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI + MOVQ br+8(FP), AX + MOVQ 32(AX), DX + MOVBQZX 40(AX), BX + MOVQ 24(AX), SI + MOVQ (AX), AX ADDQ SI, AX MOVQ AX, (SP) MOVQ ctx+16(FP), AX @@ -301,9 +301,9 @@ sequenceDecs_decode_amd64_match_len_ofs_ok: MOVQ R12, 152(AX) MOVQ R13, 160(AX) MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) + MOVQ DX, 32(AX) + MOVB BL, 40(AX) + MOVQ SI, 24(AX) // Return success MOVQ $0x00000000, ret+24(FP) @@ -336,11 +336,11 @@ error_overread: // func sequenceDecs_decode_56_amd64(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: CMOV TEXT ·sequenceDecs_decode_56_amd64(SB), $8-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI + MOVQ br+8(FP), AX + MOVQ 32(AX), DX + MOVBQZX 40(AX), BX + MOVQ 24(AX), SI + MOVQ (AX), AX ADDQ SI, AX MOVQ AX, (SP) MOVQ ctx+16(FP), AX @@ -603,9 +603,9 @@ sequenceDecs_decode_56_amd64_match_len_ofs_ok: MOVQ R12, 152(AX) MOVQ R13, 160(AX) MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) + MOVQ DX, 32(AX) + MOVB BL, 40(AX) + MOVQ SI, 24(AX) // Return success MOVQ $0x00000000, ret+24(FP) @@ -638,11 +638,11 @@ error_overread: // func sequenceDecs_decode_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: BMI, BMI2, CMOV TEXT ·sequenceDecs_decode_bmi2(SB), $8-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX + MOVQ br+8(FP), CX + MOVQ 32(CX), AX + MOVBQZX 40(CX), DX + MOVQ 24(CX), BX + MOVQ (CX), CX ADDQ BX, CX MOVQ CX, (SP) MOVQ ctx+16(FP), CX @@ -892,9 +892,9 @@ sequenceDecs_decode_bmi2_match_len_ofs_ok: MOVQ R11, 152(CX) MOVQ R12, 160(CX) MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) + MOVQ AX, 32(CX) + MOVB DL, 40(CX) + MOVQ BX, 24(CX) // Return success MOVQ $0x00000000, ret+24(FP) @@ -927,11 +927,11 @@ error_overread: // func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmContext) int // Requires: BMI, BMI2, CMOV TEXT ·sequenceDecs_decode_56_bmi2(SB), $8-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX + MOVQ br+8(FP), CX + MOVQ 32(CX), AX + MOVBQZX 40(CX), DX + MOVQ 24(CX), BX + MOVQ (CX), CX ADDQ BX, CX MOVQ CX, (SP) MOVQ ctx+16(FP), CX @@ -1152,9 +1152,9 @@ sequenceDecs_decode_56_bmi2_match_len_ofs_ok: MOVQ R11, 152(CX) MOVQ R12, 160(CX) MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) + MOVQ AX, 32(CX) + MOVB DL, 40(CX) + MOVQ BX, 24(CX) // Return success MOVQ $0x00000000, ret+24(FP) @@ -1797,11 +1797,11 @@ empty_seqs: // func sequenceDecs_decodeSync_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: CMOV, SSE TEXT ·sequenceDecs_decodeSync_amd64(SB), $64-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI + MOVQ br+8(FP), AX + MOVQ 32(AX), DX + MOVBQZX 40(AX), BX + MOVQ 24(AX), SI + MOVQ (AX), AX ADDQ SI, AX MOVQ AX, (SP) MOVQ ctx+16(FP), AX @@ -2295,9 +2295,9 @@ handle_loop: loop_finished: MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) + MOVQ DX, 32(AX) + MOVB BL, 40(AX) + MOVQ SI, 24(AX) // Update the context MOVQ ctx+16(FP), AX @@ -2362,11 +2362,11 @@ error_not_enough_space: // func sequenceDecs_decodeSync_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: BMI, BMI2, CMOV, SSE TEXT ·sequenceDecs_decodeSync_bmi2(SB), $64-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX + MOVQ br+8(FP), CX + MOVQ 32(CX), AX + MOVBQZX 40(CX), DX + MOVQ 24(CX), BX + MOVQ (CX), CX ADDQ BX, CX MOVQ CX, (SP) MOVQ ctx+16(FP), CX @@ -2818,9 +2818,9 @@ handle_loop: loop_finished: MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) + MOVQ AX, 32(CX) + MOVB DL, 40(CX) + MOVQ BX, 24(CX) // Update the context MOVQ ctx+16(FP), AX @@ -2885,11 +2885,11 @@ error_not_enough_space: // func sequenceDecs_decodeSync_safe_amd64(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: CMOV, SSE TEXT ·sequenceDecs_decodeSync_safe_amd64(SB), $64-32 - MOVQ br+8(FP), CX - MOVQ 24(CX), DX - MOVBQZX 32(CX), BX - MOVQ (CX), AX - MOVQ 8(CX), SI + MOVQ br+8(FP), AX + MOVQ 32(AX), DX + MOVBQZX 40(AX), BX + MOVQ 24(AX), SI + MOVQ (AX), AX ADDQ SI, AX MOVQ AX, (SP) MOVQ ctx+16(FP), AX @@ -3485,9 +3485,9 @@ handle_loop: loop_finished: MOVQ br+8(FP), AX - MOVQ DX, 24(AX) - MOVB BL, 32(AX) - MOVQ SI, 8(AX) + MOVQ DX, 32(AX) + MOVB BL, 40(AX) + MOVQ SI, 24(AX) // Update the context MOVQ ctx+16(FP), AX @@ -3552,11 +3552,11 @@ error_not_enough_space: // func sequenceDecs_decodeSync_safe_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeSyncAsmContext) int // Requires: BMI, BMI2, CMOV, SSE TEXT ·sequenceDecs_decodeSync_safe_bmi2(SB), $64-32 - MOVQ br+8(FP), BX - MOVQ 24(BX), AX - MOVBQZX 32(BX), DX - MOVQ (BX), CX - MOVQ 8(BX), BX + MOVQ br+8(FP), CX + MOVQ 32(CX), AX + MOVBQZX 40(CX), DX + MOVQ 24(CX), BX + MOVQ (CX), CX ADDQ BX, CX MOVQ CX, (SP) MOVQ ctx+16(FP), CX @@ -4110,9 +4110,9 @@ handle_loop: loop_finished: MOVQ br+8(FP), CX - MOVQ AX, 24(CX) - MOVB DL, 32(CX) - MOVQ BX, 8(CX) + MOVQ AX, 32(CX) + MOVB DL, 40(CX) + MOVQ BX, 24(CX) // Update the context MOVQ ctx+16(FP), AX diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go b/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go index 2fb35b788..ac2a80d29 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_generic.go @@ -29,7 +29,7 @@ func (s *sequenceDecs) decode(seqs []seqVals) error { } for i := range seqs { var ll, mo, ml int - if len(br.in) > 4+((maxOffsetBits+16+16)>>3) { + if br.off > 4+((maxOffsetBits+16+16)>>3) { // inlined function: // ll, mo, ml = s.nextFast(br, llState, mlState, ofState) diff --git a/vendor/github.com/klauspost/compress/zstd/snappy.go b/vendor/github.com/klauspost/compress/zstd/snappy.go index ec13594e8..9e1baad73 100644 --- a/vendor/github.com/klauspost/compress/zstd/snappy.go +++ b/vendor/github.com/klauspost/compress/zstd/snappy.go @@ -95,9 +95,10 @@ func (r *SnappyConverter) Convert(in io.Reader, w io.Writer) (int64, error) { var written int64 var readHeader bool { - header := frameHeader{WindowSize: snappyMaxBlockSize}.appendTo(r.buf[:0]) - + var header []byte var n int + header, r.err = frameHeader{WindowSize: snappyMaxBlockSize}.appendTo(r.buf[:0]) + n, r.err = w.Write(header) if r.err != nil { return written, r.err diff --git a/vendor/github.com/libp2p/go-libp2p-mplex/.gitignore b/vendor/github.com/libp2p/go-libp2p-mplex/.gitignore deleted file mode 100644 index 1377554eb..000000000 --- a/vendor/github.com/libp2p/go-libp2p-mplex/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.swp diff --git a/vendor/github.com/libp2p/go-libp2p-mplex/README.md b/vendor/github.com/libp2p/go-libp2p-mplex/README.md deleted file mode 100644 index 00782d7b9..000000000 --- a/vendor/github.com/libp2p/go-libp2p-mplex/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# DEPRECATION NOTICE - -mplex has been deprecated. - -see https://github.com/libp2p/specs/issues/553 for details - -# go-libp2p-mplex - a go-stream-muxer shim for multiplex - -[![](https://img.shields.io/badge/made%20by-Protocol%20Labs-blue.svg?style=flat-square)](http://ipn.io) [![](https://img.shields.io/badge/freenode-%23ipfs-blue.svg?style=flat-square)](http://webchat.freenode.net/?channels=%23ipfs) ![](https://raw.githubusercontent.com/libp2p/go-stream-muxer/master/img/badge.png) - -This is an implementation of the [go-libp2p muxer](https://pkg.go.dev/github.com/libp2p/go-libp2p@v0.30.0/core/network#Multiplexer) interface for [multiplex](https://github.com/libp2p/go-mplex). For more information, see that repo. diff --git a/vendor/github.com/libp2p/go-libp2p-mplex/version.json b/vendor/github.com/libp2p/go-libp2p-mplex/version.json deleted file mode 100644 index 960b84e55..000000000 --- a/vendor/github.com/libp2p/go-libp2p-mplex/version.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "version": "v0.9.0" -} diff --git a/vendor/github.com/libp2p/go-libp2p-pubsub/gossipsub.go b/vendor/github.com/libp2p/go-libp2p-pubsub/gossipsub.go index 9b3023221..62dbd8e80 100644 --- a/vendor/github.com/libp2p/go-libp2p-pubsub/gossipsub.go +++ b/vendor/github.com/libp2p/go-libp2p-pubsub/gossipsub.go @@ -1183,7 +1183,7 @@ func (gs *GossipSubRouter) sendRPC(p peer.ID, out *RPC) { } func (gs *GossipSubRouter) doDropRPC(rpc *RPC, p peer.ID, reason string) { - log.Debugf("dropping message to peer %s: %s", p, reason) + log.Debugf("dropping message to peer %s: %s", p.Pretty(), reason) gs.tracer.DropRPC(rpc, p) // push control messages that need to be retried ctl := rpc.GetControl() diff --git a/vendor/github.com/libp2p/go-libp2p/README.md b/vendor/github.com/libp2p/go-libp2p/README.md index 7a95a1370..b5056de6e 100644 --- a/vendor/github.com/libp2p/go-libp2p/README.md +++ b/vendor/github.com/libp2p/go-libp2p/README.md @@ -13,17 +13,18 @@

-# Table of Contents +# Table of Contents + - [Background](#background) - [Roadmap](#roadmap) - [Usage](#usage) - [Examples](#examples) - - [Dashboards](#dashboards) +- [Development](#development) + - [Tests](#tests) - [Contribute](#contribute) - - [Supported Go Versions](#supported-go-versions) -- [Notable Users](#notable-users) +- [Supported Go Versions](#supported-go-versions) -# Background +## Background [libp2p](https://github.com/libp2p/specs) is a networking stack and library modularized out of [The IPFS Project](https://github.com/ipfs/ipfs), and bundled separately for other tools to use. > @@ -36,12 +37,12 @@ To learn more, check out the following resources: - [**js-libp2p implementation**](https://github.com/libp2p/js-libp2p) - [**rust-libp2p implementation**](https://github.com/libp2p/rust-libp2p) -# Roadmap +## Roadmap Our roadmap for go-libp2p can be found here: https://github.com/libp2p/go-libp2p/blob/master/ROADMAP.md -This document represents current projects the go-libp2p team is focused on and provides an estimation of completion targets. It is a complementary roadmap to the overarching libp2p project roadmap: https://github.com/libp2p/specs/blob/master/ROADMAP.md +This document represents current projects the go-libp2p team is focused on and provides an estimation of completion targets. It is a completementary roadmap to the overarching libp2p project roadmap: https://github.com/libp2p/specs/blob/master/ROADMAP.md -# Usage +## Usage This repository (`go-libp2p`) serves as the entrypoint to the universe of packages that compose the Go implementation of the libp2p stack. @@ -51,17 +52,10 @@ You can start using go-libp2p in your Go application simply by adding imports fr import "github.com/libp2p/go-libp2p" ``` -## Examples +### Examples Examples can be found in the [examples folder](examples). -## Dashboards - -We provide prebuilt Grafana dashboards so that applications can better monitor libp2p in production. -You can find the [dashboard JSON files here](https://github.com/libp2p/go-libp2p/tree/master/dashboards). - -We also have live [Public Dashboards](https://github.com/libp2p/go-libp2p/tree/master/dashboards/README.md#public-dashboards) that you can check out to see real time monitoring in action. - # Contribute @@ -76,7 +70,7 @@ Guidelines: - have fun! There's a few things you can do right now to help out: - - Go through the modules below and **check out existing issues**. This would be especially useful for modules in active development. Some knowledge of IPFS/libp2p may be required, as well as the infrastructure behind it - for instance, you may need to read up on p2p and more complex operations like muxing to be able to help technically. + - Go through the modules below and **check out existing issues**. This would be especially useful for modules in active development. Some knowledge of IPFS/libp2p may be required, as well as the infrasture behind it - for instance, you may need to read up on p2p and more complex operations like muxing to be able to help technically. - **Perform code reviews**. - **Add tests**. There can never be enough tests. @@ -105,4 +99,4 @@ Some notable users of go-libp2p are: - [Kairos](https://github.com/kairos-io/kairos) - A Kubernetes-focused, Cloud Native Linux meta-distribution. - [Oasis Core](https://github.com/oasisprotocol/oasis-core) - The consensus and runtime layers of the [Oasis protocol](https://oasisprotocol.org/). -Please open a pull request if you want your project (min. 250 GitHub stars) to be added here. +Please open a pull request if you want your project to be added here. diff --git a/vendor/github.com/libp2p/go-libp2p/config/config.go b/vendor/github.com/libp2p/go-libp2p/config/config.go index 8be5a4399..cea8ef131 100644 --- a/vendor/github.com/libp2p/go-libp2p/config/config.go +++ b/vendor/github.com/libp2p/go-libp2p/config/config.go @@ -261,7 +261,6 @@ func (cfg *Config) addTransports(h host.Host) error { } fxopts = append(fxopts, fx.Provide(PrivKeyToStatelessResetKey)) - fxopts = append(fxopts, fx.Provide(PrivKeyToTokenGeneratorKey)) if cfg.QUICReuse != nil { fxopts = append(fxopts, cfg.QUICReuse...) } else { @@ -296,15 +295,6 @@ func (cfg *Config) addTransports(h host.Host) error { // // This function consumes the config. Do not reuse it (really!). func (cfg *Config) NewNode() (host.Host, error) { - // If possible check that the resource manager conn limit is higher than the - // limit set in the conn manager. - if l, ok := cfg.ResourceManager.(connmgr.GetConnLimiter); ok { - err := cfg.ConnManager.CheckLimit(l) - if err != nil { - log.Warn(fmt.Sprintf("rcmgr limit conflicts with connmgr limit: %v", err)) - } - } - eventBus := eventbus.NewBus(eventbus.WithMetricsTracer(eventbus.NewMetricsTracer(eventbus.WithRegisterer(cfg.PrometheusRegisterer)))) swrm, err := cfg.makeSwarm(eventBus, !cfg.DisableMetrics) if err != nil { @@ -429,11 +419,6 @@ func (cfg *Config) NewNode() (host.Host, error) { PeerKey: autonatPrivKey, Peerstore: ps, DialRanker: swarm.NoDelayDialRanker, - SwarmOpts: []swarm.Option{ - // It is better to disable black hole detection and just attempt a dial for autonat - swarm.WithUDPBlackHoleConfig(false, 0, 0), - swarm.WithIPv6BlackHoleConfig(false, 0, 0), - }, } dialer, err := autoNatCfg.makeSwarm(eventbus.NewBus(), false) diff --git a/vendor/github.com/libp2p/go-libp2p/config/quic.go b/vendor/github.com/libp2p/go-libp2p/config/quic_stateless_reset.go similarity index 53% rename from vendor/github.com/libp2p/go-libp2p/config/quic.go rename to vendor/github.com/libp2p/go-libp2p/config/quic_stateless_reset.go index 66c40da97..a12be56f5 100644 --- a/vendor/github.com/libp2p/go-libp2p/config/quic.go +++ b/vendor/github.com/libp2p/go-libp2p/config/quic_stateless_reset.go @@ -11,10 +11,7 @@ import ( "github.com/quic-go/quic-go" ) -const ( - statelessResetKeyInfo = "libp2p quic stateless reset key" - tokenGeneratorKeyInfo = "libp2p quic token generator key" -) +const statelessResetKeyInfo = "libp2p quic stateless reset key" func PrivKeyToStatelessResetKey(key crypto.PrivKey) (quic.StatelessResetKey, error) { var statelessResetKey quic.StatelessResetKey @@ -28,16 +25,3 @@ func PrivKeyToStatelessResetKey(key crypto.PrivKey) (quic.StatelessResetKey, err } return statelessResetKey, nil } - -func PrivKeyToTokenGeneratorKey(key crypto.PrivKey) (quic.TokenGeneratorKey, error) { - var tokenKey quic.TokenGeneratorKey - keyBytes, err := key.Raw() - if err != nil { - return tokenKey, err - } - keyReader := hkdf.New(sha256.New, keyBytes, nil, []byte(tokenGeneratorKeyInfo)) - if _, err := io.ReadFull(keyReader, tokenKey[:]); err != nil { - return tokenKey, err - } - return tokenKey, nil -} diff --git a/vendor/github.com/libp2p/go-libp2p/core/connmgr/manager.go b/vendor/github.com/libp2p/go-libp2p/core/connmgr/manager.go index d756e4399..e0d6c5201 100644 --- a/vendor/github.com/libp2p/go-libp2p/core/connmgr/manager.go +++ b/vendor/github.com/libp2p/go-libp2p/core/connmgr/manager.go @@ -74,10 +74,6 @@ type ConnManager interface { // then it will return true if the peer is protected for any tag IsProtected(id peer.ID, tag string) (protected bool) - // CheckLimit will return an error if the connection manager's internal - // connection limit exceeds the provided system limit. - CheckLimit(l GetConnLimiter) error - // Close closes the connection manager and stops background processes. Close() error } @@ -93,9 +89,3 @@ type TagInfo struct { // Conns maps connection ids (such as remote multiaddr) to their creation time. Conns map[string]time.Time } - -// GetConnLimiter provides access to a component's total connection limit. -type GetConnLimiter interface { - // GetConnLimit returns the total connection limit of the implementing component. - GetConnLimit() int -} diff --git a/vendor/github.com/libp2p/go-libp2p/core/connmgr/null.go b/vendor/github.com/libp2p/go-libp2p/core/connmgr/null.go index 735411712..25743f4ec 100644 --- a/vendor/github.com/libp2p/go-libp2p/core/connmgr/null.go +++ b/vendor/github.com/libp2p/go-libp2p/core/connmgr/null.go @@ -21,5 +21,4 @@ func (NullConnMgr) Notifee() network.Notifiee { return network.Gl func (NullConnMgr) Protect(peer.ID, string) {} func (NullConnMgr) Unprotect(peer.ID, string) bool { return false } func (NullConnMgr) IsProtected(peer.ID, string) bool { return false } -func (NullConnMgr) CheckLimit(l GetConnLimiter) error { return nil } func (NullConnMgr) Close() error { return nil } diff --git a/vendor/github.com/libp2p/go-libp2p/core/crypto/ecdsa.go b/vendor/github.com/libp2p/go-libp2p/core/crypto/ecdsa.go index 8e392c9ed..c936d502a 100644 --- a/vendor/github.com/libp2p/go-libp2p/core/crypto/ecdsa.go +++ b/vendor/github.com/libp2p/go-libp2p/core/crypto/ecdsa.go @@ -12,7 +12,8 @@ import ( pb "github.com/libp2p/go-libp2p/core/crypto/pb" "github.com/libp2p/go-libp2p/core/internal/catch" - "github.com/libp2p/go-libp2p/internal/sha256" + + "github.com/minio/sha256-simd" ) // ECDSAPrivateKey is an implementation of an ECDSA private key diff --git a/vendor/github.com/libp2p/go-libp2p/core/crypto/rsa_go.go b/vendor/github.com/libp2p/go-libp2p/core/crypto/rsa_go.go index c955cf8e0..8981ba6aa 100644 --- a/vendor/github.com/libp2p/go-libp2p/core/crypto/rsa_go.go +++ b/vendor/github.com/libp2p/go-libp2p/core/crypto/rsa_go.go @@ -10,7 +10,8 @@ import ( pb "github.com/libp2p/go-libp2p/core/crypto/pb" "github.com/libp2p/go-libp2p/core/internal/catch" - "github.com/libp2p/go-libp2p/internal/sha256" + + "github.com/minio/sha256-simd" ) // RsaPrivateKey is a rsa private key diff --git a/vendor/github.com/libp2p/go-libp2p/core/crypto/secp256k1.go b/vendor/github.com/libp2p/go-libp2p/core/crypto/secp256k1.go index bcd68ac6d..27544a59f 100644 --- a/vendor/github.com/libp2p/go-libp2p/core/crypto/secp256k1.go +++ b/vendor/github.com/libp2p/go-libp2p/core/crypto/secp256k1.go @@ -9,7 +9,7 @@ import ( "github.com/decred/dcrd/dcrec/secp256k1/v4" "github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa" - "github.com/libp2p/go-libp2p/internal/sha256" + "github.com/minio/sha256-simd" ) // Secp256k1PrivateKey is a Secp256k1 private key diff --git a/vendor/github.com/libp2p/go-libp2p/core/peer/addrinfo.go b/vendor/github.com/libp2p/go-libp2p/core/peer/addrinfo.go index de7dd4d98..fba4cfd0e 100644 --- a/vendor/github.com/libp2p/go-libp2p/core/peer/addrinfo.go +++ b/vendor/github.com/libp2p/go-libp2p/core/peer/addrinfo.go @@ -86,7 +86,7 @@ func AddrInfoFromP2pAddr(m ma.Multiaddr) (*AddrInfo, error) { // AddrInfoToP2pAddrs converts an AddrInfo to a list of Multiaddrs. func AddrInfoToP2pAddrs(pi *AddrInfo) ([]ma.Multiaddr, error) { - p2ppart, err := ma.NewComponent("p2p", pi.ID.String()) + p2ppart, err := ma.NewComponent("p2p", Encode(pi.ID)) if err != nil { return nil, err } @@ -102,7 +102,7 @@ func AddrInfoToP2pAddrs(pi *AddrInfo) ([]ma.Multiaddr, error) { func (pi *AddrInfo) Loggable() map[string]interface{} { return map[string]interface{}{ - "peerID": pi.ID.String(), + "peerID": pi.ID.Pretty(), "addrs": pi.Addrs, } } diff --git a/vendor/github.com/libp2p/go-libp2p/core/peer/peer.go b/vendor/github.com/libp2p/go-libp2p/core/peer/peer.go index b77fb684e..f7f649f24 100644 --- a/vendor/github.com/libp2p/go-libp2p/core/peer/peer.go +++ b/vendor/github.com/libp2p/go-libp2p/core/peer/peer.go @@ -41,6 +41,12 @@ const maxInlineKeyLength = 42 // hash output as a multihash. See IDFromPublicKey for details. type ID string +// Pretty returns a base58-encoded string representation of the ID. +// Deprecated: use String() instead. +func (id ID) Pretty() string { + return id.String() +} + // Loggable returns a pretty peer ID string in loggable JSON format. func (id ID) Loggable() map[string]interface{} { return map[string]interface{}{ @@ -139,6 +145,16 @@ func Decode(s string) (ID, error) { return FromCid(c) } +// Encode encodes a peer ID as a string. +// +// At the moment, it base58 encodes the peer ID but, in the future, it will +// switch to encoding it as a CID by default. +// +// Deprecated: use id.String instead. +func Encode(id ID) string { + return id.String() +} + // FromCid converts a CID to a peer ID, if possible. func FromCid(c cid.Cid) (ID, error) { code := mc.Code(c.Type()) diff --git a/vendor/github.com/libp2p/go-libp2p/core/peer/peer_serde.go b/vendor/github.com/libp2p/go-libp2p/core/peer/peer_serde.go index 3e2f71793..5fd1cd50c 100644 --- a/vendor/github.com/libp2p/go-libp2p/core/peer/peer_serde.go +++ b/vendor/github.com/libp2p/go-libp2p/core/peer/peer_serde.go @@ -45,7 +45,7 @@ func (id ID) Size() int { } func (id ID) MarshalJSON() ([]byte, error) { - return json.Marshal(id.String()) + return json.Marshal(Encode(id)) } func (id *ID) UnmarshalJSON(data []byte) (err error) { @@ -59,7 +59,7 @@ func (id *ID) UnmarshalJSON(data []byte) (err error) { // MarshalText returns the text encoding of the ID. func (id ID) MarshalText() ([]byte, error) { - return []byte(id.String()), nil + return []byte(Encode(id)), nil } // UnmarshalText restores the ID from its text encoding. diff --git a/vendor/github.com/libp2p/go-libp2p/core/sec/security.go b/vendor/github.com/libp2p/go-libp2p/core/sec/security.go index d9e918329..83059d94c 100644 --- a/vendor/github.com/libp2p/go-libp2p/core/sec/security.go +++ b/vendor/github.com/libp2p/go-libp2p/core/sec/security.go @@ -3,7 +3,6 @@ package sec import ( "context" - "fmt" "net" "github.com/libp2p/go-libp2p/core/network" @@ -30,14 +29,3 @@ type SecureTransport interface { // ID is the protocol ID of the security protocol. ID() protocol.ID } - -type ErrPeerIDMismatch struct { - Expected peer.ID - Actual peer.ID -} - -func (e ErrPeerIDMismatch) Error() string { - return fmt.Sprintf("peer id mismatch: expected %s, but remote key matches %s", e.Expected, e.Actual) -} - -var _ error = (*ErrPeerIDMismatch)(nil) diff --git a/vendor/github.com/libp2p/go-libp2p/core/transport/transport.go b/vendor/github.com/libp2p/go-libp2p/core/transport/transport.go index d56a3cff0..89a9608d4 100644 --- a/vendor/github.com/libp2p/go-libp2p/core/transport/transport.go +++ b/vendor/github.com/libp2p/go-libp2p/core/transport/transport.go @@ -5,7 +5,6 @@ package transport import ( "context" "errors" - "fmt" "net" "github.com/libp2p/go-libp2p/core/network" @@ -125,47 +124,3 @@ type Upgrader interface { // Upgrade upgrades the multiaddr/net connection into a full libp2p-transport connection. Upgrade(ctx context.Context, t Transport, maconn manet.Conn, dir network.Direction, p peer.ID, scope network.ConnManagementScope) (CapableConn, error) } - -// DialUpdater provides updates on in progress dials. -type DialUpdater interface { - // DialWithUpdates dials a remote peer and provides updates on the passed channel. - DialWithUpdates(context.Context, ma.Multiaddr, peer.ID, chan<- DialUpdate) (CapableConn, error) -} - -// DialUpdateKind indicates the type of DialUpdate event. -type DialUpdateKind int - -const ( - // UpdateKindDialFailed indicates dial failed. - UpdateKindDialFailed DialUpdateKind = iota - // UpdateKindDialSuccessful indicates dial succeeded. - UpdateKindDialSuccessful - // UpdateKindHandshakeProgressed indicates successful completion of the TCP 3-way - // handshake - UpdateKindHandshakeProgressed -) - -func (k DialUpdateKind) String() string { - switch k { - case UpdateKindDialFailed: - return "DialFailed" - case UpdateKindDialSuccessful: - return "DialSuccessful" - case UpdateKindHandshakeProgressed: - return "UpdateKindHandshakeProgressed" - default: - return fmt.Sprintf("DialUpdateKind", k) - } -} - -// DialUpdate is used by DialUpdater to provide dial updates. -type DialUpdate struct { - // Kind is the kind of update event. - Kind DialUpdateKind - // Addr is the peer's address. - Addr ma.Multiaddr - // Conn is the resulting connection on success. - Conn CapableConn - // Err is the reason for dial failure. - Err error -} diff --git a/vendor/github.com/libp2p/go-libp2p/defaults.go b/vendor/github.com/libp2p/go-libp2p/defaults.go index d11302690..c0ed6698a 100644 --- a/vendor/github.com/libp2p/go-libp2p/defaults.go +++ b/vendor/github.com/libp2p/go-libp2p/defaults.go @@ -79,9 +79,11 @@ var RandomIdentity = func(cfg *Config) error { var DefaultListenAddrs = func(cfg *Config) error { addrs := []string{ "/ip4/0.0.0.0/tcp/0", + "/ip4/0.0.0.0/udp/0/quic", "/ip4/0.0.0.0/udp/0/quic-v1", "/ip4/0.0.0.0/udp/0/quic-v1/webtransport", "/ip6/::/tcp/0", + "/ip6/::/udp/0/quic", "/ip6/::/udp/0/quic-v1", "/ip6/::/udp/0/quic-v1/webtransport", } diff --git a/vendor/github.com/libp2p/go-libp2p/internal/sha256/post_go1_21.go b/vendor/github.com/libp2p/go-libp2p/internal/sha256/post_go1_21.go deleted file mode 100644 index 98c14b609..000000000 --- a/vendor/github.com/libp2p/go-libp2p/internal/sha256/post_go1_21.go +++ /dev/null @@ -1,23 +0,0 @@ -//go:build go1.21 - -// This package use build tags to select between github.com/minio/sha256-simd -// for go1.20 and bellow and crypto/sha256 for go1.21 and above. -// This is used because a fast SHANI implementation of sha256 is only avaiable -// in the std for go1.21 and above. See https://go.dev/issue/50543. -// TODO: Once go1.22 releases remove this package and replace all uses -// with crypto/sha256 because the two supported version of go will have the fast -// implementation. -package sha256 - -import ( - "crypto/sha256" - "hash" -) - -func Sum256(b []byte) [sha256.Size]byte { - return sha256.Sum256(b) -} - -func New() hash.Hash { - return sha256.New() -} diff --git a/vendor/github.com/libp2p/go-libp2p/internal/sha256/pre_go1_21.go b/vendor/github.com/libp2p/go-libp2p/internal/sha256/pre_go1_21.go deleted file mode 100644 index db0573333..000000000 --- a/vendor/github.com/libp2p/go-libp2p/internal/sha256/pre_go1_21.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build !go1.21 - -// This package use build tags to select between github.com/minio/sha256-simd -// for go1.20 and bellow and crypto/sha256 for go1.21 and above. -// This is used because a fast SHANI implementation of sha256 is only avaiable -// in the std for go1.21 and above. See https://go.dev/issue/50543. -// TODO: Once go1.22 releases remove this package and replace all uses -// with crypto/sha256 because the two supported version of go will have the fast -// implementation. -package sha256 - -import ( - "hash" - - "github.com/minio/sha256-simd" -) - -func Sum256(b []byte) [sha256.Size]byte { - return sha256.Sum256(b) -} - -func New() hash.Hash { - return sha256.New() -} diff --git a/vendor/github.com/libp2p/go-libp2p/options.go b/vendor/github.com/libp2p/go-libp2p/options.go index 1a1e9d398..beb4930f7 100644 --- a/vendor/github.com/libp2p/go-libp2p/options.go +++ b/vendor/github.com/libp2p/go-libp2p/options.go @@ -579,7 +579,6 @@ func PrometheusRegisterer(reg prometheus.Registerer) Option { // DialRanker configures libp2p to use d as the dial ranker. To enable smart // dialing use `swarm.DefaultDialRanker`. use `swarm.NoDelayDialRanker` to // disable smart dialing. -// // Deprecated: use SwarmOpts(swarm.WithDialRanker(d)) instead func DialRanker(d network.DialRanker) Option { return func(cfg *Config) error { diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/host/autonat/svc.go b/vendor/github.com/libp2p/go-libp2p/p2p/host/autonat/svc.go index cf1dff8e7..98b421c9b 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/host/autonat/svc.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/host/autonat/svc.go @@ -68,7 +68,7 @@ func (as *autoNATService) handleStream(s network.Stream) { defer s.Close() pid := s.Conn().RemotePeer() - log.Debugf("New stream from %s", pid) + log.Debugf("New stream from %s", pid.Pretty()) r := pbio.NewDelimitedReader(s, maxMsgSize) w := pbio.NewDelimitedWriter(s) @@ -78,14 +78,14 @@ func (as *autoNATService) handleStream(s network.Stream) { err := r.ReadMsg(&req) if err != nil { - log.Debugf("Error reading message from %s: %s", pid, err.Error()) + log.Debugf("Error reading message from %s: %s", pid.Pretty(), err.Error()) s.Reset() return } t := req.GetType() if t != pb.Message_DIAL { - log.Debugf("Unexpected message from %s: %s (%d)", pid, t.String(), t) + log.Debugf("Unexpected message from %s: %s (%d)", pid.Pretty(), t.String(), t) s.Reset() return } @@ -96,7 +96,7 @@ func (as *autoNATService) handleStream(s network.Stream) { err = w.WriteMsg(&res) if err != nil { - log.Debugf("Error writing response to %s: %s", pid, err.Error()) + log.Debugf("Error writing response to %s: %s", pid.Pretty(), err.Error()) s.Reset() return } @@ -234,7 +234,7 @@ func (as *autoNATService) doDial(pi peer.AddrInfo) *pb.Message_DialResponse { conn, err := as.config.dialer.DialPeer(ctx, pi.ID) if err != nil { - log.Debugf("error dialing %s: %s", pi.ID, err.Error()) + log.Debugf("error dialing %s: %s", pi.ID.Pretty(), err.Error()) // wait for the context to timeout to avoid leaking timing information // this renders the service ineffective as a port scanner <-ctx.Done() diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/host/autorelay/relay_finder.go b/vendor/github.com/libp2p/go-libp2p/p2p/host/autorelay/relay_finder.go index ef79950b7..3133b7a51 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/host/autorelay/relay_finder.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/host/autorelay/relay_finder.go @@ -736,7 +736,7 @@ func (rf *relayFinder) relayAddrs(addrs []ma.Multiaddr) []ma.Multiaddr { for p := range rf.relays { addrs := cleanupAddressSet(rf.host.Peerstore().Addrs(p)) relayAddrCnt += len(addrs) - circuit := ma.StringCast(fmt.Sprintf("/p2p/%s/p2p-circuit", p)) + circuit := ma.StringCast(fmt.Sprintf("/p2p/%s/p2p-circuit", p.Pretty())) for _, addr := range addrs { pub := addr.Encapsulate(circuit) raddrs = append(raddrs, pub) diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/host/basic/basic_host.go b/vendor/github.com/libp2p/go-libp2p/p2p/host/basic/basic_host.go index 6c3ba53e5..89f5d28db 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/host/basic/basic_host.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/host/basic/basic_host.go @@ -437,7 +437,7 @@ func (h *BasicHost) newStreamHandler(s network.Stream) { log.Debugf("negotiated: %s (took %s)", protoID, took) - handle(protoID, s) + go handle(protoID, s) } // SignalAddressChange signals to the host that it needs to determine whether our listen addresses have recently @@ -629,6 +629,9 @@ func (h *BasicHost) RemoveStreamHandler(pid protocol.ID) { // to create one. If ProtocolID is "", writes no header. // (Thread-safe) func (h *BasicHost) NewStream(ctx context.Context, p peer.ID, pids ...protocol.ID) (network.Stream, error) { + // Ensure we have a connection, with peer addresses resolved by the routing system (#207) + // It is not sufficient to let the underlying host connect, it will most likely not have + // any addresses for the peer without any prior connections. // If the caller wants to prevent the host from dialing, it should use the NoDial option. if nodial, _ := network.GetNoDial(ctx); !nodial { err := h.Connect(ctx, peer.AddrInfo{ID: p}) @@ -666,9 +669,7 @@ func (h *BasicHost) NewStream(ctx context.Context, p peer.ID, pids ...protocol.I } if pref != "" { - if err := s.SetProtocol(pref); err != nil { - return nil, err - } + s.SetProtocol(pref) lzcon := msmux.NewMSSelect(s, pref) return &streamWrapper{ Stream: s, @@ -794,11 +795,10 @@ func (h *BasicHost) Addrs() []ma.Multiaddr { continue } addrWithCerthash, added := tpt.AddCertHashes(addr) + addrs[i] = addrWithCerthash if !added { log.Debug("Couldn't add certhashes to webtransport multiaddr because we aren't listening on webtransport") - continue } - addrs[i] = addrWithCerthash } } return addrs @@ -945,17 +945,17 @@ func inferWebtransportAddrsFromQuic(in []ma.Multiaddr) []ma.Multiaddr { // Remove certhashes addr, _ = ma.SplitLast(addr) } - webtransportAddrs[string(addr.Bytes())] = struct{}{} + webtransportAddrs[addr.String()] = struct{}{} // Remove webtransport component, now it's a multiaddr that ends in /quic-v1 addr, _ = ma.SplitLast(addr) } if _, lastComponent := ma.SplitLast(addr); lastComponent.Protocol().Code == ma.P_QUIC_V1 { - bytes := addr.Bytes() - if _, ok := quicOrWebtransportAddrs[string(bytes)]; ok { + addrStr := addr.String() + if _, ok := quicOrWebtransportAddrs[addrStr]; ok { foundSameListeningAddr = true } else { - quicOrWebtransportAddrs[string(bytes)] = struct{}{} + quicOrWebtransportAddrs[addrStr] = struct{}{} } } } @@ -977,7 +977,7 @@ func inferWebtransportAddrsFromQuic(in []ma.Multiaddr) []ma.Multiaddr { if _, lastComponent := ma.SplitLast(addr); lastComponent.Protocol().Code == ma.P_QUIC_V1 { // Convert quic to webtransport addr = addr.Encapsulate(wtComponent) - if _, ok := webtransportAddrs[string(addr.Bytes())]; ok { + if _, ok := webtransportAddrs[addr.String()]; ok { // We already have this address continue } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/host/basic/mocks.go b/vendor/github.com/libp2p/go-libp2p/p2p/host/basic/mocks.go index a29a0c5ef..3ad4d4e90 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/host/basic/mocks.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/host/basic/mocks.go @@ -2,5 +2,5 @@ package basichost -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package basichost -destination mock_nat_test.go github.com/libp2p/go-libp2p/p2p/host/basic NAT" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package basichost -destination mock_nat_test.go github.com/libp2p/go-libp2p/p2p/host/basic NAT" type NAT nat diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/host/blank/blank.go b/vendor/github.com/libp2p/go-libp2p/p2p/host/blank/blank.go index 0fdded30f..24304498b 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/host/blank/blank.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/host/blank/blank.go @@ -210,7 +210,7 @@ func (bh *BlankHost) newStreamHandler(s network.Stream) { s.SetProtocol(protoID) - handle(protoID, s) + go handle(protoID, s) } // TODO: i'm not sure this really needs to be here diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/host/resource-manager/README.md b/vendor/github.com/libp2p/go-libp2p/p2p/host/resource-manager/README.md index 72eb192ad..9371832c9 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/host/resource-manager/README.md +++ b/vendor/github.com/libp2p/go-libp2p/p2p/host/resource-manager/README.md @@ -541,7 +541,7 @@ works best. ## Examples -Here we consider some concrete examples that can elucidate the abstract +Here we consider some concrete examples that can ellucidate the abstract design as described so far. ### Stream Lifetime @@ -578,7 +578,7 @@ More specifically the following constraints apply: - the peer scope, where the limits for the peer at the other end of the stream apply. - the service scope, where the limits of the specific service owning the stream apply. -- the protocol scope, where the limits of the specific protocol for the stream apply. +- the protcol scope, where the limits of the specific protocol for the stream apply. The resource transfer that happens in the `SetProtocol` and `SetService` diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/host/resource-manager/extapi.go b/vendor/github.com/libp2p/go-libp2p/p2p/host/resource-manager/extapi.go index b3214f814..03edcd79e 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/host/resource-manager/extapi.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/host/resource-manager/extapi.go @@ -145,7 +145,3 @@ func (r *resourceManager) Stat() (result ResourceManagerStat) { return result } - -func (r *resourceManager) GetConnLimit() int { - return r.limits.GetConnLimits().GetConnTotalLimit() -} diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/metricshelper/conn.go b/vendor/github.com/libp2p/go-libp2p/p2p/metricshelper/conn.go index b07016ce8..ef367ac9b 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/metricshelper/conn.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/metricshelper/conn.go @@ -2,7 +2,7 @@ package metricshelper import ma "github.com/multiformats/go-multiaddr" -var transports = [...]int{ma.P_CIRCUIT, ma.P_WEBRTC, ma.P_WEBRTC_DIRECT, ma.P_WEBTRANSPORT, ma.P_QUIC, ma.P_QUIC_V1, ma.P_WSS, ma.P_WS, ma.P_TCP} +var transports = [...]int{ma.P_CIRCUIT, ma.P_WEBRTC, ma.P_WEBTRANSPORT, ma.P_QUIC, ma.P_QUIC_V1, ma.P_WSS, ma.P_WS, ma.P_TCP} func GetTransport(a ma.Multiaddr) string { for _, t := range transports { diff --git a/vendor/github.com/libp2p/go-libp2p-mplex/conn.go b/vendor/github.com/libp2p/go-libp2p/p2p/muxer/mplex/conn.go similarity index 100% rename from vendor/github.com/libp2p/go-libp2p-mplex/conn.go rename to vendor/github.com/libp2p/go-libp2p/p2p/muxer/mplex/conn.go diff --git a/vendor/github.com/libp2p/go-libp2p-mplex/stream.go b/vendor/github.com/libp2p/go-libp2p/p2p/muxer/mplex/stream.go similarity index 100% rename from vendor/github.com/libp2p/go-libp2p-mplex/stream.go rename to vendor/github.com/libp2p/go-libp2p/p2p/muxer/mplex/stream.go diff --git a/vendor/github.com/libp2p/go-libp2p-mplex/transport.go b/vendor/github.com/libp2p/go-libp2p/p2p/muxer/mplex/transport.go similarity index 81% rename from vendor/github.com/libp2p/go-libp2p-mplex/transport.go rename to vendor/github.com/libp2p/go-libp2p/p2p/muxer/mplex/transport.go index bcfadfd7e..10d54d153 100644 --- a/vendor/github.com/libp2p/go-libp2p-mplex/transport.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/muxer/mplex/transport.go @@ -1,5 +1,3 @@ -// DEPRECATED: mplex has been deprecated. Users should prefer Yamux over mplex. see https://github.com/libp2p/specs/issues/553 -// for details package mplex import ( diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/connmgr/connmgr.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/connmgr/connmgr.go index 6caa3dc1a..b42a122fa 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/connmgr/connmgr.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/connmgr/connmgr.go @@ -2,7 +2,6 @@ package connmgr import ( "context" - "fmt" "sort" "sync" "sync/atomic" @@ -240,17 +239,6 @@ func (cm *BasicConnMgr) IsProtected(id peer.ID, tag string) (protected bool) { return protected } -func (cm *BasicConnMgr) CheckLimit(systemLimit connmgr.GetConnLimiter) error { - if cm.cfg.highWater > systemLimit.GetConnLimit() { - return fmt.Errorf( - "conn manager high watermark limit: %d, exceeds the system connection limit of: %d", - cm.cfg.highWater, - systemLimit.GetConnLimit(), - ) - } - return nil -} - // peerInfo stores metadata for a given peer. type peerInfo struct { id peer.ID diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/connmgr/decay.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/connmgr/decay.go index 76f1c6872..bdac0bef7 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/connmgr/decay.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/connmgr/decay.go @@ -320,7 +320,7 @@ func (t *decayingTag) Bump(p peer.ID, delta int) error { default: return fmt.Errorf( "unable to bump decaying tag for peer %s, tag %s, delta %d; queue full (len=%d)", - p, t.name, delta, len(t.trkr.bumpTagCh)) + p.Pretty(), t.name, delta, len(t.trkr.bumpTagCh)) } } @@ -337,7 +337,7 @@ func (t *decayingTag) Remove(p peer.ID) error { default: return fmt.Errorf( "unable to remove decaying tag for peer %s, tag %s; queue full (len=%d)", - p, t.name, len(t.trkr.removeTagCh)) + p.Pretty(), t.name, len(t.trkr.removeTagCh)) } } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/addrs.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/addrs.go new file mode 100644 index 000000000..392900e06 --- /dev/null +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/addrs.go @@ -0,0 +1,39 @@ +package swarm + +import ( + ma "github.com/multiformats/go-multiaddr" + manet "github.com/multiformats/go-multiaddr/net" +) + +// http://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml +var lowTimeoutFilters = ma.NewFilters() + +func init() { + for _, p := range []string{ + "/ip4/10.0.0.0/ipcidr/8", + "/ip4/100.64.0.0/ipcidr/10", + "/ip4/169.254.0.0/ipcidr/16", + "/ip4/172.16.0.0/ipcidr/12", + "/ip4/192.0.0.0/ipcidr/24", + "/ip4/192.0.0.0/ipcidr/29", + "/ip4/192.0.0.8/ipcidr/32", + "/ip4/192.0.0.170/ipcidr/32", + "/ip4/192.0.0.171/ipcidr/32", + "/ip4/192.0.2.0/ipcidr/24", + "/ip4/192.168.0.0/ipcidr/16", + "/ip4/198.18.0.0/ipcidr/15", + "/ip4/198.51.100.0/ipcidr/24", + "/ip4/203.0.113.0/ipcidr/24", + "/ip4/240.0.0.0/ipcidr/4", + } { + f, err := ma.NewMultiaddr(p) + if err != nil { + panic("error in lowTimeoutFilters init: " + err.Error()) + } + ipnet, err := manet.MultiaddrToIPNet(f) + if err != nil { + panic("error in lowTimeoutFilters init: " + err.Error()) + } + lowTimeoutFilters.AddFilter(*ipnet, ma.ActionDeny) + } +} diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/black_hole_detector.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/black_hole_detector.go index dd7849eea..078b1126c 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/black_hole_detector.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/black_hole_detector.go @@ -178,7 +178,7 @@ type blackHoleDetector struct { } // FilterAddrs filters the peer's addresses removing black holed addresses -func (d *blackHoleDetector) FilterAddrs(addrs []ma.Multiaddr) (valid []ma.Multiaddr, blackHoled []ma.Multiaddr) { +func (d *blackHoleDetector) FilterAddrs(addrs []ma.Multiaddr) []ma.Multiaddr { hasUDP, hasIPv6 := false, false for _, a := range addrs { if !manet.IsPublicAddr(a) { @@ -202,7 +202,6 @@ func (d *blackHoleDetector) FilterAddrs(addrs []ma.Multiaddr) (valid []ma.Multia ipv6Res = d.ipv6.HandleRequest() } - blackHoled = make([]ma.Multiaddr, 0, len(addrs)) return ma.FilterAddrs( addrs, func(a ma.Multiaddr) bool { @@ -219,16 +218,14 @@ func (d *blackHoleDetector) FilterAddrs(addrs []ma.Multiaddr) (valid []ma.Multia } if udpRes == blackHoleResultBlocked && isProtocolAddr(a, ma.P_UDP) { - blackHoled = append(blackHoled, a) return false } if ipv6Res == blackHoleResultBlocked && isProtocolAddr(a, ma.P_IP6) { - blackHoled = append(blackHoled, a) return false } return true }, - ), blackHoled + ) } // RecordResult updates the state of the relevant `blackHoleFilter`s for addr diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_error.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_error.go index 4de682204..711ee0607 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_error.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_error.go @@ -30,7 +30,10 @@ func (e *DialError) recordErr(addr ma.Multiaddr, err error) { e.Skipped++ return } - e.DialErrors = append(e.DialErrors, TransportError{Address: addr, Cause: err}) + e.DialErrors = append(e.DialErrors, TransportError{ + Address: addr, + Cause: err, + }) } func (e *DialError) Error() string { @@ -48,19 +51,9 @@ func (e *DialError) Error() string { return builder.String() } -func (e *DialError) Unwrap() []error { - if e == nil { - return nil - } - - errs := make([]error, len(e.DialErrors)+1) - if e.Cause != nil { - errs = append(errs, e.Cause) - } - for i := 0; i < len(e.DialErrors); i++ { - errs = append(errs, &e.DialErrors[i]) - } - return errs +// Unwrap implements https://godoc.org/golang.org/x/xerrors#Wrapper. +func (e *DialError) Unwrap() error { + return e.Cause } var _ error = (*DialError)(nil) @@ -75,8 +68,4 @@ func (e *TransportError) Error() string { return fmt.Sprintf("failed to dial %s: %s", e.Address, e.Cause) } -func (e *TransportError) Unwrap() error { - return e.Cause -} - var _ error = (*TransportError)(nil) diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_ranker.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_ranker.go index 7e58876b9..3725884e2 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_ranker.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_ranker.go @@ -58,19 +58,8 @@ func NoDelayDialRanker(addrs []ma.Multiaddr) []network.AddrDelay { // 3. If a QUIC or WebTransport address is present, TCP addresses dials are delayed relative to the last QUIC dial: // We prefer to end up with a QUIC connection. For public addresses, the delay introduced is 250ms (PublicTCPDelay), // and for private addresses 30ms (PrivateTCPDelay). -// 4. For the TCP addresses we follow a strategy similar to QUIC with an optimisation for handling the long TCP -// handshake time described in 6. If both IPv6 TCP and IPv4 TCP addresses are present, we do a Happy Eyeballs -// style ranking. First dial the IPv6 TCP address with the lowest port. After this, dial the IPv4 TCP address -// with the lowest port delayed by 250ms (PublicTCPDelay) for public addresses, and 30ms (PrivateTCPDelay) -// for local addresses. After this we dial all the rest of the addresses delayed by 250ms (PublicTCPDelay) for -// public addresses, and 30ms (PrivateTCPDelay) for local addresses. -// 5. If only one of TCP IPv6 or TCP IPv4 addresses are present, dial the TCP address with the lowest port -// first. After this we dial the rest of the TCP addresses delayed by 250ms (PublicTCPDelay) for public -// addresses, and 30ms (PrivateTCPDelay) for local addresses. -// 6. When a TCP socket is connected and awaiting security and muxer upgrade, we stop new dials for 2*PrivateTCPDelay -// to allow for the upgrade to complete. // -// We dial lowest ports first as they are more likely to be the listen port. +// We dial lowest ports first for QUIC addresses as they are more likely to be the listen port. func DefaultDialRanker(addrs []ma.Multiaddr) []network.AddrDelay { relay, addrs := filterAddrs(addrs, isRelayAddr) pvt, addrs := filterAddrs(addrs, manet.IsPrivateAddr) @@ -99,57 +88,22 @@ func DefaultDialRanker(addrs []ma.Multiaddr) []network.AddrDelay { // addresses relative to direct addresses. func getAddrDelay(addrs []ma.Multiaddr, tcpDelay time.Duration, quicDelay time.Duration, offset time.Duration) []network.AddrDelay { - if len(addrs) == 0 { - return nil - } sort.Slice(addrs, func(i, j int) bool { return score(addrs[i]) < score(addrs[j]) }) - // addrs is now sorted by (Transport, IPVersion). Reorder addrs for happy eyeballs dialing. - // For QUIC and TCP, if we have both IPv6 and IPv4 addresses, move the - // highest priority IPv4 address to the second position. - happyEyeballsQUIC := false - happyEyeballsTCP := false - // tcpStartIdx is the index of the first TCP Address - var tcpStartIdx int - { - i := 0 - // If the first QUIC address is IPv6 move the first QUIC IPv4 address to second position + // If the first address is (QUIC, IPv6), make the second address (QUIC, IPv4). + happyEyeballs := false + if len(addrs) > 0 { if isQUICAddr(addrs[0]) && isProtocolAddr(addrs[0], ma.P_IP6) { - for j := 1; j < len(addrs); j++ { - if isQUICAddr(addrs[j]) && isProtocolAddr(addrs[j], ma.P_IP4) { - // The first IPv4 address is at position j - // Move the jth element at position 1 shifting the affected elements - if j > 1 { - a := addrs[j] - copy(addrs[2:], addrs[1:j]) + for i := 1; i < len(addrs); i++ { + if isQUICAddr(addrs[i]) && isProtocolAddr(addrs[i], ma.P_IP4) { + // make IPv4 address the second element + if i > 1 { + a := addrs[i] + copy(addrs[2:], addrs[1:i]) addrs[1] = a } - happyEyeballsQUIC = true - i = j + 1 - break - } - } - } - - for tcpStartIdx = i; tcpStartIdx < len(addrs); tcpStartIdx++ { - if isProtocolAddr(addrs[tcpStartIdx], ma.P_TCP) { - break - } - } - - // If the first TCP address is IPv6 move the first TCP IPv4 address to second position - if tcpStartIdx < len(addrs) && isProtocolAddr(addrs[tcpStartIdx], ma.P_IP6) { - for j := tcpStartIdx + 1; j < len(addrs); j++ { - if isProtocolAddr(addrs[j], ma.P_TCP) && isProtocolAddr(addrs[j], ma.P_IP4) { - // First TCP IPv4 address is at position j, move it to position tcpStartIdx+1 - // which is the second priority TCP address - if j > tcpStartIdx+1 { - a := addrs[j] - copy(addrs[tcpStartIdx+2:], addrs[tcpStartIdx+1:j]) - addrs[tcpStartIdx+1] = a - } - happyEyeballsTCP = true + happyEyeballs = true break } } @@ -157,42 +111,25 @@ func getAddrDelay(addrs []ma.Multiaddr, tcpDelay time.Duration, quicDelay time.D } res := make([]network.AddrDelay, 0, len(addrs)) - var tcpFirstDialDelay time.Duration + + var totalTCPDelay time.Duration for i, addr := range addrs { var delay time.Duration switch { case isQUICAddr(addr): - // We dial an IPv6 address, then after quicDelay an IPv4 - // address, then after a further quicDelay we dial the rest of the addresses. + // For QUIC addresses we dial an IPv6 address, then after quicDelay an IPv4 + // address, then after quicDelay we dial rest of the addresses. if i == 1 { delay = quicDelay } - if i > 1 { - // If we have happy eyeballs for QUIC, dials after the second position - // will be delayed by 2*quicDelay - if happyEyeballsQUIC { - delay = 2 * quicDelay - } else { - delay = quicDelay - } + if i > 1 && happyEyeballs { + delay = 2 * quicDelay + } else if i > 1 { + delay = quicDelay } - tcpFirstDialDelay = delay + tcpDelay + totalTCPDelay = delay + tcpDelay case isProtocolAddr(addr, ma.P_TCP): - // We dial an IPv6 address, then after tcpDelay an IPv4 - // address, then after a further tcpDelay we dial the rest of the addresses. - if i == tcpStartIdx+1 { - delay = tcpDelay - } - if i > tcpStartIdx+1 { - // If we have happy eyeballs for TCP, dials after the second position - // will be delayed by 2*tcpDelay - if happyEyeballsTCP { - delay = 2 * tcpDelay - } else { - delay = tcpDelay - } - } - delay += tcpFirstDialDelay + delay = totalTCPDelay } res = append(res, network.AddrDelay{Addr: addr, Delay: offset + delay}) } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_sync.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_sync.go index 3cc854728..2a8ff4317 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_sync.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_sync.go @@ -2,7 +2,6 @@ package swarm import ( "context" - "errors" "sync" "github.com/libp2p/go-libp2p/core/network" @@ -12,9 +11,6 @@ import ( // dialWorkerFunc is used by dialSync to spawn a new dial worker type dialWorkerFunc func(peer.ID, <-chan dialRequest) -// errConcurrentDialSuccessful is used to signal that a concurrent dial succeeded -var errConcurrentDialSuccessful = errors.New("concurrent dial successful") - // newDialSync constructs a new dialSync func newDialSync(worker dialWorkerFunc) *dialSync { return &dialSync{ @@ -34,12 +30,17 @@ type dialSync struct { type activeDial struct { refCnt int - ctx context.Context - cancelCause func(error) + ctx context.Context + cancel func() reqch chan dialRequest } +func (ad *activeDial) close() { + ad.cancel() + close(ad.reqch) +} + func (ad *activeDial) dial(ctx context.Context) (*Conn, error) { dialCtx := ad.ctx @@ -73,11 +74,11 @@ func (ds *dialSync) getActiveDial(p peer.ID) (*activeDial, error) { if !ok { // This code intentionally uses the background context. Otherwise, if the first call // to Dial is canceled, subsequent dial calls will also be canceled. - ctx, cancel := context.WithCancelCause(context.Background()) + ctx, cancel := context.WithCancel(context.Background()) actd = &activeDial{ - ctx: ctx, - cancelCause: cancel, - reqch: make(chan dialRequest), + ctx: ctx, + cancel: cancel, + reqch: make(chan dialRequest), } go ds.dialWorker(p, actd.reqch) ds.dials[p] = actd @@ -95,21 +96,14 @@ func (ds *dialSync) Dial(ctx context.Context, p peer.ID) (*Conn, error) { return nil, err } - conn, err := ad.dial(ctx) - - ds.mutex.Lock() - defer ds.mutex.Unlock() - - ad.refCnt-- - if ad.refCnt == 0 { - if err == nil { - ad.cancelCause(errConcurrentDialSuccessful) - } else { - ad.cancelCause(err) + defer func() { + ds.mutex.Lock() + defer ds.mutex.Unlock() + ad.refCnt-- + if ad.refCnt == 0 { + ad.close() + delete(ds.dials, p) } - close(ad.reqch) - delete(ds.dials, p) - } - - return conn, err + }() + return ad.dial(ctx) } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_worker.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_worker.go index 0cac6e4fa..0334ac863 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_worker.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/dial_worker.go @@ -8,12 +8,15 @@ import ( "github.com/libp2p/go-libp2p/core/network" "github.com/libp2p/go-libp2p/core/peer" - tpt "github.com/libp2p/go-libp2p/core/transport" ma "github.com/multiformats/go-multiaddr" - manet "github.com/multiformats/go-multiaddr/net" ) +// ///////////////////////////////////////////////////////////////////////////////// +// lo and behold, The Dialer +// TODO explain how all this works +// //////////////////////////////////////////////////////////////////////////////// + // dialRequest is structure used to request dials to the peer associated with a // worker loop type dialRequest struct { @@ -58,14 +61,15 @@ type addrDial struct { conn *Conn // err is the err on dialing the address err error + // requests is the list of pendRequests interested in this dial + // the value in the slice is the request number assigned to this request by the dialWorker + requests []int // dialed indicates whether we have triggered the dial to the address dialed bool // createdAt is the time this struct was created createdAt time.Time // dialRankingDelay is the delay in dialing this address introduced by the ranking logic dialRankingDelay time.Duration - // expectedTCPUpgradeTime is the expected time by which security upgrade will complete - expectedTCPUpgradeTime time.Time } // dialWorker synchronises concurrent dials to a peer. It ensures that we make at most one dial to a @@ -75,13 +79,17 @@ type dialWorker struct { peer peer.ID // reqch is used to send dial requests to the worker. close reqch to end the worker loop reqch <-chan dialRequest - // pendingRequests is the set of pendingRequests - pendingRequests map[*pendRequest]struct{} - // trackedDials tracks dials to the peer's addresses. An entry here is used to ensure that + // reqno is the request number used to track different dialRequests for a peer. + // Each incoming request is assigned a reqno. This reqno is used in pendingRequests and in + // addrDial objects in trackedDials to track this request + reqno int + // pendingRequests maps reqno to the pendRequest object for a dialRequest + pendingRequests map[int]*pendRequest + // trackedDials tracks dials to the peers addresses. An entry here is used to ensure that // we dial an address at most once trackedDials map[string]*addrDial // resch is used to receive response for dials to the peers addresses. - resch chan tpt.DialUpdate + resch chan dialResult connected bool // true when a connection has been successfully established @@ -98,9 +106,9 @@ func newDialWorker(s *Swarm, p peer.ID, reqch <-chan dialRequest, cl Clock) *dia s: s, peer: p, reqch: reqch, - pendingRequests: make(map[*pendRequest]struct{}), + pendingRequests: make(map[int]*pendRequest), trackedDials: make(map[string]*addrDial), - resch: make(chan tpt.DialUpdate), + resch: make(chan dialResult), cl: cl, } } @@ -120,8 +128,6 @@ func (w *dialWorker) loop() { startTime := w.cl.Now() // dialTimer is the dialTimer used to trigger dials dialTimer := w.cl.InstantTimer(startTime.Add(math.MaxInt64)) - defer dialTimer.Stop() - timerRunning := true // scheduleNextDial updates timer for triggering the next dial scheduleNextDial := func() { @@ -129,18 +135,12 @@ func (w *dialWorker) loop() { <-dialTimer.Ch() } timerRunning = false - if dq.Len() > 0 { + if dq.len() > 0 { if dialsInFlight == 0 && !w.connected { // if there are no dials in flight, trigger the next dials immediately dialTimer.Reset(startTime) } else { - resetTime := startTime.Add(dq.top().Delay) - for _, ad := range w.trackedDials { - if !ad.expectedTCPUpgradeTime.IsZero() && ad.expectedTCPUpgradeTime.After(resetTime) { - resetTime = ad.expectedTCPUpgradeTime - } - } - dialTimer.Reset(resetTime) + dialTimer.Reset(startTime.Add(dq.top().Delay)) } timerRunning = true } @@ -171,20 +171,15 @@ loop: // Enqueue the peer's addresses relevant to this request in dq and // track dials to the addresses relevant to this request. - c := w.s.bestAcceptableConnToPeer(req.ctx, w.peer) - if c != nil { - req.resch <- dialResponse{conn: c} + c, err := w.s.bestAcceptableConnToPeer(req.ctx, w.peer) + if c != nil || err != nil { + req.resch <- dialResponse{conn: c, err: err} continue loop } - addrs, addrErrs, err := w.s.addrsForDial(req.ctx, w.peer) + addrs, err := w.s.addrsForDial(req.ctx, w.peer) if err != nil { - req.resch <- dialResponse{ - err: &DialError{ - Peer: w.peer, - DialErrors: addrErrs, - Cause: err, - }} + req.resch <- dialResponse{err: err} continue loop } @@ -196,8 +191,8 @@ loop: // create the pending request object pr := &pendRequest{ req: req, + err: &DialError{Peer: w.peer}, addrs: make(map[string]struct{}, len(addrRanking)), - err: &DialError{Peer: w.peer, DialErrors: addrErrs}, } for _, adelay := range addrRanking { pr.addrs[string(adelay.Addr.Bytes())] = struct{}{} @@ -238,13 +233,14 @@ loop: if len(todial) == 0 && len(tojoin) == 0 { // all request applicable addrs have been dialed, we must have errored - pr.err.Cause = ErrAllDialsFailed req.resch <- dialResponse{err: pr.err} continue loop } - // The request has some pending or new dials - w.pendingRequests[pr] = struct{}{} + // The request has some pending or new dials. We assign this request a request number. + // This value of w.reqno is used to track this request in all the structures + w.reqno++ + w.pendingRequests[w.reqno] = pr for _, ad := range tojoin { if !ad.dialed { @@ -262,6 +258,7 @@ loop: } } // add the request to the addrDial + ad.requests = append(ad.requests, w.reqno) } if len(todial) > 0 { @@ -271,6 +268,7 @@ loop: w.trackedDials[string(a.Bytes())] = &addrDial{ addr: a, ctx: req.ctx, + requests: []int{w.reqno}, createdAt: now, } dq.Add(network.AddrDelay{Addr: a, Delay: addrDelay[string(a.Bytes())]}) @@ -315,29 +313,16 @@ loop: // Update all requests waiting on this address. On success, complete the request. // On error, record the error + dialsInFlight-- ad, ok := w.trackedDials[string(res.Addr.Bytes())] if !ok { log.Errorf("SWARM BUG: no entry for address %s in trackedDials", res.Addr) if res.Conn != nil { res.Conn.Close() } - dialsInFlight-- continue } - // TCP Connection has been established. Wait for connection upgrade on this address - // before making new dials. - if res.Kind == tpt.UpdateKindHandshakeProgressed { - // Only wait for public addresses to complete dialing since private dials - // are quick any way - if manet.IsPublicAddr(res.Addr) { - ad.expectedTCPUpgradeTime = w.cl.Now().Add(PublicTCPDelay) - } - scheduleNextDial() - continue - } - dialsInFlight-- - ad.expectedTCPUpgradeTime = time.Time{} if res.Conn != nil { // we got a connection, add it to the swarm conn, err := w.s.addConn(res.Conn, network.DirOutbound) @@ -348,14 +333,20 @@ loop: continue loop } - for pr := range w.pendingRequests { - if _, ok := pr.addrs[string(ad.addr.Bytes())]; ok { - pr.req.resch <- dialResponse{conn: conn} - delete(w.pendingRequests, pr) + // request succeeded, respond to all pending requests + for _, reqno := range ad.requests { + pr, ok := w.pendingRequests[reqno] + if !ok { + // some other dial for this request succeeded before this one + continue } + pr.req.resch <- dialResponse{conn: conn} + delete(w.pendingRequests, reqno) } ad.conn = conn + ad.requests = nil + if !w.connected { w.connected = true if w.s.metricsTracer != nil { @@ -389,27 +380,33 @@ loop: // dispatches an error to a specific addr dial func (w *dialWorker) dispatchError(ad *addrDial, err error) { ad.err = err - for pr := range w.pendingRequests { + for _, reqno := range ad.requests { + pr, ok := w.pendingRequests[reqno] + if !ok { + // some other dial for this request succeeded before this one + continue + } + // accumulate the error - if _, ok := pr.addrs[string(ad.addr.Bytes())]; ok { - pr.err.recordErr(ad.addr, err) - delete(pr.addrs, string(ad.addr.Bytes())) - if len(pr.addrs) == 0 { - // all addrs have erred, dispatch dial error - // but first do a last one check in case an acceptable connection has landed from - // a simultaneous dial that started later and added new acceptable addrs - c := w.s.bestAcceptableConnToPeer(pr.req.ctx, w.peer) - if c != nil { - pr.req.resch <- dialResponse{conn: c} - } else { - pr.err.Cause = ErrAllDialsFailed - pr.req.resch <- dialResponse{err: pr.err} - } - delete(w.pendingRequests, pr) + pr.err.recordErr(ad.addr, err) + + delete(pr.addrs, string(ad.addr.Bytes())) + if len(pr.addrs) == 0 { + // all addrs have erred, dispatch dial error + // but first do a last one check in case an acceptable connection has landed from + // a simultaneous dial that started later and added new acceptable addrs + c, _ := w.s.bestAcceptableConnToPeer(pr.req.ctx, w.peer) + if c != nil { + pr.req.resch <- dialResponse{conn: c} + } else { + pr.req.resch <- dialResponse{err: pr.err} } + delete(w.pendingRequests, reqno) } } + ad.requests = nil + // if it was a backoff, clear the address dial so that it doesn't inhibit new dial requests. // this is necessary to support active listen scenarios, where a new dial comes in while // another dial is in progress, and needs to do a direct connection without inhibitions from @@ -442,7 +439,7 @@ func newDialQueue() *dialQueue { // Add adds adelay to the queue. If another element exists in the queue with // the same address, it replaces that element. func (dq *dialQueue) Add(adelay network.AddrDelay) { - for i := 0; i < dq.Len(); i++ { + for i := 0; i < dq.len(); i++ { if dq.q[i].Addr.Equal(adelay.Addr) { if dq.q[i].Delay == adelay.Delay { // existing element is the same. nothing to do @@ -455,7 +452,7 @@ func (dq *dialQueue) Add(adelay network.AddrDelay) { } } - for i := 0; i < dq.Len(); i++ { + for i := 0; i < dq.len(); i++ { if dq.q[i].Delay > adelay.Delay { dq.q = append(dq.q, network.AddrDelay{}) // extend the slice copy(dq.q[i+1:], dq.q[i:]) @@ -468,13 +465,13 @@ func (dq *dialQueue) Add(adelay network.AddrDelay) { // NextBatch returns all the elements in the queue with the highest priority func (dq *dialQueue) NextBatch() []network.AddrDelay { - if dq.Len() == 0 { + if dq.len() == 0 { return nil } // i is the index of the second highest priority element var i int - for i = 0; i < dq.Len(); i++ { + for i = 0; i < dq.len(); i++ { if dq.q[i].Delay != dq.q[0].Delay { break } @@ -489,7 +486,7 @@ func (dq *dialQueue) top() network.AddrDelay { return dq.q[0] } -// Len returns the number of elements in the queue -func (dq *dialQueue) Len() int { +// len returns the number of elements in the queue +func (dq *dialQueue) len() int { return len(dq.q) } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/limiter.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/limiter.go index f5638bbe7..ccfe7d237 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/limiter.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/limiter.go @@ -13,11 +13,17 @@ import ( ma "github.com/multiformats/go-multiaddr" ) +type dialResult struct { + Conn transport.CapableConn + Addr ma.Multiaddr + Err error +} + type dialJob struct { addr ma.Multiaddr peer peer.ID ctx context.Context - resp chan transport.DialUpdate + resp chan dialResult timeout time.Duration } @@ -39,7 +45,7 @@ type dialLimiter struct { waitingOnPeerLimit map[peer.ID][]*dialJob } -type dialfunc func(context.Context, peer.ID, ma.Multiaddr, chan<- transport.DialUpdate) (transport.CapableConn, error) +type dialfunc func(context.Context, peer.ID, ma.Multiaddr) (transport.CapableConn, error) func newDialLimiter(df dialfunc) *dialLimiter { fd := ConcurrentFdDials @@ -210,13 +216,9 @@ func (dl *dialLimiter) executeDial(j *dialJob) { dctx, cancel := context.WithTimeout(j.ctx, j.timeout) defer cancel() - con, err := dl.dialFunc(dctx, j.peer, j.addr, j.resp) - kind := transport.UpdateKindDialSuccessful - if err != nil { - kind = transport.UpdateKindDialFailed - } + con, err := dl.dialFunc(dctx, j.peer, j.addr) select { - case j.resp <- transport.DialUpdate{Kind: kind, Conn: con, Addr: j.addr, Err: err}: + case j.resp <- dialResult{Conn: con, Addr: j.addr, Err: err}: case <-j.ctx.Done(): if con != nil { con.Close() diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm.go index a76edce6c..5155cd222 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm.go @@ -17,7 +17,6 @@ import ( "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/peerstore" "github.com/libp2p/go-libp2p/core/transport" - "golang.org/x/exp/slices" logging "github.com/ipfs/go-log/v2" ma "github.com/multiformats/go-multiaddr" @@ -137,8 +136,8 @@ func WithIPv6BlackHoleConfig(enabled bool, n, min int) Option { // communication. The Chan sends/receives Messages, which note the // destination or source Peer. type Swarm struct { - nextConnID atomic.Uint64 - nextStreamID atomic.Uint64 + nextConnID uint64 // guarded by atomic + nextStreamID uint64 // guarded by atomic // Close refcount. This allows us to fully wait for the swarm to be torn // down before continuing. @@ -173,11 +172,6 @@ type Swarm struct { m map[network.Notifiee]struct{} } - directConnNotifs struct { - sync.Mutex - m map[peer.ID][]chan struct{} - } - transports struct { sync.RWMutex m map[int]transport.Transport @@ -237,7 +231,6 @@ func NewSwarm(local peer.ID, peers peerstore.Peerstore, eventBus event.Bus, opts s.listeners.m = make(map[transport.Listener]struct{}) s.transports.m = make(map[int]transport.Transport) s.notifs.m = make(map[network.Notifiee]struct{}) - s.directConnNotifs.m = make(map[peer.ID][]chan struct{}) for _, opt := range opts { if err := opt(s); err != nil { @@ -350,7 +343,7 @@ func (s *Swarm) addConn(tc transport.CapableConn, dir network.Direction) (*Conn, conn: tc, swarm: s, stat: stat, - id: s.nextConnID.Add(1), + id: atomic.AddUint64(&s.nextConnID, 1), } // we ONLY check upgraded connections here so we can send them a Disconnect message. @@ -360,7 +353,7 @@ func (s *Swarm) addConn(tc transport.CapableConn, dir network.Direction) (*Conn, // TODO Send disconnect with reason here err := tc.Close() if err != nil { - log.Warnf("failed to close connection with peer %s and addr %s; err: %s", p, addr, err) + log.Warnf("failed to close connection with peer %s and addr %s; err: %s", p.Pretty(), addr, err) } return nil, ErrGaterDisallowedConnection } @@ -397,19 +390,6 @@ func (s *Swarm) addConn(tc transport.CapableConn, dir network.Direction) (*Conn, c.notifyLk.Lock() s.conns.Unlock() - // Notify goroutines waiting for a direct connection - if !c.Stat().Transient { - // Go routines interested in waiting for direct connection first acquire this lock - // and then acquire s.conns.RLock. Do not acquire this lock before conns.Unlock to - // prevent deadlock. - s.directConnNotifs.Lock() - for _, ch := range s.directConnNotifs.m[p] { - close(ch) - } - delete(s.directConnNotifs.m, p) - s.directConnNotifs.Unlock() - } - // Emit event after releasing `s.conns` lock so that a consumer can still // use swarm methods that need the `s.conns` lock. if isFirstConnection { @@ -449,110 +429,54 @@ func (s *Swarm) StreamHandler() network.StreamHandler { // NewStream creates a new stream on any available connection to peer, dialing // if necessary. -// Use network.WithUseTransient to open a stream over a transient(relayed) -// connection. func (s *Swarm) NewStream(ctx context.Context, p peer.ID) (network.Stream, error) { log.Debugf("[%s] opening stream to peer [%s]", s.local, p) // Algorithm: // 1. Find the best connection, otherwise, dial. - // 2. If the best connection is transient, wait for a direct conn via conn - // reversal or hole punching. - // 3. Try opening a stream. - // 4. If the underlying connection is, in fact, closed, close the outer + // 2. Try opening a stream. + // 3. If the underlying connection is, in fact, closed, close the outer // connection and try again. We do this in case we have a closed // connection but don't notice it until we actually try to open a // stream. // + // Note: We only dial once. + // // TODO: Try all connections even if we get an error opening a stream on // a non-closed connection. - numDials := 0 + dials := 0 for { - c := s.bestConnToPeer(p) - if c == nil { - if nodial, _ := network.GetNoDial(ctx); !nodial { - numDials++ - if numDials > DialAttempts { - return nil, errors.New("max dial attempts exceeded") - } - var err error - c, err = s.dialPeer(ctx, p) - if err != nil { - return nil, err - } - } else { - return nil, network.ErrNoConn - } + // will prefer direct connections over relayed connections for opening streams + c, err := s.bestAcceptableConnToPeer(ctx, p) + if err != nil { + return nil, err } - useTransient, _ := network.GetUseTransient(ctx) - if !useTransient && c.Stat().Transient { + if c == nil { + if nodial, _ := network.GetNoDial(ctx); nodial { + return nil, network.ErrNoConn + } + + if dials >= DialAttempts { + return nil, errors.New("max dial attempts exceeded") + } + dials++ + var err error - c, err = s.waitForDirectConn(ctx, p) + c, err = s.dialPeer(ctx, p) if err != nil { return nil, err } } - str, err := c.NewStream(ctx) + s, err := c.NewStream(ctx) if err != nil { if c.conn.IsClosed() { continue } return nil, err } - return str, nil - } -} - -// waitForDirectConn waits for a direct connection established through hole punching or connection reversal. -func (s *Swarm) waitForDirectConn(ctx context.Context, p peer.ID) (*Conn, error) { - s.directConnNotifs.Lock() - c := s.bestConnToPeer(p) - if c == nil { - s.directConnNotifs.Unlock() - return nil, network.ErrNoConn - } else if !c.Stat().Transient { - s.directConnNotifs.Unlock() - return c, nil - } - - // Wait for transient connection to upgrade to a direct connection either by - // connection reversal or hole punching. - ch := make(chan struct{}) - s.directConnNotifs.m[p] = append(s.directConnNotifs.m[p], ch) - s.directConnNotifs.Unlock() - - // apply the DialPeer timeout - ctx, cancel := context.WithTimeout(ctx, network.GetDialPeerTimeout(ctx)) - defer cancel() - - // Wait for notification. - select { - case <-ctx.Done(): - // Remove ourselves from the notification list - s.directConnNotifs.Lock() - defer s.directConnNotifs.Unlock() - - s.directConnNotifs.m[p] = slices.DeleteFunc( - s.directConnNotifs.m[p], - func(c chan struct{}) bool { return c == ch }, - ) - if len(s.directConnNotifs.m[p]) == 0 { - delete(s.directConnNotifs.m, p) - } - return nil, ctx.Err() - case <-ch: - // We do not need to remove ourselves from the list here as the notifier - // clears the map entry - c := s.bestConnToPeer(p) - if c == nil { - return nil, network.ErrNoConn - } - if c.Stat().Transient { - return nil, network.ErrTransientConn - } - return c, nil + return s, nil } } @@ -624,17 +548,26 @@ func (s *Swarm) bestConnToPeer(p peer.ID) *Conn { return best } -// bestAcceptableConnToPeer returns the best acceptable connection, considering the passed in ctx. -// If network.WithForceDirectDial is used, it only returns a direct connections, ignoring -// any transient (relayed) connections to the peer. -func (s *Swarm) bestAcceptableConnToPeer(ctx context.Context, p peer.ID) *Conn { +// - Returns the best "acceptable" connection, if available. +// - Returns nothing if no such connection exists, but if we should try dialing anyways. +// - Returns an error if no such connection exists, but we should not try dialing. +func (s *Swarm) bestAcceptableConnToPeer(ctx context.Context, p peer.ID) (*Conn, error) { conn := s.bestConnToPeer(p) + if conn == nil { + return nil, nil + } forceDirect, _ := network.GetForceDirectDial(ctx) if forceDirect && !isDirectConn(conn) { - return nil + return nil, nil } - return conn + + useTransient, _ := network.GetUseTransient(ctx) + if useTransient || !conn.Stat().Transient { + return conn, nil + } + + return nil, network.ErrTransientConn } func isDirectConn(c *Conn) bool { diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_conn.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_conn.go index 8c3ce7c5a..e770381a2 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_conn.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_conn.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "sync" + "sync/atomic" "time" ic "github.com/libp2p/go-libp2p/core/crypto" @@ -48,7 +49,7 @@ func (c *Conn) IsClosed() bool { func (c *Conn) ID() string { // format: - - return fmt.Sprintf("%s-%d", c.RemotePeer().String()[:10], c.id) + return fmt.Sprintf("%s-%d", c.RemotePeer().Pretty()[0:10], c.id) } // Close closes this connection. @@ -136,7 +137,6 @@ func (c *Conn) start() { if h := c.swarm.StreamHandler(); h != nil { h(s) } - s.completeAcceptStreamGoroutine() }() } }() @@ -147,9 +147,9 @@ func (c *Conn) String() string { " %s (%s)>", c.conn.Transport(), c.conn.LocalMultiaddr(), - c.conn.LocalPeer(), + c.conn.LocalPeer().Pretty(), c.conn.RemoteMultiaddr(), - c.conn.RemotePeer(), + c.conn.RemotePeer().Pretty(), ) } @@ -238,8 +238,7 @@ func (c *Conn) addStream(ts network.MuxedStream, dir network.Direction, scope ne Direction: dir, Opened: time.Now(), }, - id: c.swarm.nextStreamID.Add(1), - acceptStreamGoroutineCompleted: dir != network.DirInbound, + id: atomic.AddUint64(&c.swarm.nextStreamID, 1), } c.stat.NumStreams++ c.streams.m[s] = struct{}{} diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_dial.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_dial.go index 3fb15383a..f2df93af2 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_dial.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_dial.go @@ -14,10 +14,8 @@ import ( "github.com/libp2p/go-libp2p/core/peer" "github.com/libp2p/go-libp2p/core/peerstore" "github.com/libp2p/go-libp2p/core/transport" - ma "github.com/multiformats/go-multiaddr" madns "github.com/multiformats/go-multiaddr-dns" - mafmt "github.com/multiformats/go-multiaddr-fmt" manet "github.com/multiformats/go-multiaddr/net" ) @@ -67,19 +65,6 @@ var ( ErrGaterDisallowedConnection = errors.New("gater disallows connection to peer") ) -// ErrQUICDraft29 wraps ErrNoTransport and provide a more meaningful error message -var ErrQUICDraft29 errQUICDraft29 - -type errQUICDraft29 struct{} - -func (errQUICDraft29) Error() string { - return "QUIC draft-29 has been removed, QUIC (RFC 9000) is accessible with /quic-v1" -} - -func (errQUICDraft29) Unwrap() error { - return ErrNoTransport -} - // DialAttempts governs how many times a goroutine will try to dial a given peer. // Note: this is down to one, as we have _too many dials_ atm. To add back in, // add loop back in Dial(.) @@ -216,8 +201,7 @@ func (db *DialBackoff) cleanup() { } } -// DialPeer connects to a peer. Use network.WithForceDirectDial to force a -// direct connection. +// DialPeer connects to a peer. // // The idea is that the client of Swarm does not need to know what network // the connection will happen over. Swarm can use whichever it choses. @@ -247,14 +231,15 @@ func (s *Swarm) dialPeer(ctx context.Context, p peer.ID) (*Conn, error) { return nil, ErrDialToSelf } - // check if we already have an open (usable) connection. - conn := s.bestAcceptableConnToPeer(ctx, p) - if conn != nil { - return conn, nil + // check if we already have an open (usable) connection first, or can't have a usable + // connection. + conn, err := s.bestAcceptableConnToPeer(ctx, p) + if conn != nil || err != nil { + return conn, err } if s.gater != nil && !s.gater.InterceptPeerDial(p) { - log.Debugf("gater disallowed outbound connection to peer %s", p) + log.Debugf("gater disallowed outbound connection to peer %s", p.Pretty()) return nil, &DialError{Peer: p, Cause: ErrGaterDisallowedConnection} } @@ -295,47 +280,68 @@ func (s *Swarm) dialWorkerLoop(p peer.ID, reqch <-chan dialRequest) { w.loop() } -func (s *Swarm) addrsForDial(ctx context.Context, p peer.ID) (goodAddrs []ma.Multiaddr, addrErrs []TransportError, err error) { +func (s *Swarm) addrsForDial(ctx context.Context, p peer.ID) ([]ma.Multiaddr, error) { peerAddrs := s.peers.Addrs(p) if len(peerAddrs) == 0 { - return nil, nil, ErrNoAddresses + return nil, ErrNoAddresses + } + + peerAddrsAfterTransportResolved := make([]ma.Multiaddr, 0, len(peerAddrs)) + for _, a := range peerAddrs { + tpt := s.TransportForDialing(a) + resolver, ok := tpt.(transport.Resolver) + if ok { + resolvedAddrs, err := resolver.Resolve(ctx, a) + if err != nil { + log.Warnf("Failed to resolve multiaddr %s by transport %v: %v", a, tpt, err) + continue + } + peerAddrsAfterTransportResolved = append(peerAddrsAfterTransportResolved, resolvedAddrs...) + } else { + peerAddrsAfterTransportResolved = append(peerAddrsAfterTransportResolved, a) + } } // Resolve dns or dnsaddrs - resolved, err := s.resolveAddrs(ctx, peer.AddrInfo{ID: p, Addrs: peerAddrs}) - if err != nil { - return nil, nil, err - } - - goodAddrs = ma.Unique(resolved) - goodAddrs, addrErrs = s.filterKnownUndialables(p, goodAddrs) - if forceDirect, _ := network.GetForceDirectDial(ctx); forceDirect { - goodAddrs = ma.FilterAddrs(goodAddrs, s.nonProxyAddr) - } - - if len(goodAddrs) == 0 { - return nil, addrErrs, ErrNoGoodAddresses - } - - s.peers.AddAddrs(p, goodAddrs, peerstore.TempAddrTTL) - - return goodAddrs, addrErrs, nil -} - -func (s *Swarm) resolveAddrs(ctx context.Context, pi peer.AddrInfo) ([]ma.Multiaddr, error) { - p2paddr, err := ma.NewMultiaddr("/" + ma.ProtocolWithCode(ma.P_P2P).Name + "/" + pi.ID.String()) + resolved, err := s.resolveAddrs(ctx, peer.AddrInfo{ + ID: p, + Addrs: peerAddrsAfterTransportResolved, + }) if err != nil { return nil, err } - var resolveSteps int + goodAddrs := s.filterKnownUndialables(p, resolved) + if forceDirect, _ := network.GetForceDirectDial(ctx); forceDirect { + goodAddrs = ma.FilterAddrs(goodAddrs, s.nonProxyAddr) + } + goodAddrs = ma.Unique(goodAddrs) + + if len(goodAddrs) == 0 { + return nil, ErrNoGoodAddresses + } + + s.peers.AddAddrs(p, goodAddrs, peerstore.TempAddrTTL) + + return goodAddrs, nil +} + +func (s *Swarm) resolveAddrs(ctx context.Context, pi peer.AddrInfo) ([]ma.Multiaddr, error) { + proto := ma.ProtocolWithCode(ma.P_P2P).Name + p2paddr, err := ma.NewMultiaddr("/" + proto + "/" + pi.ID.Pretty()) + if err != nil { + return nil, err + } + + resolveSteps := 0 + // Recursively resolve all addrs. // // While the toResolve list is non-empty: // * Pop an address off. // * If the address is fully resolved, add it to the resolved list. // * Otherwise, resolve it and add the results to the "to resolve" list. - toResolve := append([]ma.Multiaddr{}, pi.Addrs...) + toResolve := append(([]ma.Multiaddr)(nil), pi.Addrs...) resolved := make([]ma.Multiaddr, 0, len(pi.Addrs)) for len(toResolve) > 0 { // pop the last addr off. @@ -362,26 +368,6 @@ func (s *Swarm) resolveAddrs(ctx context.Context, pi peer.AddrInfo) ([]ma.Multia continue } - tpt := s.TransportForDialing(addr) - resolver, ok := tpt.(transport.Resolver) - if ok { - resolvedAddrs, err := resolver.Resolve(ctx, addr) - if err != nil { - log.Warnf("Failed to resolve multiaddr %s by transport %v: %v", addr, tpt, err) - continue - } - var added bool - for _, a := range resolvedAddrs { - if !addr.Equal(a) { - toResolve = append(toResolve, a) - added = true - } - } - if added { - continue - } - } - // otherwise, resolve it reqaddr := addr.Encapsulate(p2paddr) resaddrs, err := s.maResolver.Resolve(ctx, reqaddr) @@ -402,7 +388,7 @@ func (s *Swarm) resolveAddrs(ctx context.Context, pi peer.AddrInfo) ([]ma.Multia return resolved, nil } -func (s *Swarm) dialNextAddr(ctx context.Context, p peer.ID, addr ma.Multiaddr, resch chan transport.DialUpdate) error { +func (s *Swarm) dialNextAddr(ctx context.Context, p peer.ID, addr ma.Multiaddr, resch chan dialResult) error { // check the dial backoff if forceDirect, _ := network.GetForceDirectDial(ctx); !forceDirect { if s.backf.Backoff(p, addr) { @@ -416,20 +402,23 @@ func (s *Swarm) dialNextAddr(ctx context.Context, p peer.ID, addr ma.Multiaddr, return nil } +func (s *Swarm) canDial(addr ma.Multiaddr) bool { + t := s.TransportForDialing(addr) + return t != nil && t.CanDial(addr) +} + func (s *Swarm) nonProxyAddr(addr ma.Multiaddr) bool { t := s.TransportForDialing(addr) return !t.Proxy() } -var quicDraft29DialMatcher = mafmt.And(mafmt.IP, mafmt.Base(ma.P_UDP), mafmt.Base(ma.P_QUIC)) - // filterKnownUndialables takes a list of multiaddrs, and removes those // that we definitely don't want to dial: addresses configured to be blocked, // IPv6 link-local addresses, addresses without a dial-capable transport, // addresses that we know to be our own, and addresses with a better tranport // available. This is an optimization to avoid wasting time on dials that we // know are going to fail or for which we have a better alternative. -func (s *Swarm) filterKnownUndialables(p peer.ID, addrs []ma.Multiaddr) (goodAddrs []ma.Multiaddr, addrErrs []TransportError) { +func (s *Swarm) filterKnownUndialables(p peer.ID, addrs []ma.Multiaddr) []ma.Multiaddr { lisAddrs, _ := s.InterfaceListenAddresses() var ourAddrs []ma.Multiaddr for _, addr := range lisAddrs { @@ -442,71 +431,35 @@ func (s *Swarm) filterKnownUndialables(p peer.ID, addrs []ma.Multiaddr) (goodAdd }) } - addrErrs = make([]TransportError, 0, len(addrs)) + // The order of these two filters is important. If we can only dial /webtransport, + // we don't want to filter /webtransport addresses out because the peer had a /quic-v1 + // address - // The order of checking for transport and filtering low priority addrs is important. If we - // can only dial /webtransport, we don't want to filter /webtransport addresses out because - // the peer had a /quic-v1 address - - // filter addresses with no transport - addrs = ma.FilterAddrs(addrs, func(a ma.Multiaddr) bool { - if s.TransportForDialing(a) == nil { - e := ErrNoTransport - // We used to support QUIC draft-29 for a long time. - // Provide a more useful error when attempting to dial a QUIC draft-29 address. - if quicDraft29DialMatcher.Matches(a) { - e = ErrQUICDraft29 - } - addrErrs = append(addrErrs, TransportError{Address: a, Cause: e}) - return false - } - return true - }) + // filter addresses we cannot dial + addrs = ma.FilterAddrs(addrs, s.canDial) // filter low priority addresses among the addresses we can dial - // We don't return an error for these addresses addrs = filterLowPriorityAddresses(addrs) // remove black holed addrs - addrs, blackHoledAddrs := s.bhd.FilterAddrs(addrs) - for _, a := range blackHoledAddrs { - addrErrs = append(addrErrs, TransportError{Address: a, Cause: ErrDialRefusedBlackHole}) - } + addrs = s.bhd.FilterAddrs(addrs) return ma.FilterAddrs(addrs, - // Linux and BSD treat an unspecified address when dialing as a localhost address. - // Windows doesn't support this. We filter all such addresses out because peers - // listening on unspecified addresses will advertise more specific addresses. - // https://unix.stackexchange.com/a/419881 - // https://superuser.com/a/1755455 - func(addr ma.Multiaddr) bool { - return !manet.IsIPUnspecified(addr) - }, - func(addr ma.Multiaddr) bool { - if ma.Contains(ourAddrs, addr) { - addrErrs = append(addrErrs, TransportError{Address: addr, Cause: ErrDialToSelf}) - return false - } - return true - }, + func(addr ma.Multiaddr) bool { return !ma.Contains(ourAddrs, addr) }, // TODO: Consider allowing link-local addresses func(addr ma.Multiaddr) bool { return !manet.IsIP6LinkLocal(addr) }, func(addr ma.Multiaddr) bool { - if s.gater != nil && !s.gater.InterceptAddrDial(p, addr) { - addrErrs = append(addrErrs, TransportError{Address: addr, Cause: ErrGaterDisallowedConnection}) - return false - } - return true + return s.gater == nil || s.gater.InterceptAddrDial(p, addr) }, - ), addrErrs + ) } // limitedDial will start a dial to the given peer when // it is able, respecting the various different types of rate // limiting that occur without using extra goroutines per addr -func (s *Swarm) limitedDial(ctx context.Context, p peer.ID, a ma.Multiaddr, resp chan transport.DialUpdate) { +func (s *Swarm) limitedDial(ctx context.Context, p peer.ID, a ma.Multiaddr, resp chan dialResult) { timeout := s.dialTimeout - if manet.IsPrivateAddr(a) && s.dialTimeoutLocal < s.dialTimeout { + if lowTimeoutFilters.AddrBlocked(a) && s.dialTimeoutLocal < s.dialTimeout { timeout = s.dialTimeoutLocal } s.limiter.AddDialJob(&dialJob{ @@ -519,7 +472,7 @@ func (s *Swarm) limitedDial(ctx context.Context, p peer.ID, a ma.Multiaddr, resp } // dialAddr is the actual dial for an addr, indirectly invoked through the limiter -func (s *Swarm) dialAddr(ctx context.Context, p peer.ID, addr ma.Multiaddr, updCh chan<- transport.DialUpdate) (transport.CapableConn, error) { +func (s *Swarm) dialAddr(ctx context.Context, p peer.ID, addr ma.Multiaddr) (transport.CapableConn, error) { // Just to double check. Costs nothing. if s.local == p { return nil, ErrDialToSelf @@ -537,13 +490,7 @@ func (s *Swarm) dialAddr(ctx context.Context, p peer.ID, addr ma.Multiaddr, updC } start := time.Now() - var connC transport.CapableConn - var err error - if du, ok := tpt.(transport.DialUpdater); ok { - connC, err = du.DialWithUpdates(ctx, addr, p, updCh) - } else { - connC, err = tpt.Dial(ctx, addr, p) - } + connC, err := tpt.Dial(ctx, addr, p) // We're recording any error as a failure here. // Notably, this also applies to cancelations (i.e. if another dial attempt was faster). @@ -552,7 +499,7 @@ func (s *Swarm) dialAddr(ctx context.Context, p peer.ID, addr ma.Multiaddr, updC if err != nil { if s.metricsTracer != nil { - s.metricsTracer.FailedDialing(addr, err, context.Cause(ctx)) + s.metricsTracer.FailedDialing(addr, err) } return nil, err } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_metrics.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_metrics.go index 9cc34599d..28564e9e5 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_metrics.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_metrics.go @@ -128,7 +128,7 @@ type MetricsTracer interface { OpenedConnection(network.Direction, crypto.PubKey, network.ConnectionState, ma.Multiaddr) ClosedConnection(network.Direction, time.Duration, network.ConnectionState, ma.Multiaddr) CompletedHandshake(time.Duration, network.ConnectionState, ma.Multiaddr) - FailedDialing(ma.Multiaddr, error, error) + FailedDialing(ma.Multiaddr, error) DialCompleted(success bool, totalDials int) DialRankingDelay(d time.Duration) UpdatedBlackHoleFilterState(name string, state blackHoleState, nextProbeAfter int, successFraction float64) @@ -216,28 +216,18 @@ func (m *metricsTracer) CompletedHandshake(t time.Duration, cs network.Connectio connHandshakeLatency.WithLabelValues(*tags...).Observe(t.Seconds()) } -func (m *metricsTracer) FailedDialing(addr ma.Multiaddr, dialErr error, cause error) { +func (m *metricsTracer) FailedDialing(addr ma.Multiaddr, err error) { transport := metricshelper.GetTransport(addr) e := "other" - // dial deadline exceeded or the the parent contexts deadline exceeded - if errors.Is(dialErr, context.DeadlineExceeded) || errors.Is(cause, context.DeadlineExceeded) { + if errors.Is(err, context.Canceled) { + e = "canceled" + } else if errors.Is(err, context.DeadlineExceeded) { e = "deadline" - } else if errors.Is(dialErr, context.Canceled) { - // dial was cancelled. - if errors.Is(cause, context.Canceled) { - // parent context was canceled - e = "application canceled" - } else if errors.Is(cause, errConcurrentDialSuccessful) { - e = "canceled: concurrent dial successful" - } else { - // something else - e = "canceled: other" - } } else { - nerr, ok := dialErr.(net.Error) + nerr, ok := err.(net.Error) if ok && nerr.Timeout() { e = "timeout" - } else if strings.Contains(dialErr.Error(), "connect: connection refused") { + } else if strings.Contains(err.Error(), "connect: connection refused") { e = "connection refused" } } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_stream.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_stream.go index b7846adec..d372bcd8e 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_stream.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/swarm/swarm_stream.go @@ -22,10 +22,7 @@ type Stream struct { conn *Conn scope network.StreamManagementScope - closeMx sync.Mutex - isClosed bool - // acceptStreamGoroutineCompleted indicates whether the goroutine handling the incoming stream has exited - acceptStreamGoroutineCompleted bool + closeOnce sync.Once protocol atomic.Pointer[protocol.ID] @@ -79,7 +76,7 @@ func (s *Stream) Write(p []byte) (int, error) { // resources. func (s *Stream) Close() error { err := s.stream.Close() - s.closeAndRemoveStream() + s.closeOnce.Do(s.remove) return err } @@ -87,25 +84,10 @@ func (s *Stream) Close() error { // associated resources. func (s *Stream) Reset() error { err := s.stream.Reset() - s.closeAndRemoveStream() + s.closeOnce.Do(s.remove) return err } -func (s *Stream) closeAndRemoveStream() { - s.closeMx.Lock() - defer s.closeMx.Unlock() - if s.isClosed { - return - } - s.isClosed = true - // We don't want to keep swarm from closing till the stream handler has exited - s.conn.swarm.refs.Done() - // Cleanup the stream from connection only after the stream handler has completed - if s.acceptStreamGoroutineCompleted { - s.conn.removeStream(s) - } -} - // CloseWrite closes the stream for writing, flushing all data and sending an EOF. // This function does not free resources, call Close or Reset when done with the // stream. @@ -119,16 +101,9 @@ func (s *Stream) CloseRead() error { return s.stream.CloseRead() } -func (s *Stream) completeAcceptStreamGoroutine() { - s.closeMx.Lock() - defer s.closeMx.Unlock() - if s.acceptStreamGoroutineCompleted { - return - } - s.acceptStreamGoroutineCompleted = true - if s.isClosed { - s.conn.removeStream(s) - } +func (s *Stream) remove() { + s.conn.removeStream(s) + s.conn.swarm.refs.Done() } // Protocol returns the protocol negotiated on this stream (if set). diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/net/upgrader/upgrader.go b/vendor/github.com/libp2p/go-libp2p/p2p/net/upgrader/upgrader.go index 3a6f8b9f5..d18c16ea0 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/net/upgrader/upgrader.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/net/upgrader/upgrader.go @@ -152,8 +152,7 @@ func (u *upgrader) upgrade(ctx context.Context, t transport.Transport, maconn ma return nil, ipnet.ErrNotInPrivateNetwork } - isServer := dir == network.DirInbound - sconn, security, err := u.setupSecurity(ctx, conn, p, isServer) + sconn, security, server, err := u.setupSecurity(ctx, conn, p, dir) if err != nil { conn.Close() return nil, fmt.Errorf("failed to negotiate security protocol: %w", err) @@ -180,7 +179,7 @@ func (u *upgrader) upgrade(ctx context.Context, t transport.Transport, maconn ma } } - muxer, smconn, err := u.setupMuxer(ctx, sconn, isServer, connScope.PeerScope()) + muxer, smconn, err := u.setupMuxer(ctx, sconn, server, connScope.PeerScope()) if err != nil { sconn.Close() return nil, fmt.Errorf("failed to negotiate stream multiplexer: %w", err) @@ -200,17 +199,20 @@ func (u *upgrader) upgrade(ctx context.Context, t transport.Transport, maconn ma return tc, nil } -func (u *upgrader) setupSecurity(ctx context.Context, conn net.Conn, p peer.ID, isServer bool) (sec.SecureConn, protocol.ID, error) { - st, err := u.negotiateSecurity(ctx, conn, isServer) +func (u *upgrader) setupSecurity(ctx context.Context, conn net.Conn, p peer.ID, dir network.Direction) (sec.SecureConn, protocol.ID, bool, error) { + isServer := dir == network.DirInbound + var st sec.SecureTransport + var err error + st, isServer, err = u.negotiateSecurity(ctx, conn, isServer) if err != nil { - return nil, "", err + return nil, "", false, err } if isServer { sconn, err := st.SecureInbound(ctx, conn, p) - return sconn, st.ID(), err + return sconn, st.ID(), true, err } sconn, err := st.SecureOutbound(ctx, conn, p) - return sconn, st.ID(), err + return sconn, st.ID(), false, err } func (u *upgrader) negotiateMuxer(nc net.Conn, isServer bool) (*StreamMuxer, error) { @@ -306,38 +308,41 @@ func (u *upgrader) getSecurityByID(id protocol.ID) sec.SecureTransport { return nil } -func (u *upgrader) negotiateSecurity(ctx context.Context, insecure net.Conn, server bool) (sec.SecureTransport, error) { +func (u *upgrader) negotiateSecurity(ctx context.Context, insecure net.Conn, server bool) (sec.SecureTransport, bool, error) { type result struct { - proto protocol.ID - err error + proto protocol.ID + iamserver bool + err error } done := make(chan result, 1) go func() { if server { var r result + r.iamserver = true r.proto, _, r.err = u.securityMuxer.Negotiate(insecure) done <- r return } var r result - r.proto, r.err = mss.SelectOneOf(u.securityIDs, insecure) + r.proto, r.iamserver, r.err = mss.SelectWithSimopenOrFail(u.securityIDs, insecure) done <- r }() select { case r := <-done: if r.err != nil { - return nil, r.err + return nil, false, r.err } if s := u.getSecurityByID(r.proto); s != nil { - return s, nil + return s, r.iamserver, nil } - return nil, fmt.Errorf("selected unknown security transport: %s", r.proto) + return nil, false, fmt.Errorf("selected unknown security transport: %s", r.proto) case <-ctx.Done(): - // We *must* do this. We have outstanding work on the connection, and it's no longer safe to use. + // We *must* do this. We have outstanding work on the connection + // and it's no longer safe to use. insecure.Close() <-done // wait to stop using the connection. - return nil, ctx.Err() + return nil, false, ctx.Err() } } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/relay/constraints.go b/vendor/github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/relay/constraints.go index 4b9b54cd8..24353086f 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/relay/constraints.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/relay/constraints.go @@ -74,10 +74,7 @@ func (c *constraints) AddReservation(p peer.ID, a ma.Multiaddr) error { var asnReservations []time.Time var asn string - // Only public addresses have an ASN. Skip checking ASN for private addresses as - // initialising the ASN store is a costly operation. Skipping this check reduces a lot of - // flakiness in tests - if ip.To4() == nil && manet.IsPublicAddr(a) { + if ip.To4() == nil { asn, _ = asnutil.Store.AsnForIPv6(ip) if asn != "" { asnReservations = c.asns[asn] diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/protocol/identify/id.go b/vendor/github.com/libp2p/go-libp2p/p2p/protocol/identify/id.go index 6c07dbdc8..69506e9b3 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/protocol/identify/id.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/protocol/identify/id.go @@ -556,7 +556,7 @@ func readAllIDMessages(r pbio.Reader, finalMsg proto.Message) error { func (ids *idService) updateSnapshot() (updated bool) { addrs := ids.Host.Addrs() - slices.SortFunc(addrs, func(a, b ma.Multiaddr) int { return bytes.Compare(a.Bytes(), b.Bytes()) }) + slices.SortFunc(addrs, func(a, b ma.Multiaddr) bool { return bytes.Compare(a.Bytes(), b.Bytes()) == -1 }) protos := ids.Host.Mux().Protocols() slices.Sort(protos) snapshot := identifySnapshot{ diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/protocol/identify/obsaddr.go b/vendor/github.com/libp2p/go-libp2p/p2p/protocol/identify/obsaddr.go index 70a7eccd4..0412541f5 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/protocol/identify/obsaddr.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/protocol/identify/obsaddr.go @@ -212,16 +212,13 @@ func (oas *ObservedAddrManager) filter(observedAddrs []*observedAddr) []ma.Multi for pat := range pmap { s := pmap[pat] - slices.SortFunc(s, func(first, second *observedAddr) int { - // We prefer inbound connection observations over outbound. + // We prefer inbound connection observations over outbound. + // For ties, we prefer the ones with more votes. + slices.SortFunc(s, func(first, second *observedAddr) bool { if first.numInbound > second.numInbound { - return -1 + return true } - // For ties, we prefer the ones with more votes. - if first.numInbound == second.numInbound && len(first.seenBy) > len(second.seenBy) { - return -1 - } - return 1 + return len(first.seenBy) > len(second.seenBy) }) for i := 0; i < maxObservedAddrsPerIPAndTransport && i < len(s); i++ { diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/security/noise/handshake.go b/vendor/github.com/libp2p/go-libp2p/p2p/security/noise/handshake.go index a9493bf8d..e1a18e9b6 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/security/noise/handshake.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/security/noise/handshake.go @@ -12,12 +12,11 @@ import ( "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" - "github.com/libp2p/go-libp2p/core/sec" - "github.com/libp2p/go-libp2p/internal/sha256" "github.com/libp2p/go-libp2p/p2p/security/noise/pb" "github.com/flynn/noise" pool "github.com/libp2p/go-buffer-pool" + "github.com/minio/sha256-simd" "google.golang.org/protobuf/proto" ) @@ -277,7 +276,7 @@ func (s *secureSession) handleRemoteHandshakePayload(payload []byte, remoteStati // check the peer ID if enabled if s.checkPeerID && s.remoteID != id { - return nil, sec.ErrPeerIDMismatch{Expected: s.remoteID, Actual: id} + return nil, fmt.Errorf("peer id mismatch: expected %s, but remote key matches %s", s.remoteID.Pretty(), id.Pretty()) } // verify payload is signed by asserted remote libp2p key. diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/security/tls/crypto.go b/vendor/github.com/libp2p/go-libp2p/p2p/security/tls/crypto.go index 385de5a16..b8f23f39e 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/security/tls/crypto.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/security/tls/crypto.go @@ -18,7 +18,6 @@ import ( ic "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peer" - "github.com/libp2p/go-libp2p/core/sec" ) const certValidityPeriod = 100 * 365 * 24 * time.Hour // ~100 years @@ -130,7 +129,7 @@ func (i *Identity) ConfigForPeer(remote peer.ID) (*tls.Config, <-chan ic.PubKey) if err != nil { peerID = peer.ID(fmt.Sprintf("(not determined: %s)", err.Error())) } - return sec.ErrPeerIDMismatch{Expected: remote, Actual: peerID} + return fmt.Errorf("peer IDs don't match: expected %s, got %s", remote, peerID) } keyCh <- pubKey return nil diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quic/listener.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quic/listener.go index d49b68649..73bb5026b 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quic/listener.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quic/listener.go @@ -29,6 +29,9 @@ type listener struct { func newListener(ln quicreuse.Listener, t *transport, localPeer peer.ID, key ic.PrivKey, rcmgr network.ResourceManager) (listener, error) { localMultiaddrs := make(map[quic.VersionNumber]ma.Multiaddr) for _, addr := range ln.Multiaddrs() { + if _, err := addr.ValueForProtocol(ma.P_QUIC); err == nil { + localMultiaddrs[quic.VersionDraft29] = addr + } if _, err := addr.ValueForProtocol(ma.P_QUIC_V1); err == nil { localMultiaddrs[quic.Version1] = addr } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quic/transport.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quic/transport.go index 18d198bbe..aef3f4c9d 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quic/transport.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quic/transport.go @@ -268,8 +268,8 @@ loop: } } -// Don't use mafmt.QUIC as we don't want to dial DNS addresses. Just /ip{4,6}/udp/quic-v1 -var dialMatcher = mafmt.And(mafmt.IP, mafmt.Base(ma.P_UDP), mafmt.Base(ma.P_QUIC_V1)) +// Don't use mafmt.QUIC as we don't want to dial DNS addresses. Just /ip{4,6}/udp/quic +var dialMatcher = mafmt.And(mafmt.IP, mafmt.Base(ma.P_UDP), mafmt.Or(mafmt.Base(ma.P_QUIC), mafmt.Base(ma.P_QUIC_V1))) // CanDial determines if we can dial to an address func (t *transport) CanDial(addr ma.Multiaddr) bool { diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/config.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/config.go index 45b1d4b8c..76a2c8cc4 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/config.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/config.go @@ -17,7 +17,9 @@ var quicConfig = &quic.Config{ return false }, KeepAlivePeriod: 15 * time.Second, - Versions: []quic.VersionNumber{quic.Version1}, + Versions: []quic.VersionNumber{quic.VersionDraft29, quic.Version1}, // We don't use datagrams (yet), but this is necessary for WebTransport EnableDatagrams: true, + // The multiaddress encodes the QUIC version, thus there's no need to send Version Negotiation packets. + DisableVersionNegotiationPackets: true, } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/connmgr.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/connmgr.go index 0add5ddfc..c12b86671 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/connmgr.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/connmgr.go @@ -16,6 +16,7 @@ import ( type ConnManager struct { reuseUDP4 *reuse reuseUDP6 *reuse + enableDraft29 bool enableReuseport bool enableMetrics bool @@ -25,8 +26,8 @@ type ConnManager struct { quicListenersMu sync.Mutex quicListeners map[string]quicListenerEntry - srk quic.StatelessResetKey - tokenKey quic.TokenGeneratorKey + srk quic.StatelessResetKey + mt *metricsTracer } type quicListenerEntry struct { @@ -34,12 +35,12 @@ type quicListenerEntry struct { ln *quicListener } -func NewConnManager(statelessResetKey quic.StatelessResetKey, tokenKey quic.TokenGeneratorKey, opts ...Option) (*ConnManager, error) { +func NewConnManager(statelessResetKey quic.StatelessResetKey, opts ...Option) (*ConnManager, error) { cm := &ConnManager{ enableReuseport: true, + enableDraft29: true, quicListeners: make(map[string]quicListenerEntry), srk: statelessResetKey, - tokenKey: tokenKey, } for _, o := range opts { if err := o(cm); err != nil { @@ -49,20 +50,29 @@ func NewConnManager(statelessResetKey quic.StatelessResetKey, tokenKey quic.Toke quicConf := quicConfig.Clone() - quicConf.Tracer = func(ctx context.Context, p quiclogging.Perspective, ci quic.ConnectionID) *quiclogging.ConnectionTracer { - var tracer *quiclogging.ConnectionTracer + if cm.enableMetrics { + cm.mt = newMetricsTracer() + } + quicConf.Tracer = func(ctx context.Context, p quiclogging.Perspective, ci quic.ConnectionID) quiclogging.ConnectionTracer { + tracers := make([]quiclogging.ConnectionTracer, 0, 2) if qlogTracerDir != "" { - tracer = qloggerForDir(qlogTracerDir, p, ci) + tracers = append(tracers, qloggerForDir(qlogTracerDir, p, ci)) } - return tracer + if cm.mt != nil { + tracers = append(tracers, cm.mt.TracerForConnection(ctx, p, ci)) + } + return quiclogging.NewMultiplexedConnectionTracer(tracers...) } serverConfig := quicConf.Clone() + if !cm.enableDraft29 { + serverConfig.Versions = []quic.VersionNumber{quic.Version1} + } cm.clientConfig = quicConf cm.serverConfig = serverConfig if cm.enableReuseport { - cm.reuseUDP4 = newReuse(&statelessResetKey, &tokenKey) - cm.reuseUDP6 = newReuse(&statelessResetKey, &tokenKey) + cm.reuseUDP4 = newReuse(&statelessResetKey, cm.mt) + cm.reuseUDP6 = newReuse(&statelessResetKey, cm.mt) } return cm, nil } @@ -79,6 +89,12 @@ func (c *ConnManager) getReuse(network string) (*reuse, error) { } func (c *ConnManager) ListenQUIC(addr ma.Multiaddr, tlsConf *tls.Config, allowWindowIncrease func(conn quic.Connection, delta uint64) bool) (Listener, error) { + if !c.enableDraft29 { + if _, err := addr.ValueForProtocol(ma.P_QUIC); err == nil { + return nil, errors.New("can't listen on `/quic` multiaddr (QUIC draft 29 version) when draft 29 support is disabled") + } + } + netw, host, err := manet.DialArgs(addr) if err != nil { return nil, err @@ -98,7 +114,7 @@ func (c *ConnManager) ListenQUIC(addr ma.Multiaddr, tlsConf *tls.Config, allowWi if err != nil { return nil, err } - ln, err := newQuicListener(tr, c.serverConfig) + ln, err := newQuicListener(tr, c.serverConfig, c.enableDraft29) if err != nil { return nil, err } @@ -140,18 +156,15 @@ func (c *ConnManager) transportForListen(network string, laddr *net.UDPAddr) (re return reuse.TransportForListen(network, laddr) } - conn, err := net.ListenUDP(network, laddr) + conn, err := listenAndOptimize(network, laddr) if err != nil { return nil, err } - return &singleOwnerTransport{ - packetConn: conn, - Transport: quic.Transport{ - Conn: conn, - StatelessResetKey: &c.srk, - TokenGeneratorKey: &c.tokenKey, - }, - }, nil + tr := &singleOwnerTransport{Transport: quic.Transport{Conn: conn, StatelessResetKey: &c.srk}, packetConn: conn} + if c.mt != nil { + tr.Transport.Tracer = c.mt + } + return tr, nil } func (c *ConnManager) DialQUIC(ctx context.Context, raddr ma.Multiaddr, tlsConf *tls.Config, allowWindowIncrease func(conn quic.Connection, delta uint64) bool) (quic.Connection, error) { @@ -170,6 +183,8 @@ func (c *ConnManager) DialQUIC(ctx context.Context, raddr ma.Multiaddr, tlsConf if v == quic.Version1 { // The endpoint has explicit support for QUIC v1, so we'll only use that version. quicConf.Versions = []quic.VersionNumber{quic.Version1} + } else if v == quic.VersionDraft29 { + quicConf.Versions = []quic.VersionNumber{quic.VersionDraft29} } else { return nil, errors.New("unknown QUIC version") } @@ -202,14 +217,22 @@ func (c *ConnManager) TransportForDial(network string, raddr *net.UDPAddr) (refC case "udp6": laddr = &net.UDPAddr{IP: net.IPv6zero, Port: 0} } - conn, err := net.ListenUDP(network, laddr) + conn, err := listenAndOptimize(network, laddr) if err != nil { return nil, err } - return &singleOwnerTransport{Transport: quic.Transport{Conn: conn, StatelessResetKey: &c.srk}, packetConn: conn}, nil + tr := &singleOwnerTransport{Transport: quic.Transport{Conn: conn, StatelessResetKey: &c.srk}, packetConn: conn} + if c.mt != nil { + tr.Transport.Tracer = c.mt + } + + return tr, nil } func (c *ConnManager) Protocols() []int { + if c.enableDraft29 { + return []int{ma.P_QUIC, ma.P_QUIC_V1} + } return []int{ma.P_QUIC_V1} } @@ -222,3 +245,12 @@ func (c *ConnManager) Close() error { } return c.reuseUDP4.Close() } + +// listenAndOptimize same as net.ListenUDP, but also calls quic.OptimizeConn +func listenAndOptimize(network string, laddr *net.UDPAddr) (net.PacketConn, error) { + conn, err := net.ListenUDP(network, laddr) + if err != nil { + return nil, err + } + return quic.OptimizeConn(conn) +} diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/listener.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/listener.go index 4ee20042d..50b793451 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/listener.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/listener.go @@ -38,13 +38,20 @@ type quicListener struct { protocols map[string]protoConf } -func newQuicListener(tr refCountedQuicTransport, quicConfig *quic.Config) (*quicListener, error) { +func newQuicListener(tr refCountedQuicTransport, quicConfig *quic.Config, enableDraft29 bool) (*quicListener, error) { localMultiaddrs := make([]ma.Multiaddr, 0, 2) a, err := ToQuicMultiaddr(tr.LocalAddr(), quic.Version1) if err != nil { return nil, err } localMultiaddrs = append(localMultiaddrs, a) + if enableDraft29 { + a, err := ToQuicMultiaddr(tr.LocalAddr(), quic.VersionDraft29) + if err != nil { + return nil, err + } + localMultiaddrs = append(localMultiaddrs, a) + } cl := &quicListener{ protocols: map[string]protoConf{}, running: make(chan struct{}), @@ -52,7 +59,6 @@ func newQuicListener(tr refCountedQuicTransport, quicConfig *quic.Config) (*quic addrs: localMultiaddrs, } tlsConf := &tls.Config{ - SessionTicketsDisabled: true, // This is set for the config for client, but we set it here as well: https://github.com/quic-go/quic-go/issues/4029 GetConfigForClient: func(info *tls.ClientHelloInfo) (*tls.Config, error) { cl.protocolsMu.Lock() defer cl.protocolsMu.Unlock() @@ -83,7 +89,7 @@ func (l *quicListener) allowWindowIncrease(conn quic.Connection, delta uint64) b l.protocolsMu.Lock() defer l.protocolsMu.Unlock() - conf, ok := l.protocols[conn.ConnectionState().TLS.NegotiatedProtocol] + conf, ok := l.protocols[conn.ConnectionState().TLS.ConnectionState.NegotiatedProtocol] if !ok { return false } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/options.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/options.go index c32506920..a700a0544 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/options.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/options.go @@ -9,6 +9,16 @@ func DisableReuseport() Option { } } +// DisableDraft29 disables support for QUIC draft-29. +// This option should be set, unless support for this legacy QUIC version is needed for backwards compatibility. +// Support for QUIC draft-29 is already deprecated and will be removed in the future, see https://github.com/libp2p/go-libp2p/issues/1841. +func DisableDraft29() Option { + return func(m *ConnManager) error { + m.enableDraft29 = false + return nil + } +} + // EnableMetrics enables Prometheus metrics collection. func EnableMetrics() Option { return func(m *ConnManager) error { diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/quic_multiaddr.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/quic_multiaddr.go index 3da4721b5..12eb7d8ab 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/quic_multiaddr.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/quic_multiaddr.go @@ -10,7 +10,8 @@ import ( ) var ( - quicV1MA = ma.StringCast("/quic-v1") + quicV1MA = ma.StringCast("/quic-v1") + quicDraft29MA = ma.StringCast("/quic") ) func ToQuicMultiaddr(na net.Addr, version quic.VersionNumber) (ma.Multiaddr, error) { @@ -19,6 +20,8 @@ func ToQuicMultiaddr(na net.Addr, version quic.VersionNumber) (ma.Multiaddr, err return nil, err } switch version { + case quic.VersionDraft29: + return udpMA.Encapsulate(quicDraft29MA), nil case quic.Version1: return udpMA.Encapsulate(quicV1MA), nil default: @@ -31,6 +34,9 @@ func FromQuicMultiaddr(addr ma.Multiaddr) (*net.UDPAddr, quic.VersionNumber, err var partsBeforeQUIC []ma.Multiaddr ma.ForEach(addr, func(c ma.Component) bool { switch c.Protocol().Code { + case ma.P_QUIC: + version = quic.VersionDraft29 + return false case ma.P_QUIC_V1: version = quic.Version1 return false diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/reuse.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/reuse.go index dc2b33b85..1584b2925 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/reuse.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/reuse.go @@ -51,7 +51,8 @@ func (c *singleOwnerTransport) Close() error { } func (c *singleOwnerTransport) WriteTo(b []byte, addr net.Addr) (int, error) { - return c.Transport.WriteTo(b, addr) + // Safe because we called quic.OptimizeConn ourselves. + return c.packetConn.WriteTo(b, addr) } // Constant. Defined as variables to simplify testing. @@ -85,7 +86,8 @@ func (c *refcountedTransport) Close() error { } func (c *refcountedTransport) WriteTo(b []byte, addr net.Addr) (int, error) { - return c.Transport.WriteTo(b, addr) + // Safe because we called quic.OptimizeConn ourselves. + return c.packetConn.WriteTo(b, addr) } func (c *refcountedTransport) LocalAddr() net.Addr { @@ -123,10 +125,10 @@ type reuse struct { globalDialers map[int]*refcountedTransport statelessResetKey *quic.StatelessResetKey - tokenGeneratorKey *quic.TokenGeneratorKey + metricsTracer *metricsTracer } -func newReuse(srk *quic.StatelessResetKey, tokenKey *quic.TokenGeneratorKey) *reuse { +func newReuse(srk *quic.StatelessResetKey, mt *metricsTracer) *reuse { r := &reuse{ unicast: make(map[string]map[int]*refcountedTransport), globalListeners: make(map[int]*refcountedTransport), @@ -134,7 +136,7 @@ func newReuse(srk *quic.StatelessResetKey, tokenKey *quic.TokenGeneratorKey) *re closeChan: make(chan struct{}), gcStopChan: make(chan struct{}), statelessResetKey: srk, - tokenGeneratorKey: tokenKey, + metricsTracer: mt, } go r.gc() return r @@ -263,15 +265,17 @@ func (r *reuse) transportForDialLocked(network string, source *net.IP) (*refcoun case "udp6": addr = &net.UDPAddr{IP: net.IPv6zero, Port: 0} } - conn, err := net.ListenUDP(network, addr) + conn, err := listenAndOptimize(network, addr) if err != nil { return nil, err } tr := &refcountedTransport{Transport: quic.Transport{ Conn: conn, StatelessResetKey: r.statelessResetKey, - TokenGeneratorKey: r.tokenGeneratorKey, }, packetConn: conn} + if r.metricsTracer != nil { + tr.Transport.Tracer = r.metricsTracer + } r.globalDialers[conn.LocalAddr().(*net.UDPAddr).Port] = tr return tr, nil } @@ -310,18 +314,19 @@ func (r *reuse) TransportForListen(network string, laddr *net.UDPAddr) (*refcoun } } - conn, err := net.ListenUDP(network, laddr) + conn, err := listenAndOptimize(network, laddr) if err != nil { return nil, err } localAddr := conn.LocalAddr().(*net.UDPAddr) - tr := &refcountedTransport{ - Transport: quic.Transport{ - Conn: conn, - StatelessResetKey: r.statelessResetKey, - }, - packetConn: conn, + tr := &refcountedTransport{Transport: quic.Transport{ + Conn: conn, + StatelessResetKey: r.statelessResetKey, + }, packetConn: conn} + if r.metricsTracer != nil { + tr.Transport.Tracer = r.metricsTracer } + tr.IncreaseCount() // Deal with listen on a global address diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/tracer.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/tracer.go index 16c7dce4f..1386a5c3d 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/tracer.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/tracer.go @@ -24,7 +24,7 @@ func init() { qlogTracerDir = os.Getenv("QLOGDIR") } -func qloggerForDir(qlogDir string, p logging.Perspective, ci quic.ConnectionID) *logging.ConnectionTracer { +func qloggerForDir(qlogDir string, p logging.Perspective, ci quic.ConnectionID) logging.ConnectionTracer { // create the QLOGDIR, if it doesn't exist if err := os.MkdirAll(qlogDir, 0777); err != nil { log.Errorf("creating the QLOGDIR failed: %s", err) diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/tracer_metrics.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/tracer_metrics.go new file mode 100644 index 000000000..03e73fd25 --- /dev/null +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/quicreuse/tracer_metrics.go @@ -0,0 +1,372 @@ +package quicreuse + +import ( + "context" + "errors" + "fmt" + "net" + "sync" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/quic-go/quic-go" + "github.com/quic-go/quic-go/logging" +) + +var ( + bytesTransferred *prometheus.CounterVec + newConns *prometheus.CounterVec + closedConns *prometheus.CounterVec + sentPackets *prometheus.CounterVec + rcvdPackets *prometheus.CounterVec + bufferedPackets *prometheus.CounterVec + droppedPackets *prometheus.CounterVec + lostPackets *prometheus.CounterVec + connErrors *prometheus.CounterVec +) + +type aggregatingCollector struct { + mutex sync.Mutex + + conns map[string] /* conn ID */ *metricsConnTracer + rtts prometheus.Histogram + connDurations prometheus.Histogram +} + +func newAggregatingCollector() *aggregatingCollector { + return &aggregatingCollector{ + conns: make(map[string]*metricsConnTracer), + rtts: prometheus.NewHistogram(prometheus.HistogramOpts{ + Name: "quic_smoothed_rtt", + Help: "Smoothed RTT", + Buckets: prometheus.ExponentialBuckets(0.001, 1.25, 40), // 1ms to ~6000ms + }), + connDurations: prometheus.NewHistogram(prometheus.HistogramOpts{ + Name: "quic_connection_duration", + Help: "Connection Duration", + Buckets: prometheus.ExponentialBuckets(1, 1.5, 40), // 1s to ~12 weeks + }), + } +} + +var _ prometheus.Collector = &aggregatingCollector{} + +func (c *aggregatingCollector) Describe(descs chan<- *prometheus.Desc) { + descs <- c.rtts.Desc() + descs <- c.connDurations.Desc() +} + +func (c *aggregatingCollector) Collect(metrics chan<- prometheus.Metric) { + now := time.Now() + c.mutex.Lock() + for _, conn := range c.conns { + if rtt, valid := conn.getSmoothedRTT(); valid { + c.rtts.Observe(rtt.Seconds()) + } + c.connDurations.Observe(now.Sub(conn.startTime).Seconds()) + } + c.mutex.Unlock() + metrics <- c.rtts + metrics <- c.connDurations +} + +func (c *aggregatingCollector) AddConn(id string, t *metricsConnTracer) { + c.mutex.Lock() + c.conns[id] = t + c.mutex.Unlock() +} + +func (c *aggregatingCollector) RemoveConn(id string) { + c.mutex.Lock() + delete(c.conns, id) + c.mutex.Unlock() +} + +var collector *aggregatingCollector + +var initMetricsOnce sync.Once + +func initMetrics() { + const ( + direction = "direction" + encLevel = "encryption_level" + ) + + closedConns = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "quic_connections_closed_total", + Help: "closed QUIC connection", + }, + []string{direction}, + ) + prometheus.MustRegister(closedConns) + newConns = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "quic_connections_new_total", + Help: "new QUIC connection", + }, + []string{direction, "handshake_successful"}, + ) + prometheus.MustRegister(newConns) + bytesTransferred = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "quic_transferred_bytes", + Help: "QUIC bytes transferred", + }, + []string{direction}, // TODO: this is confusing. Other times, we use direction for the perspective + ) + prometheus.MustRegister(bytesTransferred) + sentPackets = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "quic_packets_sent_total", + Help: "QUIC packets sent", + }, + []string{encLevel}, + ) + prometheus.MustRegister(sentPackets) + rcvdPackets = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "quic_packets_rcvd_total", + Help: "QUIC packets received", + }, + []string{encLevel}, + ) + prometheus.MustRegister(rcvdPackets) + bufferedPackets = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "quic_packets_buffered_total", + Help: "Buffered packets", + }, + []string{"packet_type"}, + ) + prometheus.MustRegister(bufferedPackets) + droppedPackets = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "quic_packets_dropped_total", + Help: "Dropped packets", + }, + []string{"packet_type", "reason"}, + ) + prometheus.MustRegister(droppedPackets) + connErrors = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "quic_connection_errors_total", + Help: "QUIC connection errors", + }, + []string{"side", "error_code"}, + ) + prometheus.MustRegister(connErrors) + lostPackets = prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "quic_packets_lost_total", + Help: "QUIC lost received", + }, + []string{encLevel, "reason"}, + ) + prometheus.MustRegister(lostPackets) + collector = newAggregatingCollector() + prometheus.MustRegister(collector) +} + +type metricsTracer struct { + logging.NullTracer +} + +var _ logging.Tracer = &metricsTracer{} + +func newMetricsTracer() *metricsTracer { + initMetricsOnce.Do(func() { initMetrics() }) + return &metricsTracer{} +} + +func (m *metricsTracer) TracerForConnection(_ context.Context, p logging.Perspective, connID logging.ConnectionID) logging.ConnectionTracer { + return &metricsConnTracer{perspective: p, connID: connID} +} + +func (m *metricsTracer) SentPacket(_ net.Addr, _ *logging.Header, size logging.ByteCount, _ []logging.Frame) { + bytesTransferred.WithLabelValues("sent").Add(float64(size)) +} + +type metricsConnTracer struct { + logging.NullConnectionTracer + + perspective logging.Perspective + startTime time.Time + connID logging.ConnectionID + handshakeComplete bool + + mutex sync.Mutex + numRTTMeasurements int + rtt time.Duration +} + +var _ logging.ConnectionTracer = &metricsConnTracer{} + +func (m *metricsConnTracer) getDirection() string { + if m.perspective == logging.PerspectiveClient { + return "outgoing" + } + return "incoming" +} + +func (m *metricsConnTracer) getEncLevel(packetType logging.PacketType) string { + switch packetType { + case logging.PacketType0RTT: + return "0-RTT" + case logging.PacketTypeInitial: + return "Initial" + case logging.PacketTypeHandshake: + return "Handshake" + case logging.PacketTypeRetry: + return "Retry" + case logging.PacketType1RTT: + return "1-RTT" + default: + return "unknown" + } +} + +func (m *metricsConnTracer) StartedConnection(net.Addr, net.Addr, logging.ConnectionID, logging.ConnectionID) { + m.startTime = time.Now() + collector.AddConn(m.connID.String(), m) +} + +func (m *metricsConnTracer) ClosedConnection(e error) { + var ( + applicationErr *quic.ApplicationError + transportErr *quic.TransportError + statelessResetErr *quic.StatelessResetError + vnErr *quic.VersionNegotiationError + idleTimeoutErr *quic.IdleTimeoutError + handshakeTimeoutErr *quic.HandshakeTimeoutError + remote bool + desc string + ) + + switch { + case errors.As(e, &applicationErr): + return + case errors.As(e, &transportErr): + remote = transportErr.Remote + desc = transportErr.ErrorCode.String() + case errors.As(e, &statelessResetErr): + remote = true + desc = "stateless_reset" + case errors.As(e, &vnErr): + desc = "version_negotiation" + case errors.As(e, &idleTimeoutErr): + desc = "idle_timeout" + case errors.As(e, &handshakeTimeoutErr): + desc = "handshake_timeout" + default: + desc = fmt.Sprintf("unknown error: %v", e) + } + + side := "local" + if remote { + side = "remote" + } + connErrors.WithLabelValues(side, desc).Inc() +} +func (m *metricsConnTracer) SentPacket(hdr *logging.ExtendedHeader, size logging.ByteCount, _ *logging.AckFrame, _ []logging.Frame) { + bytesTransferred.WithLabelValues("sent").Add(float64(size)) + sentPackets.WithLabelValues(m.getEncLevel(logging.PacketTypeFromHeader(&hdr.Header))).Inc() +} + +func (m *metricsConnTracer) ReceivedVersionNegotiationPacket(dst, src logging.ArbitraryLenConnectionID, v []logging.VersionNumber) { + bytesTransferred.WithLabelValues("rcvd").Add(1 /* header form byte */ + 4 /* version number */ + 2 /* src and dest conn id length fields */ + float64(dst.Len()+src.Len()) + float64(4*len(v))) + rcvdPackets.WithLabelValues("Version Negotiation").Inc() +} + +func (m *metricsConnTracer) ReceivedRetry(*logging.Header) { + rcvdPackets.WithLabelValues("Retry").Inc() +} + +func (m *metricsConnTracer) ReceivedPacket(hdr *logging.ExtendedHeader, size logging.ByteCount, _ []logging.Frame) { + bytesTransferred.WithLabelValues("rcvd").Add(float64(size)) + rcvdPackets.WithLabelValues(m.getEncLevel(logging.PacketTypeFromHeader(&hdr.Header))).Inc() +} + +func (m *metricsConnTracer) BufferedPacket(packetType logging.PacketType, _ logging.ByteCount) { + bufferedPackets.WithLabelValues(m.getEncLevel(packetType)).Inc() +} + +func (m *metricsConnTracer) DroppedPacket(packetType logging.PacketType, size logging.ByteCount, r logging.PacketDropReason) { + bytesTransferred.WithLabelValues("rcvd").Add(float64(size)) + var reason string + switch r { + case logging.PacketDropKeyUnavailable: + reason = "key_unavailable" + case logging.PacketDropUnknownConnectionID: + reason = "unknown_connection_id" + case logging.PacketDropHeaderParseError: + reason = "header_parse_error" + case logging.PacketDropPayloadDecryptError: + reason = "payload_decrypt_error" + case logging.PacketDropProtocolViolation: + reason = "protocol_violation" + case logging.PacketDropDOSPrevention: + reason = "dos_prevention" + case logging.PacketDropUnsupportedVersion: + reason = "unsupported_version" + case logging.PacketDropUnexpectedPacket: + reason = "unexpected_packet" + case logging.PacketDropUnexpectedSourceConnectionID: + reason = "unexpected_source_connection_id" + case logging.PacketDropUnexpectedVersion: + reason = "unexpected_version" + case logging.PacketDropDuplicate: + reason = "duplicate" + default: + reason = "unknown" + } + droppedPackets.WithLabelValues(m.getEncLevel(packetType), reason).Inc() +} + +func (m *metricsConnTracer) UpdatedMetrics(rttStats *logging.RTTStats, cwnd, bytesInFlight logging.ByteCount, packetsInFlight int) { + m.mutex.Lock() + m.rtt = rttStats.SmoothedRTT() + m.numRTTMeasurements++ + m.mutex.Unlock() +} + +func (m *metricsConnTracer) LostPacket(level logging.EncryptionLevel, _ logging.PacketNumber, r logging.PacketLossReason) { + var reason string + switch r { + case logging.PacketLossReorderingThreshold: + reason = "reordering_threshold" + case logging.PacketLossTimeThreshold: + reason = "time_threshold" + default: + reason = "unknown" + } + lostPackets.WithLabelValues(level.String(), reason).Inc() +} + +func (m *metricsConnTracer) DroppedEncryptionLevel(level logging.EncryptionLevel) { + if level == logging.EncryptionHandshake { + m.handleHandshakeComplete() + } +} + +func (m *metricsConnTracer) Close() { + if m.handshakeComplete { + closedConns.WithLabelValues(m.getDirection()).Inc() + } else { + newConns.WithLabelValues(m.getDirection(), "false").Inc() + } + collector.RemoveConn(m.connID.String()) +} + +func (m *metricsConnTracer) handleHandshakeComplete() { + m.handshakeComplete = true + newConns.WithLabelValues(m.getDirection(), "true").Inc() +} + +func (m *metricsConnTracer) getSmoothedRTT() (rtt time.Duration, valid bool) { + m.mutex.Lock() + rtt = m.rtt + valid = m.numRTTMeasurements > 10 + m.mutex.Unlock() + return +} diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics.go index 8e7308f3a..fc2add49b 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics.go @@ -1,4 +1,4 @@ -//go:build !windows && !riscv64 +//go:build !windows package tcp diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics_general.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics_general.go index e9868609f..6b6728344 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics_general.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics_general.go @@ -1,4 +1,4 @@ -//go:build !linux && !darwin && !windows && !riscv64 +//go:build !linux && !darwin && !windows package tcp diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics_none.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics_windows.go similarity index 71% rename from vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics_none.go rename to vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics_windows.go index 01cf3e9c5..7142e7dbe 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics_none.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/metrics_windows.go @@ -1,6 +1,4 @@ -// riscv64 see: https://github.com/marten-seemann/tcp/pull/1 - -//go:build windows || riscv64 +//go:build windows package tcp diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/tcp.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/tcp.go index d52bb9601..f277b3f8f 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/tcp.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/tcp/tcp.go @@ -131,7 +131,6 @@ type TcpTransport struct { } var _ transport.Transport = &TcpTransport{} -var _ transport.DialUpdater = &TcpTransport{} // NewTCPTransport creates a tcp transport object that tracks dialers and listeners // created. It represents an entire TCP stack (though it might not necessarily be). @@ -177,17 +176,13 @@ func (t *TcpTransport) maDial(ctx context.Context, raddr ma.Multiaddr) (manet.Co // Dial dials the peer at the remote address. func (t *TcpTransport) Dial(ctx context.Context, raddr ma.Multiaddr, p peer.ID) (transport.CapableConn, error) { - return t.DialWithUpdates(ctx, raddr, p, nil) -} - -func (t *TcpTransport) DialWithUpdates(ctx context.Context, raddr ma.Multiaddr, p peer.ID, updateChan chan<- transport.DialUpdate) (transport.CapableConn, error) { connScope, err := t.rcmgr.OpenConnection(network.DirOutbound, true, raddr) if err != nil { log.Debugw("resource manager blocked outgoing connection", "peer", p, "addr", raddr, "error", err) return nil, err } - c, err := t.dialWithScope(ctx, raddr, p, connScope, updateChan) + c, err := t.dialWithScope(ctx, raddr, p, connScope) if err != nil { connScope.Done() return nil, err @@ -195,7 +190,7 @@ func (t *TcpTransport) DialWithUpdates(ctx context.Context, raddr ma.Multiaddr, return c, nil } -func (t *TcpTransport) dialWithScope(ctx context.Context, raddr ma.Multiaddr, p peer.ID, connScope network.ConnManagementScope, updateChan chan<- transport.DialUpdate) (transport.CapableConn, error) { +func (t *TcpTransport) dialWithScope(ctx context.Context, raddr ma.Multiaddr, p peer.ID, connScope network.ConnManagementScope) (transport.CapableConn, error) { if err := connScope.SetPeer(p); err != nil { log.Debugw("resource manager blocked outgoing connection for peer", "peer", p, "addr", raddr, "error", err) return nil, err @@ -217,13 +212,6 @@ func (t *TcpTransport) dialWithScope(ctx context.Context, raddr ma.Multiaddr, p return nil, err } } - if updateChan != nil { - select { - case updateChan <- transport.DialUpdate{Kind: transport.UpdateKindHandshakeProgressed, Addr: raddr}: - default: - // It is better to skip the update than to delay upgrading the connection - } - } direction := network.DirOutbound if ok, isClient, _ := network.GetSimultaneousConnect(ctx); ok && !isClient { direction = network.DirInbound diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/websocket/websocket.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/websocket/websocket.go index 5142ca97a..e1965123d 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/websocket/websocket.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/websocket/websocket.go @@ -120,7 +120,7 @@ func (t *WebsocketTransport) Proxy() bool { return false } -func (t *WebsocketTransport) Resolve(_ context.Context, maddr ma.Multiaddr) ([]ma.Multiaddr, error) { +func (t *WebsocketTransport) Resolve(ctx context.Context, maddr ma.Multiaddr) ([]ma.Multiaddr, error) { parsed, err := parseWebsocketMultiaddr(maddr) if err != nil { return nil, err @@ -136,7 +136,7 @@ func (t *WebsocketTransport) Resolve(_ context.Context, maddr ma.Multiaddr) ([]m // We don't have an sni component, we'll use dns/dnsaddr ma.ForEach(parsed.restMultiaddr, func(c ma.Component) bool { switch c.Protocol().Code { - case ma.P_DNS, ma.P_DNS4, ma.P_DNS6: + case ma.P_DNS, ma.P_DNS4, ma.P_DNS6, ma.P_DNSADDR: // err shouldn't happen since this means we couldn't parse a dns hostname for an sni value. parsed.sni, err = ma.NewComponent("sni", c.Value()) return false diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/multiaddr.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/multiaddr.go index bd90638b6..d6930af36 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/multiaddr.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/multiaddr.go @@ -89,23 +89,17 @@ func IsWebtransportMultiaddr(multiaddr ma.Multiaddr) (bool, int) { certhashCount := 0 ma.ForEach(multiaddr, func(c ma.Component) bool { - switch c.Protocol().Code { - case ma.P_UDP: - if state == init { - state = foundUDP - } - case ma.P_QUIC_V1: - if state == foundUDP { - state = foundQuicV1 - } - case ma.P_WEBTRANSPORT: - if state == foundQuicV1 { - state = foundWebTransport - } - case ma.P_CERTHASH: - if state == foundWebTransport { - certhashCount++ - } + if c.Protocol().Code == ma.P_QUIC_V1 && state == init { + state = foundUDP + } + if c.Protocol().Code == ma.P_QUIC_V1 && state == foundUDP { + state = foundQuicV1 + } + if c.Protocol().Code == ma.P_WEBTRANSPORT && state == foundQuicV1 { + state = foundWebTransport + } + if c.Protocol().Code == ma.P_CERTHASH && state == foundWebTransport { + certhashCount++ } return true }) diff --git a/vendor/github.com/libp2p/go-libp2p/package-list.json b/vendor/github.com/libp2p/go-libp2p/package-list.json new file mode 100644 index 000000000..fec3fac19 --- /dev/null +++ b/vendor/github.com/libp2p/go-libp2p/package-list.json @@ -0,0 +1,82 @@ +{ + "columns": [ + "Name", + "CI/Travis", + "Coverage", + "Description" + ], + "rows": [ + "Libp2p", + ["libp2p/go-libp2p", "go-libp2p", "go-libp2p entry point"], + ["libp2p/go-libp2p-core", "go-libp2p-core", "core interfaces, types, and abstractions"], + ["libp2p/go-libp2p-blankhost", "go-libp2p-blankhost", "minimal implementation of the \"host\" interface"], + + "Network", + ["libp2p/go-libp2p-swarm", "go-libp2p-swarm", "reference implementation of network state machine"], + + "Transport", + ["libp2p/go-ws-transport", "go-ws-transport", "WebSocket transport"], + ["libp2p/go-tcp-transport", "go-tcp-transport", "TCP transport"], + ["libp2p/go-libp2p-quic-transport", "go-libp2p-quic-transport", "QUIC transport"], + ["libp2p/go-udp-transport", "go-udp-transport", "UDP transport"], + ["libp2p/go-utp-transport", "go-utp-transport", "uTorrent transport (UTP)"], + ["libp2p/go-libp2p-circuit", "go-libp2p-circuit", "relay transport"], + ["libp2p/go-libp2p-transport-upgrader", "go-libp2p-transport-upgrader", "upgrades multiaddr-net connections into full libp2p transports"], + ["libp2p/go-libp2p-reuseport-transport", "go-libp2p-reuseport-transport", "partial transport for building transports that reuse ports"], + + "Encrypted Channels", + ["libp2p/go-libp2p-secio", "go-libp2p-secio", "SecIO crypto channel"], + ["libp2p/go-libp2p-tls-transport", "go-libp2p-tls-transport", "TLS 1.3+ crypto channel"], + ["libp2p/go-conn-security-multistream", "go-conn-security-multistream", "multistream multiplexed meta crypto channel"], + + "Private Network", + ["libp2p/go-libp2p-pnet", "go-libp2p-pnet", "reference private networking implementation"], + + "Stream Muxers", + ["libp2p/go-libp2p-yamux", "go-libp2p-yamux", "YAMUX stream multiplexer"], + ["libp2p/go-libp2p-mplex", "go-libp2p-mplex", "MPLEX stream multiplexer"], + + "NAT Traversal", + ["libp2p/go-libp2p-nat", "go-libp2p-nat"], + + "Peerstore", + ["libp2p/go-libp2p-peerstore", "go-libp2p-peerstore", "reference implementation of peer metadata storage component"], + + "Connection Manager", + ["libp2p/go-libp2p-connmgr", "go-libp2p-connmgr", "reference implementation of connection manager"], + + "Routing", + ["libp2p/go-libp2p-record", "go-libp2p-record", "record type and validator logic"], + ["libp2p/go-libp2p-kad-dht", "go-libp2p-kad-dht", "Kademlia-like router"], + ["libp2p/go-libp2p-kbucket", "go-libp2p-kbucket", "Kademlia routing table helper types"], + ["libp2p/go-libp2p-coral-dht", "go-libp2p-coral-dht", "Router based on Coral DHT"], + ["libp2p/go-libp2p-pubsub-router", "go-libp2p-pubsub-router", "record-store over pubsub adapter"], + + "Consensus", + ["libp2p/go-libp2p-consensus", "go-libp2p-consensus", "consensus protocols interfaces"], + ["libp2p/go-libp2p-raft", "go-libp2p-raft", "consensus implementation over raft"], + + "Pubsub", + ["libp2p/go-libp2p-pubsub", "go-libp2p-pubsub", "multiple pubsub over libp2p implementations"], + + "RPC", + ["libp2p/go-libp2p-gorpc", "go-libp2p-gorpc", "a simple RPC library for libp2p"], + + "Utilities/miscellaneous", + ["libp2p/go-libp2p-loggables", "go-libp2p-loggables", "logging helpers"], + ["libp2p/go-maddr-filter", "go-maddr-filter", "multiaddr filtering helpers"], + ["libp2p/go-libp2p-netutil", "go-libp2p-netutil", "misc utilities"], + ["libp2p/go-msgio", "go-msgio", "length prefixed data channel"], + ["libp2p/go-addr-util", "go-addr-util", "address utilities for libp2p swarm"], + ["libp2p/go-buffer-pool", "go-buffer-pool", "a variable size buffer pool for go"], + ["libp2p/go-libp2p-routing-helpers", "go-libp2p-routing-helpers", "routing helpers"], + ["libp2p/go-reuseport", "go-reuseport", "enables reuse of addresses"], + ["libp2p/go-sockaddr", "go-sockaddr", "utils for sockaddr conversions"], + ["libp2p/go-flow-metrics", "go-flow-metrics", "metrics library"], + ["libp2p/go-libp2p-gostream", "go-libp2p-gostream", "Go 'net' wrappers for libp2p"], + ["libp2p/go-libp2p-http", "go-libp2p-http", "HTTP on top of libp2p streams"], + + "Testing and examples", + ["libp2p/go-libp2p-testing", "go-libp2p-testing", "a collection of testing utilities for libp2p"] + ] +} diff --git a/vendor/github.com/libp2p/go-libp2p/tools.go b/vendor/github.com/libp2p/go-libp2p/tools.go index 7a650d9c1..46a8037df 100644 --- a/vendor/github.com/libp2p/go-libp2p/tools.go +++ b/vendor/github.com/libp2p/go-libp2p/tools.go @@ -3,7 +3,7 @@ package libp2p import ( - _ "go.uber.org/mock/mockgen" + _ "github.com/golang/mock/mockgen" _ "golang.org/x/tools/cmd/goimports" _ "google.golang.org/protobuf/cmd/protoc-gen-go" ) diff --git a/vendor/github.com/libp2p/go-libp2p/version.json b/vendor/github.com/libp2p/go-libp2p/version.json index 7b5ac4c94..462969c8e 100644 --- a/vendor/github.com/libp2p/go-libp2p/version.json +++ b/vendor/github.com/libp2p/go-libp2p/version.json @@ -1,3 +1,3 @@ { - "version": "v0.32.2" + "version": "v0.29.2" } diff --git a/vendor/github.com/libp2p/go-reuseport/control_freebsd.go b/vendor/github.com/libp2p/go-reuseport/control_freebsd.go deleted file mode 100644 index cec1b11aa..000000000 --- a/vendor/github.com/libp2p/go-reuseport/control_freebsd.go +++ /dev/null @@ -1,27 +0,0 @@ -//go:build freebsd - -package reuseport - -import ( - "syscall" - - "golang.org/x/sys/unix" -) - -func Control(network, address string, c syscall.RawConn) (err error) { - controlErr := c.Control(func(fd uintptr) { - err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1) - if err != nil { - return - } - err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1) - if err != nil { - return - } - err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT_LB, 1) - }) - if controlErr != nil { - err = controlErr - } - return -} diff --git a/vendor/github.com/libp2p/go-reuseport/control_unix.go b/vendor/github.com/libp2p/go-reuseport/control_unix.go index e80688b5e..4197d1f74 100644 --- a/vendor/github.com/libp2p/go-reuseport/control_unix.go +++ b/vendor/github.com/libp2p/go-reuseport/control_unix.go @@ -1,4 +1,4 @@ -//go:build !plan9 && !windows && !wasm && !freebsd +//go:build !plan9 && !windows && !wasm package reuseport diff --git a/vendor/github.com/libp2p/go-reuseport/version.json b/vendor/github.com/libp2p/go-reuseport/version.json index 372b6eab3..a654d65ab 100644 --- a/vendor/github.com/libp2p/go-reuseport/version.json +++ b/vendor/github.com/libp2p/go-reuseport/version.json @@ -1,3 +1,3 @@ { - "version": "v0.4.0" + "version": "v0.3.0" } diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go index d0ea68f40..d569c0c94 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_bsd.go +++ b/vendor/github.com/mattn/go-isatty/isatty_bsd.go @@ -1,7 +1,6 @@ -//go:build (darwin || freebsd || openbsd || netbsd || dragonfly || hurd) && !appengine && !tinygo +//go:build (darwin || freebsd || openbsd || netbsd || dragonfly || hurd) && !appengine // +build darwin freebsd openbsd netbsd dragonfly hurd // +build !appengine -// +build !tinygo package isatty diff --git a/vendor/github.com/mattn/go-isatty/isatty_others.go b/vendor/github.com/mattn/go-isatty/isatty_others.go index 7402e0618..31503226f 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_others.go +++ b/vendor/github.com/mattn/go-isatty/isatty_others.go @@ -1,6 +1,5 @@ -//go:build (appengine || js || nacl || tinygo || wasm) && !windows -// +build appengine js nacl tinygo wasm -// +build !windows +//go:build appengine || js || nacl || wasm +// +build appengine js nacl wasm package isatty diff --git a/vendor/github.com/mattn/go-isatty/isatty_tcgets.go b/vendor/github.com/mattn/go-isatty/isatty_tcgets.go index 0337d8cf6..67787657f 100644 --- a/vendor/github.com/mattn/go-isatty/isatty_tcgets.go +++ b/vendor/github.com/mattn/go-isatty/isatty_tcgets.go @@ -1,7 +1,6 @@ -//go:build (linux || aix || zos) && !appengine && !tinygo +//go:build (linux || aix || zos) && !appengine // +build linux aix zos // +build !appengine -// +build !tinygo package isatty diff --git a/vendor/github.com/miekg/dns/README.md b/vendor/github.com/miekg/dns/README.md index 95bc08d5c..06bea9fab 100644 --- a/vendor/github.com/miekg/dns/README.md +++ b/vendor/github.com/miekg/dns/README.md @@ -81,7 +81,6 @@ A not-so-up-to-date-list-that-may-be-actually-current: * https://addr.tools/ * https://dnscheck.tools/ * https://github.com/egbakou/domainverifier -* https://github.com/semihalev/sdns Send pull request if you want to be listed here. diff --git a/vendor/github.com/miekg/dns/defaults.go b/vendor/github.com/miekg/dns/defaults.go index 6d7e17605..c1558b79c 100644 --- a/vendor/github.com/miekg/dns/defaults.go +++ b/vendor/github.com/miekg/dns/defaults.go @@ -5,7 +5,6 @@ import ( "net" "strconv" "strings" - "unicode" ) const hexDigit = "0123456789abcdef" @@ -331,18 +330,8 @@ func Fqdn(s string) string { // CanonicalName returns the domain name in canonical form. A name in canonical // form is lowercase and fully qualified. See Section 6.2 in RFC 4034. -// According to the RFC all uppercase US-ASCII letters in the owner name of the -// RR areeplaced by the corresponding lowercase US-ASCII letters. func CanonicalName(s string) string { - var result strings.Builder - for _, ch := range s { - if unicode.IsUpper(ch) && (ch >= 0x00 && ch <= 0x7F) { - result.WriteRune(unicode.ToLower(ch)) - } else { - result.WriteRune(ch) - } - } - return Fqdn(result.String()) + return strings.ToLower(Fqdn(s)) } // Copied from the official Go code. diff --git a/vendor/github.com/miekg/dns/msg.go b/vendor/github.com/miekg/dns/msg.go index b05cf14e9..d5049a4f9 100644 --- a/vendor/github.com/miekg/dns/msg.go +++ b/vendor/github.com/miekg/dns/msg.go @@ -896,38 +896,23 @@ func (dns *Msg) String() string { return " MsgHdr" } s := dns.MsgHdr.String() + " " - if dns.MsgHdr.Opcode == OpcodeUpdate { - s += "ZONE: " + strconv.Itoa(len(dns.Question)) + ", " - s += "PREREQ: " + strconv.Itoa(len(dns.Answer)) + ", " - s += "UPDATE: " + strconv.Itoa(len(dns.Ns)) + ", " - s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n" - } else { - s += "QUERY: " + strconv.Itoa(len(dns.Question)) + ", " - s += "ANSWER: " + strconv.Itoa(len(dns.Answer)) + ", " - s += "AUTHORITY: " + strconv.Itoa(len(dns.Ns)) + ", " - s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n" - } + s += "QUERY: " + strconv.Itoa(len(dns.Question)) + ", " + s += "ANSWER: " + strconv.Itoa(len(dns.Answer)) + ", " + s += "AUTHORITY: " + strconv.Itoa(len(dns.Ns)) + ", " + s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n" opt := dns.IsEdns0() if opt != nil { // OPT PSEUDOSECTION s += opt.String() + "\n" } if len(dns.Question) > 0 { - if dns.MsgHdr.Opcode == OpcodeUpdate { - s += "\n;; ZONE SECTION:\n" - } else { - s += "\n;; QUESTION SECTION:\n" - } + s += "\n;; QUESTION SECTION:\n" for _, r := range dns.Question { s += r.String() + "\n" } } if len(dns.Answer) > 0 { - if dns.MsgHdr.Opcode == OpcodeUpdate { - s += "\n;; PREREQUISITE SECTION:\n" - } else { - s += "\n;; ANSWER SECTION:\n" - } + s += "\n;; ANSWER SECTION:\n" for _, r := range dns.Answer { if r != nil { s += r.String() + "\n" @@ -935,11 +920,7 @@ func (dns *Msg) String() string { } } if len(dns.Ns) > 0 { - if dns.MsgHdr.Opcode == OpcodeUpdate { - s += "\n;; UPDATE SECTION:\n" - } else { - s += "\n;; AUTHORITY SECTION:\n" - } + s += "\n;; AUTHORITY SECTION:\n" for _, r := range dns.Ns { if r != nil { s += r.String() + "\n" diff --git a/vendor/github.com/miekg/dns/types.go b/vendor/github.com/miekg/dns/types.go index c9a03dec6..03afeccda 100644 --- a/vendor/github.com/miekg/dns/types.go +++ b/vendor/github.com/miekg/dns/types.go @@ -236,9 +236,6 @@ var CertTypeToString = map[uint16]string{ CertOID: "OID", } -// Prefix for IPv4 encoded as IPv6 address -const ipv4InIPv6Prefix = "::ffff:" - //go:generate go run types_generate.go // Question holds a DNS question. Usually there is just one. While the @@ -754,11 +751,6 @@ func (rr *AAAA) String() string { if rr.AAAA == nil { return rr.Hdr.String() } - - if rr.AAAA.To4() != nil { - return rr.Hdr.String() + ipv4InIPv6Prefix + rr.AAAA.String() - } - return rr.Hdr.String() + rr.AAAA.String() } @@ -1525,7 +1517,7 @@ func (a *APLPrefix) str() string { case net.IPv6len: // add prefix for IPv4-mapped IPv6 if v4 := a.Network.IP.To4(); v4 != nil { - sb.WriteString(ipv4InIPv6Prefix) + sb.WriteString("::ffff:") } sb.WriteString(a.Network.IP.String()) } diff --git a/vendor/github.com/miekg/dns/version.go b/vendor/github.com/miekg/dns/version.go index a09113662..5891044a3 100644 --- a/vendor/github.com/miekg/dns/version.go +++ b/vendor/github.com/miekg/dns/version.go @@ -3,7 +3,7 @@ package dns import "fmt" // Version is current version of this library. -var Version = v{1, 1, 56} +var Version = v{1, 1, 55} // v holds the version of this library. type v struct { diff --git a/vendor/github.com/multiformats/go-multiaddr/multiaddr.go b/vendor/github.com/multiformats/go-multiaddr/multiaddr.go index af26d4486..7c567c9fd 100644 --- a/vendor/github.com/multiformats/go-multiaddr/multiaddr.go +++ b/vendor/github.com/multiformats/go-multiaddr/multiaddr.go @@ -220,7 +220,7 @@ func Unique(addrs []Multiaddr) []Multiaddr { return addrs } // Use the new slices package here, as the sort function doesn't allocate (sort.Slice does). - slices.SortFunc(addrs, func(a, b Multiaddr) int { return bytes.Compare(a.Bytes(), b.Bytes()) }) + slices.SortFunc(addrs, func(a, b Multiaddr) bool { return bytes.Compare(a.Bytes(), b.Bytes()) < 0 }) idx := 1 for i := 1; i < len(addrs); i++ { if !addrs[i-1].Equal(addrs[i]) { diff --git a/vendor/github.com/multiformats/go-multiaddr/net/private.go b/vendor/github.com/multiformats/go-multiaddr/net/private.go index 9f966de0f..ba57f00c3 100644 --- a/vendor/github.com/multiformats/go-multiaddr/net/private.go +++ b/vendor/github.com/multiformats/go-multiaddr/net/private.go @@ -2,7 +2,6 @@ package manet import ( "net" - "strings" ma "github.com/multiformats/go-multiaddr" ) @@ -47,36 +46,6 @@ var unroutableCIDR6 = []string{ "ff00::/8", } -// unResolvableDomains do not resolve to an IP address. -// Ref: https://en.wikipedia.org/wiki/Special-use_domain_name#Reserved_domain_names -var unResolvableDomains = []string{ - // Reverse DNS Lookup - ".in-addr.arpa", - ".ip6.arpa", - - // RFC 6761: Users MAY assume that queries for "invalid" names will always return NXDOMAIN - // responses - ".invalid", -} - -// privateUseDomains are reserved for private use and have no central authority for consistent -// address resolution -// Ref: https://en.wikipedia.org/wiki/Special-use_domain_name#Reserved_domain_names -var privateUseDomains = []string{ - // RFC 8375: Reserved for home networks - ".home.arpa", - - // MDNS - ".local", - - // RFC 6761: No central authority for .test names - ".test", -} - -// RFC 6761: Users may assume that IPv4 and IPv6 address queries for localhost names will -// always resolve to the respective IP loopback address -const localHostDomain = ".localhost" - func init() { Private4 = parseCIDR(privateCIDR4) Private6 = parseCIDR(privateCIDR6) @@ -96,8 +65,7 @@ func parseCIDR(cidrs []string) []*net.IPNet { return ipnets } -// IsPublicAddr returns true if the IP part of the multiaddr is a publicly routable address -// or if it's a dns address without a special use domain e.g. .local. +// IsPublicAddr retruns true if the IP part of the multiaddr is a publicly routable address func IsPublicAddr(a ma.Multiaddr) bool { isPublic := false ma.ForEach(a, func(c ma.Component) bool { @@ -110,38 +78,12 @@ func IsPublicAddr(a ma.Multiaddr) bool { case ma.P_IP6: ip := net.IP(c.RawValue()) isPublic = !inAddrRange(ip, Private6) && !inAddrRange(ip, Unroutable6) - case ma.P_DNS, ma.P_DNS4, ma.P_DNS6, ma.P_DNSADDR: - dnsAddr := c.Value() - isPublic = true - if isSubdomain(dnsAddr, localHostDomain) { - isPublic = false - return false - } - for _, ud := range unResolvableDomains { - if isSubdomain(dnsAddr, ud) { - isPublic = false - return false - } - } - for _, pd := range privateUseDomains { - if isSubdomain(dnsAddr, pd) { - isPublic = false - break - } - } } return false }) return isPublic } -// isSubdomain checks if child is sub domain of parent. It also returns true if child and parent are -// the same domain. -// Parent must have a "." prefix. -func isSubdomain(child, parent string) bool { - return strings.HasSuffix(child, parent) || child == parent[1:] -} - // IsPrivateAddr returns true if the IP part of the mutiaddr is in a private network func IsPrivateAddr(a ma.Multiaddr) bool { isPrivate := false @@ -153,13 +95,6 @@ func IsPrivateAddr(a ma.Multiaddr) bool { isPrivate = inAddrRange(net.IP(c.RawValue()), Private4) case ma.P_IP6: isPrivate = inAddrRange(net.IP(c.RawValue()), Private6) - case ma.P_DNS, ma.P_DNS4, ma.P_DNS6, ma.P_DNSADDR: - dnsAddr := c.Value() - if isSubdomain(dnsAddr, localHostDomain) { - isPrivate = true - } - // We don't check for privateUseDomains because private use domains can - // resolve to public IP addresses } return false }) diff --git a/vendor/github.com/multiformats/go-multiaddr/version.json b/vendor/github.com/multiformats/go-multiaddr/version.json index 21e148a94..b6bb0741a 100644 --- a/vendor/github.com/multiformats/go-multiaddr/version.json +++ b/vendor/github.com/multiformats/go-multiaddr/version.json @@ -1,3 +1,3 @@ { - "version": "v0.12.0" + "version": "v0.10.1" } diff --git a/vendor/github.com/multiformats/go-multistream/client.go b/vendor/github.com/multiformats/go-multistream/client.go index 25e81e2ac..013dd5abc 100644 --- a/vendor/github.com/multiformats/go-multistream/client.go +++ b/vendor/github.com/multiformats/go-multistream/client.go @@ -2,11 +2,15 @@ package multistream import ( "bytes" + "crypto/rand" + "encoding/binary" "errors" "fmt" "io" "os" "runtime/debug" + "strconv" + "strings" ) // ErrNotSupported is the error returned when the muxer doesn't support @@ -30,6 +34,12 @@ func (e ErrNotSupported[T]) Is(target error) bool { // specified. var ErrNoProtocols = errors.New("no protocols specified") +const ( + tieBreakerPrefix = "select:" + initiator = "initiator" + responder = "responder" +) + // SelectProtoOrFail performs the initial multistream handshake // to inform the muxer of the protocol that will be used to communicate // on this ReadWriteCloser. It returns an error if, for example, @@ -100,6 +110,84 @@ func SelectOneOf[T StringLike](protos []T, rwc io.ReadWriteCloser) (proto T, err return proto, err } +const simOpenProtocol = "/libp2p/simultaneous-connect" + +// SelectWithSimopenOrFail performs protocol negotiation with the simultaneous open extension. +// The returned boolean indicator will be true if we should act as a server. +func SelectWithSimopenOrFail[T StringLike](protos []T, rwc io.ReadWriteCloser) (proto T, isServer bool, err error) { + defer func() { + if rerr := recover(); rerr != nil { + fmt.Fprintf(os.Stderr, "caught panic: %s\n%s\n", rerr, debug.Stack()) + err = fmt.Errorf("panic selecting protocol with simopen: %s", rerr) + } + }() + + if len(protos) == 0 { + return "", false, ErrNoProtocols + } + + werrCh := make(chan error, 1) + go func() { + var buf bytes.Buffer + if err := delitmWriteAll(&buf, []byte(ProtocolID), []byte(simOpenProtocol), []byte(protos[0])); err != nil { + werrCh <- err + return + } + + _, err := io.Copy(rwc, &buf) + werrCh <- err + }() + + if err := readMultistreamHeader(rwc); err != nil { + return "", false, err + } + + tok, err := ReadNextToken[T](rwc) + if err != nil { + return "", false, err + } + + if err = <-werrCh; err != nil { + return "", false, err + } + + switch tok { + case simOpenProtocol: + // simultaneous open + return simOpen(protos, rwc) + case "na": + // client open + proto, err := clientOpen(protos, rwc) + if err != nil { + return "", false, err + } + return proto, false, nil + default: + return "", false, fmt.Errorf("unexpected response: %s", tok) + } +} + +func clientOpen[T StringLike](protos []T, rwc io.ReadWriteCloser) (T, error) { + // check to see if we selected the pipelined protocol + tok, err := ReadNextToken[T](rwc) + if err != nil { + return "", err + } + + switch tok { + case protos[0]: + return tok, nil + case "na": + proto, err := selectProtosOrFail(protos[1:], rwc) + if _, ok := err.(ErrNotSupported[T]); ok { + return "", ErrNotSupported[T]{protos} + } + return proto, err + default: + return "", fmt.Errorf("unexpected response: %s", tok) + } +} + func selectProtosOrFail[T StringLike](protos []T, rwc io.ReadWriteCloser) (T, error) { for _, p := range protos { err := trySelect(p, rwc) @@ -114,6 +202,131 @@ func selectProtosOrFail[T StringLike](protos []T, rwc io.ReadWriteCloser) (T, er return "", ErrNotSupported[T]{protos} } +func simOpen[T StringLike](protos []T, rwc io.ReadWriteCloser) (T, bool, error) { + randBytes := make([]byte, 8) + _, err := rand.Read(randBytes) + if err != nil { + return "", false, err + } + myNonce := binary.LittleEndian.Uint64(randBytes) + + werrCh := make(chan error, 1) + go func() { + myselect := []byte(tieBreakerPrefix + strconv.FormatUint(myNonce, 10)) + err := delimWriteBuffered(rwc, myselect) + werrCh <- err + }() + + // skip exactly one protocol + // see https://github.com/multiformats/go-multistream/pull/42#discussion_r558757135 + _, err = ReadNextToken[T](rwc) + if err != nil { + return "", false, err + } + + // read the tie breaker nonce + tok, err := ReadNextToken[T](rwc) + if err != nil { + return "", false, err + } + if !strings.HasPrefix(string(tok), tieBreakerPrefix) { + return "", false, errors.New("tie breaker nonce not sent with the correct prefix") + } + + if err = <-werrCh; err != nil { + return "", false, err + } + + peerNonce, err := strconv.ParseUint(string(tok[len(tieBreakerPrefix):]), 10, 64) + if err != nil { + return "", false, err + } + + var iamserver bool + + if peerNonce == myNonce { + return "", false, errors.New("failed client selection; identical nonces") + } + iamserver = peerNonce > myNonce + + var proto T + if iamserver { + proto, err = simOpenSelectServer(protos, rwc) + } else { + proto, err = simOpenSelectClient(protos, rwc) + } + + return proto, iamserver, err +} + +func simOpenSelectServer[T StringLike](protos []T, rwc io.ReadWriteCloser) (T, error) { + werrCh := make(chan error, 1) + go func() { + err := delimWriteBuffered(rwc, []byte(responder)) + werrCh <- err + }() + + tok, err := ReadNextToken[T](rwc) + if err != nil { + return "", err + } + if tok != initiator { + return "", fmt.Errorf("unexpected response: %s", tok) + } + if err = <-werrCh; err != nil { + return "", err + } + for { + tok, err = ReadNextToken[T](rwc) + + if err == io.EOF { + return "", ErrNotSupported[T]{protos} + } + + if err != nil { + return "", err + } + + for _, p := range protos { + if tok == p { + err = delimWriteBuffered(rwc, []byte(p)) + if err != nil { + return "", err + } + + return p, nil + } + } + + err = delimWriteBuffered(rwc, []byte("na")) + if err != nil { + return "", err + } + } + +} + +func simOpenSelectClient[T StringLike](protos []T, rwc io.ReadWriteCloser) (T, error) { + werrCh := make(chan error, 1) + go func() { + err := delimWriteBuffered(rwc, []byte(initiator)) + werrCh <- err + }() + + tok, err := ReadNextToken[T](rwc) + if err != nil { + return "", err + } + if tok != responder { + return "", fmt.Errorf("unexpected response: %s", tok) + } + if err = <-werrCh; err != nil { + return "", err + } + + return selectProtosOrFail(protos, rwc) +} + func readMultistreamHeader(r io.Reader) error { tok, err := ReadNextToken[string](r) if err != nil { diff --git a/vendor/github.com/onsi/ginkgo/v2/ginkgo/outline/ginkgo.go b/vendor/github.com/onsi/ginkgo/v2/ginkgo/outline/ginkgo.go index 958daccbf..0b9b19fe7 100644 --- a/vendor/github.com/onsi/ginkgo/v2/ginkgo/outline/ginkgo.go +++ b/vendor/github.com/onsi/ginkgo/v2/ginkgo/outline/ginkgo.go @@ -244,7 +244,9 @@ func labelFromCallExpr(ce *ast.CallExpr) []string { } if id.Name == "Label" { ls := extractLabels(expr) - labels = append(labels, ls...) + for _, label := range ls { + labels = append(labels, label) + } } } } diff --git a/vendor/github.com/onsi/ginkgo/v2/types/config.go b/vendor/github.com/onsi/ginkgo/v2/types/config.go index c88fc85a7..1014c7b49 100644 --- a/vendor/github.com/onsi/ginkgo/v2/types/config.go +++ b/vendor/github.com/onsi/ginkgo/v2/types/config.go @@ -27,7 +27,6 @@ type SuiteConfig struct { FailOnPending bool FailFast bool FlakeAttempts int - MustPassRepeatedly int DryRun bool PollProgressAfter time.Duration PollProgressInterval time.Duration diff --git a/vendor/github.com/onsi/ginkgo/v2/types/errors.go b/vendor/github.com/onsi/ginkgo/v2/types/errors.go index 4fbdc3e9b..1e0dbfd9d 100644 --- a/vendor/github.com/onsi/ginkgo/v2/types/errors.go +++ b/vendor/github.com/onsi/ginkgo/v2/types/errors.go @@ -453,8 +453,8 @@ func (g ginkgoErrors) InvalidEntryDescription(cl CodeLocation) error { func (g ginkgoErrors) MissingParametersForTableFunction(cl CodeLocation) error { return GinkgoError{ - Heading: "No parameters have been passed to the Table Function", - Message: "The Table Function expected at least 1 parameter", + Heading: fmt.Sprintf("No parameters have been passed to the Table Function"), + Message: fmt.Sprintf("The Table Function expected at least 1 parameter"), CodeLocation: cl, DocLink: "table-specs", } diff --git a/vendor/github.com/onsi/ginkgo/v2/types/types.go b/vendor/github.com/onsi/ginkgo/v2/types/types.go index aae69b04c..d048a8ada 100644 --- a/vendor/github.com/onsi/ginkgo/v2/types/types.go +++ b/vendor/github.com/onsi/ginkgo/v2/types/types.go @@ -97,7 +97,9 @@ func (report Report) Add(other Report) Report { report.RunTime = report.EndTime.Sub(report.StartTime) reports := make(SpecReports, len(report.SpecReports)+len(other.SpecReports)) - copy(reports, report.SpecReports) + for i := range report.SpecReports { + reports[i] = report.SpecReports[i] + } offset := len(report.SpecReports) for i := range other.SpecReports { reports[i+offset] = other.SpecReports[i] diff --git a/vendor/github.com/onsi/ginkgo/v2/types/version.go b/vendor/github.com/onsi/ginkgo/v2/types/version.go index a37f30828..f895739b8 100644 --- a/vendor/github.com/onsi/ginkgo/v2/types/version.go +++ b/vendor/github.com/onsi/ginkgo/v2/types/version.go @@ -1,3 +1,3 @@ package types -const VERSION = "2.13.0" +const VERSION = "2.11.0" diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go index 4e7717d53..6a7a91e55 100644 --- a/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go +++ b/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go @@ -12,12 +12,10 @@ type Spec struct { Root *Root `json:"root,omitempty"` // Hostname configures the container's hostname. Hostname string `json:"hostname,omitempty"` - // Domainname configures the container's domainname. - Domainname string `json:"domainname,omitempty"` // Mounts configures additional mounts (on top of Root). Mounts []Mount `json:"mounts,omitempty"` // Hooks configures callbacks for container lifecycle events. - Hooks *Hooks `json:"hooks,omitempty" platform:"linux,solaris,zos"` + Hooks *Hooks `json:"hooks,omitempty" platform:"linux,solaris"` // Annotations contains arbitrary metadata for the container. Annotations map[string]string `json:"annotations,omitempty"` @@ -29,36 +27,6 @@ type Spec struct { Windows *Windows `json:"windows,omitempty" platform:"windows"` // VM specifies configuration for virtual-machine-based containers. VM *VM `json:"vm,omitempty" platform:"vm"` - // ZOS is platform-specific configuration for z/OS based containers. - ZOS *ZOS `json:"zos,omitempty" platform:"zos"` -} - -// Scheduler represents the scheduling attributes for a process. It is based on -// the Linux sched_setattr(2) syscall. -type Scheduler struct { - // Policy represents the scheduling policy (e.g., SCHED_FIFO, SCHED_RR, SCHED_OTHER). - Policy LinuxSchedulerPolicy `json:"policy"` - - // Nice is the nice value for the process, which affects its priority. - Nice int32 `json:"nice,omitempty"` - - // Priority represents the static priority of the process. - Priority int32 `json:"priority,omitempty"` - - // Flags is an array of scheduling flags. - Flags []LinuxSchedulerFlag `json:"flags,omitempty"` - - // The following ones are used by the DEADLINE scheduler. - - // Runtime is the amount of time in nanoseconds during which the process - // is allowed to run in a given period. - Runtime uint64 `json:"runtime,omitempty"` - - // Deadline is the absolute deadline for the process to complete its execution. - Deadline uint64 `json:"deadline,omitempty"` - - // Period is the length of the period in nanoseconds used for determining the process runtime. - Period uint64 `json:"period,omitempty"` } // Process contains information to start a specific application inside the container. @@ -81,19 +49,15 @@ type Process struct { // Capabilities are Linux capabilities that are kept for the process. Capabilities *LinuxCapabilities `json:"capabilities,omitempty" platform:"linux"` // Rlimits specifies rlimit options to apply to the process. - Rlimits []POSIXRlimit `json:"rlimits,omitempty" platform:"linux,solaris,zos"` + Rlimits []POSIXRlimit `json:"rlimits,omitempty" platform:"linux,solaris"` // NoNewPrivileges controls whether additional privileges could be gained by processes in the container. NoNewPrivileges bool `json:"noNewPrivileges,omitempty" platform:"linux"` // ApparmorProfile specifies the apparmor profile for the container. ApparmorProfile string `json:"apparmorProfile,omitempty" platform:"linux"` // Specify an oom_score_adj for the container. OOMScoreAdj *int `json:"oomScoreAdj,omitempty" platform:"linux"` - // Scheduler specifies the scheduling attributes for a process - Scheduler *Scheduler `json:"scheduler,omitempty" platform:"linux"` // SelinuxLabel specifies the selinux context that the container process is run as. SelinuxLabel string `json:"selinuxLabel,omitempty" platform:"linux"` - // IOPriority contains the I/O priority settings for the cgroup. - IOPriority *LinuxIOPriority `json:"ioPriority,omitempty" platform:"linux"` } // LinuxCapabilities specifies the list of allowed capabilities that are kept for a process. @@ -111,22 +75,6 @@ type LinuxCapabilities struct { Ambient []string `json:"ambient,omitempty" platform:"linux"` } -// IOPriority represents I/O priority settings for the container's processes within the process group. -type LinuxIOPriority struct { - Class IOPriorityClass `json:"class"` - Priority int `json:"priority"` -} - -// IOPriorityClass represents an I/O scheduling class. -type IOPriorityClass string - -// Possible values for IOPriorityClass. -const ( - IOPRIO_CLASS_RT IOPriorityClass = "IOPRIO_CLASS_RT" - IOPRIO_CLASS_BE IOPriorityClass = "IOPRIO_CLASS_BE" - IOPRIO_CLASS_IDLE IOPriorityClass = "IOPRIO_CLASS_IDLE" -) - // Box specifies dimensions of a rectangle. Used for specifying the size of a console. type Box struct { // Height is the vertical dimension of a box. @@ -138,11 +86,11 @@ type Box struct { // User specifies specific user (and group) information for the container process. type User struct { // UID is the user id. - UID uint32 `json:"uid" platform:"linux,solaris,zos"` + UID uint32 `json:"uid" platform:"linux,solaris"` // GID is the group id. - GID uint32 `json:"gid" platform:"linux,solaris,zos"` + GID uint32 `json:"gid" platform:"linux,solaris"` // Umask is the umask for the init process. - Umask *uint32 `json:"umask,omitempty" platform:"linux,solaris,zos"` + Umask *uint32 `json:"umask,omitempty" platform:"linux,solaris"` // AdditionalGids are additional group ids set for the container's process. AdditionalGids []uint32 `json:"additionalGids,omitempty" platform:"linux,solaris"` // Username is the user name. @@ -162,16 +110,11 @@ type Mount struct { // Destination is the absolute path where the mount will be placed in the container. Destination string `json:"destination"` // Type specifies the mount kind. - Type string `json:"type,omitempty" platform:"linux,solaris,zos"` + Type string `json:"type,omitempty" platform:"linux,solaris"` // Source specifies the source path of the mount. Source string `json:"source,omitempty"` // Options are fstab style mount options. Options []string `json:"options,omitempty"` - - // UID/GID mappings used for changing file owners w/o calling chown, fs should support it. - // Every mount point could have its own mapping. - UIDMappings []LinuxIDMapping `json:"uidMappings,omitempty" platform:"linux"` - GIDMappings []LinuxIDMapping `json:"gidMappings,omitempty" platform:"linux"` } // Hook specifies a command that is run at a particular event in the lifecycle of a container @@ -235,12 +178,10 @@ type Linux struct { // MountLabel specifies the selinux context for the mounts in the container. MountLabel string `json:"mountLabel,omitempty"` // IntelRdt contains Intel Resource Director Technology (RDT) information for - // handling resource constraints and monitoring metrics (e.g., L3 cache, memory bandwidth) for the container + // handling resource constraints (e.g., L3 cache, memory bandwidth) for the container IntelRdt *LinuxIntelRdt `json:"intelRdt,omitempty"` // Personality contains configuration for the Linux personality syscall Personality *LinuxPersonality `json:"personality,omitempty"` - // TimeOffsets specifies the offset for supporting time namespaces. - TimeOffsets map[string]LinuxTimeOffset `json:"timeOffsets,omitempty"` } // LinuxNamespace is the configuration for a Linux namespace @@ -270,8 +211,6 @@ const ( UserNamespace LinuxNamespaceType = "user" // CgroupNamespace for isolating cgroup hierarchies CgroupNamespace LinuxNamespaceType = "cgroup" - // TimeNamespace for isolating the clocks - TimeNamespace LinuxNamespaceType = "time" ) // LinuxIDMapping specifies UID/GID mappings @@ -284,14 +223,6 @@ type LinuxIDMapping struct { Size uint32 `json:"size"` } -// LinuxTimeOffset specifies the offset for Time Namespace -type LinuxTimeOffset struct { - // Secs is the offset of clock (in secs) in the container - Secs int64 `json:"secs,omitempty"` - // Nanosecs is the additional offset for Secs (in nanosecs) - Nanosecs uint32 `json:"nanosecs,omitempty"` -} - // POSIXRlimit type and restrictions type POSIXRlimit struct { // Type of the rlimit to set @@ -302,13 +233,12 @@ type POSIXRlimit struct { Soft uint64 `json:"soft"` } -// LinuxHugepageLimit structure corresponds to limiting kernel hugepages. -// Default to reservation limits if supported. Otherwise fallback to page fault limits. +// LinuxHugepageLimit structure corresponds to limiting kernel hugepages type LinuxHugepageLimit struct { - // Pagesize is the hugepage size. - // Format: "B' (e.g. 64KB, 2MB, 1GB, etc.). + // Pagesize is the hugepage size + // Format: "B' (e.g. 64KB, 2MB, 1GB, etc.) Pagesize string `json:"pageSize"` - // Limit is the limit of "hugepagesize" hugetlb reservations (if supported) or usage. + // Limit is the limit of "hugepagesize" hugetlb usage Limit uint64 `json:"limit"` } @@ -320,8 +250,8 @@ type LinuxInterfacePriority struct { Priority uint32 `json:"priority"` } -// LinuxBlockIODevice holds major:minor format supported in blkio cgroup -type LinuxBlockIODevice struct { +// linuxBlockIODevice holds major:minor format supported in blkio cgroup +type linuxBlockIODevice struct { // Major is the device's major number. Major int64 `json:"major"` // Minor is the device's minor number. @@ -330,7 +260,7 @@ type LinuxBlockIODevice struct { // LinuxWeightDevice struct holds a `major:minor weight` pair for weightDevice type LinuxWeightDevice struct { - LinuxBlockIODevice + linuxBlockIODevice // Weight is the bandwidth rate for the device. Weight *uint16 `json:"weight,omitempty"` // LeafWeight is the bandwidth rate for the device while competing with the cgroup's child cgroups, CFQ scheduler only @@ -339,7 +269,7 @@ type LinuxWeightDevice struct { // LinuxThrottleDevice struct holds a `major:minor rate_per_second` pair type LinuxThrottleDevice struct { - LinuxBlockIODevice + linuxBlockIODevice // Rate is the IO rate limit per cgroup per device Rate uint64 `json:"rate"` } @@ -380,10 +310,6 @@ type LinuxMemory struct { DisableOOMKiller *bool `json:"disableOOMKiller,omitempty"` // Enables hierarchical memory accounting UseHierarchy *bool `json:"useHierarchy,omitempty"` - // CheckBeforeUpdate enables checking if a new memory limit is lower - // than the current usage during update, and if so, rejecting the new - // limit. - CheckBeforeUpdate *bool `json:"checkBeforeUpdate,omitempty"` } // LinuxCPU for Linux cgroup 'cpu' resource management @@ -392,9 +318,6 @@ type LinuxCPU struct { Shares *uint64 `json:"shares,omitempty"` // CPU hardcap limit (in usecs). Allowed cpu time in a given period. Quota *int64 `json:"quota,omitempty"` - // CPU hardcap burst limit (in usecs). Allowed accumulated cpu time additionally for burst in a - // given period. - Burst *uint64 `json:"burst,omitempty"` // CPU period to be used for hardcapping (in usecs). Period *uint64 `json:"period,omitempty"` // How much time realtime scheduling may use (in usecs). @@ -405,8 +328,6 @@ type LinuxCPU struct { Cpus string `json:"cpus,omitempty"` // List of memory nodes in the cpuset. Default is to use any available memory node. Mems string `json:"mems,omitempty"` - // cgroups are configured with minimum weight, 0: default behavior, 1: SCHED_IDLE. - Idle *int64 `json:"idle,omitempty"` } // LinuxPids for Linux cgroup 'pids' resource management (Linux 4.3) @@ -443,7 +364,7 @@ type LinuxResources struct { Pids *LinuxPids `json:"pids,omitempty"` // BlockIO restriction configuration BlockIO *LinuxBlockIO `json:"blockIO,omitempty"` - // Hugetlb limits (in bytes). Default to reservation limits if supported. + // Hugetlb limit (in bytes) HugepageLimits []LinuxHugepageLimit `json:"hugepageLimits,omitempty"` // Network restriction configuration Network *LinuxNetwork `json:"network,omitempty"` @@ -601,21 +522,11 @@ type WindowsMemoryResources struct { // WindowsCPUResources contains CPU resource management settings. type WindowsCPUResources struct { - // Count is the number of CPUs available to the container. It represents the - // fraction of the configured processor `count` in a container in relation - // to the processors available in the host. The fraction ultimately - // determines the portion of processor cycles that the threads in a - // container can use during each scheduling interval, as the number of - // cycles per 10,000 cycles. + // Number of CPUs available to the container. Count *uint64 `json:"count,omitempty"` - // Shares limits the share of processor time given to the container relative - // to other workloads on the processor. The processor `shares` (`weight` at - // the platform level) is a value between 0 and 10000. + // CPU shares (relative weight to other containers with cpu shares). Shares *uint16 `json:"shares,omitempty"` - // Maximum determines the portion of processor cycles that the threads in a - // container can use during each scheduling interval, as the number of - // cycles per 10,000 cycles. Set processor `maximum` to a percentage times - // 100. + // Specifies the portion of processor cycles that this container can use as a percentage times 100. Maximum *uint16 `json:"maximum,omitempty"` } @@ -702,23 +613,6 @@ type Arch string // LinuxSeccompFlag is a flag to pass to seccomp(2). type LinuxSeccompFlag string -const ( - // LinuxSeccompFlagLog is a seccomp flag to request all returned - // actions except SECCOMP_RET_ALLOW to be logged. An administrator may - // override this filter flag by preventing specific actions from being - // logged via the /proc/sys/kernel/seccomp/actions_logged file. (since - // Linux 4.14) - LinuxSeccompFlagLog LinuxSeccompFlag = "SECCOMP_FILTER_FLAG_LOG" - - // LinuxSeccompFlagSpecAllow can be used to disable Speculative Store - // Bypass mitigation. (since Linux 4.17) - LinuxSeccompFlagSpecAllow LinuxSeccompFlag = "SECCOMP_FILTER_FLAG_SPEC_ALLOW" - - // LinuxSeccompFlagWaitKillableRecv can be used to switch to the wait - // killable semantics. (since Linux 5.19) - LinuxSeccompFlagWaitKillableRecv LinuxSeccompFlag = "SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV" -) - // Additional architectures permitted to be used for system calls // By default only the native architecture of the kernel is permitted const ( @@ -789,9 +683,8 @@ type LinuxSyscall struct { Args []LinuxSeccompArg `json:"args,omitempty"` } -// LinuxIntelRdt has container runtime resource constraints for Intel RDT CAT and MBA -// features and flags enabling Intel RDT CMT and MBM features. -// Intel RDT features are available in Linux 4.14 and newer kernel versions. +// LinuxIntelRdt has container runtime resource constraints for Intel RDT +// CAT and MBA features which introduced in Linux 4.10 and 4.12 kernel type LinuxIntelRdt struct { // The identity for RDT Class of Service ClosID string `json:"closID,omitempty"` @@ -804,76 +697,4 @@ type LinuxIntelRdt struct { // The unit of memory bandwidth is specified in "percentages" by // default, and in "MBps" if MBA Software Controller is enabled. MemBwSchema string `json:"memBwSchema,omitempty"` - - // EnableCMT is the flag to indicate if the Intel RDT CMT is enabled. CMT (Cache Monitoring Technology) supports monitoring of - // the last-level cache (LLC) occupancy for the container. - EnableCMT bool `json:"enableCMT,omitempty"` - - // EnableMBM is the flag to indicate if the Intel RDT MBM is enabled. MBM (Memory Bandwidth Monitoring) supports monitoring of - // total and local memory bandwidth for the container. - EnableMBM bool `json:"enableMBM,omitempty"` } - -// ZOS contains platform-specific configuration for z/OS based containers. -type ZOS struct { - // Devices are a list of device nodes that are created for the container - Devices []ZOSDevice `json:"devices,omitempty"` -} - -// ZOSDevice represents the mknod information for a z/OS special device file -type ZOSDevice struct { - // Path to the device. - Path string `json:"path"` - // Device type, block, char, etc. - Type string `json:"type"` - // Major is the device's major number. - Major int64 `json:"major"` - // Minor is the device's minor number. - Minor int64 `json:"minor"` - // FileMode permission bits for the device. - FileMode *os.FileMode `json:"fileMode,omitempty"` - // UID of the device. - UID *uint32 `json:"uid,omitempty"` - // Gid of the device. - GID *uint32 `json:"gid,omitempty"` -} - -// LinuxSchedulerPolicy represents different scheduling policies used with the Linux Scheduler -type LinuxSchedulerPolicy string - -const ( - // SchedOther is the default scheduling policy - SchedOther LinuxSchedulerPolicy = "SCHED_OTHER" - // SchedFIFO is the First-In-First-Out scheduling policy - SchedFIFO LinuxSchedulerPolicy = "SCHED_FIFO" - // SchedRR is the Round-Robin scheduling policy - SchedRR LinuxSchedulerPolicy = "SCHED_RR" - // SchedBatch is the Batch scheduling policy - SchedBatch LinuxSchedulerPolicy = "SCHED_BATCH" - // SchedISO is the Isolation scheduling policy - SchedISO LinuxSchedulerPolicy = "SCHED_ISO" - // SchedIdle is the Idle scheduling policy - SchedIdle LinuxSchedulerPolicy = "SCHED_IDLE" - // SchedDeadline is the Deadline scheduling policy - SchedDeadline LinuxSchedulerPolicy = "SCHED_DEADLINE" -) - -// LinuxSchedulerFlag represents the flags used by the Linux Scheduler. -type LinuxSchedulerFlag string - -const ( - // SchedFlagResetOnFork represents the reset on fork scheduling flag - SchedFlagResetOnFork LinuxSchedulerFlag = "SCHED_FLAG_RESET_ON_FORK" - // SchedFlagReclaim represents the reclaim scheduling flag - SchedFlagReclaim LinuxSchedulerFlag = "SCHED_FLAG_RECLAIM" - // SchedFlagDLOverrun represents the deadline overrun scheduling flag - SchedFlagDLOverrun LinuxSchedulerFlag = "SCHED_FLAG_DL_OVERRUN" - // SchedFlagKeepPolicy represents the keep policy scheduling flag - SchedFlagKeepPolicy LinuxSchedulerFlag = "SCHED_FLAG_KEEP_POLICY" - // SchedFlagKeepParams represents the keep parameters scheduling flag - SchedFlagKeepParams LinuxSchedulerFlag = "SCHED_FLAG_KEEP_PARAMS" - // SchedFlagUtilClampMin represents the utilization clamp minimum scheduling flag - SchedFlagUtilClampMin LinuxSchedulerFlag = "SCHED_FLAG_UTIL_CLAMP_MIN" - // SchedFlagUtilClampMin represents the utilization clamp maximum scheduling flag - SchedFlagUtilClampMax LinuxSchedulerFlag = "SCHED_FLAG_UTIL_CLAMP_MAX" -) diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go index b3fca349c..596af0c2f 100644 --- a/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go +++ b/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go @@ -6,12 +6,12 @@ const ( // VersionMajor is for an API incompatible changes VersionMajor = 1 // VersionMinor is for functionality in a backwards-compatible manner - VersionMinor = 1 + VersionMinor = 0 // VersionPatch is for backwards-compatible bug fixes - VersionPatch = 0 + VersionPatch = 2 // VersionDev indicates development branch. Releases will be empty string. - VersionDev = "" + VersionDev = "-dev" ) // Version is the specification version that the package types support. diff --git a/vendor/github.com/pion/datachannel/.gitignore b/vendor/github.com/pion/datachannel/.gitignore index f977e7485..83db74ba5 100644 --- a/vendor/github.com/pion/datachannel/.gitignore +++ b/vendor/github.com/pion/datachannel/.gitignore @@ -22,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/datachannel/.golangci.yml b/vendor/github.com/pion/datachannel/.golangci.yml index d7a88eca3..d6162c970 100644 --- a/vendor/github.com/pion/datachannel/.golangci.yml +++ b/vendor/github.com/pion/datachannel/.golangci.yml @@ -15,22 +15,14 @@ linters-settings: linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - deadcode # Finds unused code - - decorder # check declaration order and count of types, constants, variables and functions - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -43,62 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - varcheck # Finds unused global variables and constants - - wastedassign # wastedassign finds wasted assignment statements - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - - forbidigo # Forbids identifiers - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: diff --git a/vendor/github.com/pion/datachannel/AUTHORS.txt b/vendor/github.com/pion/datachannel/AUTHORS.txt index c5d9d8d34..92073e2c1 100644 --- a/vendor/github.com/pion/datachannel/AUTHORS.txt +++ b/vendor/github.com/pion/datachannel/AUTHORS.txt @@ -6,7 +6,6 @@ Atsushi Watanabe backkem Benny Daon -Chinmay Kousik Eric Daniels Hugo Arregui Hugo Arregui diff --git a/vendor/github.com/pion/datachannel/datachannel.go b/vendor/github.com/pion/datachannel/datachannel.go index 0b125d662..11f30cc78 100644 --- a/vendor/github.com/pion/datachannel/datachannel.go +++ b/vendor/github.com/pion/datachannel/datachannel.go @@ -2,12 +2,10 @@ package datachannel import ( - "errors" "fmt" "io" "sync" "sync/atomic" - "time" "github.com/pion/logging" "github.com/pion/sctp" @@ -21,11 +19,6 @@ type Reader interface { ReadDataChannel([]byte) (int, bool, error) } -// ReadDeadliner extends an io.Reader to expose setting a read deadline. -type ReadDeadliner interface { - SetReadDeadline(time.Time) error -} - // Writer is an extended io.Writer // that also allows indicating if a message is text. type Writer interface { @@ -191,7 +184,7 @@ func (c *DataChannel) Read(p []byte) (int, error) { func (c *DataChannel) ReadDataChannel(p []byte) (int, bool, error) { for { n, ppi, err := c.stream.ReadSCTP(p) - if errors.Is(err, io.EOF) { + if err == io.EOF { // When the peer sees that an incoming stream was // reset, it also resets its corresponding outgoing stream. if closeErr := c.stream.Close(); closeErr != nil { @@ -219,11 +212,6 @@ func (c *DataChannel) ReadDataChannel(p []byte) (int, bool, error) { } } -// SetReadDeadline sets a deadline for reads to return -func (c *DataChannel) SetReadDeadline(t time.Time) error { - return c.stream.SetReadDeadline(t) -} - // MessagesSent returns the number of messages sent func (c *DataChannel) MessagesSent() uint32 { return atomic.LoadUint32(&c.messagesSent) diff --git a/vendor/github.com/pion/datachannel/message_channel_open.go b/vendor/github.com/pion/datachannel/message_channel_open.go index 5eb58633c..c257bea8d 100644 --- a/vendor/github.com/pion/datachannel/message_channel_open.go +++ b/vendor/github.com/pion/datachannel/message_channel_open.go @@ -8,9 +8,8 @@ import ( /* channelOpen represents a DATA_CHANNEL_OPEN Message - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Message Type | Channel Type | Priority | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ diff --git a/vendor/github.com/pion/datachannel/renovate.json b/vendor/github.com/pion/datachannel/renovate.json index f1614058a..08c1e39d6 100644 --- a/vendor/github.com/pion/datachannel/renovate.json +++ b/vendor/github.com/pion/datachannel/renovate.json @@ -1,7 +1,6 @@ { "extends": [ - "config:base", - ":disableDependencyDashboard" + "config:base" ], "postUpdateOptions": [ "gomodTidy" diff --git a/vendor/github.com/pion/dtls/v2/.editorconfig b/vendor/github.com/pion/dtls/v2/.editorconfig index 1dca00f8a..d2b32061a 100644 --- a/vendor/github.com/pion/dtls/v2/.editorconfig +++ b/vendor/github.com/pion/dtls/v2/.editorconfig @@ -1,6 +1,4 @@ # http://editorconfig.org/ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT root = true diff --git a/vendor/github.com/pion/dtls/v2/.gitignore b/vendor/github.com/pion/dtls/v2/.gitignore index 6e2f206a9..83db74ba5 100644 --- a/vendor/github.com/pion/dtls/v2/.gitignore +++ b/vendor/github.com/pion/dtls/v2/.gitignore @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - ### JetBrains IDE ### ##################### .idea/ @@ -25,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/dtls/v2/.golangci.yml b/vendor/github.com/pion/dtls/v2/.golangci.yml index 4e3eddf42..d6162c970 100644 --- a/vendor/github.com/pion/dtls/v2/.golangci.yml +++ b/vendor/github.com/pion/dtls/v2/.golangci.yml @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - linters-settings: govet: check-shadowing: true @@ -13,34 +10,19 @@ linters-settings: modules: - github.com/pkg/errors: recommendations: - - errors - forbidigo: - forbid: - - ^fmt.Print(f|ln)?$ - - ^log.(Panic|Fatal|Print)(f|ln)?$ - - ^os.Exit$ - - ^panic$ - - ^print(ln)?$ + - errors linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - - decorder # check declaration order and count of types, constants, variables and functions + - deadcode # Finds unused code - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forbidigo # Forbids identifiers - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -53,59 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks + - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - - wastedassign # wastedassign finds wasted assignment statements + - varcheck # Finds unused global variables and constants - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: @@ -115,23 +78,12 @@ issues: - path: _test\.go linters: - gocognit - - forbidigo # Allow complex main function in examples - path: examples text: "of func `main` is high" linters: - gocognit - - # Allow forbidden identifiers in examples - - path: examples - linters: - - forbidigo - - # Allow forbidden identifiers in CLI commands - - path: cmd - linters: - - forbidigo run: skip-dirs-use-default: false diff --git a/vendor/github.com/pion/dtls/v2/.goreleaser.yml b/vendor/github.com/pion/dtls/v2/.goreleaser.yml deleted file mode 100644 index 30093e9d6..000000000 --- a/vendor/github.com/pion/dtls/v2/.goreleaser.yml +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - -builds: -- skip: true diff --git a/vendor/github.com/pion/dtls/v2/AUTHORS.txt b/vendor/github.com/pion/dtls/v2/AUTHORS.txt index e14fae4c0..a8e6fb46f 100644 --- a/vendor/github.com/pion/dtls/v2/AUTHORS.txt +++ b/vendor/github.com/pion/dtls/v2/AUTHORS.txt @@ -2,7 +2,7 @@ # we would love to have you https://github.com/pion/webrtc/wiki/Contributing # # This file is auto generated, using git to list all individuals contributors. -# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting +# see `.github/generate-authors.sh` for the scripting Aleksandr Razumov alvarowolfx Arlo Breault @@ -14,7 +14,6 @@ Bragadeesh Carson Hoffman Cecylia Bocovich Chris Hiszpanski -cnderrauber Daniele Sluijters folbrich Hayden James @@ -28,30 +27,19 @@ Jim Wert jinleileiking Jozef Kralik Julien Salleyron -Juliusz Chroboczek Kegan Dougal -Kevin Wang Lander Noterman Len Lukas Lihotzki -ManuelBk <26275612+ManuelBk@users.noreply.github.com> Michael Zabka Michiel De Backker -Rachel Chen Robert Eperjesi Ryan Gordon -Sam Lancia -Sean DuBois Sean DuBois Sean DuBois -Shelikhoo Stefan Tatschner -Steffen Vogel Vadim Vadim Filimonov wmiao ZHENK 吕海涛 - -# List of contributors not appearing in Git history - diff --git a/vendor/github.com/pion/dtls/v2/LICENSE b/vendor/github.com/pion/dtls/v2/LICENSE index 491caf6b0..ab602974d 100644 --- a/vendor/github.com/pion/dtls/v2/LICENSE +++ b/vendor/github.com/pion/dtls/v2/LICENSE @@ -1,9 +1,21 @@ MIT License -Copyright (c) 2023 The Pion community +Copyright (c) 2018 -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/pion/dtls/v2/Makefile b/vendor/github.com/pion/dtls/v2/Makefile new file mode 100644 index 000000000..1df38b223 --- /dev/null +++ b/vendor/github.com/pion/dtls/v2/Makefile @@ -0,0 +1,6 @@ +fuzz-build-record-layer: fuzz-prepare + go-fuzz-build -tags gofuzz -func FuzzRecordLayer +fuzz-run-record-layer: + go-fuzz -bin dtls-fuzz.zip -workdir fuzz +fuzz-prepare: + @GO111MODULE=on go mod vendor diff --git a/vendor/github.com/pion/dtls/v2/README.md b/vendor/github.com/pion/dtls/v2/README.md index 0c0659593..d6da5b33a 100644 --- a/vendor/github.com/pion/dtls/v2/README.md +++ b/vendor/github.com/pion/dtls/v2/README.md @@ -9,10 +9,11 @@ Sourcegraph Widget Slack Widget
- GitHub Workflow Status - Go Reference + Build Status + GoDoc Coverage Status - Go Report Card + Go Report Card + Codacy Badge License: MIT


@@ -21,22 +22,7 @@ Native [DTLS 1.2][rfc6347] implementation in the Go programming language. A long term goal is a professional security review, and maybe an inclusion in stdlib. -### RFCs -#### Implemented -- **RFC 6347**: [Datagram Transport Layer Security Version 1.2][rfc6347] -- **RFC 5705**: [Keying Material Exporters for Transport Layer Security (TLS)][rfc5705] -- **RFC 7627**: [Transport Layer Security (TLS) - Session Hash and Extended Master Secret Extension][rfc7627] -- **RFC 7301**: [Transport Layer Security (TLS) - Application-Layer Protocol Negotiation Extension][rfc7301] - -[rfc5289]: https://tools.ietf.org/html/rfc5289 -[rfc5487]: https://tools.ietf.org/html/rfc5487 -[rfc5489]: https://tools.ietf.org/html/rfc5489 -[rfc5705]: https://tools.ietf.org/html/rfc5705 [rfc6347]: https://tools.ietf.org/html/rfc6347 -[rfc6655]: https://tools.ietf.org/html/rfc6655 -[rfc7301]: https://tools.ietf.org/html/rfc7301 -[rfc7627]: https://tools.ietf.org/html/rfc7627 -[rfc8422]: https://tools.ietf.org/html/rfc8422 ### Goals/Progress This will only be targeting DTLS 1.2, and the most modern/common cipher suites. @@ -51,10 +37,13 @@ We would love contributions that fall under the 'Planned Features' and any bug f * Extended Master Secret extension ([RFC 7627][rfc7627]) * ALPN extension ([RFC 7301][rfc7301]) +[rfc5705]: https://tools.ietf.org/html/rfc5705 +[rfc7627]: https://tools.ietf.org/html/rfc7627 +[rfc7301]: https://tools.ietf.org/html/rfc7301 + #### Supported ciphers ##### ECDHE - * TLS_ECDHE_ECDSA_WITH_AES_128_CCM ([RFC 6655][rfc6655]) * TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ([RFC 6655][rfc6655]) * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ([RFC 5289][rfc5289]) @@ -65,16 +54,15 @@ We would love contributions that fall under the 'Planned Features' and any bug f * TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA ([RFC 8422][rfc8422]) ##### PSK - * TLS_PSK_WITH_AES_128_CCM ([RFC 6655][rfc6655]) * TLS_PSK_WITH_AES_128_CCM_8 ([RFC 6655][rfc6655]) -* TLS_PSK_WITH_AES_256_CCM_8 ([RFC 6655][rfc6655]) * TLS_PSK_WITH_AES_128_GCM_SHA256 ([RFC 5487][rfc5487]) * TLS_PSK_WITH_AES_128_CBC_SHA256 ([RFC 5487][rfc5487]) -##### ECDHE & PSK - -* TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 ([RFC 5489][rfc5489]) +[rfc5289]: https://tools.ietf.org/html/rfc5289 +[rfc8422]: https://tools.ietf.org/html/rfc8422 +[rfc6655]: https://tools.ietf.org/html/rfc6655 +[rfc5487]: https://tools.ietf.org/html/rfc5487 #### Planned Features * Chacha20Poly1305 @@ -118,6 +106,7 @@ Pion DTLS can connect to itself and OpenSSL. ### Using with PSK Pion DTLS also comes with examples that do key exchange via PSK + #### Pion DTLS ```sh go run examples/listen/psk/main.go @@ -136,16 +125,8 @@ go run examples/dial/psk/main.go openssl s_client -dtls1_2 -connect 127.0.0.1:4444 -psk abc123 -cipher PSK-AES128-CCM8 ``` -### Community -Pion has an active community on the [Slack](https://pion.ly/slack). - -Follow the [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news. - -We are always looking to support **your projects**. Please reach out if you have something to build! -If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly) - ### Contributing -Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible: [AUTHORS.txt](./AUTHORS.txt) +Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible: ### License MIT License - see [LICENSE](LICENSE) for full text diff --git a/vendor/github.com/pion/dtls/v2/certificate.go b/vendor/github.com/pion/dtls/v2/certificate.go index 519fc875f..c99e1c93d 100644 --- a/vendor/github.com/pion/dtls/v2/certificate.go +++ b/vendor/github.com/pion/dtls/v2/certificate.go @@ -1,105 +1,35 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( - "bytes" "crypto/tls" "crypto/x509" - "fmt" "strings" ) -// ClientHelloInfo contains information from a ClientHello message in order to -// guide application logic in the GetCertificate. -type ClientHelloInfo struct { - // ServerName indicates the name of the server requested by the client - // in order to support virtual hosting. ServerName is only set if the - // client is using SNI (see RFC 4366, Section 3.1). - ServerName string - - // CipherSuites lists the CipherSuites supported by the client (e.g. - // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256). - CipherSuites []CipherSuiteID -} - -// CertificateRequestInfo contains information from a server's -// CertificateRequest message, which is used to demand a certificate and proof -// of control from a client. -type CertificateRequestInfo struct { - // AcceptableCAs contains zero or more, DER-encoded, X.501 - // Distinguished Names. These are the names of root or intermediate CAs - // that the server wishes the returned certificate to be signed by. An - // empty slice indicates that the server has no preference. - AcceptableCAs [][]byte -} - -// SupportsCertificate returns nil if the provided certificate is supported by -// the server that sent the CertificateRequest. Otherwise, it returns an error -// describing the reason for the incompatibility. -// NOTE: original src: https://github.com/golang/go/blob/29b9a328d268d53833d2cc063d1d8b4bf6852675/src/crypto/tls/common.go#L1273 -func (cri *CertificateRequestInfo) SupportsCertificate(c *tls.Certificate) error { - if len(cri.AcceptableCAs) == 0 { - return nil - } - - for j, cert := range c.Certificate { - x509Cert := c.Leaf - // Parse the certificate if this isn't the leaf node, or if - // chain.Leaf was nil. - if j != 0 || x509Cert == nil { - var err error - if x509Cert, err = x509.ParseCertificate(cert); err != nil { - return fmt.Errorf("failed to parse certificate #%d in the chain: %w", j, err) - } - } - - for _, ca := range cri.AcceptableCAs { - if bytes.Equal(x509Cert.RawIssuer, ca) { - return nil - } - } - } - return errNotAcceptableCertificateChain -} - -func (c *handshakeConfig) setNameToCertificateLocked() { - nameToCertificate := make(map[string]*tls.Certificate) - for i := range c.localCertificates { - cert := &c.localCertificates[i] - x509Cert := cert.Leaf - if x509Cert == nil { - var parseErr error - x509Cert, parseErr = x509.ParseCertificate(cert.Certificate[0]) - if parseErr != nil { - continue - } - } - if len(x509Cert.Subject.CommonName) > 0 { - nameToCertificate[strings.ToLower(x509Cert.Subject.CommonName)] = cert - } - for _, san := range x509Cert.DNSNames { - nameToCertificate[strings.ToLower(san)] = cert - } - } - c.nameToCertificate = nameToCertificate -} - -func (c *handshakeConfig) getCertificate(clientHelloInfo *ClientHelloInfo) (*tls.Certificate, error) { +func (c *handshakeConfig) getCertificate(serverName string) (*tls.Certificate, error) { c.mu.Lock() defer c.mu.Unlock() - if c.localGetCertificate != nil && - (len(c.localCertificates) == 0 || len(clientHelloInfo.ServerName) > 0) { - cert, err := c.localGetCertificate(clientHelloInfo) - if cert != nil || err != nil { - return cert, err - } - } - if c.nameToCertificate == nil { - c.setNameToCertificateLocked() + nameToCertificate := make(map[string]*tls.Certificate) + for i := range c.localCertificates { + cert := &c.localCertificates[i] + x509Cert := cert.Leaf + if x509Cert == nil { + var parseErr error + x509Cert, parseErr = x509.ParseCertificate(cert.Certificate[0]) + if parseErr != nil { + continue + } + } + if len(x509Cert.Subject.CommonName) > 0 { + nameToCertificate[strings.ToLower(x509Cert.Subject.CommonName)] = cert + } + for _, san := range x509Cert.DNSNames { + nameToCertificate[strings.ToLower(san)] = cert + } + } + c.nameToCertificate = nameToCertificate } if len(c.localCertificates) == 0 { @@ -111,11 +41,11 @@ func (c *handshakeConfig) getCertificate(clientHelloInfo *ClientHelloInfo) (*tls return &c.localCertificates[0], nil } - if len(clientHelloInfo.ServerName) == 0 { + if len(serverName) == 0 { return &c.localCertificates[0], nil } - name := strings.TrimRight(strings.ToLower(clientHelloInfo.ServerName), ".") + name := strings.TrimRight(strings.ToLower(serverName), ".") if cert, ok := c.nameToCertificate[name]; ok { return cert, nil @@ -135,23 +65,3 @@ func (c *handshakeConfig) getCertificate(clientHelloInfo *ClientHelloInfo) (*tls // If nothing matches, return the first certificate. return &c.localCertificates[0], nil } - -// NOTE: original src: https://github.com/golang/go/blob/29b9a328d268d53833d2cc063d1d8b4bf6852675/src/crypto/tls/handshake_client.go#L974 -func (c *handshakeConfig) getClientCertificate(cri *CertificateRequestInfo) (*tls.Certificate, error) { - c.mu.Lock() - defer c.mu.Unlock() - if c.localGetClientCertificate != nil { - return c.localGetClientCertificate(cri) - } - - for i := range c.localCertificates { - chain := c.localCertificates[i] - if err := cri.SupportsCertificate(&chain); err != nil { - continue - } - return &chain, nil - } - - // No acceptable certificate found. Don't send a certificate. - return new(tls.Certificate), nil -} diff --git a/vendor/github.com/pion/dtls/v2/cipher_suite.go b/vendor/github.com/pion/dtls/v2/cipher_suite.go index 7a5bb4a58..5f35a8504 100644 --- a/vendor/github.com/pion/dtls/v2/cipher_suite.go +++ b/vendor/github.com/pion/dtls/v2/cipher_suite.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -22,27 +19,24 @@ type CipherSuiteID = ciphersuite.ID // Supported Cipher Suites const ( // AES-128-CCM - TLS_ECDHE_ECDSA_WITH_AES_128_CCM CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM //nolint:revive,stylecheck - TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 //nolint:revive,stylecheck + TLS_ECDHE_ECDSA_WITH_AES_128_CCM CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM //nolint:golint,stylecheck + TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 //nolint:golint,stylecheck // AES-128-GCM-SHA256 - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 //nolint:revive,stylecheck - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 //nolint:revive,stylecheck + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 //nolint:golint,stylecheck + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 //nolint:golint,stylecheck - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 //nolint:revive,stylecheck - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 CipherSuiteID = ciphersuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 //nolint:revive,stylecheck + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 //nolint:golint,stylecheck + TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 CipherSuiteID = ciphersuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 //nolint:golint,stylecheck // AES-256-CBC-SHA - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA //nolint:revive,stylecheck - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA CipherSuiteID = ciphersuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA //nolint:revive,stylecheck + TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA CipherSuiteID = ciphersuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA //nolint:golint,stylecheck + TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA CipherSuiteID = ciphersuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA //nolint:golint,stylecheck - TLS_PSK_WITH_AES_128_CCM CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CCM //nolint:revive,stylecheck - TLS_PSK_WITH_AES_128_CCM_8 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CCM_8 //nolint:revive,stylecheck - TLS_PSK_WITH_AES_256_CCM_8 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_256_CCM_8 //nolint:revive,stylecheck - TLS_PSK_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_GCM_SHA256 //nolint:revive,stylecheck - TLS_PSK_WITH_AES_128_CBC_SHA256 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CBC_SHA256 //nolint:revive,stylecheck - - TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 CipherSuiteID = ciphersuite.TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 //nolint:revive,stylecheck + TLS_PSK_WITH_AES_128_CCM CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CCM //nolint:golint,stylecheck + TLS_PSK_WITH_AES_128_CCM_8 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CCM_8 //nolint:golint,stylecheck + TLS_PSK_WITH_AES_128_GCM_SHA256 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_GCM_SHA256 //nolint:golint,stylecheck + TLS_PSK_WITH_AES_128_CBC_SHA256 CipherSuiteID = ciphersuite.TLS_PSK_WITH_AES_128_CBC_SHA256 //nolint:golint,stylecheck ) // CipherSuiteAuthenticationType controls what authentication method is using during the handshake for a CipherSuite @@ -55,16 +49,6 @@ const ( CipherSuiteAuthenticationTypeAnonymous CipherSuiteAuthenticationType = ciphersuite.AuthenticationTypeAnonymous ) -// CipherSuiteKeyExchangeAlgorithm controls what exchange algorithm is using during the handshake for a CipherSuite -type CipherSuiteKeyExchangeAlgorithm = ciphersuite.KeyExchangeAlgorithm - -// CipherSuiteKeyExchangeAlgorithm Bitmask -const ( - CipherSuiteKeyExchangeAlgorithmNone CipherSuiteKeyExchangeAlgorithm = ciphersuite.KeyExchangeAlgorithmNone - CipherSuiteKeyExchangeAlgorithmPsk CipherSuiteKeyExchangeAlgorithm = ciphersuite.KeyExchangeAlgorithmPsk - CipherSuiteKeyExchangeAlgorithmEcdhe CipherSuiteKeyExchangeAlgorithm = ciphersuite.KeyExchangeAlgorithmEcdhe -) - var _ = allCipherSuites() // Necessary until this function isn't only used by Go 1.14 // CipherSuite is an interface that all DTLS CipherSuites must satisfy @@ -84,13 +68,6 @@ type CipherSuite interface { // AuthenticationType controls what authentication method is using during the handshake AuthenticationType() CipherSuiteAuthenticationType - // KeyExchangeAlgorithm controls what exchange algorithm is using during the handshake - KeyExchangeAlgorithm() CipherSuiteKeyExchangeAlgorithm - - // ECC (Elliptic Curve Cryptography) determines whether ECC extesions will be send during handshake. - // https://datatracker.ietf.org/doc/html/rfc4492#page-10 - ECC() bool - // Called when keying material has been generated, should initialize the internal cipher Init(masterSecret, clientRandom, serverRandom []byte, isClient bool) error IsInitialized() bool @@ -132,8 +109,6 @@ func cipherSuiteForID(id CipherSuiteID, customCiphers func() []CipherSuite) Ciph return ciphersuite.NewTLSPskWithAes128Ccm() case TLS_PSK_WITH_AES_128_CCM_8: return ciphersuite.NewTLSPskWithAes128Ccm8() - case TLS_PSK_WITH_AES_256_CCM_8: - return ciphersuite.NewTLSPskWithAes256Ccm8() case TLS_PSK_WITH_AES_128_GCM_SHA256: return &ciphersuite.TLSPskWithAes128GcmSha256{} case TLS_PSK_WITH_AES_128_CBC_SHA256: @@ -142,8 +117,6 @@ func cipherSuiteForID(id CipherSuiteID, customCiphers func() []CipherSuite) Ciph return &ciphersuite.TLSEcdheEcdsaWithAes256GcmSha384{} case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: return &ciphersuite.TLSEcdheRsaWithAes256GcmSha384{} - case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256: - return ciphersuite.NewTLSEcdhePskWithAes128CbcSha256() } if customCiphers != nil { @@ -179,7 +152,6 @@ func allCipherSuites() []CipherSuite { &ciphersuite.TLSEcdheRsaWithAes256CbcSha{}, ciphersuite.NewTLSPskWithAes128Ccm(), ciphersuite.NewTLSPskWithAes128Ccm8(), - ciphersuite.NewTLSPskWithAes256Ccm8(), &ciphersuite.TLSPskWithAes128GcmSha256{}, &ciphersuite.TLSEcdheEcdsaWithAes256GcmSha384{}, &ciphersuite.TLSEcdheRsaWithAes256GcmSha384{}, @@ -200,7 +172,7 @@ func parseCipherSuites(userSelectedSuites []CipherSuiteID, customCipherSuites fu for _, id := range ids { c := cipherSuiteForID(id, nil) if c == nil { - return nil, &invalidCipherSuiteError{id} + return nil, &invalidCipherSuite{id} } cipherSuites = append(cipherSuites, c) } diff --git a/vendor/github.com/pion/dtls/v2/cipher_suite_go114.go b/vendor/github.com/pion/dtls/v2/cipher_suite_go114.go index fd46d7bd9..5c63c0913 100644 --- a/vendor/github.com/pion/dtls/v2/cipher_suite_go114.go +++ b/vendor/github.com/pion/dtls/v2/cipher_suite_go114.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build go1.14 // +build go1.14 diff --git a/vendor/github.com/pion/dtls/v2/codecov.yml b/vendor/github.com/pion/dtls/v2/codecov.yml index 263e4d45c..085200a48 100644 --- a/vendor/github.com/pion/dtls/v2/codecov.yml +++ b/vendor/github.com/pion/dtls/v2/codecov.yml @@ -3,8 +3,6 @@ # # It is automatically copied from https://github.com/pion/.goassets repository. # -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT coverage: status: diff --git a/vendor/github.com/pion/dtls/v2/compression_method.go b/vendor/github.com/pion/dtls/v2/compression_method.go index 7e44de009..693eb7a52 100644 --- a/vendor/github.com/pion/dtls/v2/compression_method.go +++ b/vendor/github.com/pion/dtls/v2/compression_method.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import "github.com/pion/dtls/v2/pkg/protocol" diff --git a/vendor/github.com/pion/dtls/v2/config.go b/vendor/github.com/pion/dtls/v2/config.go index fbc3ee247..7f68c03b1 100644 --- a/vendor/github.com/pion/dtls/v2/config.go +++ b/vendor/github.com/pion/dtls/v2/config.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -13,7 +10,6 @@ import ( "io" "time" - "github.com/pion/dtls/v2/pkg/crypto/elliptic" "github.com/pion/logging" ) @@ -86,16 +82,6 @@ type Config struct { // be considered but the verifiedChains will always be nil. VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error - // VerifyConnection, if not nil, is called after normal certificate - // verification/PSK and after VerifyPeerCertificate by either a TLS client - // or server. If it returns a non-nil error, the handshake is aborted - // and that error results. - // - // If normal verification fails then the handshake will abort before - // considering this callback. This callback will run for all connections - // regardless of InsecureSkipVerify or ClientAuth settings. - VerifyConnection func(*State) error - // RootCAs defines the set of root certificate authorities // that one peer uses when verifying the other peer's certificates. // If RootCAs is nil, TLS uses the host's root CA set. @@ -144,38 +130,6 @@ type Config struct { // List of application protocols the peer supports, for ALPN SupportedProtocols []string - - // List of Elliptic Curves to use - // - // If an ECC ciphersuite is configured and EllipticCurves is empty - // it will default to X25519, P-256, P-384 in this specific order. - EllipticCurves []elliptic.Curve - - // GetCertificate returns a Certificate based on the given - // ClientHelloInfo. It will only be called if the client supplies SNI - // information or if Certificates is empty. - // - // If GetCertificate is nil or returns nil, then the certificate is - // retrieved from NameToCertificate. If NameToCertificate is nil, the - // best element of Certificates will be used. - GetCertificate func(*ClientHelloInfo) (*tls.Certificate, error) - - // GetClientCertificate, if not nil, is called when a server requests a - // certificate from a client. If set, the contents of Certificates will - // be ignored. - // - // If GetClientCertificate returns an error, the handshake will be - // aborted and that error will be returned. Otherwise - // GetClientCertificate must return a non-nil Certificate. If - // Certificate.Certificate is empty then no certificate will be sent to - // the server. If this is unacceptable to the server then it may abort - // the handshake. - GetClientCertificate func(*CertificateRequestInfo) (*tls.Certificate, error) - - // InsecureSkipVerifyHello, if true and when acting as server, allow client to - // skip hello verify phase and receive ServerHello after initial ClientHello. - // This have implication on DoS attack resistance. - InsecureSkipVerifyHello bool } func defaultConnectContextMaker() (context.Context, func()) { @@ -189,14 +143,8 @@ func (c *Config) connectContextMaker() (context.Context, func()) { return c.ConnectContextMaker() } -func (c *Config) includeCertificateSuites() bool { - return c.PSK == nil || len(c.Certificates) > 0 || c.GetCertificate != nil || c.GetClientCertificate != nil -} - const defaultMTU = 1200 // bytes -var defaultCurves = []elliptic.Curve{elliptic.X25519, elliptic.P256, elliptic.P384} //nolint:gochecknoglobals - // PSKCallback is called once we have the remote's PSKIdentityHint. // If the remote provided none it will be nil type PSKCallback func([]byte) ([]byte, error) @@ -248,6 +196,6 @@ func validateConfig(config *Config) error { } } - _, err := parseCipherSuites(config.CipherSuites, config.CustomCipherSuites, config.includeCertificateSuites(), config.PSK != nil) + _, err := parseCipherSuites(config.CipherSuites, config.CustomCipherSuites, config.PSK == nil || len(config.Certificates) > 0, config.PSK != nil) return err } diff --git a/vendor/github.com/pion/dtls/v2/conn.go b/vendor/github.com/pion/dtls/v2/conn.go index 2b7585108..fd8cf734d 100644 --- a/vendor/github.com/pion/dtls/v2/conn.go +++ b/vendor/github.com/pion/dtls/v2/conn.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -21,9 +18,9 @@ import ( "github.com/pion/dtls/v2/pkg/protocol/handshake" "github.com/pion/dtls/v2/pkg/protocol/recordlayer" "github.com/pion/logging" - "github.com/pion/transport/v2/connctx" - "github.com/pion/transport/v2/deadline" - "github.com/pion/transport/v2/replaydetector" + "github.com/pion/transport/connctx" + "github.com/pion/transport/deadline" + "github.com/pion/transport/replaydetector" ) const ( @@ -91,7 +88,7 @@ func createConn(ctx context.Context, nextConn net.Conn, config *Config, isClient return nil, errNilNextConn } - cipherSuites, err := parseCipherSuites(config.CipherSuites, config.CustomCipherSuites, config.includeCertificateSuites(), config.PSK != nil) + cipherSuites, err := parseCipherSuites(config.CipherSuites, config.CustomCipherSuites, config.PSK == nil || len(config.Certificates) > 0, config.PSK != nil) if err != nil { return nil, err } @@ -157,11 +154,6 @@ func createConn(ctx context.Context, nextConn net.Conn, config *Config, isClient serverName = "" } - curves := config.EllipticCurves - if len(curves) == 0 { - curves = defaultCurves - } - hsCfg := &handshakeConfig{ localPSKCallback: config.PSK, localPSKIdentityHint: config.PSKIdentityHint, @@ -175,7 +167,6 @@ func createConn(ctx context.Context, nextConn net.Conn, config *Config, isClient localCertificates: config.Certificates, insecureSkipVerify: config.InsecureSkipVerify, verifyPeerCertificate: config.VerifyPeerCertificate, - verifyConnection: config.VerifyConnection, rootCAs: config.RootCAs, clientCAs: config.ClientCAs, customCipherSuites: config.CustomCipherSuites, @@ -184,22 +175,13 @@ func createConn(ctx context.Context, nextConn net.Conn, config *Config, isClient initialEpoch: 0, keyLogWriter: config.KeyLogWriter, sessionStore: config.SessionStore, - ellipticCurves: curves, - localGetCertificate: config.GetCertificate, - localGetClientCertificate: config.GetClientCertificate, - insecureSkipHelloVerify: config.InsecureSkipVerifyHello, } - // rfc5246#section-7.4.3 - // In addition, the hash and signature algorithms MUST be compatible - // with the key in the server's end-entity certificate. - if !isClient { - cert, err := hsCfg.getCertificate(&ClientHelloInfo{}) - if err != nil && !errors.Is(err, errNoCertificates) { - return nil, err - } - hsCfg.localCipherSuites = filterCipherSuitesForCertificate(cert, cipherSuites) + cert, err := hsCfg.getCertificate(serverName) + if err != nil && !errors.Is(err, errNoCertificates) { + return nil, err } + hsCfg.localCipherSuites = filterCipherSuitesForCertificate(cert, cipherSuites) var initialFlight flightVal var initialFSMState handshakeState @@ -345,7 +327,7 @@ func (c *Conn) Write(p []byte) (int, error) { { record: &recordlayer.RecordLayer{ Header: recordlayer.Header{ - Epoch: c.state.getLocalEpoch(), + Epoch: c.getLocalEpoch(), Version: protocol.Version1_2, }, Content: &protocol.ApplicationData{ @@ -359,7 +341,7 @@ func (c *Conn) Write(p []byte) (int, error) { // Close closes the connection. func (c *Conn) Close() error { - err := c.close(true) //nolint:contextcheck + err := c.close(true) c.handshakeLoopsFinished.Wait() return err } @@ -430,11 +412,6 @@ func (c *Conn) writePackets(ctx context.Context, pkts []*packet) error { } func (c *Conn) compactRawPackets(rawPackets [][]byte) [][]byte { - // avoid a useless copy in the common case - if len(rawPackets) == 1 { - return rawPackets - } - combinedRawPackets := make([][]byte, 0) currentCombinedRawPacket := make([]byte, 0) @@ -507,14 +484,14 @@ func (c *Conn) processHandshakePacket(p *packet, h *handshake.Handshake) ([][]by SequenceNumber: seq, } - rawPacket, err := recordlayerHeader.Marshal() + recordlayerHeaderBytes, err := recordlayerHeader.Marshal() if err != nil { return nil, err } p.record.Header = *recordlayerHeader - rawPacket = append(rawPacket, handshakeFragment...) + rawPacket := append(recordlayerHeaderBytes, handshakeFragment...) if p.shouldEncrypt { var err error rawPacket, err = c.state.cipherSuite.Encrypt(p.record, rawPacket) @@ -558,12 +535,12 @@ func (c *Conn) fragmentHandshake(h *handshake.Handshake) ([][]byte, error) { offset += contentFragmentLen - fragmentedHandshake, err := headerFragment.Marshal() + headerFragmentRaw, err := headerFragment.Marshal() if err != nil { return nil, err } - fragmentedHandshake = append(fragmentedHandshake, contentFragment...) + fragmentedHandshake := append(headerFragmentRaw, contentFragment...) fragmentedHandshakes = append(fragmentedHandshakes, fragmentedHandshake) } @@ -578,10 +555,7 @@ var poolReadBuffer = sync.Pool{ //nolint:gochecknoglobals } func (c *Conn) readAndBuffer(ctx context.Context) error { - bufptr, ok := poolReadBuffer.Get().(*[]byte) - if !ok { - return errFailedToAccessPoolReadBuffer - } + bufptr := poolReadBuffer.Get().(*[]byte) defer poolReadBuffer.Put(bufptr) b := *bufptr @@ -608,13 +582,13 @@ func (c *Conn) readAndBuffer(ctx context.Context) error { if hs { hasHandshake = true } - - var e *alertError - if errors.As(err, &e) { + switch e := err.(type) { + case nil: + case *errAlert: if e.IsFatalOrCloseNotify() { return e } - } else if err != nil { + default: return e } } @@ -644,12 +618,13 @@ func (c *Conn) handleQueuedPackets(ctx context.Context) error { } } } - var e *alertError - if errors.As(err, &e) { + switch e := err.(type) { + case nil: + case *errAlert: if e.IsFatalOrCloseNotify() { return e } - } else if err != nil { + default: return e } } @@ -666,7 +641,7 @@ func (c *Conn) handleIncomingPacket(ctx context.Context, buf []byte, enqueue boo } // Validate epoch - remoteEpoch := c.state.getRemoteEpoch() + remoteEpoch := c.getRemoteEpoch() if h.Epoch > remoteEpoch { if h.Epoch > remoteEpoch+1 { c.log.Debugf("discarded future packet (epoch: %d, seq: %d)", @@ -722,12 +697,13 @@ func (c *Conn) handleIncomingPacket(ctx context.Context, buf []byte, enqueue boo } else if isHandshake { markPacketAsValid() for out, epoch := c.fragmentBuffer.pop(); out != nil; out, epoch = c.fragmentBuffer.pop() { - header := &handshake.Header{} - if err := header.Unmarshal(out); err != nil { + rawHandshake := &handshake.Handshake{} + if err := rawHandshake.Unmarshal(out); err != nil { c.log.Debugf("%s: handshake parse failed: %s", srvCliStr(c.state.isClient), err) continue } - c.handshakeCache.push(out, epoch, header.MessageSequence, header.Type, !c.state.isClient) + + _ = c.handshakeCache.push(out, epoch, rawHandshake.Header.MessageSequence, rawHandshake.Header.Type, !c.state.isClient) } return true, nil, nil @@ -747,7 +723,7 @@ func (c *Conn) handleIncomingPacket(ctx context.Context, buf []byte, enqueue boo a = &alert.Alert{Level: alert.Warning, Description: alert.CloseNotify} } markPacketAsValid() - return false, a, &alertError{content} + return false, a, &errAlert{content} case *protocol.ChangeCipherSpec: if c.state.cipherSuite == nil || !c.state.cipherSuite.IsInitialized() { if enqueue { @@ -760,7 +736,7 @@ func (c *Conn) handleIncomingPacket(ctx context.Context, buf []byte, enqueue boo newRemoteEpoch := h.Epoch + 1 c.log.Tracef("%s: <- ChangeCipherSpec (epoch: %d)", srvCliStr(c.state.isClient), newRemoteEpoch) - if c.state.getRemoteEpoch()+1 == newRemoteEpoch { + if c.getRemoteEpoch()+1 == newRemoteEpoch { c.setRemoteEpoch(newRemoteEpoch) markPacketAsValid() } @@ -802,7 +778,7 @@ func (c *Conn) notify(ctx context.Context, level alert.Level, desc alert.Descrip { record: &recordlayer.RecordLayer{ Header: recordlayer.Header{ - Epoch: c.state.getLocalEpoch(), + Epoch: c.getLocalEpoch(), Version: protocol.Version1_2, }, Content: &alert.Alert{ @@ -868,8 +844,8 @@ func (c *Conn) handshake(ctx context.Context, cfg *handshakeConfig, initialFligh defer c.handshakeLoopsFinished.Done() for { if err := c.readAndBuffer(ctxRead); err != nil { - var e *alertError - if errors.As(err, &e) { + switch e := err.(type) { + case *errAlert: if !e.IsFatalOrCloseNotify() { if c.isHandshakeCompletedSuccessfully() { // Pass the error to Read() @@ -881,9 +857,9 @@ func (c *Conn) handshake(ctx context.Context, cfg *handshakeConfig, initialFligh } continue // non-fatal alert must not stop read loop } - } else { - switch { - case errors.Is(err, context.DeadlineExceeded), errors.Is(err, context.Canceled), errors.Is(err, io.EOF): + case error: + switch err { + case context.DeadlineExceeded, context.Canceled, io.EOF: default: if c.isHandshakeCompletedSuccessfully() { // Keep read loop and pass the read error to Read() @@ -896,21 +872,16 @@ func (c *Conn) handshake(ctx context.Context, cfg *handshakeConfig, initialFligh } } } - select { case firstErr <- err: default: } - if e != nil { + if e, ok := err.(*errAlert); ok { if e.IsFatalOrCloseNotify() { - _ = c.close(false) //nolint:contextcheck + _ = c.close(false) } } - if !c.isConnectionClosed() && errors.Is(err, context.Canceled) { - c.log.Trace("handshake timeouts - closing underline connection") - _ = c.close(false) //nolint:contextcheck - } return } } @@ -920,12 +891,10 @@ func (c *Conn) handshake(ctx context.Context, cfg *handshakeConfig, initialFligh case err := <-firstErr: cancelRead() cancel() - c.handshakeLoopsFinished.Wait() return c.translateHandshakeCtxError(err) case <-ctx.Done(): cancelRead() cancel() - c.handshakeLoopsFinished.Wait() return c.translateHandshakeCtxError(ctx.Err()) case <-done: return nil @@ -958,7 +927,6 @@ func (c *Conn) close(byUser bool) error { if byUser { c.connectionClosedByUser = true } - isClosed := c.isConnectionClosed() c.closed.Close() c.closeLock.Unlock() @@ -966,10 +934,6 @@ func (c *Conn) close(byUser bool) error { return ErrConnClosed } - if isClosed { - return nil - } - return c.nextConn.Close() } @@ -986,10 +950,18 @@ func (c *Conn) setLocalEpoch(epoch uint16) { c.state.localEpoch.Store(epoch) } +func (c *Conn) getLocalEpoch() uint16 { + return c.state.localEpoch.Load().(uint16) +} + func (c *Conn) setRemoteEpoch(epoch uint16) { c.state.remoteEpoch.Store(epoch) } +func (c *Conn) getRemoteEpoch() uint16 { + return c.state.remoteEpoch.Load().(uint16) +} + // LocalAddr implements net.Conn.LocalAddr func (c *Conn) LocalAddr() net.Addr { return c.nextConn.LocalAddr() diff --git a/vendor/github.com/pion/dtls/v2/crypto.go b/vendor/github.com/pion/dtls/v2/crypto.go index 968910c7e..768ee470e 100644 --- a/vendor/github.com/pion/dtls/v2/crypto.go +++ b/vendor/github.com/pion/dtls/v2/crypto.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -111,13 +108,6 @@ func verifyKeySignature(message, remoteKeySignature []byte, hashAlgorithm hash.A // the private key in the certificate. // https://tools.ietf.org/html/rfc5246#section-7.3 func generateCertificateVerify(handshakeBodies []byte, privateKey crypto.PrivateKey, hashAlgorithm hash.Algorithm) ([]byte, error) { - if p, ok := privateKey.(ed25519.PrivateKey); ok { - // https://pkg.go.dev/crypto/ed25519#PrivateKey.Sign - // Sign signs the given message with priv. Ed25519 performs two passes over - // messages to be signed and therefore cannot handle pre-hashed messages. - return p.Sign(rand.Reader, handshakeBodies, crypto.Hash(0)) - } - h := sha256.New() if _, err := h.Write(handshakeBodies); err != nil { return nil, err @@ -125,6 +115,9 @@ func generateCertificateVerify(handshakeBodies []byte, privateKey crypto.Private hashed := h.Sum(nil) switch p := privateKey.(type) { + case ed25519.PrivateKey: + // https://crypto.stackexchange.com/a/55483 + return p.Sign(rand.Reader, hashed, crypto.Hash(0)) case *ecdsa.PrivateKey: return p.Sign(rand.Reader, hashed, hashAlgorithm.CryptoHash()) case *rsa.PrivateKey: diff --git a/vendor/github.com/pion/dtls/v2/dtls.go b/vendor/github.com/pion/dtls/v2/dtls.go index b799770d8..125b904e5 100644 --- a/vendor/github.com/pion/dtls/v2/dtls.go +++ b/vendor/github.com/pion/dtls/v2/dtls.go @@ -1,5 +1,2 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package dtls implements Datagram Transport Layer Security (DTLS) 1.2 package dtls diff --git a/vendor/github.com/pion/dtls/v2/errors.go b/vendor/github.com/pion/dtls/v2/errors.go index 025d8645e..2e1638828 100644 --- a/vendor/github.com/pion/dtls/v2/errors.go +++ b/vendor/github.com/pion/dtls/v2/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -13,13 +10,14 @@ import ( "github.com/pion/dtls/v2/pkg/protocol" "github.com/pion/dtls/v2/pkg/protocol/alert" + "golang.org/x/xerrors" ) // Typed errors var ( ErrConnClosed = &FatalError{Err: errors.New("conn is closed")} //nolint:goerr113 - errDeadlineExceeded = &TimeoutError{Err: fmt.Errorf("read/write timeout: %w", context.DeadlineExceeded)} + errDeadlineExceeded = &TimeoutError{Err: xerrors.Errorf("read/write timeout: %w", context.DeadlineExceeded)} errInvalidContentType = &TemporaryError{Err: errors.New("invalid content type")} //nolint:goerr113 errBufferTooSmall = &TemporaryError{Err: errors.New("buffer is too small")} //nolint:goerr113 @@ -57,7 +55,6 @@ var ( errServerNoMatchingSRTPProfile = &FatalError{Err: errors.New("client requested SRTP but we have no matching profiles")} //nolint:goerr113 errServerRequiredButNoClientEMS = &FatalError{Err: errors.New("server requires the Extended Master Secret extension, but the client does not support it")} //nolint:goerr113 errVerifyDataMismatch = &FatalError{Err: errors.New("expected and actual verify data does not match")} //nolint:goerr113 - errNotAcceptableCertificateChain = &FatalError{Err: errors.New("certificate chain is not signed by an acceptable CA")} //nolint:goerr113 errInvalidFlight = &InternalError{Err: errors.New("invalid flight number")} //nolint:goerr113 errKeySignatureGenerateUnimplemented = &InternalError{Err: errors.New("unable to generate key signature, unimplemented")} //nolint:goerr113 @@ -65,8 +62,6 @@ var ( errLengthMismatch = &InternalError{Err: errors.New("data length and declared length do not match")} //nolint:goerr113 errSequenceNumberOverflow = &InternalError{Err: errors.New("sequence number overflow")} //nolint:goerr113 errInvalidFSMTransition = &InternalError{Err: errors.New("invalid state machine transition")} //nolint:goerr113 - errFailedToAccessPoolReadBuffer = &InternalError{Err: errors.New("failed to access pool read buffer")} //nolint:goerr113 - errFragmentBufferOverflow = &InternalError{Err: errors.New("fragment buffer overflow")} //nolint:goerr113 ) // FatalError indicates that the DTLS connection is no longer available. @@ -86,39 +81,37 @@ type TimeoutError = protocol.TimeoutError // HandshakeError indicates that the handshake failed. type HandshakeError = protocol.HandshakeError -// errInvalidCipherSuite indicates an attempt at using an unsupported cipher suite. -type invalidCipherSuiteError struct { +// invalidCipherSuite indicates an attempt at using an unsupported cipher suite. +type invalidCipherSuite struct { id CipherSuiteID } -func (e *invalidCipherSuiteError) Error() string { +func (e *invalidCipherSuite) Error() string { return fmt.Sprintf("CipherSuite with id(%d) is not valid", e.id) } -func (e *invalidCipherSuiteError) Is(err error) bool { - var other *invalidCipherSuiteError - if errors.As(err, &other) { +func (e *invalidCipherSuite) Is(err error) bool { + if other, ok := err.(*invalidCipherSuite); ok { return e.id == other.id } return false } // errAlert wraps DTLS alert notification as an error -type alertError struct { +type errAlert struct { *alert.Alert } -func (e *alertError) Error() string { +func (e *errAlert) Error() string { return fmt.Sprintf("alert: %s", e.Alert.String()) } -func (e *alertError) IsFatalOrCloseNotify() bool { +func (e *errAlert) IsFatalOrCloseNotify() bool { return e.Level == alert.Fatal || e.Description == alert.CloseNotify } -func (e *alertError) Is(err error) bool { - var other *alertError - if errors.As(err, &other) { +func (e *errAlert) Is(err error) bool { + if other, ok := err.(*errAlert); ok { return e.Level == other.Level && e.Description == other.Description } return false @@ -126,20 +119,14 @@ func (e *alertError) Is(err error) bool { // netError translates an error from underlying Conn to corresponding net.Error. func netError(err error) error { - switch { - case errors.Is(err, io.EOF), errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded): + switch err { + case io.EOF, context.Canceled, context.DeadlineExceeded: // Return io.EOF and context errors as is. return err } - - var ( - ne net.Error - opError *net.OpError - se *os.SyscallError - ) - - if errors.As(err, &opError) { - if errors.As(opError, &se) { + switch e := err.(type) { + case (*net.OpError): + if se, ok := e.Err.(*os.SyscallError); ok { if se.Timeout() { return &TimeoutError{Err: err} } @@ -147,11 +134,8 @@ func netError(err error) error { return &TemporaryError{Err: err} } } - } - - if errors.As(err, &ne) { + case (net.Error): return err } - return &FatalError{Err: err} } diff --git a/vendor/github.com/pion/dtls/v2/errors_errno.go b/vendor/github.com/pion/dtls/v2/errors_errno.go index f8e424eb3..c03779a45 100644 --- a/vendor/github.com/pion/dtls/v2/errors_errno.go +++ b/vendor/github.com/pion/dtls/v2/errors_errno.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build aix || darwin || dragonfly || freebsd || linux || nacl || nacljs || netbsd || openbsd || solaris || windows // +build aix darwin dragonfly freebsd linux nacl nacljs netbsd openbsd solaris windows @@ -12,11 +9,18 @@ package dtls import ( - "errors" "os" "syscall" ) func isOpErrorTemporary(err *os.SyscallError) bool { - return errors.Is(err.Err, syscall.ECONNREFUSED) + if ne, ok := err.Err.(syscall.Errno); ok { + switch ne { + case syscall.ECONNREFUSED: + return true + default: + return false + } + } + return false } diff --git a/vendor/github.com/pion/dtls/v2/errors_noerrno.go b/vendor/github.com/pion/dtls/v2/errors_noerrno.go index 844ff1e75..ad1bf8523 100644 --- a/vendor/github.com/pion/dtls/v2/errors_noerrno.go +++ b/vendor/github.com/pion/dtls/v2/errors_noerrno.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !aix && !darwin && !dragonfly && !freebsd && !linux && !nacl && !nacljs && !netbsd && !openbsd && !solaris && !windows // +build !aix,!darwin,!dragonfly,!freebsd,!linux,!nacl,!nacljs,!netbsd,!openbsd,!solaris,!windows diff --git a/vendor/github.com/pion/dtls/v2/flight.go b/vendor/github.com/pion/dtls/v2/flight.go index cfa58c574..bed3f8c9a 100644 --- a/vendor/github.com/pion/dtls/v2/flight.go +++ b/vendor/github.com/pion/dtls/v2/flight.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls /* diff --git a/vendor/github.com/pion/dtls/v2/flight0handler.go b/vendor/github.com/pion/dtls/v2/flight0handler.go index ec766ddff..23dddeda6 100644 --- a/vendor/github.com/pion/dtls/v2/flight0handler.go +++ b/vendor/github.com/pion/dtls/v2/flight0handler.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -14,8 +11,8 @@ import ( "github.com/pion/dtls/v2/pkg/protocol/handshake" ) -func flight0Parse(_ context.Context, _ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { - seq, msgs, ok := cache.fullPullMap(0, state.cipherSuite, +func flight0Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { + seq, msgs, ok := cache.fullPullMap(0, handshakeCachePullRule{handshake.TypeClientHello, cfg.initialEpoch, true, false}, ) if !ok { @@ -84,13 +81,7 @@ func flight0Parse(_ context.Context, _ flightConn, state *State, cache *handshak } } - nextFlight := flight2 - - if cfg.insecureSkipHelloVerify { - nextFlight = flight4 - } - - return handleHelloResume(clientHello.SessionID, state, cfg, nextFlight) + return handleHelloResume(clientHello.SessionID, state, cfg, flight2) } func handleHelloResume(sessionID []byte, state *State, cfg *handshakeConfig, next flightVal) (flightVal, *alert.Alert, error) { @@ -116,13 +107,11 @@ func handleHelloResume(sessionID []byte, state *State, cfg *handshakeConfig, nex return next, nil, nil } -func flight0Generate(_ flightConn, state *State, _ *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { +func flight0Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { // Initialize - if !cfg.insecureSkipHelloVerify { - state.cookie = make([]byte, cookieLength) - if _, err := rand.Read(state.cookie); err != nil { - return nil, nil, err - } + state.cookie = make([]byte, cookieLength) + if _, err := rand.Read(state.cookie); err != nil { + return nil, nil, err } var zeroEpoch uint16 diff --git a/vendor/github.com/pion/dtls/v2/flight1handler.go b/vendor/github.com/pion/dtls/v2/flight1handler.go index 94fdc222d..48c82013c 100644 --- a/vendor/github.com/pion/dtls/v2/flight1handler.go +++ b/vendor/github.com/pion/dtls/v2/flight1handler.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -17,7 +14,7 @@ import ( func flight1Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { // HelloVerifyRequest can be skipped by the server, // so allow ServerHello during flight1 also - seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite, + seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, handshakeCachePullRule{handshake.TypeHelloVerifyRequest, cfg.initialEpoch, false, true}, handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, true}, ) @@ -46,7 +43,7 @@ func flight1Parse(ctx context.Context, c flightConn, state *State, cache *handsh return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, nil } -func flight1Generate(c flightConn, state *State, _ *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { +func flight1Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { var zeroEpoch uint16 state.localEpoch.Store(zeroEpoch) state.remoteEpoch.Store(zeroEpoch) @@ -65,19 +62,10 @@ func flight1Generate(c flightConn, state *State, _ *handshakeCache, cfg *handsha RenegotiatedConnection: 0, }, } - - var setEllipticCurveCryptographyClientHelloExtensions bool - for _, c := range cfg.localCipherSuites { - if c.ECC() { - setEllipticCurveCryptographyClientHelloExtensions = true - break - } - } - - if setEllipticCurveCryptographyClientHelloExtensions { + if cfg.localPSKCallback == nil { extensions = append(extensions, []extension.Extension{ &extension.SupportedEllipticCurves{ - EllipticCurves: cfg.ellipticCurves, + EllipticCurves: []elliptic.Curve{elliptic.X25519, elliptic.P256, elliptic.P384}, }, &extension.SupportedPointFormats{ PointFormats: []elliptic.CurvePointFormat{elliptic.CurvePointFormatUncompressed}, diff --git a/vendor/github.com/pion/dtls/v2/flight2handler.go b/vendor/github.com/pion/dtls/v2/flight2handler.go index 26e57d2f2..bb8e91db0 100644 --- a/vendor/github.com/pion/dtls/v2/flight2handler.go +++ b/vendor/github.com/pion/dtls/v2/flight2handler.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -14,7 +11,7 @@ import ( ) func flight2Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { - seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite, + seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, handshakeCachePullRule{handshake.TypeClientHello, cfg.initialEpoch, true, false}, ) if !ok { @@ -44,7 +41,7 @@ func flight2Parse(ctx context.Context, c flightConn, state *State, cache *handsh return flight4, nil, nil } -func flight2Generate(_ flightConn, state *State, _ *handshakeCache, _ *handshakeConfig) ([]*packet, *alert.Alert, error) { +func flight2Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { state.handshakeSendSequence = 0 return []*packet{ { diff --git a/vendor/github.com/pion/dtls/v2/flight3handler.go b/vendor/github.com/pion/dtls/v2/flight3handler.go index 5a763dc08..697b304c4 100644 --- a/vendor/github.com/pion/dtls/v2/flight3handler.go +++ b/vendor/github.com/pion/dtls/v2/flight3handler.go @@ -1,13 +1,9 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( "bytes" "context" - "github.com/pion/dtls/v2/internal/ciphersuite/types" "github.com/pion/dtls/v2/pkg/crypto/elliptic" "github.com/pion/dtls/v2/pkg/crypto/prf" "github.com/pion/dtls/v2/pkg/protocol" @@ -21,7 +17,7 @@ func flight3Parse(ctx context.Context, c flightConn, state *State, cache *handsh // Clients may receive multiple HelloVerifyRequest messages with different cookies. // Clients SHOULD handle this by sending a new ClientHello with a cookie in response // to the new HelloVerifyRequest. RFC 6347 Section 4.2.1 - seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite, + seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, handshakeCachePullRule{handshake.TypeHelloVerifyRequest, cfg.initialEpoch, false, true}, ) if ok { @@ -37,7 +33,7 @@ func flight3Parse(ctx context.Context, c flightConn, state *State, cache *handsh } } - _, msgs, ok = cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite, + _, msgs, ok = cache.fullPullMap(state.handshakeRecvSequence, handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, false}, ) if !ok { @@ -110,12 +106,12 @@ func flight3Parse(ctx context.Context, c flightConn, state *State, cache *handsh } if cfg.localPSKCallback != nil { - seq, msgs, ok = cache.fullPullMap(state.handshakeRecvSequence+1, state.cipherSuite, + seq, msgs, ok = cache.fullPullMap(state.handshakeRecvSequence+1, handshakeCachePullRule{handshake.TypeServerKeyExchange, cfg.initialEpoch, false, true}, handshakeCachePullRule{handshake.TypeServerHelloDone, cfg.initialEpoch, false, false}, ) } else { - seq, msgs, ok = cache.fullPullMap(state.handshakeRecvSequence+1, state.cipherSuite, + seq, msgs, ok = cache.fullPullMap(state.handshakeRecvSequence+1, handshakeCachePullRule{handshake.TypeCertificate, cfg.initialEpoch, false, true}, handshakeCachePullRule{handshake.TypeServerKeyExchange, cfg.initialEpoch, false, false}, handshakeCachePullRule{handshake.TypeCertificateRequest, cfg.initialEpoch, false, true}, @@ -158,7 +154,7 @@ func handleResumption(ctx context.Context, c flightConn, state *State, cache *ha return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err } - _, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence+1, state.cipherSuite, + _, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence+1, handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, false, false}, ) if !ok { @@ -191,29 +187,13 @@ func handleResumption(ctx context.Context, c flightConn, state *State, cache *ha func handleServerKeyExchange(_ flightConn, state *State, cfg *handshakeConfig, h *handshake.MessageServerKeyExchange) (*alert.Alert, error) { var err error - if state.cipherSuite == nil { - return &alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}, errInvalidCipherSuite - } if cfg.localPSKCallback != nil { var psk []byte if psk, err = cfg.localPSKCallback(h.IdentityHint); err != nil { return &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err } state.IdentityHint = h.IdentityHint - switch state.cipherSuite.KeyExchangeAlgorithm() { - case types.KeyExchangeAlgorithmPsk: - state.preMasterSecret = prf.PSKPreMasterSecret(psk) - case (types.KeyExchangeAlgorithmEcdhe | types.KeyExchangeAlgorithmPsk): - if state.localKeypair, err = elliptic.GenerateKeypair(h.NamedCurve); err != nil { - return &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err - } - state.preMasterSecret, err = prf.EcdhePSKPreMasterSecret(psk, h.PublicKey, state.localKeypair.PrivateKey, state.localKeypair.Curve) - if err != nil { - return &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err - } - default: - return &alert.Alert{Level: alert.Fatal, Description: alert.InsufficientSecurity}, errInvalidCipherSuite - } + state.preMasterSecret = prf.PSKPreMasterSecret(psk) } else { if state.localKeypair, err = elliptic.GenerateKeypair(h.NamedCurve); err != nil { return &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err @@ -224,10 +204,10 @@ func handleServerKeyExchange(_ flightConn, state *State, cfg *handshakeConfig, h } } - return nil, nil //nolint:nilnil + return nil, nil } -func flight3Generate(_ flightConn, state *State, _ *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { +func flight3Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { extensions := []extension.Extension{ &extension.SupportedSignatureAlgorithms{ SignatureHashAlgorithms: cfg.localSignatureSchemes, @@ -236,7 +216,7 @@ func flight3Generate(_ flightConn, state *State, _ *handshakeCache, cfg *handsha RenegotiatedConnection: 0, }, } - if state.namedCurve != 0 { + if cfg.localPSKCallback == nil { extensions = append(extensions, []extension.Extension{ &extension.SupportedEllipticCurves{ EllipticCurves: []elliptic.Curve{elliptic.X25519, elliptic.P256, elliptic.P384}, diff --git a/vendor/github.com/pion/dtls/v2/flight4bhandler.go b/vendor/github.com/pion/dtls/v2/flight4bhandler.go index 6bbbc5972..36cd0b45f 100644 --- a/vendor/github.com/pion/dtls/v2/flight4bhandler.go +++ b/vendor/github.com/pion/dtls/v2/flight4bhandler.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -15,8 +12,8 @@ import ( "github.com/pion/dtls/v2/pkg/protocol/recordlayer" ) -func flight4bParse(_ context.Context, _ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { - _, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite, +func flight4bParse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { + _, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, true, false}, ) if !ok { @@ -47,7 +44,7 @@ func flight4bParse(_ context.Context, _ flightConn, state *State, cache *handsha return flight4b, nil, nil } -func flight4bGenerate(_ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { +func flight4bGenerate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { var pkts []*packet extensions := []extension.Extension{&extension.RenegotiationInfo{ diff --git a/vendor/github.com/pion/dtls/v2/flight4handler.go b/vendor/github.com/pion/dtls/v2/flight4handler.go index 67a486461..a6ba36c2c 100644 --- a/vendor/github.com/pion/dtls/v2/flight4handler.go +++ b/vendor/github.com/pion/dtls/v2/flight4handler.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -8,7 +5,6 @@ import ( "crypto/rand" "crypto/x509" - "github.com/pion/dtls/v2/internal/ciphersuite" "github.com/pion/dtls/v2/pkg/crypto/clientcertificate" "github.com/pion/dtls/v2/pkg/crypto/elliptic" "github.com/pion/dtls/v2/pkg/crypto/prf" @@ -21,7 +17,7 @@ import ( ) func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { //nolint:gocognit - seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite, + seq, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, handshakeCachePullRule{handshake.TypeCertificate, cfg.initialEpoch, true, true}, handshakeCachePullRule{handshake.TypeClientKeyExchange, cfg.initialEpoch, true, false}, handshakeCachePullRule{handshake.TypeCertificateVerify, cfg.initialEpoch, true, true}, @@ -93,10 +89,6 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh } } state.peerCertificatesVerified = verified - } else if state.PeerCertificates != nil { - // A certificate was received, but we haven't seen a CertificateVerify - // keep reading until we receive one - return 0, nil, nil } if !state.cipherSuite.IsInitialized() { @@ -111,16 +103,7 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err } state.IdentityHint = clientKeyExchange.IdentityHint - switch state.cipherSuite.KeyExchangeAlgorithm() { - case CipherSuiteKeyExchangeAlgorithmPsk: - preMasterSecret = prf.PSKPreMasterSecret(psk) - case (CipherSuiteKeyExchangeAlgorithmPsk | CipherSuiteKeyExchangeAlgorithmEcdhe): - if preMasterSecret, err = prf.EcdhePSKPreMasterSecret(psk, clientKeyExchange.PublicKey, state.localKeypair.PrivateKey, state.localKeypair.Curve); err != nil { - return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err - } - default: - return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, errInvalidCipherSuite - } + preMasterSecret = prf.PSKPreMasterSecret(psk) } else { preMasterSecret, err = prf.PreMasterSecret(clientKeyExchange.PublicKey, state.localKeypair.PrivateKey, state.localKeypair.Curve) if err != nil { @@ -168,7 +151,7 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh return 0, &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err } - seq, msgs, ok = cache.fullPullMap(seq, state.cipherSuite, + seq, msgs, ok = cache.fullPullMap(seq, handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, true, false}, ) if !ok { @@ -182,11 +165,6 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh } if state.cipherSuite.AuthenticationType() == CipherSuiteAuthenticationTypeAnonymous { - if cfg.verifyConnection != nil { - if err := cfg.verifyConnection(state.clone()); err != nil { - return 0, &alert.Alert{Level: alert.Fatal, Description: alert.BadCertificate}, err - } - } return flight6, nil, nil } @@ -207,18 +185,13 @@ func flight4Parse(ctx context.Context, c flightConn, state *State, cache *handsh return 0, &alert.Alert{Level: alert.Fatal, Description: alert.BadCertificate}, errClientCertificateNotVerified } case NoClientCert, RequestClientCert: - // go to flight6 - } - if cfg.verifyConnection != nil { - if err := cfg.verifyConnection(state.clone()); err != nil { - return 0, &alert.Alert{Level: alert.Fatal, Description: alert.BadCertificate}, err - } + return flight6, nil, nil } return flight6, nil, nil } -func flight4Generate(_ flightConn, state *State, _ *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { +func flight4Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { extensions := []extension.Extension{&extension.RenegotiationInfo{ RenegotiatedConnection: 0, }} @@ -280,10 +253,7 @@ func flight4Generate(_ flightConn, state *State, _ *handshakeCache, cfg *handsha switch { case state.cipherSuite.AuthenticationType() == CipherSuiteAuthenticationTypeCertificate: - certificate, err := cfg.getCertificate(&ClientHelloInfo{ - ServerName: state.serverName, - CipherSuites: []ciphersuite.ID{state.cipherSuite.ID()}, - }) + certificate, err := cfg.getCertificate(state.serverName) if err != nil { return nil, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, err } @@ -335,16 +305,6 @@ func flight4Generate(_ flightConn, state *State, _ *handshakeCache, cfg *handsha }) if cfg.clientAuth > NoClientCert { - // An empty list of certificateAuthorities signals to - // the client that it may send any certificate in response - // to our request. When we know the CAs we trust, then - // we can send them down, so that the client can choose - // an appropriate certificate to give to us. - var certificateAuthorities [][]byte - if cfg.clientCAs != nil { - // nolint:staticcheck // ignoring tlsCert.RootCAs.Subjects is deprecated ERR because cert does not come from SystemCertPool and it's ok if certificate authorities is empty. - certificateAuthorities = cfg.clientCAs.Subjects() - } pkts = append(pkts, &packet{ record: &recordlayer.RecordLayer{ Header: recordlayer.Header{ @@ -352,36 +312,43 @@ func flight4Generate(_ flightConn, state *State, _ *handshakeCache, cfg *handsha }, Content: &handshake.Handshake{ Message: &handshake.MessageCertificateRequest{ - CertificateTypes: []clientcertificate.Type{clientcertificate.RSASign, clientcertificate.ECDSASign}, - SignatureHashAlgorithms: cfg.localSignatureSchemes, - CertificateAuthoritiesNames: certificateAuthorities, + CertificateTypes: []clientcertificate.Type{clientcertificate.RSASign, clientcertificate.ECDSASign}, + SignatureHashAlgorithms: cfg.localSignatureSchemes, }, }, }, }) } - case cfg.localPSKIdentityHint != nil || state.cipherSuite.KeyExchangeAlgorithm().Has(CipherSuiteKeyExchangeAlgorithmEcdhe): + case cfg.localPSKIdentityHint != nil: // To help the client in selecting which identity to use, the server // can provide a "PSK identity hint" in the ServerKeyExchange message. - // If no hint is provided and cipher suite doesn't use elliptic curve, - // the ServerKeyExchange message is omitted. + // If no hint is provided, the ServerKeyExchange message is omitted. // // https://tools.ietf.org/html/rfc4279#section-2 - srvExchange := &handshake.MessageServerKeyExchange{ - IdentityHint: cfg.localPSKIdentityHint, - } - if state.cipherSuite.KeyExchangeAlgorithm().Has(CipherSuiteKeyExchangeAlgorithmEcdhe) { - srvExchange.EllipticCurveType = elliptic.CurveTypeNamedCurve - srvExchange.NamedCurve = state.namedCurve - srvExchange.PublicKey = state.localKeypair.PublicKey - } pkts = append(pkts, &packet{ record: &recordlayer.RecordLayer{ Header: recordlayer.Header{ Version: protocol.Version1_2, }, Content: &handshake.Handshake{ - Message: srvExchange, + Message: &handshake.MessageServerKeyExchange{ + IdentityHint: cfg.localPSKIdentityHint, + }, + }, + }, + }) + case state.cipherSuite.AuthenticationType() == CipherSuiteAuthenticationTypeAnonymous: + pkts = append(pkts, &packet{ + record: &recordlayer.RecordLayer{ + Header: recordlayer.Header{ + Version: protocol.Version1_2, + }, + Content: &handshake.Handshake{ + Message: &handshake.MessageServerKeyExchange{ + EllipticCurveType: elliptic.CurveTypeNamedCurve, + NamedCurve: state.namedCurve, + PublicKey: state.localKeypair.PublicKey, + }, }, }, }) diff --git a/vendor/github.com/pion/dtls/v2/flight5bhandler.go b/vendor/github.com/pion/dtls/v2/flight5bhandler.go index ddd37324c..577342e5b 100644 --- a/vendor/github.com/pion/dtls/v2/flight5bhandler.go +++ b/vendor/github.com/pion/dtls/v2/flight5bhandler.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -13,8 +10,8 @@ import ( "github.com/pion/dtls/v2/pkg/protocol/recordlayer" ) -func flight5bParse(_ context.Context, _ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { - _, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence-1, state.cipherSuite, +func flight5bParse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { + _, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence-1, handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, false, false}, ) if !ok { @@ -30,7 +27,7 @@ func flight5bParse(_ context.Context, _ flightConn, state *State, cache *handsha return flight5b, nil, nil } -func flight5bGenerate(_ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { //nolint:gocognit +func flight5bGenerate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { //nolint:gocognit var pkts []*packet pkts = append(pkts, diff --git a/vendor/github.com/pion/dtls/v2/flight5handler.go b/vendor/github.com/pion/dtls/v2/flight5handler.go index e8adf4f36..510fa4512 100644 --- a/vendor/github.com/pion/dtls/v2/flight5handler.go +++ b/vendor/github.com/pion/dtls/v2/flight5handler.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -17,8 +14,8 @@ import ( "github.com/pion/dtls/v2/pkg/protocol/recordlayer" ) -func flight5Parse(_ context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { - _, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, state.cipherSuite, +func flight5Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { + _, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence, handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, false, false}, ) if !ok { @@ -66,30 +63,20 @@ func flight5Parse(_ context.Context, c flightConn, state *State, cache *handshak } func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { //nolint:gocognit + var certBytes [][]byte var privateKey crypto.PrivateKey - var pkts []*packet - if state.remoteRequestedCertificate { - _, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence-2, state.cipherSuite, - handshakeCachePullRule{handshake.TypeCertificateRequest, cfg.initialEpoch, false, false}) - if !ok { - return nil, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, errClientCertificateRequired - } - reqInfo := CertificateRequestInfo{} - if r, ok := msgs[handshake.TypeCertificateRequest].(*handshake.MessageCertificateRequest); ok { - reqInfo.AcceptableCAs = r.CertificateAuthoritiesNames - } else { - return nil, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, errClientCertificateRequired - } - certificate, err := cfg.getClientCertificate(&reqInfo) + if len(cfg.localCertificates) > 0 { + certificate, err := cfg.getCertificate(cfg.serverName) if err != nil { return nil, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, err } - if certificate == nil { - return nil, &alert.Alert{Level: alert.Fatal, Description: alert.HandshakeFailure}, errNotAcceptableCertificateChain - } - if certificate.Certificate != nil { - privateKey = certificate.PrivateKey - } + certBytes = certificate.Certificate + privateKey = certificate.PrivateKey + } + + var pkts []*packet + + if state.remoteRequestedCertificate { pkts = append(pkts, &packet{ record: &recordlayer.RecordLayer{ @@ -98,7 +85,7 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han }, Content: &handshake.Handshake{ Message: &handshake.MessageCertificate{ - Certificate: certificate.Certificate, + Certificate: certBytes, }, }, }, @@ -111,9 +98,6 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han } else { clientKeyExchange.IdentityHint = cfg.localPSKIdentityHint } - if state != nil && state.localKeypair != nil && len(state.localKeypair.PublicKey) > 0 { - clientKeyExchange.PublicKey = state.localKeypair.PublicKey - } pkts = append(pkts, &packet{ @@ -140,9 +124,7 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han return nil, alertPtr, err } } else { - rawHandshake := &handshake.Handshake{ - KeyExchangeAlgorithm: state.cipherSuite.KeyExchangeAlgorithm(), - } + rawHandshake := &handshake.Handshake{} err := rawHandshake.Unmarshal(serverKeyExchangeData) if err != nil { return nil, &alert.Alert{Level: alert.Fatal, Description: alert.UnexpectedMessage}, err @@ -180,7 +162,7 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han // If the client has sent a certificate with signing ability, a digitally-signed // CertificateVerify message is sent to explicitly verify possession of the // private key in the certificate. - if state.remoteRequestedCertificate && privateKey != nil { + if state.remoteRequestedCertificate && len(cfg.localCertificates) > 0 { plainText := append(cache.pullAndMerge( handshakeCachePullRule{handshake.TypeClientHello, cfg.initialEpoch, true, false}, handshakeCachePullRule{handshake.TypeServerHello, cfg.initialEpoch, false, false}, @@ -286,7 +268,7 @@ func flight5Generate(c flightConn, state *State, cache *handshakeCache, cfg *han func initalizeCipherSuite(state *State, cache *handshakeCache, cfg *handshakeConfig, h *handshake.MessageServerKeyExchange, sendingPlainText []byte) (*alert.Alert, error) { //nolint:gocognit if state.cipherSuite.IsInitialized() { - return nil, nil //nolint + return nil, nil } clientRandom := state.localRandom.MarshalFixed() @@ -341,11 +323,6 @@ func initalizeCipherSuite(state *State, cache *handshakeCache, cfg *handshakeCon } } } - if cfg.verifyConnection != nil { - if err = cfg.verifyConnection(state.clone()); err != nil { - return &alert.Alert{Level: alert.Fatal, Description: alert.BadCertificate}, err - } - } if err = state.cipherSuite.Init(state.masterSecret, clientRandom[:], serverRandom[:], true); err != nil { return &alert.Alert{Level: alert.Fatal, Description: alert.InternalError}, err @@ -353,5 +330,5 @@ func initalizeCipherSuite(state *State, cache *handshakeCache, cfg *handshakeCon cfg.writeKeyLog(keyLogLabelTLS12, clientRandom[:], state.masterSecret) - return nil, nil //nolint + return nil, nil } diff --git a/vendor/github.com/pion/dtls/v2/flight6handler.go b/vendor/github.com/pion/dtls/v2/flight6handler.go index 57ac14360..fddaa0e6b 100644 --- a/vendor/github.com/pion/dtls/v2/flight6handler.go +++ b/vendor/github.com/pion/dtls/v2/flight6handler.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -13,8 +10,8 @@ import ( "github.com/pion/dtls/v2/pkg/protocol/recordlayer" ) -func flight6Parse(_ context.Context, _ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { - _, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence-1, state.cipherSuite, +func flight6Parse(ctx context.Context, c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) (flightVal, *alert.Alert, error) { + _, msgs, ok := cache.fullPullMap(state.handshakeRecvSequence-1, handshakeCachePullRule{handshake.TypeFinished, cfg.initialEpoch + 1, true, false}, ) if !ok { @@ -30,7 +27,7 @@ func flight6Parse(_ context.Context, _ flightConn, state *State, cache *handshak return flight6, nil, nil } -func flight6Generate(_ flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { +func flight6Generate(c flightConn, state *State, cache *handshakeCache, cfg *handshakeConfig) ([]*packet, *alert.Alert, error) { var pkts []*packet pkts = append(pkts, diff --git a/vendor/github.com/pion/dtls/v2/flighthandler.go b/vendor/github.com/pion/dtls/v2/flighthandler.go index ceb4a992b..f899ffa5b 100644 --- a/vendor/github.com/pion/dtls/v2/flighthandler.go +++ b/vendor/github.com/pion/dtls/v2/flighthandler.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( diff --git a/vendor/github.com/pion/dtls/v2/fragment_buffer.go b/vendor/github.com/pion/dtls/v2/fragment_buffer.go index f20033758..02749939f 100644 --- a/vendor/github.com/pion/dtls/v2/fragment_buffer.go +++ b/vendor/github.com/pion/dtls/v2/fragment_buffer.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -9,9 +6,6 @@ import ( "github.com/pion/dtls/v2/pkg/protocol/recordlayer" ) -// 2 megabytes -const fragmentBufferMaxSize = 2000000 - type fragment struct { recordLayerHeader recordlayer.Header handshakeHeader handshake.Header @@ -29,25 +23,10 @@ func newFragmentBuffer() *fragmentBuffer { return &fragmentBuffer{cache: map[uint16][]*fragment{}} } -// current total size of buffer -func (f *fragmentBuffer) size() int { - size := 0 - for i := range f.cache { - for j := range f.cache[i] { - size += len(f.cache[i][j].data) - } - } - return size -} - // Attempts to push a DTLS packet to the fragmentBuffer // when it returns true it means the fragmentBuffer has inserted and the buffer shouldn't be handled // when an error returns it is fatal, and the DTLS connection should be stopped func (f *fragmentBuffer) push(buf []byte) (bool, error) { - if f.size()+len(buf) >= fragmentBufferMaxSize { - return false, errFragmentBufferOverflow - } - frag := new(fragment) if err := frag.recordLayerHeader.Unmarshal(buf); err != nil { return false, err @@ -97,7 +76,7 @@ func (f *fragmentBuffer) pop() (content []byte, epoch uint16) { for _, f := range frags { if f.handshakeHeader.FragmentOffset == targetOffset { fragmentEnd := (f.handshakeHeader.FragmentOffset + f.handshakeHeader.FragmentLength) - if fragmentEnd != f.handshakeHeader.Length && f.handshakeHeader.FragmentLength != 0 { + if fragmentEnd != f.handshakeHeader.Length { if !appendMessage(fragmentEnd) { return false } diff --git a/vendor/github.com/pion/dtls/v2/fuzz.go b/vendor/github.com/pion/dtls/v2/fuzz.go new file mode 100644 index 000000000..d6863241e --- /dev/null +++ b/vendor/github.com/pion/dtls/v2/fuzz.go @@ -0,0 +1,39 @@ +//go:build gofuzz +// +build gofuzz + +package dtls + +import "fmt" + +func partialHeaderMismatch(a, b recordlayer.Header) bool { + // Ignoring content length for now. + a.contentLen = b.contentLen + return a != b +} + +func FuzzRecordLayer(data []byte) int { + var r recordLayer + if err := r.Unmarshal(data); err != nil { + return 0 + } + buf, err := r.Marshal() + if err != nil { + return 1 + } + if len(buf) == 0 { + panic("zero buff") // nolint + } + var nr recordLayer + if err = nr.Unmarshal(data); err != nil { + panic(err) // nolint + } + if partialHeaderMismatch(nr.recordlayer.Header, r.recordlayer.Header) { + panic( // nolint + fmt.Sprintf("header mismatch: %+v != %+v", + nr.recordlayer.Header, r.recordlayer.Header, + ), + ) + } + + return 1 +} diff --git a/vendor/github.com/pion/dtls/v2/handshake_cache.go b/vendor/github.com/pion/dtls/v2/handshake_cache.go index 8d5960568..063a85807 100644 --- a/vendor/github.com/pion/dtls/v2/handshake_cache.go +++ b/vendor/github.com/pion/dtls/v2/handshake_cache.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -34,10 +31,17 @@ func newHandshakeCache() *handshakeCache { return &handshakeCache{} } -func (h *handshakeCache) push(data []byte, epoch, messageSequence uint16, typ handshake.Type, isClient bool) { +func (h *handshakeCache) push(data []byte, epoch, messageSequence uint16, typ handshake.Type, isClient bool) bool { //nolint h.mu.Lock() defer h.mu.Unlock() + for _, i := range h.cache { + if i.messageSequence == messageSequence && + i.isClient == isClient { + return false + } + } + h.cache = append(h.cache, &handshakeCacheItem{ data: append([]byte{}, data...), epoch: epoch, @@ -45,6 +49,7 @@ func (h *handshakeCache) push(data []byte, epoch, messageSequence uint16, typ ha typ: typ, isClient: isClient, }) + return true } // returns a list handshakes that match the requested rules @@ -72,7 +77,7 @@ func (h *handshakeCache) pull(rules ...handshakeCachePullRule) []*handshakeCache } // fullPullMap pulls all handshakes between rules[0] to rules[len(rules)-1] as map. -func (h *handshakeCache) fullPullMap(startSeq int, cipherSuite CipherSuite, rules ...handshakeCachePullRule) (int, map[handshake.Type]handshake.Message, bool) { +func (h *handshakeCache) fullPullMap(startSeq int, rules ...handshakeCachePullRule) (int, map[handshake.Type]handshake.Message, bool) { h.mu.Lock() defer h.mu.Unlock() @@ -103,13 +108,7 @@ func (h *handshakeCache) fullPullMap(startSeq int, cipherSuite CipherSuite, rule if i == nil { continue } - var keyExchangeAlgorithm CipherSuiteKeyExchangeAlgorithm - if cipherSuite != nil { - keyExchangeAlgorithm = cipherSuite.KeyExchangeAlgorithm() - } - rawHandshake := &handshake.Handshake{ - KeyExchangeAlgorithm: keyExchangeAlgorithm, - } + rawHandshake := &handshake.Handshake{} if err := rawHandshake.Unmarshal(i.data); err != nil { return startSeq, nil, false } diff --git a/vendor/github.com/pion/dtls/v2/handshaker.go b/vendor/github.com/pion/dtls/v2/handshaker.go index 1c6d58fe9..1c7b9ffa2 100644 --- a/vendor/github.com/pion/dtls/v2/handshaker.go +++ b/vendor/github.com/pion/dtls/v2/handshaker.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -12,7 +9,6 @@ import ( "sync" "time" - "github.com/pion/dtls/v2/pkg/crypto/elliptic" "github.com/pion/dtls/v2/pkg/crypto/signaturehash" "github.com/pion/dtls/v2/pkg/protocol/alert" "github.com/pion/dtls/v2/pkg/protocol/handshake" @@ -105,22 +101,16 @@ type handshakeConfig struct { nameToCertificate map[string]*tls.Certificate insecureSkipVerify bool verifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error - verifyConnection func(*State) error sessionStore SessionStore rootCAs *x509.CertPool clientCAs *x509.CertPool retransmitInterval time.Duration customCipherSuites func() []CipherSuite - ellipticCurves []elliptic.Curve - insecureSkipHelloVerify bool onFlightState func(flightVal, handshakeState) log logging.LeveledLogger keyLogWriter io.Writer - localGetCertificate func(*ClientHelloInfo) (*tls.Certificate, error) - localGetClientCertificate func(*CertificateRequestInfo) (*tls.Certificate, error) - initialEpoch uint16 mu sync.Mutex diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_128_ccm.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_128_ccm.go index f78b6dc2c..dcc537991 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_128_ccm.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_128_ccm.go @@ -1,33 +1,108 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( + "crypto/sha256" + "fmt" + "hash" + "sync/atomic" + "github.com/pion/dtls/v2/pkg/crypto/ciphersuite" "github.com/pion/dtls/v2/pkg/crypto/clientcertificate" + "github.com/pion/dtls/v2/pkg/crypto/prf" + "github.com/pion/dtls/v2/pkg/protocol/recordlayer" ) // Aes128Ccm is a base class used by multiple AES-CCM Ciphers type Aes128Ccm struct { - AesCcm + ccm atomic.Value // *cryptoCCM + clientCertificateType clientcertificate.Type + id ID + psk bool + cryptoCCMTagLen ciphersuite.CCMTagLen } -func newAes128Ccm(clientCertificateType clientcertificate.Type, id ID, psk bool, cryptoCCMTagLen ciphersuite.CCMTagLen, keyExchangeAlgorithm KeyExchangeAlgorithm, ecc bool) *Aes128Ccm { +func newAes128Ccm(clientCertificateType clientcertificate.Type, id ID, psk bool, cryptoCCMTagLen ciphersuite.CCMTagLen) *Aes128Ccm { return &Aes128Ccm{ - AesCcm: AesCcm{ - clientCertificateType: clientCertificateType, - id: id, - psk: psk, - cryptoCCMTagLen: cryptoCCMTagLen, - keyExchangeAlgorithm: keyExchangeAlgorithm, - ecc: ecc, - }, + clientCertificateType: clientCertificateType, + id: id, + psk: psk, + cryptoCCMTagLen: cryptoCCMTagLen, } } +// CertificateType returns what type of certificate this CipherSuite exchanges +func (c *Aes128Ccm) CertificateType() clientcertificate.Type { + return c.clientCertificateType +} + +// ID returns the ID of the CipherSuite +func (c *Aes128Ccm) ID() ID { + return c.id +} + +func (c *Aes128Ccm) String() string { + return c.id.String() +} + +// HashFunc returns the hashing func for this CipherSuite +func (c *Aes128Ccm) HashFunc() func() hash.Hash { + return sha256.New +} + +// AuthenticationType controls what authentication method is using during the handshake +func (c *Aes128Ccm) AuthenticationType() AuthenticationType { + if c.psk { + return AuthenticationTypePreSharedKey + } + return AuthenticationTypeCertificate +} + +// IsInitialized returns if the CipherSuite has keying material and can +// encrypt/decrypt packets +func (c *Aes128Ccm) IsInitialized() bool { + return c.ccm.Load() != nil +} + // Init initializes the internal Cipher with keying material func (c *Aes128Ccm) Init(masterSecret, clientRandom, serverRandom []byte, isClient bool) error { - const prfKeyLen = 16 - return c.AesCcm.Init(masterSecret, clientRandom, serverRandom, isClient, prfKeyLen) + const ( + prfMacLen = 0 + prfKeyLen = 16 + prfIvLen = 4 + ) + + keys, err := prf.GenerateEncryptionKeys(masterSecret, clientRandom, serverRandom, prfMacLen, prfKeyLen, prfIvLen, c.HashFunc()) + if err != nil { + return err + } + + var ccm *ciphersuite.CCM + if isClient { + ccm, err = ciphersuite.NewCCM(c.cryptoCCMTagLen, keys.ClientWriteKey, keys.ClientWriteIV, keys.ServerWriteKey, keys.ServerWriteIV) + } else { + ccm, err = ciphersuite.NewCCM(c.cryptoCCMTagLen, keys.ServerWriteKey, keys.ServerWriteIV, keys.ClientWriteKey, keys.ClientWriteIV) + } + c.ccm.Store(ccm) + + return err +} + +// Encrypt encrypts a single TLS RecordLayer +func (c *Aes128Ccm) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) { + ccm := c.ccm.Load() + if ccm == nil { + return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit) + } + + return ccm.(*ciphersuite.CCM).Encrypt(pkt, raw) +} + +// Decrypt decrypts a single TLS RecordLayer +func (c *Aes128Ccm) Decrypt(raw []byte) ([]byte, error) { + ccm := c.ccm.Load() + if ccm == nil { + return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit) + } + + return ccm.(*ciphersuite.CCM).Decrypt(raw) } diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_256_ccm.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_256_ccm.go deleted file mode 100644 index bb8128627..000000000 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_256_ccm.go +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package ciphersuite - -import ( - "github.com/pion/dtls/v2/pkg/crypto/ciphersuite" - "github.com/pion/dtls/v2/pkg/crypto/clientcertificate" -) - -// Aes256Ccm is a base class used by multiple AES-CCM Ciphers -type Aes256Ccm struct { - AesCcm -} - -func newAes256Ccm(clientCertificateType clientcertificate.Type, id ID, psk bool, cryptoCCMTagLen ciphersuite.CCMTagLen, keyExchangeAlgorithm KeyExchangeAlgorithm, ecc bool) *Aes256Ccm { - return &Aes256Ccm{ - AesCcm: AesCcm{ - clientCertificateType: clientCertificateType, - id: id, - psk: psk, - cryptoCCMTagLen: cryptoCCMTagLen, - keyExchangeAlgorithm: keyExchangeAlgorithm, - ecc: ecc, - }, - } -} - -// Init initializes the internal Cipher with keying material -func (c *Aes256Ccm) Init(masterSecret, clientRandom, serverRandom []byte, isClient bool) error { - const prfKeyLen = 32 - return c.AesCcm.Init(masterSecret, clientRandom, serverRandom, isClient, prfKeyLen) -} diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_ccm.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_ccm.go deleted file mode 100644 index dc5119823..000000000 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/aes_ccm.go +++ /dev/null @@ -1,113 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package ciphersuite - -import ( - "crypto/sha256" - "fmt" - "hash" - "sync/atomic" - - "github.com/pion/dtls/v2/pkg/crypto/ciphersuite" - "github.com/pion/dtls/v2/pkg/crypto/clientcertificate" - "github.com/pion/dtls/v2/pkg/crypto/prf" - "github.com/pion/dtls/v2/pkg/protocol/recordlayer" -) - -// AesCcm is a base class used by multiple AES-CCM Ciphers -type AesCcm struct { - ccm atomic.Value // *cryptoCCM - clientCertificateType clientcertificate.Type - id ID - psk bool - keyExchangeAlgorithm KeyExchangeAlgorithm - cryptoCCMTagLen ciphersuite.CCMTagLen - ecc bool -} - -// CertificateType returns what type of certificate this CipherSuite exchanges -func (c *AesCcm) CertificateType() clientcertificate.Type { - return c.clientCertificateType -} - -// ID returns the ID of the CipherSuite -func (c *AesCcm) ID() ID { - return c.id -} - -func (c *AesCcm) String() string { - return c.id.String() -} - -// ECC uses Elliptic Curve Cryptography -func (c *AesCcm) ECC() bool { - return c.ecc -} - -// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake -func (c *AesCcm) KeyExchangeAlgorithm() KeyExchangeAlgorithm { - return c.keyExchangeAlgorithm -} - -// HashFunc returns the hashing func for this CipherSuite -func (c *AesCcm) HashFunc() func() hash.Hash { - return sha256.New -} - -// AuthenticationType controls what authentication method is using during the handshake -func (c *AesCcm) AuthenticationType() AuthenticationType { - if c.psk { - return AuthenticationTypePreSharedKey - } - return AuthenticationTypeCertificate -} - -// IsInitialized returns if the CipherSuite has keying material and can -// encrypt/decrypt packets -func (c *AesCcm) IsInitialized() bool { - return c.ccm.Load() != nil -} - -// Init initializes the internal Cipher with keying material -func (c *AesCcm) Init(masterSecret, clientRandom, serverRandom []byte, isClient bool, prfKeyLen int) error { - const ( - prfMacLen = 0 - prfIvLen = 4 - ) - - keys, err := prf.GenerateEncryptionKeys(masterSecret, clientRandom, serverRandom, prfMacLen, prfKeyLen, prfIvLen, c.HashFunc()) - if err != nil { - return err - } - - var ccm *ciphersuite.CCM - if isClient { - ccm, err = ciphersuite.NewCCM(c.cryptoCCMTagLen, keys.ClientWriteKey, keys.ClientWriteIV, keys.ServerWriteKey, keys.ServerWriteIV) - } else { - ccm, err = ciphersuite.NewCCM(c.cryptoCCMTagLen, keys.ServerWriteKey, keys.ServerWriteIV, keys.ClientWriteKey, keys.ClientWriteIV) - } - c.ccm.Store(ccm) - - return err -} - -// Encrypt encrypts a single TLS RecordLayer -func (c *AesCcm) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) { - cipherSuite, ok := c.ccm.Load().(*ciphersuite.CCM) - if !ok { - return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit) - } - - return cipherSuite.Encrypt(pkt, raw) -} - -// Decrypt decrypts a single TLS RecordLayer -func (c *AesCcm) Decrypt(raw []byte) ([]byte, error) { - cipherSuite, ok := c.ccm.Load().(*ciphersuite.CCM) - if !ok { - return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit) - } - - return cipherSuite.Decrypt(raw) -} diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/ciphersuite.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/ciphersuite.go index f44f29fd3..7405792c2 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/ciphersuite.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/ciphersuite.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package ciphersuite provides TLS Ciphers as registered with the IANA https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4 package ciphersuite @@ -8,7 +5,6 @@ import ( "errors" "fmt" - "github.com/pion/dtls/v2/internal/ciphersuite/types" "github.com/pion/dtls/v2/pkg/protocol" ) @@ -35,8 +31,6 @@ func (i ID) String() string { return "TLS_PSK_WITH_AES_128_CCM" case TLS_PSK_WITH_AES_128_CCM_8: return "TLS_PSK_WITH_AES_128_CCM_8" - case TLS_PSK_WITH_AES_256_CCM_8: - return "TLS_PSK_WITH_AES_256_CCM_8" case TLS_PSK_WITH_AES_128_GCM_SHA256: return "TLS_PSK_WITH_AES_128_GCM_SHA256" case TLS_PSK_WITH_AES_128_CBC_SHA256: @@ -45,8 +39,6 @@ func (i ID) String() string { return "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" case TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: return "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384" - case TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256: - return "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256" default: return fmt.Sprintf("unknown(%v)", uint16(i)) } @@ -55,44 +47,31 @@ func (i ID) String() string { // Supported Cipher Suites const ( // AES-128-CCM - TLS_ECDHE_ECDSA_WITH_AES_128_CCM ID = 0xc0ac //nolint:revive,stylecheck - TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ID = 0xc0ae //nolint:revive,stylecheck + TLS_ECDHE_ECDSA_WITH_AES_128_CCM ID = 0xc0ac //nolint:golint,stylecheck + TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 ID = 0xc0ae //nolint:golint,stylecheck // AES-128-GCM-SHA256 - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ID = 0xc02b //nolint:revive,stylecheck - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ID = 0xc02f //nolint:revive,stylecheck + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ID = 0xc02b //nolint:golint,stylecheck + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ID = 0xc02f //nolint:golint,stylecheck - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 ID = 0xc02c //nolint:revive,stylecheck - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ID = 0xc030 //nolint:revive,stylecheck + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 ID = 0xc02c //nolint:golint,stylecheck + TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 ID = 0xc030 //nolint:golint,stylecheck // AES-256-CBC-SHA - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ID = 0xc00a //nolint:revive,stylecheck - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA ID = 0xc014 //nolint:revive,stylecheck + TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA ID = 0xc00a //nolint:golint,stylecheck + TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA ID = 0xc014 //nolint:golint,stylecheck - TLS_PSK_WITH_AES_128_CCM ID = 0xc0a4 //nolint:revive,stylecheck - TLS_PSK_WITH_AES_128_CCM_8 ID = 0xc0a8 //nolint:revive,stylecheck - TLS_PSK_WITH_AES_256_CCM_8 ID = 0xc0a9 //nolint:revive,stylecheck - TLS_PSK_WITH_AES_128_GCM_SHA256 ID = 0x00a8 //nolint:revive,stylecheck - TLS_PSK_WITH_AES_128_CBC_SHA256 ID = 0x00ae //nolint:revive,stylecheck - - TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 ID = 0xC037 //nolint:revive,stylecheck + TLS_PSK_WITH_AES_128_CCM ID = 0xc0a4 //nolint:golint,stylecheck + TLS_PSK_WITH_AES_128_CCM_8 ID = 0xc0a8 //nolint:golint,stylecheck + TLS_PSK_WITH_AES_128_GCM_SHA256 ID = 0x00a8 //nolint:golint,stylecheck + TLS_PSK_WITH_AES_128_CBC_SHA256 ID = 0x00ae //nolint:golint,stylecheck ) // AuthenticationType controls what authentication method is using during the handshake -type AuthenticationType = types.AuthenticationType +type AuthenticationType int // AuthenticationType Enums const ( - AuthenticationTypeCertificate AuthenticationType = types.AuthenticationTypeCertificate - AuthenticationTypePreSharedKey AuthenticationType = types.AuthenticationTypePreSharedKey - AuthenticationTypeAnonymous AuthenticationType = types.AuthenticationTypeAnonymous -) - -// KeyExchangeAlgorithm controls what exchange algorithm was chosen. -type KeyExchangeAlgorithm = types.KeyExchangeAlgorithm - -// KeyExchangeAlgorithm Bitmask -const ( - KeyExchangeAlgorithmNone KeyExchangeAlgorithm = types.KeyExchangeAlgorithmNone - KeyExchangeAlgorithmPsk KeyExchangeAlgorithm = types.KeyExchangeAlgorithmPsk - KeyExchangeAlgorithmEcdhe KeyExchangeAlgorithm = types.KeyExchangeAlgorithmEcdhe + AuthenticationTypeCertificate AuthenticationType = iota + 1 + AuthenticationTypePreSharedKey + AuthenticationTypeAnonymous ) diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_ccm.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_ccm.go index 8367b2c6d..ac73556fb 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_ccm.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_ccm.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( @@ -10,5 +7,5 @@ import ( // NewTLSEcdheEcdsaWithAes128Ccm constructs a TLS_ECDHE_ECDSA_WITH_AES_128_CCM Cipher func NewTLSEcdheEcdsaWithAes128Ccm() *Aes128Ccm { - return newAes128Ccm(clientcertificate.ECDSASign, TLS_ECDHE_ECDSA_WITH_AES_128_CCM, false, ciphersuite.CCMTagLength, KeyExchangeAlgorithmEcdhe, true) + return newAes128Ccm(clientcertificate.ECDSASign, TLS_ECDHE_ECDSA_WITH_AES_128_CCM, false, ciphersuite.CCMTagLength) } diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_ccm8.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_ccm8.go index 11b687327..49b1a8304 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_ccm8.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_ccm8.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( @@ -10,5 +7,5 @@ import ( // NewTLSEcdheEcdsaWithAes128Ccm8 creates a new TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 CipherSuite func NewTLSEcdheEcdsaWithAes128Ccm8() *Aes128Ccm { - return newAes128Ccm(clientcertificate.ECDSASign, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, false, ciphersuite.CCMTagLength8, KeyExchangeAlgorithmEcdhe, true) + return newAes128Ccm(clientcertificate.ECDSASign, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, false, ciphersuite.CCMTagLength8) } diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_gcm_sha256.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_gcm_sha256.go index 0c919fe47..ede12bbe5 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_gcm_sha256.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_128_gcm_sha256.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( @@ -25,16 +22,6 @@ func (c *TLSEcdheEcdsaWithAes128GcmSha256) CertificateType() clientcertificate.T return clientcertificate.ECDSASign } -// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake -func (c *TLSEcdheEcdsaWithAes128GcmSha256) KeyExchangeAlgorithm() KeyExchangeAlgorithm { - return KeyExchangeAlgorithmEcdhe -} - -// ECC uses Elliptic Curve Cryptography -func (c *TLSEcdheEcdsaWithAes128GcmSha256) ECC() bool { - return true -} - // ID returns the ID of the CipherSuite func (c *TLSEcdheEcdsaWithAes128GcmSha256) ID() ID { return TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 @@ -89,20 +76,20 @@ func (c *TLSEcdheEcdsaWithAes128GcmSha256) Init(masterSecret, clientRandom, serv // Encrypt encrypts a single TLS RecordLayer func (c *TLSEcdheEcdsaWithAes128GcmSha256) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) { - cipherSuite, ok := c.gcm.Load().(*ciphersuite.GCM) - if !ok { + gcm := c.gcm.Load() + if gcm == nil { return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit) } - return cipherSuite.Encrypt(pkt, raw) + return gcm.(*ciphersuite.GCM).Encrypt(pkt, raw) } // Decrypt decrypts a single TLS RecordLayer func (c *TLSEcdheEcdsaWithAes128GcmSha256) Decrypt(raw []byte) ([]byte, error) { - cipherSuite, ok := c.gcm.Load().(*ciphersuite.GCM) - if !ok { + gcm := c.gcm.Load() + if gcm == nil { return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit) } - return cipherSuite.Decrypt(raw) + return gcm.(*ciphersuite.GCM).Decrypt(raw) } diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_256_cbc_sha.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_256_cbc_sha.go index 577192c89..f7a33ad8d 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_256_cbc_sha.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_256_cbc_sha.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( @@ -26,16 +23,6 @@ func (c *TLSEcdheEcdsaWithAes256CbcSha) CertificateType() clientcertificate.Type return clientcertificate.ECDSASign } -// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake -func (c *TLSEcdheEcdsaWithAes256CbcSha) KeyExchangeAlgorithm() KeyExchangeAlgorithm { - return KeyExchangeAlgorithmEcdhe -} - -// ECC uses Elliptic Curve Cryptography -func (c *TLSEcdheEcdsaWithAes256CbcSha) ECC() bool { - return true -} - // ID returns the ID of the CipherSuite func (c *TLSEcdheEcdsaWithAes256CbcSha) ID() ID { return TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA @@ -95,20 +82,20 @@ func (c *TLSEcdheEcdsaWithAes256CbcSha) Init(masterSecret, clientRandom, serverR // Encrypt encrypts a single TLS RecordLayer func (c *TLSEcdheEcdsaWithAes256CbcSha) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) { - cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC) - if !ok { + cbc := c.cbc.Load() + if cbc == nil { // !c.isInitialized() return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit) } - return cipherSuite.Encrypt(pkt, raw) + return cbc.(*ciphersuite.CBC).Encrypt(pkt, raw) } // Decrypt decrypts a single TLS RecordLayer func (c *TLSEcdheEcdsaWithAes256CbcSha) Decrypt(raw []byte) ([]byte, error) { - cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC) - if !ok { + cbc := c.cbc.Load() + if cbc == nil { // !c.isInitialized() return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit) } - return cipherSuite.Decrypt(raw) + return cbc.(*ciphersuite.CBC).Decrypt(raw) } diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_256_gcm_sha384.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_256_gcm_sha384.go index 2a3cfa4f5..a2fe30244 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_256_gcm_sha384.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_ecdsa_with_aes_256_gcm_sha384.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_psk_with_aes_128_cbc_sha256.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_psk_with_aes_128_cbc_sha256.go deleted file mode 100644 index 75a25633a..000000000 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_psk_with_aes_128_cbc_sha256.go +++ /dev/null @@ -1,118 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package ciphersuite - -import ( - "crypto/sha256" - "fmt" - "hash" - "sync/atomic" - - "github.com/pion/dtls/v2/pkg/crypto/ciphersuite" - "github.com/pion/dtls/v2/pkg/crypto/clientcertificate" - "github.com/pion/dtls/v2/pkg/crypto/prf" - "github.com/pion/dtls/v2/pkg/protocol/recordlayer" -) - -// TLSEcdhePskWithAes128CbcSha256 implements the TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 CipherSuite -type TLSEcdhePskWithAes128CbcSha256 struct { - cbc atomic.Value // *cryptoCBC -} - -// NewTLSEcdhePskWithAes128CbcSha256 creates TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 cipher. -func NewTLSEcdhePskWithAes128CbcSha256() *TLSEcdhePskWithAes128CbcSha256 { - return &TLSEcdhePskWithAes128CbcSha256{} -} - -// CertificateType returns what type of certificate this CipherSuite exchanges -func (c *TLSEcdhePskWithAes128CbcSha256) CertificateType() clientcertificate.Type { - return clientcertificate.Type(0) -} - -// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake -func (c *TLSEcdhePskWithAes128CbcSha256) KeyExchangeAlgorithm() KeyExchangeAlgorithm { - return (KeyExchangeAlgorithmPsk | KeyExchangeAlgorithmEcdhe) -} - -// ECC uses Elliptic Curve Cryptography -func (c *TLSEcdhePskWithAes128CbcSha256) ECC() bool { - return true -} - -// ID returns the ID of the CipherSuite -func (c *TLSEcdhePskWithAes128CbcSha256) ID() ID { - return TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 -} - -func (c *TLSEcdhePskWithAes128CbcSha256) String() string { - return "TLS-ECDHE-PSK-WITH-AES-128-CBC-SHA256" -} - -// HashFunc returns the hashing func for this CipherSuite -func (c *TLSEcdhePskWithAes128CbcSha256) HashFunc() func() hash.Hash { - return sha256.New -} - -// AuthenticationType controls what authentication method is using during the handshake -func (c *TLSEcdhePskWithAes128CbcSha256) AuthenticationType() AuthenticationType { - return AuthenticationTypePreSharedKey -} - -// IsInitialized returns if the CipherSuite has keying material and can -// encrypt/decrypt packets -func (c *TLSEcdhePskWithAes128CbcSha256) IsInitialized() bool { - return c.cbc.Load() != nil -} - -// Init initializes the internal Cipher with keying material -func (c *TLSEcdhePskWithAes128CbcSha256) Init(masterSecret, clientRandom, serverRandom []byte, isClient bool) error { - const ( - prfMacLen = 32 - prfKeyLen = 16 - prfIvLen = 16 - ) - - keys, err := prf.GenerateEncryptionKeys(masterSecret, clientRandom, serverRandom, prfMacLen, prfKeyLen, prfIvLen, c.HashFunc()) - if err != nil { - return err - } - - var cbc *ciphersuite.CBC - if isClient { - cbc, err = ciphersuite.NewCBC( - keys.ClientWriteKey, keys.ClientWriteIV, keys.ClientMACKey, - keys.ServerWriteKey, keys.ServerWriteIV, keys.ServerMACKey, - c.HashFunc(), - ) - } else { - cbc, err = ciphersuite.NewCBC( - keys.ServerWriteKey, keys.ServerWriteIV, keys.ServerMACKey, - keys.ClientWriteKey, keys.ClientWriteIV, keys.ClientMACKey, - c.HashFunc(), - ) - } - c.cbc.Store(cbc) - - return err -} - -// Encrypt encrypts a single TLS RecordLayer -func (c *TLSEcdhePskWithAes128CbcSha256) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) { - cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC) - if !ok { // !c.isInitialized() - return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit) - } - - return cipherSuite.Encrypt(pkt, raw) -} - -// Decrypt decrypts a single TLS RecordLayer -func (c *TLSEcdhePskWithAes128CbcSha256) Decrypt(raw []byte) ([]byte, error) { - cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC) - if !ok { // !c.isInitialized() - return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit) - } - - return cipherSuite.Decrypt(raw) -} diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_128_gcm_sha256.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_128_gcm_sha256.go index 478a2e0dc..70400c37d 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_128_gcm_sha256.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_128_gcm_sha256.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import "github.com/pion/dtls/v2/pkg/crypto/clientcertificate" diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_256_cbc_sha.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_256_cbc_sha.go index 8e88ee639..0d82dc3ad 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_256_cbc_sha.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_256_cbc_sha.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import "github.com/pion/dtls/v2/pkg/crypto/clientcertificate" diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_256_gcm_sha384.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_256_gcm_sha384.go index 752fb529c..3473527e7 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_256_gcm_sha384.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_ecdhe_rsa_with_aes_256_gcm_sha384.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import "github.com/pion/dtls/v2/pkg/crypto/clientcertificate" diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_cbc_sha256.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_cbc_sha256.go index 7336ad946..43e5e3800 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_cbc_sha256.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_cbc_sha256.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( @@ -25,16 +22,6 @@ func (c *TLSPskWithAes128CbcSha256) CertificateType() clientcertificate.Type { return clientcertificate.Type(0) } -// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake -func (c *TLSPskWithAes128CbcSha256) KeyExchangeAlgorithm() KeyExchangeAlgorithm { - return KeyExchangeAlgorithmPsk -} - -// ECC uses Elliptic Curve Cryptography -func (c *TLSPskWithAes128CbcSha256) ECC() bool { - return false -} - // ID returns the ID of the CipherSuite func (c *TLSPskWithAes128CbcSha256) ID() ID { return TLS_PSK_WITH_AES_128_CBC_SHA256 @@ -94,20 +81,20 @@ func (c *TLSPskWithAes128CbcSha256) Init(masterSecret, clientRandom, serverRando // Encrypt encrypts a single TLS RecordLayer func (c *TLSPskWithAes128CbcSha256) Encrypt(pkt *recordlayer.RecordLayer, raw []byte) ([]byte, error) { - cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC) - if !ok { - return nil, fmt.Errorf("%w, unable to encrypt", errCipherSuiteNotInit) + cbc := c.cbc.Load() + if cbc == nil { // !c.isInitialized() + return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit) } - return cipherSuite.Encrypt(pkt, raw) + return cbc.(*ciphersuite.CBC).Encrypt(pkt, raw) } // Decrypt decrypts a single TLS RecordLayer func (c *TLSPskWithAes128CbcSha256) Decrypt(raw []byte) ([]byte, error) { - cipherSuite, ok := c.cbc.Load().(*ciphersuite.CBC) - if !ok { + cbc := c.cbc.Load() + if cbc == nil { // !c.isInitialized() return nil, fmt.Errorf("%w, unable to decrypt", errCipherSuiteNotInit) } - return cipherSuite.Decrypt(raw) + return cbc.(*ciphersuite.CBC).Decrypt(raw) } diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_ccm.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_ccm.go index 1ded09b88..8c13bb1b3 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_ccm.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_ccm.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( @@ -10,5 +7,5 @@ import ( // NewTLSPskWithAes128Ccm returns the TLS_PSK_WITH_AES_128_CCM CipherSuite func NewTLSPskWithAes128Ccm() *Aes128Ccm { - return newAes128Ccm(clientcertificate.Type(0), TLS_PSK_WITH_AES_128_CCM, true, ciphersuite.CCMTagLength, KeyExchangeAlgorithmPsk, false) + return newAes128Ccm(clientcertificate.Type(0), TLS_PSK_WITH_AES_128_CCM, true, ciphersuite.CCMTagLength) } diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_ccm8.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_ccm8.go index 478197074..d04abb4d2 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_ccm8.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_ccm8.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( @@ -10,5 +7,5 @@ import ( // NewTLSPskWithAes128Ccm8 returns the TLS_PSK_WITH_AES_128_CCM_8 CipherSuite func NewTLSPskWithAes128Ccm8() *Aes128Ccm { - return newAes128Ccm(clientcertificate.Type(0), TLS_PSK_WITH_AES_128_CCM_8, true, ciphersuite.CCMTagLength8, KeyExchangeAlgorithmPsk, false) + return newAes128Ccm(clientcertificate.Type(0), TLS_PSK_WITH_AES_128_CCM_8, true, ciphersuite.CCMTagLength8) } diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_gcm_sha256.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_gcm_sha256.go index 8ab5b89a8..5f1033559 100644 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_gcm_sha256.go +++ b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_128_gcm_sha256.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import "github.com/pion/dtls/v2/pkg/crypto/clientcertificate" @@ -15,11 +12,6 @@ func (c *TLSPskWithAes128GcmSha256) CertificateType() clientcertificate.Type { return clientcertificate.Type(0) } -// KeyExchangeAlgorithm controls what key exchange algorithm is using during the handshake -func (c *TLSPskWithAes128GcmSha256) KeyExchangeAlgorithm() KeyExchangeAlgorithm { - return KeyExchangeAlgorithmPsk -} - // ID returns the ID of the CipherSuite func (c *TLSPskWithAes128GcmSha256) ID() ID { return TLS_PSK_WITH_AES_128_GCM_SHA256 diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_256_ccm8.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_256_ccm8.go deleted file mode 100644 index 32d503018..000000000 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/tls_psk_with_aes_256_ccm8.go +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package ciphersuite - -import ( - "github.com/pion/dtls/v2/pkg/crypto/ciphersuite" - "github.com/pion/dtls/v2/pkg/crypto/clientcertificate" -) - -// NewTLSPskWithAes256Ccm8 returns the TLS_PSK_WITH_AES_256_CCM_8 CipherSuite -func NewTLSPskWithAes256Ccm8() *Aes256Ccm { - return newAes256Ccm(clientcertificate.Type(0), TLS_PSK_WITH_AES_256_CCM_8, true, ciphersuite.CCMTagLength8, KeyExchangeAlgorithmPsk, false) -} diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/types/authentication_type.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/types/authentication_type.go deleted file mode 100644 index 2da21e642..000000000 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/types/authentication_type.go +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package types - -// AuthenticationType controls what authentication method is using during the handshake -type AuthenticationType int - -// AuthenticationType Enums -const ( - AuthenticationTypeCertificate AuthenticationType = iota + 1 - AuthenticationTypePreSharedKey - AuthenticationTypeAnonymous -) diff --git a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/types/key_exchange_algorithm.go b/vendor/github.com/pion/dtls/v2/internal/ciphersuite/types/key_exchange_algorithm.go deleted file mode 100644 index c2c39113a..000000000 --- a/vendor/github.com/pion/dtls/v2/internal/ciphersuite/types/key_exchange_algorithm.go +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -// Package types provides types for TLS Ciphers -package types - -// KeyExchangeAlgorithm controls what exchange algorithm was chosen. -type KeyExchangeAlgorithm int - -// KeyExchangeAlgorithm Bitmask -const ( - KeyExchangeAlgorithmNone KeyExchangeAlgorithm = 0 - KeyExchangeAlgorithmPsk KeyExchangeAlgorithm = iota << 1 - KeyExchangeAlgorithmEcdhe -) - -// Has check if keyExchangeAlgorithm is supported. -func (a KeyExchangeAlgorithm) Has(v KeyExchangeAlgorithm) bool { - return (a & v) == v -} diff --git a/vendor/github.com/pion/dtls/v2/internal/closer/closer.go b/vendor/github.com/pion/dtls/v2/internal/closer/closer.go index bfa171cda..b99e13e44 100644 --- a/vendor/github.com/pion/dtls/v2/internal/closer/closer.go +++ b/vendor/github.com/pion/dtls/v2/internal/closer/closer.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package closer provides signaling channel for shutdown package closer diff --git a/vendor/github.com/pion/dtls/v2/internal/util/util.go b/vendor/github.com/pion/dtls/v2/internal/util/util.go index 685910fc2..746a670f4 100644 --- a/vendor/github.com/pion/dtls/v2/internal/util/util.go +++ b/vendor/github.com/pion/dtls/v2/internal/util/util.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package util contains small helpers used across the repo package util diff --git a/vendor/github.com/pion/dtls/v2/listener.go b/vendor/github.com/pion/dtls/v2/listener.go index 190d236c7..bf80345b1 100644 --- a/vendor/github.com/pion/dtls/v2/listener.go +++ b/vendor/github.com/pion/dtls/v2/listener.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -8,7 +5,7 @@ import ( "github.com/pion/dtls/v2/pkg/protocol" "github.com/pion/dtls/v2/pkg/protocol/recordlayer" - "github.com/pion/transport/v2/udp" + "github.com/pion/udp" ) // Listen creates a DTLS listener diff --git a/vendor/github.com/pion/dtls/v2/packet.go b/vendor/github.com/pion/dtls/v2/packet.go index 55d6272ee..8366a3c3d 100644 --- a/vendor/github.com/pion/dtls/v2/packet.go +++ b/vendor/github.com/pion/dtls/v2/packet.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import "github.com/pion/dtls/v2/pkg/protocol/recordlayer" diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/ccm/ccm.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/ccm/ccm.go index d6e6fc479..20e3436e2 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/ccm/ccm.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/ccm/ccm.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package ccm implements a CCM, Counter with CBC-MAC // as per RFC 3610. // diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/cbc.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/cbc.go index 460fb1437..8ff163486 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/cbc.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/cbc.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( //nolint:gci @@ -42,21 +39,11 @@ func NewCBC(localKey, localWriteIV, localMac, remoteKey, remoteWriteIV, remoteMa return nil, err } - writeCBC, ok := cipher.NewCBCEncrypter(writeBlock, localWriteIV).(cbcMode) - if !ok { - return nil, errFailedToCast - } - - readCBC, ok := cipher.NewCBCDecrypter(readBlock, remoteWriteIV).(cbcMode) - if !ok { - return nil, errFailedToCast - } - return &CBC{ - writeCBC: writeCBC, + writeCBC: cipher.NewCBCEncrypter(writeBlock, localWriteIV).(cbcMode), writeMac: localMac, - readCBC: readCBC, + readCBC: cipher.NewCBCDecrypter(readBlock, remoteWriteIV).(cbcMode), readMac: remoteMac, h: h, }, nil diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/ccm.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/ccm.go index 24050dc92..354b1cc50 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/ccm.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/ccm.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( @@ -101,7 +98,7 @@ func (c *CCM) Decrypt(in []byte) ([]byte, error) { additionalData := generateAEADAdditionalData(&h, len(out)-int(c.tagLen)) out, err = c.remoteCCM.Open(out[:0], nonce, out, additionalData) if err != nil { - return nil, fmt.Errorf("%w: %v", errDecryptPacket, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errDecryptPacket, err) } return append(in[:recordlayer.HeaderSize], out...), nil } diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/ciphersuite.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/ciphersuite.go index 9d9fb7418..72beffd09 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/ciphersuite.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/ciphersuite.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package ciphersuite provides the crypto operations needed for a DTLS CipherSuite package ciphersuite @@ -16,7 +13,6 @@ var ( errNotEnoughRoomForNonce = &protocol.InternalError{Err: errors.New("buffer not long enough to contain nonce")} //nolint:goerr113 errDecryptPacket = &protocol.TemporaryError{Err: errors.New("failed to decrypt packet")} //nolint:goerr113 errInvalidMAC = &protocol.TemporaryError{Err: errors.New("invalid mac")} //nolint:goerr113 - errFailedToCast = &protocol.FatalError{Err: errors.New("failed to cast")} //nolint:goerr113 ) func generateAEADAdditionalData(h *recordlayer.Header, payloadLen int) []byte { diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/gcm.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/gcm.go index c0fd1f76f..af986d46e 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/gcm.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/ciphersuite/gcm.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ciphersuite import ( @@ -97,7 +94,7 @@ func (g *GCM) Decrypt(in []byte) ([]byte, error) { additionalData := generateAEADAdditionalData(&h, len(out)-gcmTagLength) out, err = g.remoteGCM.Open(out[:0], nonce, out, additionalData) if err != nil { - return nil, fmt.Errorf("%w: %v", errDecryptPacket, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errDecryptPacket, err) } return append(in[:recordlayer.HeaderSize], out...), nil } diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/clientcertificate/client_certificate.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/clientcertificate/client_certificate.go index ddfa39ebe..c222c01c7 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/clientcertificate/client_certificate.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/clientcertificate/client_certificate.go @@ -1,13 +1,10 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package clientcertificate provides all the support Client Certificate types package clientcertificate // Type is used to communicate what // type of certificate is being transported // -// https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-2 +//https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-2 type Type byte // ClientCertificateType enums diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/elliptic/elliptic.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/elliptic/elliptic.go index 126523872..5b0e4fa14 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/elliptic/elliptic.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/elliptic/elliptic.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package elliptic provides elliptic curve cryptography for DTLS package elliptic @@ -8,7 +5,6 @@ import ( "crypto/elliptic" "crypto/rand" "errors" - "fmt" "golang.org/x/crypto/curve25519" ) @@ -61,18 +57,6 @@ const ( X25519 Curve = 0x001d ) -func (c Curve) String() string { - switch c { - case P256: - return "P-256" - case P384: - return "P-384" - case X25519: - return "X25519" - } - return fmt.Sprintf("%#x", uint16(c)) -} - // Curves returns all curves we implement func Curves() map[Curve]bool { return map[Curve]bool{ @@ -84,7 +68,7 @@ func Curves() map[Curve]bool { // GenerateKeypair generates a keypair for the given Curve func GenerateKeypair(c Curve) (*Keypair, error) { - switch c { //nolint:revive + switch c { //nolint:golint case X25519: tmp := make([]byte, 32) if _, err := rand.Read(tmp); err != nil { diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/fingerprint/fingerprint.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/fingerprint/fingerprint.go index 7c66265c7..215b44ec7 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/fingerprint/fingerprint.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/fingerprint/fingerprint.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package fingerprint provides a helper to create fingerprint string from certificate package fingerprint diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/fingerprint/hash.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/fingerprint/hash.go index 3f988ffb7..09107db92 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/fingerprint/hash.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/fingerprint/hash.go @@ -1,12 +1,8 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package fingerprint import ( "crypto" "errors" - "strings" ) var errInvalidHashAlgorithm = errors.New("fingerprint: invalid hash algorithm") @@ -24,7 +20,7 @@ func nameToHash() map[string]crypto.Hash { // HashFromString allows looking up a hash algorithm by it's string representation func HashFromString(s string) (crypto.Hash, error) { - if h, ok := nameToHash()[strings.ToLower(s)]; ok { + if h, ok := nameToHash()[s]; ok { return h, nil } return 0, errInvalidHashAlgorithm diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/hash/hash.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/hash/hash.go index 9966626e3..660326f78 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/hash/hash.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/hash/hash.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package hash provides TLS HashAlgorithm as defined in TLS 1.2 package hash diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/prf/prf.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/prf/prf.go index 6e7b3ecba..d33df19cb 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/prf/prf.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/prf/prf.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package prf implements TLS 1.2 Pseudorandom functions package prf @@ -77,34 +74,6 @@ func PSKPreMasterSecret(psk []byte) []byte { return out } -// EcdhePSKPreMasterSecret implements TLS 1.2 Premaster Secret generation given a psk, a keypair and a curve -// -// https://datatracker.ietf.org/doc/html/rfc5489#section-2 -func EcdhePSKPreMasterSecret(psk, publicKey, privateKey []byte, curve elliptic.Curve) ([]byte, error) { - preMasterSecret, err := PreMasterSecret(publicKey, privateKey, curve) - if err != nil { - return nil, err - } - out := make([]byte, 2+len(preMasterSecret)+2+len(psk)) - - // write preMasterSecret length - offset := 0 - binary.BigEndian.PutUint16(out[offset:], uint16(len(preMasterSecret))) - offset += 2 - - // write preMasterSecret - copy(out[offset:], preMasterSecret) - offset += len(preMasterSecret) - - // write psk length - binary.BigEndian.PutUint16(out[offset:], uint16(len(psk))) - offset += 2 - - // write psk - copy(out[offset:], psk) - return out, nil -} - // PreMasterSecret implements TLS 1.2 Premaster Secret generation given a keypair and a curve func PreMasterSecret(publicKey, privateKey []byte, curve elliptic.Curve) ([]byte, error) { switch curve { @@ -138,14 +107,14 @@ func ellipticCurvePreMasterSecret(publicKey, privateKey []byte, c1, c2 ellipticS // specify a PRF and, in general, SHOULD use the TLS PRF with SHA-256 or a // stronger standard hash function. // -// P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + -// HMAC_hash(secret, A(2) + seed) + -// HMAC_hash(secret, A(3) + seed) + ... +// P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + +// HMAC_hash(secret, A(2) + seed) + +// HMAC_hash(secret, A(3) + seed) + ... // // A() is defined as: // -// A(0) = seed -// A(i) = HMAC_hash(secret, A(i-1)) +// A(0) = seed +// A(i) = HMAC_hash(secret, A(i-1)) // // P_hash can be iterated as many times as necessary to produce the // required quantity of data. For example, if P_SHA256 is being used to diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/signature/signature.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/signature/signature.go index fec7fba3b..d9150eb8c 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/signature/signature.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/signature/signature.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package signature provides our implemented Signature Algorithms package signature diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/signaturehash/errors.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/signaturehash/errors.go index 4aeb3e40a..9d9d3b309 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/signaturehash/errors.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/signaturehash/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package signaturehash import "errors" diff --git a/vendor/github.com/pion/dtls/v2/pkg/crypto/signaturehash/signaturehash.go b/vendor/github.com/pion/dtls/v2/pkg/crypto/signaturehash/signaturehash.go index 2561accd1..f2017bc28 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/crypto/signaturehash/signaturehash.go +++ b/vendor/github.com/pion/dtls/v2/pkg/crypto/signaturehash/signaturehash.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package signaturehash provides the SignatureHashAlgorithm as defined in TLS 1.2 package signaturehash @@ -10,10 +7,10 @@ import ( "crypto/ed25519" "crypto/rsa" "crypto/tls" - "fmt" "github.com/pion/dtls/v2/pkg/crypto/hash" "github.com/pion/dtls/v2/pkg/crypto/signature" + "golang.org/x/xerrors" ) // Algorithm is a signature/hash algorithm pairs which may be used in @@ -73,11 +70,11 @@ func ParseSignatureSchemes(sigs []tls.SignatureScheme, insecureHashes bool) ([]A sig := signature.Algorithm(ss & 0xFF) if _, ok := signature.Algorithms()[sig]; !ok { return nil, - fmt.Errorf("SignatureScheme %04x: %w", ss, errInvalidSignatureAlgorithm) + xerrors.Errorf("SignatureScheme %04x: %w", ss, errInvalidSignatureAlgorithm) } h := hash.Algorithm(ss >> 8) if _, ok := hash.Algorithms()[h]; !ok || (ok && h == hash.None) { - return nil, fmt.Errorf("SignatureScheme %04x: %w", ss, errInvalidHashAlgorithm) + return nil, xerrors.Errorf("SignatureScheme %04x: %w", ss, errInvalidHashAlgorithm) } if h.Insecure() && !insecureHashes { continue diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/alert/alert.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/alert/alert.go index 91e9f4d60..663c6b379 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/alert/alert.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/alert/alert.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package alert implements TLS alert protocol https://tools.ietf.org/html/rfc5246#section-7.2 package alert diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/application_data.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/application_data.go index f42211511..e5fd6f549 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/application_data.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/application_data.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package protocol // ApplicationData messages are carried by the record layer and are diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/change_cipher_spec.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/change_cipher_spec.go index 87f28bc37..b42647a05 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/change_cipher_spec.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/change_cipher_spec.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package protocol // ChangeCipherSpec protocol exists to signal transitions in diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/compression_method.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/compression_method.go index 3478ee38c..678e816cb 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/compression_method.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/compression_method.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package protocol // CompressionMethodID is the ID for a CompressionMethod diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/content.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/content.go index 92c9db2bf..47e5c96bb 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/content.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/content.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package protocol // ContentType represents the IANA Registered ContentTypes diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/errors.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/errors.go index d87aff7fb..e52014a1e 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/errors.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package protocol import ( @@ -87,8 +84,7 @@ func (e *TimeoutError) Error() string { return fmt.Sprintf("dtls timeout: %v", e // Timeout implements net.Error.Timeout() func (e *HandshakeError) Timeout() bool { - var netErr net.Error - if errors.As(e.Err, &netErr) { + if netErr, ok := e.Err.(net.Error); ok { return netErr.Timeout() } return false @@ -96,9 +92,8 @@ func (e *HandshakeError) Timeout() bool { // Temporary implements net.Error.Temporary() func (e *HandshakeError) Temporary() bool { - var netErr net.Error - if errors.As(e.Err, &netErr) { - return netErr.Temporary() //nolint + if netErr, ok := e.Err.(net.Error); ok { + return netErr.Temporary() } return false } diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/alpn.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/alpn.go index e780dc9e1..8d7e1123e 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/alpn.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/alpn.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package extension import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/errors.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/errors.go index c5e954ce5..82d8b3408 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/errors.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package extension import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/extension.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/extension.go index 5173a5863..ec4c1ff5c 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/extension.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/extension.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package extension implements the extension values in the ClientHello/ServerHello package extension diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/renegotiation_info.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/renegotiation_info.go index c5092a7db..8378c3d94 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/renegotiation_info.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/renegotiation_info.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package extension import "encoding/binary" diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/server_name.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/server_name.go index 183e08e6e..9a1cc2926 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/server_name.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/server_name.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package extension import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/srtp_protection_profile.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/srtp_protection_profile.go index 2966966dd..2c4d1d4a6 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/srtp_protection_profile.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/srtp_protection_profile.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package extension // SRTPProtectionProfile defines the parameters and options that are in effect for the SRTP processing diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_elliptic_curves.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_elliptic_curves.go index dd9b54f0d..8f077fcc7 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_elliptic_curves.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_elliptic_curves.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package extension import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_point_formats.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_point_formats.go index 9c2543e6e..873d07827 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_point_formats.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_point_formats.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package extension import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_signature_algorithms.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_signature_algorithms.go index 2ff4b90b6..ee284f6e1 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_signature_algorithms.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/supported_signature_algorithms.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package extension import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/use_master_secret.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/use_master_secret.go index d0b70cafb..04ddc956a 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/use_master_secret.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/use_master_secret.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package extension import "encoding/binary" diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/use_srtp.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/use_srtp.go index ea9f10872..729fa3a98 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/use_srtp.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/extension/use_srtp.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package extension import "encoding/binary" diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/cipher_suite.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/cipher_suite.go index b29629717..e8fbdeae7 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/cipher_suite.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/cipher_suite.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import "encoding/binary" diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/errors.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/errors.go index 1354300c4..ac77c0434 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/errors.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/handshake.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/handshake.go index b1f682bf5..f25458178 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/handshake.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/handshake.go @@ -1,11 +1,7 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package handshake provides the DTLS wire protocol for handshakes package handshake import ( - "github.com/pion/dtls/v2/internal/ciphersuite/types" "github.com/pion/dtls/v2/internal/util" "github.com/pion/dtls/v2/pkg/protocol" ) @@ -74,8 +70,6 @@ type Message interface { type Handshake struct { Header Header Message Message - - KeyExchangeAlgorithm types.KeyExchangeAlgorithm } // ContentType returns what kind of content this message is carying @@ -132,13 +126,13 @@ func (h *Handshake) Unmarshal(data []byte) error { case TypeCertificate: h.Message = &MessageCertificate{} case TypeServerKeyExchange: - h.Message = &MessageServerKeyExchange{KeyExchangeAlgorithm: h.KeyExchangeAlgorithm} + h.Message = &MessageServerKeyExchange{} case TypeCertificateRequest: h.Message = &MessageCertificateRequest{} case TypeServerHelloDone: h.Message = &MessageServerHelloDone{} case TypeClientKeyExchange: - h.Message = &MessageClientKeyExchange{KeyExchangeAlgorithm: h.KeyExchangeAlgorithm} + h.Message = &MessageClientKeyExchange{} case TypeFinished: h.Message = &MessageFinished{} case TypeCertificateVerify: diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/header.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/header.go index 4f9a96287..cb6a22489 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/header.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/header.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate.go index d5c861d90..05fb74656 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate_request.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate_request.go index 11a44d440..e711f392b 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate_request.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate_request.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import ( @@ -22,9 +19,8 @@ server's Certificate message). https://tools.ietf.org/html/rfc5246#section-7.4.4 */ type MessageCertificateRequest struct { - CertificateTypes []clientcertificate.Type - SignatureHashAlgorithms []signaturehash.Algorithm - CertificateAuthoritiesNames [][]byte + CertificateTypes []clientcertificate.Type + SignatureHashAlgorithms []signaturehash.Algorithm } const ( @@ -50,20 +46,7 @@ func (m *MessageCertificateRequest) Marshal() ([]byte, error) { out = append(out, byte(v.Signature)) } - // Distinguished Names - casLength := 0 - for _, ca := range m.CertificateAuthoritiesNames { - casLength += len(ca) + 2 - } - out = append(out, []byte{0x00, 0x00}...) - binary.BigEndian.PutUint16(out[len(out)-2:], uint16(casLength)) - if casLength > 0 { - for _, ca := range m.CertificateAuthoritiesNames { - out = append(out, []byte{0x00, 0x00}...) - binary.BigEndian.PutUint16(out[len(out)-2:], uint16(len(ca))) - out = append(out, ca...) - } - } + out = append(out, []byte{0x00, 0x00}...) // Distinguished Names Length return out, nil } @@ -113,32 +96,5 @@ func (m *MessageCertificateRequest) Unmarshal(data []byte) error { m.SignatureHashAlgorithms = append(m.SignatureHashAlgorithms, signaturehash.Algorithm{Signature: s, Hash: h}) } - offset += signatureHashAlgorithmsLength - if len(data) < offset+2 { - return errBufferTooSmall - } - casLength := int(binary.BigEndian.Uint16(data[offset:])) - offset += 2 - if (offset + casLength) > len(data) { - return errBufferTooSmall - } - cas := make([]byte, casLength) - copy(cas, data[offset:offset+casLength]) - m.CertificateAuthoritiesNames = nil - for len(cas) > 0 { - if len(cas) < 2 { - return errBufferTooSmall - } - caLen := binary.BigEndian.Uint16(cas) - cas = cas[2:] - - if len(cas) < int(caLen) { - return errBufferTooSmall - } - - m.CertificateAuthoritiesNames = append(m.CertificateAuthoritiesNames, cas[:caLen]) - cas = cas[caLen:] - } - return nil } diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate_verify.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate_verify.go index 9e02a9c11..fb5e4639d 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate_verify.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_certificate_verify.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_client_hello.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_client_hello.go index bea6dd969..1deca38aa 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_client_hello.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_client_hello.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_client_key_exchange.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_client_key_exchange.go index 2abcd5bf7..f8fc36985 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_client_key_exchange.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_client_key_exchange.go @@ -1,12 +1,7 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import ( "encoding/binary" - - "github.com/pion/dtls/v2/internal/ciphersuite/types" ) // MessageClientKeyExchange is a DTLS Handshake Message @@ -19,9 +14,6 @@ import ( type MessageClientKeyExchange struct { IdentityHint []byte PublicKey []byte - - // for unmarshaling - KeyExchangeAlgorithm types.KeyExchangeAlgorithm } // Type returns the Handshake Type @@ -30,52 +22,35 @@ func (m MessageClientKeyExchange) Type() Type { } // Marshal encodes the Handshake -func (m *MessageClientKeyExchange) Marshal() (out []byte, err error) { - if m.IdentityHint == nil && m.PublicKey == nil { +func (m *MessageClientKeyExchange) Marshal() ([]byte, error) { + switch { + case (m.IdentityHint != nil && m.PublicKey != nil) || (m.IdentityHint == nil && m.PublicKey == nil): return nil, errInvalidClientKeyExchange - } - - if m.IdentityHint != nil { - out = append([]byte{0x00, 0x00}, m.IdentityHint...) + case m.PublicKey != nil: + return append([]byte{byte(len(m.PublicKey))}, m.PublicKey...), nil + default: + out := append([]byte{0x00, 0x00}, m.IdentityHint...) binary.BigEndian.PutUint16(out, uint16(len(out)-2)) + return out, nil } - - if m.PublicKey != nil { - out = append(out, byte(len(m.PublicKey))) - out = append(out, m.PublicKey...) - } - - return out, nil } // Unmarshal populates the message from encoded data func (m *MessageClientKeyExchange) Unmarshal(data []byte) error { - switch { - case len(data) < 2: + if len(data) < 2 { return errBufferTooSmall - case m.KeyExchangeAlgorithm == types.KeyExchangeAlgorithmNone: - return errCipherSuiteUnset } - offset := 0 - if m.KeyExchangeAlgorithm.Has(types.KeyExchangeAlgorithmPsk) { - pskLength := int(binary.BigEndian.Uint16(data)) - if pskLength > len(data)-2 { - return errBufferTooSmall - } - - m.IdentityHint = append([]byte{}, data[2:pskLength+2]...) - offset += pskLength + 2 + // If parsed as PSK return early and only populate PSK Identity Hint + if pskLength := binary.BigEndian.Uint16(data); len(data) == int(pskLength+2) { + m.IdentityHint = append([]byte{}, data[2:]...) + return nil } - if m.KeyExchangeAlgorithm.Has(types.KeyExchangeAlgorithmEcdhe) { - publicKeyLength := int(data[offset]) - if publicKeyLength > len(data)-1-offset { - return errBufferTooSmall - } - - m.PublicKey = append([]byte{}, data[offset+1:]...) + if publicKeyLength := int(data[0]); len(data) != publicKeyLength+1 { + return errBufferTooSmall } + m.PublicKey = append([]byte{}, data[1:]...) return nil } diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_finished.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_finished.go index 255aedd7e..c65d42abb 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_finished.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_finished.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake // MessageFinished is a DTLS Handshake Message diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_hello_verify_request.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_hello_verify_request.go index 398e59cc3..ef834dc85 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_hello_verify_request.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_hello_verify_request.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import ( @@ -9,19 +6,19 @@ import ( // MessageHelloVerifyRequest is as follows: // -// struct { -// ProtocolVersion server_version; -// opaque cookie<0..2^8-1>; -// } HelloVerifyRequest; +// struct { +// ProtocolVersion server_version; +// opaque cookie<0..2^8-1>; +// } HelloVerifyRequest; // -// The HelloVerifyRequest message type is hello_verify_request(3). +// The HelloVerifyRequest message type is hello_verify_request(3). // -// When the client sends its ClientHello message to the server, the server -// MAY respond with a HelloVerifyRequest message. This message contains -// a stateless cookie generated using the technique of [PHOTURIS]. The -// client MUST retransmit the ClientHello with the cookie added. +// When the client sends its ClientHello message to the server, the server +// MAY respond with a HelloVerifyRequest message. This message contains +// a stateless cookie generated using the technique of [PHOTURIS]. The +// client MUST retransmit the ClientHello with the cookie added. // -// https://tools.ietf.org/html/rfc6347#section-4.2.1 +// https://tools.ietf.org/html/rfc6347#section-4.2.1 type MessageHelloVerifyRequest struct { Version protocol.Version Cookie []byte @@ -54,8 +51,8 @@ func (m *MessageHelloVerifyRequest) Unmarshal(data []byte) error { } m.Version.Major = data[0] m.Version.Minor = data[1] - cookieLength := int(data[2]) - if len(data) < cookieLength+3 { + cookieLength := data[2] + if len(data) < (int(cookieLength) + 3) { return errBufferTooSmall } m.Cookie = make([]byte, cookieLength) diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_hello.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_hello.go index caf186da8..9c1cc2218 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_hello.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_hello.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import ( @@ -91,14 +88,11 @@ func (m *MessageServerHello) Unmarshal(data []byte) error { m.SessionID = append([]byte{}, data[currOffset:currOffset+n]...) currOffset += len(m.SessionID) - if len(data) < currOffset+2 { - return errBufferTooSmall - } m.CipherSuiteID = new(uint16) *m.CipherSuiteID = binary.BigEndian.Uint16(data[currOffset:]) currOffset += 2 - if len(data) <= currOffset { + if len(data) < currOffset { return errBufferTooSmall } if compressionMethod, ok := protocol.CompressionMethods()[protocol.CompressionMethodID(data[currOffset])]; ok { diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_hello_done.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_hello_done.go index b187dd417..0f65b198e 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_hello_done.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_hello_done.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake // MessageServerHelloDone is final non-encrypted message from server @@ -19,6 +16,6 @@ func (m *MessageServerHelloDone) Marshal() ([]byte, error) { } // Unmarshal populates the message from encoded data -func (m *MessageServerHelloDone) Unmarshal([]byte) error { +func (m *MessageServerHelloDone) Unmarshal(data []byte) error { return nil } diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_key_exchange.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_key_exchange.go index 82abbe0d4..4148fe05b 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_key_exchange.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/message_server_key_exchange.go @@ -1,12 +1,8 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import ( "encoding/binary" - "github.com/pion/dtls/v2/internal/ciphersuite/types" "github.com/pion/dtls/v2/pkg/crypto/elliptic" "github.com/pion/dtls/v2/pkg/crypto/hash" "github.com/pion/dtls/v2/pkg/crypto/signature" @@ -22,9 +18,6 @@ type MessageServerKeyExchange struct { HashAlgorithm hash.Algorithm SignatureAlgorithm signature.Algorithm Signature []byte - - // for unmarshaling - KeyExchangeAlgorithm types.KeyExchangeAlgorithm } // Type returns the Handshake Type @@ -34,28 +27,19 @@ func (m MessageServerKeyExchange) Type() Type { // Marshal encodes the Handshake func (m *MessageServerKeyExchange) Marshal() ([]byte, error) { - var out []byte if m.IdentityHint != nil { - out = append([]byte{0x00, 0x00}, m.IdentityHint...) + out := append([]byte{0x00, 0x00}, m.IdentityHint...) binary.BigEndian.PutUint16(out, uint16(len(out)-2)) - } - - if m.EllipticCurveType == 0 || len(m.PublicKey) == 0 { return out, nil } - out = append(out, byte(m.EllipticCurveType), 0x00, 0x00) - binary.BigEndian.PutUint16(out[len(out)-2:], uint16(m.NamedCurve)) + + out := []byte{byte(m.EllipticCurveType), 0x00, 0x00} + binary.BigEndian.PutUint16(out[1:], uint16(m.NamedCurve)) out = append(out, byte(len(m.PublicKey))) out = append(out, m.PublicKey...) - switch { - case m.HashAlgorithm != hash.None && len(m.Signature) == 0: - return nil, errInvalidHashAlgorithm - case m.HashAlgorithm == hash.None && len(m.Signature) > 0: - return nil, errInvalidHashAlgorithm - case m.SignatureAlgorithm == signature.Anonymous && (m.HashAlgorithm != hash.None || len(m.Signature) > 0): - return nil, errInvalidSignatureAlgorithm - case m.SignatureAlgorithm == signature.Anonymous: + + if m.HashAlgorithm == hash.None && m.SignatureAlgorithm == signature.Anonymous && len(m.Signature) == 0 { return out, nil } @@ -68,27 +52,14 @@ func (m *MessageServerKeyExchange) Marshal() ([]byte, error) { // Unmarshal populates the message from encoded data func (m *MessageServerKeyExchange) Unmarshal(data []byte) error { - switch { - case len(data) < 2: + if len(data) < 2 { return errBufferTooSmall - case m.KeyExchangeAlgorithm == types.KeyExchangeAlgorithmNone: - return errCipherSuiteUnset } - hintLength := binary.BigEndian.Uint16(data) - if int(hintLength) <= len(data)-2 && m.KeyExchangeAlgorithm.Has(types.KeyExchangeAlgorithmPsk) { - m.IdentityHint = append([]byte{}, data[2:2+hintLength]...) - data = data[2+hintLength:] - } - if m.KeyExchangeAlgorithm == types.KeyExchangeAlgorithmPsk { - if len(data) == 0 { - return nil - } - return errLengthMismatch - } - - if !m.KeyExchangeAlgorithm.Has(types.KeyExchangeAlgorithmEcdhe) { - return errLengthMismatch + // If parsed as PSK return early and only populate PSK Identity Hint + if pskLength := binary.BigEndian.Uint16(data); len(data) == int(pskLength+2) { + m.IdentityHint = append([]byte{}, data[2:]...) + return nil } if _, ok := elliptic.CurveTypes()[elliptic.CurveType(data[0])]; ok { diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/random.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/random.go index 56f37569b..0ade936eb 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/random.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/handshake/random.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package handshake import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/errors.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/errors.go index cd4cb60a5..7033d4058 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/errors.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package recordlayer implements the TLS Record Layer https://tools.ietf.org/html/rfc5246#section-6 package recordlayer diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/header.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/header.go index 92252502b..65047d767 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/header.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/header.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package recordlayer import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/recordlayer.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/recordlayer.go index 02325fd2d..67e5a727b 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/recordlayer.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/recordlayer/recordlayer.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package recordlayer import ( diff --git a/vendor/github.com/pion/dtls/v2/pkg/protocol/version.go b/vendor/github.com/pion/dtls/v2/pkg/protocol/version.go index c4d94ac3a..d5ddb1d00 100644 --- a/vendor/github.com/pion/dtls/v2/pkg/protocol/version.go +++ b/vendor/github.com/pion/dtls/v2/pkg/protocol/version.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package protocol provides the DTLS wire format package protocol diff --git a/vendor/github.com/pion/dtls/v2/renovate.json b/vendor/github.com/pion/dtls/v2/renovate.json index f1bb98c6a..f1614058a 100644 --- a/vendor/github.com/pion/dtls/v2/renovate.json +++ b/vendor/github.com/pion/dtls/v2/renovate.json @@ -1,6 +1,27 @@ { - "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ - "github>pion/renovate-config" + "config:base", + ":disableDependencyDashboard" + ], + "postUpdateOptions": [ + "gomodTidy" + ], + "commitBody": "Generated by renovateBot", + "packageRules": [ + { + "matchUpdateTypes": ["minor", "patch", "pin", "digest"], + "automerge": true + }, + { + "packagePatterns": ["^golang.org/x/"], + "schedule": ["on the first day of the month"] + } + ], + "ignorePaths": [ + ".github/workflows/generate-authors.yml", + ".github/workflows/lint.yaml", + ".github/workflows/renovate-go-mod-fix.yaml", + ".github/workflows/test.yaml", + ".github/workflows/tidy-check.yaml" ] } diff --git a/vendor/github.com/pion/dtls/v2/resume.go b/vendor/github.com/pion/dtls/v2/resume.go index c470d856b..40e55e449 100644 --- a/vendor/github.com/pion/dtls/v2/resume.go +++ b/vendor/github.com/pion/dtls/v2/resume.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( diff --git a/vendor/github.com/pion/dtls/v2/session.go b/vendor/github.com/pion/dtls/v2/session.go index 99bf5a499..f52120cd8 100644 --- a/vendor/github.com/pion/dtls/v2/session.go +++ b/vendor/github.com/pion/dtls/v2/session.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls // Session store data needed in resumption diff --git a/vendor/github.com/pion/dtls/v2/srtp_protection_profile.go b/vendor/github.com/pion/dtls/v2/srtp_protection_profile.go index e306e9e6a..1c3ae55dc 100644 --- a/vendor/github.com/pion/dtls/v2/srtp_protection_profile.go +++ b/vendor/github.com/pion/dtls/v2/srtp_protection_profile.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import "github.com/pion/dtls/v2/pkg/protocol/extension" @@ -10,8 +7,8 @@ import "github.com/pion/dtls/v2/pkg/protocol/extension" type SRTPProtectionProfile = extension.SRTPProtectionProfile const ( - SRTP_AES128_CM_HMAC_SHA1_80 SRTPProtectionProfile = extension.SRTP_AES128_CM_HMAC_SHA1_80 // nolint:revive,stylecheck - SRTP_AES128_CM_HMAC_SHA1_32 SRTPProtectionProfile = extension.SRTP_AES128_CM_HMAC_SHA1_32 // nolint:revive,stylecheck - SRTP_AEAD_AES_128_GCM SRTPProtectionProfile = extension.SRTP_AEAD_AES_128_GCM // nolint:revive,stylecheck - SRTP_AEAD_AES_256_GCM SRTPProtectionProfile = extension.SRTP_AEAD_AES_256_GCM // nolint:revive,stylecheck + SRTP_AES128_CM_HMAC_SHA1_80 SRTPProtectionProfile = extension.SRTP_AES128_CM_HMAC_SHA1_80 // nolint + SRTP_AES128_CM_HMAC_SHA1_32 SRTPProtectionProfile = extension.SRTP_AES128_CM_HMAC_SHA1_32 // nolint + SRTP_AEAD_AES_128_GCM SRTPProtectionProfile = extension.SRTP_AEAD_AES_128_GCM // nolint + SRTP_AEAD_AES_256_GCM SRTPProtectionProfile = extension.SRTP_AEAD_AES_256_GCM // nolint ) diff --git a/vendor/github.com/pion/dtls/v2/state.go b/vendor/github.com/pion/dtls/v2/state.go index e9f86a80b..96fc71b12 100644 --- a/vendor/github.com/pion/dtls/v2/state.go +++ b/vendor/github.com/pion/dtls/v2/state.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls import ( @@ -11,7 +8,7 @@ import ( "github.com/pion/dtls/v2/pkg/crypto/elliptic" "github.com/pion/dtls/v2/pkg/crypto/prf" "github.com/pion/dtls/v2/pkg/protocol/handshake" - "github.com/pion/transport/v2/replaydetector" + "github.com/pion/transport/replaydetector" ) // State holds the dtls connection state and implements both encoding.BinaryMarshaler and encoding.BinaryUnmarshaler @@ -78,10 +75,10 @@ func (s *State) serialize() *serializedState { localRnd := s.localRandom.MarshalFixed() remoteRnd := s.remoteRandom.MarshalFixed() - epoch := s.getLocalEpoch() + epoch := s.localEpoch.Load().(uint16) return &serializedState{ - LocalEpoch: s.getLocalEpoch(), - RemoteEpoch: s.getRemoteEpoch(), + LocalEpoch: epoch, + RemoteEpoch: s.remoteEpoch.Load().(uint16), CipherSuiteID: uint16(s.cipherSuite.ID()), MasterSecret: s.masterSecret, SequenceNumber: atomic.LoadUint64(&s.localSequenceNumber[epoch]), @@ -172,8 +169,10 @@ func (s *State) UnmarshalBinary(data []byte) error { } s.deserialize(serialized) - - return s.initCipherSuite() + if err := s.initCipherSuite(); err != nil { + return err + } + return nil } // ExportKeyingMaterial returns length bytes of exported key material in a new @@ -181,7 +180,7 @@ func (s *State) UnmarshalBinary(data []byte) error { // This allows protocols to use DTLS for key establishment, but // then use some of the keying material for their own purposes func (s *State) ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error) { - if s.getLocalEpoch() == 0 { + if s.localEpoch.Load().(uint16) == 0 { return nil, errHandshakeInProgress } else if len(context) != 0 { return nil, errContextUnsupported @@ -200,17 +199,3 @@ func (s *State) ExportKeyingMaterial(label string, context []byte, length int) ( } return prf.PHash(s.masterSecret, seed, length, s.cipherSuite.HashFunc()) } - -func (s *State) getRemoteEpoch() uint16 { - if remoteEpoch, ok := s.remoteEpoch.Load().(uint16); ok { - return remoteEpoch - } - return 0 -} - -func (s *State) getLocalEpoch() uint16 { - if localEpoch, ok := s.localEpoch.Load().(uint16); ok { - return localEpoch - } - return 0 -} diff --git a/vendor/github.com/pion/dtls/v2/util.go b/vendor/github.com/pion/dtls/v2/util.go index 663c4437c..745182dcd 100644 --- a/vendor/github.com/pion/dtls/v2/util.go +++ b/vendor/github.com/pion/dtls/v2/util.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package dtls func findMatchingSRTPProfile(a, b []SRTPProtectionProfile) (SRTPProtectionProfile, bool) { @@ -14,7 +11,7 @@ func findMatchingSRTPProfile(a, b []SRTPProtectionProfile) (SRTPProtectionProfil return 0, false } -func findMatchingCipherSuite(a, b []CipherSuite) (CipherSuite, bool) { +func findMatchingCipherSuite(a, b []CipherSuite) (CipherSuite, bool) { //nolint for _, aSuite := range a { for _, bSuite := range b { if aSuite.ID() == bSuite.ID() { diff --git a/vendor/github.com/pion/ice/v2/.gitignore b/vendor/github.com/pion/ice/v2/.gitignore index 6e2f206a9..83db74ba5 100644 --- a/vendor/github.com/pion/ice/v2/.gitignore +++ b/vendor/github.com/pion/ice/v2/.gitignore @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - ### JetBrains IDE ### ##################### .idea/ @@ -25,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/ice/v2/.golangci.yml b/vendor/github.com/pion/ice/v2/.golangci.yml index 4e3eddf42..d6162c970 100644 --- a/vendor/github.com/pion/ice/v2/.golangci.yml +++ b/vendor/github.com/pion/ice/v2/.golangci.yml @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - linters-settings: govet: check-shadowing: true @@ -13,34 +10,19 @@ linters-settings: modules: - github.com/pkg/errors: recommendations: - - errors - forbidigo: - forbid: - - ^fmt.Print(f|ln)?$ - - ^log.(Panic|Fatal|Print)(f|ln)?$ - - ^os.Exit$ - - ^panic$ - - ^print(ln)?$ + - errors linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - - decorder # check declaration order and count of types, constants, variables and functions + - deadcode # Finds unused code - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forbidigo # Forbids identifiers - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -53,59 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks + - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - - wastedassign # wastedassign finds wasted assignment statements + - varcheck # Finds unused global variables and constants - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: @@ -115,23 +78,12 @@ issues: - path: _test\.go linters: - gocognit - - forbidigo # Allow complex main function in examples - path: examples text: "of func `main` is high" linters: - gocognit - - # Allow forbidden identifiers in examples - - path: examples - linters: - - forbidigo - - # Allow forbidden identifiers in CLI commands - - path: cmd - linters: - - forbidigo run: skip-dirs-use-default: false diff --git a/vendor/github.com/pion/ice/v2/.goreleaser.yml b/vendor/github.com/pion/ice/v2/.goreleaser.yml deleted file mode 100644 index 30093e9d6..000000000 --- a/vendor/github.com/pion/ice/v2/.goreleaser.yml +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - -builds: -- skip: true diff --git a/vendor/github.com/pion/ice/v2/AUTHORS.txt b/vendor/github.com/pion/ice/v2/AUTHORS.txt index 57eb69378..8c8b66b05 100644 --- a/vendor/github.com/pion/ice/v2/AUTHORS.txt +++ b/vendor/github.com/pion/ice/v2/AUTHORS.txt @@ -2,26 +2,20 @@ # we would love to have you https://github.com/pion/webrtc/wiki/Contributing # # This file is auto generated, using git to list all individuals contributors. -# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting +# see `.github/generate-authors.sh` for the scripting Aaron France Adam Kiss adwpc Aleksandr Razumov -aler9 <46489434+aler9@users.noreply.github.com> Antoine Baché -Artur Shellunts Assad Obaid Atsushi Watanabe backkem buptczq cgojin Chao Yuan -cnderrauber David Hamilton David Zhao -David Zhao -Eric Daniels -Genteure Henry hexiang hn8 <10730886+hn8@users.noreply.github.com> @@ -31,8 +25,6 @@ Jason Maldonis Jerko Steiner JooYoung Juliusz Chroboczek -Kacper Bąk <56700396+53jk1@users.noreply.github.com> -Kevin Caffrey Konstantin Itskov korymiller1489 Kyle Carberry @@ -41,25 +33,17 @@ Luke Curley Meelap Shah Michael MacDonald Michael MacDonald -Mikhail Bragin -Miroslav Šedivý Nevio Vesic Ori Bernstein -Rasmus Hanning Robert Eperjesi Sam Lancia Sam Lancia -San9H0 Sean DuBois Sean DuBois Sebastian Waisbrot Sidney San Martín -Steffen Vogel Will Forcey Woodrow Douglass Yutaka Takeda ZHENK Zizheng Tai - -# List of contributors not appearing in Git history - diff --git a/vendor/github.com/pion/ice/v2/LICENSE b/vendor/github.com/pion/ice/v2/LICENSE index 491caf6b0..ab602974d 100644 --- a/vendor/github.com/pion/ice/v2/LICENSE +++ b/vendor/github.com/pion/ice/v2/LICENSE @@ -1,9 +1,21 @@ MIT License -Copyright (c) 2023 The Pion community +Copyright (c) 2018 -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/pion/ice/v2/README.md b/vendor/github.com/pion/ice/v2/README.md index 111ca7057..8191fc479 100644 --- a/vendor/github.com/pion/ice/v2/README.md +++ b/vendor/github.com/pion/ice/v2/README.md @@ -5,11 +5,11 @@

A Go implementation of ICE

- Pion ICE + Pion transport Slack Widget
- GitHub Workflow Status - Go Reference + Build Status + GoDoc Coverage Status Go Report Card License: MIT @@ -20,15 +20,14 @@ The library is used as a part of our WebRTC implementation. Please refer to that [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones. ### Community -Pion has an active community on the [Slack](https://pion.ly/slack). - -Follow the [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news. +Pion has an active community on the [Golang Slack](https://invite.slack.golangbridge.org/). Sign up and join the **#pion** channel for discussions and support. You can also use [Pion mailing list](https://groups.google.com/forum/#!forum/pion). We are always looking to support **your projects**. Please reach out if you have something to build! + If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly) ### Contributing -Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible: [AUTHORS.txt](./AUTHORS.txt) +Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible: ### License MIT License - see [LICENSE](LICENSE) for full text diff --git a/vendor/github.com/pion/ice/v2/addr.go b/vendor/github.com/pion/ice/v2/addr.go deleted file mode 100644 index 1d70025be..000000000 --- a/vendor/github.com/pion/ice/v2/addr.go +++ /dev/null @@ -1,71 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package ice - -import ( - "net" -) - -func parseMulticastAnswerAddr(in net.Addr) (net.IP, bool) { - switch addr := in.(type) { - case *net.IPAddr: - return addr.IP, true - case *net.UDPAddr: - return addr.IP, true - case *net.TCPAddr: - return addr.IP, true - } - return nil, false -} - -func parseAddr(in net.Addr) (net.IP, int, NetworkType, bool) { - switch addr := in.(type) { - case *net.UDPAddr: - return addr.IP, addr.Port, NetworkTypeUDP4, true - case *net.TCPAddr: - return addr.IP, addr.Port, NetworkTypeTCP4, true - } - return nil, 0, 0, false -} - -func createAddr(network NetworkType, ip net.IP, port int) net.Addr { - switch { - case network.IsTCP(): - return &net.TCPAddr{IP: ip, Port: port} - default: - return &net.UDPAddr{IP: ip, Port: port} - } -} - -func addrEqual(a, b net.Addr) bool { - aIP, aPort, aType, aOk := parseAddr(a) - if !aOk { - return false - } - - bIP, bPort, bType, bOk := parseAddr(b) - if !bOk { - return false - } - - return aType == bType && aIP.Equal(bIP) && aPort == bPort -} - -// AddrPort is an IP and a port number. -type AddrPort [18]byte - -func toAddrPort(addr net.Addr) AddrPort { - var ap AddrPort - switch addr := addr.(type) { - case *net.UDPAddr: - copy(ap[:16], addr.IP.To16()) - ap[16] = uint8(addr.Port >> 8) - ap[17] = uint8(addr.Port) - case *net.TCPAddr: - copy(ap[:16], addr.IP.To16()) - ap[16] = uint8(addr.Port >> 8) - ap[17] = uint8(addr.Port) - } - return ap -} diff --git a/vendor/github.com/pion/ice/v2/agent.go b/vendor/github.com/pion/ice/v2/agent.go index 5350330f6..b4aba19f5 100644 --- a/vendor/github.com/pion/ice/v2/agent.go +++ b/vendor/github.com/pion/ice/v2/agent.go @@ -1,28 +1,20 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package ice implements the Interactive Connectivity Establishment (ICE) // protocol defined in rfc5245. package ice import ( "context" - "fmt" "net" "strings" "sync" "sync/atomic" "time" - atomicx "github.com/pion/ice/v2/internal/atomic" - stunx "github.com/pion/ice/v2/internal/stun" "github.com/pion/logging" "github.com/pion/mdns" "github.com/pion/stun" - "github.com/pion/transport/v2" - "github.com/pion/transport/v2/packetio" - "github.com/pion/transport/v2/stdnet" - "github.com/pion/transport/v2/vnet" + "github.com/pion/transport/packetio" + "github.com/pion/transport/vnet" "golang.org/x/net/proxy" ) @@ -47,7 +39,7 @@ type Agent struct { onConnected chan struct{} onConnectedOnce sync.Once - // Force candidate to be contacted immediately (instead of waiting for task ticker) + // force candidate to be contacted immediately (instead of waiting for task ticker) forceCandidateContact chan bool tieBreaker uint64 @@ -72,8 +64,8 @@ type Agent struct { prflxAcceptanceMinWait time.Duration relayAcceptanceMinWait time.Duration - portMin uint16 - portMax uint16 + portmin uint16 + portmax uint16 candidateTypes []CandidateType @@ -105,10 +97,10 @@ type Agent struct { selectedPair atomic.Value // *CandidatePair - urls []*stun.URI + urls []*URL networkTypes []NetworkType - buf *packetio.Buffer + buffer *packetio.Buffer // LRU of outbound Binding request Transaction IDs pendingBindingRequests []bindingRequest @@ -119,10 +111,9 @@ type Agent struct { // State for closing done chan struct{} taskLoopDone chan struct{} - err atomicx.Error + err atomicError gatherCandidateCancel func() - gatherCandidateDone chan struct{} chanCandidate chan Candidate chanCandidatePair chan *CandidatePair @@ -131,14 +122,11 @@ type Agent struct { loggerFactory logging.LoggerFactory log logging.LeveledLogger - net transport.Net - tcpMux TCPMux - udpMux UDPMux - udpMuxSrflx UniversalUDPMux + net *vnet.Net + tcpMux TCPMux + udpMux UDPMux interfaceFilter func(string) bool - ipFilter func(net.IP) bool - includeLoopback bool insecureSkipVerify bool @@ -214,8 +202,8 @@ func (a *Agent) taskLoop() { a.deleteAllCandidates() a.startedFn() - if err := a.buf.Close(); err != nil { - a.log.Warnf("Failed to close buffer: %v", err) + if err := a.buffer.Close(); err != nil { + a.log.Warnf("failed to close buffer: %v", err) } a.closeMulticastConn() @@ -270,6 +258,21 @@ func NewAgent(config *AgentConfig) (*Agent, error) { //nolint:gocognit } log := loggerFactory.NewLogger("ice") + var mDNSConn *mdns.Conn + mDNSConn, mDNSMode, err = createMulticastDNS(mDNSMode, mDNSName, log) + // Opportunistic mDNS: If we can't open the connection, that's ok: we + // can continue without it. + if err != nil { + log.Warnf("Failed to initialize mDNS %s: %v", mDNSName, err) + } + closeMDNSConn := func() { + if mDNSConn != nil { + if mdnsCloseErr := mDNSConn.Close(); mdnsCloseErr != nil { + log.Warnf("Failed to close mDNS: %v", mdnsCloseErr) + } + } + } + startedCtx, startedFn := context.WithCancel(context.Background()) a := &Agent{ @@ -286,23 +289,21 @@ func NewAgent(config *AgentConfig) (*Agent, error) { //nolint:gocognit urls: config.Urls, networkTypes: config.NetworkTypes, onConnected: make(chan struct{}), - buf: packetio.NewBuffer(), + buffer: packetio.NewBuffer(), done: make(chan struct{}), taskLoopDone: make(chan struct{}), startedCh: startedCtx.Done(), startedFn: startedFn, - portMin: config.PortMin, - portMax: config.PortMax, + portmin: config.PortMin, + portmax: config.PortMax, loggerFactory: loggerFactory, log: log, net: config.Net, proxyDialer: config.ProxyDialer, - tcpMux: config.TCPMux, - udpMux: config.UDPMux, - udpMuxSrflx: config.UDPMuxSrflx, mDNSMode: mDNSMode, mDNSName: mDNSName, + mDNSConn: mDNSConn, gatherCandidateCancel: func() {}, @@ -310,65 +311,52 @@ func NewAgent(config *AgentConfig) (*Agent, error) { //nolint:gocognit interfaceFilter: config.InterfaceFilter, - ipFilter: config.IPFilter, - insecureSkipVerify: config.InsecureSkipVerify, - - includeLoopback: config.IncludeLoopback, } + a.tcpMux = config.TCPMux + if a.tcpMux == nil { + a.tcpMux = newInvalidTCPMux() + } + a.udpMux = config.UDPMux + if a.net == nil { - a.net, err = stdnet.NewNet() - if err != nil { - return nil, fmt.Errorf("failed to create network: %w", err) - } - } else if _, isVirtual := a.net.(*vnet.Net); isVirtual { - a.log.Warn("Virtual network is enabled") + a.net = vnet.NewNet(nil) + } else if a.net.IsVirtual() { + a.log.Warn("vnet is enabled") if a.mDNSMode != MulticastDNSModeDisabled { - a.log.Warn("Virtual network does not support mDNS yet") + a.log.Warn("vnet does not support mDNS yet") } } - // Opportunistic mDNS: If we can't open the connection, that's ok: we - // can continue without it. - if a.mDNSConn, a.mDNSMode, err = createMulticastDNS(a.net, mDNSMode, mDNSName, log); err != nil { - log.Warnf("Failed to initialize mDNS %s: %v", mDNSName, err) - } - config.initWithDefaults(a) // Make sure the buffer doesn't grow indefinitely. // NOTE: We actually won't get anywhere close to this limit. // SRTP will constantly read from the endpoint and drop packets if it's full. - a.buf.SetLimitSize(maxBufferSize) + a.buffer.SetLimitSize(maxBufferSize) if a.lite && (len(a.candidateTypes) != 1 || a.candidateTypes[0] != CandidateTypeHost) { - a.closeMulticastConn() + closeMDNSConn() return nil, ErrLiteUsingNonHostCandidates } if config.Urls != nil && len(config.Urls) > 0 && !containsCandidateType(CandidateTypeServerReflexive, a.candidateTypes) && !containsCandidateType(CandidateTypeRelay, a.candidateTypes) { - a.closeMulticastConn() + closeMDNSConn() return nil, ErrUselessUrlsProvided } if err = config.initExtIPMapping(a); err != nil { - a.closeMulticastConn() + closeMDNSConn() return nil, err } go a.taskLoop() - - // CandidatePair and ConnectionState are usually changed at once. - // Blocking one by the other one causes deadlock. - // Hence, we call handlers from independent Goroutines. - go a.candidatePairRoutine() - go a.connectionStateRoutine() - go a.candidateRoutine() + a.startOnConnectionStateChangeRoutine() // Restart is also used to initialize the agent for the first time if err := a.Restart(config.LocalUfrag, config.LocalPwd); err != nil { - a.closeMulticastConn() + closeMDNSConn() _ = a.Close() return nil, err } @@ -376,6 +364,81 @@ func NewAgent(config *AgentConfig) (*Agent, error) { //nolint:gocognit return a, nil } +// OnConnectionStateChange sets a handler that is fired when the connection state changes +func (a *Agent) OnConnectionStateChange(f func(ConnectionState)) error { + a.onConnectionStateChangeHdlr.Store(f) + return nil +} + +// OnSelectedCandidatePairChange sets a handler that is fired when the final candidate +// pair is selected +func (a *Agent) OnSelectedCandidatePairChange(f func(Candidate, Candidate)) error { + a.onSelectedCandidatePairChangeHdlr.Store(f) + return nil +} + +// OnCandidate sets a handler that is fired when new candidates gathered. When +// the gathering process complete the last candidate is nil. +func (a *Agent) OnCandidate(f func(Candidate)) error { + a.onCandidateHdlr.Store(f) + return nil +} + +func (a *Agent) onSelectedCandidatePairChange(p *CandidatePair) { + if h, ok := a.onSelectedCandidatePairChangeHdlr.Load().(func(Candidate, Candidate)); ok { + h(p.Local, p.Remote) + } +} + +func (a *Agent) onCandidate(c Candidate) { + if onCandidateHdlr, ok := a.onCandidateHdlr.Load().(func(Candidate)); ok { + onCandidateHdlr(c) + } +} + +func (a *Agent) onConnectionStateChange(s ConnectionState) { + if hdlr, ok := a.onConnectionStateChangeHdlr.Load().(func(ConnectionState)); ok { + hdlr(s) + } +} + +func (a *Agent) startOnConnectionStateChangeRoutine() { + go func() { + for { + // CandidatePair and ConnectionState are usually changed at once. + // Blocking one by the other one causes deadlock. + p, isOpen := <-a.chanCandidatePair + if !isOpen { + return + } + a.onSelectedCandidatePairChange(p) + } + }() + go func() { + for { + select { + case s, isOpen := <-a.chanState: + if !isOpen { + for c := range a.chanCandidate { + a.onCandidate(c) + } + return + } + go a.onConnectionStateChange(s) + + case c, isOpen := <-a.chanCandidate: + if !isOpen { + for s := range a.chanState { + go a.onConnectionStateChange(s) + } + return + } + a.onCandidate(c) + } + } + }() +} + func (a *Agent) startConnectivityChecks(isControlling bool, remoteUfrag, remotePwd string) error { a.muHaveStarted.Lock() defer a.muHaveStarted.Unlock() @@ -384,7 +447,7 @@ func (a *Agent) startConnectivityChecks(isControlling bool, remoteUfrag, remoteP return ErrMultipleStart default: } - if err := a.SetRemoteCredentials(remoteUfrag, remotePwd); err != nil { //nolint:contextcheck + if err := a.SetRemoteCredentials(remoteUfrag, remotePwd); err != nil { return err } @@ -411,7 +474,7 @@ func (a *Agent) startConnectivityChecks(isControlling bool, remoteUfrag, remoteP agent.updateConnectionState(ConnectionStateChecking) a.requestConnectivityCheck() - go a.connectivityChecks() //nolint:contextcheck + go a.connectivityChecks() }) } @@ -441,12 +504,11 @@ func (a *Agent) connectivityChecks() { a.updateConnectionState(ConnectionStateFailed) return } - default: } a.selector.ContactCandidates() }); err != nil { - a.log.Warnf("Failed to start connectivity checks: %v", err) + a.log.Warnf("taskLoop failed: %v", err) } } @@ -503,26 +565,28 @@ func (a *Agent) updateConnectionState(newState ConnectionState) { } func (a *Agent) setSelectedPair(p *CandidatePair) { + a.log.Tracef("Set selected candidate pair: %s", p) + if p == nil { var nilPair *CandidatePair a.selectedPair.Store(nilPair) - a.log.Tracef("Unset selected candidate pair") return } p.nominated = true a.selectedPair.Store(p) - a.log.Tracef("Set selected candidate pair: %s", p) a.updateConnectionState(ConnectionStateConnected) // Notify when the selected pair changes - a.afterRun(func(ctx context.Context) { - select { - case a.chanCandidatePair <- p: - case <-ctx.Done(): - } - }) + if p != nil { + a.afterRun(func(ctx context.Context) { + select { + case a.chanCandidatePair <- p: + case <-ctx.Done(): + } + }) + } // Signal connected a.onConnectedOnce.Do(func() { close(a.onConnected) }) @@ -532,7 +596,7 @@ func (a *Agent) pingAllCandidates() { a.log.Trace("pinging all candidates") if len(a.checklist) == 0 { - a.log.Warn("Failed to ping without candidate pairs. Connection is not possible yet.") + a.log.Warn("pingAllCandidates called with no candidate pairs. Connection is not possible yet.") } for _, p := range a.checklist { @@ -543,7 +607,7 @@ func (a *Agent) pingAllCandidates() { } if p.bindingRequestCount > a.maxBindingRequests { - a.log.Tracef("max requests reached for pair %s, marking it as failed", p) + a.log.Tracef("max requests reached for pair %s, marking it as failed\n", p) p.state = CandidatePairStateFailed } else { a.selector.PingCandidate(p.Local, p.Remote) @@ -639,7 +703,7 @@ func (a *Agent) checkKeepalive() { if (a.keepaliveInterval != 0) && ((time.Since(selectedPair.Local.LastSent()) > a.keepaliveInterval) || (time.Since(selectedPair.Remote.LastReceived()) > a.keepaliveInterval)) { - // We use binding request instead of indication to support refresh consent schemas + // we use binding request instead of indication to support refresh consent schemas // see https://tools.ietf.org/html/rfc7675 a.selector.PingCandidate(selectedPair.Local, selectedPair.Remote) } @@ -651,10 +715,10 @@ func (a *Agent) AddRemoteCandidate(c Candidate) error { return nil } - // Cannot check for network yet because it might not be applied - // when mDNS hostname is used. + // cannot check for network yet because it might not be applied + // when mDNS hostame is used. if c.TCPType() == TCPTypeActive { - // TCP Candidates with TCP type active will probe server passive ones, so + // TCP Candidates with tcptype active will probe server passive ones, so // no need to do anything with them. a.log.Infof("Ignoring remote candidate with tcpType active: %s", c) return nil @@ -663,7 +727,7 @@ func (a *Agent) AddRemoteCandidate(c Candidate) error { // If we have a mDNS Candidate lets fully resolve it before adding it locally if c.Type() == CandidateTypeHost && strings.HasSuffix(c.Address(), ".local") { if a.mDNSMode == MulticastDNSModeDisabled { - a.log.Warnf("Remote mDNS candidate added, but mDNS is disabled: (%s)", c.Address()) + a.log.Warnf("remote mDNS candidate added, but mDNS is disabled: (%s)", c.Address()) return nil } @@ -697,8 +761,8 @@ func (a *Agent) resolveAndAddMulticastCandidate(c *CandidateHost) { return } - ip, ipOk := parseMulticastAnswerAddr(src) - if !ipOk { + ip, _, _, _ := parseAddr(src) //nolint:dogsled + if ip == nil { a.log.Warnf("Failed to discover mDNS candidate %s: failed to parse IP", c.Address()) return } @@ -754,9 +818,6 @@ func (a *Agent) addCandidate(ctx context.Context, c Candidate, candidateConn net if err := c.close(); err != nil { a.log.Warnf("Failed to close duplicate candidate: %v", err) } - if err := candidateConn.Close(); err != nil { - a.log.Warnf("Failed to close duplicate candidate connection: %v", err) - } return } } @@ -827,15 +888,10 @@ func (a *Agent) GetRemoteUserCredentials() (frag string, pwd string, err error) } func (a *Agent) removeUfragFromMux() { - if a.tcpMux != nil { - a.tcpMux.RemoveConnByUfrag(a.localUfrag) - } + a.tcpMux.RemoveConnByUfrag(a.localUfrag) if a.udpMux != nil { a.udpMux.RemoveConnByUfrag(a.localUfrag) } - if a.udpMuxSrflx != nil { - a.udpMuxSrflx.RemoveConnByUfrag(a.localUfrag) - } } // Close cleans up the Agent @@ -846,9 +902,6 @@ func (a *Agent) Close() error { a.afterRun(func(context.Context) { a.gatherCandidateCancel() - if a.gatherCandidateDone != nil { - <-a.gatherCandidateDone - } }) a.err.Store(ErrClosed) @@ -885,7 +938,7 @@ func (a *Agent) deleteAllCandidates() { func (a *Agent) findRemoteCandidate(networkType NetworkType, addr net.Addr) Candidate { ip, port, _, ok := parseAddr(addr) if !ok { - a.log.Warnf("Failed to parse address: %s", addr) + a.log.Warnf("Error parsing addr: %s", addr) return nil } @@ -899,7 +952,7 @@ func (a *Agent) findRemoteCandidate(networkType NetworkType, addr net.Addr) Cand } func (a *Agent) sendBindingRequest(m *stun.Message, local, remote Candidate) { - a.log.Tracef("ping STUN from %s to %s", local.String(), remote.String()) + a.log.Tracef("ping STUN from %s to %s\n", local.String(), remote.String()) a.invalidatePendingBindingRequests(time.Now()) a.pendingBindingRequests = append(a.pendingBindingRequests, bindingRequest{ @@ -917,7 +970,7 @@ func (a *Agent) sendBindingSuccess(m *stun.Message, local, remote Candidate) { ip, port, _, ok := parseAddr(base.addr()) if !ok { - a.log.Warnf("Failed to parse address: %s", base.addr()) + a.log.Warnf("Error parsing addr: %s", base.addr()) return } @@ -935,11 +988,12 @@ func (a *Agent) sendBindingSuccess(m *stun.Message, local, remote Candidate) { } } -// Removes pending binding requests that are over maxBindingRequestTimeout old -// -// Let HTO be the transaction timeout, which SHOULD be 2*RTT if -// RTT is known or 500 ms otherwise. -// https://tools.ietf.org/html/rfc8445#appendix-B.1 +/* Removes pending binding requests that are over maxBindingRequestTimeout old + + Let HTO be the transaction timeout, which SHOULD be 2*RTT if + RTT is known or 500 ms otherwise. + https://tools.ietf.org/html/rfc8445#appendix-B.1 +*/ func (a *Agent) invalidatePendingBindingRequests(filterTime time.Time) { initialSize := len(a.pendingBindingRequests) @@ -987,38 +1041,38 @@ func (a *Agent) handleInbound(m *stun.Message, local Candidate, remote net.Addr) if a.isControlling { if m.Contains(stun.AttrICEControlling) { - a.log.Debug("Inbound STUN message: isControlling && a.isControlling == true") + a.log.Debug("inbound isControlling && a.isControlling == true") return } else if m.Contains(stun.AttrUseCandidate) { - a.log.Debug("Inbound STUN message: useCandidate && a.isControlling == true") + a.log.Debug("useCandidate && a.isControlling == true") return } } else { if m.Contains(stun.AttrICEControlled) { - a.log.Debug("Inbound STUN message: isControlled && a.isControlling == false") + a.log.Debug("inbound isControlled && a.isControlling == false") return } } remoteCandidate := a.findRemoteCandidate(local.NetworkType(), remote) if m.Type.Class == stun.ClassSuccessResponse { - if err = stun.MessageIntegrity([]byte(a.remotePwd)).Check(m); err != nil { - a.log.Warnf("Discard message from (%s), %v", remote, err) + if err = assertInboundMessageIntegrity(m, []byte(a.remotePwd)); err != nil { + a.log.Warnf("discard message from (%s), %v", remote, err) return } if remoteCandidate == nil { - a.log.Warnf("Discard success message from (%s), no such remote", remote) + a.log.Warnf("discard success message from (%s), no such remote", remote) return } a.selector.HandleSuccessResponse(m, local, remoteCandidate, remote) } else if m.Type.Class == stun.ClassRequest { - if err = stunx.AssertUsername(m, a.localUfrag+":"+a.remoteUfrag); err != nil { - a.log.Warnf("Discard message from (%s), %v", remote, err) + if err = assertInboundUsername(m, a.localUfrag+":"+a.remoteUfrag); err != nil { + a.log.Warnf("discard message from (%s), %v", remote, err) return - } else if err = stun.MessageIntegrity([]byte(a.localPwd)).Check(m); err != nil { - a.log.Warnf("Discard message from (%s), %v", remote, err) + } else if err = assertInboundMessageIntegrity(m, []byte(a.localPwd)); err != nil { + a.log.Warnf("discard message from (%s), %v", remote, err) return } @@ -1045,7 +1099,7 @@ func (a *Agent) handleInbound(m *stun.Message, local Candidate, remote net.Addr) } remoteCandidate = prflxCandidate - a.log.Debugf("Adding a new peer-reflexive candidate: %s ", remote) + a.log.Debugf("adding a new peer-reflexive candidate: %s ", remote) a.addRemoteCandidate(remoteCandidate) } @@ -1061,25 +1115,26 @@ func (a *Agent) handleInbound(m *stun.Message, local Candidate, remote net.Addr) // validateNonSTUNTraffic processes non STUN traffic from a remote candidate, // and returns true if it is an actual remote candidate -func (a *Agent) validateNonSTUNTraffic(local Candidate, remote net.Addr) (Candidate, bool) { - var remoteCandidate Candidate +func (a *Agent) validateNonSTUNTraffic(local Candidate, remote net.Addr) bool { + var isValidCandidate uint64 if err := a.run(local.context(), func(ctx context.Context, agent *Agent) { - remoteCandidate = a.findRemoteCandidate(local.NetworkType(), remote) + remoteCandidate := a.findRemoteCandidate(local.NetworkType(), remote) if remoteCandidate != nil { remoteCandidate.seen(false) + atomic.AddUint64(&isValidCandidate, 1) } }); err != nil { - a.log.Warnf("Failed to validate remote candidate: %v", err) + a.log.Warnf("failed to validate remote candidate: %v", err) } - return remoteCandidate, remoteCandidate != nil + return atomic.LoadUint64(&isValidCandidate) == 1 } // GetSelectedCandidatePair returns the selected pair or nil if there is none func (a *Agent) GetSelectedCandidatePair() (*CandidatePair, error) { selectedPair := a.getSelectedPair() if selectedPair == nil { - return nil, nil //nolint:nilnil + return nil, nil } local, err := selectedPair.Local.copy() @@ -1096,17 +1151,18 @@ func (a *Agent) GetSelectedCandidatePair() (*CandidatePair, error) { } func (a *Agent) getSelectedPair() *CandidatePair { - if selectedPair, ok := a.selectedPair.Load().(*CandidatePair); ok { - return selectedPair + selectedPair := a.selectedPair.Load() + if selectedPair == nil { + return nil } - return nil + return selectedPair.(*CandidatePair) } func (a *Agent) closeMulticastConn() { if a.mDNSConn != nil { if err := a.mDNSConn.Close(); err != nil { - a.log.Warnf("Failed to close mDNS Conn: %v", err) + a.log.Warnf("failed to close mDNS Conn: %v", err) } } } @@ -1129,10 +1185,8 @@ func (a *Agent) SetRemoteCredentials(remoteUfrag, remotePwd string) error { // Restart restarts the ICE Agent with the provided ufrag/pwd // If no ufrag/pwd is provided the Agent will generate one itself // -// If there is a gatherer routine currently running, Restart will -// cancel it. -// After a Restart, the user must then call GatherCandidates explicitly -// to start generating new ones. +// Restart must only be called when GatheringState is GatheringStateComplete +// a user must then call GatherCandidates explicitly to start generating new ones func (a *Agent) Restart(ufrag, pwd string) error { if ufrag == "" { var err error @@ -1159,7 +1213,8 @@ func (a *Agent) Restart(ufrag, pwd string) error { var err error if runErr := a.run(a.context(), func(ctx context.Context, agent *Agent) { if agent.gatheringState == GatheringStateGathering { - agent.gatherCandidateCancel() + err = ErrRestartWhenGathering + return } // Clear all agent needed to take back to fresh state diff --git a/vendor/github.com/pion/ice/v2/agent_config.go b/vendor/github.com/pion/ice/v2/agent_config.go index f5897cd4a..e577af101 100644 --- a/vendor/github.com/pion/ice/v2/agent_config.go +++ b/vendor/github.com/pion/ice/v2/agent_config.go @@ -1,15 +1,10 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( - "net" "time" "github.com/pion/logging" - "github.com/pion/stun" - "github.com/pion/transport/v2" + "github.com/pion/transport/vnet" "golang.org/x/net/proxy" ) @@ -26,25 +21,25 @@ const ( // defaultFailedTimeout is the default time till an Agent transitions to failed after disconnected defaultFailedTimeout = 25 * time.Second - // defaultHostAcceptanceMinWait is the wait time before nominating a host candidate + // wait time before nominating a host candidate defaultHostAcceptanceMinWait = 0 - // defaultSrflxAcceptanceMinWait is the wait time before nominating a srflx candidate + // wait time before nominating a srflx candidate defaultSrflxAcceptanceMinWait = 500 * time.Millisecond - // defaultPrflxAcceptanceMinWait is the wait time before nominating a prflx candidate + // wait time before nominating a prflx candidate defaultPrflxAcceptanceMinWait = 1000 * time.Millisecond - // defaultRelayAcceptanceMinWait is the wait time before nominating a relay candidate + // wait time before nominating a relay candidate defaultRelayAcceptanceMinWait = 2000 * time.Millisecond - // defaultMaxBindingRequests is the maximum number of binding requests before considering a pair failed + // max binding request before considering a pair failed defaultMaxBindingRequests = 7 - // maxBufferSize is the number of bytes that can be buffered before we start to error + // the number of bytes that can be buffered before we start to error maxBufferSize = 1000 * 1000 // 1MB - // maxBindingRequestTimeout is the wait time before binding requests can be deleted + // wait time before binding requests can be deleted maxBindingRequestTimeout = 4000 * time.Millisecond ) @@ -55,7 +50,7 @@ func defaultCandidateTypes() []CandidateType { // AgentConfig collects the arguments to ice.Agent construction into // a single structure, for future-proofness of the interface type AgentConfig struct { - Urls []*stun.URI + Urls []*URL // PortMin and PortMax are optional. Leave them 0 for the default UDP port allocation strategy. PortMin uint16 @@ -113,14 +108,14 @@ type AgentConfig struct { // NAT1To1IPCandidateType is used along with NAT1To1IPs to specify which candidate type // the 1:1 NAT IP addresses should be mapped to. // If unspecified or CandidateTypeHost, NAT1To1IPs are used to replace host candidate IPs. - // If CandidateTypeServerReflexive, it will insert a srflx candidate (as if it was derived + // If CandidateTypeServerReflexive, it will insert a srflx candidate (as if it was dervied // from a STUN server) with its port number being the one for the actual host candidate. // Other values will result in an error. NAT1To1IPCandidateType CandidateType // NAT1To1IPs contains a list of public IP addresses that are to be used as a host // candidate or srflx candidate. This is used typically for servers that are behind - // 1:1 D-NAT (e.g. AWS EC2 instances) and to eliminate the need of server reflexive + // 1:1 D-NAT (e.g. AWS EC2 instances) and to eliminate the need of server reflexisive // candidate gathering. NAT1To1IPs []string @@ -134,17 +129,13 @@ type AgentConfig struct { RelayAcceptanceMinWait *time.Duration // Net is the our abstracted network interface for internal development purpose only - // (see https://github.com/pion/transport) - Net transport.Net + // (see github.com/pion/transport/vnet) + Net *vnet.Net - // InterfaceFilter is a function that you can use in order to whitelist or blacklist + // InterfaceFilter is a function that you can use in order to whitelist or blacklist // the interfaces which are used to gather ICE candidates. InterfaceFilter func(string) bool - // IPFilter is a function that you can use in order to whitelist or blacklist - // the ips which are used to gather ICE candidates. - IPFilter func(net.IP) bool - // InsecureSkipVerify controls if self-signed certificates are accepted when connecting // to TURN servers via TLS or DTLS InsecureSkipVerify bool @@ -159,21 +150,9 @@ type AgentConfig struct { // defer to UDPMux for incoming connections UDPMux UDPMux - // UDPMuxSrflx is used for multiplexing multiple incoming UDP connections of server reflexive candidates - // on a single port when this is set, the agent ignores PortMin and PortMax configurations and will - // defer to UDPMuxSrflx for incoming connections - // It embeds UDPMux to do the actual connection multiplexing - UDPMuxSrflx UniversalUDPMux - // Proxy Dialer is a dialer that should be implemented by the user based on golang.org/x/net/proxy // dial interface in order to support corporate proxies ProxyDialer proxy.Dialer - - // Deprecated: AcceptAggressiveNomination always enabled. - AcceptAggressiveNomination bool - - // Include loopback addresses in the candidate list. - IncludeLoopback bool } // initWithDefaults populates an agent and falls back to defaults if fields are unset @@ -246,7 +225,7 @@ func (config *AgentConfig) initExtIPMapping(a *Agent) error { return err } if a.extIPMapper == nil { - return nil // This may happen when config.NAT1To1IPs is an empty array + return nil // this may happen when config.NAT1To1IPs is an empty array } if a.extIPMapper.candidateType == CandidateTypeHost { if a.mDNSMode == MulticastDNSModeQueryAndGather { diff --git a/vendor/github.com/pion/ice/v2/agent_handlers.go b/vendor/github.com/pion/ice/v2/agent_handlers.go deleted file mode 100644 index c5a5ec03b..000000000 --- a/vendor/github.com/pion/ice/v2/agent_handlers.go +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package ice - -// OnConnectionStateChange sets a handler that is fired when the connection state changes -func (a *Agent) OnConnectionStateChange(f func(ConnectionState)) error { - a.onConnectionStateChangeHdlr.Store(f) - return nil -} - -// OnSelectedCandidatePairChange sets a handler that is fired when the final candidate -// pair is selected -func (a *Agent) OnSelectedCandidatePairChange(f func(Candidate, Candidate)) error { - a.onSelectedCandidatePairChangeHdlr.Store(f) - return nil -} - -// OnCandidate sets a handler that is fired when new candidates gathered. When -// the gathering process complete the last candidate is nil. -func (a *Agent) OnCandidate(f func(Candidate)) error { - a.onCandidateHdlr.Store(f) - return nil -} - -func (a *Agent) onSelectedCandidatePairChange(p *CandidatePair) { - if h, ok := a.onSelectedCandidatePairChangeHdlr.Load().(func(Candidate, Candidate)); ok { - h(p.Local, p.Remote) - } -} - -func (a *Agent) onCandidate(c Candidate) { - if onCandidateHdlr, ok := a.onCandidateHdlr.Load().(func(Candidate)); ok { - onCandidateHdlr(c) - } -} - -func (a *Agent) onConnectionStateChange(s ConnectionState) { - if hdlr, ok := a.onConnectionStateChangeHdlr.Load().(func(ConnectionState)); ok { - hdlr(s) - } -} - -func (a *Agent) candidatePairRoutine() { - for p := range a.chanCandidatePair { - a.onSelectedCandidatePairChange(p) - } -} - -func (a *Agent) connectionStateRoutine() { - for s := range a.chanState { - go a.onConnectionStateChange(s) - } -} - -func (a *Agent) candidateRoutine() { - for c := range a.chanCandidate { - a.onCandidate(c) - } -} diff --git a/vendor/github.com/pion/ice/v2/agent_stats.go b/vendor/github.com/pion/ice/v2/agent_stats.go index b9ad7187e..b249560b6 100644 --- a/vendor/github.com/pion/ice/v2/agent_stats.go +++ b/vendor/github.com/pion/ice/v2/agent_stats.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( @@ -48,7 +45,7 @@ func (a *Agent) GetCandidatePairsStats() []CandidatePairStats { res = result }) if err != nil { - a.log.Errorf("Failed to get candidate pairs stats: %v", err) + a.log.Errorf("error getting candidate pairs stats %v", err) return []CandidatePairStats{} } return res @@ -63,9 +60,7 @@ func (a *Agent) GetLocalCandidatesStats() []CandidateStats { for _, c := range localCandidates { relayProtocol := "" if c.Type() == CandidateTypeRelay { - if cRelay, ok := c.(*CandidateRelay); ok { - relayProtocol = cRelay.RelayProtocol() - } + relayProtocol = c.(*CandidateRelay).RelayProtocol() } stat := CandidateStats{ Timestamp: time.Now(), @@ -85,7 +80,7 @@ func (a *Agent) GetLocalCandidatesStats() []CandidateStats { res = result }) if err != nil { - a.log.Errorf("Failed to get candidate pair stats: %v", err) + a.log.Errorf("error getting candidate pairs stats %v", err) return []CandidateStats{} } return res @@ -96,8 +91,8 @@ func (a *Agent) GetRemoteCandidatesStats() []CandidateStats { var res []CandidateStats err := a.run(a.context(), func(ctx context.Context, agent *Agent) { result := make([]CandidateStats, 0, len(agent.remoteCandidates)) - for networkType, remoteCandidates := range agent.remoteCandidates { - for _, c := range remoteCandidates { + for networkType, localCandidates := range agent.remoteCandidates { + for _, c := range localCandidates { stat := CandidateStats{ Timestamp: time.Now(), ID: c.ID(), @@ -115,7 +110,7 @@ func (a *Agent) GetRemoteCandidatesStats() []CandidateStats { res = result }) if err != nil { - a.log.Errorf("Failed to get candidate pair stats: %v", err) + a.log.Errorf("error getting candidate pairs stats %v", err) return []CandidateStats{} } return res diff --git a/vendor/github.com/pion/ice/v2/candidate.go b/vendor/github.com/pion/ice/v2/candidate.go index 92a007688..c3049dd00 100644 --- a/vendor/github.com/pion/ice/v2/candidate.go +++ b/vendor/github.com/pion/ice/v2/candidate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( diff --git a/vendor/github.com/pion/ice/v2/candidate_base.go b/vendor/github.com/pion/ice/v2/candidate_base.go index 8e551d8f2..7703e7106 100644 --- a/vendor/github.com/pion/ice/v2/candidate_base.go +++ b/vendor/github.com/pion/ice/v2/candidate_base.go @@ -1,20 +1,16 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( "context" - "errors" "fmt" "hash/crc32" - "io" "net" "strconv" "strings" "sync/atomic" "time" + "github.com/pion/logging" "github.com/pion/stun" ) @@ -41,8 +37,6 @@ type candidateBase struct { foundationOverride string priorityOverride uint32 - - remoteCandidateCaches map[AddrPort]Candidate } // Done implements context.Context @@ -66,7 +60,7 @@ func (c *candidateBase) Deadline() (deadline time.Time, ok bool) { } // Value implements context.Context -func (c *candidateBase) Value(interface{}) interface{} { +func (c *candidateBase) Value(key interface{}) interface{} { return nil } @@ -212,9 +206,9 @@ func (c *candidateBase) start(a *Agent, conn net.PacketConn, initializedCh <-cha } func (c *candidateBase) recvLoop(initializedCh <-chan struct{}) { - a := c.agent() - - defer close(c.closedCh) + defer func() { + close(c.closedCh) + }() select { case <-initializedCh: @@ -222,73 +216,47 @@ func (c *candidateBase) recvLoop(initializedCh <-chan struct{}) { return } - buf := make([]byte, receiveMTU) + log := c.agent().log + buffer := make([]byte, receiveMTU) for { - n, srcAddr, err := c.conn.ReadFrom(buf) + n, srcAddr, err := c.conn.ReadFrom(buffer) if err != nil { - if !(errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed)) { - a.log.Warnf("Failed to read from candidate %s: %v", c, err) - } return } - c.handleInboundPacket(buf[:n], srcAddr) + handleInboundCandidateMsg(c, c, buffer[:n], srcAddr, log) } } -func (c *candidateBase) validateSTUNTrafficCache(addr net.Addr) bool { - if candidate, ok := c.remoteCandidateCaches[toAddrPort(addr)]; ok { - candidate.seen(false) - return true - } - return false -} - -func (c *candidateBase) addRemoteCandidateCache(candidate Candidate, srcAddr net.Addr) { - if c.validateSTUNTrafficCache(srcAddr) { - return - } - c.remoteCandidateCaches[toAddrPort(srcAddr)] = candidate -} - -func (c *candidateBase) handleInboundPacket(buf []byte, srcAddr net.Addr) { - a := c.agent() - - if stun.IsMessage(buf) { +func handleInboundCandidateMsg(ctx context.Context, c Candidate, buffer []byte, srcAddr net.Addr, log logging.LeveledLogger) { + if stun.IsMessage(buffer) { m := &stun.Message{ - Raw: make([]byte, len(buf)), + Raw: make([]byte, len(buffer)), } - // Explicitly copy raw buffer so Message can own the memory. - copy(m.Raw, buf) - + copy(m.Raw, buffer) if err := m.Decode(); err != nil { - a.log.Warnf("Failed to handle decode ICE from %s to %s: %v", c.addr(), srcAddr, err) + log.Warnf("Failed to handle decode ICE from %s to %s: %v", c.addr(), srcAddr, err) return } - - if err := a.run(c, func(ctx context.Context, a *Agent) { - a.handleInbound(m, c, srcAddr) - }); err != nil { - a.log.Warnf("Failed to handle message: %v", err) + err := c.agent().run(ctx, func(ctx context.Context, agent *Agent) { + agent.handleInbound(m, c, srcAddr) + }) + if err != nil { + log.Warnf("Failed to handle message: %v", err) } return } - if !c.validateSTUNTrafficCache(srcAddr) { - remoteCandidate, valid := a.validateNonSTUNTraffic(c, srcAddr) //nolint:contextcheck - if !valid { - a.log.Warnf("Discarded message from %s, not a valid remote candidate", c.addr()) - return - } - c.addRemoteCandidateCache(remoteCandidate, srcAddr) + if !c.agent().validateNonSTUNTraffic(c, srcAddr) { + log.Warnf("Discarded message from %s, not a valid remote candidate", c.addr()) + return } - // Note: This will return packetio.ErrFull if the buffer ever manages to fill up. - if _, err := a.buf.Write(buf); err != nil { - a.log.Warnf("Failed to write packet: %s", err) - return + // NOTE This will return packetio.ErrFull if the buffer ever manages to fill up. + if _, err := c.agent().buffer.Write(buffer); err != nil { + log.Warnf("failed to write packet") } } @@ -332,11 +300,7 @@ func (c *candidateBase) close() error { func (c *candidateBase) writeTo(raw []byte, dst Candidate) (int, error) { n, err := c.conn.WriteTo(raw, dst.addr()) if err != nil { - // If the connection is closed, we should return the error - if errors.Is(err, io.ErrClosedPipe) { - return n, err - } - c.agent().log.Infof("%s: %v", errSendPacket, err) + c.agent().log.Warnf("%s: %v", errSendPacket, err) return n, nil } c.seen(true) @@ -372,16 +336,17 @@ func (c *candidateBase) Equal(other Candidate) bool { // String makes the candidateBase printable func (c *candidateBase) String() string { - return fmt.Sprintf("%s %s %s%s", c.NetworkType(), c.Type(), net.JoinHostPort(c.Address(), strconv.Itoa(c.Port())), c.relatedAddress) + return fmt.Sprintf("%s %s %s:%d%s", c.NetworkType(), c.Type(), c.Address(), c.Port(), c.relatedAddress) } // LastReceived returns a time.Time indicating the last time // this candidate was received func (c *candidateBase) LastReceived() time.Time { - if lastReceived, ok := c.lastReceived.Load().(time.Time); ok { - return lastReceived + lastReceived := c.lastReceived.Load() + if lastReceived == nil { + return time.Time{} } - return time.Time{} + return lastReceived.(time.Time) } func (c *candidateBase) setLastReceived(t time.Time) { @@ -391,10 +356,11 @@ func (c *candidateBase) setLastReceived(t time.Time) { // LastSent returns a time.Time indicating the last time // this candidate was sent func (c *candidateBase) LastSent() time.Time { - if lastSent, ok := c.lastSent.Load().(time.Time); ok { - return lastSent + lastSent := c.lastSent.Load() + if lastSent == nil { + return time.Time{} } - return time.Time{} + return lastSent.(time.Time) } func (c *candidateBase) setLastSent(t time.Time) { @@ -472,7 +438,7 @@ func UnmarshalCandidate(raw string) (Candidate, error) { // Component rawComponent, err := strconv.ParseUint(split[1], 10, 16) if err != nil { - return nil, fmt.Errorf("%w: %v", errParseComponent, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errParseComponent, err) } component := uint16(rawComponent) @@ -482,7 +448,7 @@ func UnmarshalCandidate(raw string) (Candidate, error) { // Priority priorityRaw, err := strconv.ParseUint(split[3], 10, 32) if err != nil { - return nil, fmt.Errorf("%w: %v", errParsePriority, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errParsePriority, err) } priority := uint32(priorityRaw) @@ -492,7 +458,7 @@ func UnmarshalCandidate(raw string) (Candidate, error) { // Port rawPort, err := strconv.ParseUint(split[5], 10, 16) if err != nil { - return nil, fmt.Errorf("%w: %v", errParsePort, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errParsePort, err) } port := int(rawPort) typ := split[7] @@ -515,12 +481,12 @@ func UnmarshalCandidate(raw string) (Candidate, error) { // RelatedPort rawRelatedPort, parseErr := strconv.ParseUint(split[3], 10, 16) if parseErr != nil { - return nil, fmt.Errorf("%w: %v", errParsePort, parseErr) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errParsePort, parseErr) } relatedPort = int(rawRelatedPort) } else if split[0] == "tcptype" { if len(split) < 2 { - return nil, fmt.Errorf("%w: incorrect length", errParseTCPType) + return nil, fmt.Errorf("%w: incorrect length", errParseTypType) } tcpType = NewTCPType(split[1]) diff --git a/vendor/github.com/pion/ice/v2/candidate_host.go b/vendor/github.com/pion/ice/v2/candidate_host.go index 5d207dd91..b03dbdb51 100644 --- a/vendor/github.com/pion/ice/v2/candidate_host.go +++ b/vendor/github.com/pion/ice/v2/candidate_host.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( @@ -37,15 +34,14 @@ func NewCandidateHost(config *CandidateHostConfig) (*CandidateHost, error) { c := &CandidateHost{ candidateBase: candidateBase{ - id: candidateID, - address: config.Address, - candidateType: CandidateTypeHost, - component: config.Component, - port: config.Port, - tcpType: config.TCPType, - foundationOverride: config.Foundation, - priorityOverride: config.Priority, - remoteCandidateCaches: map[AddrPort]Candidate{}, + id: candidateID, + address: config.Address, + candidateType: CandidateTypeHost, + component: config.Component, + port: config.Port, + tcpType: config.TCPType, + foundationOverride: config.Foundation, + priorityOverride: config.Priority, }, network: config.Network, } diff --git a/vendor/github.com/pion/ice/v2/candidate_peer_reflexive.go b/vendor/github.com/pion/ice/v2/candidate_peer_reflexive.go index f019ec698..0b330d1c9 100644 --- a/vendor/github.com/pion/ice/v2/candidate_peer_reflexive.go +++ b/vendor/github.com/pion/ice/v2/candidate_peer_reflexive.go @@ -1,8 +1,4 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package ice ... -// //nolint:dupl package ice @@ -59,7 +55,6 @@ func NewCandidatePeerReflexive(config *CandidatePeerReflexiveConfig) (*Candidate Address: config.RelAddr, Port: config.RelPort, }, - remoteCandidateCaches: map[AddrPort]Candidate{}, }, }, nil } diff --git a/vendor/github.com/pion/ice/v2/candidate_relay.go b/vendor/github.com/pion/ice/v2/candidate_relay.go index 449d077a6..3d0be3168 100644 --- a/vendor/github.com/pion/ice/v2/candidate_relay.go +++ b/vendor/github.com/pion/ice/v2/candidate_relay.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( @@ -63,7 +60,6 @@ func NewCandidateRelay(config *CandidateRelayConfig) (*CandidateRelay, error) { Address: config.RelAddr, Port: config.RelPort, }, - remoteCandidateCaches: map[AddrPort]Candidate{}, }, relayProtocol: config.RelayProtocol, onClose: config.OnClose, @@ -83,16 +79,3 @@ func (c *CandidateRelay) close() error { } return err } - -func (c *CandidateRelay) copy() (Candidate, error) { - cc, err := c.candidateBase.copy() - if err != nil { - return nil, err - } - - if ccr, ok := cc.(*CandidateRelay); ok { - ccr.relayProtocol = c.relayProtocol - } - - return cc, nil -} diff --git a/vendor/github.com/pion/ice/v2/candidate_server_reflexive.go b/vendor/github.com/pion/ice/v2/candidate_server_reflexive.go index 3a8ac0ff7..125a53782 100644 --- a/vendor/github.com/pion/ice/v2/candidate_server_reflexive.go +++ b/vendor/github.com/pion/ice/v2/candidate_server_reflexive.go @@ -1,6 +1,5 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - +// Package ice ... +//nolint:dupl package ice import "net" @@ -55,7 +54,6 @@ func NewCandidateServerReflexive(config *CandidateServerReflexiveConfig) (*Candi Address: config.RelAddr, Port: config.RelPort, }, - remoteCandidateCaches: map[AddrPort]Candidate{}, }, }, nil } diff --git a/vendor/github.com/pion/ice/v2/candidatepair.go b/vendor/github.com/pion/ice/v2/candidatepair.go index f33be539c..79cab1a9f 100644 --- a/vendor/github.com/pion/ice/v2/candidatepair.go +++ b/vendor/github.com/pion/ice/v2/candidatepair.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( @@ -21,13 +18,12 @@ func newCandidatePair(local, remote Candidate, controlling bool) *CandidatePair // CandidatePair is a combination of a // local and remote candidate type CandidatePair struct { - iceRoleControlling bool - Remote Candidate - Local Candidate - bindingRequestCount uint16 - state CandidatePairState - nominated bool - nominateOnBindingSuccess bool + iceRoleControlling bool + Remote Candidate + Local Candidate + bindingRequestCount uint16 + state CandidatePairState + nominated bool } func (p *CandidatePair) String() string { diff --git a/vendor/github.com/pion/ice/v2/candidatepair_state.go b/vendor/github.com/pion/ice/v2/candidatepair_state.go index 1a1e827b0..28c7187eb 100644 --- a/vendor/github.com/pion/ice/v2/candidatepair_state.go +++ b/vendor/github.com/pion/ice/v2/candidatepair_state.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice // CandidatePairState represent the ICE candidate pair state diff --git a/vendor/github.com/pion/ice/v2/candidaterelatedaddress.go b/vendor/github.com/pion/ice/v2/candidaterelatedaddress.go index e87c70514..18cf31831 100644 --- a/vendor/github.com/pion/ice/v2/candidaterelatedaddress.go +++ b/vendor/github.com/pion/ice/v2/candidaterelatedaddress.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import "fmt" diff --git a/vendor/github.com/pion/ice/v2/candidatetype.go b/vendor/github.com/pion/ice/v2/candidatetype.go index 3972934cb..376c4089f 100644 --- a/vendor/github.com/pion/ice/v2/candidatetype.go +++ b/vendor/github.com/pion/ice/v2/candidatetype.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice // CandidateType represents the type of candidate diff --git a/vendor/github.com/pion/ice/v2/codecov.yml b/vendor/github.com/pion/ice/v2/codecov.yml index 263e4d45c..085200a48 100644 --- a/vendor/github.com/pion/ice/v2/codecov.yml +++ b/vendor/github.com/pion/ice/v2/codecov.yml @@ -3,8 +3,6 @@ # # It is automatically copied from https://github.com/pion/.goassets repository. # -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT coverage: status: diff --git a/vendor/github.com/pion/ice/v2/context.go b/vendor/github.com/pion/ice/v2/context.go index 36454450c..627d81ef4 100644 --- a/vendor/github.com/pion/ice/v2/context.go +++ b/vendor/github.com/pion/ice/v2/context.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( @@ -35,6 +32,6 @@ func (a agentContext) Deadline() (deadline time.Time, ok bool) { } // Value implements context.Context -func (a agentContext) Value(interface{}) interface{} { +func (a agentContext) Value(key interface{}) interface{} { return nil } diff --git a/vendor/github.com/pion/ice/v2/errors.go b/vendor/github.com/pion/ice/v2/errors.go index e05cce898..8ca9c2cde 100644 --- a/vendor/github.com/pion/ice/v2/errors.go +++ b/vendor/github.com/pion/ice/v2/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import "errors" @@ -13,7 +10,7 @@ var ( ErrSchemeType = errors.New("unknown scheme type") // ErrSTUNQuery indicates query arguments are provided in a STUN URL. - ErrSTUNQuery = errors.New("queries not supported in STUN address") + ErrSTUNQuery = errors.New("queries not supported in stun address") // ErrInvalidQuery indicates an malformed query is provided. ErrInvalidQuery = errors.New("invalid query") @@ -28,7 +25,7 @@ var ( // Have to be at least 24 bits long ErrLocalUfragInsufficientBits = errors.New("local username fragment is less than 24 bits long") - // ErrLocalPwdInsufficientBits indicates local password insufficient bits are provided. + // ErrLocalPwdInsufficientBits indicates local passoword insufficient bits are provided. // Have to be at least 128 bits long ErrLocalPwdInsufficientBits = errors.New("local password is less than 128 bits long") @@ -100,9 +97,15 @@ var ( // ErrInvalidMulticastDNSHostName indicates an invalid MulticastDNSHostName ErrInvalidMulticastDNSHostName = errors.New("invalid mDNS HostName, must end with .local and can only contain a single '.'") + // ErrRestartWhenGathering indicates Restart was called when Agent is in GatheringStateGathering + ErrRestartWhenGathering = errors.New("ICE Agent can not be restarted when gathering") + // ErrRunCanceled indicates a run operation was canceled by its individual done ErrRunCanceled = errors.New("run was canceled by done") + // ErrTCPMuxNotInitialized indicates TCPMux is not initialized and that invalidTCPMux is used. + ErrTCPMuxNotInitialized = errors.New("TCPMux is not initialized") + // ErrTCPRemoteAddrAlreadyExists indicates we already have the connection with same remote addr. ErrTCPRemoteAddrAlreadyExists = errors.New("conn with same remote addr already exists") @@ -118,25 +121,18 @@ var ( errParsePriority = errors.New("could not parse priority") errParsePort = errors.New("could not parse port") errParseRelatedAddr = errors.New("could not parse related addresses") - errParseTCPType = errors.New("could not parse TCP type") + errParseTypType = errors.New("could not parse typtype") errGetXorMappedAddrResponse = errors.New("failed to get XOR-MAPPED-ADDRESS response") errConnectionAddrAlreadyExist = errors.New("connection with same remote address already exists") errReadingStreamingPacket = errors.New("error reading streaming packet") errWriting = errors.New("error writing to") errClosingConnection = errors.New("error closing connection") + errMissingProtocolScheme = errors.New("missing protocol scheme") + errTooManyColonsAddr = errors.New("too many colons in address") errRead = errors.New("unexpected error trying to read") errUnknownRole = errors.New("unknown role") + errMismatchUsername = errors.New("username mismatch") errICEWriteSTUNMessage = errors.New("the ICE conn can't write STUN messages") errUDPMuxDisabled = errors.New("UDPMux is not enabled") - errNoXorAddrMapping = errors.New("no address mapping") - errSendSTUNPacket = errors.New("failed to send STUN packet") - errXORMappedAddrTimeout = errors.New("timeout while waiting for XORMappedAddr") - errNotImplemented = errors.New("not implemented yet") - errNoUDPMuxAvailable = errors.New("no UDP mux is available") - errNoTCPMuxAvailable = errors.New("no TCP mux is available") - errInvalidAddress = errors.New("invalid address") - - // UDPMuxDefault should not listen on unspecified address, but to keep backward compatibility, don't return error now. - // will be used in the future. - // errListenUnspecified = errors.New("can't listen on unspecified address") + errCandidateIPNotFound = errors.New("could not determine local IP for Mux candidate") ) diff --git a/vendor/github.com/pion/ice/v2/external_ip_mapper.go b/vendor/github.com/pion/ice/v2/external_ip_mapper.go index 3d542fb1a..5310cc0ae 100644 --- a/vendor/github.com/pion/ice/v2/external_ip_mapper.go +++ b/vendor/github.com/pion/ice/v2/external_ip_mapper.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( @@ -18,9 +15,8 @@ func validateIPString(ipStr string) (net.IP, bool, error) { // ipMapping holds the mapping of local and external IP address for a particular IP family type ipMapping struct { - ipSole net.IP // When non-nil, this is the sole external IP for one local IP assumed - ipMap map[string]net.IP // Local-to-external IP mapping (k: local, v: external) - valid bool // If not set any external IP, valid is false + ipSole net.IP // when non-nil, this is the sole external IP for one local IP assumed + ipMap map[string]net.IP // local-to-external IP mapping (k: local, v: external) } func (m *ipMapping) setSoleIP(ip net.IP) error { @@ -29,7 +25,6 @@ func (m *ipMapping) setSoleIP(ip net.IP) error { } m.ipSole = ip - m.valid = true return nil } @@ -41,22 +36,17 @@ func (m *ipMapping) addIPMapping(locIP, extIP net.IP) error { locIPStr := locIP.String() - // Check if dup of local IP + // check if dup of local IP if _, ok := m.ipMap[locIPStr]; ok { return ErrInvalidNAT1To1IPMapping } m.ipMap[locIPStr] = extIP - m.valid = true return nil } func (m *ipMapping) findExternalIP(locIP net.IP) (net.IP, error) { - if !m.valid { - return locIP, nil - } - if m.ipSole != nil { return m.ipSole, nil } @@ -77,10 +67,10 @@ type externalIPMapper struct { func newExternalIPMapper(candidateType CandidateType, ips []string) (*externalIPMapper, error) { //nolint:gocognit if len(ips) == 0 { - return nil, nil //nolint:nilnil + return nil, nil } if candidateType == CandidateTypeUnspecified { - candidateType = CandidateTypeHost // Defaults to host + candidateType = CandidateTypeHost // defaults to host } else if candidateType != CandidateTypeHost && candidateType != CandidateTypeServerReflexive { return nil, ErrUnsupportedNAT1To1IPCandidateType } diff --git a/vendor/github.com/pion/ice/v2/gather.go b/vendor/github.com/pion/ice/v2/gather.go index 15e2da146..e248c08de 100644 --- a/vendor/github.com/pion/ice/v2/gather.go +++ b/vendor/github.com/pion/ice/v2/gather.go @@ -1,23 +1,17 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( "context" "crypto/tls" + "errors" "fmt" - "io" "net" "reflect" "sync" "time" "github.com/pion/dtls/v2" - "github.com/pion/ice/v2/internal/fakenet" - stunx "github.com/pion/ice/v2/internal/stun" "github.com/pion/logging" - "github.com/pion/stun" "github.com/pion/turn/v2" ) @@ -25,19 +19,42 @@ const ( stunGatherTimeout = time.Second * 5 ) +type closeable interface { + Close() error +} + // Close a net.Conn and log if we have a failure -func closeConnAndLog(c io.Closer, log logging.LeveledLogger, msg string, args ...interface{}) { +func closeConnAndLog(c closeable, log logging.LeveledLogger, msg string) { if c == nil || (reflect.ValueOf(c).Kind() == reflect.Ptr && reflect.ValueOf(c).IsNil()) { - log.Warnf("Connection is not allocated: "+msg, args...) + log.Warnf("Conn is not allocated (%s)", msg) return } log.Warnf(msg) if err := c.Close(); err != nil { - log.Warnf("Failed to close connection: %v", err) + log.Warnf("Failed to close conn: %v", err) } } +// fakePacketConn wraps a net.Conn and emulates net.PacketConn +type fakePacketConn struct { + nextConn net.Conn +} + +func (f *fakePacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { + n, err = f.nextConn.Read(p) + addr = f.nextConn.RemoteAddr() + return +} +func (f *fakePacketConn) Close() error { return f.nextConn.Close() } +func (f *fakePacketConn) LocalAddr() net.Addr { return f.nextConn.LocalAddr() } +func (f *fakePacketConn) SetDeadline(t time.Time) error { return f.nextConn.SetDeadline(t) } +func (f *fakePacketConn) SetReadDeadline(t time.Time) error { return f.nextConn.SetReadDeadline(t) } +func (f *fakePacketConn) SetWriteDeadline(t time.Time) error { return f.nextConn.SetWriteDeadline(t) } +func (f *fakePacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error) { + return f.nextConn.Write(p) +} + // GatherCandidates initiates the trickle based gathering process. func (a *Agent) GatherCandidates() error { var gatherErr error @@ -54,20 +71,17 @@ func (a *Agent) GatherCandidates() error { a.gatherCandidateCancel() // Cancel previous gathering routine ctx, cancel := context.WithCancel(ctx) a.gatherCandidateCancel = cancel - done := make(chan struct{}) - a.gatherCandidateDone = done - go a.gatherCandidates(ctx, done) + go a.gatherCandidates(ctx) }); runErr != nil { return runErr } return gatherErr } -func (a *Agent) gatherCandidates(ctx context.Context, done chan struct{}) { - defer close(done) - if err := a.setGatheringState(GatheringStateGathering); err != nil { //nolint:contextcheck - a.log.Warnf("Failed to set gatheringState to GatheringStateGathering: %v", err) +func (a *Agent) gatherCandidates(ctx context.Context) { + if err := a.setGatheringState(GatheringStateGathering); err != nil { + a.log.Warnf("failed to set gatheringState to GatheringStateGathering: %v", err) return } @@ -83,11 +97,7 @@ func (a *Agent) gatherCandidates(ctx context.Context, done chan struct{}) { case CandidateTypeServerReflexive: wg.Add(1) go func() { - if a.udpMuxSrflx != nil { - a.gatherCandidatesSrflxUDPMux(ctx, a.urls, a.networkTypes) - } else { - a.gatherCandidatesSrflx(ctx, a.urls, a.networkTypes) - } + a.gatherCandidatesSrflx(ctx, a.urls, a.networkTypes) wg.Done() }() if a.extIPMapper != nil && a.extIPMapper.candidateType == CandidateTypeServerReflexive { @@ -106,12 +116,11 @@ func (a *Agent) gatherCandidates(ctx context.Context, done chan struct{}) { case CandidateTypePeerReflexive, CandidateTypeUnspecified: } } - // Block until all STUN and TURN URLs have been gathered (or timed out) wg.Wait() - if err := a.setGatheringState(GatheringStateComplete); err != nil { //nolint:contextcheck - a.log.Warnf("Failed to set gatheringState to GatheringStateComplete: %v", err) + if err := a.setGatheringState(GatheringStateComplete); err != nil { + a.log.Warnf("failed to set gatheringState to GatheringStateComplete: %v", err) } } @@ -125,27 +134,27 @@ func (a *Agent) gatherCandidatesLocal(ctx context.Context, networkTypes []Networ } } - // When UDPMux is enabled, skip other UDP candidates + // when UDPMux is enabled, skip other UDP candidates if a.udpMux != nil { if err := a.gatherCandidatesLocalUDPMux(ctx); err != nil { - a.log.Warnf("Failed to create host candidate for UDPMux: %s", err) + a.log.Warnf("could not create host candidate for UDPMux") } delete(networks, udp) } - localIPs, err := localInterfaces(a.net, a.interfaceFilter, a.ipFilter, networkTypes, a.includeLoopback) + localIPs, err := localInterfaces(a.net, a.interfaceFilter, networkTypes) if err != nil { - a.log.Warnf("Failed to iterate local interfaces, host candidates will not be gathered %s", err) + a.log.Warnf("failed to iterate local interfaces, host candidates will not be gathered %s", err) return } for _, ip := range localIPs { mappedIP := ip if a.mDNSMode != MulticastDNSModeQueryAndGather && a.extIPMapper != nil && a.extIPMapper.candidateType == CandidateTypeHost { - if _mappedIP, innerErr := a.extIPMapper.findExternalIP(ip.String()); innerErr == nil { + if _mappedIP, err := a.extIPMapper.findExternalIP(ip.String()); err == nil { mappedIP = _mappedIP } else { - a.log.Warnf("1:1 NAT mapping is enabled but no external IP is found for %s", ip.String()) + a.log.Warnf("1:1 NAT mapping is enabled but no external IP is found for %s\n", ip.String()) } } @@ -155,163 +164,115 @@ func (a *Agent) gatherCandidatesLocal(ctx context.Context, networkTypes []Networ } for network := range networks { - type connAndPort struct { - conn net.PacketConn - port int - } - var ( - conns []connAndPort - tcpType TCPType - ) + var port int + var conn net.PacketConn + var err error + var tcpType TCPType switch network { case tcp: - if a.tcpMux == nil { - continue - } - // Handle ICE TCP passive mode - var muxConns []net.PacketConn - if multi, ok := a.tcpMux.(AllConnsGetter); ok { - a.log.Debugf("GetAllConns by ufrag: %s", a.localUfrag) - muxConns, err = multi.GetAllConns(a.localUfrag, mappedIP.To4() == nil, ip) - if err != nil { - a.log.Warnf("Failed to get all TCP connections by ufrag: %s %s %s", network, ip, a.localUfrag) - continue + a.log.Debugf("GetConn by ufrag: %s\n", a.localUfrag) + conn, err = a.tcpMux.GetConnByUfrag(a.localUfrag) + if err != nil { + if !errors.Is(err, ErrTCPMuxNotInitialized) { + a.log.Warnf("error getting tcp conn by ufrag: %s %s %s\n", network, ip, a.localUfrag) } - } else { - a.log.Debugf("GetConn by ufrag: %s", a.localUfrag) - conn, err := a.tcpMux.GetConnByUfrag(a.localUfrag, mappedIP.To4() == nil, ip) - if err != nil { - a.log.Warnf("Failed to get TCP connections by ufrag: %s %s %s", network, ip, a.localUfrag) - continue - } - muxConns = []net.PacketConn{conn} - } - - // Extract the port for each PacketConn we got. - for _, conn := range muxConns { - if tcpConn, ok := conn.LocalAddr().(*net.TCPAddr); ok { - conns = append(conns, connAndPort{conn, tcpConn.Port}) - } else { - a.log.Warnf("Failed to get port of connection from TCPMux: %s %s %s", network, ip, a.localUfrag) - } - } - if len(conns) == 0 { - // Didn't succeed with any, try the next network. continue } + port = conn.LocalAddr().(*net.TCPAddr).Port tcpType = TCPTypePassive - // Is there a way to verify that the listen address is even + // is there a way to verify that the listen address is even // accessible from the current interface. case udp: - conn, err := listenUDPInPortRange(a.net, a.log, int(a.portMax), int(a.portMin), network, &net.UDPAddr{IP: ip, Port: 0}) + conn, err = listenUDPInPortRange(a.net, a.log, int(a.portmax), int(a.portmin), network, &net.UDPAddr{IP: ip, Port: 0}) if err != nil { - a.log.Warnf("Failed to listen %s %s", network, ip) + a.log.Warnf("could not listen %s %s\n", network, ip) continue } - if udpConn, ok := conn.LocalAddr().(*net.UDPAddr); ok { - conns = append(conns, connAndPort{conn, udpConn.Port}) - } else { - a.log.Warnf("Failed to get port of UDPAddr from ListenUDPInPortRange: %s %s %s", network, ip, a.localUfrag) + port = conn.LocalAddr().(*net.UDPAddr).Port + } + hostConfig := CandidateHostConfig{ + Network: network, + Address: address, + Port: port, + Component: ComponentRTP, + TCPType: tcpType, + } + + c, err := NewCandidateHost(&hostConfig) + if err != nil { + closeConnAndLog(conn, a.log, fmt.Sprintf("Failed to create host candidate: %s %s %d: %v\n", network, mappedIP, port, err)) + continue + } + + if a.mDNSMode == MulticastDNSModeQueryAndGather { + if err = c.setIP(ip); err != nil { + closeConnAndLog(conn, a.log, fmt.Sprintf("Failed to create host candidate: %s %s %d: %v\n", network, mappedIP, port, err)) continue } } - for _, connAndPort := range conns { - hostConfig := CandidateHostConfig{ - Network: network, - Address: address, - Port: connAndPort.port, - Component: ComponentRTP, - TCPType: tcpType, - } - - c, err := NewCandidateHost(&hostConfig) - if err != nil { - closeConnAndLog(connAndPort.conn, a.log, "failed to create host candidate: %s %s %d: %v", network, mappedIP, connAndPort.port, err) - continue - } - - if a.mDNSMode == MulticastDNSModeQueryAndGather { - if err = c.setIP(ip); err != nil { - closeConnAndLog(connAndPort.conn, a.log, "failed to create host candidate: %s %s %d: %v", network, mappedIP, connAndPort.port, err) - continue - } - } - - if err := a.addCandidate(ctx, c, connAndPort.conn); err != nil { - if closeErr := c.close(); closeErr != nil { - a.log.Warnf("Failed to close candidate: %v", closeErr) - } - a.log.Warnf("Failed to append to localCandidates and run onCandidateHdlr: %v", err) + if err := a.addCandidate(ctx, c, conn); err != nil { + if closeErr := c.close(); closeErr != nil { + a.log.Warnf("Failed to close candidate: %v", closeErr) } + a.log.Warnf("Failed to append to localCandidates and run onCandidateHdlr: %v\n", err) } } } } -func (a *Agent) gatherCandidatesLocalUDPMux(ctx context.Context) error { //nolint:gocognit +func (a *Agent) gatherCandidatesLocalUDPMux(ctx context.Context) error { if a.udpMux == nil { return errUDPMuxDisabled } - localAddresses := a.udpMux.GetListenAddresses() - existingConfigs := make(map[CandidateHostConfig]struct{}) + localIPs, err := localInterfaces(a.net, a.interfaceFilter, []NetworkType{NetworkTypeUDP4}) + switch { + case err != nil: + return err + case len(localIPs) == 0: + return errCandidateIPNotFound + } - for _, addr := range localAddresses { - udpAddr, ok := addr.(*net.UDPAddr) - if !ok { - return errInvalidAddress - } - candidateIP := udpAddr.IP + for _, candidateIP := range localIPs { if a.extIPMapper != nil && a.extIPMapper.candidateType == CandidateTypeHost { - mappedIP, err := a.extIPMapper.findExternalIP(candidateIP.String()) - if err != nil { + if mappedIP, err := a.extIPMapper.findExternalIP(candidateIP.String()); err != nil { a.log.Warnf("1:1 NAT mapping is enabled but no external IP is found for %s", candidateIP.String()) continue + } else { + candidateIP = mappedIP } - - candidateIP = mappedIP } + conn, err := a.udpMux.GetConn(a.localUfrag) + if err != nil { + return err + } + port := conn.LocalAddr().(*net.UDPAddr).Port + hostConfig := CandidateHostConfig{ Network: udp, Address: candidateIP.String(), - Port: udpAddr.Port, + Port: port, Component: ComponentRTP, } - // Detect a duplicate candidate before calling addCandidate(). - // otherwise, addCandidate() detects the duplicate candidate - // and close its connection, invalidating all candidates - // that share the same connection. - if _, ok := existingConfigs[hostConfig]; ok { - continue - } - - conn, err := a.udpMux.GetConn(a.localUfrag, udpAddr) - if err != nil { - return err - } - c, err := NewCandidateHost(&hostConfig) if err != nil { - closeConnAndLog(conn, a.log, "failed to create host mux candidate: %s %d: %v", candidateIP, udpAddr.Port, err) - continue + closeConnAndLog(conn, a.log, fmt.Sprintf("Failed to create host mux candidate: %s %d: %v\n", candidateIP, port, err)) + // already logged error + return nil } if err := a.addCandidate(ctx, c, conn); err != nil { if closeErr := c.close(); closeErr != nil { a.log.Warnf("Failed to close candidate: %v", closeErr) } - - closeConnAndLog(conn, a.log, "failed to add candidate: %s %d: %v", candidateIP, udpAddr.Port, err) - continue + return err } - - existingConfigs[hostConfig] = struct{}{} } return nil @@ -331,39 +292,34 @@ func (a *Agent) gatherCandidatesSrflxMapped(ctx context.Context, networkTypes [] go func() { defer wg.Done() - conn, err := listenUDPInPortRange(a.net, a.log, int(a.portMax), int(a.portMin), network, &net.UDPAddr{IP: nil, Port: 0}) + conn, err := listenUDPInPortRange(a.net, a.log, int(a.portmax), int(a.portmin), network, &net.UDPAddr{IP: nil, Port: 0}) if err != nil { - a.log.Warnf("Failed to listen %s: %v", network, err) + a.log.Warnf("Failed to listen %s: %v\n", network, err) return } - lAddr, ok := conn.LocalAddr().(*net.UDPAddr) - if !ok { - closeConnAndLog(conn, a.log, "1:1 NAT mapping is enabled but LocalAddr is not a UDPAddr") - return - } - - mappedIP, err := a.extIPMapper.findExternalIP(lAddr.IP.String()) + laddr := conn.LocalAddr().(*net.UDPAddr) + mappedIP, err := a.extIPMapper.findExternalIP(laddr.IP.String()) if err != nil { - closeConnAndLog(conn, a.log, "1:1 NAT mapping is enabled but no external IP is found for %s", lAddr.IP.String()) + closeConnAndLog(conn, a.log, fmt.Sprintf("1:1 NAT mapping is enabled but no external IP is found for %s\n", laddr.IP.String())) return } srflxConfig := CandidateServerReflexiveConfig{ Network: network, Address: mappedIP.String(), - Port: lAddr.Port, + Port: laddr.Port, Component: ComponentRTP, - RelAddr: lAddr.IP.String(), - RelPort: lAddr.Port, + RelAddr: laddr.IP.String(), + RelPort: laddr.Port, } c, err := NewCandidateServerReflexive(&srflxConfig) if err != nil { - closeConnAndLog(conn, a.log, "failed to create server reflexive candidate: %s %s %d: %v", + closeConnAndLog(conn, a.log, fmt.Sprintf("Failed to create server reflexive candidate: %s %s %d: %v\n", network, mappedIP.String(), - lAddr.Port, - err) + laddr.Port, + err)) return } @@ -371,81 +327,13 @@ func (a *Agent) gatherCandidatesSrflxMapped(ctx context.Context, networkTypes [] if closeErr := c.close(); closeErr != nil { a.log.Warnf("Failed to close candidate: %v", closeErr) } - a.log.Warnf("Failed to append to localCandidates and run onCandidateHdlr: %v", err) + a.log.Warnf("Failed to append to localCandidates and run onCandidateHdlr: %v\n", err) } }() } } -func (a *Agent) gatherCandidatesSrflxUDPMux(ctx context.Context, urls []*stun.URI, networkTypes []NetworkType) { //nolint:gocognit - var wg sync.WaitGroup - defer wg.Wait() - - for _, networkType := range networkTypes { - if networkType.IsTCP() { - continue - } - - for i := range urls { - for _, listenAddr := range a.udpMuxSrflx.GetListenAddresses() { - udpAddr, ok := listenAddr.(*net.UDPAddr) - if !ok { - a.log.Warn("Failed to cast udpMuxSrflx listen address to UDPAddr") - continue - } - wg.Add(1) - go func(url stun.URI, network string, localAddr *net.UDPAddr) { - defer wg.Done() - - hostPort := fmt.Sprintf("%s:%d", url.Host, url.Port) - serverAddr, err := a.net.ResolveUDPAddr(network, hostPort) - if err != nil { - a.log.Warnf("Failed to resolve STUN host: %s: %v", hostPort, err) - return - } - - xorAddr, err := a.udpMuxSrflx.GetXORMappedAddr(serverAddr, stunGatherTimeout) - if err != nil { - a.log.Warnf("Failed get server reflexive address %s %s: %v", network, url, err) - return - } - - conn, err := a.udpMuxSrflx.GetConnForURL(a.localUfrag, url.String(), localAddr) - if err != nil { - a.log.Warnf("Failed to find connection in UDPMuxSrflx %s %s: %v", network, url, err) - return - } - - ip := xorAddr.IP - port := xorAddr.Port - - srflxConfig := CandidateServerReflexiveConfig{ - Network: network, - Address: ip.String(), - Port: port, - Component: ComponentRTP, - RelAddr: localAddr.IP.String(), - RelPort: localAddr.Port, - } - c, err := NewCandidateServerReflexive(&srflxConfig) - if err != nil { - closeConnAndLog(conn, a.log, "failed to create server reflexive candidate: %s %s %d: %v", network, ip, port, err) - return - } - - if err := a.addCandidate(ctx, c, conn); err != nil { - if closeErr := c.close(); closeErr != nil { - a.log.Warnf("Failed to close candidate: %v", closeErr) - } - a.log.Warnf("Failed to append to localCandidates and run onCandidateHdlr: %v", err) - } - }(*urls[i], networkType.String(), udpAddr) - } - } - } -} - -func (a *Agent) gatherCandidatesSrflx(ctx context.Context, urls []*stun.URI, networkTypes []NetworkType) { //nolint:gocognit +func (a *Agent) gatherCandidatesSrflx(ctx context.Context, urls []*URL, networkTypes []NetworkType) { var wg sync.WaitGroup defer wg.Wait() @@ -456,55 +344,43 @@ func (a *Agent) gatherCandidatesSrflx(ctx context.Context, urls []*stun.URI, net for i := range urls { wg.Add(1) - go func(url stun.URI, network string) { + go func(url URL, network string) { defer wg.Done() hostPort := fmt.Sprintf("%s:%d", url.Host, url.Port) serverAddr, err := a.net.ResolveUDPAddr(network, hostPort) if err != nil { - a.log.Warnf("Failed to resolve STUN host: %s: %v", hostPort, err) + a.log.Warnf("failed to resolve stun host: %s: %v", hostPort, err) return } - conn, err := listenUDPInPortRange(a.net, a.log, int(a.portMax), int(a.portMin), network, &net.UDPAddr{IP: nil, Port: 0}) + conn, err := listenUDPInPortRange(a.net, a.log, int(a.portmax), int(a.portmin), network, &net.UDPAddr{IP: nil, Port: 0}) if err != nil { - closeConnAndLog(conn, a.log, "failed to listen for %s: %v", serverAddr.String(), err) + closeConnAndLog(conn, a.log, fmt.Sprintf("Failed to listen for %s: %v\n", serverAddr.String(), err)) return } - // If the agent closes midway through the connection - // we end it early to prevent close delay. - cancelCtx, cancelFunc := context.WithCancel(ctx) - defer cancelFunc() - go func() { - select { - case <-cancelCtx.Done(): - return - case <-a.done: - _ = conn.Close() - } - }() - xorAddr, err := stunx.GetXORMappedAddr(conn, serverAddr, stunGatherTimeout) + xoraddr, err := getXORMappedAddr(conn, serverAddr, stunGatherTimeout) if err != nil { - closeConnAndLog(conn, a.log, "failed to get server reflexive address %s %s: %v", network, url, err) + closeConnAndLog(conn, a.log, fmt.Sprintf("could not get server reflexive address %s %s: %v\n", network, url, err)) return } - ip := xorAddr.IP - port := xorAddr.Port + ip := xoraddr.IP + port := xoraddr.Port - lAddr := conn.LocalAddr().(*net.UDPAddr) //nolint:forcetypeassert + laddr := conn.LocalAddr().(*net.UDPAddr) srflxConfig := CandidateServerReflexiveConfig{ Network: network, Address: ip.String(), Port: port, Component: ComponentRTP, - RelAddr: lAddr.IP.String(), - RelPort: lAddr.Port, + RelAddr: laddr.IP.String(), + RelPort: laddr.Port, } c, err := NewCandidateServerReflexive(&srflxConfig) if err != nil { - closeConnAndLog(conn, a.log, "failed to create server reflexive candidate: %s %s %d: %v", network, ip, port, err) + closeConnAndLog(conn, a.log, fmt.Sprintf("Failed to create server reflexive candidate: %s %s %d: %v\n", network, ip, port, err)) return } @@ -512,21 +388,21 @@ func (a *Agent) gatherCandidatesSrflx(ctx context.Context, urls []*stun.URI, net if closeErr := c.close(); closeErr != nil { a.log.Warnf("Failed to close candidate: %v", closeErr) } - a.log.Warnf("Failed to append to localCandidates and run onCandidateHdlr: %v", err) + a.log.Warnf("Failed to append to localCandidates and run onCandidateHdlr: %v\n", err) } }(*urls[i], networkType.String()) } } } -func (a *Agent) gatherCandidatesRelay(ctx context.Context, urls []*stun.URI) { //nolint:gocognit +func (a *Agent) gatherCandidatesRelay(ctx context.Context, urls []*URL) { //nolint:gocognit var wg sync.WaitGroup defer wg.Wait() network := NetworkTypeUDP4.String() for i := range urls { switch { - case urls[i].Scheme != stun.SchemeTypeTURN && urls[i].Scheme != stun.SchemeTypeTURNS: + case urls[i].Scheme != SchemeTypeTURN && urls[i].Scheme != SchemeTypeTURNS: continue case urls[i].Username == "": a.log.Errorf("Failed to gather relay candidates: %v", ErrUsernameEmpty) @@ -537,124 +413,100 @@ func (a *Agent) gatherCandidatesRelay(ctx context.Context, urls []*stun.URI) { / } wg.Add(1) - go func(url stun.URI) { + go func(url URL) { defer wg.Done() - turnServerAddr := fmt.Sprintf("%s:%d", url.Host, url.Port) + TURNServerAddr := fmt.Sprintf("%s:%d", url.Host, url.Port) var ( locConn net.PacketConn err error - relAddr string - relPort int + RelAddr string + RelPort int relayProtocol string ) switch { - case url.Proto == stun.ProtoTypeUDP && url.Scheme == stun.SchemeTypeTURN: + case url.Proto == ProtoTypeUDP && url.Scheme == SchemeTypeTURN: if locConn, err = a.net.ListenPacket(network, "0.0.0.0:0"); err != nil { - a.log.Warnf("Failed to listen %s: %v", network, err) + a.log.Warnf("Failed to listen %s: %v\n", network, err) return } - relAddr = locConn.LocalAddr().(*net.UDPAddr).IP.String() //nolint:forcetypeassert - relPort = locConn.LocalAddr().(*net.UDPAddr).Port //nolint:forcetypeassert + RelAddr = locConn.LocalAddr().(*net.UDPAddr).IP.String() + RelPort = locConn.LocalAddr().(*net.UDPAddr).Port relayProtocol = udp - case a.proxyDialer != nil && url.Proto == stun.ProtoTypeTCP && - (url.Scheme == stun.SchemeTypeTURN || url.Scheme == stun.SchemeTypeTURNS): - conn, connectErr := a.proxyDialer.Dial(NetworkTypeTCP4.String(), turnServerAddr) + case a.proxyDialer != nil && url.Proto == ProtoTypeTCP && + (url.Scheme == SchemeTypeTURN || url.Scheme == SchemeTypeTURNS): + conn, connectErr := a.proxyDialer.Dial(NetworkTypeTCP4.String(), TURNServerAddr) if connectErr != nil { - a.log.Warnf("Failed to dial TCP address %s via proxy dialer: %v", turnServerAddr, connectErr) + a.log.Warnf("Failed to Dial TCP Addr %s via proxy dialer: %v\n", TURNServerAddr, connectErr) return } - relAddr = conn.LocalAddr().(*net.TCPAddr).IP.String() //nolint:forcetypeassert - relPort = conn.LocalAddr().(*net.TCPAddr).Port //nolint:forcetypeassert - if url.Scheme == stun.SchemeTypeTURN { + RelAddr = conn.LocalAddr().(*net.TCPAddr).IP.String() + RelPort = conn.LocalAddr().(*net.TCPAddr).Port + if url.Scheme == SchemeTypeTURN { relayProtocol = tcp - } else if url.Scheme == stun.SchemeTypeTURNS { + } else if url.Scheme == SchemeTypeTURNS { relayProtocol = "tls" } locConn = turn.NewSTUNConn(conn) - case url.Proto == stun.ProtoTypeTCP && url.Scheme == stun.SchemeTypeTURN: - tcpAddr, connectErr := a.net.ResolveTCPAddr(NetworkTypeTCP4.String(), turnServerAddr) + case url.Proto == ProtoTypeTCP && url.Scheme == SchemeTypeTURN: + tcpAddr, connectErr := net.ResolveTCPAddr(NetworkTypeTCP4.String(), TURNServerAddr) if connectErr != nil { - a.log.Warnf("Failed to resolve TCP address %s: %v", turnServerAddr, connectErr) + a.log.Warnf("Failed to resolve TCP Addr %s: %v\n", TURNServerAddr, connectErr) return } - conn, connectErr := a.net.DialTCP(NetworkTypeTCP4.String(), nil, tcpAddr) + conn, connectErr := net.DialTCP(NetworkTypeTCP4.String(), nil, tcpAddr) if connectErr != nil { - a.log.Warnf("Failed to dial TCP address %s: %v", turnServerAddr, connectErr) + a.log.Warnf("Failed to Dial TCP Addr %s: %v\n", TURNServerAddr, connectErr) return } - relAddr = conn.LocalAddr().(*net.TCPAddr).IP.String() //nolint:forcetypeassert - relPort = conn.LocalAddr().(*net.TCPAddr).Port //nolint:forcetypeassert + RelAddr = conn.LocalAddr().(*net.TCPAddr).IP.String() + RelPort = conn.LocalAddr().(*net.TCPAddr).Port relayProtocol = tcp locConn = turn.NewSTUNConn(conn) - case url.Proto == stun.ProtoTypeUDP && url.Scheme == stun.SchemeTypeTURNS: - udpAddr, connectErr := a.net.ResolveUDPAddr(network, turnServerAddr) + case url.Proto == ProtoTypeUDP && url.Scheme == SchemeTypeTURNS: + udpAddr, connectErr := net.ResolveUDPAddr(network, TURNServerAddr) if connectErr != nil { - a.log.Warnf("Failed to resolve UDP address %s: %v", turnServerAddr, connectErr) + a.log.Warnf("Failed to resolve UDP Addr %s: %v\n", TURNServerAddr, connectErr) return } - udpConn, dialErr := a.net.DialUDP("udp", nil, udpAddr) - if dialErr != nil { - a.log.Warnf("Failed to dial DTLS address %s: %v", turnServerAddr, dialErr) - return - } - - conn, connectErr := dtls.ClientWithContext(ctx, udpConn, &dtls.Config{ + conn, connectErr := dtls.Dial(network, udpAddr, &dtls.Config{ ServerName: url.Host, InsecureSkipVerify: a.insecureSkipVerify, //nolint:gosec }) if connectErr != nil { - a.log.Warnf("Failed to create DTLS client: %v", turnServerAddr, connectErr) + a.log.Warnf("Failed to Dial DTLS Addr %s: %v\n", TURNServerAddr, connectErr) return } - relAddr = conn.LocalAddr().(*net.UDPAddr).IP.String() //nolint:forcetypeassert - relPort = conn.LocalAddr().(*net.UDPAddr).Port //nolint:forcetypeassert + RelAddr = conn.LocalAddr().(*net.UDPAddr).IP.String() + RelPort = conn.LocalAddr().(*net.UDPAddr).Port relayProtocol = "dtls" - locConn = &fakenet.PacketConn{Conn: conn} - case url.Proto == stun.ProtoTypeTCP && url.Scheme == stun.SchemeTypeTURNS: - tcpAddr, resolvErr := a.net.ResolveTCPAddr(NetworkTypeTCP4.String(), turnServerAddr) - if resolvErr != nil { - a.log.Warnf("Failed to resolve relay address %s: %v", turnServerAddr, resolvErr) - return - } - - tcpConn, dialErr := a.net.DialTCP(NetworkTypeTCP4.String(), nil, tcpAddr) - if dialErr != nil { - a.log.Warnf("Failed to connect to relay: %v", dialErr) - return - } - - conn := tls.Client(tcpConn, &tls.Config{ - ServerName: url.Host, + locConn = &fakePacketConn{conn} + case url.Proto == ProtoTypeTCP && url.Scheme == SchemeTypeTURNS: + conn, connectErr := tls.Dial(NetworkTypeTCP4.String(), TURNServerAddr, &tls.Config{ InsecureSkipVerify: a.insecureSkipVerify, //nolint:gosec }) - - if hsErr := conn.HandshakeContext(ctx); hsErr != nil { - if closeErr := tcpConn.Close(); closeErr != nil { - a.log.Errorf("Failed to close relay connection: %v", closeErr) - } - a.log.Warnf("Failed to connect to relay: %v", hsErr) + if connectErr != nil { + a.log.Warnf("Failed to Dial TLS Addr %s: %v\n", TURNServerAddr, connectErr) return } - - relAddr = conn.LocalAddr().(*net.TCPAddr).IP.String() //nolint:forcetypeassert - relPort = conn.LocalAddr().(*net.TCPAddr).Port //nolint:forcetypeassert + RelAddr = conn.LocalAddr().(*net.TCPAddr).IP.String() + RelPort = conn.LocalAddr().(*net.TCPAddr).Port relayProtocol = "tls" locConn = turn.NewSTUNConn(conn) default: - a.log.Warnf("Unable to handle URL in gatherCandidatesRelay %v", url) + a.log.Warnf("Unable to handle URL in gatherCandidatesRelay %v\n", url) return } client, err := turn.NewClient(&turn.ClientConfig{ - TURNServerAddr: turnServerAddr, + TURNServerAddr: TURNServerAddr, Conn: locConn, Username: url.Username, Password: url.Password, @@ -662,31 +514,31 @@ func (a *Agent) gatherCandidatesRelay(ctx context.Context, urls []*stun.URI) { / Net: a.net, }) if err != nil { - closeConnAndLog(locConn, a.log, "failed to create new TURN client %s %s", turnServerAddr, err) + closeConnAndLog(locConn, a.log, fmt.Sprintf("Failed to build new turn.Client %s %s\n", TURNServerAddr, err)) return } if err = client.Listen(); err != nil { client.Close() - closeConnAndLog(locConn, a.log, "failed to listen on TURN client %s %s", turnServerAddr, err) + closeConnAndLog(locConn, a.log, fmt.Sprintf("Failed to listen on turn.Client %s %s\n", TURNServerAddr, err)) return } relayConn, err := client.Allocate() if err != nil { client.Close() - closeConnAndLog(locConn, a.log, "failed to allocate on TURN client %s %s", turnServerAddr, err) + closeConnAndLog(locConn, a.log, fmt.Sprintf("Failed to allocate on turn.Client %s %s\n", TURNServerAddr, err)) return } - rAddr := relayConn.LocalAddr().(*net.UDPAddr) //nolint:forcetypeassert + raddr := relayConn.LocalAddr().(*net.UDPAddr) relayConfig := CandidateRelayConfig{ Network: network, Component: ComponentRTP, - Address: rAddr.IP.String(), - Port: rAddr.Port, - RelAddr: relAddr, - RelPort: relPort, + Address: raddr.IP.String(), + Port: raddr.Port, + RelAddr: RelAddr, + RelPort: RelPort, RelayProtocol: relayProtocol, OnClose: func() error { client.Close() @@ -703,7 +555,7 @@ func (a *Agent) gatherCandidatesRelay(ctx context.Context, urls []*stun.URI) { / relayConnClose() client.Close() - closeConnAndLog(locConn, a.log, "failed to create relay candidate: %s %s: %v", network, rAddr.String(), err) + closeConnAndLog(locConn, a.log, fmt.Sprintf("Failed to create relay candidate: %s %s: %v\n", network, raddr.String(), err)) return } @@ -713,7 +565,7 @@ func (a *Agent) gatherCandidatesRelay(ctx context.Context, urls []*stun.URI) { / if closeErr := candidate.close(); closeErr != nil { a.log.Warnf("Failed to close candidate: %v", closeErr) } - a.log.Warnf("Failed to append to localCandidates and run onCandidateHdlr: %v", err) + a.log.Warnf("Failed to append to localCandidates and run onCandidateHdlr: %v\n", err) } }(*urls[i]) } diff --git a/vendor/github.com/pion/ice/v2/ice.go b/vendor/github.com/pion/ice/v2/ice.go index bd551206e..d7094f6db 100644 --- a/vendor/github.com/pion/ice/v2/ice.go +++ b/vendor/github.com/pion/ice/v2/ice.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice // ConnectionState is an enum showing the state of a ICE Connection @@ -8,11 +5,8 @@ type ConnectionState int // List of supported States const ( - // ConnectionStateUnknown represents an unknown state - ConnectionStateUnknown ConnectionState = iota - // ConnectionStateNew ICE agent is gathering addresses - ConnectionStateNew + ConnectionStateNew = iota + 1 // ConnectionStateChecking ICE agent has been given local and remote candidates, and is attempting to find a match ConnectionStateChecking @@ -58,16 +52,13 @@ func (c ConnectionState) String() string { type GatheringState int const ( - // GatheringStateUnknown represents an unknown state - GatheringStateUnknown GatheringState = iota + // GatheringStateNew indicates candidate gatering is not yet started + GatheringStateNew GatheringState = iota + 1 - // GatheringStateNew indicates candidate gathering is not yet started - GatheringStateNew - - // GatheringStateGathering indicates candidate gathering is ongoing + // GatheringStateGathering indicates candidate gatering is ongoing GatheringStateGathering - // GatheringStateComplete indicates candidate gathering has been completed + // GatheringStateComplete indicates candidate gatering has been completed GatheringStateComplete ) diff --git a/vendor/github.com/pion/ice/v2/icecontrol.go b/vendor/github.com/pion/ice/v2/icecontrol.go index b086bd892..ede2e09cb 100644 --- a/vendor/github.com/pion/ice/v2/icecontrol.go +++ b/vendor/github.com/pion/ice/v2/icecontrol.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( diff --git a/vendor/github.com/pion/ice/v2/internal/atomic/atomic.go b/vendor/github.com/pion/ice/v2/internal/atomic/atomic.go deleted file mode 100644 index f8caf5a2e..000000000 --- a/vendor/github.com/pion/ice/v2/internal/atomic/atomic.go +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -// Package atomic contains custom atomic types -package atomic - -import "sync/atomic" - -// Error is an atomic error -type Error struct { - v atomic.Value -} - -// Store updates the value of the atomic variable -func (a *Error) Store(err error) { - a.v.Store(struct{ error }{err}) -} - -// Load retrieves the current value of the atomic variable -func (a *Error) Load() error { - err, _ := a.v.Load().(struct{ error }) - return err.error -} diff --git a/vendor/github.com/pion/ice/v2/internal/fakenet/mock_conn.go b/vendor/github.com/pion/ice/v2/internal/fakenet/mock_conn.go deleted file mode 100644 index cc98849d5..000000000 --- a/vendor/github.com/pion/ice/v2/internal/fakenet/mock_conn.go +++ /dev/null @@ -1,23 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -//go:build !js -// +build !js - -package fakenet - -import ( - "net" - "time" -) - -// MockPacketConn for tests -type MockPacketConn struct{} - -func (m *MockPacketConn) ReadFrom([]byte) (n int, addr net.Addr, err error) { return 0, nil, nil } //nolint:revive -func (m *MockPacketConn) WriteTo([]byte, net.Addr) (n int, err error) { return 0, nil } //nolint:revive -func (m *MockPacketConn) Close() error { return nil } //nolint:revive -func (m *MockPacketConn) LocalAddr() net.Addr { return nil } //nolint:revive -func (m *MockPacketConn) SetDeadline(time.Time) error { return nil } //nolint:revive -func (m *MockPacketConn) SetReadDeadline(time.Time) error { return nil } //nolint:revive -func (m *MockPacketConn) SetWriteDeadline(time.Time) error { return nil } //nolint:revive diff --git a/vendor/github.com/pion/ice/v2/internal/fakenet/packet_conn.go b/vendor/github.com/pion/ice/v2/internal/fakenet/packet_conn.go deleted file mode 100644 index 0b9faaa84..000000000 --- a/vendor/github.com/pion/ice/v2/internal/fakenet/packet_conn.go +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -// Package fakenet contains fake network abstractions -package fakenet - -import ( - "net" -) - -// Compile-time assertion -var _ net.PacketConn = (*PacketConn)(nil) - -// PacketConn wraps a net.Conn and emulates net.PacketConn -type PacketConn struct { - net.Conn -} - -// ReadFrom reads a packet from the connection, -func (f *PacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { - n, err = f.Conn.Read(p) - addr = f.Conn.RemoteAddr() - return -} - -// WriteTo writes a packet with payload p to addr. -func (f *PacketConn) WriteTo(p []byte, _ net.Addr) (int, error) { - return f.Conn.Write(p) -} diff --git a/vendor/github.com/pion/ice/v2/internal/stun/stun.go b/vendor/github.com/pion/ice/v2/internal/stun/stun.go deleted file mode 100644 index 230cf850a..000000000 --- a/vendor/github.com/pion/ice/v2/internal/stun/stun.go +++ /dev/null @@ -1,72 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -// Package stun contains ICE specific STUN code -package stun - -import ( - "errors" - "fmt" - "net" - "time" - - "github.com/pion/stun" -) - -var ( - errGetXorMappedAddrResponse = errors.New("failed to get XOR-MAPPED-ADDRESS response") - errMismatchUsername = errors.New("username mismatch") -) - -// GetXORMappedAddr initiates a STUN requests to serverAddr using conn, reads the response and returns -// the XORMappedAddress returned by the STUN server. -func GetXORMappedAddr(conn net.PacketConn, serverAddr net.Addr, timeout time.Duration) (*stun.XORMappedAddress, error) { - if timeout > 0 { - if err := conn.SetReadDeadline(time.Now().Add(timeout)); err != nil { - return nil, err - } - - // Reset timeout after completion - defer conn.SetReadDeadline(time.Time{}) //nolint:errcheck - } - - req, err := stun.Build(stun.BindingRequest, stun.TransactionID) - if err != nil { - return nil, err - } - - if _, err = conn.WriteTo(req.Raw, serverAddr); err != nil { - return nil, err - } - - const maxMessageSize = 1280 - buf := make([]byte, maxMessageSize) - n, _, err := conn.ReadFrom(buf) - if err != nil { - return nil, err - } - - res := &stun.Message{Raw: buf[:n]} - if err = res.Decode(); err != nil { - return nil, err - } - - var addr stun.XORMappedAddress - if err = addr.GetFrom(res); err != nil { - return nil, fmt.Errorf("%w: %v", errGetXorMappedAddrResponse, err) //nolint:errorlint - } - - return &addr, nil -} - -// AssertUsername checks that the given STUN message m has a USERNAME attribute with a given value -func AssertUsername(m *stun.Message, expectedUsername string) error { - var username stun.Username - if err := username.GetFrom(m); err != nil { - return err - } else if string(username) != expectedUsername { - return fmt.Errorf("%w expected(%x) actual(%x)", errMismatchUsername, expectedUsername, string(username)) - } - - return nil -} diff --git a/vendor/github.com/pion/ice/v2/mdns.go b/vendor/github.com/pion/ice/v2/mdns.go index aa8231648..5a431d152 100644 --- a/vendor/github.com/pion/ice/v2/mdns.go +++ b/vendor/github.com/pion/ice/v2/mdns.go @@ -1,13 +1,11 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( + "net" + "github.com/google/uuid" "github.com/pion/logging" "github.com/pion/mdns" - "github.com/pion/transport/v2" "golang.org/x/net/ipv4" ) @@ -33,17 +31,17 @@ func generateMulticastDNSName() (string, error) { return u.String() + ".local", err } -func createMulticastDNS(n transport.Net, mDNSMode MulticastDNSMode, mDNSName string, log logging.LeveledLogger) (*mdns.Conn, MulticastDNSMode, error) { +func createMulticastDNS(mDNSMode MulticastDNSMode, mDNSName string, log logging.LeveledLogger) (*mdns.Conn, MulticastDNSMode, error) { if mDNSMode == MulticastDNSModeDisabled { return nil, mDNSMode, nil } - addr, mdnsErr := n.ResolveUDPAddr("udp4", mdns.DefaultAddress) + addr, mdnsErr := net.ResolveUDPAddr("udp4", mdns.DefaultAddress) if mdnsErr != nil { return nil, mDNSMode, mdnsErr } - l, mdnsErr := n.ListenUDP("udp4", addr) + l, mdnsErr := net.ListenUDP("udp4", addr) if mdnsErr != nil { // If ICE fails to start MulticastDNS server just warn the user and continue log.Errorf("Failed to enable mDNS, continuing in mDNS disabled mode: (%s)", mdnsErr) diff --git a/vendor/github.com/pion/ice/v2/net.go b/vendor/github.com/pion/ice/v2/net.go deleted file mode 100644 index d716bc19c..000000000 --- a/vendor/github.com/pion/ice/v2/net.go +++ /dev/null @@ -1,137 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package ice - -import ( - "net" - - "github.com/pion/logging" - "github.com/pion/transport/v2" -) - -// The conditions of invalidation written below are defined in -// https://tools.ietf.org/html/rfc8445#section-5.1.1.1 -func isSupportedIPv6(ip net.IP) bool { - if len(ip) != net.IPv6len || - isZeros(ip[0:12]) || // !(IPv4-compatible IPv6) - ip[0] == 0xfe && ip[1]&0xc0 == 0xc0 || // !(IPv6 site-local unicast) - ip.IsLinkLocalUnicast() || - ip.IsLinkLocalMulticast() { - return false - } - return true -} - -func isZeros(ip net.IP) bool { - for i := 0; i < len(ip); i++ { - if ip[i] != 0 { - return false - } - } - return true -} - -func localInterfaces(n transport.Net, interfaceFilter func(string) bool, ipFilter func(net.IP) bool, networkTypes []NetworkType, includeLoopback bool) ([]net.IP, error) { //nolint:gocognit - ips := []net.IP{} - ifaces, err := n.Interfaces() - if err != nil { - return ips, err - } - - var IPv4Requested, IPv6Requested bool - for _, typ := range networkTypes { - if typ.IsIPv4() { - IPv4Requested = true - } - - if typ.IsIPv6() { - IPv6Requested = true - } - } - - for _, iface := range ifaces { - if iface.Flags&net.FlagUp == 0 { - continue // Interface down - } - if (iface.Flags&net.FlagLoopback != 0) && !includeLoopback { - continue // Loopback interface - } - - if interfaceFilter != nil && !interfaceFilter(iface.Name) { - continue - } - - addrs, err := iface.Addrs() - if err != nil { - continue - } - - for _, addr := range addrs { - var ip net.IP - switch addr := addr.(type) { - case *net.IPNet: - ip = addr.IP - case *net.IPAddr: - ip = addr.IP - } - if ip == nil || (ip.IsLoopback() && !includeLoopback) { - continue - } - - if ipv4 := ip.To4(); ipv4 == nil { - if !IPv6Requested { - continue - } else if !isSupportedIPv6(ip) { - continue - } - } else if !IPv4Requested { - continue - } - - if ipFilter != nil && !ipFilter(ip) { - continue - } - - ips = append(ips, ip) - } - } - return ips, nil -} - -func listenUDPInPortRange(n transport.Net, log logging.LeveledLogger, portMax, portMin int, network string, lAddr *net.UDPAddr) (transport.UDPConn, error) { - if (lAddr.Port != 0) || ((portMin == 0) && (portMax == 0)) { - return n.ListenUDP(network, lAddr) - } - var i, j int - i = portMin - if i == 0 { - i = 1 - } - j = portMax - if j == 0 { - j = 0xFFFF - } - if i > j { - return nil, ErrPort - } - - portStart := globalMathRandomGenerator.Intn(j-i+1) + i - portCurrent := portStart - for { - lAddr = &net.UDPAddr{IP: lAddr.IP, Port: portCurrent} - c, e := n.ListenUDP(network, lAddr) - if e == nil { - return c, e //nolint:nilerr - } - log.Debugf("Failed to listen %s: %v", lAddr.String(), e) - portCurrent++ - if portCurrent > j { - portCurrent = i - } - if portCurrent == portStart { - break - } - } - return nil, ErrPort -} diff --git a/vendor/github.com/pion/ice/v2/networktype.go b/vendor/github.com/pion/ice/v2/networktype.go index 57df18631..95091018e 100644 --- a/vendor/github.com/pion/ice/v2/networktype.go +++ b/vendor/github.com/pion/ice/v2/networktype.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( @@ -10,12 +7,8 @@ import ( ) const ( - udp = "udp" - tcp = "tcp" - udp4 = "udp4" - udp6 = "udp6" - tcp4 = "tcp4" - tcp6 = "tcp6" + udp = "udp" + tcp = "tcp" ) func supportedNetworkTypes() []NetworkType { @@ -47,13 +40,13 @@ const ( func (t NetworkType) String() string { switch t { case NetworkTypeUDP4: - return udp4 + return "udp4" case NetworkTypeUDP6: - return udp6 + return "udp6" case NetworkTypeTCP4: - return tcp4 + return "tcp4" case NetworkTypeTCP6: - return tcp6 + return "tcp6" default: return ErrUnknownType.Error() } diff --git a/vendor/github.com/pion/ice/v2/priority.go b/vendor/github.com/pion/ice/v2/priority.go index 16ac5cc73..421829938 100644 --- a/vendor/github.com/pion/ice/v2/priority.go +++ b/vendor/github.com/pion/ice/v2/priority.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( diff --git a/vendor/github.com/pion/ice/v2/rand.go b/vendor/github.com/pion/ice/v2/rand.go index 3de1f0407..918783e02 100644 --- a/vendor/github.com/pion/ice/v2/rand.go +++ b/vendor/github.com/pion/ice/v2/rand.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import "github.com/pion/randutil" diff --git a/vendor/github.com/pion/ice/v2/renovate.json b/vendor/github.com/pion/ice/v2/renovate.json index f1bb98c6a..f1614058a 100644 --- a/vendor/github.com/pion/ice/v2/renovate.json +++ b/vendor/github.com/pion/ice/v2/renovate.json @@ -1,6 +1,27 @@ { - "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ - "github>pion/renovate-config" + "config:base", + ":disableDependencyDashboard" + ], + "postUpdateOptions": [ + "gomodTidy" + ], + "commitBody": "Generated by renovateBot", + "packageRules": [ + { + "matchUpdateTypes": ["minor", "patch", "pin", "digest"], + "automerge": true + }, + { + "packagePatterns": ["^golang.org/x/"], + "schedule": ["on the first day of the month"] + } + ], + "ignorePaths": [ + ".github/workflows/generate-authors.yml", + ".github/workflows/lint.yaml", + ".github/workflows/renovate-go-mod-fix.yaml", + ".github/workflows/test.yaml", + ".github/workflows/tidy-check.yaml" ] } diff --git a/vendor/github.com/pion/ice/v2/role.go b/vendor/github.com/pion/ice/v2/role.go index e9a7bda94..7a8bc064a 100644 --- a/vendor/github.com/pion/ice/v2/role.go +++ b/vendor/github.com/pion/ice/v2/role.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( diff --git a/vendor/github.com/pion/ice/v2/selection.go b/vendor/github.com/pion/ice/v2/selection.go index 9f312637f..72484148d 100644 --- a/vendor/github.com/pion/ice/v2/selection.go +++ b/vendor/github.com/pion/ice/v2/selection.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( @@ -43,7 +40,7 @@ func (s *controllingSelector) isNominatable(c Candidate) bool { return time.Since(s.startTime).Nanoseconds() > s.agent.relayAcceptanceMinWait.Nanoseconds() } - s.log.Errorf("Invalid candidate type: %s", c.Type()) + s.log.Errorf("isNominatable invalid candidate type %s", c.Type().String()) return false } @@ -87,7 +84,7 @@ func (s *controllingSelector) nominatePair(pair *CandidatePair) { return } - s.log.Tracef("ping STUN (nominate candidate pair) from %s to %s", pair.Local.String(), pair.Remote.String()) + s.log.Tracef("ping STUN (nominate candidate pair) from %s to %s\n", pair.Local.String(), pair.Remote.String()) s.agent.sendBindingRequest(msg, pair.Local, pair.Remote) } @@ -104,9 +101,9 @@ func (s *controllingSelector) HandleBindingRequest(m *stun.Message, local, remot if p.state == CandidatePairStateSucceeded && s.nominatedPair == nil && s.agent.getSelectedPair() == nil { bestPair := s.agent.getBestAvailableCandidatePair() if bestPair == nil { - s.log.Tracef("No best pair available") + s.log.Tracef("No best pair available\n") } else if bestPair.equal(p) && s.isNominatable(p.Local) && s.isNominatable(p.Remote) { - s.log.Tracef("The candidate (%s, %s) is the best candidate available, marking it as nominated", + s.log.Tracef("The candidate (%s, %s) is the best candidate available, marking it as nominated\n", p.Local.String(), p.Remote.String()) s.nominatedPair = p s.nominatePair(p) @@ -117,7 +114,7 @@ func (s *controllingSelector) HandleBindingRequest(m *stun.Message, local, remot func (s *controllingSelector) HandleSuccessResponse(m *stun.Message, local, remote Candidate, remoteAddr net.Addr) { ok, pendingRequest := s.agent.handleInboundBindingSuccess(m.TransactionID) if !ok { - s.log.Warnf("Discard message from (%s), unknown TransactionID 0x%x", remote, m.TransactionID) + s.log.Warnf("discard message from (%s), unknown TransactionID 0x%x", remote, m.TransactionID) return } @@ -126,7 +123,7 @@ func (s *controllingSelector) HandleSuccessResponse(m *stun.Message, local, remo // Assert that NAT is not symmetric // https://tools.ietf.org/html/rfc8445#section-7.2.5.2.1 if !addrEqual(transactionAddr, remoteAddr) { - s.log.Debugf("Discard message: transaction source and destination does not match expected(%s), actual(%s)", transactionAddr, remote) + s.log.Debugf("discard message: transaction source and destination does not match expected(%s), actual(%s)", transactionAddr, remote) return } @@ -198,7 +195,7 @@ func (s *controlledSelector) PingCandidate(local, remote Candidate) { } func (s *controlledSelector) HandleSuccessResponse(m *stun.Message, local, remote Candidate, remoteAddr net.Addr) { - //nolint:godox + // nolint:godox // TODO according to the standard we should specifically answer a failed nomination: // https://tools.ietf.org/html/rfc8445#section-7.3.1.5 // If the controlled agent does not accept the request from the @@ -208,7 +205,7 @@ func (s *controlledSelector) HandleSuccessResponse(m *stun.Message, local, remot ok, pendingRequest := s.agent.handleInboundBindingSuccess(m.TransactionID) if !ok { - s.log.Warnf("Discard message from (%s), unknown TransactionID 0x%x", remote, m.TransactionID) + s.log.Warnf("discard message from (%s), unknown TransactionID 0x%x", remote, m.TransactionID) return } @@ -217,7 +214,7 @@ func (s *controlledSelector) HandleSuccessResponse(m *stun.Message, local, remot // Assert that NAT is not symmetric // https://tools.ietf.org/html/rfc8445#section-7.2.5.2.1 if !addrEqual(transactionAddr, remoteAddr) { - s.log.Debugf("Discard message: transaction source and destination does not match expected(%s), actual(%s)", transactionAddr, remote) + s.log.Debugf("discard message: transaction source and destination does not match expected(%s), actual(%s)", transactionAddr, remote) return } @@ -232,20 +229,13 @@ func (s *controlledSelector) HandleSuccessResponse(m *stun.Message, local, remot p.state = CandidatePairStateSucceeded s.log.Tracef("Found valid candidate pair: %s", p) - if p.nominateOnBindingSuccess { - if selectedPair := s.agent.getSelectedPair(); selectedPair == nil || - (selectedPair != p && selectedPair.priority() <= p.priority()) { - s.agent.setSelectedPair(p) - } else if selectedPair != p { - s.log.Tracef("ignore nominate new pair %s, already nominated pair %s", p, selectedPair) - } - } } func (s *controlledSelector) HandleBindingRequest(m *stun.Message, local, remote Candidate) { useCandidate := m.Contains(stun.AttrUseCandidate) p := s.agent.findPair(local, remote) + if p == nil { p = s.agent.addPair(local, remote) } @@ -258,12 +248,10 @@ func (s *controlledSelector) HandleBindingRequest(m *stun.Message, local, remote // previously sent by this pair produced a successful response and // generated a valid pair (Section 7.2.5.3.2). The agent sets the // nominated flag value of the valid pair to true. - if selectedPair := s.agent.getSelectedPair(); selectedPair == nil || - (selectedPair != p && selectedPair.priority() <= p.priority()) { + if selectedPair := s.agent.getSelectedPair(); selectedPair == nil { s.agent.setSelectedPair(p) - } else if selectedPair != p { - s.log.Tracef("ignore nominate new pair %s, already nominated pair %s", p, selectedPair) } + s.agent.sendBindingSuccess(m, local, remote) } else { // If the received Binding request triggered a new check to be // enqueued in the triggered-check queue (Section 7.3.1.4), once the @@ -273,12 +261,12 @@ func (s *controlledSelector) HandleBindingRequest(m *stun.Message, local, remote // MUST remove the candidate pair from the valid list, set the // candidate pair state to Failed, and set the checklist state to // Failed. - p.nominateOnBindingSuccess = true + s.PingCandidate(local, remote) } + } else { + s.agent.sendBindingSuccess(m, local, remote) + s.PingCandidate(local, remote) } - - s.agent.sendBindingSuccess(m, local, remote) - s.PingCandidate(local, remote) } type liteSelector struct { @@ -288,8 +276,8 @@ type liteSelector struct { // A lite selector should not contact candidates func (s *liteSelector) ContactCandidates() { if _, ok := s.pairCandidateSelector.(*controllingSelector); ok { - //nolint:godox - // https://github.com/pion/ice/issues/96 + // nolint:godox + // pion/ice#96 // TODO: implement lite controlling agent. For now falling back to full agent. // This only happens if both peers are lite. See RFC 8445 S6.1.1 and S6.2 s.pairCandidateSelector.ContactCandidates() diff --git a/vendor/github.com/pion/ice/v2/stats.go b/vendor/github.com/pion/ice/v2/stats.go index 9b83bea85..f59d89ff9 100644 --- a/vendor/github.com/pion/ice/v2/stats.go +++ b/vendor/github.com/pion/ice/v2/stats.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( @@ -107,7 +104,7 @@ type CandidatePairStats struct { // ResponsesReceived represents the total number of connectivity check responses received. ResponsesReceived uint64 - // ResponsesSent represents the total number of connectivity check responses sent. + // ResponsesSent epresents the total number of connectivity check responses sent. // Since we cannot distinguish connectivity check requests and consent requests, // all responses are counted. ResponsesSent uint64 @@ -167,7 +164,7 @@ type CandidateStats struct { // RelayProtocol is the protocol used by the endpoint to communicate with the // TURN server. This is only present for local candidates. Valid values for - // the TURN URL protocol is one of UDP, TCP, or TLS. + // the TURN URL protocol is one of udp, tcp, or tls. RelayProtocol string // Deleted is true if the candidate has been deleted/freed. For host candidates, diff --git a/vendor/github.com/pion/ice/v2/stun.go b/vendor/github.com/pion/ice/v2/stun.go new file mode 100644 index 000000000..bef7c87e5 --- /dev/null +++ b/vendor/github.com/pion/ice/v2/stun.go @@ -0,0 +1,24 @@ +package ice + +import ( + "fmt" + + "github.com/pion/stun" +) + +func assertInboundUsername(m *stun.Message, expectedUsername string) error { + var username stun.Username + if err := username.GetFrom(m); err != nil { + return err + } + if string(username) != expectedUsername { + return fmt.Errorf("%w expected(%x) actual(%x)", errMismatchUsername, expectedUsername, string(username)) + } + + return nil +} + +func assertInboundMessageIntegrity(m *stun.Message, key []byte) error { + messageIntegrityAttr := stun.MessageIntegrity(key) + return messageIntegrityAttr.Check(m) +} diff --git a/vendor/github.com/pion/ice/v2/tcp_mux.go b/vendor/github.com/pion/ice/v2/tcp_mux.go index fb4e5243e..e5da608c9 100644 --- a/vendor/github.com/pion/ice/v2/tcp_mux.go +++ b/vendor/github.com/pion/ice/v2/tcp_mux.go @@ -1,11 +1,7 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( "encoding/binary" - "errors" "io" "net" "strings" @@ -15,19 +11,37 @@ import ( "github.com/pion/stun" ) -// ErrGetTransportAddress can't convert net.Addr to underlying type (UDPAddr or TCPAddr). -var ErrGetTransportAddress = errors.New("failed to get local transport address") - // TCPMux is allows grouping multiple TCP net.Conns and using them like UDP // net.PacketConns. The main implementation of this is TCPMuxDefault, and this -// interface exists to allow mocking in tests. +// interface exists to: +// 1. prevent SEGV panics when TCPMuxDefault is not initialized by using the +// invalidTCPMux implementation, and +// 2. allow mocking in tests. type TCPMux interface { io.Closer - GetConnByUfrag(ufrag string, isIPv6 bool, local net.IP) (net.PacketConn, error) + GetConnByUfrag(ufrag string) (net.PacketConn, error) RemoveConnByUfrag(ufrag string) } -type ipAddr string +// invalidTCPMux is an implementation of TCPMux that always returns ErrTCPMuxNotInitialized. +type invalidTCPMux struct{} + +func newInvalidTCPMux() *invalidTCPMux { + return &invalidTCPMux{} +} + +// Close implements TCPMux interface. +func (m *invalidTCPMux) Close() error { + return ErrTCPMuxNotInitialized +} + +// GetConnByUfrag implements TCPMux interface. +func (m *invalidTCPMux) GetConnByUfrag(ufrag string) (net.PacketConn, error) { + return nil, ErrTCPMuxNotInitialized +} + +// RemoveConnByUfrag implements TCPMux interface. +func (m *invalidTCPMux) RemoveConnByUfrag(ufrag string) {} // TCPMuxDefault muxes TCP net.Conns into net.PacketConns and groups them by // Ufrag. It is a default implementation of TCPMux interface. @@ -35,8 +49,8 @@ type TCPMuxDefault struct { params *TCPMuxParams closed bool - // connsIPv4 and connsIPv6 are maps of all tcpPacketConns indexed by ufrag and local address - connsIPv4, connsIPv6 map[string]map[ipAddr]*tcpPacketConn + // conns is a map of all tcpPacketConns indexed by ufrag + conns map[string]*tcpPacketConn mu sync.Mutex wg sync.WaitGroup @@ -47,11 +61,6 @@ type TCPMuxParams struct { Listener net.Listener Logger logging.LeveledLogger ReadBufferSize int - - // Maximum buffer size for write op. 0 means no write buffer, the write op will block until the whole packet is written - // if the write buffer is full, the subsequent write packet will be dropped until it has enough space. - // a default 4MB is recommended. - WriteBufferSize int } // NewTCPMuxDefault creates a new instance of TCPMuxDefault. @@ -63,8 +72,7 @@ func NewTCPMuxDefault(params TCPMuxParams) *TCPMuxDefault { m := &TCPMuxDefault{ params: ¶ms, - connsIPv4: map[string]map[ipAddr]*tcpPacketConn{}, - connsIPv6: map[string]map[ipAddr]*tcpPacketConn{}, + conns: map[string]*tcpPacketConn{}, } m.wg.Add(1) @@ -77,11 +85,11 @@ func NewTCPMuxDefault(params TCPMuxParams) *TCPMuxDefault { } func (m *TCPMuxDefault) start() { - m.params.Logger.Infof("Listening TCP on %s", m.params.Listener.Addr()) + m.params.Logger.Infof("Listening TCP on %s\n", m.params.Listener.Addr()) for { conn, err := m.params.Listener.Accept() if err != nil { - m.params.Logger.Infof("Error accepting connection: %s", err) + m.params.Logger.Infof("Error accepting connection: %s\n", err) return } @@ -101,7 +109,7 @@ func (m *TCPMuxDefault) LocalAddr() net.Addr { } // GetConnByUfrag retrieves an existing or creates a new net.PacketConn. -func (m *TCPMuxDefault) GetConnByUfrag(ufrag string, isIPv6 bool, local net.IP) (net.PacketConn, error) { +func (m *TCPMuxDefault) GetConnByUfrag(ufrag string) (net.PacketConn, error) { m.mu.Lock() defer m.mu.Unlock() @@ -109,50 +117,34 @@ func (m *TCPMuxDefault) GetConnByUfrag(ufrag string, isIPv6 bool, local net.IP) return nil, io.ErrClosedPipe } - if conn, ok := m.getConn(ufrag, isIPv6, local); ok { + conn, ok := m.conns[ufrag] + + if ok { return conn, nil + // return nil, fmt.Errorf("duplicate ufrag %v", ufrag) } - return m.createConn(ufrag, isIPv6, local) + conn = m.createConn(ufrag, m.LocalAddr()) + + return conn, nil } -func (m *TCPMuxDefault) createConn(ufrag string, isIPv6 bool, local net.IP) (*tcpPacketConn, error) { - addr, ok := m.LocalAddr().(*net.TCPAddr) - if !ok { - return nil, ErrGetTransportAddress - } - localAddr := *addr - localAddr.IP = local - +func (m *TCPMuxDefault) createConn(ufrag string, localAddr net.Addr) *tcpPacketConn { conn := newTCPPacketConn(tcpPacketParams{ - ReadBuffer: m.params.ReadBufferSize, - WriteBuffer: m.params.WriteBufferSize, - LocalAddr: &localAddr, - Logger: m.params.Logger, + ReadBuffer: m.params.ReadBufferSize, + LocalAddr: localAddr, + Logger: m.params.Logger, }) - - var conns map[ipAddr]*tcpPacketConn - if isIPv6 { - if conns, ok = m.connsIPv6[ufrag]; !ok { - conns = make(map[ipAddr]*tcpPacketConn) - m.connsIPv6[ufrag] = conns - } - } else { - if conns, ok = m.connsIPv4[ufrag]; !ok { - conns = make(map[ipAddr]*tcpPacketConn) - m.connsIPv4[ufrag] = conns - } - } - conns[ipAddr(local.String())] = conn + m.conns[ufrag] = conn m.wg.Add(1) go func() { defer m.wg.Done() <-conn.CloseChannel() - m.removeConnByUfragAndLocalHost(ufrag, local) + m.RemoveConnByUfrag(ufrag) }() - return conn, nil + return conn } func (m *TCPMuxDefault) closeAndLogError(closer io.Closer) { @@ -180,61 +172,41 @@ func (m *TCPMuxDefault) handleConn(conn net.Conn) { copy(msg.Raw, buf) if err = msg.Decode(); err != nil { m.closeAndLogError(conn) - m.params.Logger.Warnf("Failed to handle decode ICE from %s to %s: %v", conn.RemoteAddr(), conn.LocalAddr(), err) + m.params.Logger.Warnf("Failed to handle decode ICE from %s to %s: %v\n", conn.RemoteAddr(), conn.LocalAddr(), err) return } - if m == nil || msg.Type.Method != stun.MethodBinding { // Not a STUN + if m == nil || msg.Type.Method != stun.MethodBinding { // not a stun m.closeAndLogError(conn) - m.params.Logger.Warnf("Not a STUN message from %s to %s", conn.RemoteAddr(), conn.LocalAddr()) + m.params.Logger.Warnf("Not a STUN message from %s to %s\n", conn.RemoteAddr(), conn.LocalAddr()) return } for _, attr := range msg.Attributes { - m.params.Logger.Debugf("msg attr: %s", attr.String()) + m.params.Logger.Debugf("msg attr: %s\n", attr.String()) } attr, err := msg.Get(stun.AttrUsername) if err != nil { m.closeAndLogError(conn) - m.params.Logger.Warnf("No Username attribute in STUN message from %s to %s", conn.RemoteAddr(), conn.LocalAddr()) + m.params.Logger.Warnf("No Username attribute in STUN message from %s to %s\n", conn.RemoteAddr(), conn.LocalAddr()) return } ufrag := strings.Split(string(attr), ":")[0] - m.params.Logger.Debugf("Ufrag: %s", ufrag) + m.params.Logger.Debugf("Ufrag: %s\n", ufrag) m.mu.Lock() defer m.mu.Unlock() - host, _, err := net.SplitHostPort(conn.RemoteAddr().String()) - if err != nil { - m.closeAndLogError(conn) - m.params.Logger.Warnf("Failed to get host in STUN message from %s to %s", conn.RemoteAddr(), conn.LocalAddr()) - return - } - - isIPv6 := net.ParseIP(host).To4() == nil - - localAddr, ok := conn.LocalAddr().(*net.TCPAddr) + packetConn, ok := m.conns[ufrag] if !ok { - m.closeAndLogError(conn) - m.params.Logger.Warnf("Failed to get local tcp address in STUN message from %s to %s", conn.RemoteAddr(), conn.LocalAddr()) - return - } - packetConn, ok := m.getConn(ufrag, isIPv6, localAddr.IP) - if !ok { - packetConn, err = m.createConn(ufrag, isIPv6, localAddr.IP) - if err != nil { - m.closeAndLogError(conn) - m.params.Logger.Warnf("Failed to create packetConn for STUN message from %s to %s", conn.RemoteAddr(), conn.LocalAddr()) - return - } + packetConn = m.createConn(ufrag, conn.LocalAddr()) } if err := packetConn.AddConn(conn, buf); err != nil { m.closeAndLogError(conn) - m.params.Logger.Warnf("Error adding conn to tcpPacketConn from %s to %s: %s", conn.RemoteAddr(), conn.LocalAddr(), err) + m.params.Logger.Warnf("Error adding conn to tcpPacketConn from %s to %s: %s\n", conn.RemoteAddr(), conn.LocalAddr(), err) return } } @@ -244,19 +216,10 @@ func (m *TCPMuxDefault) Close() error { m.mu.Lock() m.closed = true - for _, conns := range m.connsIPv4 { - for _, conn := range conns { - m.closeAndLogError(conn) - } + for _, conn := range m.conns { + m.closeAndLogError(conn) } - for _, conns := range m.connsIPv6 { - for _, conn := range conns { - m.closeAndLogError(conn) - } - } - - m.connsIPv4 = map[string]map[ipAddr]*tcpPacketConn{} - m.connsIPv6 = map[string]map[ipAddr]*tcpPacketConn{} + m.conns = map[string]*tcpPacketConn{} err := m.params.Listener.Close() @@ -269,90 +232,25 @@ func (m *TCPMuxDefault) Close() error { // RemoveConnByUfrag closes and removes a net.PacketConn by Ufrag. func (m *TCPMuxDefault) RemoveConnByUfrag(ufrag string) { - removedConns := make([]*tcpPacketConn, 0, 4) - - // Keep lock section small to avoid deadlock with conn lock m.mu.Lock() - if conns, ok := m.connsIPv4[ufrag]; ok { - delete(m.connsIPv4, ufrag) - for _, conn := range conns { - removedConns = append(removedConns, conn) - } - } - if conns, ok := m.connsIPv6[ufrag]; ok { - delete(m.connsIPv6, ufrag) - for _, conn := range conns { - removedConns = append(removedConns, conn) - } - } + defer m.mu.Unlock() - m.mu.Unlock() - - // Close the connections outside the critical section to avoid - // deadlocking TCP mux if (*tcpPacketConn).Close() blocks. - for _, conn := range removedConns { + if conn, ok := m.conns[ufrag]; ok { m.closeAndLogError(conn) + delete(m.conns, ufrag) } } -func (m *TCPMuxDefault) removeConnByUfragAndLocalHost(ufrag string, local net.IP) { - removedConns := make([]*tcpPacketConn, 0, 4) - - localIP := ipAddr(local.String()) - // Keep lock section small to avoid deadlock with conn lock - m.mu.Lock() - if conns, ok := m.connsIPv4[ufrag]; ok { - if conn, ok := conns[localIP]; ok { - delete(conns, localIP) - if len(conns) == 0 { - delete(m.connsIPv4, ufrag) - } - removedConns = append(removedConns, conn) - } - } - if conns, ok := m.connsIPv6[ufrag]; ok { - if conn, ok := conns[localIP]; ok { - delete(conns, localIP) - if len(conns) == 0 { - delete(m.connsIPv6, ufrag) - } - removedConns = append(removedConns, conn) - } - } - m.mu.Unlock() - - // Close the connections outside the critical section to avoid - // deadlocking TCP mux if (*tcpPacketConn).Close() blocks. - for _, conn := range removedConns { - m.closeAndLogError(conn) - } -} - -func (m *TCPMuxDefault) getConn(ufrag string, isIPv6 bool, local net.IP) (val *tcpPacketConn, ok bool) { - var conns map[ipAddr]*tcpPacketConn - if isIPv6 { - conns, ok = m.connsIPv6[ufrag] - } else { - conns, ok = m.connsIPv4[ufrag] - } - if conns != nil { - val, ok = conns[ipAddr(local.String())] - } - - return -} - const streamingPacketHeaderLen = 2 // readStreamingPacket reads 1 packet from stream // read packet bytes https://tools.ietf.org/html/rfc4571#section-2 // 2-byte length header prepends each packet: -// -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -// ----------------------------------------------------------------- -// | LENGTH | RTP or RTCP packet ... | -// ----------------------------------------------------------------- +// 0 1 2 3 +// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +// ----------------------------------------------------------------- +// | LENGTH | RTP or RTCP packet ... | +// ----------------------------------------------------------------- func readStreamingPacket(conn net.Conn, buf []byte) (int, error) { header := make([]byte, streamingPacketHeaderLen) var bytesRead, n int @@ -383,11 +281,11 @@ func readStreamingPacket(conn net.Conn, buf []byte) (int, error) { } func writeStreamingPacket(conn net.Conn, buf []byte) (int, error) { - bufCopy := make([]byte, streamingPacketHeaderLen+len(buf)) - binary.BigEndian.PutUint16(bufCopy, uint16(len(buf))) - copy(bufCopy[2:], buf) + bufferCopy := make([]byte, streamingPacketHeaderLen+len(buf)) + binary.BigEndian.PutUint16(bufferCopy, uint16(len(buf))) + copy(bufferCopy[2:], buf) - n, err := conn.Write(bufCopy) + n, err := conn.Write(bufferCopy) if err != nil { return 0, err } diff --git a/vendor/github.com/pion/ice/v2/tcp_mux_multi.go b/vendor/github.com/pion/ice/v2/tcp_mux_multi.go deleted file mode 100644 index e32acbf3e..000000000 --- a/vendor/github.com/pion/ice/v2/tcp_mux_multi.go +++ /dev/null @@ -1,81 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package ice - -import "net" - -// AllConnsGetter allows multiple fixed TCP ports to be used, -// each of which is multiplexed like TCPMux. AllConnsGetter also acts as -// a TCPMux, in which case it will return a single connection for one -// of the ports. -type AllConnsGetter interface { - GetAllConns(ufrag string, isIPv6 bool, localIP net.IP) ([]net.PacketConn, error) -} - -// MultiTCPMuxDefault implements both TCPMux and AllConnsGetter, -// allowing users to pass multiple TCPMux instances to the ICE agent -// configuration. -type MultiTCPMuxDefault struct { - muxes []TCPMux -} - -// NewMultiTCPMuxDefault creates an instance of MultiTCPMuxDefault that -// uses the provided TCPMux instances. -func NewMultiTCPMuxDefault(muxes ...TCPMux) *MultiTCPMuxDefault { - return &MultiTCPMuxDefault{ - muxes: muxes, - } -} - -// GetConnByUfrag returns a PacketConn given the connection's ufrag, network and local address -// creates the connection if an existing one can't be found. This, unlike -// GetAllConns, will only return a single PacketConn from the first mux that was -// passed in to NewMultiTCPMuxDefault. -func (m *MultiTCPMuxDefault) GetConnByUfrag(ufrag string, isIPv6 bool, local net.IP) (net.PacketConn, error) { - // NOTE: We always use the first element here in order to maintain the - // behavior of using an existing connection if one exists. - if len(m.muxes) == 0 { - return nil, errNoTCPMuxAvailable - } - return m.muxes[0].GetConnByUfrag(ufrag, isIPv6, local) -} - -// RemoveConnByUfrag stops and removes the muxed packet connection -// from all underlying TCPMux instances. -func (m *MultiTCPMuxDefault) RemoveConnByUfrag(ufrag string) { - for _, mux := range m.muxes { - mux.RemoveConnByUfrag(ufrag) - } -} - -// GetAllConns returns a PacketConn for each underlying TCPMux -func (m *MultiTCPMuxDefault) GetAllConns(ufrag string, isIPv6 bool, local net.IP) ([]net.PacketConn, error) { - if len(m.muxes) == 0 { - // Make sure that we either return at least one connection or an error. - return nil, errNoTCPMuxAvailable - } - var conns []net.PacketConn - for _, mux := range m.muxes { - conn, err := mux.GetConnByUfrag(ufrag, isIPv6, local) - if err != nil { - // For now, this implementation is all or none. - return nil, err - } - if conn != nil { - conns = append(conns, conn) - } - } - return conns, nil -} - -// Close the multi mux, no further connections could be created -func (m *MultiTCPMuxDefault) Close() error { - var err error - for _, mux := range m.muxes { - if e := mux.Close(); e != nil { - err = e - } - } - return err -} diff --git a/vendor/github.com/pion/ice/v2/tcp_packet_conn.go b/vendor/github.com/pion/ice/v2/tcp_packet_conn.go index 8c51fd1cc..dc4eaf04f 100644 --- a/vendor/github.com/pion/ice/v2/tcp_packet_conn.go +++ b/vendor/github.com/pion/ice/v2/tcp_packet_conn.go @@ -1,78 +1,15 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( - "errors" "fmt" "io" "net" "sync" - "sync/atomic" "time" "github.com/pion/logging" - "github.com/pion/transport/v2/packetio" ) -type bufferedConn struct { - net.Conn - buf *packetio.Buffer - logger logging.LeveledLogger - closed int32 -} - -func newBufferedConn(conn net.Conn, bufSize int, logger logging.LeveledLogger) net.Conn { - buf := packetio.NewBuffer() - if bufSize > 0 { - buf.SetLimitSize(bufSize) - } - - bc := &bufferedConn{ - Conn: conn, - buf: buf, - logger: logger, - } - - go bc.writeProcess() - return bc -} - -func (bc *bufferedConn) Write(b []byte) (int, error) { - n, err := bc.buf.Write(b) - if err != nil { - return n, err - } - return n, nil -} - -func (bc *bufferedConn) writeProcess() { - pktBuf := make([]byte, receiveMTU) - for atomic.LoadInt32(&bc.closed) == 0 { - n, err := bc.buf.Read(pktBuf) - if errors.Is(err, io.EOF) { - return - } - - if err != nil { - bc.logger.Warnf("read buffer error: %s", err) - continue - } - - if _, err := bc.Conn.Write(pktBuf[:n]); err != nil { - bc.logger.Warnf("write error: %s", err) - continue - } - } -} - -func (bc *bufferedConn) Close() error { - atomic.StoreInt32(&bc.closed, 1) - _ = bc.buf.Close() - return bc.Conn.Close() -} - type tcpPacketConn struct { params *tcpPacketParams @@ -94,10 +31,9 @@ type streamingPacket struct { } type tcpPacketParams struct { - ReadBuffer int - LocalAddr net.Addr - Logger logging.LeveledLogger - WriteBuffer int + ReadBuffer int + LocalAddr net.Addr + Logger logging.LeveledLogger } func newTCPPacketConn(params tcpPacketParams) *tcpPacketConn { @@ -114,7 +50,7 @@ func newTCPPacketConn(params tcpPacketParams) *tcpPacketConn { } func (t *tcpPacketConn) AddConn(conn net.Conn, firstPacketData []byte) error { - t.params.Logger.Infof("AddConn: %s remote %s to local %s", conn.RemoteAddr().Network(), conn.RemoteAddr(), conn.LocalAddr()) + t.params.Logger.Infof("AddConn: %s %s", conn.RemoteAddr().Network(), conn.RemoteAddr()) t.mu.Lock() defer t.mu.Unlock() @@ -129,25 +65,14 @@ func (t *tcpPacketConn) AddConn(conn net.Conn, firstPacketData []byte) error { return fmt.Errorf("%w: %s", errConnectionAddrAlreadyExist, conn.RemoteAddr().String()) } - if t.params.WriteBuffer > 0 { - conn = newBufferedConn(conn, t.params.WriteBuffer, t.params.Logger) - } t.conns[conn.RemoteAddr().String()] = conn t.wg.Add(1) go func() { - defer t.wg.Done() if firstPacketData != nil { - select { - case <-t.closedChan: - // NOTE: recvChan can fill up and never drain in edge - // cases while closing a connection, which can cause the - // packetConn to never finish closing. Bail out early - // here to prevent that. - return - case t.recvChan <- streamingPacket{firstPacketData, conn.RemoteAddr(), nil}: - } + t.recvChan <- streamingPacket{firstPacketData, conn.RemoteAddr(), nil} } + defer t.wg.Done() t.startReading(conn) }() @@ -159,8 +84,9 @@ func (t *tcpPacketConn) startReading(conn net.Conn) { for { n, err := readStreamingPacket(conn, buf) + // t.params.Logger.Infof("readStreamingPacket read %d bytes", n) if err != nil { - t.params.Logger.Infof("%v: %s", errReadingStreamingPacket, err) + t.params.Logger.Infof("%w: %s\n", errReadingStreamingPacket, err) t.handleRecv(streamingPacket{nil, conn.RemoteAddr(), err}) t.removeConn(conn) return @@ -169,6 +95,7 @@ func (t *tcpPacketConn) startReading(conn net.Conn) { data := make([]byte, n) copy(data, buf[:n]) + // t.params.Logger.Infof("Writing read streaming packet to recvChan: %d bytes", len(data)) t.handleRecv(streamingPacket{data, conn.RemoteAddr(), nil}) } } @@ -199,7 +126,7 @@ func (t *tcpPacketConn) isClosed() bool { } // WriteTo is for passive and s-o candidates. -func (t *tcpPacketConn) ReadFrom(b []byte) (n int, rAddr net.Addr, err error) { +func (t *tcpPacketConn) ReadFrom(b []byte) (n int, raddr net.Addr, err error) { pkt, ok := <-t.recvChan if !ok { @@ -220,18 +147,27 @@ func (t *tcpPacketConn) ReadFrom(b []byte) (n int, rAddr net.Addr, err error) { } // WriteTo is for active and s-o candidates. -func (t *tcpPacketConn) WriteTo(buf []byte, rAddr net.Addr) (n int, err error) { +func (t *tcpPacketConn) WriteTo(buf []byte, raddr net.Addr) (n int, err error) { t.mu.Lock() - conn, ok := t.conns[rAddr.String()] - t.mu.Unlock() + defer t.mu.Unlock() + conn, ok := t.conns[raddr.String()] if !ok { return 0, io.ErrClosedPipe + // conn, err := net.DialTCP(tcp, nil, raddr.(*net.TCPAddr)) + + // if err != nil { + // t.params.Logger.Tracef("DialTCP error: %s", err) + // return 0, err + // } + + // go t.startReading(conn) + // t.conns[raddr.String()] = conn } n, err = writeStreamingPacket(conn, buf) if err != nil { - t.params.Logger.Tracef("%w %s", errWriting, rAddr) + t.params.Logger.Tracef("%w %s\n", errWriting, raddr) return n, err } @@ -241,7 +177,7 @@ func (t *tcpPacketConn) WriteTo(buf []byte, rAddr net.Addr) (n int, err error) { func (t *tcpPacketConn) closeAndLogError(closer io.Closer) { err := closer.Close() if err != nil { - t.params.Logger.Warnf("%v: %s", errClosingConnection, err) + t.params.Logger.Warnf("%w: %s", errClosingConnection, err) } } @@ -283,15 +219,15 @@ func (t *tcpPacketConn) LocalAddr() net.Addr { return t.params.LocalAddr } -func (t *tcpPacketConn) SetDeadline(time.Time) error { +func (t *tcpPacketConn) SetDeadline(tm time.Time) error { return nil } -func (t *tcpPacketConn) SetReadDeadline(time.Time) error { +func (t *tcpPacketConn) SetReadDeadline(tm time.Time) error { return nil } -func (t *tcpPacketConn) SetWriteDeadline(time.Time) error { +func (t *tcpPacketConn) SetWriteDeadline(tm time.Time) error { return nil } diff --git a/vendor/github.com/pion/ice/v2/tcptype.go b/vendor/github.com/pion/ice/v2/tcptype.go index e500e57f5..6700fe5ff 100644 --- a/vendor/github.com/pion/ice/v2/tcptype.go +++ b/vendor/github.com/pion/ice/v2/tcptype.go @@ -1,12 +1,9 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import "strings" // TCPType is the type of ICE TCP candidate as described in -// https://tools.ietf.org/html/rfc6544#section-4.5 +// ttps://tools.ietf.org/html/rfc6544#section-4.5 type TCPType int const ( diff --git a/vendor/github.com/pion/ice/v2/test_utils.go b/vendor/github.com/pion/ice/v2/test_utils.go deleted file mode 100644 index 235fda315..000000000 --- a/vendor/github.com/pion/ice/v2/test_utils.go +++ /dev/null @@ -1,79 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -//go:build !js -// +build !js - -package ice - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func newHostRemote(t *testing.T) *CandidateHost { - remoteHostConfig := &CandidateHostConfig{ - Network: "udp", - Address: "1.2.3.5", - Port: 12350, - Component: 1, - } - hostRemote, err := NewCandidateHost(remoteHostConfig) - require.NoError(t, err) - return hostRemote -} - -func newPrflxRemote(t *testing.T) *CandidatePeerReflexive { - prflxConfig := &CandidatePeerReflexiveConfig{ - Network: "udp", - Address: "10.10.10.2", - Port: 19217, - Component: 1, - RelAddr: "4.3.2.1", - RelPort: 43211, - } - prflxRemote, err := NewCandidatePeerReflexive(prflxConfig) - require.NoError(t, err) - return prflxRemote -} - -func newSrflxRemote(t *testing.T) *CandidateServerReflexive { - srflxConfig := &CandidateServerReflexiveConfig{ - Network: "udp", - Address: "10.10.10.2", - Port: 19218, - Component: 1, - RelAddr: "4.3.2.1", - RelPort: 43212, - } - srflxRemote, err := NewCandidateServerReflexive(srflxConfig) - require.NoError(t, err) - return srflxRemote -} - -func newRelayRemote(t *testing.T) *CandidateRelay { - relayConfig := &CandidateRelayConfig{ - Network: "udp", - Address: "1.2.3.4", - Port: 12340, - Component: 1, - RelAddr: "4.3.2.1", - RelPort: 43210, - } - relayRemote, err := NewCandidateRelay(relayConfig) - require.NoError(t, err) - return relayRemote -} - -func newHostLocal(t *testing.T) *CandidateHost { - localHostConfig := &CandidateHostConfig{ - Network: "udp", - Address: "192.168.1.1", - Port: 19216, - Component: 1, - } - hostLocal, err := NewCandidateHost(localHostConfig) - require.NoError(t, err) - return hostLocal -} diff --git a/vendor/github.com/pion/ice/v2/transport.go b/vendor/github.com/pion/ice/v2/transport.go index cd37a9b26..6d9aaffad 100644 --- a/vendor/github.com/pion/ice/v2/transport.go +++ b/vendor/github.com/pion/ice/v2/transport.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( @@ -47,12 +44,12 @@ func (a *Agent) connect(ctx context.Context, isControlling bool, remoteUfrag, re if err != nil { return nil, err } - err = a.startConnectivityChecks(isControlling, remoteUfrag, remotePwd) //nolint:contextcheck + err = a.startConnectivityChecks(isControlling, remoteUfrag, remotePwd) if err != nil { return nil, err } - // Block until pair selected + // block until pair selected select { case <-a.done: return nil, a.getErr() @@ -73,7 +70,7 @@ func (c *Conn) Read(p []byte) (int, error) { return 0, err } - n, err := c.agent.buf.Read(p) + n, err := c.agent.buffer.Read(p) atomic.AddUint64(&c.bytesReceived, uint64(n)) return n, err } @@ -133,16 +130,16 @@ func (c *Conn) RemoteAddr() net.Addr { } // SetDeadline is a stub -func (c *Conn) SetDeadline(time.Time) error { +func (c *Conn) SetDeadline(t time.Time) error { return nil } // SetReadDeadline is a stub -func (c *Conn) SetReadDeadline(time.Time) error { +func (c *Conn) SetReadDeadline(t time.Time) error { return nil } // SetWriteDeadline is a stub -func (c *Conn) SetWriteDeadline(time.Time) error { +func (c *Conn) SetWriteDeadline(t time.Time) error { return nil } diff --git a/vendor/github.com/pion/ice/v2/udp_mux.go b/vendor/github.com/pion/ice/v2/udp_mux.go index 405bb7b1a..0bbe3b5cc 100644 --- a/vendor/github.com/pion/ice/v2/udp_mux.go +++ b/vendor/github.com/pion/ice/v2/udp_mux.go @@ -1,10 +1,6 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( - "errors" "io" "net" "os" @@ -13,16 +9,13 @@ import ( "github.com/pion/logging" "github.com/pion/stun" - "github.com/pion/transport/v2" - "github.com/pion/transport/v2/stdnet" ) // UDPMux allows multiple connections to go over a single UDP port type UDPMux interface { io.Closer - GetConn(ufrag string, addr net.Addr) (net.PacketConn, error) + GetConn(ufrag string) (net.PacketConn, error) RemoveConnByUfrag(ufrag string) - GetListenAddresses() []net.Addr } // UDPMuxDefault is an implementation of the interface @@ -32,19 +25,16 @@ type UDPMuxDefault struct { closedChan chan struct{} closeOnce sync.Once - // connsIPv4 and connsIPv6 are maps of all udpMuxedConn indexed by ufrag|network|candidateType - connsIPv4, connsIPv6 map[string]*udpMuxedConn + // conns is a map of all udpMuxedConn indexed by ufrag|network|candidateType + conns map[string]*udpMuxedConn addressMapMu sync.RWMutex addressMap map[string]*udpMuxedConn - // Buffer pool to recycle buffers for net.UDPAddr encodes/decodes + // buffer pool to recycle buffers for net.UDPAddr encodes/decodes pool *sync.Pool mu sync.Mutex - - // For UDP connection listen at unspecified address - localAddrsForUnspecified []net.Addr } const maxAddrSize = 512 @@ -53,11 +43,6 @@ const maxAddrSize = 512 type UDPMuxParams struct { Logger logging.LeveledLogger UDPConn net.PacketConn - - // Required for gathering local addresses - // in case a un UDPConn is passed which does not - // bind to a specific local address. - Net transport.Net } // NewUDPMuxDefault creates an implementation of UDPMux @@ -66,57 +51,17 @@ func NewUDPMuxDefault(params UDPMuxParams) *UDPMuxDefault { params.Logger = logging.NewDefaultLoggerFactory().NewLogger("ice") } - var localAddrsForUnspecified []net.Addr - if addr, ok := params.UDPConn.LocalAddr().(*net.UDPAddr); !ok { - params.Logger.Errorf("LocalAddr is not a net.UDPAddr, got %T", params.UDPConn.LocalAddr()) - } else if ok && addr.IP.IsUnspecified() { - // For unspecified addresses, the correct behavior is to return errListenUnspecified, but - // it will break the applications that are already using unspecified UDP connection - // with UDPMuxDefault, so print a warn log and create a local address list for mux. - params.Logger.Warn("UDPMuxDefault should not listening on unspecified address, use NewMultiUDPMuxFromPort instead") - var networks []NetworkType - switch { - case addr.IP.To4() != nil: - networks = []NetworkType{NetworkTypeUDP4} - - case addr.IP.To16() != nil: - networks = []NetworkType{NetworkTypeUDP4, NetworkTypeUDP6} - - default: - params.Logger.Errorf("LocalAddr expected IPV4 or IPV6, got %T", params.UDPConn.LocalAddr()) - } - if len(networks) > 0 { - if params.Net == nil { - var err error - if params.Net, err = stdnet.NewNet(); err != nil { - params.Logger.Errorf("failed to get create network: %v", err) - } - } - - ips, err := localInterfaces(params.Net, nil, nil, networks, true) - if err == nil { - for _, ip := range ips { - localAddrsForUnspecified = append(localAddrsForUnspecified, &net.UDPAddr{IP: ip, Port: addr.Port}) - } - } else { - params.Logger.Errorf("failed to get local interfaces for unspecified addr: %v", err) - } - } - } - m := &UDPMuxDefault{ addressMap: map[string]*udpMuxedConn{}, params: params, - connsIPv4: make(map[string]*udpMuxedConn), - connsIPv6: make(map[string]*udpMuxedConn), + conns: make(map[string]*udpMuxedConn), closedChan: make(chan struct{}, 1), pool: &sync.Pool{ New: func() interface{} { - // Big enough buffer to fit both packet and address + // big enough buffer to fit both packet and address return newBufferHolder(receiveMTU + maxAddrSize) }, }, - localAddrsForUnspecified: localAddrsForUnspecified, } go m.connWorker() @@ -129,27 +74,9 @@ func (m *UDPMuxDefault) LocalAddr() net.Addr { return m.params.UDPConn.LocalAddr() } -// GetListenAddresses returns the list of addresses that this mux is listening on -func (m *UDPMuxDefault) GetListenAddresses() []net.Addr { - if len(m.localAddrsForUnspecified) > 0 { - return m.localAddrsForUnspecified - } - - return []net.Addr{m.LocalAddr()} -} - -// GetConn returns a PacketConn given the connection's ufrag and network address +// GetConn returns a PacketConn given the connection's ufrag and network // creates the connection if an existing one can't be found -func (m *UDPMuxDefault) GetConn(ufrag string, addr net.Addr) (net.PacketConn, error) { - // don't check addr for mux using unspecified address - if len(m.localAddrsForUnspecified) == 0 && m.params.UDPConn.LocalAddr().String() != addr.String() { - return nil, errInvalidAddress - } - - var isIPv6 bool - if udpAddr, _ := addr.(*net.UDPAddr); udpAddr != nil && udpAddr.IP.To4() == nil { - isIPv6 = true - } +func (m *UDPMuxDefault) GetConn(ufrag string) (net.PacketConn, error) { m.mu.Lock() defer m.mu.Unlock() @@ -157,45 +84,36 @@ func (m *UDPMuxDefault) GetConn(ufrag string, addr net.Addr) (net.PacketConn, er return nil, io.ErrClosedPipe } - if conn, ok := m.getConn(ufrag, isIPv6); ok { - return conn, nil + if c, ok := m.conns[ufrag]; ok { + return c, nil } c := m.createMuxedConn(ufrag) go func() { <-c.CloseChannel() - m.RemoveConnByUfrag(ufrag) + m.removeConn(ufrag) }() - - if isIPv6 { - m.connsIPv6[ufrag] = c - } else { - m.connsIPv4[ufrag] = c - } - + m.conns[ufrag] = c return c, nil } // RemoveConnByUfrag stops and removes the muxed packet connection func (m *UDPMuxDefault) RemoveConnByUfrag(ufrag string) { - removedConns := make([]*udpMuxedConn, 0, 2) - - // Keep lock section small to avoid deadlock with conn lock m.mu.Lock() - if c, ok := m.connsIPv4[ufrag]; ok { - delete(m.connsIPv4, ufrag) - removedConns = append(removedConns, c) - } - if c, ok := m.connsIPv6[ufrag]; ok { - delete(m.connsIPv6, ufrag) - removedConns = append(removedConns, c) - } - m.mu.Unlock() + removedConns := make([]*udpMuxedConn, 0) + for key := range m.conns { + if key != ufrag { + continue + } - if len(removedConns) == 0 { - // No need to lock if no connection was found - return + c := m.conns[key] + delete(m.conns, key) + if c != nil { + removedConns = append(removedConns, c) + } } + // keep lock section small to avoid deadlock with conn lock + m.mu.Unlock() m.addressMapMu.Lock() defer m.addressMapMu.Unlock() @@ -225,25 +143,37 @@ func (m *UDPMuxDefault) Close() error { m.mu.Lock() defer m.mu.Unlock() - for _, c := range m.connsIPv4 { + for _, c := range m.conns { _ = c.Close() } - for _, c := range m.connsIPv6 { - _ = c.Close() - } - - m.connsIPv4 = make(map[string]*udpMuxedConn) - m.connsIPv6 = make(map[string]*udpMuxedConn) - + m.conns = make(map[string]*udpMuxedConn) close(m.closedChan) - - _ = m.params.UDPConn.Close() }) return err } -func (m *UDPMuxDefault) writeTo(buf []byte, rAddr net.Addr) (n int, err error) { - return m.params.UDPConn.WriteTo(buf, rAddr) +func (m *UDPMuxDefault) removeConn(key string) { + m.mu.Lock() + c := m.conns[key] + delete(m.conns, key) + // keep lock section small to avoid deadlock with conn lock + m.mu.Unlock() + + if c == nil { + return + } + + m.addressMapMu.Lock() + defer m.addressMapMu.Unlock() + + addresses := c.getAddresses() + for _, addr := range addresses { + delete(m.addressMap, addr) + } +} + +func (m *UDPMuxDefault) writeTo(buf []byte, raddr net.Addr) (n int, err error) { + return m.params.UDPConn.WriteTo(buf, raddr) } func (m *UDPMuxDefault) registerConnForAddress(conn *udpMuxedConn, addr string) { @@ -289,7 +219,7 @@ func (m *UDPMuxDefault) connWorker() { } else if err != nil { if os.IsTimeout(err) { continue - } else if !errors.Is(err, io.EOF) { + } else if err != io.EOF { logger.Errorf("could not read udp packet: %v", err) } @@ -314,21 +244,20 @@ func (m *UDPMuxDefault) connWorker() { } if err = msg.Decode(); err != nil { - m.params.Logger.Warnf("Failed to handle decode ICE from %s: %v", addr.String(), err) + m.params.Logger.Warnf("Failed to handle decode ICE from %s: %v\n", addr.String(), err) continue } attr, stunAttrErr := msg.Get(stun.AttrUsername) if stunAttrErr != nil { - m.params.Logger.Warnf("No Username attribute in STUN message from %s", addr.String()) + m.params.Logger.Warnf("No Username attribute in STUN message from %s\n", addr.String()) continue } ufrag := strings.Split(string(attr), ":")[0] - isIPv6 := udpAddr.IP.To4() == nil m.mu.Lock() - destinationConn, _ = m.getConn(ufrag, isIPv6) + destinationConn = m.conns[ufrag] m.mu.Unlock() } @@ -343,21 +272,12 @@ func (m *UDPMuxDefault) connWorker() { } } -func (m *UDPMuxDefault) getConn(ufrag string, isIPv6 bool) (val *udpMuxedConn, ok bool) { - if isIPv6 { - val, ok = m.connsIPv6[ufrag] - } else { - val, ok = m.connsIPv4[ufrag] - } - return -} - type bufferHolder struct { - buf []byte + buffer []byte } func newBufferHolder(size int) *bufferHolder { return &bufferHolder{ - buf: make([]byte, size), + buffer: make([]byte, size), } } diff --git a/vendor/github.com/pion/ice/v2/udp_mux_multi.go b/vendor/github.com/pion/ice/v2/udp_mux_multi.go deleted file mode 100644 index 158cbc37f..000000000 --- a/vendor/github.com/pion/ice/v2/udp_mux_multi.go +++ /dev/null @@ -1,228 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package ice - -import ( - "fmt" - "net" - - "github.com/pion/logging" - "github.com/pion/transport/v2" - "github.com/pion/transport/v2/stdnet" -) - -// MultiUDPMuxDefault implements both UDPMux and AllConnsGetter, -// allowing users to pass multiple UDPMux instances to the ICE agent -// configuration. -type MultiUDPMuxDefault struct { - muxes []UDPMux - localAddrToMux map[string]UDPMux -} - -// NewMultiUDPMuxDefault creates an instance of MultiUDPMuxDefault that -// uses the provided UDPMux instances. -func NewMultiUDPMuxDefault(muxes ...UDPMux) *MultiUDPMuxDefault { - addrToMux := make(map[string]UDPMux) - for _, mux := range muxes { - for _, addr := range mux.GetListenAddresses() { - addrToMux[addr.String()] = mux - } - } - return &MultiUDPMuxDefault{ - muxes: muxes, - localAddrToMux: addrToMux, - } -} - -// GetConn returns a PacketConn given the connection's ufrag and network -// creates the connection if an existing one can't be found. -func (m *MultiUDPMuxDefault) GetConn(ufrag string, addr net.Addr) (net.PacketConn, error) { - mux, ok := m.localAddrToMux[addr.String()] - if !ok { - return nil, errNoUDPMuxAvailable - } - return mux.GetConn(ufrag, addr) -} - -// RemoveConnByUfrag stops and removes the muxed packet connection -// from all underlying UDPMux instances. -func (m *MultiUDPMuxDefault) RemoveConnByUfrag(ufrag string) { - for _, mux := range m.muxes { - mux.RemoveConnByUfrag(ufrag) - } -} - -// Close the multi mux, no further connections could be created -func (m *MultiUDPMuxDefault) Close() error { - var err error - for _, mux := range m.muxes { - if e := mux.Close(); e != nil { - err = e - } - } - return err -} - -// GetListenAddresses returns the list of addresses that this mux is listening on -func (m *MultiUDPMuxDefault) GetListenAddresses() []net.Addr { - addrs := make([]net.Addr, 0, len(m.localAddrToMux)) - for _, mux := range m.muxes { - addrs = append(addrs, mux.GetListenAddresses()...) - } - return addrs -} - -// NewMultiUDPMuxFromPort creates an instance of MultiUDPMuxDefault that -// listen all interfaces on the provided port. -func NewMultiUDPMuxFromPort(port int, opts ...UDPMuxFromPortOption) (*MultiUDPMuxDefault, error) { - params := multiUDPMuxFromPortParam{ - networks: []NetworkType{NetworkTypeUDP4, NetworkTypeUDP6}, - } - for _, opt := range opts { - opt.apply(¶ms) - } - - if params.net == nil { - var err error - if params.net, err = stdnet.NewNet(); err != nil { - return nil, fmt.Errorf("failed to get create network: %w", err) - } - } - - ips, err := localInterfaces(params.net, params.ifFilter, params.ipFilter, params.networks, params.includeLoopback) - if err != nil { - return nil, err - } - - conns := make([]net.PacketConn, 0, len(ips)) - for _, ip := range ips { - conn, listenErr := params.net.ListenUDP("udp", &net.UDPAddr{IP: ip, Port: port}) - if listenErr != nil { - err = listenErr - break - } - if params.readBufferSize > 0 { - _ = conn.SetReadBuffer(params.readBufferSize) - } - if params.writeBufferSize > 0 { - _ = conn.SetWriteBuffer(params.writeBufferSize) - } - conns = append(conns, conn) - } - - if err != nil { - for _, conn := range conns { - _ = conn.Close() - } - return nil, err - } - - muxes := make([]UDPMux, 0, len(conns)) - for _, conn := range conns { - mux := NewUDPMuxDefault(UDPMuxParams{ - Logger: params.logger, - UDPConn: conn, - Net: params.net, - }) - muxes = append(muxes, mux) - } - - return NewMultiUDPMuxDefault(muxes...), nil -} - -// UDPMuxFromPortOption provide options for NewMultiUDPMuxFromPort -type UDPMuxFromPortOption interface { - apply(*multiUDPMuxFromPortParam) -} - -type multiUDPMuxFromPortParam struct { - ifFilter func(string) bool - ipFilter func(ip net.IP) bool - networks []NetworkType - readBufferSize int - writeBufferSize int - logger logging.LeveledLogger - includeLoopback bool - net transport.Net -} - -type udpMuxFromPortOption struct { - f func(*multiUDPMuxFromPortParam) -} - -func (o *udpMuxFromPortOption) apply(p *multiUDPMuxFromPortParam) { - o.f(p) -} - -// UDPMuxFromPortWithInterfaceFilter set the filter to filter out interfaces that should not be used -func UDPMuxFromPortWithInterfaceFilter(f func(string) bool) UDPMuxFromPortOption { - return &udpMuxFromPortOption{ - f: func(p *multiUDPMuxFromPortParam) { - p.ifFilter = f - }, - } -} - -// UDPMuxFromPortWithIPFilter set the filter to filter out IP addresses that should not be used -func UDPMuxFromPortWithIPFilter(f func(ip net.IP) bool) UDPMuxFromPortOption { - return &udpMuxFromPortOption{ - f: func(p *multiUDPMuxFromPortParam) { - p.ipFilter = f - }, - } -} - -// UDPMuxFromPortWithNetworks set the networks that should be used. default is both IPv4 and IPv6 -func UDPMuxFromPortWithNetworks(networks ...NetworkType) UDPMuxFromPortOption { - return &udpMuxFromPortOption{ - f: func(p *multiUDPMuxFromPortParam) { - p.networks = networks - }, - } -} - -// UDPMuxFromPortWithReadBufferSize set the UDP connection read buffer size -func UDPMuxFromPortWithReadBufferSize(size int) UDPMuxFromPortOption { - return &udpMuxFromPortOption{ - f: func(p *multiUDPMuxFromPortParam) { - p.readBufferSize = size - }, - } -} - -// UDPMuxFromPortWithWriteBufferSize set the UDP connection write buffer size -func UDPMuxFromPortWithWriteBufferSize(size int) UDPMuxFromPortOption { - return &udpMuxFromPortOption{ - f: func(p *multiUDPMuxFromPortParam) { - p.writeBufferSize = size - }, - } -} - -// UDPMuxFromPortWithLogger set the logger for the created UDPMux -func UDPMuxFromPortWithLogger(logger logging.LeveledLogger) UDPMuxFromPortOption { - return &udpMuxFromPortOption{ - f: func(p *multiUDPMuxFromPortParam) { - p.logger = logger - }, - } -} - -// UDPMuxFromPortWithLoopback set loopback interface should be included -func UDPMuxFromPortWithLoopback() UDPMuxFromPortOption { - return &udpMuxFromPortOption{ - f: func(p *multiUDPMuxFromPortParam) { - p.includeLoopback = true - }, - } -} - -// UDPMuxFromPortWithNet sets the network transport to use. -func UDPMuxFromPortWithNet(n transport.Net) UDPMuxFromPortOption { - return &udpMuxFromPortOption{ - f: func(p *multiUDPMuxFromPortParam) { - p.net = n - }, - } -} diff --git a/vendor/github.com/pion/ice/v2/udp_mux_universal.go b/vendor/github.com/pion/ice/v2/udp_mux_universal.go deleted file mode 100644 index 07b6a70ea..000000000 --- a/vendor/github.com/pion/ice/v2/udp_mux_universal.go +++ /dev/null @@ -1,271 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package ice - -import ( - "fmt" - "net" - "time" - - "github.com/pion/logging" - "github.com/pion/stun" - "github.com/pion/transport/v2" -) - -// UniversalUDPMux allows multiple connections to go over a single UDP port for -// host, server reflexive and relayed candidates. -// Actual connection muxing is happening in the UDPMux. -type UniversalUDPMux interface { - UDPMux - GetXORMappedAddr(stunAddr net.Addr, deadline time.Duration) (*stun.XORMappedAddress, error) - GetRelayedAddr(turnAddr net.Addr, deadline time.Duration) (*net.Addr, error) - GetConnForURL(ufrag string, url string, addr net.Addr) (net.PacketConn, error) -} - -// UniversalUDPMuxDefault handles STUN and TURN servers packets by wrapping the original UDPConn overriding ReadFrom. -// It the passes packets to the UDPMux that does the actual connection muxing. -type UniversalUDPMuxDefault struct { - *UDPMuxDefault - params UniversalUDPMuxParams - - // Since we have a shared socket, for srflx candidates it makes sense to have a shared mapped address across all the agents - // stun.XORMappedAddress indexed by the STUN server addr - xorMappedMap map[string]*xorMapped -} - -// UniversalUDPMuxParams are parameters for UniversalUDPMux server reflexive. -type UniversalUDPMuxParams struct { - Logger logging.LeveledLogger - UDPConn net.PacketConn - XORMappedAddrCacheTTL time.Duration - Net transport.Net -} - -// NewUniversalUDPMuxDefault creates an implementation of UniversalUDPMux embedding UDPMux -func NewUniversalUDPMuxDefault(params UniversalUDPMuxParams) *UniversalUDPMuxDefault { - if params.Logger == nil { - params.Logger = logging.NewDefaultLoggerFactory().NewLogger("ice") - } - if params.XORMappedAddrCacheTTL == 0 { - params.XORMappedAddrCacheTTL = time.Second * 25 - } - - m := &UniversalUDPMuxDefault{ - params: params, - xorMappedMap: make(map[string]*xorMapped), - } - - // Wrap UDP connection, process server reflexive messages - // before they are passed to the UDPMux connection handler (connWorker) - m.params.UDPConn = &udpConn{ - PacketConn: params.UDPConn, - mux: m, - logger: params.Logger, - } - - // Embed UDPMux - udpMuxParams := UDPMuxParams{ - Logger: params.Logger, - UDPConn: m.params.UDPConn, - Net: m.params.Net, - } - m.UDPMuxDefault = NewUDPMuxDefault(udpMuxParams) - - return m -} - -// udpConn is a wrapper around UDPMux conn that overrides ReadFrom and handles STUN/TURN packets -type udpConn struct { - net.PacketConn - mux *UniversalUDPMuxDefault - logger logging.LeveledLogger -} - -// GetRelayedAddr creates relayed connection to the given TURN service and returns the relayed addr. -// Not implemented yet. -func (m *UniversalUDPMuxDefault) GetRelayedAddr(net.Addr, time.Duration) (*net.Addr, error) { - return nil, errNotImplemented -} - -// GetConnForURL add uniques to the muxed connection by concatenating ufrag and URL (e.g. STUN URL) to be able to support multiple STUN/TURN servers -// and return a unique connection per server. -func (m *UniversalUDPMuxDefault) GetConnForURL(ufrag string, url string, addr net.Addr) (net.PacketConn, error) { - return m.UDPMuxDefault.GetConn(fmt.Sprintf("%s%s", ufrag, url), addr) -} - -// ReadFrom is called by UDPMux connWorker and handles packets coming from the STUN server discovering a mapped address. -// It passes processed packets further to the UDPMux (maybe this is not really necessary). -func (c *udpConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { - n, addr, err = c.PacketConn.ReadFrom(p) - if err != nil { - return - } - - if stun.IsMessage(p[:n]) { - msg := &stun.Message{ - Raw: append([]byte{}, p[:n]...), - } - - if err = msg.Decode(); err != nil { - c.logger.Warnf("Failed to handle decode ICE from %s: %v", addr.String(), err) - err = nil - return - } - - udpAddr, ok := addr.(*net.UDPAddr) - if !ok { - // Message about this err will be logged in the UDPMux - return - } - - if c.mux.isXORMappedResponse(msg, udpAddr.String()) { - err = c.mux.handleXORMappedResponse(udpAddr, msg) - if err != nil { - c.logger.Debugf("%w: %v", errGetXorMappedAddrResponse, err) - err = nil - } - return - } - } - return n, addr, err -} - -// isXORMappedResponse indicates whether the message is a XORMappedAddress and is coming from the known STUN server. -func (m *UniversalUDPMuxDefault) isXORMappedResponse(msg *stun.Message, stunAddr string) bool { - m.mu.Lock() - defer m.mu.Unlock() - // Check first if it is a STUN server address because remote peer can also send similar messages but as a BindingSuccess - _, ok := m.xorMappedMap[stunAddr] - _, err := msg.Get(stun.AttrXORMappedAddress) - return err == nil && ok -} - -// handleXORMappedResponse parses response from the STUN server, extracts XORMappedAddress attribute -// and set the mapped address for the server -func (m *UniversalUDPMuxDefault) handleXORMappedResponse(stunAddr *net.UDPAddr, msg *stun.Message) error { - m.mu.Lock() - defer m.mu.Unlock() - - mappedAddr, ok := m.xorMappedMap[stunAddr.String()] - if !ok { - return errNoXorAddrMapping - } - - var addr stun.XORMappedAddress - if err := addr.GetFrom(msg); err != nil { - return err - } - - m.xorMappedMap[stunAddr.String()] = mappedAddr - mappedAddr.SetAddr(&addr) - - return nil -} - -// GetXORMappedAddr returns *stun.XORMappedAddress if already present for a given STUN server. -// Makes a STUN binding request to discover mapped address otherwise. -// Blocks until the stun.XORMappedAddress has been discovered or deadline. -// Method is safe for concurrent use. -func (m *UniversalUDPMuxDefault) GetXORMappedAddr(serverAddr net.Addr, deadline time.Duration) (*stun.XORMappedAddress, error) { - m.mu.Lock() - mappedAddr, ok := m.xorMappedMap[serverAddr.String()] - // If we already have a mapping for this STUN server (address already received) - // and if it is not too old we return it without making a new request to STUN server - if ok { - if mappedAddr.expired() { - mappedAddr.closeWaiters() - delete(m.xorMappedMap, serverAddr.String()) - ok = false - } else if mappedAddr.pending() { - ok = false - } - } - m.mu.Unlock() - if ok { - return mappedAddr.addr, nil - } - - // Otherwise, make a STUN request to discover the address - // or wait for already sent request to complete - waitAddrReceived, err := m.sendSTUN(serverAddr) - if err != nil { - return nil, fmt.Errorf("%w: %s", errSendSTUNPacket, err) //nolint:errorlint - } - - // Block until response was handled by the connWorker routine and XORMappedAddress was updated - select { - case <-waitAddrReceived: - // When channel closed, addr was obtained - m.mu.Lock() - mappedAddr := *m.xorMappedMap[serverAddr.String()] - m.mu.Unlock() - if mappedAddr.addr == nil { - return nil, errNoXorAddrMapping - } - return mappedAddr.addr, nil - case <-time.After(deadline): - return nil, errXORMappedAddrTimeout - } -} - -// sendSTUN sends a STUN request via UDP conn. -// -// The returned channel is closed when the STUN response has been received. -// Method is safe for concurrent use. -func (m *UniversalUDPMuxDefault) sendSTUN(serverAddr net.Addr) (chan struct{}, error) { - m.mu.Lock() - defer m.mu.Unlock() - - // If record present in the map, we already sent a STUN request, - // just wait when waitAddrReceived will be closed - addrMap, ok := m.xorMappedMap[serverAddr.String()] - if !ok { - addrMap = &xorMapped{ - expiresAt: time.Now().Add(m.params.XORMappedAddrCacheTTL), - waitAddrReceived: make(chan struct{}), - } - m.xorMappedMap[serverAddr.String()] = addrMap - } - - req, err := stun.Build(stun.BindingRequest, stun.TransactionID) - if err != nil { - return nil, err - } - - if _, err = m.params.UDPConn.WriteTo(req.Raw, serverAddr); err != nil { - return nil, err - } - - return addrMap.waitAddrReceived, nil -} - -type xorMapped struct { - addr *stun.XORMappedAddress - waitAddrReceived chan struct{} - expiresAt time.Time -} - -func (a *xorMapped) closeWaiters() { - select { - case <-a.waitAddrReceived: - // Notify was close, ok, that means we received duplicate response just exit - break - default: - // Notify tha twe have a new addr - close(a.waitAddrReceived) - } -} - -func (a *xorMapped) pending() bool { - return a.addr == nil -} - -func (a *xorMapped) expired() bool { - return a.expiresAt.Before(time.Now()) -} - -func (a *xorMapped) SetAddr(addr *stun.XORMappedAddress) { - a.addr = addr - a.closeWaiters() -} diff --git a/vendor/github.com/pion/ice/v2/udp_muxed_conn.go b/vendor/github.com/pion/ice/v2/udp_muxed_conn.go index 09e4b3a8e..35169af35 100644 --- a/vendor/github.com/pion/ice/v2/udp_muxed_conn.go +++ b/vendor/github.com/pion/ice/v2/udp_muxed_conn.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import ( @@ -11,7 +8,7 @@ import ( "time" "github.com/pion/logging" - "github.com/pion/transport/v2/packetio" + "github.com/pion/transport/packetio" ) type udpMuxedConnParams struct { @@ -25,11 +22,11 @@ type udpMuxedConnParams struct { // udpMuxedConn represents a logical packet conn for a single remote as identified by ufrag type udpMuxedConn struct { params *udpMuxedConnParams - // Remote addresses that we have sent to on this conn + // remote addresses that we have sent to on this conn addresses []string - // Channel holding incoming packets - buf *packetio.Buffer + // channel holding incoming packets + buffer *packetio.Buffer closedChan chan struct{} closeOnce sync.Once mu sync.Mutex @@ -38,70 +35,70 @@ type udpMuxedConn struct { func newUDPMuxedConn(params *udpMuxedConnParams) *udpMuxedConn { p := &udpMuxedConn{ params: params, - buf: packetio.NewBuffer(), + buffer: packetio.NewBuffer(), closedChan: make(chan struct{}), } return p } -func (c *udpMuxedConn) ReadFrom(b []byte) (n int, rAddr net.Addr, err error) { - buf := c.params.AddrPool.Get().(*bufferHolder) //nolint:forcetypeassert +func (c *udpMuxedConn) ReadFrom(b []byte) (n int, raddr net.Addr, err error) { + buf := c.params.AddrPool.Get().(*bufferHolder) defer c.params.AddrPool.Put(buf) - // Read address - total, err := c.buf.Read(buf.buf) + // read address + total, err := c.buffer.Read(buf.buffer) if err != nil { return 0, nil, err } - dataLen := int(binary.LittleEndian.Uint16(buf.buf[:2])) + dataLen := int(binary.LittleEndian.Uint16(buf.buffer[:2])) if dataLen > total || dataLen > len(b) { return 0, nil, io.ErrShortBuffer } - // Read data and then address + // read data and then address offset := 2 - copy(b, buf.buf[offset:offset+dataLen]) + copy(b, buf.buffer[offset:offset+dataLen]) offset += dataLen - // Read address len & decode address - addrLen := int(binary.LittleEndian.Uint16(buf.buf[offset : offset+2])) + // read address len & decode address + addrLen := int(binary.LittleEndian.Uint16(buf.buffer[offset : offset+2])) offset += 2 - if rAddr, err = decodeUDPAddr(buf.buf[offset : offset+addrLen]); err != nil { + if raddr, err = decodeUDPAddr(buf.buffer[offset : offset+addrLen]); err != nil { return 0, nil, err } - return dataLen, rAddr, nil + return dataLen, raddr, nil } -func (c *udpMuxedConn) WriteTo(buf []byte, rAddr net.Addr) (n int, err error) { +func (c *udpMuxedConn) WriteTo(buf []byte, raddr net.Addr) (n int, err error) { if c.isClosed() { return 0, io.ErrClosedPipe } - // Each time we write to a new address, we'll register it with the mux - addr := rAddr.String() + // each time we write to a new address, we'll register it with the mux + addr := raddr.String() if !c.containsAddress(addr) { c.addAddress(addr) } - return c.params.Mux.writeTo(buf, rAddr) + return c.params.Mux.writeTo(buf, raddr) } func (c *udpMuxedConn) LocalAddr() net.Addr { return c.params.LocalAddr } -func (c *udpMuxedConn) SetDeadline(time.Time) error { +func (c *udpMuxedConn) SetDeadline(tm time.Time) error { return nil } -func (c *udpMuxedConn) SetReadDeadline(time.Time) error { +func (c *udpMuxedConn) SetReadDeadline(tm time.Time) error { return nil } -func (c *udpMuxedConn) SetWriteDeadline(time.Time) error { +func (c *udpMuxedConn) SetWriteDeadline(tm time.Time) error { return nil } @@ -112,9 +109,12 @@ func (c *udpMuxedConn) CloseChannel() <-chan struct{} { func (c *udpMuxedConn) Close() error { var err error c.closeOnce.Do(func() { - err = c.buf.Close() + err = c.buffer.Close() close(c.closedChan) }) + c.mu.Lock() + defer c.mu.Unlock() + c.addresses = nil return err } @@ -140,7 +140,7 @@ func (c *udpMuxedConn) addAddress(addr string) { c.addresses = append(c.addresses, addr) c.mu.Unlock() - // Map it on mux + // map it on mux c.params.Mux.registerConnForAddress(c, addr) } @@ -170,51 +170,51 @@ func (c *udpMuxedConn) containsAddress(addr string) bool { } func (c *udpMuxedConn) writePacket(data []byte, addr *net.UDPAddr) error { - // Write two packets, address and data - buf := c.params.AddrPool.Get().(*bufferHolder) //nolint:forcetypeassert + // write two packets, address and data + buf := c.params.AddrPool.Get().(*bufferHolder) defer c.params.AddrPool.Put(buf) - // Format of buffer | data len | data bytes | addr len | addr bytes | - if len(buf.buf) < len(data)+maxAddrSize { + // format of buffer | data len | data bytes | addr len | addr bytes | + if len(buf.buffer) < len(data)+maxAddrSize { return io.ErrShortBuffer } - // Data length - binary.LittleEndian.PutUint16(buf.buf, uint16(len(data))) + // data len + binary.LittleEndian.PutUint16(buf.buffer, uint16(len(data))) offset := 2 - // Data - copy(buf.buf[offset:], data) + // data + copy(buf.buffer[offset:], data) offset += len(data) - // Write address first, leaving room for its length - n, err := encodeUDPAddr(addr, buf.buf[offset+2:]) + // write address first, leaving room for its length + n, err := encodeUDPAddr(addr, buf.buffer[offset+2:]) if err != nil { - return err + return nil } total := offset + n + 2 - // Address len - binary.LittleEndian.PutUint16(buf.buf[offset:], uint16(n)) + // address len + binary.LittleEndian.PutUint16(buf.buffer[offset:], uint16(n)) - if _, err := c.buf.Write(buf.buf[:total]); err != nil { + if _, err := c.buffer.Write(buf.buffer[:total]); err != nil { return err } return nil } func encodeUDPAddr(addr *net.UDPAddr, buf []byte) (int, error) { - ipData, err := addr.IP.MarshalText() + ipdata, err := addr.IP.MarshalText() if err != nil { return 0, err } - total := 2 + len(ipData) + 2 + len(addr.Zone) + total := 2 + len(ipdata) + 2 + len(addr.Zone) if total > len(buf) { return 0, io.ErrShortBuffer } - binary.LittleEndian.PutUint16(buf, uint16(len(ipData))) + binary.LittleEndian.PutUint16(buf, uint16(len(ipdata))) offset := 2 - n := copy(buf[offset:], ipData) + n := copy(buf[offset:], ipdata) offset += n binary.LittleEndian.PutUint16(buf[offset:], uint16(addr.Port)) offset += 2 @@ -228,7 +228,7 @@ func decodeUDPAddr(buf []byte) (*net.UDPAddr, error) { offset := 0 ipLen := int(binary.LittleEndian.Uint16(buf[:2])) offset += 2 - // Basic bounds checking + // basic bounds checking if ipLen+offset > len(buf) { return nil, io.ErrShortBuffer } diff --git a/vendor/github.com/pion/ice/v2/url.go b/vendor/github.com/pion/ice/v2/url.go index b2b9f8bd3..390591e3d 100644 --- a/vendor/github.com/pion/ice/v2/url.go +++ b/vendor/github.com/pion/ice/v2/url.go @@ -1,82 +1,225 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice -import "github.com/pion/stun" - -type ( - // URL represents a STUN (rfc7064) or TURN (rfc7065) URI - // - // Deprecated: Please use pion/stun.URI - URL = stun.URI - - // ProtoType indicates the transport protocol type that is used in the ice.URL - // structure. - // - // Deprecated: TPlease use pion/stun.ProtoType - ProtoType = stun.ProtoType - - // SchemeType indicates the type of server used in the ice.URL structure. - // - // Deprecated: Please use pion/stun.SchemeType - SchemeType = stun.SchemeType +import ( + "net" + "net/url" + "strconv" ) +// SchemeType indicates the type of server used in the ice.URL structure. +type SchemeType int + +// Unknown defines default public constant to use for "enum" like struct +// comparisons when no value was defined. +const Unknown = iota + const ( // SchemeTypeSTUN indicates the URL represents a STUN server. - // - // Deprecated: Please use pion/stun.SchemeTypeSTUN - SchemeTypeSTUN = stun.SchemeTypeSTUN + SchemeTypeSTUN SchemeType = iota + 1 // SchemeTypeSTUNS indicates the URL represents a STUNS (secure) server. - // - // Deprecated: Please use pion/stun.SchemeTypeSTUNS - SchemeTypeSTUNS = stun.SchemeTypeSTUNS + SchemeTypeSTUNS // SchemeTypeTURN indicates the URL represents a TURN server. - // - // Deprecated: Please use pion/stun.SchemeTypeTURN - SchemeTypeTURN = stun.SchemeTypeTURN + SchemeTypeTURN // SchemeTypeTURNS indicates the URL represents a TURNS (secure) server. - // - // Deprecated: Please use pion/stun.SchemeTypeTURNS - SchemeTypeTURNS = stun.SchemeTypeTURNS + SchemeTypeTURNS ) +// NewSchemeType defines a procedure for creating a new SchemeType from a raw +// string naming the scheme type. +func NewSchemeType(raw string) SchemeType { + switch raw { + case "stun": + return SchemeTypeSTUN + case "stuns": + return SchemeTypeSTUNS + case "turn": + return SchemeTypeTURN + case "turns": + return SchemeTypeTURNS + default: + return SchemeType(Unknown) + } +} + +func (t SchemeType) String() string { + switch t { + case SchemeTypeSTUN: + return "stun" + case SchemeTypeSTUNS: + return "stuns" + case SchemeTypeTURN: + return "turn" + case SchemeTypeTURNS: + return "turns" + default: + return ErrUnknownType.Error() + } +} + +// ProtoType indicates the transport protocol type that is used in the ice.URL +// structure. +type ProtoType int + const ( // ProtoTypeUDP indicates the URL uses a UDP transport. - // - // Deprecated: Please use pion/stun.ProtoTypeUDP - ProtoTypeUDP = stun.ProtoTypeUDP + ProtoTypeUDP ProtoType = iota + 1 // ProtoTypeTCP indicates the URL uses a TCP transport. - // - // Deprecated: Please use pion/stun.ProtoTypeTCP - ProtoTypeTCP = stun.ProtoTypeTCP + ProtoTypeTCP ) -// Unknown represents and unknown ProtoType or SchemeType -// -// Deprecated: Please use pion/stun.SchemeTypeUnknown or pion/stun.ProtoTypeUnknown -const Unknown = 0 +// NewProtoType defines a procedure for creating a new ProtoType from a raw +// string naming the transport protocol type. +func NewProtoType(raw string) ProtoType { + switch raw { + case "udp": + return ProtoTypeUDP + case "tcp": + return ProtoTypeTCP + default: + return ProtoType(Unknown) + } +} + +func (t ProtoType) String() string { + switch t { + case ProtoTypeUDP: + return "udp" + case ProtoTypeTCP: + return "tcp" + default: + return ErrUnknownType.Error() + } +} + +// URL represents a STUN (rfc7064) or TURN (rfc7065) URL +type URL struct { + Scheme SchemeType + Host string + Port int + Username string + Password string + Proto ProtoType +} // ParseURL parses a STUN or TURN urls following the ABNF syntax described in // https://tools.ietf.org/html/rfc7064 and https://tools.ietf.org/html/rfc7065 // respectively. -// -// Deprecated: Please use pion/stun.ParseURI -var ParseURL = stun.ParseURI //nolint:gochecknoglobals +func ParseURL(raw string) (*URL, error) { //nolint:gocognit + rawParts, err := url.Parse(raw) + if err != nil { + return nil, err + } -// NewSchemeType defines a procedure for creating a new SchemeType from a raw -// string naming the scheme type. -// -// Deprecated: Please use pion/stun.NewSchemeType -var NewSchemeType = stun.NewSchemeType //nolint:gochecknoglobals + var u URL + u.Scheme = NewSchemeType(rawParts.Scheme) + if u.Scheme == SchemeType(Unknown) { + return nil, ErrSchemeType + } -// NewProtoType defines a procedure for creating a new ProtoType from a raw -// string naming the transport protocol type. -// -// Deprecated: Please use pion/stun.NewProtoType -var NewProtoType = stun.NewProtoType //nolint:gochecknoglobals + var rawPort string + if u.Host, rawPort, err = net.SplitHostPort(rawParts.Opaque); err != nil { + if e, ok := err.(*net.AddrError); ok { + if e.Err == "missing port in address" { + nextRawURL := u.Scheme.String() + ":" + rawParts.Opaque + switch { + case u.Scheme == SchemeTypeSTUN || u.Scheme == SchemeTypeTURN: + nextRawURL += ":3478" + if rawParts.RawQuery != "" { + nextRawURL += "?" + rawParts.RawQuery + } + return ParseURL(nextRawURL) + case u.Scheme == SchemeTypeSTUNS || u.Scheme == SchemeTypeTURNS: + nextRawURL += ":5349" + if rawParts.RawQuery != "" { + nextRawURL += "?" + rawParts.RawQuery + } + return ParseURL(nextRawURL) + } + } + } + return nil, err + } + + if u.Host == "" { + return nil, ErrHost + } + + if u.Port, err = strconv.Atoi(rawPort); err != nil { + return nil, ErrPort + } + + switch u.Scheme { + case SchemeTypeSTUN: + qArgs, err := url.ParseQuery(rawParts.RawQuery) + if err != nil || len(qArgs) > 0 { + return nil, ErrSTUNQuery + } + u.Proto = ProtoTypeUDP + case SchemeTypeSTUNS: + qArgs, err := url.ParseQuery(rawParts.RawQuery) + if err != nil || len(qArgs) > 0 { + return nil, ErrSTUNQuery + } + u.Proto = ProtoTypeTCP + case SchemeTypeTURN: + proto, err := parseProto(rawParts.RawQuery) + if err != nil { + return nil, err + } + + u.Proto = proto + if u.Proto == ProtoType(Unknown) { + u.Proto = ProtoTypeUDP + } + case SchemeTypeTURNS: + proto, err := parseProto(rawParts.RawQuery) + if err != nil { + return nil, err + } + + u.Proto = proto + if u.Proto == ProtoType(Unknown) { + u.Proto = ProtoTypeTCP + } + } + + return &u, nil +} + +func parseProto(raw string) (ProtoType, error) { + qArgs, err := url.ParseQuery(raw) + if err != nil || len(qArgs) > 1 { + return ProtoType(Unknown), ErrInvalidQuery + } + + var proto ProtoType + if rawProto := qArgs.Get("transport"); rawProto != "" { + if proto = NewProtoType(rawProto); proto == ProtoType(0) { + return ProtoType(Unknown), ErrProtoType + } + return proto, nil + } + + if len(qArgs) > 0 { + return ProtoType(Unknown), ErrInvalidQuery + } + + return proto, nil +} + +func (u URL) String() string { + rawURL := u.Scheme.String() + ":" + net.JoinHostPort(u.Host, strconv.Itoa(u.Port)) + if u.Scheme == SchemeTypeTURN || u.Scheme == SchemeTypeTURNS { + rawURL += "?transport=" + u.Proto.String() + } + return rawURL +} + +// IsSecure returns whether the this URL's scheme describes secure scheme or not. +func (u URL) IsSecure() bool { + return u.Scheme == SchemeTypeSTUNS || u.Scheme == SchemeTypeTURNS +} diff --git a/vendor/github.com/pion/ice/v2/usecandidate.go b/vendor/github.com/pion/ice/v2/usecandidate.go index 6fc7ed50c..f168c08eb 100644 --- a/vendor/github.com/pion/ice/v2/usecandidate.go +++ b/vendor/github.com/pion/ice/v2/usecandidate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package ice import "github.com/pion/stun" diff --git a/vendor/github.com/pion/ice/v2/util.go b/vendor/github.com/pion/ice/v2/util.go new file mode 100644 index 000000000..7eb13c803 --- /dev/null +++ b/vendor/github.com/pion/ice/v2/util.go @@ -0,0 +1,233 @@ +package ice + +import ( + "fmt" + "net" + "sync/atomic" + "time" + + "github.com/pion/logging" + "github.com/pion/stun" + "github.com/pion/transport/vnet" +) + +type atomicError struct{ v atomic.Value } + +func (a *atomicError) Store(err error) { + a.v.Store(struct{ error }{err}) +} + +func (a *atomicError) Load() error { + err, _ := a.v.Load().(struct{ error }) + return err.error +} + +// The conditions of invalidation written below are defined in +// https://tools.ietf.org/html/rfc8445#section-5.1.1.1 +func isSupportedIPv6(ip net.IP) bool { + if len(ip) != net.IPv6len || + isZeros(ip[0:12]) || // !(IPv4-compatible IPv6) + ip[0] == 0xfe && ip[1]&0xc0 == 0xc0 || // !(IPv6 site-local unicast) + ip.IsLinkLocalUnicast() || + ip.IsLinkLocalMulticast() { + return false + } + return true +} + +func isZeros(ip net.IP) bool { + for i := 0; i < len(ip); i++ { + if ip[i] != 0 { + return false + } + } + return true +} + +func parseAddr(in net.Addr) (net.IP, int, NetworkType, bool) { + switch addr := in.(type) { + case *net.UDPAddr: + return addr.IP, addr.Port, NetworkTypeUDP4, true + case *net.TCPAddr: + return addr.IP, addr.Port, NetworkTypeTCP4, true + } + return nil, 0, 0, false +} + +func createAddr(network NetworkType, ip net.IP, port int) net.Addr { + switch { + case network.IsTCP(): + return &net.TCPAddr{IP: ip, Port: port} + default: + return &net.UDPAddr{IP: ip, Port: port} + } +} + +func addrEqual(a, b net.Addr) bool { + aIP, aPort, aType, aOk := parseAddr(a) + if !aOk { + return false + } + + bIP, bPort, bType, bOk := parseAddr(b) + if !bOk { + return false + } + + return aType == bType && aIP.Equal(bIP) && aPort == bPort +} + +// getXORMappedAddr initiates a stun requests to serverAddr using conn, reads the response and returns +// the XORMappedAddress returned by the stun server. +// +// Adapted from stun v0.2. +func getXORMappedAddr(conn net.PacketConn, serverAddr net.Addr, deadline time.Duration) (*stun.XORMappedAddress, error) { + if deadline > 0 { + if err := conn.SetReadDeadline(time.Now().Add(deadline)); err != nil { + return nil, err + } + } + defer func() { + if deadline > 0 { + _ = conn.SetReadDeadline(time.Time{}) + } + }() + resp, err := stunRequest( + func(p []byte) (int, error) { + n, _, errr := conn.ReadFrom(p) + return n, errr + }, + func(b []byte) (int, error) { + return conn.WriteTo(b, serverAddr) + }, + ) + if err != nil { + return nil, err + } + var addr stun.XORMappedAddress + if err = addr.GetFrom(resp); err != nil { + return nil, fmt.Errorf("%w: %v", errGetXorMappedAddrResponse, err) + } + return &addr, nil +} + +func stunRequest(read func([]byte) (int, error), write func([]byte) (int, error)) (*stun.Message, error) { + req, err := stun.Build(stun.BindingRequest, stun.TransactionID) + if err != nil { + return nil, err + } + if _, err = write(req.Raw); err != nil { + return nil, err + } + const maxMessageSize = 1280 + bs := make([]byte, maxMessageSize) + n, err := read(bs) + if err != nil { + return nil, err + } + res := &stun.Message{Raw: bs[:n]} + if err := res.Decode(); err != nil { + return nil, err + } + return res, nil +} + +func localInterfaces(vnet *vnet.Net, interfaceFilter func(string) bool, networkTypes []NetworkType) ([]net.IP, error) { //nolint:gocognit + ips := []net.IP{} + ifaces, err := vnet.Interfaces() + if err != nil { + return ips, err + } + + var IPv4Requested, IPv6Requested bool + for _, typ := range networkTypes { + if typ.IsIPv4() { + IPv4Requested = true + } + + if typ.IsIPv6() { + IPv6Requested = true + } + } + + for _, iface := range ifaces { + if iface.Flags&net.FlagUp == 0 { + continue // interface down + } + if iface.Flags&net.FlagLoopback != 0 { + continue // loopback interface + } + + if interfaceFilter != nil && !interfaceFilter(iface.Name) { + continue + } + + addrs, err := iface.Addrs() + if err != nil { + continue + } + + for _, addr := range addrs { + var ip net.IP + switch addr := addr.(type) { + case *net.IPNet: + ip = addr.IP + case *net.IPAddr: + ip = addr.IP + } + if ip == nil || ip.IsLoopback() { + continue + } + + if ipv4 := ip.To4(); ipv4 == nil { + if !IPv6Requested { + continue + } else if !isSupportedIPv6(ip) { + continue + } + } else if !IPv4Requested { + continue + } + + ips = append(ips, ip) + } + } + return ips, nil +} + +func listenUDPInPortRange(vnet *vnet.Net, log logging.LeveledLogger, portMax, portMin int, network string, laddr *net.UDPAddr) (vnet.UDPPacketConn, error) { + if (laddr.Port != 0) || ((portMin == 0) && (portMax == 0)) { + return vnet.ListenUDP(network, laddr) + } + var i, j int + i = portMin + if i == 0 { + i = 1 + } + j = portMax + if j == 0 { + j = 0xFFFF + } + if i > j { + return nil, ErrPort + } + + portStart := globalMathRandomGenerator.Intn(j-i+1) + i + portCurrent := portStart + for { + laddr = &net.UDPAddr{IP: laddr.IP, Port: portCurrent} + c, e := vnet.ListenUDP(network, laddr) + if e == nil { + return c, e + } + log.Debugf("failed to listen %s: %v", laddr.String(), e) + portCurrent++ + if portCurrent > j { + portCurrent = i + } + if portCurrent == portStart { + break + } + } + return nil, ErrPort +} diff --git a/vendor/github.com/pion/interceptor/.gitignore b/vendor/github.com/pion/interceptor/.gitignore index 6e2f206a9..83db74ba5 100644 --- a/vendor/github.com/pion/interceptor/.gitignore +++ b/vendor/github.com/pion/interceptor/.gitignore @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - ### JetBrains IDE ### ##################### .idea/ @@ -25,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/interceptor/.golangci.yml b/vendor/github.com/pion/interceptor/.golangci.yml index 4e3eddf42..d6162c970 100644 --- a/vendor/github.com/pion/interceptor/.golangci.yml +++ b/vendor/github.com/pion/interceptor/.golangci.yml @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - linters-settings: govet: check-shadowing: true @@ -13,34 +10,19 @@ linters-settings: modules: - github.com/pkg/errors: recommendations: - - errors - forbidigo: - forbid: - - ^fmt.Print(f|ln)?$ - - ^log.(Panic|Fatal|Print)(f|ln)?$ - - ^os.Exit$ - - ^panic$ - - ^print(ln)?$ + - errors linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - - decorder # check declaration order and count of types, constants, variables and functions + - deadcode # Finds unused code - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forbidigo # Forbids identifiers - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -53,59 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks + - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - - wastedassign # wastedassign finds wasted assignment statements + - varcheck # Finds unused global variables and constants - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: @@ -115,23 +78,12 @@ issues: - path: _test\.go linters: - gocognit - - forbidigo # Allow complex main function in examples - path: examples text: "of func `main` is high" linters: - gocognit - - # Allow forbidden identifiers in examples - - path: examples - linters: - - forbidigo - - # Allow forbidden identifiers in CLI commands - - path: cmd - linters: - - forbidigo run: skip-dirs-use-default: false diff --git a/vendor/github.com/pion/interceptor/.goreleaser.yml b/vendor/github.com/pion/interceptor/.goreleaser.yml deleted file mode 100644 index 30093e9d6..000000000 --- a/vendor/github.com/pion/interceptor/.goreleaser.yml +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - -builds: -- skip: true diff --git a/vendor/github.com/pion/interceptor/AUTHORS.txt b/vendor/github.com/pion/interceptor/AUTHORS.txt index 44a421ef8..ea5d0e561 100644 --- a/vendor/github.com/pion/interceptor/AUTHORS.txt +++ b/vendor/github.com/pion/interceptor/AUTHORS.txt @@ -2,29 +2,15 @@ # we would love to have you https://github.com/pion/webrtc/wiki/Contributing # # This file is auto generated, using git to list all individuals contributors. -# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting -Aaron Boushley +# see `.github/generate-authors.sh` for the scripting Adam Kiss adamroach -Aditya Kumar aler9 <46489434+aler9@users.noreply.github.com> Antoine Baché Atsushi Watanabe -Bobby Peck boks1971 David Zhao Jonathan Müller Kevin Caffrey -Maksim Nesterov Mathis Engelbart -Miroslav -Miroslav Šedivý -Quentin Renard -Rayleigh Li Sean DuBois -Steffen Vogel -XLPolar -ziminghua <565209960@qq.com> - -# List of contributors not appearing in Git history - diff --git a/vendor/github.com/pion/interceptor/LICENSE b/vendor/github.com/pion/interceptor/LICENSE index 491caf6b0..ab602974d 100644 --- a/vendor/github.com/pion/interceptor/LICENSE +++ b/vendor/github.com/pion/interceptor/LICENSE @@ -1,9 +1,21 @@ MIT License -Copyright (c) 2023 The Pion community +Copyright (c) 2018 -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/pion/interceptor/README.md b/vendor/github.com/pion/interceptor/README.md index dcc856f1e..8c67a46df 100644 --- a/vendor/github.com/pion/interceptor/README.md +++ b/vendor/github.com/pion/interceptor/README.md @@ -8,8 +8,7 @@ Pion Interceptor Slack Widget
- GitHub Workflow Status - Go Reference + GoDoc Coverage Status Go Report Card License: MIT @@ -28,20 +27,19 @@ by anyone. With the following tenets in mind. * Encourage modification. Add your own interceptors without forking. Mixing with the ones we provide. * Empower learning. This code base should be useful to read and learn even if you aren't using Pion. -### Current Interceptors +#### Current Interceptors * [NACK Generator/Responder](https://github.com/pion/interceptor/tree/master/pkg/nack) * [Sender and Receiver Reports](https://github.com/pion/interceptor/tree/master/pkg/report) * [Transport Wide Congestion Control Feedback](https://github.com/pion/interceptor/tree/master/pkg/twcc) * [Packet Dump](https://github.com/pion/interceptor/tree/master/pkg/packetdump) -* [Google Congestion Control](https://github.com/pion/interceptor/tree/master/pkg/gcc) -* [Stats](https://github.com/pion/interceptor/tree/master/pkg/stats) A [webrtc-stats](https://www.w3.org/TR/webrtc-stats/) compliant statistics generation -* [Interval PLI](https://github.com/pion/interceptor/tree/master/pkg/intervalpli) Generate PLI on a interval. Useful when no decoder is available. -### Planned Interceptors +#### Planned Interceptors * Bandwidth Estimation - [NADA](https://tools.ietf.org/html/rfc8698) + - [Google Congestion Control](https://tools.ietf.org/html/draft-ietf-rmcat-gcc-02) * JitterBuffer, re-order packets and wait for arrival * [FlexFec](https://tools.ietf.org/html/draft-ietf-payload-flexible-fec-scheme-20) +* [webrtc-stats](https://www.w3.org/TR/webrtc-stats/) compliant statistics generation * [RTCP Feedback for Congestion Control](https://datatracker.ietf.org/doc/html/rfc8888) the standardized alternative to TWCC. ### Interceptor Public API @@ -66,19 +64,15 @@ sequentially as the packet moves through them. The [examples](https://github.com/pion/interceptor/blob/master/examples) directory provides some basic examples. If you need more please file an issue! You should also look in [pion/webrtc](https://github.com/pion/webrtc) for real world examples. -### Roadmap -The library is used as a part of our WebRTC implementation. Please refer to that [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones. - ### Community -Pion has an active community on the [Slack](https://pion.ly/slack). - -Follow the [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news. +Pion has an active community on the [Golang Slack](https://invite.slack.golangbridge.org/). Sign up and join the **#pion** channel for discussions and support. You can also use [Pion mailing list](https://groups.google.com/forum/#!forum/pion). We are always looking to support **your projects**. Please reach out if you have something to build! + If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly) ### Contributing -Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible: [AUTHORS.txt](./AUTHORS.txt) +Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible: ### License MIT License - see [LICENSE](LICENSE) for full text diff --git a/vendor/github.com/pion/interceptor/attributes.go b/vendor/github.com/pion/interceptor/attributes.go index d7936d526..603315da3 100644 --- a/vendor/github.com/pion/interceptor/attributes.go +++ b/vendor/github.com/pion/interceptor/attributes.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package interceptor import ( diff --git a/vendor/github.com/pion/interceptor/chain.go b/vendor/github.com/pion/interceptor/chain.go index 267f36651..d53c30714 100644 --- a/vendor/github.com/pion/interceptor/chain.go +++ b/vendor/github.com/pion/interceptor/chain.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package interceptor // Chain is an interceptor that runs all child interceptors in order. diff --git a/vendor/github.com/pion/interceptor/codecov.yml b/vendor/github.com/pion/interceptor/codecov.yml index 263e4d45c..085200a48 100644 --- a/vendor/github.com/pion/interceptor/codecov.yml +++ b/vendor/github.com/pion/interceptor/codecov.yml @@ -3,8 +3,6 @@ # # It is automatically copied from https://github.com/pion/.goassets repository. # -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT coverage: status: diff --git a/vendor/github.com/pion/interceptor/errors.go b/vendor/github.com/pion/interceptor/errors.go index 3dafee3ef..45e1252c9 100644 --- a/vendor/github.com/pion/interceptor/errors.go +++ b/vendor/github.com/pion/interceptor/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package interceptor import ( @@ -21,7 +18,7 @@ func flattenErrs(errs []error) error { return multiError(errs2) } -type multiError []error //nolint +type multiError []error func (me multiError) Error() string { var errstrings []string @@ -44,7 +41,7 @@ func (me multiError) Is(err error) bool { if errors.Is(e, err) { return true } - if me2, ok := e.(multiError); ok { //nolint + if me2, ok := e.(multiError); ok { if me2.Is(err) { return true } diff --git a/vendor/github.com/pion/interceptor/interceptor.go b/vendor/github.com/pion/interceptor/interceptor.go index c6ba53242..a143fdd03 100644 --- a/vendor/github.com/pion/interceptor/interceptor.go +++ b/vendor/github.com/pion/interceptor/interceptor.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package interceptor contains the Interceptor interface, with some useful interceptors that should be safe to use // in most cases. package interceptor @@ -20,6 +17,7 @@ type Factory interface { // Interceptor can be used to add functionality to you PeerConnections by modifying any incoming/outgoing rtp/rtcp // packets, or sending your own packets as needed. type Interceptor interface { + // BindRTCPReader lets you modify any incoming RTCP packets. It is called once per sender/receiver, however this might // change in the future. The returned method will be called once per packet batch. BindRTCPReader(reader RTCPReader) RTCPReader diff --git a/vendor/github.com/pion/interceptor/internal/ntp/ntp.go b/vendor/github.com/pion/interceptor/internal/ntp/ntp.go deleted file mode 100644 index 69f98d6c9..000000000 --- a/vendor/github.com/pion/interceptor/internal/ntp/ntp.go +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -// Package ntp provides conversion methods between time.Time and NTP timestamps -// stored in uint64 -package ntp - -import ( - "time" -) - -// ToNTP converts a time.Time oboject to an uint64 NTP timestamp -func ToNTP(t time.Time) uint64 { - // seconds since 1st January 1900 - s := (float64(t.UnixNano()) / 1000000000) + 2208988800 - - // higher 32 bits are the integer part, lower 32 bits are the fractional part - integerPart := uint32(s) - fractionalPart := uint32((s - float64(integerPart)) * 0xFFFFFFFF) - return uint64(integerPart)<<32 | uint64(fractionalPart) -} - -// ToTime converts a uint64 NTP timestamps to a time.Time object -func ToTime(t uint64) time.Time { - seconds := (t & 0xFFFFFFFF00000000) >> 32 - fractional := float64(t&0x00000000FFFFFFFF) / float64(0xFFFFFFFF) - d := time.Duration(seconds)*time.Second + time.Duration(fractional*1e9)*time.Nanosecond - - return time.Unix(0, 0).Add(-2208988800 * time.Second).Add(d) -} diff --git a/vendor/github.com/pion/interceptor/noop.go b/vendor/github.com/pion/interceptor/noop.go index b0fc2a69a..2dc4e8e2e 100644 --- a/vendor/github.com/pion/interceptor/noop.go +++ b/vendor/github.com/pion/interceptor/noop.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package interceptor // NoOp is an Interceptor that does not modify any packets. It can embedded in other interceptors, so it's diff --git a/vendor/github.com/pion/interceptor/pkg/nack/errors.go b/vendor/github.com/pion/interceptor/pkg/nack/errors.go index b47ec39c2..66ed2b31f 100644 --- a/vendor/github.com/pion/interceptor/pkg/nack/errors.go +++ b/vendor/github.com/pion/interceptor/pkg/nack/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package nack import "errors" @@ -8,8 +5,4 @@ import "errors" // ErrInvalidSize is returned by newReceiveLog/newSendBuffer, when an incorrect buffer size is supplied. var ErrInvalidSize = errors.New("invalid buffer size") -var ( - errPacketReleased = errors.New("could not retain packet, already released") - errFailedToCastHeaderPool = errors.New("could not access header pool, failed cast") - errFailedToCastPayloadPool = errors.New("could not access payload pool, failed cast") -) +var errPacketReleased = errors.New("could not retain packet, already released") diff --git a/vendor/github.com/pion/interceptor/pkg/nack/generator_interceptor.go b/vendor/github.com/pion/interceptor/pkg/nack/generator_interceptor.go index faf533ba4..f55f4d7f3 100644 --- a/vendor/github.com/pion/interceptor/pkg/nack/generator_interceptor.go +++ b/vendor/github.com/pion/interceptor/pkg/nack/generator_interceptor.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package nack import ( @@ -19,7 +16,7 @@ type GeneratorInterceptorFactory struct { } // NewInterceptor constructs a new ReceiverInterceptor -func (g *GeneratorInterceptorFactory) NewInterceptor(_ string) (interceptor.Interceptor, error) { +func (g *GeneratorInterceptorFactory) NewInterceptor(id string) (interceptor.Interceptor, error) { i := &GeneratorInterceptor{ size: 512, skipLastN: 0, @@ -111,8 +108,8 @@ func (n *GeneratorInterceptor) BindRemoteStream(info *interceptor.StreamInfo, re }) } -// UnbindRemoteStream is called when the Stream is removed. It can be used to clean up any data related to that track. -func (n *GeneratorInterceptor) UnbindRemoteStream(info *interceptor.StreamInfo) { +// UnbindLocalStream is called when the Stream is removed. It can be used to clean up any data related to that track. +func (n *GeneratorInterceptor) UnbindLocalStream(info *interceptor.StreamInfo) { n.receiveLogsMu.Lock() delete(n.receiveLogs, info.SSRC) n.receiveLogsMu.Unlock() diff --git a/vendor/github.com/pion/interceptor/pkg/nack/generator_option.go b/vendor/github.com/pion/interceptor/pkg/nack/generator_option.go index e4f46f7c9..092f5db92 100644 --- a/vendor/github.com/pion/interceptor/pkg/nack/generator_option.go +++ b/vendor/github.com/pion/interceptor/pkg/nack/generator_option.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package nack import ( diff --git a/vendor/github.com/pion/interceptor/pkg/nack/nack.go b/vendor/github.com/pion/interceptor/pkg/nack/nack.go index b7589ebd9..a658e7f39 100644 --- a/vendor/github.com/pion/interceptor/pkg/nack/nack.go +++ b/vendor/github.com/pion/interceptor/pkg/nack/nack.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package nack provides interceptors to implement sending and receiving negative acknowledgements package nack diff --git a/vendor/github.com/pion/interceptor/pkg/nack/receive_log.go b/vendor/github.com/pion/interceptor/pkg/nack/receive_log.go index 6a19996e7..8107f59a2 100644 --- a/vendor/github.com/pion/interceptor/pkg/nack/receive_log.go +++ b/vendor/github.com/pion/interceptor/pkg/nack/receive_log.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package nack import ( @@ -130,9 +127,8 @@ func (s *receiveLog) getReceived(seq uint16) bool { func (s *receiveLog) fixLastConsecutive() { i := s.lastConsecutive + 1 - for ; i != s.end+1 && s.getReceived(i); i++ { //nolint:revive + for ; i != s.end+1 && s.getReceived(i); i++ { // find all consecutive packets } - s.lastConsecutive = i - 1 } diff --git a/vendor/github.com/pion/interceptor/pkg/nack/responder_interceptor.go b/vendor/github.com/pion/interceptor/pkg/nack/responder_interceptor.go index 8f74952dd..9b49f1130 100644 --- a/vendor/github.com/pion/interceptor/pkg/nack/responder_interceptor.go +++ b/vendor/github.com/pion/interceptor/pkg/nack/responder_interceptor.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package nack import ( @@ -17,16 +14,13 @@ type ResponderInterceptorFactory struct { opts []ResponderOption } -type packetFactory interface { - NewPacket(header *rtp.Header, payload []byte) (*retainablePacket, error) -} - // NewInterceptor constructs a new ResponderInterceptor -func (r *ResponderInterceptorFactory) NewInterceptor(_ string) (interceptor.Interceptor, error) { +func (r *ResponderInterceptorFactory) NewInterceptor(id string) (interceptor.Interceptor, error) { i := &ResponderInterceptor{ - size: 1024, - log: logging.NewDefaultLoggerFactory().NewLogger("nack_responder"), - streams: map[uint32]*localStream{}, + size: 8192, + log: logging.NewDefaultLoggerFactory().NewLogger("nack_responder"), + streams: map[uint32]*localStream{}, + packetMan: newPacketManager(), } for _, opt := range r.opts { @@ -35,10 +29,6 @@ func (r *ResponderInterceptorFactory) NewInterceptor(_ string) (interceptor.Inte } } - if i.packetFactory == nil { - i.packetFactory = newPacketManager() - } - if _, err := newSendBuffer(i.size); err != nil { return nil, err } @@ -49,9 +39,9 @@ func (r *ResponderInterceptorFactory) NewInterceptor(_ string) (interceptor.Inte // ResponderInterceptor responds to nack feedback messages type ResponderInterceptor struct { interceptor.NoOp - size uint16 - log logging.LeveledLogger - packetFactory packetFactory + size uint16 + log logging.LeveledLogger + packetMan *packetManager streams map[uint32]*localStream streamsMu sync.Mutex @@ -110,7 +100,7 @@ func (n *ResponderInterceptor) BindLocalStream(info *interceptor.StreamInfo, wri n.streamsMu.Unlock() return interceptor.RTPWriterFunc(func(header *rtp.Header, payload []byte, attributes interceptor.Attributes) (int, error) { - pkt, err := n.packetFactory.NewPacket(header, payload) + pkt, err := n.packetMan.NewPacket(header, payload) if err != nil { return 0, err } diff --git a/vendor/github.com/pion/interceptor/pkg/nack/responder_option.go b/vendor/github.com/pion/interceptor/pkg/nack/responder_option.go index 0aaa7577f..7ad52c8ad 100644 --- a/vendor/github.com/pion/interceptor/pkg/nack/responder_option.go +++ b/vendor/github.com/pion/interceptor/pkg/nack/responder_option.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package nack import "github.com/pion/logging" @@ -24,12 +21,3 @@ func ResponderLog(log logging.LeveledLogger) ResponderOption { return nil } } - -// DisableCopy bypasses copy of underlying packets. It should be used when -// you are not re-using underlying buffers of packets that have been written -func DisableCopy() ResponderOption { - return func(s *ResponderInterceptor) error { - s.packetFactory = &noOpPacketFactory{} - return nil - } -} diff --git a/vendor/github.com/pion/interceptor/pkg/nack/retainable_packet.go b/vendor/github.com/pion/interceptor/pkg/nack/retainable_packet.go index 31e9d832f..89e9cb625 100644 --- a/vendor/github.com/pion/interceptor/pkg/nack/retainable_packet.go +++ b/vendor/github.com/pion/interceptor/pkg/nack/retainable_packet.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package nack import ( @@ -44,20 +41,11 @@ func (m *packetManager) NewPacket(header *rtp.Header, payload []byte) (*retainab count: 1, } - var ok bool - p.header, ok = m.headerPool.Get().(*rtp.Header) - if !ok { - return nil, errFailedToCastHeaderPool - } - + p.header = m.headerPool.Get().(*rtp.Header) *p.header = header.Clone() if payload != nil { - p.buffer, ok = m.payloadPool.Get().(*[]byte) - if !ok { - return nil, errFailedToCastPayloadPool - } - + p.buffer = m.payloadPool.Get().(*[]byte) size := copy(*p.buffer, payload) p.payload = (*p.buffer)[:size] } @@ -72,21 +60,6 @@ func (m *packetManager) releasePacket(header *rtp.Header, payload *[]byte) { } } -type noOpPacketFactory struct{} - -func (f *noOpPacketFactory) NewPacket(header *rtp.Header, payload []byte) (*retainablePacket, error) { - return &retainablePacket{ - onRelease: f.releasePacket, - count: 1, - header: header, - payload: payload, - }, nil -} - -func (f *noOpPacketFactory) releasePacket(_ *rtp.Header, _ *[]byte) { - // no-op -} - type retainablePacket struct { onRelease func(*rtp.Header, *[]byte) diff --git a/vendor/github.com/pion/interceptor/pkg/nack/send_buffer.go b/vendor/github.com/pion/interceptor/pkg/nack/send_buffer.go index e8e816f61..8e3607584 100644 --- a/vendor/github.com/pion/interceptor/pkg/nack/send_buffer.go +++ b/vendor/github.com/pion/interceptor/pkg/nack/send_buffer.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package nack import ( diff --git a/vendor/github.com/pion/interceptor/pkg/report/receiver_interceptor.go b/vendor/github.com/pion/interceptor/pkg/report/receiver_interceptor.go index c126f9abc..cb0e7e1ef 100644 --- a/vendor/github.com/pion/interceptor/pkg/report/receiver_interceptor.go +++ b/vendor/github.com/pion/interceptor/pkg/report/receiver_interceptor.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package report import ( @@ -18,7 +15,7 @@ type ReceiverInterceptorFactory struct { } // NewInterceptor constructs a new ReceiverInterceptor -func (r *ReceiverInterceptorFactory) NewInterceptor(_ string) (interceptor.Interceptor, error) { +func (r *ReceiverInterceptorFactory) NewInterceptor(id string) (interceptor.Interceptor, error) { i := &ReceiverInterceptor{ interval: 1 * time.Second, now: time.Now, @@ -101,9 +98,13 @@ func (r *ReceiverInterceptor) loop(rtcpWriter interceptor.RTCPWriter) { case <-ticker.C: now := r.now() r.streams.Range(func(key, value interface{}) bool { - if stream, ok := value.(*receiverStream); !ok { - r.log.Warnf("failed to cast ReceiverInterceptor stream") - } else if _, err := rtcpWriter.Write([]rtcp.Packet{stream.generateReport(now)}, interceptor.Attributes{}); err != nil { + stream := value.(*receiverStream) + + var pkts []rtcp.Packet + + pkts = append(pkts, stream.generateReport(now)) + + if _, err := rtcpWriter.Write(pkts, interceptor.Attributes{}); err != nil { r.log.Warnf("failed sending: %+v", err) } @@ -171,11 +172,8 @@ func (r *ReceiverInterceptor) BindRTCPReader(reader interceptor.RTCPReader) inte continue } - if stream, ok := value.(*receiverStream); !ok { - r.log.Warnf("failed to cast ReceiverInterceptor stream") - } else { - stream.processSenderReport(r.now(), sr) - } + stream := value.(*receiverStream) + stream.processSenderReport(r.now(), sr) } } diff --git a/vendor/github.com/pion/interceptor/pkg/report/receiver_option.go b/vendor/github.com/pion/interceptor/pkg/report/receiver_option.go index 337a34142..0467dc5de 100644 --- a/vendor/github.com/pion/interceptor/pkg/report/receiver_option.go +++ b/vendor/github.com/pion/interceptor/pkg/report/receiver_option.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package report import ( diff --git a/vendor/github.com/pion/interceptor/pkg/report/receiver_stream.go b/vendor/github.com/pion/interceptor/pkg/report/receiver_stream.go index b899bb1b2..c5722611e 100644 --- a/vendor/github.com/pion/interceptor/pkg/report/receiver_stream.go +++ b/vendor/github.com/pion/interceptor/pkg/report/receiver_stream.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package report import ( diff --git a/vendor/github.com/pion/interceptor/pkg/report/report.go b/vendor/github.com/pion/interceptor/pkg/report/report.go index e4d2e64a4..0a3034ce6 100644 --- a/vendor/github.com/pion/interceptor/pkg/report/report.go +++ b/vendor/github.com/pion/interceptor/pkg/report/report.go @@ -1,5 +1,2 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package report provides interceptors to implement sending sender and receiver reports. package report diff --git a/vendor/github.com/pion/interceptor/pkg/report/sender_interceptor.go b/vendor/github.com/pion/interceptor/pkg/report/sender_interceptor.go index 02d1c0001..0c18e45a8 100644 --- a/vendor/github.com/pion/interceptor/pkg/report/sender_interceptor.go +++ b/vendor/github.com/pion/interceptor/pkg/report/sender_interceptor.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package report import ( @@ -19,7 +16,7 @@ type SenderInterceptorFactory struct { } // NewInterceptor constructs a new SenderInterceptor -func (s *SenderInterceptorFactory) NewInterceptor(_ string) (interceptor.Interceptor, error) { +func (s *SenderInterceptorFactory) NewInterceptor(id string) (interceptor.Interceptor, error) { i := &SenderInterceptor{ interval: 1 * time.Second, now: time.Now, @@ -102,9 +99,21 @@ func (s *SenderInterceptor) loop(rtcpWriter interceptor.RTCPWriter) { case <-ticker.C: now := s.now() s.streams.Range(func(key, value interface{}) bool { - if stream, ok := value.(*senderStream); !ok { - s.log.Warnf("failed to cast SenderInterceptor stream") - } else if _, err := rtcpWriter.Write([]rtcp.Packet{stream.generateReport(now)}, interceptor.Attributes{}); err != nil { + ssrc := key.(uint32) + stream := value.(*senderStream) + + stream.m.Lock() + defer stream.m.Unlock() + + sr := &rtcp.SenderReport{ + SSRC: ssrc, + NTPTime: ntpTime(now), + RTPTime: stream.lastRTPTimeRTP + uint32(now.Sub(stream.lastRTPTimeTime).Seconds()*stream.clockRate), + PacketCount: stream.packetCount, + OctetCount: stream.octetCount, + } + + if _, err := rtcpWriter.Write([]rtcp.Packet{sr}, interceptor.Attributes{}); err != nil { s.log.Warnf("failed sending: %+v", err) } @@ -120,7 +129,7 @@ func (s *SenderInterceptor) loop(rtcpWriter interceptor.RTCPWriter) { // BindLocalStream lets you modify any outgoing RTP packets. It is called once for per LocalStream. The returned method // will be called once per rtp packet. func (s *SenderInterceptor) BindLocalStream(info *interceptor.StreamInfo, writer interceptor.RTPWriter) interceptor.RTPWriter { - stream := newSenderStream(info.SSRC, info.ClockRate) + stream := newSenderStream(info.ClockRate) s.streams.Store(info.SSRC, stream) return interceptor.RTPWriterFunc(func(header *rtp.Header, payload []byte, a interceptor.Attributes) (int, error) { @@ -129,3 +138,13 @@ func (s *SenderInterceptor) BindLocalStream(info *interceptor.StreamInfo, writer return writer.Write(header, payload, a) }) } + +func ntpTime(t time.Time) uint64 { + // seconds since 1st January 1900 + s := (float64(t.UnixNano()) / 1000000000) + 2208988800 + + // higher 32 bits are the integer part, lower 32 bits are the fractional part + integerPart := uint32(s) + fractionalPart := uint32((s - float64(integerPart)) * 0xFFFFFFFF) + return uint64(integerPart)<<32 | uint64(fractionalPart) +} diff --git a/vendor/github.com/pion/interceptor/pkg/report/sender_option.go b/vendor/github.com/pion/interceptor/pkg/report/sender_option.go index 6932e1c0a..4cb161a37 100644 --- a/vendor/github.com/pion/interceptor/pkg/report/sender_option.go +++ b/vendor/github.com/pion/interceptor/pkg/report/sender_option.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package report import ( diff --git a/vendor/github.com/pion/interceptor/pkg/report/sender_stream.go b/vendor/github.com/pion/interceptor/pkg/report/sender_stream.go index 29d14da41..851d70e58 100644 --- a/vendor/github.com/pion/interceptor/pkg/report/sender_stream.go +++ b/vendor/github.com/pion/interceptor/pkg/report/sender_stream.go @@ -1,19 +1,13 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package report import ( "sync" "time" - "github.com/pion/interceptor/internal/ntp" - "github.com/pion/rtcp" "github.com/pion/rtp" ) type senderStream struct { - ssrc uint32 clockRate float64 m sync.Mutex @@ -24,9 +18,8 @@ type senderStream struct { octetCount uint32 } -func newSenderStream(ssrc uint32, clockRate uint32) *senderStream { +func newSenderStream(clockRate uint32) *senderStream { return &senderStream{ - ssrc: ssrc, clockRate: float64(clockRate), } } @@ -42,16 +35,3 @@ func (stream *senderStream) processRTP(now time.Time, header *rtp.Header, payloa stream.packetCount++ stream.octetCount += uint32(len(payload)) } - -func (stream *senderStream) generateReport(now time.Time) *rtcp.SenderReport { - stream.m.Lock() - defer stream.m.Unlock() - - return &rtcp.SenderReport{ - SSRC: stream.ssrc, - NTPTime: ntp.ToNTP(now), - RTPTime: stream.lastRTPTimeRTP + uint32(now.Sub(stream.lastRTPTimeTime).Seconds()*stream.clockRate), - PacketCount: stream.packetCount, - OctetCount: stream.octetCount, - } -} diff --git a/vendor/github.com/pion/interceptor/pkg/twcc/header_extension_interceptor.go b/vendor/github.com/pion/interceptor/pkg/twcc/header_extension_interceptor.go index 791b14592..fa3fb810c 100644 --- a/vendor/github.com/pion/interceptor/pkg/twcc/header_extension_interceptor.go +++ b/vendor/github.com/pion/interceptor/pkg/twcc/header_extension_interceptor.go @@ -1,23 +1,17 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package twcc import ( - "errors" "sync/atomic" "github.com/pion/interceptor" "github.com/pion/rtp" ) -var errHeaderIsNil = errors.New("header is nil") - // HeaderExtensionInterceptorFactory is a interceptor.Factory for a HeaderExtensionInterceptor type HeaderExtensionInterceptorFactory struct{} // NewInterceptor constructs a new HeaderExtensionInterceptor -func (h *HeaderExtensionInterceptorFactory) NewInterceptor(_ string) (interceptor.Interceptor, error) { +func (h *HeaderExtensionInterceptorFactory) NewInterceptor(id string) (interceptor.Interceptor, error) { return &HeaderExtensionInterceptor{}, nil } @@ -54,9 +48,6 @@ func (h *HeaderExtensionInterceptor) BindLocalStream(info *interceptor.StreamInf if err != nil { return 0, err } - if header == nil { - return 0, errHeaderIsNil - } err = header.SetExtension(hdrExtID, tcc) if err != nil { return 0, err diff --git a/vendor/github.com/pion/interceptor/pkg/twcc/sender_interceptor.go b/vendor/github.com/pion/interceptor/pkg/twcc/sender_interceptor.go index 8706e4518..cf8688ebf 100644 --- a/vendor/github.com/pion/interceptor/pkg/twcc/sender_interceptor.go +++ b/vendor/github.com/pion/interceptor/pkg/twcc/sender_interceptor.go @@ -1,10 +1,6 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package twcc import ( - "errors" "math/rand" "sync" "time" @@ -19,10 +15,8 @@ type SenderInterceptorFactory struct { opts []Option } -var errClosed = errors.New("interceptor is closed") - // NewInterceptor constructs a new SenderInterceptor -func (s *SenderInterceptorFactory) NewInterceptor(_ string) (interceptor.Interceptor, error) { +func (s *SenderInterceptorFactory) NewInterceptor(id string) (interceptor.Interceptor, error) { i := &SenderInterceptor{ log: logging.NewDefaultLoggerFactory().NewLogger("twcc_sender_interceptor"), packetChan: make(chan packet), @@ -135,17 +129,12 @@ func (s *SenderInterceptor) BindRemoteStream(info *interceptor.StreamInfo, reade return 0, nil, err } - p := packet{ + s.packetChan <- packet{ hdr: header, sequenceNumber: tccExt.TransportSequence, arrivalTime: time.Since(s.startTime).Microseconds(), ssrc: info.SSRC, } - select { - case <-s.close: - return 0, nil, errClosed - case s.packetChan <- p: - } } return i, attr, nil @@ -177,13 +166,6 @@ func (s *SenderInterceptor) isClosed() bool { func (s *SenderInterceptor) loop(w interceptor.RTCPWriter) { defer s.wg.Done() - select { - case <-s.close: - return - case p := <-s.packetChan: - s.recorder.Record(p.ssrc, p.sequenceNumber, p.arrivalTime) - } - ticker := time.NewTicker(s.interval) for { select { diff --git a/vendor/github.com/pion/interceptor/pkg/twcc/twcc.go b/vendor/github.com/pion/interceptor/pkg/twcc/twcc.go index 235f1f11c..0e43f69ab 100644 --- a/vendor/github.com/pion/interceptor/pkg/twcc/twcc.go +++ b/vendor/github.com/pion/interceptor/pkg/twcc/twcc.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package twcc provides interceptors to implement transport wide congestion control. package twcc @@ -73,12 +70,13 @@ func insertSorted(list []pktInfo, element pktInfo) []pktInfo { // BuildFeedbackPacket creates a new RTCP packet containing a TWCC feedback report. func (r *Recorder) BuildFeedbackPacket() []rtcp.Packet { - if len(r.receivedPackets) < 2 { - return nil - } - feedback := newFeedback(r.senderSSRC, r.mediaSSRC, r.fbPktCnt) r.fbPktCnt++ + if len(r.receivedPackets) < 2 { + r.receivedPackets = []pktInfo{} + return []rtcp.Packet{feedback.getRTCP()} + } + feedback.setBase(uint16(r.receivedPackets[0].sequenceNumber&0xffff), r.receivedPackets[0].arrivalTime) var pkts []rtcp.Packet diff --git a/vendor/github.com/pion/interceptor/registry.go b/vendor/github.com/pion/interceptor/registry.go index e36ef6bfb..1347193d4 100644 --- a/vendor/github.com/pion/interceptor/registry.go +++ b/vendor/github.com/pion/interceptor/registry.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package interceptor // Registry is a collector for interceptors. diff --git a/vendor/github.com/pion/interceptor/renovate.json b/vendor/github.com/pion/interceptor/renovate.json index f1bb98c6a..f1614058a 100644 --- a/vendor/github.com/pion/interceptor/renovate.json +++ b/vendor/github.com/pion/interceptor/renovate.json @@ -1,6 +1,27 @@ { - "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ - "github>pion/renovate-config" + "config:base", + ":disableDependencyDashboard" + ], + "postUpdateOptions": [ + "gomodTidy" + ], + "commitBody": "Generated by renovateBot", + "packageRules": [ + { + "matchUpdateTypes": ["minor", "patch", "pin", "digest"], + "automerge": true + }, + { + "packagePatterns": ["^golang.org/x/"], + "schedule": ["on the first day of the month"] + } + ], + "ignorePaths": [ + ".github/workflows/generate-authors.yml", + ".github/workflows/lint.yaml", + ".github/workflows/renovate-go-mod-fix.yaml", + ".github/workflows/test.yaml", + ".github/workflows/tidy-check.yaml" ] } diff --git a/vendor/github.com/pion/interceptor/streaminfo.go b/vendor/github.com/pion/interceptor/streaminfo.go index 4108159c5..956fa5306 100644 --- a/vendor/github.com/pion/interceptor/streaminfo.go +++ b/vendor/github.com/pion/interceptor/streaminfo.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package interceptor // RTPHeaderExtension represents a negotiated RFC5285 RTP header extension. diff --git a/vendor/github.com/pion/mdns/.gitignore b/vendor/github.com/pion/mdns/.gitignore index f977e7485..83db74ba5 100644 --- a/vendor/github.com/pion/mdns/.gitignore +++ b/vendor/github.com/pion/mdns/.gitignore @@ -22,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/mdns/.golangci.yml b/vendor/github.com/pion/mdns/.golangci.yml index 48696f16b..d6162c970 100644 --- a/vendor/github.com/pion/mdns/.golangci.yml +++ b/vendor/github.com/pion/mdns/.golangci.yml @@ -15,21 +15,14 @@ linters-settings: linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - - decorder # check declaration order and count of types, constants, variables and functions + - deadcode # Finds unused code - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -42,60 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks + - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - - wastedassign # wastedassign finds wasted assignment statements + - varcheck # Finds unused global variables and constants - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - - forbidigo # Forbids identifiers - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: diff --git a/vendor/github.com/pion/mdns/.goreleaser.yml b/vendor/github.com/pion/mdns/.goreleaser.yml deleted file mode 100644 index 2caa5fbd3..000000000 --- a/vendor/github.com/pion/mdns/.goreleaser.yml +++ /dev/null @@ -1,2 +0,0 @@ -builds: -- skip: true diff --git a/vendor/github.com/pion/mdns/AUTHORS.txt b/vendor/github.com/pion/mdns/AUTHORS.txt deleted file mode 100644 index 48ceb8211..000000000 --- a/vendor/github.com/pion/mdns/AUTHORS.txt +++ /dev/null @@ -1,17 +0,0 @@ -# Thank you to everyone that made Pion possible. If you are interested in contributing -# we would love to have you https://github.com/pion/webrtc/wiki/Contributing -# -# This file is auto generated, using git to list all individuals contributors. -# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting -Atsushi Watanabe -Bjørn Remseth -Doug Cone -Hugo Arregui -Javier Peletier -Jonas van den Berg <24623262+vonas@users.noreply.github.com> -Konstantin Itskov -Sean DuBois -Sean DuBois - -# List of contributors not appearing in Git history - diff --git a/vendor/github.com/pion/mdns/README.md b/vendor/github.com/pion/mdns/README.md index b2d7d9c73..634699e02 100644 --- a/vendor/github.com/pion/mdns/README.md +++ b/vendor/github.com/pion/mdns/README.md @@ -21,7 +21,7 @@ Go mDNS implementation. The original user is Pion WebRTC, but we would love to s ### Running Server For a mDNS server that responds to queries for `pion-test.local` ```sh -go run examples/server/main.go +go run examples/listen/main.go ``` @@ -55,5 +55,11 @@ If you need commercial support or don't want to use public methods you can conta ### Contributing Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible: +* [Sean DuBois](https://github.com/Sean-Der) - *Original Author* +* [Konstantin Itskov](https://github.com/trivigy) - Contributor +* [Hugo Arregui](https://github.com/hugoArregui) +* [Atsushi Watanabe](https://github.com/at-wat) +* [Doug Cone](https://github.com/nullvariable) + ### License MIT License - see [LICENSE](LICENSE) for full text diff --git a/vendor/github.com/pion/mdns/conn.go b/vendor/github.com/pion/mdns/conn.go index 31037e252..2c169e2a6 100644 --- a/vendor/github.com/pion/mdns/conn.go +++ b/vendor/github.com/pion/mdns/conn.go @@ -5,7 +5,6 @@ import ( "errors" "math/big" "net" - "runtime" "sync" "time" @@ -25,7 +24,6 @@ type Conn struct { queryInterval time.Duration localNames []string queries []query - ifaces []net.Interface closed chan interface{} } @@ -41,14 +39,13 @@ type queryResult struct { } const ( + inboundBufferSize = 512 defaultQueryInterval = time.Second destinationAddress = "224.0.0.251:5353" maxMessageRecords = 3 responseTTL = 120 ) -var errNoPositiveMTUFound = errors.New("no positive MTU found") - // Server establishes a mDNS connection over an existing conn func Server(conn *ipv4.PacketConn, config *Config) (*Conn, error) { if config == nil { @@ -60,24 +57,11 @@ func Server(conn *ipv4.PacketConn, config *Config) (*Conn, error) { return nil, err } - inboundBufferSize := 0 joinErrCount := 0 - ifacesToUse := make([]net.Interface, 0, len(ifaces)) - for i, ifc := range ifaces { + for i := range ifaces { if err = conn.JoinGroup(&ifaces[i], &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251)}); err != nil { joinErrCount++ - continue } - - ifcCopy := ifc - ifacesToUse = append(ifacesToUse, ifcCopy) - if ifaces[i].MTU > inboundBufferSize { - inboundBufferSize = ifaces[i].MTU - } - } - - if inboundBufferSize == 0 { - return nil, errNoPositiveMTUFound } if joinErrCount >= len(ifaces) { return nil, errJoiningMulticastGroup @@ -104,7 +88,6 @@ func Server(conn *ipv4.PacketConn, config *Config) (*Conn, error) { socket: conn, dstAddr: dstAddr, localNames: localNames, - ifaces: ifacesToUse, log: loggerFactory.NewLogger("mdns"), closed: make(chan interface{}), } @@ -112,11 +95,7 @@ func Server(conn *ipv4.PacketConn, config *Config) (*Conn, error) { c.queryInterval = config.QueryInterval } - // https://www.rfc-editor.org/rfc/rfc6762.html#section-17 - // Multicast DNS messages carried by UDP may be up to the IP MTU of the - // physical interface, less the space required for the IP header (20 - // bytes for IPv4; 40 bytes for IPv6) and the UDP header (8 bytes). - go c.start(inboundBufferSize - 20 - 8) + go c.start() return c, nil } @@ -188,11 +167,7 @@ func interfaceForRemote(remote string) (net.IP, error) { return nil, err } - localAddr, ok := conn.LocalAddr().(*net.UDPAddr) - if !ok { - return nil, errFailedCast - } - + localAddr := conn.LocalAddr().(*net.UDPAddr) if err := conn.Close(); err != nil { return nil, err } @@ -224,24 +199,9 @@ func (c *Conn) sendQuestion(name string) { return } - c.writeToSocket(rawQuery) -} - -const isWindows = runtime.GOOS == "windows" - -func (c *Conn) writeToSocket(b []byte) { - var wcm ipv4.ControlMessage - for i := range c.ifaces { - if isWindows { - if err := c.socket.SetMulticastInterface(&c.ifaces[i]); err != nil { - c.log.Warnf("Failed to set multicast interface for %d: %v", i, err) - } - } else { - wcm.IfIndex = c.ifaces[i].Index - } - if _, err := c.socket.WriteTo(b, &wcm, c.dstAddr); err != nil { - c.log.Warnf("Failed to send mDNS packet on interface %d: %v", i, err) - } + if _, err := c.socket.WriteTo(rawQuery, nil, c.dstAddr); err != nil { + c.log.Warnf("Failed to send mDNS packet %v", err) + return } } @@ -278,10 +238,13 @@ func (c *Conn) sendAnswer(name string, dst net.IP) { return } - c.writeToSocket(rawAnswer) + if _, err := c.socket.WriteTo(rawAnswer, nil, c.dstAddr); err != nil { + c.log.Warnf("Failed to send mDNS packet %v", err) + return + } } -func (c *Conn) start(inboundBufferSize int) { //nolint gocognit +func (c *Conn) start() { //nolint gocognit defer func() { c.mu.Lock() defer c.mu.Unlock() @@ -294,11 +257,7 @@ func (c *Conn) start(inboundBufferSize int) { //nolint gocognit for { n, _, src, err := c.socket.ReadFrom(b) if err != nil { - if errors.Is(err, net.ErrClosed) { - return - } - c.log.Warnf("Failed to ReadFrom %q %v", src, err) - continue + return } func() { @@ -348,15 +307,7 @@ func (c *Conn) start(inboundBufferSize int) { //nolint gocognit for i := len(c.queries) - 1; i >= 0; i-- { if c.queries[i].nameWithSuffix == a.Name.String() { - ip, err := ipFromAnswerHeader(a, p) - if err != nil { - c.log.Warnf("Failed to parse mDNS answer %v", err) - return - } - - c.queries[i].queryResultChan <- queryResult{a, &net.IPAddr{ - IP: ip, - }} + c.queries[i].queryResultChan <- queryResult{a, src} c.queries = append(c.queries[:i], c.queries[i+1:]...) } } @@ -364,21 +315,3 @@ func (c *Conn) start(inboundBufferSize int) { //nolint gocognit }() } } - -func ipFromAnswerHeader(a dnsmessage.ResourceHeader, p dnsmessage.Parser) (ip []byte, err error) { - if a.Type == dnsmessage.TypeA { - resource, err := p.AResource() - if err != nil { - return nil, err - } - ip = net.IP(resource.A[:]) - } else { - resource, err := p.AAAAResource() - if err != nil { - return nil, err - } - ip = resource.AAAA[:] - } - - return -} diff --git a/vendor/github.com/pion/mdns/errors.go b/vendor/github.com/pion/mdns/errors.go index 0a1b61240..2f8dc928b 100644 --- a/vendor/github.com/pion/mdns/errors.go +++ b/vendor/github.com/pion/mdns/errors.go @@ -7,5 +7,4 @@ var ( errConnectionClosed = errors.New("mDNS: connection is closed") errContextElapsed = errors.New("mDNS: context has elapsed") errNilConfig = errors.New("mDNS: config must not be nil") - errFailedCast = errors.New("mDNS: failed to cast listener to UDPAddr") ) diff --git a/vendor/github.com/pion/mdns/renovate.json b/vendor/github.com/pion/mdns/renovate.json index f1bb98c6a..4400fd9b2 100644 --- a/vendor/github.com/pion/mdns/renovate.json +++ b/vendor/github.com/pion/mdns/renovate.json @@ -1,6 +1,15 @@ { - "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ - "github>pion/renovate-config" + "config:base" + ], + "postUpdateOptions": [ + "gomodTidy" + ], + "commitBody": "Generated by renovateBot", + "packageRules": [ + { + "packagePatterns": ["^golang.org/x/"], + "schedule": ["on the first day of the month"] + } ] } diff --git a/vendor/github.com/pion/rtcp/.gitignore b/vendor/github.com/pion/rtcp/.gitignore index f977e7485..83db74ba5 100644 --- a/vendor/github.com/pion/rtcp/.gitignore +++ b/vendor/github.com/pion/rtcp/.gitignore @@ -22,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/rtcp/.golangci.yml b/vendor/github.com/pion/rtcp/.golangci.yml index d7a88eca3..d6162c970 100644 --- a/vendor/github.com/pion/rtcp/.golangci.yml +++ b/vendor/github.com/pion/rtcp/.golangci.yml @@ -15,22 +15,14 @@ linters-settings: linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - deadcode # Finds unused code - - decorder # check declaration order and count of types, constants, variables and functions - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -43,62 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - varcheck # Finds unused global variables and constants - - wastedassign # wastedassign finds wasted assignment statements - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - - forbidigo # Forbids identifiers - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: diff --git a/vendor/github.com/pion/rtcp/AUTHORS.txt b/vendor/github.com/pion/rtcp/AUTHORS.txt index 5d5a53cc2..783fc31ef 100644 --- a/vendor/github.com/pion/rtcp/AUTHORS.txt +++ b/vendor/github.com/pion/rtcp/AUTHORS.txt @@ -15,7 +15,6 @@ Juliusz Chroboczek Kevin Wang lllf Luke Curley -Mathis Engelbart Max Hawkins Sean DuBois Sean DuBois diff --git a/vendor/github.com/pion/rtcp/fuzz.go b/vendor/github.com/pion/rtcp/fuzz.go index b8118224a..2ea4fb1fc 100644 --- a/vendor/github.com/pion/rtcp/fuzz.go +++ b/vendor/github.com/pion/rtcp/fuzz.go @@ -1,4 +1,3 @@ -//go:build gofuzz // +build gofuzz package rtcp diff --git a/vendor/github.com/pion/rtcp/header.go b/vendor/github.com/pion/rtcp/header.go index 43f6abc06..5bc34abe5 100644 --- a/vendor/github.com/pion/rtcp/header.go +++ b/vendor/github.com/pion/rtcp/header.go @@ -27,7 +27,6 @@ const ( FormatFIR uint8 = 4 FormatTLN uint8 = 1 FormatRRR uint8 = 5 - FormatCCFB uint8 = 11 FormatREMB uint8 = 15 // https://tools.ietf.org/html/draft-holmer-rmcat-transport-wide-cc-extensions-01#page-5 diff --git a/vendor/github.com/pion/rtcp/packet.go b/vendor/github.com/pion/rtcp/packet.go index 885d52cde..0200a79c0 100644 --- a/vendor/github.com/pion/rtcp/packet.go +++ b/vendor/github.com/pion/rtcp/packet.go @@ -87,8 +87,6 @@ func unmarshal(rawData []byte) (packet Packet, bytesprocessed int, err error) { packet = new(RapidResynchronizationRequest) case FormatTCC: packet = new(TransportLayerCC) - case FormatCCFB: - packet = new(CCFeedbackReport) default: packet = new(RawPacket) } diff --git a/vendor/github.com/pion/rtcp/rapid_resynchronization_request.go b/vendor/github.com/pion/rtcp/rapid_resynchronization_request.go index 00c7e8626..b876e9c88 100644 --- a/vendor/github.com/pion/rtcp/rapid_resynchronization_request.go +++ b/vendor/github.com/pion/rtcp/rapid_resynchronization_request.go @@ -14,10 +14,6 @@ type RapidResynchronizationRequest struct { MediaSSRC uint32 } -// RapidResynchronisationRequest is provided as RFC 6051 spells resynchronization with an s. -// We provide both names to be consistent with other RFCs which spell resynchronization with a z. -type RapidResynchronisationRequest = RapidResynchronizationRequest - const ( rrrLength = 2 rrrHeaderLength = ssrcLength * 2 diff --git a/vendor/github.com/pion/rtcp/rfc8888.go b/vendor/github.com/pion/rtcp/rfc8888.go deleted file mode 100644 index 8527fc8e7..000000000 --- a/vendor/github.com/pion/rtcp/rfc8888.go +++ /dev/null @@ -1,325 +0,0 @@ -package rtcp - -import ( - "encoding/binary" - "errors" - "fmt" -) - -// https://www.rfc-editor.org/rfc/rfc8888.html#name-rtcp-congestion-control-fee -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// |V=2|P| FMT=11 | PT = 205 | length | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | SSRC of RTCP packet sender | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | SSRC of 1st RTP Stream | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | begin_seq | num_reports | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// |R|ECN| Arrival time offset | ... . -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// . . -// . . -// . . -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | SSRC of nth RTP Stream | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | begin_seq | num_reports | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// |R|ECN| Arrival time offset | ... | -// . . -// . . -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | Report Timestamp (32 bits) | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - -var ( - errReportBlockLength = errors.New("feedback report blocks must be at least 8 bytes") - errIncorrectNumReports = errors.New("feedback report block contains less reports than num_reports") - errMetricBlockLength = errors.New("feedback report metric blocks must be exactly 2 bytes") -) - -// ECN represents the two ECN bits -type ECN uint8 - -const ( - //nolint:misspell - // ECNNonECT signals Non ECN-Capable Transport, Non-ECT - ECNNonECT ECN = iota // 00 - - //nolint:misspell - // ECNECT1 signals ECN Capable Transport, ECT(0) - ECNECT1 // 01 - - //nolint:misspell - // ECNECT0 signals ECN Capable Transport, ECT(1) - ECNECT0 // 10 - - // ECNCE signals ECN Congestion Encountered, CE - ECNCE // 11 -) - -const ( - reportTimestampLength = 4 - reportBlockOffset = 8 -) - -// CCFeedbackReport is a Congestion Control Feedback Report as defined in -// https://www.rfc-editor.org/rfc/rfc8888.html#name-rtcp-congestion-control-fee -type CCFeedbackReport struct { - // SSRC of sender - SenderSSRC uint32 - - // Report Blocks - ReportBlocks []CCFeedbackReportBlock - - // Basetime - ReportTimestamp uint32 -} - -// DestinationSSRC returns an array of SSRC values that this packet refers to. -func (b CCFeedbackReport) DestinationSSRC() []uint32 { - ssrcs := make([]uint32, len(b.ReportBlocks)) - for i, block := range b.ReportBlocks { - ssrcs[i] = block.MediaSSRC - } - return ssrcs -} - -// Len returns the length of the report in bytes -func (b *CCFeedbackReport) Len() uint16 { - n := uint16(0) - for _, block := range b.ReportBlocks { - n += block.len() - } - return reportBlockOffset + n + reportTimestampLength -} - -// Header returns the Header associated with this packet. -func (b *CCFeedbackReport) Header() Header { - return Header{ - Padding: false, - Count: FormatCCFB, - Type: TypeTransportSpecificFeedback, - Length: b.Len()/4 - 1, - } -} - -// Marshal encodes the Congestion Control Feedback Report in binary -func (b CCFeedbackReport) Marshal() ([]byte, error) { - header := b.Header() - headerBuf, err := header.Marshal() - if err != nil { - return nil, err - } - length := 4 * (header.Length + 1) - buf := make([]byte, length) - copy(buf[:headerLength], headerBuf) - binary.BigEndian.PutUint32(buf[headerLength:], b.SenderSSRC) - offset := uint16(reportBlockOffset) - for _, block := range b.ReportBlocks { - b, err := block.marshal() - if err != nil { - return nil, err - } - copy(buf[offset:], b) - offset += block.len() - } - - binary.BigEndian.PutUint32(buf[offset:], b.ReportTimestamp) - return buf, nil -} - -func (b CCFeedbackReport) String() string { - out := fmt.Sprintf("CCFB:\n\tHeader %v\n", b.Header()) - out += fmt.Sprintf("CCFB:\n\tSender SSRC %d\n", b.SenderSSRC) - out += fmt.Sprintf("\tReport Timestamp %d\n", b.ReportTimestamp) - out += "\tFeedback Reports \n" - for _, report := range b.ReportBlocks { - out += fmt.Sprintf("%v ", report) - } - out += "\n" - return out -} - -// Unmarshal decodes the Congestion Control Feedback Report from binary -func (b *CCFeedbackReport) Unmarshal(rawPacket []byte) error { - if len(rawPacket) < headerLength+ssrcLength+reportTimestampLength { - return errPacketTooShort - } - - var h Header - if err := h.Unmarshal(rawPacket); err != nil { - return err - } - if h.Type != TypeTransportSpecificFeedback { - return errWrongType - } - - b.SenderSSRC = binary.BigEndian.Uint32(rawPacket[headerLength:]) - - reportTimestampOffset := uint16(len(rawPacket) - reportTimestampLength) - b.ReportTimestamp = binary.BigEndian.Uint32(rawPacket[reportTimestampOffset:]) - - offset := uint16(reportBlockOffset) - b.ReportBlocks = []CCFeedbackReportBlock{} - for offset < reportTimestampOffset { - var block CCFeedbackReportBlock - if err := block.unmarshal(rawPacket[offset:]); err != nil { - return err - } - b.ReportBlocks = append(b.ReportBlocks, block) - offset += block.len() - } - - return nil -} - -const ( - ssrcOffset = 0 - beginSequenceOffset = 4 - numReportsOffset = 6 - reportsOffset = 8 - - maxMetricBlocks = 16384 -) - -// CCFeedbackReportBlock is a Feedback Report Block -type CCFeedbackReportBlock struct { - // SSRC of the RTP stream on which this block is reporting - MediaSSRC uint32 - BeginSequence uint16 - MetricBlocks []CCFeedbackMetricBlock -} - -// len returns the length of the report block in bytes -func (b *CCFeedbackReportBlock) len() uint16 { - n := len(b.MetricBlocks) - if n%2 != 0 { - n++ - } - return reportsOffset + 2*uint16(n) -} - -func (b CCFeedbackReportBlock) String() string { - out := fmt.Sprintf("\tReport Block Media SSRC %d\n", b.MediaSSRC) - out += fmt.Sprintf("\tReport Begin Sequence Nr %d\n", b.BeginSequence) - out += fmt.Sprintf("\tReport length %d\n\t", len(b.MetricBlocks)) - for i, block := range b.MetricBlocks { - out += fmt.Sprintf("{nr: %d, rx: %v, ts: %v} ", b.BeginSequence+uint16(i), block.Received, block.ArrivalTimeOffset) - } - out += "\n" - return out -} - -// marshal encodes the Congestion Control Feedback Report Block in binary -func (b CCFeedbackReportBlock) marshal() ([]byte, error) { - if len(b.MetricBlocks) > maxMetricBlocks { - return nil, errTooManyReports - } - - buf := make([]byte, b.len()) - binary.BigEndian.PutUint32(buf[ssrcOffset:], b.MediaSSRC) - binary.BigEndian.PutUint16(buf[beginSequenceOffset:], b.BeginSequence) - - length := uint16(len(b.MetricBlocks)) - if length > 0 { - length-- - } - - binary.BigEndian.PutUint16(buf[numReportsOffset:], length) - - for i, block := range b.MetricBlocks { - b, err := block.marshal() - if err != nil { - return nil, err - } - copy(buf[reportsOffset+i*2:], b) - } - - return buf, nil -} - -// Unmarshal decodes the Congestion Control Feedback Report Block from binary -func (b *CCFeedbackReportBlock) unmarshal(rawPacket []byte) error { - if len(rawPacket) < reportsOffset { - return errReportBlockLength - } - b.MediaSSRC = binary.BigEndian.Uint32(rawPacket[:beginSequenceOffset]) - b.BeginSequence = binary.BigEndian.Uint16(rawPacket[beginSequenceOffset:numReportsOffset]) - numReportsField := binary.BigEndian.Uint16(rawPacket[numReportsOffset:]) - if numReportsField == 0 { - return nil - } - endSequence := b.BeginSequence + numReportsField - numReports := endSequence - b.BeginSequence + 1 - - if len(rawPacket) < int(reportsOffset+numReports*2) { - return errIncorrectNumReports - } - b.MetricBlocks = make([]CCFeedbackMetricBlock, numReports) - for i := uint16(0); i < numReports; i++ { - var mb CCFeedbackMetricBlock - offset := reportsOffset + 2*i - if err := mb.unmarshal(rawPacket[offset : offset+2]); err != nil { - return err - } - b.MetricBlocks[i] = mb - } - return nil -} - -const ( - metricBlockLength = 2 -) - -// CCFeedbackMetricBlock is a Feedback Metric Block -type CCFeedbackMetricBlock struct { - Received bool - ECN ECN - - // Offset in 1/1024 seconds before Report Timestamp - ArrivalTimeOffset uint16 -} - -// Marshal encodes the Congestion Control Feedback Metric Block in binary -func (b CCFeedbackMetricBlock) marshal() ([]byte, error) { - buf := make([]byte, 2) - r := uint16(0) - if b.Received { - r = 1 - } - dst, err := setNBitsOfUint16(0, 1, 0, r) - if err != nil { - return nil, err - } - dst, err = setNBitsOfUint16(dst, 2, 1, uint16(b.ECN)) - if err != nil { - return nil, err - } - dst, err = setNBitsOfUint16(dst, 13, 3, b.ArrivalTimeOffset) - if err != nil { - return nil, err - } - - binary.BigEndian.PutUint16(buf, dst) - return buf, nil -} - -// Unmarshal decodes the Congestion Control Feedback Metric Block from binary -func (b *CCFeedbackMetricBlock) unmarshal(rawPacket []byte) error { - if len(rawPacket) != metricBlockLength { - return errMetricBlockLength - } - b.Received = rawPacket[0]&0x80 != 0 - if !b.Received { - b.ECN = ECNNonECT - b.ArrivalTimeOffset = 0 - return nil - } - b.ECN = ECN(rawPacket[0] >> 5 & 0x03) - b.ArrivalTimeOffset = binary.BigEndian.Uint16(rawPacket) & 0x1FFF - return nil -} diff --git a/vendor/github.com/pion/rtcp/source_description.go b/vendor/github.com/pion/rtcp/source_description.go index c4483c301..d62e57a87 100644 --- a/vendor/github.com/pion/rtcp/source_description.go +++ b/vendor/github.com/pion/rtcp/source_description.go @@ -61,19 +61,6 @@ type SourceDescription struct { Chunks []SourceDescriptionChunk } -// NewCNAMESourceDescription creates a new SourceDescription with a single CNAME item. -func NewCNAMESourceDescription(ssrc uint32, cname string) *SourceDescription { - return &SourceDescription{ - Chunks: []SourceDescriptionChunk{{ - Source: ssrc, - Items: []SourceDescriptionItem{{ - Type: SDESCNAME, - Text: cname, - }}, - }}, - } -} - // Marshal encodes the SourceDescription in binary func (s SourceDescription) Marshal() ([]byte, error) { /* @@ -255,16 +242,16 @@ func (s *SourceDescriptionChunk) Unmarshal(rawPacket []byte) error { } func (s SourceDescriptionChunk) len() int { - chunkLen := sdesSourceLen + len := sdesSourceLen for _, it := range s.Items { - chunkLen += it.len() + len += it.len() } - chunkLen += sdesTypeLen // for terminating null octet + len += sdesTypeLen // for terminating null octet // align to 32-bit boundary - chunkLen += getPadding(chunkLen) + len += getPadding(len) - return chunkLen + return len } // A SourceDescriptionItem is a part of a SourceDescription that describes a stream. diff --git a/vendor/github.com/pion/rtcp/util.go b/vendor/github.com/pion/rtcp/util.go index 95e8f1a83..5702d35f8 100644 --- a/vendor/github.com/pion/rtcp/util.go +++ b/vendor/github.com/pion/rtcp/util.go @@ -1,11 +1,11 @@ package rtcp // getPadding Returns the padding required to make the length a multiple of 4 -func getPadding(packetLen int) int { - if packetLen%4 == 0 { +func getPadding(len int) int { + if len%4 == 0 { return 0 } - return 4 - (packetLen % 4) + return 4 - (len % 4) } // setNBitsOfUint16 will truncate the value to size, left-shift to startIndex position and set diff --git a/vendor/github.com/pion/rtp/.gitignore b/vendor/github.com/pion/rtp/.gitignore index f977e7485..83db74ba5 100644 --- a/vendor/github.com/pion/rtp/.gitignore +++ b/vendor/github.com/pion/rtp/.gitignore @@ -22,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/rtp/AUTHORS.txt b/vendor/github.com/pion/rtp/AUTHORS.txt index a7bc7a02b..52d7bd90a 100644 --- a/vendor/github.com/pion/rtp/AUTHORS.txt +++ b/vendor/github.com/pion/rtp/AUTHORS.txt @@ -27,10 +27,8 @@ Michael Uti Raphael Derosso Pereira Rob Lofthouse Robin Raymond -Sean DuBois Sean DuBois Sean DuBois Simone Gotti Tarrence van As -wangzixiang Woodrow Douglass diff --git a/vendor/github.com/pion/rtp/abssendtimeextension.go b/vendor/github.com/pion/rtp/abssendtimeextension.go index f0c6de375..fc9731d0b 100644 --- a/vendor/github.com/pion/rtp/abssendtimeextension.go +++ b/vendor/github.com/pion/rtp/abssendtimeextension.go @@ -15,7 +15,7 @@ type AbsSendTimeExtension struct { } // Marshal serializes the members to buffer. -func (t AbsSendTimeExtension) Marshal() ([]byte, error) { +func (t *AbsSendTimeExtension) Marshal() ([]byte, error) { return []byte{ byte(t.Timestamp & 0xFF0000 >> 16), byte(t.Timestamp & 0xFF00 >> 8), diff --git a/vendor/github.com/pion/rtp/audiolevelextension.go b/vendor/github.com/pion/rtp/audiolevelextension.go index ca44f2870..f8701e153 100644 --- a/vendor/github.com/pion/rtp/audiolevelextension.go +++ b/vendor/github.com/pion/rtp/audiolevelextension.go @@ -36,7 +36,7 @@ type AudioLevelExtension struct { } // Marshal serializes the members to buffer -func (a AudioLevelExtension) Marshal() ([]byte, error) { +func (a *AudioLevelExtension) Marshal() ([]byte, error) { if a.Level > 127 { return nil, errAudioLevelOverflow } diff --git a/vendor/github.com/pion/rtp/codecs/av1_packet.go b/vendor/github.com/pion/rtp/codecs/av1_packet.go deleted file mode 100644 index 120a904c1..000000000 --- a/vendor/github.com/pion/rtp/codecs/av1_packet.go +++ /dev/null @@ -1,158 +0,0 @@ -package codecs - -import ( - "github.com/pion/rtp/pkg/obu" -) - -const ( - zMask = byte(0b10000000) - zBitshift = 7 - - yMask = byte(0b01000000) - yBitshift = 6 - - wMask = byte(0b00110000) - wBitshift = 4 - - nMask = byte(0b00001000) - nBitshift = 3 - - av1PayloaderHeadersize = 1 -) - -// AV1Payloader payloads AV1 packets -type AV1Payloader struct{} - -// Payload fragments a AV1 packet across one or more byte arrays -// See AV1Packet for description of AV1 Payload Header -func (p *AV1Payloader) Payload(mtu uint16, payload []byte) (payloads [][]byte) { - maxFragmentSize := int(mtu) - av1PayloaderHeadersize - 2 - payloadDataRemaining := len(payload) - payloadDataIndex := 0 - - // Make sure the fragment/payload size is correct - if min(maxFragmentSize, payloadDataRemaining) <= 0 { - return payloads - } - - for payloadDataRemaining > 0 { - currentFragmentSize := min(maxFragmentSize, payloadDataRemaining) - leb128Size := 1 - if currentFragmentSize >= 127 { - leb128Size = 2 - } - - out := make([]byte, av1PayloaderHeadersize+leb128Size+currentFragmentSize) - leb128Value := obu.EncodeLEB128(uint(currentFragmentSize)) - if leb128Size == 1 { - out[1] = byte(leb128Value) - } else { - out[1] = byte(leb128Value >> 8) - out[2] = byte(leb128Value) - } - - copy(out[av1PayloaderHeadersize+leb128Size:], payload[payloadDataIndex:payloadDataIndex+currentFragmentSize]) - payloads = append(payloads, out) - - payloadDataRemaining -= currentFragmentSize - payloadDataIndex += currentFragmentSize - - if len(payloads) > 1 { - out[0] ^= zMask - } - if payloadDataRemaining != 0 { - out[0] ^= yMask - } - } - - return payloads -} - -// AV1Packet represents a depacketized AV1 RTP Packet -// -// 0 1 2 3 4 5 6 7 -// +-+-+-+-+-+-+-+-+ -// |Z|Y| W |N|-|-|-| -// +-+-+-+-+-+-+-+-+ -// -// https://aomediacodec.github.io/av1-rtp-spec/#44-av1-aggregation-header -type AV1Packet struct { - // Z: MUST be set to 1 if the first OBU element is an - // OBU fragment that is a continuation of an OBU fragment - // from the previous packet, and MUST be set to 0 otherwise. - Z bool - - // Y: MUST be set to 1 if the last OBU element is an OBU fragment - // that will continue in the next packet, and MUST be set to 0 otherwise. - Y bool - - // W: two bit field that describes the number of OBU elements in the packet. - // This field MUST be set equal to 0 or equal to the number of OBU elements - // contained in the packet. If set to 0, each OBU element MUST be preceded by - // a length field. If not set to 0 (i.e., W = 1, 2 or 3) the last OBU element - // MUST NOT be preceded by a length field. Instead, the length of the last OBU - // element contained in the packet can be calculated as follows: - // Length of the last OBU element = - // length of the RTP payload - // - length of aggregation header - // - length of previous OBU elements including length fields - W byte - - // N: MUST be set to 1 if the packet is the first packet of a coded video sequence, and MUST be set to 0 otherwise. - N bool - - // Each AV1 RTP Packet is a collection of OBU Elements. Each OBU Element may be a full OBU, or just a fragment of one. - // AV1Frame provides the tools to construct a collection of OBUs from a collection of OBU Elements - OBUElements [][]byte -} - -// Unmarshal parses the passed byte slice and stores the result in the AV1Packet this method is called upon -func (p *AV1Packet) Unmarshal(payload []byte) ([]byte, error) { - if payload == nil { - return nil, errNilPacket - } else if len(payload) < 2 { - return nil, errShortPacket - } - - p.Z = ((payload[0] & zMask) >> zBitshift) != 0 - p.Y = ((payload[0] & yMask) >> yBitshift) != 0 - p.N = ((payload[0] & nMask) >> nBitshift) != 0 - p.W = (payload[0] & wMask) >> wBitshift - - if p.Z && p.N { - return nil, errIsKeyframeAndFragment - } - - currentIndex := uint(1) - p.OBUElements = [][]byte{} - - var ( - obuElementLength, bytesRead uint - err error - ) - for i := 1; ; i++ { - if currentIndex == uint(len(payload)) { - break - } - - // If W bit is set the last OBU Element will have no length header - if byte(i) == p.W { - bytesRead = 0 - obuElementLength = uint(len(payload)) - currentIndex - } else { - obuElementLength, bytesRead, err = obu.ReadLeb128(payload[currentIndex:]) - if err != nil { - return nil, err - } - } - - currentIndex += bytesRead - if uint(len(payload)) < currentIndex+obuElementLength { - return nil, errShortPacket - } - p.OBUElements = append(p.OBUElements, payload[currentIndex:currentIndex+obuElementLength]) - currentIndex += obuElementLength - } - - return payload[1:], nil -} diff --git a/vendor/github.com/pion/rtp/codecs/error.go b/vendor/github.com/pion/rtp/codecs/error.go index 7f72e7b8e..38ee9076b 100644 --- a/vendor/github.com/pion/rtp/codecs/error.go +++ b/vendor/github.com/pion/rtp/codecs/error.go @@ -8,7 +8,4 @@ var ( errTooManyPDiff = errors.New("too many PDiff") errTooManySpatialLayers = errors.New("too many spatial layers") errUnhandledNALUType = errors.New("NALU Type is unhandled") - - // AV1 Errors - errIsKeyframeAndFragment = errors.New("bits Z and N are set. Not possible to have OBU be tail fragment and be keyframe") ) diff --git a/vendor/github.com/pion/rtp/codecs/g711_packet.go b/vendor/github.com/pion/rtp/codecs/g711_packet.go index 7ab68b2c3..2348a79f7 100644 --- a/vendor/github.com/pion/rtp/codecs/g711_packet.go +++ b/vendor/github.com/pion/rtp/codecs/g711_packet.go @@ -6,7 +6,7 @@ type G711Payloader struct{} // Payload fragments an G711 packet across one or more byte arrays func (p *G711Payloader) Payload(mtu uint16, payload []byte) [][]byte { var out [][]byte - if payload == nil || mtu == 0 { + if payload == nil || mtu <= 0 { return out } diff --git a/vendor/github.com/pion/rtp/codecs/h265_packet.go b/vendor/github.com/pion/rtp/codecs/h265_packet.go index 6f0490dc6..a4ae84334 100644 --- a/vendor/github.com/pion/rtp/codecs/h265_packet.go +++ b/vendor/github.com/pion/rtp/codecs/h265_packet.go @@ -1,7 +1,6 @@ package codecs import ( - "encoding/binary" "errors" "fmt" ) @@ -728,8 +727,6 @@ var ( type H265Packet struct { packet isH265Packet mightNeedDONL bool - - videoDepacketizer } // WithDONL can be called to specify whether or not DONL might be parsed. @@ -804,16 +801,3 @@ func (p *H265Packet) Unmarshal(payload []byte) ([]byte, error) { func (p *H265Packet) Packet() isH265Packet { return p.packet } - -// IsPartitionHead checks if this is the head of a packetized nalu stream. -func (*H265Packet) IsPartitionHead(payload []byte) bool { - if len(payload) < 3 { - return false - } - - if H265NALUHeader(binary.BigEndian.Uint16(payload[0:2])).Type() == h265NaluFragmentationUnitType { - return H265FragmentationUnitHeader(payload[2]).S() - } - - return true -} diff --git a/vendor/github.com/pion/rtp/header_extension.go b/vendor/github.com/pion/rtp/header_extension.go deleted file mode 100644 index c143ac119..000000000 --- a/vendor/github.com/pion/rtp/header_extension.go +++ /dev/null @@ -1,350 +0,0 @@ -package rtp - -import ( - "encoding/binary" - "fmt" - "io" -) - -const ( - headerExtensionProfileOneByte = 0xBEDE - headerExtensionProfileTwoByte = 0x1000 - headerExtensionIDReserved = 0xF -) - -// HeaderExtension represents an RTP extension header. -type HeaderExtension interface { - Set(id uint8, payload []byte) error - GetIDs() []uint8 - Get(id uint8) []byte - Del(id uint8) error - - Unmarshal(buf []byte) (int, error) - Marshal() ([]byte, error) - MarshalTo(buf []byte) (int, error) - MarshalSize() int -} - -// OneByteHeaderExtension is an RFC8285 one-byte header extension. -type OneByteHeaderExtension struct { - payload []byte -} - -// Set sets the extension payload for the specified ID. -func (e *OneByteHeaderExtension) Set(id uint8, buf []byte) error { - if id < 1 || id > 14 { - return fmt.Errorf("%w actual(%d)", errRFC8285OneByteHeaderIDRange, id) - } - if len(buf) > 16 { - return fmt.Errorf("%w actual(%d)", errRFC8285OneByteHeaderSize, len(buf)) - } - - for n := 4; n < len(e.payload); { - if e.payload[n] == 0x00 { // padding - n++ - continue - } - - extid := e.payload[n] >> 4 - len := int(e.payload[n]&^0xF0 + 1) - n++ - - if extid == id { - e.payload = append(e.payload[:n+1], append(buf, e.payload[n+1+len:]...)...) - return nil - } - n += len - } - e.payload = append(e.payload, (id<<4 | uint8(len(buf)-1))) - e.payload = append(e.payload, buf...) - binary.BigEndian.PutUint16(e.payload[2:4], binary.BigEndian.Uint16(e.payload[2:4])+1) - return nil -} - -// GetIDs returns the available IDs. -func (e *OneByteHeaderExtension) GetIDs() []uint8 { - ids := make([]uint8, 0, binary.BigEndian.Uint16(e.payload[2:4])) - for n := 4; n < len(e.payload); { - if e.payload[n] == 0x00 { // padding - n++ - continue - } - - extid := e.payload[n] >> 4 - len := int(e.payload[n]&^0xF0 + 1) - n++ - - if extid == headerExtensionIDReserved { - break - } - - ids = append(ids, extid) - n += len - } - return ids -} - -// Get returns the payload of the extension with the given ID. -func (e *OneByteHeaderExtension) Get(id uint8) []byte { - for n := 4; n < len(e.payload); { - if e.payload[n] == 0x00 { // padding - n++ - continue - } - - extid := e.payload[n] >> 4 - len := int(e.payload[n]&^0xF0 + 1) - n++ - - if extid == id { - return e.payload[n : n+len] - } - n += len - } - return nil -} - -// Del deletes the extension with the specified ID. -func (e *OneByteHeaderExtension) Del(id uint8) error { - for n := 4; n < len(e.payload); { - if e.payload[n] == 0x00 { // padding - n++ - continue - } - - extid := e.payload[n] >> 4 - len := int(e.payload[n]&^0xF0 + 1) - - if extid == id { - e.payload = append(e.payload[:n], e.payload[n+1+len:]...) - return nil - } - n += len + 1 - } - return errHeaderExtensionNotFound -} - -// Unmarshal parses the extension payload. -func (e *OneByteHeaderExtension) Unmarshal(buf []byte) (int, error) { - profile := binary.BigEndian.Uint16(buf[0:2]) - if profile != headerExtensionProfileOneByte { - return 0, fmt.Errorf("%w actual(%x)", errHeaderExtensionNotFound, buf[0:2]) - } - e.payload = buf - return len(buf), nil -} - -// Marshal returns the extension payload. -func (e OneByteHeaderExtension) Marshal() ([]byte, error) { - return e.payload, nil -} - -// MarshalTo writes the extension payload to the given buffer. -func (e OneByteHeaderExtension) MarshalTo(buf []byte) (int, error) { - size := e.MarshalSize() - if size > len(buf) { - return 0, io.ErrShortBuffer - } - return copy(buf, e.payload), nil -} - -// MarshalSize returns the size of the extension payload. -func (e OneByteHeaderExtension) MarshalSize() int { - return len(e.payload) -} - -// TwoByteHeaderExtension is an RFC8285 two-byte header extension. -type TwoByteHeaderExtension struct { - payload []byte -} - -// Set sets the extension payload for the specified ID. -func (e *TwoByteHeaderExtension) Set(id uint8, buf []byte) error { - if id < 1 || id > 255 { - return fmt.Errorf("%w actual(%d)", errRFC8285TwoByteHeaderIDRange, id) - } - if len(buf) > 255 { - return fmt.Errorf("%w actual(%d)", errRFC8285TwoByteHeaderSize, len(buf)) - } - - for n := 4; n < len(e.payload); { - if e.payload[n] == 0x00 { // padding - n++ - continue - } - - extid := e.payload[n] - n++ - - len := int(e.payload[n]) - n++ - - if extid == id { - e.payload = append(e.payload[:n+2], append(buf, e.payload[n+2+len:]...)...) - return nil - } - n += len - } - e.payload = append(e.payload, id, uint8(len(buf))) - e.payload = append(e.payload, buf...) - binary.BigEndian.PutUint16(e.payload[2:4], binary.BigEndian.Uint16(e.payload[2:4])+1) - return nil -} - -// GetIDs returns the available IDs. -func (e *TwoByteHeaderExtension) GetIDs() []uint8 { - ids := make([]uint8, 0, binary.BigEndian.Uint16(e.payload[2:4])) - for n := 4; n < len(e.payload); { - if e.payload[n] == 0x00 { // padding - n++ - continue - } - - extid := e.payload[n] - n++ - - len := int(e.payload[n]) - n++ - - ids = append(ids, extid) - n += len - } - return ids -} - -// Get returns the payload of the extension with the given ID. -func (e *TwoByteHeaderExtension) Get(id uint8) []byte { - for n := 4; n < len(e.payload); { - if e.payload[n] == 0x00 { // padding - n++ - continue - } - - extid := e.payload[n] - n++ - - len := int(e.payload[n]) - n++ - - if extid == id { - return e.payload[n : n+len] - } - n += len - } - return nil -} - -// Del deletes the extension with the specified ID. -func (e *TwoByteHeaderExtension) Del(id uint8) error { - for n := 4; n < len(e.payload); { - if e.payload[n] == 0x00 { // padding - n++ - continue - } - - extid := e.payload[n] - - len := int(e.payload[n+1]) - - if extid == id { - e.payload = append(e.payload[:n], e.payload[n+2+len:]...) - return nil - } - n += len + 2 - } - return errHeaderExtensionNotFound -} - -// Unmarshal parses the extension payload. -func (e *TwoByteHeaderExtension) Unmarshal(buf []byte) (int, error) { - profile := binary.BigEndian.Uint16(buf[0:2]) - if profile != headerExtensionProfileTwoByte { - return 0, fmt.Errorf("%w actual(%x)", errHeaderExtensionNotFound, buf[0:2]) - } - e.payload = buf - return len(buf), nil -} - -// Marshal returns the extension payload. -func (e TwoByteHeaderExtension) Marshal() ([]byte, error) { - return e.payload, nil -} - -// MarshalTo marshals the extension to the given buffer. -func (e TwoByteHeaderExtension) MarshalTo(buf []byte) (int, error) { - size := e.MarshalSize() - if size > len(buf) { - return 0, io.ErrShortBuffer - } - return copy(buf, e.payload), nil -} - -// MarshalSize returns the size of the extension payload. -func (e TwoByteHeaderExtension) MarshalSize() int { - return len(e.payload) -} - -// RawExtension represents an RFC3550 header extension. -type RawExtension struct { - payload []byte -} - -// Set sets the extension payload for the specified ID. -func (e *RawExtension) Set(id uint8, payload []byte) error { - if id != 0 { - return fmt.Errorf("%w actual(%d)", errRFC3550HeaderIDRange, id) - } - e.payload = payload - return nil -} - -// GetIDs returns the available IDs. -func (e *RawExtension) GetIDs() []uint8 { - return []uint8{0} -} - -// Get returns the payload of the extension with the given ID. -func (e *RawExtension) Get(id uint8) []byte { - if id == 0 { - return e.payload - } - return nil -} - -// Del deletes the extension with the specified ID. -func (e *RawExtension) Del(id uint8) error { - if id == 0 { - e.payload = nil - return nil - } - return fmt.Errorf("%w actual(%d)", errRFC3550HeaderIDRange, id) -} - -// Unmarshal parses the extension from the given buffer. -func (e *RawExtension) Unmarshal(buf []byte) (int, error) { - profile := binary.BigEndian.Uint16(buf[0:2]) - if profile == headerExtensionProfileOneByte || profile == headerExtensionProfileTwoByte { - return 0, fmt.Errorf("%w actual(%x)", errHeaderExtensionNotFound, buf[0:2]) - } - e.payload = buf - return len(buf), nil -} - -// Marshal returns the raw extension payload. -func (e RawExtension) Marshal() ([]byte, error) { - return e.payload, nil -} - -// MarshalTo marshals the extension to the given buffer. -func (e RawExtension) MarshalTo(buf []byte) (int, error) { - size := e.MarshalSize() - if size > len(buf) { - return 0, io.ErrShortBuffer - } - return copy(buf, e.payload), nil -} - -// MarshalSize returns the size of the extension when marshaled. -func (e RawExtension) MarshalSize() int { - return len(e.payload) -} diff --git a/vendor/github.com/pion/rtp/packet.go b/vendor/github.com/pion/rtp/packet.go index b3ae12400..c1d20f387 100644 --- a/vendor/github.com/pion/rtp/packet.go +++ b/vendor/github.com/pion/rtp/packet.go @@ -30,8 +30,7 @@ type Header struct { // Packet represents an RTP Packet type Packet struct { Header - Payload []byte - PaddingSize byte + Payload []byte } const ( @@ -213,8 +212,7 @@ func (p *Packet) Unmarshal(buf []byte) error { } end := len(buf) if p.Header.Padding { - p.PaddingSize = buf[end-1] - end -= int(p.PaddingSize) + end -= int(buf[end-1]) } if end < n { return errTooSmall @@ -224,7 +222,7 @@ func (p *Packet) Unmarshal(buf []byte) error { } // Marshal serializes the header into bytes. -func (h Header) Marshal() (buf []byte, err error) { +func (h *Header) Marshal() (buf []byte, err error) { buf = make([]byte, h.MarshalSize()) n, err := h.MarshalTo(buf) @@ -235,7 +233,7 @@ func (h Header) Marshal() (buf []byte, err error) { } // MarshalTo serializes the header and writes to the buffer. -func (h Header) MarshalTo(buf []byte) (n int, err error) { +func (h *Header) MarshalTo(buf []byte) (n int, err error) { /* * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 @@ -332,7 +330,7 @@ func (h Header) MarshalTo(buf []byte) (n int, err error) { } // MarshalSize returns the size of the header once marshaled. -func (h Header) MarshalSize() int { +func (h *Header) MarshalSize() int { // NOTE: Be careful to match the MarshalTo() method. size := 12 + (len(h.CSRC) * csrcLength) @@ -457,7 +455,7 @@ func (h *Header) DelExtension(id uint8) error { } // Marshal serializes the packet into bytes. -func (p Packet) Marshal() (buf []byte, err error) { +func (p *Packet) Marshal() (buf []byte, err error) { buf = make([]byte, p.MarshalSize()) n, err := p.MarshalTo(buf) @@ -469,40 +467,35 @@ func (p Packet) Marshal() (buf []byte, err error) { } // MarshalTo serializes the packet and writes to the buffer. -func (p Packet) MarshalTo(buf []byte) (n int, err error) { - p.Header.Padding = p.PaddingSize != 0 +func (p *Packet) MarshalTo(buf []byte) (n int, err error) { n, err = p.Header.MarshalTo(buf) if err != nil { return 0, err } // Make sure the buffer is large enough to hold the packet. - if n+len(p.Payload)+int(p.PaddingSize) > len(buf) { + if n+len(p.Payload) > len(buf) { return 0, io.ErrShortBuffer } m := copy(buf[n:], p.Payload) - if p.Header.Padding { - buf[n+m+int(p.PaddingSize-1)] = p.PaddingSize - } - return n + m + int(p.PaddingSize), nil + return n + m, nil } // MarshalSize returns the size of the packet once marshaled. -func (p Packet) MarshalSize() int { - return p.Header.MarshalSize() + len(p.Payload) + int(p.PaddingSize) +func (p *Packet) MarshalSize() int { + return p.Header.MarshalSize() + len(p.Payload) } // Clone returns a deep copy of p. -func (p Packet) Clone() *Packet { +func (p *Packet) Clone() *Packet { clone := &Packet{} clone.Header = p.Header.Clone() if p.Payload != nil { clone.Payload = make([]byte, len(p.Payload)) copy(clone.Payload, p.Payload) } - clone.PaddingSize = p.PaddingSize return clone } diff --git a/vendor/github.com/pion/rtp/pkg/obu/leb128.go b/vendor/github.com/pion/rtp/pkg/obu/leb128.go deleted file mode 100644 index 988a8f442..000000000 --- a/vendor/github.com/pion/rtp/pkg/obu/leb128.go +++ /dev/null @@ -1,66 +0,0 @@ -// Package obu implements tools for working with the "Open Bitstream Unit" -package obu - -import "errors" - -const ( - sevenLsbBitmask = uint(0b01111111) - msbBitmask = uint(0b10000000) -) - -// ErrFailedToReadLEB128 indicates that a buffer ended before a LEB128 value could be successfully read -var ErrFailedToReadLEB128 = errors.New("payload ended before LEB128 was finished") - -// EncodeLEB128 encodes a uint as LEB128 -func EncodeLEB128(in uint) (out uint) { - for { - // Copy seven bits from in and discard - // what we have copied from in - out |= (in & sevenLsbBitmask) - in >>= 7 - - // If we have more bits to encode set MSB - // otherwise we are done - if in != 0 { - out |= msbBitmask - out <<= 8 - } else { - return out - } - } -} - -func decodeLEB128(in uint) (out uint) { - for { - // Take 7 LSB from in - out |= (in & sevenLsbBitmask) - - // Discard the MSB - in >>= 8 - if in == 0 { - return out - } - - out <<= 7 - } -} - -// ReadLeb128 scans an buffer and decodes a Leb128 value. -// If the end of the buffer is reached and all MSB are set -// an error is returned -func ReadLeb128(in []byte) (uint, uint, error) { - var encodedLength uint - - for i := range in { - encodedLength |= uint(in[i]) - - if in[i]&byte(msbBitmask) == 0 { - return decodeLEB128(encodedLength), uint(i + 1), nil - } - - // Make more room for next read - encodedLength <<= 8 - } - - return 0, 0, ErrFailedToReadLEB128 -} diff --git a/vendor/github.com/pion/rtp/renovate.json b/vendor/github.com/pion/rtp/renovate.json index f1614058a..08c1e39d6 100644 --- a/vendor/github.com/pion/rtp/renovate.json +++ b/vendor/github.com/pion/rtp/renovate.json @@ -1,7 +1,6 @@ { "extends": [ - "config:base", - ":disableDependencyDashboard" + "config:base" ], "postUpdateOptions": [ "gomodTidy" diff --git a/vendor/github.com/pion/rtp/transportccextension.go b/vendor/github.com/pion/rtp/transportccextension.go index 236af056a..f9ffe4eb1 100644 --- a/vendor/github.com/pion/rtp/transportccextension.go +++ b/vendor/github.com/pion/rtp/transportccextension.go @@ -23,7 +23,7 @@ type TransportCCExtension struct { } // Marshal serializes the members to buffer -func (t TransportCCExtension) Marshal() ([]byte, error) { +func (t *TransportCCExtension) Marshal() ([]byte, error) { buf := make([]byte, transportCCExtensionSize) binary.BigEndian.PutUint16(buf[0:2], t.TransportSequence) return buf, nil diff --git a/vendor/github.com/pion/sctp/.gitignore b/vendor/github.com/pion/sctp/.gitignore index f977e7485..83db74ba5 100644 --- a/vendor/github.com/pion/sctp/.gitignore +++ b/vendor/github.com/pion/sctp/.gitignore @@ -22,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/sctp/.golangci.yml b/vendor/github.com/pion/sctp/.golangci.yml index 48696f16b..d6162c970 100644 --- a/vendor/github.com/pion/sctp/.golangci.yml +++ b/vendor/github.com/pion/sctp/.golangci.yml @@ -15,21 +15,14 @@ linters-settings: linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - - decorder # check declaration order and count of types, constants, variables and functions + - deadcode # Finds unused code - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -42,60 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks + - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - - wastedassign # wastedassign finds wasted assignment statements + - varcheck # Finds unused global variables and constants - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - - forbidigo # Forbids identifiers - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: diff --git a/vendor/github.com/pion/sctp/.goreleaser.yml b/vendor/github.com/pion/sctp/.goreleaser.yml deleted file mode 100644 index 2caa5fbd3..000000000 --- a/vendor/github.com/pion/sctp/.goreleaser.yml +++ /dev/null @@ -1,2 +0,0 @@ -builds: -- skip: true diff --git a/vendor/github.com/pion/sctp/AUTHORS.txt b/vendor/github.com/pion/sctp/AUTHORS.txt index ed95135c8..91314c3f8 100644 --- a/vendor/github.com/pion/sctp/AUTHORS.txt +++ b/vendor/github.com/pion/sctp/AUTHORS.txt @@ -2,32 +2,23 @@ # we would love to have you https://github.com/pion/webrtc/wiki/Contributing # # This file is auto generated, using git to list all individuals contributors. -# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting +# see `.github/generate-authors.sh` for the scripting Aaron France -Adrian Cable Atsushi Watanabe backkem Cecylia Bocovich chenkaiC4 -Eric Daniels Hugo Arregui Hugo Arregui Jerko Steiner -Jerry Tao John Bradley Konstantin Itskov Lukas Herman Luke Curley Michael MacDonald ronan -Sam Lancia Sean DuBois Sean DuBois -Steffen Vogel Teddy -Will Forcey Yutaka Takeda ZHENK - -# List of contributors not appearing in Git history - diff --git a/vendor/github.com/pion/sctp/DESIGN.md b/vendor/github.com/pion/sctp/DESIGN.md new file mode 100644 index 000000000..02ac16113 --- /dev/null +++ b/vendor/github.com/pion/sctp/DESIGN.md @@ -0,0 +1,20 @@ +

+ Design +

+ +### Portable +Pion SCTP is written in Go and extremely portable. Anywhere Golang runs, Pion SCTP should work as well! Instead of dealing with complicated +cross-compiling of multiple libraries, you now can run anywhere with one `go build` + +### Simple API +The API is based on an io.ReadWriteCloser. + +### Readable +If code comes from an RFC we try to make sure everything is commented with a link to the spec. +This makes learning and debugging easier, this library was written to also serve as a guide for others. + +### Tested +Every commit is tested via travis-ci Go provides fantastic facilities for testing, and more will be added as time goes on. + +### Shared libraries +Every pion product is built using shared libraries, allowing others to review and reuse our libraries. diff --git a/vendor/github.com/pion/sctp/README.md b/vendor/github.com/pion/sctp/README.md index 3ca234452..f1815cdd7 100644 --- a/vendor/github.com/pion/sctp/README.md +++ b/vendor/github.com/pion/sctp/README.md @@ -6,29 +6,32 @@

A Go implementation of SCTP

Pion SCTP + Slack Widget
- GitHub Workflow Status - Go Reference + Build Status + GoDoc Coverage Status Go Report Card + License: MIT


+See [DESIGN.md](DESIGN.md) for an overview of features and future goals. + ### Roadmap The library is used as a part of our WebRTC implementation. Please refer to that [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones. ### Community -Pion has an active community on the [Slack](https://pion.ly/slack). - -Follow the [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news. +Pion has an active community on the [Golang Slack](https://invite.slack.golangbridge.org/). Sign up and join the **#pion** channel for discussions and support. You can also use [Pion mailing list](https://groups.google.com/forum/#!forum/pion). We are always looking to support **your projects**. Please reach out if you have something to build! + If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly) ### Contributing -Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible: [AUTHORS.txt](./AUTHORS.txt) +Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible: ### License MIT License - see [LICENSE](LICENSE) for full text diff --git a/vendor/github.com/pion/sctp/association.go b/vendor/github.com/pion/sctp/association.go index fb7fd38db..caf6d4eb1 100644 --- a/vendor/github.com/pion/sctp/association.go +++ b/vendor/github.com/pion/sctp/association.go @@ -17,30 +17,28 @@ import ( ) // Use global random generator to properly seed by crypto grade random. -var globalMathRandomGenerator = randutil.NewMathRandomGenerator() // nolint:gochecknoglobals - -// Association errors var ( - ErrChunk = errors.New("abort chunk, with following errors") - ErrShutdownNonEstablished = errors.New("shutdown called in non-established state") - ErrAssociationClosedBeforeConn = errors.New("association closed before connecting") - ErrSilentlyDiscard = errors.New("silently discard") - ErrInitNotStoredToSend = errors.New("the init not stored to send") - ErrCookieEchoNotStoredToSend = errors.New("cookieEcho not stored to send") - ErrSCTPPacketSourcePortZero = errors.New("sctp packet must not have a source port of 0") - ErrSCTPPacketDestinationPortZero = errors.New("sctp packet must not have a destination port of 0") - ErrInitChunkBundled = errors.New("init chunk must not be bundled with any other chunk") - ErrInitChunkVerifyTagNotZero = errors.New("init chunk expects a verification tag of 0 on the packet when out-of-the-blue") - ErrHandleInitState = errors.New("todo: handle Init when in state") - ErrInitAckNoCookie = errors.New("no cookie in InitAck") - ErrInflightQueueTSNPop = errors.New("unable to be popped from inflight queue TSN") - ErrTSNRequestNotExist = errors.New("requested non-existent TSN") - ErrResetPacketInStateNotExist = errors.New("sending reset packet in non-established state") - ErrParamterType = errors.New("unexpected parameter type") - ErrPayloadDataStateNotExist = errors.New("sending payload data in non-established state") - ErrChunkTypeUnhandled = errors.New("unhandled chunk type") - ErrHandshakeInitAck = errors.New("handshake failed (INIT ACK)") - ErrHandshakeCookieEcho = errors.New("handshake failed (COOKIE ECHO)") + globalMathRandomGenerator = randutil.NewMathRandomGenerator() // nolint:gochecknoglobals + errChunk = errors.New("abort chunk, with following errors") + errShutdownNonEstablished = errors.New("shutdown called in non-established state") + errAssociationClosedBeforeConn = errors.New("association closed before connecting") + errSilentlyDiscard = errors.New("silently discard") + errInitNotStoredToSend = errors.New("the init not stored to send") + errCookieEchoNotStoredToSend = errors.New("cookieEcho not stored to send") + errSCTPPacketSourcePortZero = errors.New("sctp packet must not have a source port of 0") + errSCTPPacketDestinationPortZero = errors.New("sctp packet must not have a destination port of 0") + errInitChunkBundled = errors.New("init chunk must not be bundled with any other chunk") + errInitChunkVerifyTagNotZero = errors.New("init chunk expects a verification tag of 0 on the packet when out-of-the-blue") + errHandleInitState = errors.New("todo: handle Init when in state") + errInitAckNoCookie = errors.New("no cookie in InitAck") + errInflightQueueTSNPop = errors.New("unable to be popped from inflight queue TSN") + errTSNRequestNotExist = errors.New("requested non-existent TSN") + errResetPacketInStateNotExist = errors.New("sending reset packet in non-established state") + errParamterType = errors.New("unexpected parameter type") + errPayloadDataStateNotExist = errors.New("sending payload data in non-established state") + errChunkTypeUnhandled = errors.New("unhandled chunk type") + errHandshakeInitAck = errors.New("handshake failed (INIT ACK)") + errHandshakeCookieEcho = errors.New("handshake failed (COOKIE ECHO)") ) const ( @@ -117,17 +115,21 @@ func getAssociationStateString(a uint32) string { // Association represents an SCTP association // 13.2. Parameters Necessary per Association (i.e., the TCB) +// Peer : Tag value to be sent in every packet and is received +// Verification: in the INIT or INIT ACK chunk. +// Tag : // -// Peer : Tag value to be sent in every packet and is received -// Verification: in the INIT or INIT ACK chunk. -// Tag : -// State : A state variable indicating what state the association -// : is in, i.e., COOKIE-WAIT, COOKIE-ECHOED, ESTABLISHED, -// : SHUTDOWN-PENDING, SHUTDOWN-SENT, SHUTDOWN-RECEIVED, -// : SHUTDOWN-ACK-SENT. +// My : Tag expected in every inbound packet and sent in the +// Verification: INIT or INIT ACK chunk. // -// Note: No "CLOSED" state is illustrated since if a -// association is "CLOSED" its TCB SHOULD be removed. +// Tag : +// State : A state variable indicating what state the association +// : is in, i.e., COOKIE-WAIT, COOKIE-ECHOED, ESTABLISHED, +// : SHUTDOWN-PENDING, SHUTDOWN-SENT, SHUTDOWN-RECEIVED, +// : SHUTDOWN-ACK-SENT. +// +// Note: No "CLOSED" state is illustrated since if a +// association is "CLOSED" its TCB SHOULD be removed. type Association struct { bytesReceived uint64 bytesSent uint64 @@ -150,9 +152,6 @@ type Association struct { willSendShutdownAck bool willSendShutdownComplete bool - willSendAbort bool - willSendAbortCause errorCause - // Reconfig myNextRSN uint32 reconfigs map[uint32]*chunkReconfig @@ -169,8 +168,7 @@ type Association struct { pendingQueue *pendingQueue controlQueue *controlQueue mtu uint32 - maxPayloadSize uint32 // max DATA chunk payload size - srtt atomic.Value // type float64 + maxPayloadSize uint32 // max DATA chunk payload size cumulativeTSNAckPoint uint32 advancedPeerTSNAckPoint uint32 useForwardTSN bool @@ -245,7 +243,7 @@ func Server(config Config) (*Association, error) { } return a, nil case <-a.readLoopCloseCh: - return nil, ErrAssociationClosedBeforeConn + return nil, errAssociationClosedBeforeConn } } @@ -261,7 +259,7 @@ func Client(config Config) (*Association, error) { } return a, nil case <-a.readLoopCloseCh: - return nil, ErrAssociationClosedBeforeConn + return nil, errAssociationClosedBeforeConn } } @@ -309,7 +307,7 @@ func createAssociation(config Config) *Association { handshakeCompletedCh: make(chan error), cumulativeTSNAckPoint: tsn - 1, advancedPeerTSNAckPoint: tsn - 1, - silentError: ErrSilentlyDiscard, + silentError: errSilentlyDiscard, stats: &associationStats{}, log: config.LoggerFactory.NewLogger("sctp"), } @@ -324,7 +322,6 @@ func createAssociation(config Config) *Association { a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (INI)", a.name, a.cwnd, a.ssthresh, a.inflightQueue.getNumBytes()) - a.srtt.Store(float64(0)) a.t1Init = newRTXTimer(timerT1Init, a, maxInitRetrans) a.t1Cookie = newRTXTimer(timerT1Cookie, a, maxInitRetrans) a.t2Shutdown = newRTXTimer(timerT2Shutdown, a, noMaxRetrans) // retransmit forever @@ -366,7 +363,7 @@ func (a *Association) init(isClient bool) { func (a *Association) sendInit() error { a.log.Debugf("[%s] sending INIT", a.name) if a.storedInit == nil { - return ErrInitNotStoredToSend + return errInitNotStoredToSend } outbound := &packet{} @@ -387,7 +384,7 @@ func (a *Association) sendInit() error { // caller must hold a.lock func (a *Association) sendCookieEcho() error { if a.storedCookieEcho == nil { - return ErrCookieEchoNotStoredToSend + return errCookieEchoNotStoredToSend } a.log.Debugf("[%s] sending COOKIE-ECHO", a.name) @@ -413,7 +410,7 @@ func (a *Association) Shutdown(ctx context.Context) error { state := a.getState() if state != established { - return fmt.Errorf("%w: shutdown %s", ErrShutdownNonEstablished, a.name) + return fmt.Errorf("%w: shutdown %s", errShutdownNonEstablished, a.name) } // Attempt a graceful shutdown. @@ -472,26 +469,6 @@ func (a *Association) close() error { return err } -// Abort sends the abort packet with user initiated abort and immediately -// closes the connection. -func (a *Association) Abort(reason string) { - a.log.Debugf("[%s] aborting association: %s", a.name, reason) - - a.lock.Lock() - - a.willSendAbort = true - a.willSendAbortCause = &errorCauseUserInitiatedAbort{ - upperLayerAbortReason: []byte(reason), - } - - a.lock.Unlock() - - a.awakeWriteLoop() - - // Wait for readLoop to end - <-a.readLoopCloseCh -} - func (a *Association) closeAllTimers() { // Close all retransmission & ack timers a.t1Init.close() @@ -561,7 +538,7 @@ loop: for _, raw := range rawPackets { _, err := a.netConn.Write(raw) if err != nil { - if !errors.Is(err, io.EOF) { + if err != io.EOF { a.log.Warnf("[%s] failed to write packets on netConn: %v", a.name, err) } a.log.Debugf("[%s] writeLoop ended", a.name) @@ -775,7 +752,7 @@ func (a *Association) gatherOutboundSackPackets(rawPackets [][]byte) [][]byte { if a.ackState == ackStateImmediate { a.ackState = ackStateIdle sack := a.createSelectiveAckChunk() - a.log.Debugf("[%s] sending SACK: %s", a.name, sack) + a.log.Debugf("[%s] sending SACK: %s", a.name, sack.String()) raw, err := a.createPacket([]chunk{sack}).marshal() if err != nil { a.log.Warnf("[%s] failed to serialize a SACK packet", a.name) @@ -852,39 +829,12 @@ func (a *Association) gatherOutboundShutdownPackets(rawPackets [][]byte) ([][]by return rawPackets, ok } -func (a *Association) gatherAbortPacket() ([]byte, error) { - cause := a.willSendAbortCause - - a.willSendAbort = false - a.willSendAbortCause = nil - - abort := &chunkAbort{} - - if cause != nil { - abort.errorCauses = []errorCause{cause} - } - - raw, err := a.createPacket([]chunk{abort}).marshal() - - return raw, err -} - // gatherOutbound gathers outgoing packets. The returned bool value set to // false means the association should be closed down after the final send. func (a *Association) gatherOutbound() ([][]byte, bool) { a.lock.Lock() defer a.lock.Unlock() - if a.willSendAbort { - pkt, err := a.gatherAbortPacket() - if err != nil { - a.log.Warnf("[%s] failed to serialize an abort packet", a.name) - return nil, false - } - - return [][]byte{pkt}, false - } - rawPackets := [][]byte{} if a.controlQueue.size() > 0 { @@ -930,7 +880,7 @@ func checkPacket(p *packet) error { // identify the association to which this packet belongs. The port // number 0 MUST NOT be used. if p.sourcePort == 0 { - return ErrSCTPPacketSourcePortZero + return errSCTPPacketSourcePortZero } // This is the SCTP port number to which this packet is destined. @@ -938,7 +888,7 @@ func checkPacket(p *packet) error { // SCTP packet to the correct receiving endpoint/application. The // port number 0 MUST NOT be used. if p.destinationPort == 0 { - return ErrSCTPPacketDestinationPortZero + return errSCTPPacketDestinationPortZero } // Check values on the packet that are specific to a particular chunk type @@ -949,13 +899,13 @@ func checkPacket(p *packet) error { // They MUST be the only chunks present in the SCTP packets that carry // them. if len(p.chunks) != 1 { - return ErrInitChunkBundled + return errInitChunkBundled } // A packet containing an INIT chunk MUST have a zero Verification // Tag. if p.verificationTag != 0 { - return ErrInitChunkVerifyTagNotZero + return errInitChunkVerifyTagNotZero } } } @@ -1011,26 +961,6 @@ func (a *Association) BytesReceived() uint64 { return atomic.LoadUint64(&a.bytesReceived) } -// MTU returns the association's current MTU -func (a *Association) MTU() uint32 { - return atomic.LoadUint32(&a.mtu) -} - -// CWND returns the association's current congestion window (cwnd) -func (a *Association) CWND() uint32 { - return atomic.LoadUint32(&a.cwnd) -} - -// RWND returns the association's current receiver window (rwnd) -func (a *Association) RWND() uint32 { - return atomic.LoadUint32(&a.rwnd) -} - -// SRTT returns the latest smoothed round-trip time (srrt) -func (a *Association) SRTT() float64 { - return a.srtt.Load().(float64) //nolint:forcetypeassert -} - func setSupportedExtensions(init *chunkInitCommon) { // nolint:godox // TODO RFC5061 https://tools.ietf.org/html/rfc6525#section-5.2 @@ -1057,7 +987,7 @@ func (a *Association) handleInit(p *packet, i *chunkInit) ([]*packet, error) { if state != closed && state != cookieWait && state != cookieEchoed { // 5.2.2. Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED, // COOKIE-WAIT, and SHUTDOWN-ACK-SENT - return nil, fmt.Errorf("%w: %s", ErrHandleInitState, getAssociationStateString(state)) + return nil, fmt.Errorf("%w: %s", errHandleInitState, getAssociationStateString(state)) } // Should we be setting any of these permanently until we've ACKed further? @@ -1078,14 +1008,14 @@ func (a *Association) handleInit(p *packet, i *chunkInit) ([]*packet, error) { case *paramSupportedExtensions: for _, t := range v.ChunkTypes { if t == ctForwardTSN { - a.log.Debugf("[%s] use ForwardTSN (on init)", a.name) + a.log.Debugf("[%s] use ForwardTSN (on init)\n", a.name) a.useForwardTSN = true } } } } if !a.useForwardTSN { - a.log.Warnf("[%s] not using ForwardTSN (on init)", a.name) + a.log.Warnf("[%s] not using ForwardTSN (on init)\n", a.name) } outbound := &packet{} @@ -1163,17 +1093,17 @@ func (a *Association) handleInitAck(p *packet, i *chunkInitAck) error { case *paramSupportedExtensions: for _, t := range v.ChunkTypes { if t == ctForwardTSN { - a.log.Debugf("[%s] use ForwardTSN (on initAck)", a.name) + a.log.Debugf("[%s] use ForwardTSN (on initAck)\n", a.name) a.useForwardTSN = true } } } } if !a.useForwardTSN { - a.log.Warnf("[%s] not using ForwardTSN (on initAck)", a.name) + a.log.Warnf("[%s] not using ForwardTSN (on initAck)\n", a.name) } if cookieParam == nil { - return ErrInitAckNoCookie + return errInitAckNoCookie } a.storedCookieEcho = &chunkCookieEcho{} @@ -1435,7 +1365,7 @@ func (a *Association) processSelectiveAck(d *chunkSelectiveAck) (map[uint16]int, for i := a.cumulativeTSNAckPoint + 1; sna32LTE(i, d.cumulativeTSNAck); i++ { c, ok := a.inflightQueue.pop(i) if !ok { - return nil, 0, fmt.Errorf("%w: %v", ErrInflightQueueTSNPop, i) + return nil, 0, fmt.Errorf("%w: %v", errInflightQueueTSNPop, i) } if !c.acked { @@ -1471,7 +1401,6 @@ func (a *Association) processSelectiveAck(d *chunkSelectiveAck) (map[uint16]int, a.minTSN2MeasureRTT = a.myNextTSN rtt := time.Since(c.since).Seconds() * 1000.0 srtt := a.rtoMgr.setNewRTT(rtt) - a.srtt.Store(srtt) a.log.Tracef("[%s] SACK: measured-rtt=%f srtt=%f new-rto=%f", a.name, rtt, srtt, a.rtoMgr.getRTO()) } @@ -1491,7 +1420,7 @@ func (a *Association) processSelectiveAck(d *chunkSelectiveAck) (map[uint16]int, tsn := d.cumulativeTSNAck + uint32(i) c, ok := a.inflightQueue.get(tsn) if !ok { - return nil, 0, fmt.Errorf("%w: %v", ErrTSNRequestNotExist, tsn) + return nil, 0, fmt.Errorf("%w: %v", errTSNRequestNotExist, tsn) } if !c.acked { @@ -1510,7 +1439,6 @@ func (a *Association) processSelectiveAck(d *chunkSelectiveAck) (map[uint16]int, a.minTSN2MeasureRTT = a.myNextTSN rtt := time.Since(c.since).Seconds() * 1000.0 srtt := a.rtoMgr.setNewRTT(rtt) - a.srtt.Store(srtt) a.log.Tracef("[%s] SACK: measured-rtt=%f srtt=%f new-rto=%f", a.name, rtt, srtt, a.rtoMgr.getRTO()) } @@ -1608,7 +1536,7 @@ func (a *Association) processFastRetransmission(cumTSNAckPoint, htna uint32, cum for tsn := cumTSNAckPoint + 1; sna32LT(tsn, maxTSN); tsn++ { c, ok := a.inflightQueue.get(tsn) if !ok { - return fmt.Errorf("%w: %v", ErrTSNRequestNotExist, tsn) + return fmt.Errorf("%w: %v", errTSNRequestNotExist, tsn) } if !c.acked && !c.abandoned() && c.missIndicator < 3 { c.missIndicator++ @@ -1819,17 +1747,6 @@ func (a *Association) handleShutdownComplete(_ *chunkShutdownComplete) error { return nil } -func (a *Association) handleAbort(c *chunkAbort) error { - var errStr string - for _, e := range c.errorCauses { - errStr += fmt.Sprintf("(%s)", e) - } - - _ = a.close() - - return fmt.Errorf("[%s] %w: %s", a.name, ErrChunk, errStr) -} - // createForwardTSN generates ForwardTSN chunk. // This method will be be called if useForwardTSN is set to false. // The caller should hold the lock. @@ -1932,7 +1849,7 @@ func (a *Association) handleForwardTSN(c *chunkForwardTSN) []*packet { // send a SACK to its peer (the sender of the FORWARD TSN) since such a // duplicate may indicate the previous SACK was lost in the network. - a.log.Tracef("[%s] should send ack? newCumTSN=%d peerLastTSN=%d", + a.log.Tracef("[%s] should send ack? newCumTSN=%d peerLastTSN=%d\n", a.name, c.newCumulativeTSN, a.peerLastTSN) if sna32LTE(c.newCumulativeTSN, a.peerLastTSN) { a.log.Tracef("[%s] sending ack on Forward TSN", a.name) @@ -1985,7 +1902,7 @@ func (a *Association) sendResetRequest(streamIdentifier uint16) error { state := a.getState() if state != established { - return fmt.Errorf("%w: state=%s", ErrResetPacketInStateNotExist, + return fmt.Errorf("%w: state=%s", errResetPacketInStateNotExist, getAssociationStateString(state)) } @@ -2007,23 +1924,21 @@ func (a *Association) sendResetRequest(streamIdentifier uint16) error { func (a *Association) handleReconfigParam(raw param) (*packet, error) { switch p := raw.(type) { case *paramOutgoingResetRequest: - a.log.Tracef("[%s] handleReconfigParam (OutgoingResetRequest)", a.name) a.reconfigRequests[p.reconfigRequestSequenceNumber] = p resp := a.resetStreamsIfAny(p) if resp != nil { return resp, nil } - return nil, nil //nolint:nilnil + return nil, nil case *paramReconfigResponse: - a.log.Tracef("[%s] handleReconfigParam (ReconfigResponse)", a.name) delete(a.reconfigs, p.reconfigResponseSequenceNumber) if len(a.reconfigs) == 0 { a.tReconfig.stop() } - return nil, nil //nolint:nilnil + return nil, nil default: - return nil, fmt.Errorf("%w: %t", ErrParamterType, p) + return nil, fmt.Errorf("%w: %t", errParamterType, p) } } @@ -2038,11 +1953,7 @@ func (a *Association) resetStreamsIfAny(p *paramOutgoingResetRequest) *packet { if !ok { continue } - a.lock.Unlock() - s.onInboundStreamReset() - a.lock.Lock() - a.log.Debugf("[%s] deleting stream %d", a.name, id) - delete(a.streams, s.streamIdentifier) + a.unregisterStream(s, io.EOF) } delete(a.reconfigRequests, p.reconfigRequestSequenceNumber) } else { @@ -2184,7 +2095,7 @@ func (a *Association) sendPayloadData(chunks []*chunkPayloadData) error { state := a.getState() if state != established { - return fmt.Errorf("%w: state=%s", ErrPayloadDataStateNotExist, + return fmt.Errorf("%w: state=%s", errPayloadDataStateNotExist, getAssociationStateString(state)) } @@ -2340,8 +2251,6 @@ func (a *Association) handleChunk(p *packet, c chunk) error { return nil } - isAbort := false - switch c := c.(type) { case *chunkInit: packets, err = a.handleInit(p, c) @@ -2350,8 +2259,11 @@ func (a *Association) handleChunk(p *packet, c chunk) error { err = a.handleInitAck(p, c) case *chunkAbort: - isAbort = true - err = a.handleAbort(c) + var errStr string + for _, e := range c.errorCauses { + errStr += fmt.Sprintf("(%s)", e) + } + return fmt.Errorf("[%s] %w: %s", a.name, errChunk, errStr) case *chunkError: var errStr string @@ -2389,15 +2301,11 @@ func (a *Association) handleChunk(p *packet, c chunk) error { err = a.handleShutdownComplete(c) default: - err = ErrChunkTypeUnhandled + err = errChunkTypeUnhandled } // Log and return, the only condition that is fatal is a ABORT chunk if err != nil { - if isAbort { - return err - } - a.log.Errorf("Failed to handle chunk: %v", err) return nil } @@ -2517,13 +2425,13 @@ func (a *Association) onRetransmissionFailure(id int) { if id == timerT1Init { a.log.Errorf("[%s] retransmission failure: T1-init", a.name) - a.handshakeCompletedCh <- ErrHandshakeInitAck + a.handshakeCompletedCh <- errHandshakeInitAck return } if id == timerT1Cookie { a.log.Errorf("[%s] retransmission failure: T1-cookie", a.name) - a.handshakeCompletedCh <- ErrHandshakeCookieEcho + a.handshakeCompletedCh <- errHandshakeCookieEcho return } diff --git a/vendor/github.com/pion/sctp/chunk_abort.go b/vendor/github.com/pion/sctp/chunk_abort.go index eab64a4f4..9288412ef 100644 --- a/vendor/github.com/pion/sctp/chunk_abort.go +++ b/vendor/github.com/pion/sctp/chunk_abort.go @@ -16,25 +16,24 @@ SHUTDOWN COMPLETE) MAY be bundled with an ABORT, but they MUST be placed before the ABORT in the SCTP packet or they will be ignored by the receiver. - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Type = 6 |Reserved |T| Length | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | | - | zero or more Error Causes | - | | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Type = 6 |Reserved |T| Length | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| | +| zero or more Error Causes | +| | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ type chunkAbort struct { chunkHeader errorCauses []errorCause } -// Abort chunk errors var ( - ErrChunkTypeNotAbort = errors.New("ChunkType is not of type ABORT") - ErrBuildAbortChunkFailed = errors.New("failed build Abort Chunk") + errChunkTypeNotAbort = errors.New("ChunkType is not of type ABORT") + errBuildAbortChunkFailed = errors.New("failed build Abort Chunk") ) func (a *chunkAbort) unmarshal(raw []byte) error { @@ -43,7 +42,7 @@ func (a *chunkAbort) unmarshal(raw []byte) error { } if a.typ != ctAbort { - return fmt.Errorf("%w: actually is %s", ErrChunkTypeNotAbort, a.typ.String()) + return fmt.Errorf("%w: actually is %s", errChunkTypeNotAbort, a.typ.String()) } offset := chunkHeaderSize @@ -54,7 +53,7 @@ func (a *chunkAbort) unmarshal(raw []byte) error { e, err := buildErrorCause(raw[offset:]) if err != nil { - return fmt.Errorf("%w: %v", ErrBuildAbortChunkFailed, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errBuildAbortChunkFailed, err) } offset += int(e.length()) diff --git a/vendor/github.com/pion/sctp/chunk_cookie_ack.go b/vendor/github.com/pion/sctp/chunk_cookie_ack.go index 5d63b1c48..742529cbd 100644 --- a/vendor/github.com/pion/sctp/chunk_cookie_ack.go +++ b/vendor/github.com/pion/sctp/chunk_cookie_ack.go @@ -8,20 +8,17 @@ import ( /* chunkCookieAck represents an SCTP Chunk of type chunkCookieAck - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Type = 11 |Chunk Flags | Length = 4 | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Type = 11 |Chunk Flags | Length = 4 | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ type chunkCookieAck struct { chunkHeader } -// Cookie ack chunk errors -var ( - ErrChunkTypeNotCookieAck = errors.New("ChunkType is not of type COOKIEACK") -) +var errChunkTypeNotCookieAck = errors.New("ChunkType is not of type COOKIEACK") func (c *chunkCookieAck) unmarshal(raw []byte) error { if err := c.chunkHeader.unmarshal(raw); err != nil { @@ -29,7 +26,7 @@ func (c *chunkCookieAck) unmarshal(raw []byte) error { } if c.typ != ctCookieAck { - return fmt.Errorf("%w: actually is %s", ErrChunkTypeNotCookieAck, c.typ.String()) + return fmt.Errorf("%w: actually is %s", errChunkTypeNotCookieAck, c.typ.String()) } return nil diff --git a/vendor/github.com/pion/sctp/chunk_cookie_echo.go b/vendor/github.com/pion/sctp/chunk_cookie_echo.go index 8eb956647..3aaced3de 100644 --- a/vendor/github.com/pion/sctp/chunk_cookie_echo.go +++ b/vendor/github.com/pion/sctp/chunk_cookie_echo.go @@ -8,24 +8,21 @@ import ( /* CookieEcho represents an SCTP Chunk of type CookieEcho - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Type = 10 |Chunk Flags | Length | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Cookie | - | | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Type = 10 |Chunk Flags | Length | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Cookie | +| | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ type chunkCookieEcho struct { chunkHeader cookie []byte } -// Cookie echo chunk errors -var ( - ErrChunkTypeNotCookieEcho = errors.New("ChunkType is not of type COOKIEECHO") -) +var errChunkTypeNotCookieEcho = errors.New("ChunkType is not of type COOKIEECHO") func (c *chunkCookieEcho) unmarshal(raw []byte) error { if err := c.chunkHeader.unmarshal(raw); err != nil { @@ -33,7 +30,7 @@ func (c *chunkCookieEcho) unmarshal(raw []byte) error { } if c.typ != ctCookieEcho { - return fmt.Errorf("%w: actually is %s", ErrChunkTypeNotCookieEcho, c.typ.String()) + return fmt.Errorf("%w: actually is %s", errChunkTypeNotCookieEcho, c.typ.String()) } c.cookie = c.raw diff --git a/vendor/github.com/pion/sctp/chunk_error.go b/vendor/github.com/pion/sctp/chunk_error.go index d2a2b2971..d58d752c4 100644 --- a/vendor/github.com/pion/sctp/chunk_error.go +++ b/vendor/github.com/pion/sctp/chunk_error.go @@ -6,42 +6,41 @@ import ( ) /* -Operation Error (ERROR) (9) + Operation Error (ERROR) (9) -An endpoint sends this chunk to its peer endpoint to notify it of -certain error conditions. It contains one or more error causes. An -Operation Error is not considered fatal in and of itself, but may be -used with an ERROR chunk to report a fatal condition. It has the -following parameters: + An endpoint sends this chunk to its peer endpoint to notify it of + certain error conditions. It contains one or more error causes. An + Operation Error is not considered fatal in and of itself, but may be + used with an ERROR chunk to report a fatal condition. It has the + following parameters: - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Type = 9 | Chunk Flags | Length | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - \ \ - / one or more Error Causes / - \ \ - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Type = 9 | Chunk Flags | Length | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + \ \ + / one or more Error Causes / + \ \ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -Chunk Flags: 8 bits + Chunk Flags: 8 bits - Set to 0 on transmit and ignored on receipt. + Set to 0 on transmit and ignored on receipt. -Length: 16 bits (unsigned integer) + Length: 16 bits (unsigned integer) - Set to the size of the chunk in bytes, including the chunk header - and all the Error Cause fields present. + Set to the size of the chunk in bytes, including the chunk header + and all the Error Cause fields present. */ type chunkError struct { chunkHeader errorCauses []errorCause } -// Error chunk errors var ( - ErrChunkTypeNotCtError = errors.New("ChunkType is not of type ctError") - ErrBuildErrorChunkFailed = errors.New("failed build Error Chunk") + errChunkTypeNotCtError = errors.New("ChunkType is not of type ctError") + errBuildErrorChunkFailed = errors.New("failed build Error Chunk") ) func (a *chunkError) unmarshal(raw []byte) error { @@ -50,7 +49,7 @@ func (a *chunkError) unmarshal(raw []byte) error { } if a.typ != ctError { - return fmt.Errorf("%w, actually is %s", ErrChunkTypeNotCtError, a.typ.String()) + return fmt.Errorf("%w, actually is %s", errChunkTypeNotCtError, a.typ.String()) } offset := chunkHeaderSize @@ -61,7 +60,7 @@ func (a *chunkError) unmarshal(raw []byte) error { e, err := buildErrorCause(raw[offset:]) if err != nil { - return fmt.Errorf("%w: %v", ErrBuildErrorChunkFailed, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errBuildErrorChunkFailed, err) } offset += int(e.length()) diff --git a/vendor/github.com/pion/sctp/chunk_forward_tsn.go b/vendor/github.com/pion/sctp/chunk_forward_tsn.go index 70b5079f0..8f04d93f2 100644 --- a/vendor/github.com/pion/sctp/chunk_forward_tsn.go +++ b/vendor/github.com/pion/sctp/chunk_forward_tsn.go @@ -43,10 +43,9 @@ const ( forwardTSNStreamLength = 4 ) -// Forward TSN chunk errors var ( - ErrMarshalStreamFailed = errors.New("failed to marshal stream") - ErrChunkTooShort = errors.New("chunk too short") + errMarshalStreamFailed = errors.New("failed to marshal stream") + errChunkTooShort = errors.New("chunk too short") ) func (c *chunkForwardTSN) unmarshal(raw []byte) error { @@ -55,7 +54,7 @@ func (c *chunkForwardTSN) unmarshal(raw []byte) error { } if len(c.raw) < newCumulativeTSNLength { - return ErrChunkTooShort + return errChunkTooShort } c.newCumulativeTSN = binary.BigEndian.Uint32(c.raw[0:]) @@ -66,7 +65,7 @@ func (c *chunkForwardTSN) unmarshal(raw []byte) error { s := chunkForwardTSNStream{} if err := s.unmarshal(c.raw[offset:]); err != nil { - return fmt.Errorf("%w: %v", ErrMarshalStreamFailed, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errMarshalStreamFailed, err) } c.streams = append(c.streams, s) @@ -85,7 +84,7 @@ func (c *chunkForwardTSN) marshal() ([]byte, error) { for _, s := range c.streams { b, err := s.marshal() if err != nil { - return nil, fmt.Errorf("%w: %v", ErrMarshalStreamFailed, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errMarshalStreamFailed, err) } out = append(out, b...) } @@ -130,7 +129,7 @@ func (s *chunkForwardTSNStream) length() int { func (s *chunkForwardTSNStream) unmarshal(raw []byte) error { if len(raw) < forwardTSNStreamLength { - return ErrChunkTooShort + return errChunkTooShort } s.identifier = binary.BigEndian.Uint16(raw[0:]) s.sequence = binary.BigEndian.Uint16(raw[2:]) diff --git a/vendor/github.com/pion/sctp/chunk_heartbeat.go b/vendor/github.com/pion/sctp/chunk_heartbeat.go index 3cfcd5ada..7db97cdf2 100644 --- a/vendor/github.com/pion/sctp/chunk_heartbeat.go +++ b/vendor/github.com/pion/sctp/chunk_heartbeat.go @@ -15,15 +15,16 @@ the present association. The parameter field contains the Heartbeat Information, which is a variable-length opaque data structure understood only by the sender. - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Type = 4 | Chunk Flags | Heartbeat Length | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | | - | Heartbeat Information TLV (Variable-Length) | - | | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Type = 4 | Chunk Flags | Heartbeat Length | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| | +| Heartbeat Information TLV (Variable-Length) | +| | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Defined as a variable-length parameter using the format described in Section 3.2.1, i.e.: @@ -37,37 +38,36 @@ type chunkHeartbeat struct { params []param } -// Heartbeat chunk errors var ( - ErrChunkTypeNotHeartbeat = errors.New("ChunkType is not of type HEARTBEAT") - ErrHeartbeatNotLongEnoughInfo = errors.New("heartbeat is not long enough to contain Heartbeat Info") - ErrParseParamTypeFailed = errors.New("failed to parse param type") - ErrHeartbeatParam = errors.New("heartbeat should only have HEARTBEAT param") - ErrHeartbeatChunkUnmarshal = errors.New("failed unmarshalling param in Heartbeat Chunk") + errChunkTypeNotHeartbeat = errors.New("ChunkType is not of type HEARTBEAT") + errHeartbeatNotLongEnoughInfo = errors.New("heartbeat is not long enough to contain Heartbeat Info") + errParseParamTypeFailed = errors.New("failed to parse param type") + errHeartbeatParam = errors.New("heartbeat should only have HEARTBEAT param") + errHeartbeatChunkUnmarshal = errors.New("failed unmarshalling param in Heartbeat Chunk") ) func (h *chunkHeartbeat) unmarshal(raw []byte) error { if err := h.chunkHeader.unmarshal(raw); err != nil { return err } else if h.typ != ctHeartbeat { - return fmt.Errorf("%w: actually is %s", ErrChunkTypeNotHeartbeat, h.typ.String()) + return fmt.Errorf("%w: actually is %s", errChunkTypeNotHeartbeat, h.typ.String()) } if len(raw) <= chunkHeaderSize { - return fmt.Errorf("%w: %d", ErrHeartbeatNotLongEnoughInfo, len(raw)) + return fmt.Errorf("%w: %d", errHeartbeatNotLongEnoughInfo, len(raw)) } pType, err := parseParamType(raw[chunkHeaderSize:]) if err != nil { - return fmt.Errorf("%w: %v", ErrParseParamTypeFailed, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errParseParamTypeFailed, err) } if pType != heartbeatInfo { - return fmt.Errorf("%w: instead have %s", ErrHeartbeatParam, pType.String()) + return fmt.Errorf("%w: instead have %s", errHeartbeatParam, pType.String()) } p, err := buildParam(pType, raw[chunkHeaderSize:]) if err != nil { - return fmt.Errorf("%w: %v", ErrHeartbeatChunkUnmarshal, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errHeartbeatChunkUnmarshal, err) } h.params = append(h.params, p) @@ -75,7 +75,7 @@ func (h *chunkHeartbeat) unmarshal(raw []byte) error { } func (h *chunkHeartbeat) Marshal() ([]byte, error) { - return nil, ErrUnimplemented + return nil, errUnimplemented } func (h *chunkHeartbeat) check() (abort bool, err error) { diff --git a/vendor/github.com/pion/sctp/chunk_heartbeat_ack.go b/vendor/github.com/pion/sctp/chunk_heartbeat_ack.go index 3d21b593d..feb822c20 100644 --- a/vendor/github.com/pion/sctp/chunk_heartbeat_ack.go +++ b/vendor/github.com/pion/sctp/chunk_heartbeat_ack.go @@ -15,15 +15,16 @@ HEARTBEAT chunk to which this ack is responding. The parameter field contains a variable-length opaque data structure. - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Type = 5 | Chunk Flags | Heartbeat Ack Length | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | | - | Heartbeat Information TLV (Variable-Length) | - | | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Type = 5 | Chunk Flags | Heartbeat Ack Length | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| | +| Heartbeat Information TLV (Variable-Length) | +| | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + Defined as a variable-length parameter using the format described in Section 3.2.1, i.e.: @@ -37,35 +38,34 @@ type chunkHeartbeatAck struct { params []param } -// Heartbeat ack chunk errors var ( - ErrUnimplemented = errors.New("unimplemented") - ErrHeartbeatAckParams = errors.New("heartbeat Ack must have one param") - ErrHeartbeatAckNotHeartbeatInfo = errors.New("heartbeat Ack must have one param, and it should be a HeartbeatInfo") - ErrHeartbeatAckMarshalParam = errors.New("unable to marshal parameter for Heartbeat Ack") + errUnimplemented = errors.New("unimplemented") + errHeartbeatAckParams = errors.New("heartbeat Ack must have one param") + errHeartbeatAckNotHeartbeatInfo = errors.New("heartbeat Ack must have one param, and it should be a HeartbeatInfo") + errHeartbeatAckMarshalParam = errors.New("unable to marshal parameter for Heartbeat Ack") ) -func (h *chunkHeartbeatAck) unmarshal([]byte) error { - return ErrUnimplemented +func (h *chunkHeartbeatAck) unmarshal(raw []byte) error { + return errUnimplemented } func (h *chunkHeartbeatAck) marshal() ([]byte, error) { if len(h.params) != 1 { - return nil, ErrHeartbeatAckParams + return nil, errHeartbeatAckParams } switch h.params[0].(type) { case *paramHeartbeatInfo: // ParamHeartbeatInfo is valid default: - return nil, ErrHeartbeatAckNotHeartbeatInfo + return nil, errHeartbeatAckNotHeartbeatInfo } out := make([]byte, 0) for idx, p := range h.params { pp, err := p.marshal() if err != nil { - return nil, fmt.Errorf("%w: %v", ErrHeartbeatAckMarshalParam, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errHeartbeatAckMarshalParam, err) } out = append(out, pp...) diff --git a/vendor/github.com/pion/sctp/chunk_init.go b/vendor/github.com/pion/sctp/chunk_init.go index 8eab506b9..8a2a1cdaa 100644 --- a/vendor/github.com/pion/sctp/chunk_init.go +++ b/vendor/github.com/pion/sctp/chunk_init.go @@ -10,31 +10,30 @@ Init represents an SCTP Chunk of type INIT See chunkInitCommon for the fixed headers - Variable Parameters Status Type Value - ------------------------------------------------------------- - IPv4 IP (Note 1) Optional 5 - IPv6 IP (Note 1) Optional 6 - Cookie Preservative Optional 9 - Reserved for ECN Capable (Note 2) Optional 32768 (0x8000) - Host Name IP (Note 3) Optional 11 - Supported IP Types (Note 4) Optional 12 +Variable Parameters Status Type Value +------------------------------------------------------------- +IPv4 IP (Note 1) Optional 5 +IPv6 IP (Note 1) Optional 6 +Cookie Preservative Optional 9 +Reserved for ECN Capable (Note 2) Optional 32768 (0x8000) +Host Name IP (Note 3) Optional 11 +Supported IP Types (Note 4) Optional 12 */ type chunkInit struct { chunkHeader chunkInitCommon } -// Init chunk errors var ( - ErrChunkTypeNotTypeInit = errors.New("ChunkType is not of type INIT") - ErrChunkValueNotLongEnough = errors.New("chunk Value isn't long enough for mandatory parameters exp") - ErrChunkTypeInitFlagZero = errors.New("ChunkType of type INIT flags must be all 0") - ErrChunkTypeInitUnmarshalFailed = errors.New("failed to unmarshal INIT body") - ErrChunkTypeInitMarshalFailed = errors.New("failed marshaling INIT common data") - ErrChunkTypeInitInitateTagZero = errors.New("ChunkType of type INIT ACK InitiateTag must not be 0") - ErrInitInboundStreamRequestZero = errors.New("INIT ACK inbound stream request must be > 0") - ErrInitOutboundStreamRequestZero = errors.New("INIT ACK outbound stream request must be > 0") - ErrInitAdvertisedReceiver1500 = errors.New("INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500") + errChunkTypeNotTypeInit = errors.New("ChunkType is not of type INIT") + errChunkValueNotLongEnough = errors.New("chunk Value isn't long enough for mandatory parameters exp") + errChunkTypeInitFlagZero = errors.New("ChunkType of type INIT flags must be all 0") + errChunkTypeInitUnmarshalFailed = errors.New("failed to unmarshal INIT body") + errChunkTypeInitMarshalFailed = errors.New("failed marshaling INIT common data") + errChunkTypeInitInitateTagZero = errors.New("ChunkType of type INIT ACK InitiateTag must not be 0") + errInitInboundStreamRequestZero = errors.New("INIT ACK inbound stream request must be > 0") + errInitOutboundStreamRequestZero = errors.New("INIT ACK outbound stream request must be > 0") + errInitAdvertisedReceiver1500 = errors.New("INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500") ) func (i *chunkInit) unmarshal(raw []byte) error { @@ -43,20 +42,20 @@ func (i *chunkInit) unmarshal(raw []byte) error { } if i.typ != ctInit { - return fmt.Errorf("%w: actually is %s", ErrChunkTypeNotTypeInit, i.typ.String()) + return fmt.Errorf("%w: actually is %s", errChunkTypeNotTypeInit, i.typ.String()) } else if len(i.raw) < initChunkMinLength { - return fmt.Errorf("%w: %d actual: %d", ErrChunkValueNotLongEnough, initChunkMinLength, len(i.raw)) + return fmt.Errorf("%w: %d actual: %d", errChunkValueNotLongEnough, initChunkMinLength, len(i.raw)) } // The Chunk Flags field in INIT is reserved, and all bits in it should // be set to 0 by the sender and ignored by the receiver. The sequence // of parameters within an INIT can be processed in any order. if i.flags != 0 { - return ErrChunkTypeInitFlagZero + return errChunkTypeInitFlagZero } if err := i.chunkInitCommon.unmarshal(i.raw); err != nil { - return fmt.Errorf("%w: %v", ErrChunkTypeInitUnmarshalFailed, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errChunkTypeInitUnmarshalFailed, err) } return nil @@ -65,7 +64,7 @@ func (i *chunkInit) unmarshal(raw []byte) error { func (i *chunkInit) marshal() ([]byte, error) { initShared, err := i.chunkInitCommon.marshal() if err != nil { - return nil, fmt.Errorf("%w: %v", ErrChunkTypeInitMarshalFailed, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errChunkTypeInitMarshalFailed, err) } i.chunkHeader.typ = ctInit @@ -87,7 +86,7 @@ func (i *chunkInit) check() (abort bool, err error) { // association by transmitting an ABORT. if i.initiateTag == 0 { abort = true - return abort, ErrChunkTypeInitInitateTagZero + return abort, errChunkTypeInitInitateTagZero } // Defines the maximum number of streams the sender of this INIT @@ -102,7 +101,7 @@ func (i *chunkInit) check() (abort bool, err error) { // the association. if i.numInboundStreams == 0 { abort = true - return abort, ErrInitInboundStreamRequestZero + return abort, errInitInboundStreamRequestZero } // Defines the number of outbound streams the sender of this INIT @@ -114,7 +113,7 @@ func (i *chunkInit) check() (abort bool, err error) { if i.numOutboundStreams == 0 { abort = true - return abort, ErrInitOutboundStreamRequestZero + return abort, errInitOutboundStreamRequestZero } // An SCTP receiver MUST be able to receive a minimum of 1500 bytes in @@ -123,7 +122,7 @@ func (i *chunkInit) check() (abort bool, err error) { // ACK. if i.advertisedReceiverWindowCredit < 1500 { abort = true - return abort, ErrInitAdvertisedReceiver1500 + return abort, errInitAdvertisedReceiver1500 } return false, nil diff --git a/vendor/github.com/pion/sctp/chunk_init_ack.go b/vendor/github.com/pion/sctp/chunk_init_ack.go index c34f1d6b6..02a3344b0 100644 --- a/vendor/github.com/pion/sctp/chunk_init_ack.go +++ b/vendor/github.com/pion/sctp/chunk_init_ack.go @@ -10,31 +10,30 @@ chunkInitAck represents an SCTP Chunk of type INIT ACK See chunkInitCommon for the fixed headers - Variable Parameters Status Type Value - ------------------------------------------------------------- - State Cookie Mandatory 7 - IPv4 IP (Note 1) Optional 5 - IPv6 IP (Note 1) Optional 6 - Unrecognized Parameter Optional 8 - Reserved for ECN Capable (Note 2) Optional 32768 (0x8000) - Host Name IP (Note 3) Optional 11 +Variable Parameters Status Type Value +------------------------------------------------------------- +State Cookie Mandatory 7 +IPv4 IP (Note 1) Optional 5 +IPv6 IP (Note 1) Optional 6 +Unrecognized Parameter Optional 8 +Reserved for ECN Capable (Note 2) Optional 32768 (0x8000) +Host Name IP (Note 3) Optional 11 */ type chunkInitAck struct { chunkHeader chunkInitCommon } -// Init ack chunk errors var ( - ErrChunkTypeNotInitAck = errors.New("ChunkType is not of type INIT ACK") - ErrChunkNotLongEnoughForParams = errors.New("chunk Value isn't long enough for mandatory parameters exp") - ErrChunkTypeInitAckFlagZero = errors.New("ChunkType of type INIT ACK flags must be all 0") - ErrInitAckUnmarshalFailed = errors.New("failed to unmarshal INIT body") - ErrInitCommonDataMarshalFailed = errors.New("failed marshaling INIT common data") - ErrChunkTypeInitAckInitateTagZero = errors.New("ChunkType of type INIT ACK InitiateTag must not be 0") - ErrInitAckInboundStreamRequestZero = errors.New("INIT ACK inbound stream request must be > 0") - ErrInitAckOutboundStreamRequestZero = errors.New("INIT ACK outbound stream request must be > 0") - ErrInitAckAdvertisedReceiver1500 = errors.New("INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500") + errChunkTypeNotInitAck = errors.New("ChunkType is not of type INIT ACK") + errChunkNotLongEnoughForParams = errors.New("chunk Value isn't long enough for mandatory parameters exp") + errChunkTypeInitAckFlagZero = errors.New("ChunkType of type INIT ACK flags must be all 0") + errInitAckUnmarshalFailed = errors.New("failed to unmarshal INIT body") + errInitCommonDataMarshalFailed = errors.New("failed marshaling INIT common data") + errChunkTypeInitAckInitateTagZero = errors.New("ChunkType of type INIT ACK InitiateTag must not be 0") + errInitAckInboundStreamRequestZero = errors.New("INIT ACK inbound stream request must be > 0") + errInitAckOutboundStreamRequestZero = errors.New("INIT ACK outbound stream request must be > 0") + errInitAckAdvertisedReceiver1500 = errors.New("INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500") ) func (i *chunkInitAck) unmarshal(raw []byte) error { @@ -43,20 +42,20 @@ func (i *chunkInitAck) unmarshal(raw []byte) error { } if i.typ != ctInitAck { - return fmt.Errorf("%w: actually is %s", ErrChunkTypeNotInitAck, i.typ.String()) + return fmt.Errorf("%w: actually is %s", errChunkTypeNotInitAck, i.typ.String()) } else if len(i.raw) < initChunkMinLength { - return fmt.Errorf("%w: %d actual: %d", ErrChunkNotLongEnoughForParams, initChunkMinLength, len(i.raw)) + return fmt.Errorf("%w: %d actual: %d", errChunkNotLongEnoughForParams, initChunkMinLength, len(i.raw)) } // The Chunk Flags field in INIT is reserved, and all bits in it should // be set to 0 by the sender and ignored by the receiver. The sequence // of parameters within an INIT can be processed in any order. if i.flags != 0 { - return ErrChunkTypeInitAckFlagZero + return errChunkTypeInitAckFlagZero } if err := i.chunkInitCommon.unmarshal(i.raw); err != nil { - return fmt.Errorf("%w: %v", ErrInitAckUnmarshalFailed, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errInitAckUnmarshalFailed, err) } return nil @@ -65,7 +64,7 @@ func (i *chunkInitAck) unmarshal(raw []byte) error { func (i *chunkInitAck) marshal() ([]byte, error) { initShared, err := i.chunkInitCommon.marshal() if err != nil { - return nil, fmt.Errorf("%w: %v", ErrInitCommonDataMarshalFailed, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errInitCommonDataMarshalFailed, err) } i.chunkHeader.typ = ctInitAck @@ -88,7 +87,7 @@ func (i *chunkInitAck) check() (abort bool, err error) { // purpose. if i.initiateTag == 0 { abort = true - return abort, ErrChunkTypeInitAckInitateTagZero + return abort, errChunkTypeInitAckInitateTagZero } // Defines the maximum number of streams the sender of this INIT ACK @@ -103,7 +102,7 @@ func (i *chunkInitAck) check() (abort bool, err error) { // destroy the association discarding its TCB. if i.numInboundStreams == 0 { abort = true - return abort, ErrInitAckInboundStreamRequestZero + return abort, errInitAckInboundStreamRequestZero } // Defines the number of outbound streams the sender of this INIT ACK @@ -116,7 +115,7 @@ func (i *chunkInitAck) check() (abort bool, err error) { if i.numOutboundStreams == 0 { abort = true - return abort, ErrInitAckOutboundStreamRequestZero + return abort, errInitAckOutboundStreamRequestZero } // An SCTP receiver MUST be able to receive a minimum of 1500 bytes in @@ -125,7 +124,7 @@ func (i *chunkInitAck) check() (abort bool, err error) { // ACK. if i.advertisedReceiverWindowCredit < 1500 { abort = true - return abort, ErrInitAckAdvertisedReceiver1500 + return abort, errInitAckAdvertisedReceiver1500 } return false, nil diff --git a/vendor/github.com/pion/sctp/chunk_init_common.go b/vendor/github.com/pion/sctp/chunk_init_common.go index c2ccfadc0..14535cab1 100644 --- a/vendor/github.com/pion/sctp/chunk_init_common.go +++ b/vendor/github.com/pion/sctp/chunk_init_common.go @@ -53,11 +53,10 @@ const ( initOptionalVarHeaderLength = 4 ) -// Init chunk errors var ( - ErrInitChunkParseParamTypeFailed = errors.New("failed to parse param type") - ErrInitChunkUnmarshalParam = errors.New("failed unmarshalling param in Init Chunk") - ErrInitAckMarshalParam = errors.New("unable to marshal parameter for INIT/INITACK") + errInitChunkParseParamTypeFailed = errors.New("failed to parse param type") + errInitChunkUnmarshalParam = errors.New("failed unmarshalling param in Init Chunk") + errInitAckMarshalParam = errors.New("unable to marshal parameter for INIT/INITACK") ) func (i *chunkInitCommon) unmarshal(raw []byte) error { @@ -90,11 +89,11 @@ func (i *chunkInitCommon) unmarshal(raw []byte) error { if remaining > initOptionalVarHeaderLength { pType, err := parseParamType(raw[offset:]) if err != nil { - return fmt.Errorf("%w: %v", ErrInitChunkParseParamTypeFailed, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errInitChunkParseParamTypeFailed, err) } p, err := buildParam(pType, raw[offset:]) if err != nil { - return fmt.Errorf("%w: %v", ErrInitChunkUnmarshalParam, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errInitChunkUnmarshalParam, err) } i.params = append(i.params, p) padding := getPadding(p.length()) @@ -118,7 +117,7 @@ func (i *chunkInitCommon) marshal() ([]byte, error) { for idx, p := range i.params { pp, err := p.marshal() if err != nil { - return nil, fmt.Errorf("%w: %v", ErrInitAckMarshalParam, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errInitAckMarshalParam, err) } out = append(out, pp...) diff --git a/vendor/github.com/pion/sctp/chunk_payload_data.go b/vendor/github.com/pion/sctp/chunk_payload_data.go index 50554ac45..eecc7c8c8 100644 --- a/vendor/github.com/pion/sctp/chunk_payload_data.go +++ b/vendor/github.com/pion/sctp/chunk_payload_data.go @@ -10,38 +10,38 @@ import ( /* chunkPayloadData represents an SCTP Chunk of type DATA - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Type = 0 | Reserved|U|B|E| Length | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | TSN | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Stream Identifier S | Stream Sequence Number n | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Payload Protocol Identifier | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | | - | User Data (seq n of Stream S) | - | | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Type = 0 | Reserved|U|B|E| Length | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| TSN | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Stream Identifier S | Stream Sequence Number n | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Payload Protocol Identifier | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| | +| User Data (seq n of Stream S) | +| | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + An unfragmented user message shall have both the B and E bits set to '1'. Setting both B and E bits to '0' indicates a middle fragment of a multi-fragment user message, as summarized in the following table: - - B E Description - ============================================================ - | 1 0 | First piece of a fragmented user message | - +----------------------------------------------------------+ - | 0 0 | Middle piece of a fragmented user message | - +----------------------------------------------------------+ - | 0 1 | Last piece of a fragmented user message | - +----------------------------------------------------------+ - | 1 1 | Unfragmented message | - ============================================================ - | Table 1: Fragment Description Flags | - ============================================================ + B E Description +============================================================ +| 1 0 | First piece of a fragmented user message | ++----------------------------------------------------------+ +| 0 0 | Middle piece of a fragmented user message | ++----------------------------------------------------------+ +| 0 1 | Last piece of a fragmented user message | ++----------------------------------------------------------+ +| 1 1 | Unfragmented message | +============================================================ +| Table 1: Fragment Description Flags | +============================================================ */ type chunkPayloadData struct { chunkHeader @@ -97,10 +97,7 @@ const ( PayloadTypeWebRTCBinaryEmpty PayloadProtocolIdentifier = 57 ) -// Data chunk errors -var ( - ErrChunkPayloadSmall = errors.New("packet is smaller than the header size") -) +var errChunkPayloadSmall = errors.New("packet is smaller than the header size") func (p PayloadProtocolIdentifier) String() string { switch p { @@ -130,7 +127,7 @@ func (p *chunkPayloadData) unmarshal(raw []byte) error { p.endingFragment = p.flags&payloadDataEndingFragmentBitmask != 0 if len(raw) < payloadDataHeaderSize { - return ErrChunkPayloadSmall + return errChunkPayloadSmall } p.tsn = binary.BigEndian.Uint32(p.raw[0:]) p.streamIdentifier = binary.BigEndian.Uint16(p.raw[4:]) diff --git a/vendor/github.com/pion/sctp/chunk_reconfig.go b/vendor/github.com/pion/sctp/chunk_reconfig.go index 9b018b213..c827a40a4 100644 --- a/vendor/github.com/pion/sctp/chunk_reconfig.go +++ b/vendor/github.com/pion/sctp/chunk_reconfig.go @@ -28,11 +28,10 @@ type chunkReconfig struct { paramB param } -// Reconfigure chunk errors var ( - ErrChunkParseParamTypeFailed = errors.New("failed to parse param type") - ErrChunkMarshalParamAReconfigFailed = errors.New("unable to marshal parameter A for reconfig") - ErrChunkMarshalParamBReconfigFailed = errors.New("unable to marshal parameter B for reconfig") + errChunkParseParamTypeFailed = errors.New("failed to parse param type") + errChunkMarshalParamAReconfigFailed = errors.New("unable to marshal parameter A for reconfig") + errChunkMarshalParamBReconfigFailed = errors.New("unable to marshal parameter B for reconfig") ) func (c *chunkReconfig) unmarshal(raw []byte) error { @@ -41,7 +40,7 @@ func (c *chunkReconfig) unmarshal(raw []byte) error { } pType, err := parseParamType(c.raw) if err != nil { - return fmt.Errorf("%w: %v", ErrChunkParseParamTypeFailed, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errChunkParseParamTypeFailed, err) } a, err := buildParam(pType, c.raw) if err != nil { @@ -54,7 +53,7 @@ func (c *chunkReconfig) unmarshal(raw []byte) error { if len(c.raw) > offset { pType, err := parseParamType(c.raw[offset:]) if err != nil { - return fmt.Errorf("%w: %v", ErrChunkParseParamTypeFailed, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errChunkParseParamTypeFailed, err) } b, err := buildParam(pType, c.raw[offset:]) if err != nil { @@ -69,7 +68,7 @@ func (c *chunkReconfig) unmarshal(raw []byte) error { func (c *chunkReconfig) marshal() ([]byte, error) { out, err := c.paramA.marshal() if err != nil { - return nil, fmt.Errorf("%w: %v", ErrChunkMarshalParamAReconfigFailed, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errChunkMarshalParamAReconfigFailed, err) } if c.paramB != nil { // Pad param A @@ -77,7 +76,7 @@ func (c *chunkReconfig) marshal() ([]byte, error) { outB, err := c.paramB.marshal() if err != nil { - return nil, fmt.Errorf("%w: %v", ErrChunkMarshalParamBReconfigFailed, err) //nolint:errorlint + return nil, fmt.Errorf("%w: %v", errChunkMarshalParamBReconfigFailed, err) } out = append(out, outB...) diff --git a/vendor/github.com/pion/sctp/chunk_selective_ack.go b/vendor/github.com/pion/sctp/chunk_selective_ack.go index 28223a920..00f83dba5 100644 --- a/vendor/github.com/pion/sctp/chunk_selective_ack.go +++ b/vendor/github.com/pion/sctp/chunk_selective_ack.go @@ -46,11 +46,10 @@ type gapAckBlock struct { end uint16 } -// Selective ack chunk errors var ( - ErrChunkTypeNotSack = errors.New("ChunkType is not of type SACK") - ErrSackSizeNotLargeEnoughInfo = errors.New("SACK Chunk size is not large enough to contain header") - ErrSackSizeNotMatchPredicted = errors.New("SACK Chunk size does not match predicted amount from header values") + errChunkTypeNotSack = errors.New("ChunkType is not of type SACK") + errSackSizeNotLargeEnoughInfo = errors.New("SACK Chunk size is not large enough to contain header") + errSackSizeNotMatchPredicted = errors.New("SACK Chunk size does not match predicted amount from header values") ) // String makes gapAckBlock printable @@ -76,11 +75,11 @@ func (s *chunkSelectiveAck) unmarshal(raw []byte) error { } if s.typ != ctSack { - return fmt.Errorf("%w: actually is %s", ErrChunkTypeNotSack, s.typ.String()) + return fmt.Errorf("%w: actually is %s", errChunkTypeNotSack, s.typ.String()) } if len(s.raw) < selectiveAckHeaderSize { - return fmt.Errorf("%w: %v remaining, needs %v bytes", ErrSackSizeNotLargeEnoughInfo, + return fmt.Errorf("%w: %v remaining, needs %v bytes", errSackSizeNotLargeEnoughInfo, len(s.raw), selectiveAckHeaderSize) } @@ -90,7 +89,7 @@ func (s *chunkSelectiveAck) unmarshal(raw []byte) error { s.duplicateTSN = make([]uint32, binary.BigEndian.Uint16(s.raw[10:])) if len(s.raw) != selectiveAckHeaderSize+(4*len(s.gapAckBlocks)+(4*len(s.duplicateTSN))) { - return ErrSackSizeNotMatchPredicted + return errSackSizeNotMatchPredicted } offset := selectiveAckHeaderSize diff --git a/vendor/github.com/pion/sctp/chunk_shutdown.go b/vendor/github.com/pion/sctp/chunk_shutdown.go index bcd9fc155..be0371a88 100644 --- a/vendor/github.com/pion/sctp/chunk_shutdown.go +++ b/vendor/github.com/pion/sctp/chunk_shutdown.go @@ -26,10 +26,9 @@ const ( cumulativeTSNAckLength = 4 ) -// Shutdown chunk errors var ( - ErrInvalidChunkSize = errors.New("invalid chunk size") - ErrChunkTypeNotShutdown = errors.New("ChunkType is not of type SHUTDOWN") + errInvalidChunkSize = errors.New("invalid chunk size") + errChunkTypeNotShutdown = errors.New("ChunkType is not of type SHUTDOWN") ) func (c *chunkShutdown) unmarshal(raw []byte) error { @@ -38,11 +37,11 @@ func (c *chunkShutdown) unmarshal(raw []byte) error { } if c.typ != ctShutdown { - return fmt.Errorf("%w: actually is %s", ErrChunkTypeNotShutdown, c.typ.String()) + return fmt.Errorf("%w: actually is %s", errChunkTypeNotShutdown, c.typ.String()) } if len(c.raw) != cumulativeTSNAckLength { - return ErrInvalidChunkSize + return errInvalidChunkSize } c.cumulativeTSNAck = binary.BigEndian.Uint32(c.raw[0:]) diff --git a/vendor/github.com/pion/sctp/chunk_shutdown_ack.go b/vendor/github.com/pion/sctp/chunk_shutdown_ack.go index a8bb8d0c2..f575dbbd6 100644 --- a/vendor/github.com/pion/sctp/chunk_shutdown_ack.go +++ b/vendor/github.com/pion/sctp/chunk_shutdown_ack.go @@ -18,10 +18,7 @@ type chunkShutdownAck struct { chunkHeader } -// Shutdown ack chunk errors -var ( - ErrChunkTypeNotShutdownAck = errors.New("ChunkType is not of type SHUTDOWN-ACK") -) +var errChunkTypeNotShutdownAck = errors.New("ChunkType is not of type SHUTDOWN-ACK") func (c *chunkShutdownAck) unmarshal(raw []byte) error { if err := c.chunkHeader.unmarshal(raw); err != nil { @@ -29,7 +26,7 @@ func (c *chunkShutdownAck) unmarshal(raw []byte) error { } if c.typ != ctShutdownAck { - return fmt.Errorf("%w: actually is %s", ErrChunkTypeNotShutdownAck, c.typ.String()) + return fmt.Errorf("%w: actually is %s", errChunkTypeNotShutdownAck, c.typ.String()) } return nil diff --git a/vendor/github.com/pion/sctp/chunk_shutdown_complete.go b/vendor/github.com/pion/sctp/chunk_shutdown_complete.go index 4de045d62..99883f346 100644 --- a/vendor/github.com/pion/sctp/chunk_shutdown_complete.go +++ b/vendor/github.com/pion/sctp/chunk_shutdown_complete.go @@ -18,10 +18,7 @@ type chunkShutdownComplete struct { chunkHeader } -// Shutdown complete chunk errors -var ( - ErrChunkTypeNotShutdownComplete = errors.New("ChunkType is not of type SHUTDOWN-COMPLETE") -) +var errChunkTypeNotShutdownComplete = errors.New("ChunkType is not of type SHUTDOWN-COMPLETE") func (c *chunkShutdownComplete) unmarshal(raw []byte) error { if err := c.chunkHeader.unmarshal(raw); err != nil { @@ -29,7 +26,7 @@ func (c *chunkShutdownComplete) unmarshal(raw []byte) error { } if c.typ != ctShutdownComplete { - return fmt.Errorf("%w: actually is %s", ErrChunkTypeNotShutdownComplete, c.typ.String()) + return fmt.Errorf("%w: actually is %s", errChunkTypeNotShutdownComplete, c.typ.String()) } return nil diff --git a/vendor/github.com/pion/sctp/chunkheader.go b/vendor/github.com/pion/sctp/chunkheader.go index 6e9a5e9d6..be2a12264 100644 --- a/vendor/github.com/pion/sctp/chunkheader.go +++ b/vendor/github.com/pion/sctp/chunkheader.go @@ -13,15 +13,15 @@ transmitted in the SCTP packet. Each chunk is formatted with a Chunk Type field, a chunk-specific Flag field, a Chunk Length field, and a Value field. - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Chunk Type | Chunk Flags | Chunk Length | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | | - | Chunk Value | - | | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Chunk Type | Chunk Flags | Chunk Length | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| | +| Chunk Value | +| | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ type chunkHeader struct { typ chunkType @@ -33,16 +33,15 @@ const ( chunkHeaderSize = 4 ) -// SCTP chunk header errors var ( - ErrChunkHeaderTooSmall = errors.New("raw is too small for a SCTP chunk") - ErrChunkHeaderNotEnoughSpace = errors.New("not enough data left in SCTP packet to satisfy requested length") - ErrChunkHeaderPaddingNonZero = errors.New("chunk padding is non-zero at offset") + errChunkHeaderTooSmall = errors.New("raw is too small for a SCTP chunk") + errChunkHeaderNotEnoughSpace = errors.New("not enough data left in SCTP packet to satisfy requested length") + errChunkHeaderPaddingNonZero = errors.New("chunk padding is non-zero at offset") ) func (c *chunkHeader) unmarshal(raw []byte) error { if len(raw) < chunkHeaderSize { - return fmt.Errorf("%w: raw only %d bytes, %d is the minimum length", ErrChunkHeaderTooSmall, len(raw), chunkHeaderSize) + return fmt.Errorf("%w: raw only %d bytes, %d is the minimum length", errChunkHeaderTooSmall, len(raw), chunkHeaderSize) } c.typ = chunkType(raw[0]) @@ -54,7 +53,7 @@ func (c *chunkHeader) unmarshal(raw []byte) error { lengthAfterValue := len(raw) - (chunkHeaderSize + valueLength) if lengthAfterValue < 0 { - return fmt.Errorf("%w: remain %d req %d ", ErrChunkHeaderNotEnoughSpace, valueLength, len(raw)-chunkHeaderSize) + return fmt.Errorf("%w: remain %d req %d ", errChunkHeaderNotEnoughSpace, valueLength, len(raw)-chunkHeaderSize) } else if lengthAfterValue < 4 { // https://tools.ietf.org/html/rfc4960#section-3.2 // The Chunk Length field does not count any chunk padding. @@ -68,7 +67,7 @@ func (c *chunkHeader) unmarshal(raw []byte) error { for i := lengthAfterValue; i > 0; i-- { paddingOffset := chunkHeaderSize + valueLength + (i - 1) if raw[paddingOffset] != 0 { - return fmt.Errorf("%w: %d ", ErrChunkHeaderPaddingNonZero, paddingOffset) + return fmt.Errorf("%w: %d ", errChunkHeaderPaddingNonZero, paddingOffset) } } } diff --git a/vendor/github.com/pion/sctp/error_cause.go b/vendor/github.com/pion/sctp/error_cause.go index 9e5e68d85..db9a56f05 100644 --- a/vendor/github.com/pion/sctp/error_cause.go +++ b/vendor/github.com/pion/sctp/error_cause.go @@ -18,10 +18,7 @@ type errorCause interface { errorCauseCode() errorCauseCode } -// Error and abort chunk errors -var ( - ErrBuildErrorCaseHandle = errors.New("BuildErrorCause does not handle") -) +var errBuildErrorCaseHandle = errors.New("BuildErrorCause does not handle") // buildErrorCause delegates the building of a error cause from raw bytes to the correct structure func buildErrorCause(raw []byte) (errorCause, error) { @@ -35,16 +32,13 @@ func buildErrorCause(raw []byte) (errorCause, error) { e = &errorCauseUnrecognizedChunkType{} case protocolViolation: e = &errorCauseProtocolViolation{} - case userInitiatedAbort: - e = &errorCauseUserInitiatedAbort{} default: - return nil, fmt.Errorf("%w: %s", ErrBuildErrorCaseHandle, c.String()) + return nil, fmt.Errorf("%w: %s", errBuildErrorCaseHandle, c.String()) } if err := e.unmarshal(raw); err != nil { return nil, err } - return e, nil } diff --git a/vendor/github.com/pion/sctp/error_cause_protocol_violation.go b/vendor/github.com/pion/sctp/error_cause_protocol_violation.go index 5434e0e3e..3379ea24b 100644 --- a/vendor/github.com/pion/sctp/error_cause_protocol_violation.go +++ b/vendor/github.com/pion/sctp/error_cause_protocol_violation.go @@ -6,31 +6,28 @@ import ( ) /* -This error cause MAY be included in ABORT chunks that are sent -because an SCTP endpoint detects a protocol violation of the peer -that is not covered by the error causes described in Section 3.3.10.1 -to Section 3.3.10.12. An implementation MAY provide additional -information specifying what kind of protocol violation has been -detected. + This error cause MAY be included in ABORT chunks that are sent + because an SCTP endpoint detects a protocol violation of the peer + that is not covered by the error causes described in Section 3.3.10.1 + to Section 3.3.10.12. An implementation MAY provide additional + information specifying what kind of protocol violation has been + detected. - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Cause Code=13 | Cause Length=Variable | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - / Additional Information / - \ \ - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Cause Code=13 | Cause Length=Variable | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + / Additional Information / + \ \ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ type errorCauseProtocolViolation struct { errorCauseHeader additionalInformation []byte } -// Abort chunk errors -var ( - ErrProtocolViolationUnmarshal = errors.New("unable to unmarshal Protocol Violation error") -) +var errProtocolViolationUnmarshal = errors.New("unable to unmarshal Protocol Violation error") func (e *errorCauseProtocolViolation) marshal() ([]byte, error) { e.raw = e.additionalInformation @@ -40,7 +37,7 @@ func (e *errorCauseProtocolViolation) marshal() ([]byte, error) { func (e *errorCauseProtocolViolation) unmarshal(raw []byte) error { err := e.errorCauseHeader.unmarshal(raw) if err != nil { - return fmt.Errorf("%w: %v", ErrProtocolViolationUnmarshal, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errProtocolViolationUnmarshal, err) } e.additionalInformation = e.raw diff --git a/vendor/github.com/pion/sctp/error_cause_user_initiated_abort.go b/vendor/github.com/pion/sctp/error_cause_user_initiated_abort.go deleted file mode 100644 index 1dee93733..000000000 --- a/vendor/github.com/pion/sctp/error_cause_user_initiated_abort.go +++ /dev/null @@ -1,46 +0,0 @@ -package sctp - -import ( - "fmt" -) - -/* -This error cause MAY be included in ABORT chunks that are sent -because of an upper-layer request. The upper layer can specify an -Upper Layer Abort Reason that is transported by SCTP transparently -and MAY be delivered to the upper-layer protocol at the peer. - - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Cause Code=12 | Cause Length=Variable | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - / Upper Layer Abort Reason / - \ \ - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -*/ -type errorCauseUserInitiatedAbort struct { - errorCauseHeader - upperLayerAbortReason []byte -} - -func (e *errorCauseUserInitiatedAbort) marshal() ([]byte, error) { - e.code = userInitiatedAbort - e.errorCauseHeader.raw = e.upperLayerAbortReason - return e.errorCauseHeader.marshal() -} - -func (e *errorCauseUserInitiatedAbort) unmarshal(raw []byte) error { - err := e.errorCauseHeader.unmarshal(raw) - if err != nil { - return err - } - - e.upperLayerAbortReason = e.errorCauseHeader.raw - return nil -} - -// String makes errorCauseUserInitiatedAbort printable -func (e *errorCauseUserInitiatedAbort) String() string { - return fmt.Sprintf("%s: %s", e.errorCauseHeader.String(), e.upperLayerAbortReason) -} diff --git a/vendor/github.com/pion/sctp/packet.go b/vendor/github.com/pion/sctp/packet.go index 7bc22c82f..f1765adb0 100644 --- a/vendor/github.com/pion/sctp/packet.go +++ b/vendor/github.com/pion/sctp/packet.go @@ -19,29 +19,34 @@ Packet represents an SCTP packet, defined in https://tools.ietf.org/html/rfc4960 An SCTP packet is composed of a common header and chunks. A chunk contains either control information or user data. - SCTP Packet Format - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Common Header | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Chunk #1 | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | ... | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Chunk #n | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - SCTP Common Header Format - 0 1 2 3 - 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Source Value Number | Destination Value Number | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Verification Tag | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - | Checksum | - +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + SCTP Packet Format + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Common Header | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Chunk #1 | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| ... | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Chunk #n | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + + SCTP Common Header Format + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Source Value Number | Destination Value Number | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Verification Tag | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +| Checksum | ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + */ type packet struct { sourcePort uint16 @@ -54,17 +59,16 @@ const ( packetHeaderSize = 12 ) -// SCTP packet errors var ( - ErrPacketRawTooSmall = errors.New("raw is smaller than the minimum length for a SCTP packet") - ErrParseSCTPChunkNotEnoughData = errors.New("unable to parse SCTP chunk, not enough data for complete header") - ErrUnmarshalUnknownChunkType = errors.New("failed to unmarshal, contains unknown chunk type") - ErrChecksumMismatch = errors.New("checksum mismatch theirs") + errPacketRawTooSmall = errors.New("raw is smaller than the minimum length for a SCTP packet") + errParseSCTPChunkNotEnoughData = errors.New("unable to parse SCTP chunk, not enough data for complete header") + errUnmarshalUnknownChunkType = errors.New("failed to unmarshal, contains unknown chunk type") + errChecksumMismatch = errors.New("checksum mismatch theirs") ) func (p *packet) unmarshal(raw []byte) error { if len(raw) < packetHeaderSize { - return fmt.Errorf("%w: raw only %d bytes, %d is the minimum length", ErrPacketRawTooSmall, len(raw), packetHeaderSize) + return fmt.Errorf("%w: raw only %d bytes, %d is the minimum length", errPacketRawTooSmall, len(raw), packetHeaderSize) } p.sourcePort = binary.BigEndian.Uint16(raw[0:]) @@ -77,7 +81,7 @@ func (p *packet) unmarshal(raw []byte) error { if offset == len(raw) { break } else if offset+chunkHeaderSize > len(raw) { - return fmt.Errorf("%w: offset %d remaining %d", ErrParseSCTPChunkNotEnoughData, offset, len(raw)) + return fmt.Errorf("%w: offset %d remaining %d", errParseSCTPChunkNotEnoughData, offset, len(raw)) } var c chunk @@ -111,7 +115,7 @@ func (p *packet) unmarshal(raw []byte) error { case ctShutdownComplete: c = &chunkShutdownComplete{} default: - return fmt.Errorf("%w: %s", ErrUnmarshalUnknownChunkType, chunkType(raw[offset]).String()) + return fmt.Errorf("%w: %s", errUnmarshalUnknownChunkType, chunkType(raw[offset]).String()) } if err := c.unmarshal(raw[offset:]); err != nil { @@ -125,7 +129,7 @@ func (p *packet) unmarshal(raw []byte) error { theirChecksum := binary.LittleEndian.Uint32(raw[8:]) ourChecksum := generatePacketChecksum(raw) if theirChecksum != ourChecksum { - return fmt.Errorf("%w: %d ours: %d", ErrChecksumMismatch, theirChecksum, ourChecksum) + return fmt.Errorf("%w: %d ours: %d", errChecksumMismatch, theirChecksum, ourChecksum) } return nil } diff --git a/vendor/github.com/pion/sctp/param.go b/vendor/github.com/pion/sctp/param.go index a23935341..b7887c5bd 100644 --- a/vendor/github.com/pion/sctp/param.go +++ b/vendor/github.com/pion/sctp/param.go @@ -10,8 +10,7 @@ type param interface { length() int } -// ErrParamTypeUnhandled is returned if unknown parameter type is specified. -var ErrParamTypeUnhandled = errors.New("unhandled ParamType") +var errParamTypeUnhandled = errors.New("unhandled ParamType") func buildParam(t paramType, rawParam []byte) (param, error) { switch t { @@ -36,6 +35,6 @@ func buildParam(t paramType, rawParam []byte) (param, error) { case reconfigResp: return (¶mReconfigResponse{}).unmarshal(rawParam) default: - return nil, fmt.Errorf("%w: %v", ErrParamTypeUnhandled, t) + return nil, fmt.Errorf("%w: %v", errParamTypeUnhandled, t) } } diff --git a/vendor/github.com/pion/sctp/param_outgoing_reset_request.go b/vendor/github.com/pion/sctp/param_outgoing_reset_request.go index 8ec0bf6cc..ceae17892 100644 --- a/vendor/github.com/pion/sctp/param_outgoing_reset_request.go +++ b/vendor/github.com/pion/sctp/param_outgoing_reset_request.go @@ -52,10 +52,7 @@ type paramOutgoingResetRequest struct { streamIdentifiers []uint16 } -// Outgoing reset request parameter errors -var ( - ErrSSNResetRequestParamTooShort = errors.New("outgoing SSN reset request parameter too short") -) +var errSSNResetRequestParamTooShort = errors.New("outgoing SSN reset request parameter too short") func (r *paramOutgoingResetRequest) marshal() ([]byte, error) { r.typ = outSSNResetReq @@ -75,7 +72,7 @@ func (r *paramOutgoingResetRequest) unmarshal(raw []byte) (param, error) { return nil, err } if len(r.raw) < paramOutgoingResetRequestStreamIdentifiersOffset { - return nil, ErrSSNResetRequestParamTooShort + return nil, errSSNResetRequestParamTooShort } r.reconfigRequestSequenceNumber = binary.BigEndian.Uint32(r.raw) r.reconfigResponseSequenceNumber = binary.BigEndian.Uint32(r.raw[4:]) diff --git a/vendor/github.com/pion/sctp/param_reconfig_response.go b/vendor/github.com/pion/sctp/param_reconfig_response.go index e3bfab5a4..d9eab5512 100644 --- a/vendor/github.com/pion/sctp/param_reconfig_response.go +++ b/vendor/github.com/pion/sctp/param_reconfig_response.go @@ -45,10 +45,7 @@ const ( reconfigResultInProgress reconfigResult = 6 ) -// Reconfiguration response errors -var ( - ErrReconfigRespParamTooShort = errors.New("reconfig response parameter too short") -) +var errReconfigRespParamTooShort = errors.New("reconfig response parameter too short") func (t reconfigResult) String() string { switch t { @@ -86,7 +83,7 @@ func (r *paramReconfigResponse) unmarshal(raw []byte) (param, error) { return nil, err } if len(r.raw) < 8 { - return nil, ErrReconfigRespParamTooShort + return nil, errReconfigRespParamTooShort } r.reconfigResponseSequenceNumber = binary.BigEndian.Uint32(r.raw) r.result = reconfigResult(binary.BigEndian.Uint32(r.raw[4:])) diff --git a/vendor/github.com/pion/sctp/param_requested_hmac_algorithm.go b/vendor/github.com/pion/sctp/param_requested_hmac_algorithm.go index d546af88a..895f3d75a 100644 --- a/vendor/github.com/pion/sctp/param_requested_hmac_algorithm.go +++ b/vendor/github.com/pion/sctp/param_requested_hmac_algorithm.go @@ -15,8 +15,7 @@ const ( hmacSHA256 hmacAlgorithm = 3 ) -// ErrInvalidAlgorithmType is returned if unknown auth algorithm is specified. -var ErrInvalidAlgorithmType = errors.New("invalid algorithm type") +var errInvalidAlgorithmType = errors.New("invalid algorithm type") func (c hmacAlgorithm) String() string { switch c { @@ -65,7 +64,7 @@ func (r *paramRequestedHMACAlgorithm) unmarshal(raw []byte) (param, error) { case hmacSHA256: r.availableAlgorithms = append(r.availableAlgorithms, a) default: - return nil, fmt.Errorf("%w: %v", ErrInvalidAlgorithmType, a) + return nil, fmt.Errorf("%w: %v", errInvalidAlgorithmType, a) } i += 2 diff --git a/vendor/github.com/pion/sctp/paramheader.go b/vendor/github.com/pion/sctp/paramheader.go index f3cbf74ca..f814d461f 100644 --- a/vendor/github.com/pion/sctp/paramheader.go +++ b/vendor/github.com/pion/sctp/paramheader.go @@ -17,12 +17,11 @@ const ( paramHeaderLength = 4 ) -// Parameter header parse errors var ( - ErrParamHeaderTooShort = errors.New("param header too short") - ErrParamHeaderSelfReportedLengthShorter = errors.New("param self reported length is shorter than header length") - ErrParamHeaderSelfReportedLengthLonger = errors.New("param self reported length is longer than header length") - ErrParamHeaderParseFailed = errors.New("failed to parse param type") + errParamHeaderTooShort = errors.New("param header too short") + errParamHeaderSelfReportedLengthShorter = errors.New("param self reported length is shorter than header length") + errParamHeaderSelfReportedLengthLonger = errors.New("param self reported length is longer than header length") + errParamHeaderParseFailed = errors.New("failed to parse param type") ) func (p *paramHeader) marshal() ([]byte, error) { @@ -38,20 +37,20 @@ func (p *paramHeader) marshal() ([]byte, error) { func (p *paramHeader) unmarshal(raw []byte) error { if len(raw) < paramHeaderLength { - return ErrParamHeaderTooShort + return errParamHeaderTooShort } paramLengthPlusHeader := binary.BigEndian.Uint16(raw[2:]) if int(paramLengthPlusHeader) < paramHeaderLength { - return fmt.Errorf("%w: param self reported length (%d) shorter than header length (%d)", ErrParamHeaderSelfReportedLengthShorter, int(paramLengthPlusHeader), paramHeaderLength) + return fmt.Errorf("%w: param self reported length (%d) shorter than header length (%d)", errParamHeaderSelfReportedLengthShorter, int(paramLengthPlusHeader), paramHeaderLength) } if len(raw) < int(paramLengthPlusHeader) { - return fmt.Errorf("%w: param length (%d) shorter than its self reported length (%d)", ErrParamHeaderSelfReportedLengthLonger, len(raw), int(paramLengthPlusHeader)) + return fmt.Errorf("%w: param length (%d) shorter than its self reported length (%d)", errParamHeaderSelfReportedLengthLonger, len(raw), int(paramLengthPlusHeader)) } typ, err := parseParamType(raw[0:]) if err != nil { - return fmt.Errorf("%w: %v", ErrParamHeaderParseFailed, err) //nolint:errorlint + return fmt.Errorf("%w: %v", errParamHeaderParseFailed, err) } p.typ = typ p.raw = raw[paramHeaderLength:paramLengthPlusHeader] diff --git a/vendor/github.com/pion/sctp/paramtype.go b/vendor/github.com/pion/sctp/paramtype.go index 2db73ddec..9fe2cf14c 100644 --- a/vendor/github.com/pion/sctp/paramtype.go +++ b/vendor/github.com/pion/sctp/paramtype.go @@ -39,14 +39,11 @@ const ( adaptLayerInd paramType = 49158 // Adaptation Layer Indication (0xC006) [RFC5061] ) -// Parameter packet errors -var ( - ErrParamPacketTooShort = errors.New("packet to short") -) +var errParamPacketTooShort = errors.New("packet to short") func parseParamType(raw []byte) (paramType, error) { if len(raw) < 2 { - return paramType(0), ErrParamPacketTooShort + return paramType(0), errParamPacketTooShort } return paramType(binary.BigEndian.Uint16(raw)), nil } diff --git a/vendor/github.com/pion/sctp/pending_queue.go b/vendor/github.com/pion/sctp/pending_queue.go index 8082cf52f..a6e1a7a55 100644 --- a/vendor/github.com/pion/sctp/pending_queue.go +++ b/vendor/github.com/pion/sctp/pending_queue.go @@ -48,11 +48,10 @@ type pendingQueue struct { unorderedIsSelected bool } -// Pending queue errors var ( - ErrUnexpectedChuckPoppedUnordered = errors.New("unexpected chunk popped (unordered)") - ErrUnexpectedChuckPoppedOrdered = errors.New("unexpected chunk popped (ordered)") - ErrUnexpectedQState = errors.New("unexpected q state (should've been selected)") + errUnexpectedChuckPoppedUnordered = errors.New("unexpected chunk popped (unordered)") + errUnexpectedChuckPoppedOrdered = errors.New("unexpected chunk popped (ordered)") + errUnexpectedQState = errors.New("unexpected q state (should've been selected)") ) func newPendingQueue() *pendingQueue { @@ -91,12 +90,12 @@ func (q *pendingQueue) pop(c *chunkPayloadData) error { if q.unorderedIsSelected { popped = q.unorderedQueue.pop() if popped != c { - return ErrUnexpectedChuckPoppedUnordered + return errUnexpectedChuckPoppedUnordered } } else { popped = q.orderedQueue.pop() if popped != c { - return ErrUnexpectedChuckPoppedOrdered + return errUnexpectedChuckPoppedOrdered } } if popped.endingFragment { @@ -104,12 +103,12 @@ func (q *pendingQueue) pop(c *chunkPayloadData) error { } } else { if !c.beginningFragment { - return ErrUnexpectedQState + return errUnexpectedQState } if c.unordered { popped := q.unorderedQueue.pop() if popped != c { - return ErrUnexpectedChuckPoppedUnordered + return errUnexpectedChuckPoppedUnordered } if !popped.endingFragment { q.selected = true @@ -118,7 +117,7 @@ func (q *pendingQueue) pop(c *chunkPayloadData) error { } else { popped := q.orderedQueue.pop() if popped != c { - return ErrUnexpectedChuckPoppedOrdered + return errUnexpectedChuckPoppedOrdered } if !popped.endingFragment { q.selected = true diff --git a/vendor/github.com/pion/sctp/renovate.json b/vendor/github.com/pion/sctp/renovate.json index f1bb98c6a..f1614058a 100644 --- a/vendor/github.com/pion/sctp/renovate.json +++ b/vendor/github.com/pion/sctp/renovate.json @@ -1,6 +1,27 @@ { - "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ - "github>pion/renovate-config" + "config:base", + ":disableDependencyDashboard" + ], + "postUpdateOptions": [ + "gomodTidy" + ], + "commitBody": "Generated by renovateBot", + "packageRules": [ + { + "matchUpdateTypes": ["minor", "patch", "pin", "digest"], + "automerge": true + }, + { + "packagePatterns": ["^golang.org/x/"], + "schedule": ["on the first day of the month"] + } + ], + "ignorePaths": [ + ".github/workflows/generate-authors.yml", + ".github/workflows/lint.yaml", + ".github/workflows/renovate-go-mod-fix.yaml", + ".github/workflows/test.yaml", + ".github/workflows/tidy-check.yaml" ] } diff --git a/vendor/github.com/pion/sctp/stream.go b/vendor/github.com/pion/sctp/stream.go index 43038ee1e..58041b1f4 100644 --- a/vendor/github.com/pion/sctp/stream.go +++ b/vendor/github.com/pion/sctp/stream.go @@ -5,10 +5,8 @@ import ( "fmt" "io" "math" - "os" "sync" "sync/atomic" - "time" "github.com/pion/logging" ) @@ -22,34 +20,9 @@ const ( ReliabilityTypeTimed byte = 2 ) -// StreamState is an enum for SCTP Stream state field -// This field identifies the state of stream. -type StreamState int - -// StreamState enums -const ( - StreamStateOpen StreamState = iota // Stream object starts with StreamStateOpen - StreamStateClosing // Outgoing stream is being reset - StreamStateClosed // Stream has been closed -) - -func (ss StreamState) String() string { - switch ss { - case StreamStateOpen: - return "open" - case StreamStateClosing: - return "closing" - case StreamStateClosed: - return "closed" - } - return "unknown" -} - -// SCTP stream errors var ( - ErrOutboundPacketTooLarge = errors.New("outbound packet larger than maximum message size") - ErrStreamClosed = errors.New("stream closed") - ErrReadDeadlineExceeded = fmt.Errorf("read deadline exceeded: %w", os.ErrDeadlineExceeded) + errOutboundPacketTooLarge = errors.New("outbound packet larger than maximum message size") + errStreamClosed = errors.New("Stream closed") ) // Stream represents an SCTP stream @@ -62,14 +35,13 @@ type Stream struct { sequenceNumber uint16 readNotifier *sync.Cond readErr error - readTimeoutCancel chan struct{} + writeErr error unordered bool reliabilityType byte reliabilityValue uint32 bufferedAmount uint64 bufferedAmountLow uint64 onBufferedAmountLow func() - state StreamState log logging.LeveledLogger name string } @@ -120,14 +92,6 @@ func (s *Stream) ReadSCTP(p []byte) (int, PayloadProtocolIdentifier, error) { s.lock.Lock() defer s.lock.Unlock() - defer func() { - // close readTimeoutCancel if the current read timeout routine is no longer effective - if s.readTimeoutCancel != nil && s.readErr != nil { - close(s.readTimeoutCancel) - s.readTimeoutCancel = nil - } - }() - for { n, ppi, err := s.reassemblyQueue.read(p) if err == nil { @@ -145,47 +109,6 @@ func (s *Stream) ReadSCTP(p []byte) (int, PayloadProtocolIdentifier, error) { } } -// SetReadDeadline sets the read deadline in an identical way to net.Conn -func (s *Stream) SetReadDeadline(deadline time.Time) error { - s.lock.Lock() - defer s.lock.Unlock() - - if s.readTimeoutCancel != nil { - close(s.readTimeoutCancel) - s.readTimeoutCancel = nil - } - - if s.readErr != nil { - if !errors.Is(s.readErr, ErrReadDeadlineExceeded) { - return nil - } - s.readErr = nil - } - - if !deadline.IsZero() { - s.readTimeoutCancel = make(chan struct{}) - - go func(readTimeoutCancel chan struct{}) { - t := time.NewTimer(time.Until(deadline)) - select { - case <-readTimeoutCancel: - t.Stop() - return - case <-t.C: - s.lock.Lock() - if s.readErr == nil { - s.readErr = ErrReadDeadlineExceeded - } - s.readTimeoutCancel = nil - s.lock.Unlock() - - s.readNotifier.Signal() - } - }(s.readTimeoutCancel) - } - return nil -} - func (s *Stream) handleData(pd *chunkPayloadData) { s.lock.Lock() defer s.lock.Unlock() @@ -255,23 +178,32 @@ func (s *Stream) Write(p []byte) (n int, err error) { } // WriteSCTP writes len(p) bytes from p to the DTLS connection -func (s *Stream) WriteSCTP(p []byte, ppi PayloadProtocolIdentifier) (int, error) { +func (s *Stream) WriteSCTP(p []byte, ppi PayloadProtocolIdentifier) (n int, err error) { maxMessageSize := s.association.MaxMessageSize() if len(p) > int(maxMessageSize) { - return 0, fmt.Errorf("%w: %v", ErrOutboundPacketTooLarge, math.MaxUint16) + return 0, fmt.Errorf("%w: %v", errOutboundPacketTooLarge, math.MaxUint16) } - if s.State() != StreamStateOpen { - return 0, ErrStreamClosed + switch s.association.getState() { + case shutdownSent, shutdownAckSent, shutdownPending, shutdownReceived: + s.lock.Lock() + if s.writeErr == nil { + s.writeErr = errStreamClosed + } + s.lock.Unlock() + default: + } + + s.lock.RLock() + err = s.writeErr + s.lock.RUnlock() + if err != nil { + return 0, err } chunks := s.packetize(p, ppi) - n := len(p) - err := s.association.sendPayloadData(chunks) - if err != nil { - return n, ErrStreamClosed - } - return n, nil + + return len(p), s.association.sendPayloadData(chunks) } func (s *Stream) packetize(raw []byte, ppi PayloadProtocolIdentifier) []*chunkPayloadData { @@ -335,23 +267,26 @@ func (s *Stream) packetize(raw []byte, ppi PayloadProtocolIdentifier) []*chunkPa // Close closes the write-direction of the stream. // Future calls to Write are not permitted after calling Close. func (s *Stream) Close() error { - if sid, resetOutbound := func() (uint16, bool) { + if sid, isOpen := func() (uint16, bool) { s.lock.Lock() defer s.lock.Unlock() - s.log.Debugf("[%s] Close: state=%s", s.name, s.state.String()) - - if s.state == StreamStateOpen { - if s.readErr == nil { - s.state = StreamStateClosing - } else { - s.state = StreamStateClosed - } - s.log.Debugf("[%s] state change: open => %s", s.name, s.state.String()) - return s.streamIdentifier, true + isOpen := true + if s.writeErr == nil { + s.writeErr = errStreamClosed + } else { + isOpen = false } - return s.streamIdentifier, false - }(); resetOutbound { + + if s.readErr == nil { + s.readErr = io.EOF + } else { + isOpen = false + } + s.readNotifier.Broadcast() // broadcast regardless + + return s.streamIdentifier, isOpen + }(); isOpen { // Reset the outgoing stream // https://tools.ietf.org/html/rfc6525 return s.association.sendResetRequest(sid) @@ -430,35 +365,3 @@ func (s *Stream) getNumBytesInReassemblyQueue() int { // No lock is required as it reads the size with atomic load function. return s.reassemblyQueue.getNumBytes() } - -func (s *Stream) onInboundStreamReset() { - s.lock.Lock() - defer s.lock.Unlock() - - s.log.Debugf("[%s] onInboundStreamReset: state=%s", s.name, s.state.String()) - - // No more inbound data to read. Unblock the read with io.EOF. - // This should cause DCEP layer (datachannel package) to call Close() which - // will reset outgoing stream also. - - // See RFC 8831 section 6.7: - // if one side decides to close the data channel, it resets the corresponding - // outgoing stream. When the peer sees that an incoming stream was - // reset, it also resets its corresponding outgoing stream. Once this - // is completed, the data channel is closed. - - s.readErr = io.EOF - s.readNotifier.Broadcast() - - if s.state == StreamStateClosing { - s.log.Debugf("[%s] state change: closing => closed", s.name) - s.state = StreamStateClosed - } -} - -// State return the stream state. -func (s *Stream) State() StreamState { - s.lock.RLock() - defer s.lock.RUnlock() - return s.state -} diff --git a/vendor/github.com/pion/sctp/util.go b/vendor/github.com/pion/sctp/util.go index 9302e7126..e2e54ab0c 100644 --- a/vendor/github.com/pion/sctp/util.go +++ b/vendor/github.com/pion/sctp/util.go @@ -4,8 +4,8 @@ const ( paddingMultiple = 4 ) -func getPadding(l int) int { - return (paddingMultiple - (l % paddingMultiple)) % paddingMultiple +func getPadding(len int) int { + return (paddingMultiple - (len % paddingMultiple)) % paddingMultiple } func padByte(in []byte, cnt int) []byte { diff --git a/vendor/github.com/pion/sdp/v3/.gitignore b/vendor/github.com/pion/sdp/v3/.gitignore index f977e7485..83db74ba5 100644 --- a/vendor/github.com/pion/sdp/v3/.gitignore +++ b/vendor/github.com/pion/sdp/v3/.gitignore @@ -22,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/sdp/v3/.golangci.yml b/vendor/github.com/pion/sdp/v3/.golangci.yml index d7a88eca3..d6162c970 100644 --- a/vendor/github.com/pion/sdp/v3/.golangci.yml +++ b/vendor/github.com/pion/sdp/v3/.golangci.yml @@ -15,22 +15,14 @@ linters-settings: linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - deadcode # Finds unused code - - decorder # check declaration order and count of types, constants, variables and functions - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -43,62 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - varcheck # Finds unused global variables and constants - - wastedassign # wastedassign finds wasted assignment statements - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - - forbidigo # Forbids identifiers - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: diff --git a/vendor/github.com/pion/sdp/v3/AUTHORS.txt b/vendor/github.com/pion/sdp/v3/AUTHORS.txt deleted file mode 100644 index 038e59911..000000000 --- a/vendor/github.com/pion/sdp/v3/AUTHORS.txt +++ /dev/null @@ -1,32 +0,0 @@ -# Thank you to everyone that made Pion possible. If you are interested in contributing -# we would love to have you https://github.com/pion/webrtc/wiki/Contributing -# -# This file is auto generated, using git to list all individuals contributors. -# see `.github/generate-authors.sh` for the scripting -adwpc -Atsushi Watanabe -backkem -Brendan Abolivier -chenkaiC4 -cnderrauber -Daniele Sluijters -Graham King -Guilherme -Hugo Arregui -Jason -Jerko Steiner -John Bradley -Konstantin Itskov -korymiller1489 -Luke S -Max Hawkins -Maxim Oransky -mchlrhw <4028654+mchlrhw@users.noreply.github.com> -Michael MacDonald -Mustafa Navruz -Roman Romanenko -Sean DuBois -Sean DuBois -tarrencev -Woodrow Douglass -ZHENK diff --git a/vendor/github.com/pion/sdp/v3/README.md b/vendor/github.com/pion/sdp/v3/README.md index c29c97f78..e7d7ff692 100644 --- a/vendor/github.com/pion/sdp/v3/README.md +++ b/vendor/github.com/pion/sdp/v3/README.md @@ -17,6 +17,7 @@


+See [DESIGN.md](DESIGN.md) for an overview of features and future goals. ### Roadmap The library is used as a part of our WebRTC implementation. Please refer to that [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones. @@ -31,5 +32,28 @@ If you need commercial support or don't want to use public methods you can conta ### Contributing Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible: +* [John Bradley](https://github.com/kc5nra) - *Original Author* +* [Sean DuBois](https://github.com/Sean-Der) - *Original Author* +* [Michiel De Backker](https://github.com/backkem) - *Public API, Initialization* +* [Konstantin Itskov](https://github.com/trivigy) - *Fix documentation* +* [chenkaiC4](https://github.com/chenkaiC4) - *Fix GolangCI Linter* +* [Woodrow Douglass](https://github.com/wdouglass) *RTCP, RTP improvements, G.722 support, Bugfixes* +* [Michael MacDonald](https://github.com/mjmac) +* [Max Hawkins](https://github.com/maxhawkins) +* [mchlrhw](https://github.com/mchlrhw) +* [Hugo Arregui](https://github.com/hugoArregui) +* [Guilherme Souza](https://github.com/gqgs) +* [adwpc](https://github.com/adwpc) - *extmap add transport-cc* +* [Atsushi Watanabe](https://github.com/at-wat) +* [Luke S](https://github.com/encounter) +* [Jerko Steiner](https://github.com/jeremija) +* [Roman Romanenko](https://github.com/r-novel) +* [Jason Brady](https://github.com/jbrady42) +* [Kory Miller](https://github.com/jbrady42/korymiller1489) +* [ZHENK](https://github.com/scorpionknifes) +* [Tarrence van As](https://github.com/tarrencev) +* [Maxim Oransky](https://github.com/sdfsdhgjkbmnmxc) +* [Graham King](https://github.com/grahamking/) + ### License MIT License - see [LICENSE](LICENSE) for full text diff --git a/vendor/github.com/pion/sdp/v3/base_lexer.go b/vendor/github.com/pion/sdp/v3/base_lexer.go index f1f2ccd1a..45fe7994b 100644 --- a/vendor/github.com/pion/sdp/v3/base_lexer.go +++ b/vendor/github.com/pion/sdp/v3/base_lexer.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "io" - "strconv" ) var errDocumentStart = errors.New("already on document start") @@ -18,7 +17,8 @@ func (e syntaxError) Error() string { if e.i < 0 { e.i = 0 } - return fmt.Sprintf("sdp: syntax error at pos %d: %s", e.i, strconv.QuoteToASCII(e.s[e.i:e.i+1])) + head, middle, tail := e.s[:e.i], e.s[e.i:e.i+1], e.s[e.i+1:] + return fmt.Sprintf("%s --> %s <-- %s", head, middle, tail) } type baseLexer struct { @@ -50,7 +50,7 @@ func (l *baseLexer) readByte() (byte, error) { func (l *baseLexer) nextLine() error { for { ch, err := l.readByte() - if errors.Is(err, io.EOF) { + if err == io.EOF { return nil } else if err != nil { return err @@ -64,7 +64,7 @@ func (l *baseLexer) nextLine() error { func (l *baseLexer) readWhitespace() error { for { ch, err := l.readByte() - if errors.Is(err, io.EOF) { + if err == io.EOF { return nil } else if err != nil { return err @@ -78,7 +78,7 @@ func (l *baseLexer) readWhitespace() error { func (l *baseLexer) readUint64Field() (i uint64, err error) { for { ch, err := l.readByte() - if errors.Is(err, io.EOF) && i > 0 { + if err == io.EOF && i > 0 { break } else if err != nil { return i, err @@ -130,11 +130,11 @@ func (l *baseLexer) readUint64Field() (i uint64, err error) { // Returns next field on this line or empty string if no more fields on line func (l *baseLexer) readField() (string, error) { start := l.pos - var stop int + stop := start for { stop = l.pos ch, err := l.readByte() - if errors.Is(err, io.EOF) && stop > start { + if err == io.EOF && stop > start { break } else if err != nil { return "", err diff --git a/vendor/github.com/pion/sdp/v3/jsep.go b/vendor/github.com/pion/sdp/v3/jsep.go index de07d8f30..efdef0301 100644 --- a/vendor/github.com/pion/sdp/v3/jsep.go +++ b/vendor/github.com/pion/sdp/v3/jsep.go @@ -9,25 +9,24 @@ import ( // Constants for SDP attributes used in JSEP const ( - AttrKeyCandidate = "candidate" - AttrKeyEndOfCandidates = "end-of-candidates" - AttrKeyIdentity = "identity" - AttrKeyGroup = "group" - AttrKeySSRC = "ssrc" - AttrKeySSRCGroup = "ssrc-group" - AttrKeyMsid = "msid" - AttrKeyMsidSemantic = "msid-semantic" - AttrKeyConnectionSetup = "setup" - AttrKeyMID = "mid" - AttrKeyICELite = "ice-lite" - AttrKeyRTCPMux = "rtcp-mux" - AttrKeyRTCPRsize = "rtcp-rsize" - AttrKeyInactive = "inactive" - AttrKeyRecvOnly = "recvonly" - AttrKeySendOnly = "sendonly" - AttrKeySendRecv = "sendrecv" - AttrKeyExtMap = "extmap" - AttrKeyExtMapAllowMixed = "extmap-allow-mixed" + AttrKeyCandidate = "candidate" + AttrKeyEndOfCandidates = "end-of-candidates" + AttrKeyIdentity = "identity" + AttrKeyGroup = "group" + AttrKeySSRC = "ssrc" + AttrKeySSRCGroup = "ssrc-group" + AttrKeyMsid = "msid" + AttrKeyMsidSemantic = "msid-semantic" + AttrKeyConnectionSetup = "setup" + AttrKeyMID = "mid" + AttrKeyICELite = "ice-lite" + AttrKeyRTCPMux = "rtcp-mux" + AttrKeyRTCPRsize = "rtcp-rsize" + AttrKeyInactive = "inactive" + AttrKeyRecvOnly = "recvonly" + AttrKeySendOnly = "sendonly" + AttrKeySendRecv = "sendrecv" + AttrKeyExtMap = "extmap" ) // Constants for semantic tokens used in JSEP diff --git a/vendor/github.com/pion/sdp/v3/renovate.json b/vendor/github.com/pion/sdp/v3/renovate.json index f1614058a..4400fd9b2 100644 --- a/vendor/github.com/pion/sdp/v3/renovate.json +++ b/vendor/github.com/pion/sdp/v3/renovate.json @@ -1,27 +1,15 @@ { "extends": [ - "config:base", - ":disableDependencyDashboard" + "config:base" ], "postUpdateOptions": [ "gomodTidy" ], "commitBody": "Generated by renovateBot", "packageRules": [ - { - "matchUpdateTypes": ["minor", "patch", "pin", "digest"], - "automerge": true - }, { "packagePatterns": ["^golang.org/x/"], "schedule": ["on the first day of the month"] } - ], - "ignorePaths": [ - ".github/workflows/generate-authors.yml", - ".github/workflows/lint.yaml", - ".github/workflows/renovate-go-mod-fix.yaml", - ".github/workflows/test.yaml", - ".github/workflows/tidy-check.yaml" ] } diff --git a/vendor/github.com/pion/sdp/v3/unmarshal.go b/vendor/github.com/pion/sdp/v3/unmarshal.go index 59fcbe74c..92e0dcf48 100644 --- a/vendor/github.com/pion/sdp/v3/unmarshal.go +++ b/vendor/github.com/pion/sdp/v3/unmarshal.go @@ -568,11 +568,9 @@ func unmarshalBandwidth(value string) (*Bandwidth, error) { experimental := strings.HasPrefix(parts[0], "X-") if experimental { parts[0] = strings.TrimPrefix(parts[0], "X-") - } else if !anyOf(parts[0], "CT", "AS", "TIAS", "RS", "RR") { + } else if !anyOf(parts[0], "CT", "AS") { // Set according to currently registered with IANA // https://tools.ietf.org/html/rfc4566#section-5.8 - // https://tools.ietf.org/html/rfc3890#section-6.2 - // https://tools.ietf.org/html/rfc3556#section-2 return nil, fmt.Errorf("%w `%v`", errSDPInvalidValue, parts[0]) } @@ -769,9 +767,8 @@ func unmarshalMediaDescription(l *lexer) (stateFn, error) { // Set according to currently registered with IANA // https://tools.ietf.org/html/rfc4566#section-5.14 - // https://tools.ietf.org/html/rfc4975#section-8.1 for _, proto := range strings.Split(field, "/") { - if !anyOf(proto, "UDP", "RTP", "AVP", "SAVP", "SAVPF", "TLS", "DTLS", "SCTP", "AVPF", "TCP", "MSRP") { + if !anyOf(proto, "UDP", "RTP", "AVP", "SAVP", "SAVPF", "TLS", "DTLS", "SCTP", "AVPF") { return nil, fmt.Errorf("%w `%v`", errSDPInvalidNumericValue, field) } newMediaDesc.MediaName.Protos = append(newMediaDesc.MediaName.Protos, proto) diff --git a/vendor/github.com/pion/sdp/v3/util.go b/vendor/github.com/pion/sdp/v3/util.go index 84cba7f7d..74f47ed19 100644 --- a/vendor/github.com/pion/sdp/v3/util.go +++ b/vendor/github.com/pion/sdp/v3/util.go @@ -98,7 +98,7 @@ func parseRtpmap(rtpmap string) (Codec, error) { return codec, parsingFailed } - ptInt, err := strconv.ParseUint(ptSplit[1], 10, 8) + ptInt, err := strconv.Atoi(ptSplit[1]) if err != nil { return codec, parsingFailed } @@ -109,7 +109,7 @@ func parseRtpmap(rtpmap string) (Codec, error) { codec.Name = split[0] parts := len(split) if parts > 1 { - rate, err := strconv.ParseUint(split[1], 10, 32) + rate, err := strconv.Atoi(split[1]) if err != nil { return codec, parsingFailed } @@ -139,7 +139,7 @@ func parseFmtp(fmtp string) (Codec, error) { return codec, parsingFailed } - ptInt, err := strconv.ParseUint(split[1], 10, 8) + ptInt, err := strconv.Atoi(split[1]) if err != nil { return codec, parsingFailed } @@ -165,7 +165,7 @@ func parseRtcpFb(rtcpFb string) (Codec, error) { return codec, parsingFailed } - ptInt, err := strconv.ParseUint(ptSplit[1], 10, 8) + ptInt, err := strconv.Atoi(ptSplit[1]) if err != nil { return codec, parsingFailed } @@ -304,8 +304,8 @@ type keyToState func(key string) stateFn func (l *lexer) handleType(fn keyToState) (stateFn, error) { key, err := l.readType() - if errors.Is(err, io.EOF) && key == "" { - return nil, nil //nolint:nilnil + if err == io.EOF && key == "" { + return nil, nil } else if err != nil { return nil, err } diff --git a/vendor/github.com/pion/srtp/v2/.gitignore b/vendor/github.com/pion/srtp/v2/.gitignore index 6e2f206a9..83db74ba5 100644 --- a/vendor/github.com/pion/srtp/v2/.gitignore +++ b/vendor/github.com/pion/srtp/v2/.gitignore @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - ### JetBrains IDE ### ##################### .idea/ @@ -25,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/srtp/v2/.golangci.yml b/vendor/github.com/pion/srtp/v2/.golangci.yml index 4e3eddf42..d6162c970 100644 --- a/vendor/github.com/pion/srtp/v2/.golangci.yml +++ b/vendor/github.com/pion/srtp/v2/.golangci.yml @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - linters-settings: govet: check-shadowing: true @@ -13,34 +10,19 @@ linters-settings: modules: - github.com/pkg/errors: recommendations: - - errors - forbidigo: - forbid: - - ^fmt.Print(f|ln)?$ - - ^log.(Panic|Fatal|Print)(f|ln)?$ - - ^os.Exit$ - - ^panic$ - - ^print(ln)?$ + - errors linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - - decorder # check declaration order and count of types, constants, variables and functions + - deadcode # Finds unused code - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forbidigo # Forbids identifiers - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -53,59 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks + - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - - wastedassign # wastedassign finds wasted assignment statements + - varcheck # Finds unused global variables and constants - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: @@ -115,23 +78,12 @@ issues: - path: _test\.go linters: - gocognit - - forbidigo # Allow complex main function in examples - path: examples text: "of func `main` is high" linters: - gocognit - - # Allow forbidden identifiers in examples - - path: examples - linters: - - forbidigo - - # Allow forbidden identifiers in CLI commands - - path: cmd - linters: - - forbidigo run: skip-dirs-use-default: false diff --git a/vendor/github.com/pion/srtp/v2/.goreleaser.yml b/vendor/github.com/pion/srtp/v2/.goreleaser.yml deleted file mode 100644 index 30093e9d6..000000000 --- a/vendor/github.com/pion/srtp/v2/.goreleaser.yml +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - -builds: -- skip: true diff --git a/vendor/github.com/pion/srtp/v2/AUTHORS.txt b/vendor/github.com/pion/srtp/v2/AUTHORS.txt index daca101e1..03ce53e92 100644 --- a/vendor/github.com/pion/srtp/v2/AUTHORS.txt +++ b/vendor/github.com/pion/srtp/v2/AUTHORS.txt @@ -2,11 +2,7 @@ # we would love to have you https://github.com/pion/webrtc/wiki/Contributing # # This file is auto generated, using git to list all individuals contributors. -# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting -adamroach -Adrian Cable -Agniva De Sarker -Antoine Baché +# see `.github/generate-authors.sh` for the scripting Atsushi Watanabe backkem chenkaiC4 @@ -21,16 +17,8 @@ Max Hawkins mission-liao Novel Corpse OrlandoCo -Patryk -Patryk Rogalski Sean DuBois Sean DuBois -SeongGyu Park -Steffen -Steffen Vogel Tobias Fridén Woodrow Douglass Yutaka Takeda - -# List of contributors not appearing in Git history - diff --git a/vendor/github.com/pion/srtp/v2/DESIGN.md b/vendor/github.com/pion/srtp/v2/DESIGN.md new file mode 100644 index 000000000..8742540df --- /dev/null +++ b/vendor/github.com/pion/srtp/v2/DESIGN.md @@ -0,0 +1,20 @@ +

+ Design +

+ +### Portable +Pion SRTP is written in Go and extremely portable. Anywhere Golang runs, Pion SRTP should work as well! Instead of dealing with complicated +cross-compiling of multiple libraries, you now can run anywhere with one `go build` + +### Simple API +The API is based on an io.ReadWriteCloser. + +### Readable +If code comes from an RFC we try to make sure everything is commented with a link to the spec. +This makes learning and debugging easier, this library was written to also serve as a guide for others. + +### Tested +Every commit is tested via travis-ci Go provides fantastic facilities for testing, and more will be added as time goes on. + +### Shared libraries +Every pion product is built using shared libraries, allowing others to review and reuse our libraries. diff --git a/vendor/github.com/pion/srtp/v2/LICENSE b/vendor/github.com/pion/srtp/v2/LICENSE index 491caf6b0..ab602974d 100644 --- a/vendor/github.com/pion/srtp/v2/LICENSE +++ b/vendor/github.com/pion/srtp/v2/LICENSE @@ -1,9 +1,21 @@ MIT License -Copyright (c) 2023 The Pion community +Copyright (c) 2018 -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/pion/srtp/v2/README.md b/vendor/github.com/pion/srtp/v2/README.md index d0e94e7a9..55685b767 100644 --- a/vendor/github.com/pion/srtp/v2/README.md +++ b/vendor/github.com/pion/srtp/v2/README.md @@ -9,27 +9,28 @@ Sourcegraph Widget Slack Widget
- GitHub Workflow Status - Go Reference + Build Status + GoDoc Coverage Status Go Report Card License: MIT


+See [DESIGN.md](DESIGN.md) for an overview of features and future goals. + ### Roadmap The library is used as a part of our WebRTC implementation. Please refer to that [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones. ### Community -Pion has an active community on the [Slack](https://pion.ly/slack). - -Follow the [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news. +Pion has an active community on the [Golang Slack](https://invite.slack.golangbridge.org/). Sign up and join the **#pion** channel for discussions and support. You can also use [Pion mailing list](https://groups.google.com/forum/#!forum/pion). We are always looking to support **your projects**. Please reach out if you have something to build! + If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly) ### Contributing -Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible: [AUTHORS.txt](./AUTHORS.txt) +Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible: ### License MIT License - see [LICENSE](LICENSE) for full text diff --git a/vendor/github.com/pion/srtp/v2/codecov.yml b/vendor/github.com/pion/srtp/v2/codecov.yml index 263e4d45c..085200a48 100644 --- a/vendor/github.com/pion/srtp/v2/codecov.yml +++ b/vendor/github.com/pion/srtp/v2/codecov.yml @@ -3,8 +3,6 @@ # # It is automatically copied from https://github.com/pion/.goassets repository. # -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT coverage: status: diff --git a/vendor/github.com/pion/srtp/v2/context.go b/vendor/github.com/pion/srtp/v2/context.go index 27da02cfd..3e778814a 100644 --- a/vendor/github.com/pion/srtp/v2/context.go +++ b/vendor/github.com/pion/srtp/v2/context.go @@ -1,12 +1,9 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( "fmt" - "github.com/pion/transport/v2/replaydetector" + "github.com/pion/transport/replaydetector" ) const ( @@ -19,7 +16,6 @@ const ( labelSRTCPSalt = 0x05 maxSequenceNumber = 65535 - maxROC = (1 << 32) - 1 seqNumMedian = 1 << 15 seqNumMax = 1 << 16 @@ -30,8 +26,8 @@ const ( // Encrypt/Decrypt state for a single SRTP SSRC type srtpSSRCState struct { ssrc uint32 - rolloverHasProcessed bool index uint64 + rolloverHasProcessed bool replayDetector replaydetector.ReplayDetector } @@ -45,9 +41,6 @@ type srtcpSSRCState struct { // Context represents a SRTP cryptographic context. // Context can only be used for one-way operations. // it must either used ONLY for encryption or ONLY for decryption. -// Note that Context does not provide any concurrency protection: -// access to a Context from multiple goroutines requires external -// synchronization. type Context struct { cipher srtpCipher @@ -64,7 +57,8 @@ type Context struct { // Passing multiple options which set the same parameter let the last one valid. // Following example create SRTP Context with replay protection with window size of 256. // -// decCtx, err := srtp.CreateContext(key, salt, profile, srtp.SRTPReplayProtection(256)) +// decCtx, err := srtp.CreateContext(key, salt, profile, srtp.SRTPReplayProtection(256)) +// func CreateContext(masterKey, masterSalt []byte, profile ProtectionProfile, opts ...ContextOption) (c *Context, err error) { keyLen, err := profile.keyLen() if err != nil { @@ -88,10 +82,10 @@ func CreateContext(masterKey, masterSalt []byte, profile ProtectionProfile, opts } switch profile { - case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm: - c.cipher, err = newSrtpCipherAeadAesGcm(profile, masterKey, masterSalt) - case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80: - c.cipher, err = newSrtpCipherAesCmHmacSha1(profile, masterKey, masterSalt) + case ProtectionProfileAeadAes128Gcm: + c.cipher, err = newSrtpCipherAeadAesGcm(masterKey, masterSalt) + case ProtectionProfileAes128CmHmacSha1_80: + c.cipher, err = newSrtpCipherAesCmHmacSha1(masterKey, masterSalt) default: return nil, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, profile) } @@ -115,13 +109,13 @@ func CreateContext(masterKey, masterSalt []byte, profile ProtectionProfile, opts } // https://tools.ietf.org/html/rfc3550#appendix-A.1 -func (s *srtpSSRCState) nextRolloverCount(sequenceNumber uint16) (roc uint32, diff int32, overflow bool) { +func (s *srtpSSRCState) nextRolloverCount(sequenceNumber uint16) (uint32, func()) { seq := int32(sequenceNumber) localRoc := uint32(s.index >> 16) localSeq := int32(s.index & (seqNumMax - 1)) guessRoc := localRoc - var difference int32 + var difference int32 = 0 if s.rolloverHasProcessed { // When localROC is equal to 0, and entering seq-localSeq > seqNumMedian @@ -150,17 +144,15 @@ func (s *srtpSSRCState) nextRolloverCount(sequenceNumber uint16) (roc uint32, di } } - return guessRoc, difference, (guessRoc == 0 && localRoc == maxROC) -} - -func (s *srtpSSRCState) updateRolloverCount(sequenceNumber uint16, difference int32) { - if !s.rolloverHasProcessed { - s.index |= uint64(sequenceNumber) - s.rolloverHasProcessed = true - return - } - if difference > 0 { - s.index += uint64(difference) + return guessRoc, func() { + if !s.rolloverHasProcessed { + s.index |= uint64(sequenceNumber) + s.rolloverHasProcessed = true + return + } + if difference > 0 { + s.index += uint64(difference) + } } } @@ -204,8 +196,7 @@ func (c *Context) ROC(ssrc uint32) (uint32, bool) { // SetROC sets SRTP rollover counter value of specified SSRC. func (c *Context) SetROC(ssrc uint32, roc uint32) { s := c.getSRTPSSRCState(ssrc) - s.index = uint64(roc) << 16 - s.rolloverHasProcessed = false + s.index = uint64(roc<<16) | (s.index & (seqNumMax - 1)) } // Index returns SRTCP index value of specified SSRC. diff --git a/vendor/github.com/pion/srtp/v2/crypto.go b/vendor/github.com/pion/srtp/v2/crypto.go deleted file mode 100644 index 9696e8f2c..000000000 --- a/vendor/github.com/pion/srtp/v2/crypto.go +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package srtp - -import ( - "crypto/cipher" - - "github.com/pion/transport/v2/utils/xor" -) - -// incrementCTR increments a big-endian integer of arbitrary size. -func incrementCTR(ctr []byte) { - for i := len(ctr) - 1; i >= 0; i-- { - ctr[i]++ - if ctr[i] != 0 { - break - } - } -} - -// xorBytesCTR performs CTR encryption and decryption. -// It is equivalent to cipher.NewCTR followed by XORKeyStream. -func xorBytesCTR(block cipher.Block, iv []byte, dst, src []byte) error { - if len(iv) != block.BlockSize() { - return errBadIVLength - } - - ctr := make([]byte, len(iv)) - copy(ctr, iv) - bs := block.BlockSize() - stream := make([]byte, bs) - - i := 0 - for i < len(src) { - block.Encrypt(stream, ctr) - incrementCTR(ctr) - n := xor.XorBytes(dst[i:], src[i:], stream) - if n == 0 { - break - } - i += n - } - return nil -} diff --git a/vendor/github.com/pion/srtp/v2/errors.go b/vendor/github.com/pion/srtp/v2/errors.go index 5b1751d30..a70262145 100644 --- a/vendor/github.com/pion/srtp/v2/errors.go +++ b/vendor/github.com/pion/srtp/v2/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( @@ -21,8 +18,6 @@ var ( errTooShortRTCP = errors.New("packet is too short to be rtcp packet") errPayloadDiffers = errors.New("payload differs") errStartedChannelUsedIncorrectly = errors.New("started channel used incorrectly, should only be closed") - errBadIVLength = errors.New("bad iv length in xorBytesCTR") - errExceededMaxPackets = errors.New("exceeded the maximum number of packets") errStreamNotInited = errors.New("stream has not been inited, unable to close") errStreamAlreadyClosed = errors.New("stream is already closed") @@ -30,16 +25,16 @@ var ( errFailedTypeAssertion = errors.New("failed to cast child") ) -type duplicatedError struct { +type errorDuplicated struct { Proto string // srtp or srtcp SSRC uint32 Index uint32 // sequence number or index } -func (e *duplicatedError) Error() string { +func (e *errorDuplicated) Error() string { return fmt.Sprintf("%s ssrc=%d index=%d: %v", e.Proto, e.SSRC, e.Index, errDuplicated) } -func (e *duplicatedError) Unwrap() error { +func (e *errorDuplicated) Unwrap() error { return errDuplicated } diff --git a/vendor/github.com/pion/srtp/v2/key_derivation.go b/vendor/github.com/pion/srtp/v2/key_derivation.go index 05f0f29fa..5bbf3aaad 100644 --- a/vendor/github.com/pion/srtp/v2/key_derivation.go +++ b/vendor/github.com/pion/srtp/v2/key_derivation.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( @@ -22,7 +19,7 @@ func aesCmKeyDerivation(label byte, masterKey, masterSalt []byte, indexOverKdr i nMasterKey := len(masterKey) nMasterSalt := len(masterSalt) - prfIn := make([]byte, 16) + prfIn := make([]byte, nMasterKey) copy(prfIn[:nMasterSalt], masterSalt) prfIn[7] ^= label @@ -35,8 +32,8 @@ func aesCmKeyDerivation(label byte, masterKey, masterSalt []byte, indexOverKdr i out := make([]byte, ((outLen+nMasterKey)/nMasterKey)*nMasterKey) var i uint16 - for n := 0; n < outLen; n += block.BlockSize() { - binary.BigEndian.PutUint16(prfIn[len(prfIn)-2:], i) + for n := 0; n < outLen; n += nMasterKey { + binary.BigEndian.PutUint16(prfIn[nMasterKey-2:], i) block.Encrypt(out[n:n+nMasterKey], prfIn) i++ } @@ -51,19 +48,16 @@ func aesCmKeyDerivation(label byte, masterKey, masterSalt []byte, indexOverKdr i // - passing through 65,535 // i = 2^16 * ROC + SEQ // IV = (salt*2 ^ 16) | (ssrc*2 ^ 64) | (i*2 ^ 16) -func generateCounter(sequenceNumber uint16, rolloverCounter uint32, ssrc uint32, sessionSalt []byte) (counter [16]byte) { - copy(counter[:], sessionSalt) +func generateCounter(sequenceNumber uint16, rolloverCounter uint32, ssrc uint32, sessionSalt []byte) []byte { + counter := make([]byte, 16) - counter[4] ^= byte(ssrc >> 24) - counter[5] ^= byte(ssrc >> 16) - counter[6] ^= byte(ssrc >> 8) - counter[7] ^= byte(ssrc) - counter[8] ^= byte(rolloverCounter >> 24) - counter[9] ^= byte(rolloverCounter >> 16) - counter[10] ^= byte(rolloverCounter >> 8) - counter[11] ^= byte(rolloverCounter) - counter[12] ^= byte(sequenceNumber >> 8) - counter[13] ^= byte(sequenceNumber) + binary.BigEndian.PutUint32(counter[4:], ssrc) + binary.BigEndian.PutUint32(counter[8:], rolloverCounter) + binary.BigEndian.PutUint32(counter[12:], uint32(sequenceNumber)<<16) + + for i := range sessionSalt { + counter[i] ^= sessionSalt[i] + } return counter } diff --git a/vendor/github.com/pion/srtp/v2/keying.go b/vendor/github.com/pion/srtp/v2/keying.go index c5977c398..82fd4d900 100644 --- a/vendor/github.com/pion/srtp/v2/keying.go +++ b/vendor/github.com/pion/srtp/v2/keying.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp const labelExtractorDtlsSrtp = "EXTRACTOR-dtls_srtp" diff --git a/vendor/github.com/pion/srtp/v2/option.go b/vendor/github.com/pion/srtp/v2/option.go index 7e2618e38..d6159f13f 100644 --- a/vendor/github.com/pion/srtp/v2/option.go +++ b/vendor/github.com/pion/srtp/v2/option.go @@ -1,20 +1,17 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( - "github.com/pion/transport/v2/replaydetector" + "github.com/pion/transport/replaydetector" ) // ContextOption represents option of Context using the functional options pattern. type ContextOption func(*Context) error // SRTPReplayProtection sets SRTP replay protection window size. -func SRTPReplayProtection(windowSize uint) ContextOption { // nolint:revive +func SRTPReplayProtection(windowSize uint) ContextOption { // nolint:golint return func(c *Context) error { c.newSRTPReplayDetector = func() replaydetector.ReplayDetector { - return replaydetector.New(windowSize, maxROC<<16|maxSequenceNumber) + return replaydetector.WithWrap(windowSize, maxSequenceNumber) } return nil } @@ -24,14 +21,14 @@ func SRTPReplayProtection(windowSize uint) ContextOption { // nolint:revive func SRTCPReplayProtection(windowSize uint) ContextOption { return func(c *Context) error { c.newSRTCPReplayDetector = func() replaydetector.ReplayDetector { - return replaydetector.New(windowSize, maxSRTCPIndex) + return replaydetector.WithWrap(windowSize, maxSRTCPIndex) } return nil } } // SRTPNoReplayProtection disables SRTP replay protection. -func SRTPNoReplayProtection() ContextOption { // nolint:revive +func SRTPNoReplayProtection() ContextOption { // nolint:golint return func(c *Context) error { c.newSRTPReplayDetector = func() replaydetector.ReplayDetector { return &nopReplayDetector{} diff --git a/vendor/github.com/pion/srtp/v2/protection_profile.go b/vendor/github.com/pion/srtp/v2/protection_profile.go index c9b0fce3a..94476ad54 100644 --- a/vendor/github.com/pion/srtp/v2/protection_profile.go +++ b/vendor/github.com/pion/srtp/v2/protection_profile.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import "fmt" @@ -9,20 +6,17 @@ import "fmt" type ProtectionProfile uint16 // Supported protection profiles -// See https://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml const ( ProtectionProfileAes128CmHmacSha1_80 ProtectionProfile = 0x0001 - ProtectionProfileAes128CmHmacSha1_32 ProtectionProfile = 0x0002 ProtectionProfileAeadAes128Gcm ProtectionProfile = 0x0007 - ProtectionProfileAeadAes256Gcm ProtectionProfile = 0x0008 ) func (p ProtectionProfile) keyLen() (int, error) { switch p { - case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80, ProtectionProfileAeadAes128Gcm: + case ProtectionProfileAes128CmHmacSha1_80: + fallthrough + case ProtectionProfileAeadAes128Gcm: return 16, nil - case ProtectionProfileAeadAes256Gcm: - return 32, nil default: return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p) } @@ -30,34 +24,21 @@ func (p ProtectionProfile) keyLen() (int, error) { func (p ProtectionProfile) saltLen() (int, error) { switch p { - case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80: + case ProtectionProfileAes128CmHmacSha1_80: return 14, nil - case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm: + case ProtectionProfileAeadAes128Gcm: return 12, nil default: return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p) } } -func (p ProtectionProfile) rtpAuthTagLen() (int, error) { +func (p ProtectionProfile) authTagLen() (int, error) { switch p { case ProtectionProfileAes128CmHmacSha1_80: - return 10, nil - case ProtectionProfileAes128CmHmacSha1_32: - return 4, nil - case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm: - return 0, nil - default: - return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p) - } -} - -func (p ProtectionProfile) rtcpAuthTagLen() (int, error) { - switch p { - case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80: - return 10, nil - case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm: - return 0, nil + return (&srtpCipherAesCmHmacSha1{}).authTagLen(), nil + case ProtectionProfileAeadAes128Gcm: + return (&srtpCipherAeadAesGcm{}).authTagLen(), nil default: return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p) } @@ -65,10 +46,10 @@ func (p ProtectionProfile) rtcpAuthTagLen() (int, error) { func (p ProtectionProfile) aeadAuthTagLen() (int, error) { switch p { - case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80: - return 0, nil - case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm: - return 16, nil + case ProtectionProfileAes128CmHmacSha1_80: + return (&srtpCipherAesCmHmacSha1{}).aeadAuthTagLen(), nil + case ProtectionProfileAeadAes128Gcm: + return (&srtpCipherAeadAesGcm{}).aeadAuthTagLen(), nil default: return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p) } @@ -76,9 +57,9 @@ func (p ProtectionProfile) aeadAuthTagLen() (int, error) { func (p ProtectionProfile) authKeyLen() (int, error) { switch p { - case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80: + case ProtectionProfileAes128CmHmacSha1_80: return 20, nil - case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm: + case ProtectionProfileAeadAes128Gcm: return 0, nil default: return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p) diff --git a/vendor/github.com/pion/srtp/v2/renovate.json b/vendor/github.com/pion/srtp/v2/renovate.json index f1bb98c6a..08c1e39d6 100644 --- a/vendor/github.com/pion/srtp/v2/renovate.json +++ b/vendor/github.com/pion/srtp/v2/renovate.json @@ -1,6 +1,26 @@ { - "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ - "github>pion/renovate-config" + "config:base" + ], + "postUpdateOptions": [ + "gomodTidy" + ], + "commitBody": "Generated by renovateBot", + "packageRules": [ + { + "matchUpdateTypes": ["minor", "patch", "pin", "digest"], + "automerge": true + }, + { + "packagePatterns": ["^golang.org/x/"], + "schedule": ["on the first day of the month"] + } + ], + "ignorePaths": [ + ".github/workflows/generate-authors.yml", + ".github/workflows/lint.yaml", + ".github/workflows/renovate-go-mod-fix.yaml", + ".github/workflows/test.yaml", + ".github/workflows/tidy-check.yaml" ] } diff --git a/vendor/github.com/pion/srtp/v2/session.go b/vendor/github.com/pion/srtp/v2/session.go index 2e1f4fe3f..95520f782 100644 --- a/vendor/github.com/pion/srtp/v2/session.go +++ b/vendor/github.com/pion/srtp/v2/session.go @@ -1,17 +1,12 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( - "errors" "io" "net" "sync" - "time" "github.com/pion/logging" - "github.com/pion/transport/v2/packetio" + "github.com/pion/transport/packetio" ) type streamSession interface { @@ -25,8 +20,7 @@ type session struct { localContext, remoteContext *Context localOptions, remoteOptions []ContextOption - newStream chan readStream - acceptStreamTimeout time.Time + newStream chan readStream started chan interface{} closed chan interface{} @@ -46,11 +40,10 @@ type session struct { // or directly pass the keys themselves. // After a Config is passed to a session it must not be modified. type Config struct { - Keys SessionKeys - Profile ProtectionProfile - BufferFactory func(packetType packetio.BufferPacketType, ssrc uint32) io.ReadWriteCloser - LoggerFactory logging.LoggerFactory - AcceptStreamTimeout time.Time + Keys SessionKeys + Profile ProtectionProfile + BufferFactory func(packetType packetio.BufferPacketType, ssrc uint32) io.ReadWriteCloser + LoggerFactory logging.LoggerFactory // List of local/remote context options. // ReplayProtection is enabled on remote context by default. @@ -124,10 +117,6 @@ func (s *session) start(localMasterKey, localMasterSalt, remoteMasterKey, remote return err } - if err = s.nextConn.SetReadDeadline(s.acceptStreamTimeout); err != nil { - return err - } - go func() { defer func() { close(s.newStream) @@ -143,7 +132,7 @@ func (s *session) start(localMasterKey, localMasterSalt, remoteMasterKey, remote var i int i, err = s.nextConn.Read(b) if err != nil { - if !errors.Is(err, io.EOF) { + if err != io.EOF { s.log.Error(err.Error()) } return diff --git a/vendor/github.com/pion/srtp/v2/session_srtcp.go b/vendor/github.com/pion/srtp/v2/session_srtcp.go index 13f1a9589..a5fb656cc 100644 --- a/vendor/github.com/pion/srtp/v2/session_srtcp.go +++ b/vendor/github.com/pion/srtp/v2/session_srtcp.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( @@ -49,16 +46,15 @@ func NewSessionSRTCP(conn net.Conn, config *Config) (*SessionSRTCP, error) { //n s := &SessionSRTCP{ session: session{ - nextConn: conn, - localOptions: localOpts, - remoteOptions: remoteOpts, - readStreams: map[uint32]readStream{}, - newStream: make(chan readStream), - acceptStreamTimeout: config.AcceptStreamTimeout, - started: make(chan interface{}), - closed: make(chan interface{}), - bufferFactory: config.BufferFactory, - log: loggerFactory.NewLogger("srtp"), + nextConn: conn, + localOptions: localOpts, + remoteOptions: remoteOpts, + readStreams: map[uint32]readStream{}, + newStream: make(chan readStream), + started: make(chan interface{}), + closed: make(chan interface{}), + bufferFactory: config.BufferFactory, + log: loggerFactory.NewLogger("srtp"), }, } s.writeStream = &WriteStreamSRTCP{s} @@ -118,11 +114,8 @@ func (s *SessionSRTCP) write(buf []byte) (int, error) { return 0, errStartedChannelUsedIncorrectly } - ibuf := bufferpool.Get() - defer bufferpool.Put(ibuf) - s.session.localContextMutex.Lock() - encrypted, err := s.localContext.EncryptRTCP(ibuf.([]byte), buf, nil) + encrypted, err := s.localContext.EncryptRTCP(nil, buf, nil) s.session.localContextMutex.Unlock() if err != nil { @@ -169,9 +162,6 @@ func (s *SessionSRTCP) decrypt(buf []byte) error { if r == nil { return nil // Session has been closed } else if isNew { - if !s.session.acceptStreamTimeout.IsZero() { - _ = s.session.nextConn.SetReadDeadline(time.Time{}) - } s.session.newStream <- r // Notify AcceptStream } diff --git a/vendor/github.com/pion/srtp/v2/session_srtp.go b/vendor/github.com/pion/srtp/v2/session_srtp.go index e07cbe216..071c465ed 100644 --- a/vendor/github.com/pion/srtp/v2/session_srtp.go +++ b/vendor/github.com/pion/srtp/v2/session_srtp.go @@ -1,11 +1,7 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( "net" - "sync" "time" "github.com/pion/logging" @@ -50,16 +46,15 @@ func NewSessionSRTP(conn net.Conn, config *Config) (*SessionSRTP, error) { //nol s := &SessionSRTP{ session: session{ - nextConn: conn, - localOptions: localOpts, - remoteOptions: remoteOpts, - readStreams: map[uint32]readStream{}, - newStream: make(chan readStream), - acceptStreamTimeout: config.AcceptStreamTimeout, - started: make(chan interface{}), - closed: make(chan interface{}), - bufferFactory: config.BufferFactory, - log: loggerFactory.NewLogger("srtp"), + nextConn: conn, + localOptions: localOpts, + remoteOptions: remoteOpts, + readStreams: map[uint32]readStream{}, + newStream: make(chan readStream), + started: make(chan interface{}), + closed: make(chan interface{}), + bufferFactory: config.BufferFactory, + log: loggerFactory.NewLogger("srtp"), }, } s.writeStream = &WriteStreamSRTP{s} @@ -116,41 +111,21 @@ func (s *SessionSRTP) Close() error { func (s *SessionSRTP) write(b []byte) (int, error) { packet := &rtp.Packet{} - if err := packet.Unmarshal(b); err != nil { - return 0, err + err := packet.Unmarshal(b) + if err != nil { + return 0, nil } return s.writeRTP(&packet.Header, packet.Payload) } -// bufferpool is a global pool of buffers used for encrypted packets in -// writeRTP below. Since it's global, buffers can be shared between -// different sessions, which amortizes the cost of allocating the pool. -// -// 1472 is the maximum Ethernet UDP payload. We give ourselves 20 bytes -// of slack for any authentication tags, which is more than enough for -// either CTR or GCM. If the buffer is too small, no harm, it will just -// get expanded by growBuffer. -var bufferpool = sync.Pool{ // nolint:gochecknoglobals - New: func() interface{} { - return make([]byte, 1492) - }, -} - func (s *SessionSRTP) writeRTP(header *rtp.Header, payload []byte) (int, error) { if _, ok := <-s.session.started; ok { return 0, errStartedChannelUsedIncorrectly } - // encryptRTP will either return our buffer, or, if it is too - // small, allocate a new buffer itself. In either case, it is - // safe to put the buffer back into the pool, but only after - // nextConn.Write has returned. - ibuf := bufferpool.Get() - defer bufferpool.Put(ibuf) - s.session.localContextMutex.Lock() - encrypted, err := s.localContext.encryptRTP(ibuf.([]byte), header, payload) + encrypted, err := s.localContext.encryptRTP(nil, header, payload) s.session.localContextMutex.Unlock() if err != nil { @@ -175,9 +150,6 @@ func (s *SessionSRTP) decrypt(buf []byte) error { if r == nil { return nil // Session has been closed } else if isNew { - if !s.session.acceptStreamTimeout.IsZero() { - _ = s.session.nextConn.SetReadDeadline(time.Time{}) - } s.session.newStream <- r // Notify AcceptStream } diff --git a/vendor/github.com/pion/srtp/v2/srtcp.go b/vendor/github.com/pion/srtp/v2/srtcp.go index 7fd0746bd..dbf512549 100644 --- a/vendor/github.com/pion/srtp/v2/srtcp.go +++ b/vendor/github.com/pion/srtp/v2/srtcp.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( @@ -14,18 +11,9 @@ const maxSRTCPIndex = 0x7FFFFFFF func (c *Context) decryptRTCP(dst, encrypted []byte) ([]byte, error) { out := allocateIfMismatch(dst, encrypted) + tailOffset := len(encrypted) - (c.cipher.authTagLen() + srtcpIndexSize) - authTagLen, err := c.cipher.rtcpAuthTagLen() - if err != nil { - return nil, err - } - aeadAuthTagLen, err := c.cipher.aeadAuthTagLen() - if err != nil { - return nil, err - } - tailOffset := len(encrypted) - (authTagLen + srtcpIndexSize) - - if tailOffset < aeadAuthTagLen { + if tailOffset < 0 { return nil, fmt.Errorf("%w: %d", errTooShortRTCP, len(encrypted)) } else if isEncrypted := encrypted[tailOffset] >> 7; isEncrypted == 0 { return out, nil @@ -37,10 +25,10 @@ func (c *Context) decryptRTCP(dst, encrypted []byte) ([]byte, error) { s := c.getSRTCPSSRCState(ssrc) markAsValid, ok := s.replayDetector.Check(uint64(index)) if !ok { - return nil, &duplicatedError{Proto: "srtcp", SSRC: ssrc, Index: index} + return nil, &errorDuplicated{Proto: "srtcp", SSRC: ssrc, Index: index} } - out, err = c.cipher.decryptRTCP(out, encrypted, index, ssrc) + out, err := c.cipher.decryptRTCP(out, encrypted, index, ssrc) if err != nil { return nil, err } @@ -66,16 +54,11 @@ func (c *Context) encryptRTCP(dst, decrypted []byte) ([]byte, error) { ssrc := binary.BigEndian.Uint32(decrypted[4:]) s := c.getSRTCPSSRCState(ssrc) - if s.srtcpIndex >= maxSRTCPIndex { - // ... when 2^48 SRTP packets or 2^31 SRTCP packets have been secured with the same key - // (whichever occurs before), the key management MUST be called to provide new master key(s) - // (previously stored and used keys MUST NOT be used again), or the session MUST be terminated. - // https://www.rfc-editor.org/rfc/rfc3711#section-9.2 - return nil, errExceededMaxPackets - } - // We roll over early because MSB is used for marking as encrypted s.srtcpIndex++ + if s.srtcpIndex > maxSRTCPIndex { + s.srtcpIndex = 0 + } return c.cipher.encryptRTCP(dst, decrypted, s.srtcpIndex, ssrc) } diff --git a/vendor/github.com/pion/srtp/v2/srtp.go b/vendor/github.com/pion/srtp/v2/srtp.go index 42c71be01..26283722d 100644 --- a/vendor/github.com/pion/srtp/v2/srtp.go +++ b/vendor/github.com/pion/srtp/v2/srtp.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package srtp implements Secure Real-time Transport Protocol package srtp @@ -11,29 +8,23 @@ import ( func (c *Context) decryptRTP(dst, ciphertext []byte, header *rtp.Header, headerLen int) ([]byte, error) { s := c.getSRTPSSRCState(header.SSRC) - roc, diff, _ := s.nextRolloverCount(header.SequenceNumber) - markAsValid, ok := s.replayDetector.Check( - (uint64(roc) << 16) | uint64(header.SequenceNumber), - ) + markAsValid, ok := s.replayDetector.Check(uint64(header.SequenceNumber)) if !ok { - return nil, &duplicatedError{ + return nil, &errorDuplicated{ Proto: "srtp", SSRC: header.SSRC, Index: uint32(header.SequenceNumber), } } - authTagLen, err := c.cipher.rtpAuthTagLen() - if err != nil { - return nil, err - } - dst = growBufferSize(dst, len(ciphertext)-authTagLen) + dst = growBufferSize(dst, len(ciphertext)-c.cipher.authTagLen()) + roc, updateROC := s.nextRolloverCount(header.SequenceNumber) - dst, err = c.cipher.decryptRTP(dst, ciphertext, header, headerLen, roc) + dst, err := c.cipher.decryptRTP(dst, ciphertext, header, headerLen, roc) if err != nil { return nil, err } markAsValid() - s.updateRolloverCount(header.SequenceNumber, diff) + updateROC() return dst, nil } @@ -72,15 +63,8 @@ func (c *Context) EncryptRTP(dst []byte, plaintext []byte, header *rtp.Header) ( // Similar to above but faster because it can avoid unmarshaling the header and marshaling the payload. func (c *Context) encryptRTP(dst []byte, header *rtp.Header, payload []byte) (ciphertext []byte, err error) { s := c.getSRTPSSRCState(header.SSRC) - roc, diff, ovf := s.nextRolloverCount(header.SequenceNumber) - if ovf { - // ... when 2^48 SRTP packets or 2^31 SRTCP packets have been secured with the same key - // (whichever occurs before), the key management MUST be called to provide new master key(s) - // (previously stored and used keys MUST NOT be used again), or the session MUST be terminated. - // https://www.rfc-editor.org/rfc/rfc3711#section-9.2 - return nil, errExceededMaxPackets - } - s.updateRolloverCount(header.SequenceNumber, diff) + roc, updateROC := s.nextRolloverCount(header.SequenceNumber) + updateROC() return c.cipher.encryptRTP(dst, header, payload, roc) } diff --git a/vendor/github.com/pion/srtp/v2/srtp_cipher.go b/vendor/github.com/pion/srtp/v2/srtp_cipher.go index db501472f..2cdf32587 100644 --- a/vendor/github.com/pion/srtp/v2/srtp_cipher.go +++ b/vendor/github.com/pion/srtp/v2/srtp_cipher.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import "github.com/pion/rtp" @@ -10,11 +7,10 @@ import "github.com/pion/rtp" type srtpCipher interface { // authTagLen returns auth key length of the cipher. // See the note below. - rtpAuthTagLen() (int, error) - rtcpAuthTagLen() (int, error) + authTagLen() int // aeadAuthTagLen returns AEAD auth key length of the cipher. // See the note below. - aeadAuthTagLen() (int, error) + aeadAuthTagLen() int getRTCPIndex([]byte) uint32 encryptRTP([]byte, *rtp.Header, []byte, uint32) ([]byte, error) diff --git a/vendor/github.com/pion/srtp/v2/srtp_cipher_aead_aes_gcm.go b/vendor/github.com/pion/srtp/v2/srtp_cipher_aead_aes_gcm.go index 90643d92d..ea819bf57 100644 --- a/vendor/github.com/pion/srtp/v2/srtp_cipher_aead_aes_gcm.go +++ b/vendor/github.com/pion/srtp/v2/srtp_cipher_aead_aes_gcm.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( @@ -16,15 +13,13 @@ const ( ) type srtpCipherAeadAesGcm struct { - ProtectionProfile - srtpCipher, srtcpCipher cipher.AEAD srtpSessionSalt, srtcpSessionSalt []byte } -func newSrtpCipherAeadAesGcm(profile ProtectionProfile, masterKey, masterSalt []byte) (*srtpCipherAeadAesGcm, error) { - s := &srtpCipherAeadAesGcm{ProtectionProfile: profile} +func newSrtpCipherAeadAesGcm(masterKey, masterSalt []byte) (*srtpCipherAeadAesGcm, error) { + s := &srtpCipherAeadAesGcm{} srtpSessionKey, err := aesCmKeyDerivation(labelSRTPEncryption, masterKey, masterSalt, 0, len(masterKey)) if err != nil { @@ -65,31 +60,33 @@ func newSrtpCipherAeadAesGcm(profile ProtectionProfile, masterKey, masterSalt [] return s, nil } +func (s *srtpCipherAeadAesGcm) authTagLen() int { + return 0 +} + +func (s *srtpCipherAeadAesGcm) aeadAuthTagLen() int { + return 16 +} + func (s *srtpCipherAeadAesGcm) encryptRTP(dst []byte, header *rtp.Header, payload []byte, roc uint32) (ciphertext []byte, err error) { // Grow the given buffer to fit the output. - authTagLen, err := s.aeadAuthTagLen() - if err != nil { - return nil, err - } - dst = growBufferSize(dst, header.MarshalSize()+len(payload)+authTagLen) + dst = growBufferSize(dst, header.MarshalSize()+len(payload)+s.aeadAuthTagLen()) - n, err := header.MarshalTo(dst) + hdr, err := header.Marshal() if err != nil { return nil, err } iv := s.rtpInitializationVector(header, roc) - s.srtpCipher.Seal(dst[n:n], iv[:], payload, dst[:n]) + nHdr := len(hdr) + s.srtpCipher.Seal(dst[nHdr:nHdr], iv, payload, hdr) + copy(dst[:nHdr], hdr) return dst, nil } func (s *srtpCipherAeadAesGcm) decryptRTP(dst, ciphertext []byte, header *rtp.Header, headerLen int, roc uint32) ([]byte, error) { // Grow the given buffer to fit the output. - authTagLen, err := s.aeadAuthTagLen() - if err != nil { - return nil, err - } - nDst := len(ciphertext) - authTagLen + nDst := len(ciphertext) - s.aeadAuthTagLen() if nDst < 0 { // Size of ciphertext is shorter than AEAD auth tag len. return nil, errFailedToVerifyAuthTag @@ -99,7 +96,7 @@ func (s *srtpCipherAeadAesGcm) decryptRTP(dst, ciphertext []byte, header *rtp.He iv := s.rtpInitializationVector(header, roc) if _, err := s.srtpCipher.Open( - dst[headerLen:headerLen], iv[:], ciphertext[headerLen:], ciphertext[:headerLen], + dst[headerLen:headerLen], iv, ciphertext[headerLen:], ciphertext[:headerLen], ); err != nil { return nil, err } @@ -109,18 +106,14 @@ func (s *srtpCipherAeadAesGcm) decryptRTP(dst, ciphertext []byte, header *rtp.He } func (s *srtpCipherAeadAesGcm) encryptRTCP(dst, decrypted []byte, srtcpIndex uint32, ssrc uint32) ([]byte, error) { - authTagLen, err := s.aeadAuthTagLen() - if err != nil { - return nil, err - } - aadPos := len(decrypted) + authTagLen + aadPos := len(decrypted) + s.aeadAuthTagLen() // Grow the given buffer to fit the output. dst = growBufferSize(dst, aadPos+srtcpIndexSize) iv := s.rtcpInitializationVector(srtcpIndex, ssrc) aad := s.rtcpAdditionalAuthenticatedData(decrypted, srtcpIndex) - s.srtcpCipher.Seal(dst[8:8], iv[:], decrypted[8:], aad[:]) + s.srtcpCipher.Seal(dst[8:8], iv, decrypted[8:], aad) copy(dst[:8], decrypted[:8]) copy(dst[aadPos:aadPos+4], aad[8:12]) @@ -130,11 +123,7 @@ func (s *srtpCipherAeadAesGcm) encryptRTCP(dst, decrypted []byte, srtcpIndex uin func (s *srtpCipherAeadAesGcm) decryptRTCP(dst, encrypted []byte, srtcpIndex, ssrc uint32) ([]byte, error) { aadPos := len(encrypted) - srtcpIndexSize // Grow the given buffer to fit the output. - authTagLen, err := s.aeadAuthTagLen() - if err != nil { - return nil, err - } - nDst := aadPos - authTagLen + nDst := aadPos - s.aeadAuthTagLen() if nDst < 0 { // Size of ciphertext is shorter than AEAD auth tag len. return nil, errFailedToVerifyAuthTag @@ -144,7 +133,7 @@ func (s *srtpCipherAeadAesGcm) decryptRTCP(dst, encrypted []byte, srtcpIndex, ss iv := s.rtcpInitializationVector(srtcpIndex, ssrc) aad := s.rtcpAdditionalAuthenticatedData(encrypted, srtcpIndex) - if _, err := s.srtcpCipher.Open(dst[8:8], iv[:], encrypted[8:aadPos], aad[:]); err != nil { + if _, err := s.srtcpCipher.Open(dst[8:8], iv, encrypted[8:aadPos], aad); err != nil { return nil, err } @@ -158,8 +147,8 @@ func (s *srtpCipherAeadAesGcm) decryptRTCP(dst, encrypted []byte, srtcpIndex, ss // value is then XORed to the 12-octet salt to form the 12-octet IV. // // https://tools.ietf.org/html/rfc7714#section-8.1 -func (s *srtpCipherAeadAesGcm) rtpInitializationVector(header *rtp.Header, roc uint32) [12]byte { - var iv [12]byte +func (s *srtpCipherAeadAesGcm) rtpInitializationVector(header *rtp.Header, roc uint32) []byte { + iv := make([]byte, 12) binary.BigEndian.PutUint32(iv[2:], header.SSRC) binary.BigEndian.PutUint32(iv[6:], roc) binary.BigEndian.PutUint16(iv[10:], header.SequenceNumber) @@ -177,8 +166,8 @@ func (s *srtpCipherAeadAesGcm) rtpInitializationVector(header *rtp.Header, roc u // form the 12-octet IV. // // https://tools.ietf.org/html/rfc7714#section-9.1 -func (s *srtpCipherAeadAesGcm) rtcpInitializationVector(srtcpIndex uint32, ssrc uint32) [12]byte { - var iv [12]byte +func (s *srtpCipherAeadAesGcm) rtcpInitializationVector(srtcpIndex uint32, ssrc uint32) []byte { + iv := make([]byte, 12) binary.BigEndian.PutUint32(iv[2:], ssrc) binary.BigEndian.PutUint32(iv[8:], srtcpIndex) @@ -194,10 +183,10 @@ func (s *srtpCipherAeadAesGcm) rtcpInitializationVector(srtcpIndex uint32, ssrc // "ESRTCP word" // // https://tools.ietf.org/html/rfc7714#section-17 -func (s *srtpCipherAeadAesGcm) rtcpAdditionalAuthenticatedData(rtcpPacket []byte, srtcpIndex uint32) [12]byte { - var aad [12]byte +func (s *srtpCipherAeadAesGcm) rtcpAdditionalAuthenticatedData(rtcpPacket []byte, srtcpIndex uint32) []byte { + aad := make([]byte, 12) - copy(aad[:], rtcpPacket[:8]) + copy(aad, rtcpPacket[:8]) binary.BigEndian.PutUint32(aad[8:], srtcpIndex) aad[8] |= rtcpEncryptionFlag diff --git a/vendor/github.com/pion/srtp/v2/srtp_cipher_aes_cm_hmac_sha1.go b/vendor/github.com/pion/srtp/v2/srtp_cipher_aes_cm_hmac_sha1.go index d56e6afb1..85d7ac4ad 100644 --- a/vendor/github.com/pion/srtp/v2/srtp_cipher_aes_cm_hmac_sha1.go +++ b/vendor/github.com/pion/srtp/v2/srtp_cipher_aes_cm_hmac_sha1.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( //nolint:gci @@ -16,8 +13,6 @@ import ( //nolint:gci ) type srtpCipherAesCmHmacSha1 struct { - ProtectionProfile - srtpSessionSalt []byte srtpSessionAuth hash.Hash srtpBlock cipher.Block @@ -27,8 +22,8 @@ type srtpCipherAesCmHmacSha1 struct { srtcpBlock cipher.Block } -func newSrtpCipherAesCmHmacSha1(profile ProtectionProfile, masterKey, masterSalt []byte) (*srtpCipherAesCmHmacSha1, error) { - s := &srtpCipherAesCmHmacSha1{ProtectionProfile: profile} +func newSrtpCipherAesCmHmacSha1(masterKey, masterSalt []byte) (*srtpCipherAesCmHmacSha1, error) { + s := &srtpCipherAesCmHmacSha1{} srtpSessionKey, err := aesCmKeyDerivation(labelSRTPEncryption, masterKey, masterSalt, 0, len(masterKey)) if err != nil { return nil, err @@ -49,7 +44,7 @@ func newSrtpCipherAesCmHmacSha1(profile ProtectionProfile, masterKey, masterSalt return nil, err } - authKeyLen, err := profile.authKeyLen() + authKeyLen, err := ProtectionProfileAes128CmHmacSha1_80.authKeyLen() if err != nil { return nil, err } @@ -69,13 +64,17 @@ func newSrtpCipherAesCmHmacSha1(profile ProtectionProfile, masterKey, masterSalt return s, nil } +func (s *srtpCipherAesCmHmacSha1) authTagLen() int { + return 10 +} + +func (s *srtpCipherAesCmHmacSha1) aeadAuthTagLen() int { + return 0 +} + func (s *srtpCipherAesCmHmacSha1) encryptRTP(dst []byte, header *rtp.Header, payload []byte, roc uint32) (ciphertext []byte, err error) { // Grow the given buffer to fit the output. - authTagLen, err := s.rtpAuthTagLen() - if err != nil { - return nil, err - } - dst = growBufferSize(dst, header.MarshalSize()+len(payload)+authTagLen) + dst = growBufferSize(dst, header.MarshalSize()+len(payload)+s.authTagLen()) // Copy the header unencrypted. n, err := header.MarshalTo(dst) @@ -85,9 +84,8 @@ func (s *srtpCipherAesCmHmacSha1) encryptRTP(dst []byte, header *rtp.Header, pay // Encrypt the payload counter := generateCounter(header.SequenceNumber, roc, header.SSRC, s.srtpSessionSalt) - if err = xorBytesCTR(s.srtpBlock, counter[:], dst[n:], payload); err != nil { - return nil, err - } + stream := cipher.NewCTR(s.srtpBlock, counter) + stream.XORKeyStream(dst[n:], payload) n += len(payload) // Generate the auth tag. @@ -104,12 +102,8 @@ func (s *srtpCipherAesCmHmacSha1) encryptRTP(dst []byte, header *rtp.Header, pay func (s *srtpCipherAesCmHmacSha1) decryptRTP(dst, ciphertext []byte, header *rtp.Header, headerLen int, roc uint32) ([]byte, error) { // Split the auth tag and the cipher text into two parts. - authTagLen, err := s.rtpAuthTagLen() - if err != nil { - return nil, err - } - actualTag := ciphertext[len(ciphertext)-authTagLen:] - ciphertext = ciphertext[:len(ciphertext)-authTagLen] + actualTag := ciphertext[len(ciphertext)-s.authTagLen():] + ciphertext = ciphertext[:len(ciphertext)-s.authTagLen()] // Generate the auth tag we expect to see from the ciphertext. expectedTag, err := s.generateSrtpAuthTag(ciphertext, roc) @@ -128,20 +122,17 @@ func (s *srtpCipherAesCmHmacSha1) decryptRTP(dst, ciphertext []byte, header *rtp // Decrypt the ciphertext for the payload. counter := generateCounter(header.SequenceNumber, roc, header.SSRC, s.srtpSessionSalt) - err = xorBytesCTR( - s.srtpBlock, counter[:], dst[headerLen:], ciphertext[headerLen:], - ) - return dst, err + stream := cipher.NewCTR(s.srtpBlock, counter) + stream.XORKeyStream(dst[headerLen:], ciphertext[headerLen:]) + return dst, nil } func (s *srtpCipherAesCmHmacSha1) encryptRTCP(dst, decrypted []byte, srtcpIndex uint32, ssrc uint32) ([]byte, error) { dst = allocateIfMismatch(dst, decrypted) // Encrypt everything after header - counter := generateCounter(uint16(srtcpIndex&0xffff), srtcpIndex>>16, ssrc, s.srtcpSessionSalt) - if err := xorBytesCTR(s.srtcpBlock, counter[:], dst[8:], dst[8:]); err != nil { - return nil, err - } + stream := cipher.NewCTR(s.srtcpBlock, generateCounter(uint16(srtcpIndex&0xffff), srtcpIndex>>16, ssrc, s.srtcpSessionSalt)) + stream.XORKeyStream(dst[8:], dst[8:]) // Add SRTCP Index and set Encryption bit dst = append(dst, make([]byte, 4)...) @@ -156,27 +147,23 @@ func (s *srtpCipherAesCmHmacSha1) encryptRTCP(dst, decrypted []byte, srtcpIndex } func (s *srtpCipherAesCmHmacSha1) decryptRTCP(out, encrypted []byte, index, ssrc uint32) ([]byte, error) { - authTagLen, err := s.rtcpAuthTagLen() - if err != nil { - return nil, err - } - tailOffset := len(encrypted) - (authTagLen + srtcpIndexSize) + tailOffset := len(encrypted) - (s.authTagLen() + srtcpIndexSize) out = out[0:tailOffset] - expectedTag, err := s.generateSrtcpAuthTag(encrypted[:len(encrypted)-authTagLen]) + expectedTag, err := s.generateSrtcpAuthTag(encrypted[:len(encrypted)-s.authTagLen()]) if err != nil { return nil, err } - actualTag := encrypted[len(encrypted)-authTagLen:] + actualTag := encrypted[len(encrypted)-s.authTagLen():] if subtle.ConstantTimeCompare(actualTag, expectedTag) != 1 { return nil, errFailedToVerifyAuthTag } - counter := generateCounter(uint16(index&0xffff), index>>16, ssrc, s.srtcpSessionSalt) - err = xorBytesCTR(s.srtcpBlock, counter[:], out[8:], out[8:]) + stream := cipher.NewCTR(s.srtcpBlock, generateCounter(uint16(index&0xffff), index>>16, ssrc, s.srtcpSessionSalt)) + stream.XORKeyStream(out[8:], out[8:]) - return out, err + return out, nil } func (s *srtpCipherAesCmHmacSha1) generateSrtpAuthTag(buf []byte, roc uint32) ([]byte, error) { @@ -209,12 +196,8 @@ func (s *srtpCipherAesCmHmacSha1) generateSrtpAuthTag(buf []byte, roc uint32) ([ return nil, err } - // Truncate the hash to the size indicated by the profile - authTagLen, err := s.rtpAuthTagLen() - if err != nil { - return nil, err - } - return s.srtpSessionAuth.Sum(nil)[0:authTagLen], nil + // Truncate the hash to the first 10 bytes. + return s.srtpSessionAuth.Sum(nil)[0:s.authTagLen()], nil } func (s *srtpCipherAesCmHmacSha1) generateSrtcpAuthTag(buf []byte) ([]byte, error) { @@ -234,17 +217,12 @@ func (s *srtpCipherAesCmHmacSha1) generateSrtcpAuthTag(buf []byte) ([]byte, erro if _, err := s.srtcpSessionAuth.Write(buf); err != nil { return nil, err } - authTagLen, err := s.rtcpAuthTagLen() - if err != nil { - return nil, err - } - return s.srtcpSessionAuth.Sum(nil)[0:authTagLen], nil + return s.srtcpSessionAuth.Sum(nil)[0:s.authTagLen()], nil } func (s *srtpCipherAesCmHmacSha1) getRTCPIndex(in []byte) uint32 { - authTagLen, _ := s.rtcpAuthTagLen() - tailOffset := len(in) - (authTagLen + srtcpIndexSize) + tailOffset := len(in) - (s.authTagLen() + srtcpIndexSize) srtcpIndexBuffer := in[tailOffset : tailOffset+srtcpIndexSize] return binary.BigEndian.Uint32(srtcpIndexBuffer) &^ (1 << 31) } diff --git a/vendor/github.com/pion/srtp/v2/stream.go b/vendor/github.com/pion/srtp/v2/stream.go index 5f9c58a75..7b7a0cf9a 100644 --- a/vendor/github.com/pion/srtp/v2/stream.go +++ b/vendor/github.com/pion/srtp/v2/stream.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp type readStream interface { diff --git a/vendor/github.com/pion/srtp/v2/stream_srtcp.go b/vendor/github.com/pion/srtp/v2/stream_srtcp.go index 08d36dca5..e335937ff 100644 --- a/vendor/github.com/pion/srtp/v2/stream_srtcp.go +++ b/vendor/github.com/pion/srtp/v2/stream_srtcp.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( @@ -10,7 +7,7 @@ import ( "time" "github.com/pion/rtcp" - "github.com/pion/transport/v2/packetio" + "github.com/pion/transport/packetio" ) // Limit the buffer size to 100KB @@ -20,11 +17,11 @@ const srtcpBufferSize = 100 * 1000 type ReadStreamSRTCP struct { mu sync.Mutex + isInited bool isClosed chan bool - session *SessionSRTCP - ssrc uint32 - isInited bool + session *SessionSRTCP + ssrc uint32 buffer io.ReadWriteCloser } diff --git a/vendor/github.com/pion/srtp/v2/stream_srtp.go b/vendor/github.com/pion/srtp/v2/stream_srtp.go index 858970082..8b57c7c6f 100644 --- a/vendor/github.com/pion/srtp/v2/stream_srtp.go +++ b/vendor/github.com/pion/srtp/v2/stream_srtp.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import ( @@ -10,7 +7,7 @@ import ( "time" "github.com/pion/rtp" - "github.com/pion/transport/v2/packetio" + "github.com/pion/transport/packetio" ) // Limit the buffer size to 1MB @@ -20,11 +17,11 @@ const srtpBufferSize = 1000 * 1000 type ReadStreamSRTP struct { mu sync.Mutex + isInited bool isClosed chan bool - session *SessionSRTP - ssrc uint32 - isInited bool + session *SessionSRTP + ssrc uint32 buffer io.ReadWriteCloser } diff --git a/vendor/github.com/pion/srtp/v2/util.go b/vendor/github.com/pion/srtp/v2/util.go index 792175d96..1ae34a62a 100644 --- a/vendor/github.com/pion/srtp/v2/util.go +++ b/vendor/github.com/pion/srtp/v2/util.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package srtp import "bytes" diff --git a/vendor/github.com/pion/stun/.codecov.yml b/vendor/github.com/pion/stun/.codecov.yml new file mode 100644 index 000000000..7fa67fec8 --- /dev/null +++ b/vendor/github.com/pion/stun/.codecov.yml @@ -0,0 +1,9 @@ +coverage: + status: + patch: off + project: + default: + # basic + target: 98 + threshold: null + base: auto diff --git a/vendor/github.com/pion/stun/.gitignore b/vendor/github.com/pion/stun/.gitignore index 6e2f206a9..b9420d943 100644 --- a/vendor/github.com/pion/stun/.gitignore +++ b/vendor/github.com/pion/stun/.gitignore @@ -1,28 +1,17 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - -### JetBrains IDE ### -##################### -.idea/ - -### Emacs Temporary Files ### -############################# -*~ - -### Folders ### -############### -bin/ -vendor/ -node_modules/ - -### Files ### -############# -*.ivf -*.ogg -tags -cover.out +*-fuzz.zip +.idea +benchmark.*.write +*.test +*.out *.sw[poe] -*.wasm -examples/sfu-ws/cert.pem -examples/sfu-ws/key.pem -wasm_exec.js +bench.go-* +PACKAGES +cmd/stun-cli/stun-cli +cmd/stun-decode/stun-decode +cmd/stun-bench/stun-bench +cmd/stun-nat-behaviour/stun-nat-behaviour + +coverage.txt + +e2e/dump.pcap +e2e/log-*.txt diff --git a/vendor/github.com/pion/stun/.golangci.yml b/vendor/github.com/pion/stun/.golangci.yml index 4e3eddf42..40ca69c0d 100644 --- a/vendor/github.com/pion/stun/.golangci.yml +++ b/vendor/github.com/pion/stun/.golangci.yml @@ -1,137 +1,93 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - linters-settings: govet: check-shadowing: true + golint: + min-confidence: 0 + gocyclo: + min-complexity: 15 + maligned: + suggest-new: true + dupl: + threshold: 100 + goconst: + min-len: 2 + min-occurrences: 2 misspell: locale: US - exhaustive: - default-signifies-exhaustive: true - gomodguard: - blocked: - modules: - - github.com/pkg/errors: - recommendations: - - errors - forbidigo: - forbid: - - ^fmt.Print(f|ln)?$ - - ^log.(Panic|Fatal|Print)(f|ln)?$ - - ^os.Exit$ - - ^panic$ - - ^print(ln)?$ - -linters: - enable: - - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - - decorder # check declaration order and count of types, constants, variables and functions - - depguard # Go linter that checks if package imports are in a list of acceptable packages - - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - - exhaustive # check exhaustiveness of enum switch statements - - exportloopref # checks for pointers to enclosing loop variables - - forbidigo # Forbids identifiers - - forcetypeassert # finds forced type assertions - - gci # Gci control golang package import order and make it always deterministic. - - gochecknoglobals # Checks that no globals are present in Go code - - gochecknoinits # Checks that no init functions are present in Go code - - gocognit # Computes and checks the cognitive complexity of functions - - goconst # Finds repeated strings that could be replaced by a constant - - gocritic # The most opinionated Go source code linter - - godox # Tool for detection of FIXME, TODO and other comment keywords - - goerr113 # Golang linter to check the errors handling expressions - - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification - - gofumpt # Gofumpt checks whether code was gofumpt-ed. - - goheader # Checks is file header matches to pattern - - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. - - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - - goprintffuncname # Checks that printf-like functions are named with `f` at the end - - gosec # Inspects source code for security problems - - gosimple # Linter for Go source code that specializes in simplifying a code - - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - - ineffassign # Detects when assignments to existing variables are not used - - misspell # Finds commonly misspelled English words in comments - - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes - - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks - - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - - unconvert # Remove unnecessary type conversions - - unparam # Reports unused function parameters - - unused # Checks Go code for unused constants, variables, functions and types - - wastedassign # wastedassign finds wasted assignment statements - - whitespace # Tool for detection of leading and trailing whitespace - disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - - funlen # Tool for detection of long functions - - gocyclo # Computes and checks the cyclomatic complexity of functions - - godot # Check if comments end in a period - - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - - nestif # Reports deeply nested if statements - - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - - rowserrcheck # checks whether Err of rows is checked successfully - - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - - wsl # Whitespace Linter - Forces you to use empty lines! + lll: + line-length: 140 + goimports: + local-prefixes: github.com/pion + gocritic: + enabled-tags: + - performance + - style + - experimental + disabled-checks: + - commentedOutCode + - sloppyReassign issues: - exclude-use-default: false + exclude: + - "`assertHMACSize` - `blocksize` always receives `64`" exclude-rules: - # Allow complex tests, better to be self contained + - text: "string ``" + linters: + - goconst + + # Exclude some linters from running on tests files. - path: _test\.go linters: - - gocognit - - forbidigo + - gocyclo + - errcheck + - dupl + - gosec + - goconst - # Allow complex main function in examples - - path: examples - text: "of func `main` is high" + # Ease some gocritic warnings on test files. + - path: _test\.go + text: "(unnamedResult|exitAfterDefer|unlambda)" linters: - - gocognit - - # Allow forbidden identifiers in examples - - path: examples - linters: - - forbidigo + - gocritic - # Allow forbidden identifiers in CLI commands - - path: cmd + # Exclude known linters from partially hard-vendored code, + # which is impossible to exclude via "nolint" comments. + - path: internal/hmac/ + text: "weak cryptographic primitive" linters: - - forbidigo + - gosec + - path: internal/hmac/ + text: "Write\\` is not checked" + linters: + - errcheck + + # Ease linting on benchmarking code. + - path: cmd/stun-bench/ + linters: + - gosec + - errcheck + - unparam + + - path: ^cmd/ + linters: + - gocyclo + - path: ^cmd/ + text: "(unnamedResult|exitAfterDefer)" + linters: + - gocritic + +linters: + enable-all: true + disable: + - funlen + - gochecknoglobals + - godox + - prealloc + - scopelint run: - skip-dirs-use-default: false + skip-dirs: + - e2e + - fuzz + - testdata + - api diff --git a/vendor/github.com/pion/stun/.goreleaser.yml b/vendor/github.com/pion/stun/.goreleaser.yml index 30093e9d6..d72bde60c 100644 --- a/vendor/github.com/pion/stun/.goreleaser.yml +++ b/vendor/github.com/pion/stun/.goreleaser.yml @@ -1,5 +1,39 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT +before: + hooks: + - go mod tidy + +archives: +- replacements: + darwin: Darwin + linux: Linux + windows: Windows + 386: i386 + amd64: x86_64 + +checksum: + name_template: 'checksums.txt' + +snapshot: + name_template: "{{ .Tag }}-next" + +changelog: + sort: asc + filters: + exclude: + - '^docs:' + - '^test:' builds: -- skip: true + - binary: stun-not-behavior + id: stun-not-behavior + goos: + - darwin + - windows + - linux + - freebsd + goarch: + - amd64 + - 386 + env: + - CGO_ENABLED=0 + main: ./cmd/stun-nat-behavior diff --git a/vendor/github.com/pion/stun/.travis.yml b/vendor/github.com/pion/stun/.travis.yml new file mode 100644 index 000000000..e464e84ad --- /dev/null +++ b/vendor/github.com/pion/stun/.travis.yml @@ -0,0 +1,135 @@ +# +# DO NOT EDIT THIS FILE DIRECTLY +# +# It is automatically copied from https://github.com/pion/.goassets repository. +# If this repository should have package specific CI config, +# remove the repository name from .goassets/.github/workflows/assets-sync.yml. +# + +dist: bionic +language: go + + +branches: + only: + - master + +env: + global: + - GO111MODULE=on + - GOLANGCI_LINT_VERSION=1.19.1 + +cache: + directories: + - ${HOME}/.cache/go-build + - ${GOPATH}/pkg/mod + npm: true + yarn: true + +_lint_job: &lint_job + env: CACHE_NAME=lint + before_install: + - if [ -f .github/.ci.conf ]; then . .github/.ci.conf; fi + install: skip + before_script: + - | + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh \ + | bash -s - -b $GOPATH/bin v${GOLANGCI_LINT_VERSION} + script: + - bash .github/assert-contributors.sh + - bash .github/lint-disallowed-functions-in-library.sh + - bash .github/lint-commit-message.sh + - bash .github/lint-filename.sh + - golangci-lint run ./... +_test_job: &test_job + env: CACHE_NAME=test + before_install: + - if [ -f .github/.ci.conf ]; then . .github/.ci.conf; fi + - go mod download + install: + - go build ./... + script: + - testpkgs=${TEST_PACKAGES:-$(go list ./... | grep -v examples)} + - coverpkgs=$(echo "${testpkgs}" | paste -s -d ',') + - | + go test \ + -coverpkg=${coverpkgs} -coverprofile=cover.out -covermode=atomic \ + ${TEST_EXTRA_ARGS:-} \ + -v -race ${testpkgs} + - if [ -n "${TEST_HOOK}" ]; then ${TEST_HOOK}; fi + after_success: + - travis_retry bash <(curl -s https://codecov.io/bash) -c -F go +_test_i386_job: &test_i386_job + env: CACHE_NAME=test386 + services: docker + before_install: + - if [ -f .github/.ci.conf ]; then . .github/.ci.conf; fi + script: + - testpkgs=${TEST_PACKAGES:-$(go list ./... | grep -v examples)} + - | + docker run \ + -u $(id -u):$(id -g) \ + -e "GO111MODULE=on" \ + -e "CGO_ENABLED=0" \ + -v ${PWD}:/go/src/github.com/pion/$(basename ${PWD}) \ + -v ${HOME}/gopath/pkg/mod:/go/pkg/mod \ + -v ${HOME}/.cache/go-build:/.cache/go-build \ + -w /go/src/github.com/pion/$(basename ${PWD}) \ + -it i386/golang:${GO_VERSION}-alpine \ + /usr/local/go/bin/go test \ + ${TEST_EXTRA_ARGS:-} \ + -v ${testpkgs} +_test_wasm_job: &test_wasm_job + env: CACHE_NAME=wasm + language: node_js + node_js: 12 + before_install: + - if [ -f .github/.ci.conf ]; then . .github/.ci.conf; fi + - if ${SKIP_WASM_TEST:-false}; then exit 0; fi + install: + # Manually download and install Go instead of using gimme. + # It looks like gimme Go causes some errors on go-test for Wasm. + - curl -sSfL https://dl.google.com/go/go${GO_VERSION}.linux-amd64.tar.gz | tar -C ~ -xzf - + - export GOROOT=${HOME}/go + - export PATH=${GOROOT}/bin:${PATH} + - yarn install + - export GO_JS_WASM_EXEC=${GO_JS_WASM_EXEC:-${GOROOT}/misc/wasm/go_js_wasm_exec} + script: + - testpkgs=${TEST_PACKAGES:-$(go list ./... | grep -v examples)} + - coverpkgs=$(echo "${testpkgs}" | paste -s -d ',') + - | + GOOS=js GOARCH=wasm go test \ + -coverpkg=${coverpkgs} -coverprofile=cover.out -covermode=atomic \ + -exec="${GO_JS_WASM_EXEC}" \ + -v ${testpkgs} + after_success: + - travis_retry bash <(curl -s https://codecov.io/bash) -c -F wasm + +jobs: + include: + - <<: *lint_job + name: Lint 1.14 + go: 1.14 + - <<: *test_job + name: Test 1.13 + go: 1.13 + - <<: *test_job + name: Test 1.14 + go: 1.14 + - <<: *test_i386_job + name: Test i386 1.13 + env: GO_VERSION=1.13 + go: 1.14 # version for host environment used to go list + - <<: *test_i386_job + name: Test i386 1.14 + env: GO_VERSION=1.14 + go: 1.14 # version for host environment used to go list + - <<: *test_wasm_job + name: Test WASM 1.13 + env: GO_VERSION=1.13 + - <<: *test_wasm_job + name: Test WASM 1.14 + env: GO_VERSION=1.14 + +notifications: + email: false diff --git a/vendor/github.com/pion/stun/AUTHORS b/vendor/github.com/pion/stun/AUTHORS new file mode 100644 index 000000000..717af8f60 --- /dev/null +++ b/vendor/github.com/pion/stun/AUTHORS @@ -0,0 +1,10 @@ +Sean DuBois +Raphael Randschau +Aleksandr Razumov +Aliaksandr Valialkin +Michiel De Backker +Y.Horie +songjiayang +The gortc project +The IETF Trust +The Go Authors diff --git a/vendor/github.com/pion/stun/AUTHORS.txt b/vendor/github.com/pion/stun/AUTHORS.txt deleted file mode 100644 index 3c3d9e00f..000000000 --- a/vendor/github.com/pion/stun/AUTHORS.txt +++ /dev/null @@ -1,40 +0,0 @@ -# Thank you to everyone that made Pion possible. If you are interested in contributing -# we would love to have you https://github.com/pion/webrtc/wiki/Contributing -# -# This file is auto generated, using git to list all individuals contributors. -# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting -Adam Kiss -Aleksandr Razumov -Aleksandr Razumov -Atsushi Watanabe -backkem -Cecylia Bocovich -Christian Muehlhaeuser -David-dp- -ernado -ernado -fossabot -Frank Dietrich -Hugo Arregui -Jerry Tao -jinleileiking -John Bradley -Juliusz Chroboczek -Maanas Royy -Moises Marangoni -Raphael Randschau -Sean DuBois -Sean DuBois -Sean DuBois -songjiayang -Steffen Vogel -Vladislav Yarmak -Will LE -Y.Horie -Yutaka Takeda -ZHENK - -# List of contributors not appearing in Git history -Aliaksandr Valialkin -The IETF Trust -The gortc project diff --git a/vendor/github.com/pion/stun/Dockerfile b/vendor/github.com/pion/stun/Dockerfile new file mode 100644 index 000000000..429239a38 --- /dev/null +++ b/vendor/github.com/pion/stun/Dockerfile @@ -0,0 +1,5 @@ +FROM golang:1.14 + +COPY . /go/src/github.com/pion/stun + +RUN go test github.com/pion/stun diff --git a/vendor/github.com/pion/stun/LICENSE b/vendor/github.com/pion/stun/LICENSE.md similarity index 93% rename from vendor/github.com/pion/stun/LICENSE rename to vendor/github.com/pion/stun/LICENSE.md index 491caf6b0..5cc9cbdc5 100644 --- a/vendor/github.com/pion/stun/LICENSE +++ b/vendor/github.com/pion/stun/LICENSE.md @@ -1,6 +1,4 @@ -MIT License - -Copyright (c) 2023 The Pion community +Copyright 2018 Pion LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: diff --git a/vendor/github.com/pion/stun/Makefile b/vendor/github.com/pion/stun/Makefile index ebfcd3394..43de8d003 100644 --- a/vendor/github.com/pion/stun/Makefile +++ b/vendor/github.com/pion/stun/Makefile @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - VERSION := $(shell git describe --tags | sed -e 's/^v//g' | awk -F "-" '{print $$1}') ITERATION := $(shell git describe --tags --long | awk -F "-" '{print $$2}') GO_VERSION=$(shell gobuild -v) @@ -12,6 +9,22 @@ bench: go test -bench . bench-record: $(GO) test -bench . > "benchmarks/stun-go-$(GO_VERSION).txt" +fuzz-prepare-msg: + go-fuzz-build -func FuzzMessage -o stun-msg-fuzz.zip github.com/pion/stun +fuzz-prepare-typ: + go-fuzz-build -func FuzzType -o stun-typ-fuzz.zip github.com/pion/stun +fuzz-prepare-setters: + go-fuzz-build -func FuzzSetters -o stun-setters-fuzz.zip github.com/pion/stun +fuzz-msg: + go-fuzz -bin=./stun-msg-fuzz.zip -workdir=fuzz/stun-msg +fuzz-typ: + go-fuzz -bin=./stun-typ-fuzz.zip -workdir=fuzz/stun-typ +fuzz-setters: + go-fuzz -bin=./stun-setters-fuzz.zip -workdir=fuzz/stun-setters +fuzz-test: + go test -tags gofuzz -run TestFuzz -v . +fuzz-reset-setters: + rm -f -v -r stun-setters-fuzz.zip fuzz/stun-setters lint: @golangci-lint run ./... @echo "ok" @@ -26,14 +39,23 @@ bench-compare: go test -bench . > bench.go-16 go-tip test -bench . > bench.go-tip @benchcmp bench.go-16 bench.go-tip +install-fuzz: + go get -u github.com/dvyukov/go-fuzz/go-fuzz-build + go get github.com/dvyukov/go-fuzz/go-fuzz install: go get gortc.io/api go get -u github.com/golangci/golangci-lint/cmd/golangci-lint +docker-build: + docker build -t pion/stun . test-integration: @cd e2e && bash ./test.sh -prepush: test lint test-integration +prepush: assert test lint test-integration check-api: @cd api && bash ./check.sh +assert: + bash .github/assert-contributors.sh + bash .github/lint-disallowed-functions-in-library.sh + bash .github/lint-commit-message.sh test: @./go.test.sh clean: diff --git a/vendor/github.com/pion/stun/README.md b/vendor/github.com/pion/stun/README.md index fe1b28ffb..6dd50d0f3 100644 --- a/vendor/github.com/pion/stun/README.md +++ b/vendor/github.com/pion/stun/README.md @@ -6,21 +6,52 @@

A Go implementation of STUN

Pion stun + Slack Widget
- GitHub Workflow Status - Go Reference + Build Status + GoDoc Coverage Status Go Report Card + License: MIT


-Package `stun` implements Session Traversal Utilities for NAT (STUN) ([RFC 5389][rfc5389]) +### Roadmap +The library is used as a part of our WebRTC implementation. Please refer to that [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones. + +### Community +Pion has an active community on the [Golang Slack](https://invite.slack.golangbridge.org/). Sign up and join the **#pion** channel for discussions and support. You can also use [Pion mailing list](https://groups.google.com/forum/#!forum/pion). + +We are always looking to support **your projects**. Please reach out if you have something to build! + +If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly) + +### Contributing +Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible: + +* [Sean DuBois](https://github.com/Sean-Der) - *Original Author* +* [Raphael Randschau](https://github.com/nicolai86) - *STUN client* +* [Michiel De Backker](https://github.com/backkem) - *Minor fixes* +* [Y.Horie](https://github.com/u5surf) - *Fix lint issues* +* [Aleksandr Razumov](https://github.com/ernado) - *The v0.3 version* +* [songjiayang](https://github.com/songjiayang) +* [Adam Kiss](https://github.com/masterada) +* [Moises Marangoni](https://github.com/Moisesbr) +* [Yutaka Takeda](https://github.com/enobufs) +* [Hugo Arregui](https://github.com/hugoArregui) +* [Maanas Royy](https://github.com/maanas) +* [Atsushi Watanabe](https://github.com/at-wat) +* [Cecylia Bocovich](https://github.com/cohosh) +* [Christian Muehlhaeuser](https://github.com/muesli) + +# STUN +Package stun implements Session Traversal Utilities for NAT (STUN) [[RFC5389](https://tools.ietf.org/html/rfc5389)] protocol and [client](https://pkg.go.dev/github.com/pion/stun#Client) with no external dependencies and zero allocations in hot paths. Client [supports](https://pkg.go.dev/github.com/pion/stun#WithRTO) automatic request retransmissions. -### Example +# Example You can get your current IP address from any STUN server by sending binding request. See more idiomatic example at `cmd/stun-client`. ```go @@ -33,14 +64,8 @@ import ( ) func main() { - // Parse a STUN URI - u, err := stun.ParseURI("stun:stun.l.google.com:19302") - if err != nil { - panic(err) - } - // Creating a "connection" to STUN server. - c, err := stun.DialURI(u, &stun.DialConfig{}) + c, err := stun.Dial("udp", "stun.l.google.com:19302") if err != nil { panic(err) } @@ -63,43 +88,30 @@ func main() { } ``` -### RFCs -#### Implemented -- **RFC 5389**: [Session Traversal Utilities for NAT (STUN)][rfc5389] -- **RFC 5769**: [Test Vectors for Session Traversal Utilities for NAT (STUN)][rfc5769] -- **RFC 6062**: [Traversal Using Relays around NAT (TURN) Extensions for TCP Allocations][rfc6062] -- **RFC 7064**: [URI Scheme for the Session Traversal Utilities for NAT (STUN) Protocol][rfc7064] -- **RFC 7065**: [Traversal Using Relays around NAT (TURN) Uniform Resource Identifiers][rfc7065] -- **RFC 5780**: [NAT Behavior Discovery Using Session Traversal Utilities for NAT (STUN)][rfc5780] via [cmd/stun-nat-behaviour](cmd/stun-nat-behaviour) -- (TLS-over-)TCP client support +## Supported RFCs +- [x] [RFC 5389](https://tools.ietf.org/html/rfc5389) — Session Traversal Utilities for NAT +- [x] [RFC 5769](https://tools.ietf.org/html/rfc5769) — Test Vectors for STUN +- [x] [RFC 6062](https://tools.ietf.org/html/rfc6062) — TURN extensions for TCP allocations +- [x] [RFC 7064](https://tools.ietf.org/html/rfc7064) — STUN URI +- [x] (TLS-over-)TCP client support +- [ ] [ALTERNATE-SERVER](https://tools.ietf.org/html/rfc5389#section-11) support [#48](https://github.com/pion/stun/issues/48) +- [ ] [RFC 5780](https://tools.ietf.org/html/rfc5780) — NAT Behavior Discovery Using STUN [#49](https://github.com/pion/stun/issues/49) -#### Planned -- **RFC 5389**: [ALTERNATE-SERVER](https://tools.ietf.org/html/rfc5389#section-11) support [#48](https://github.com/pion/stun/issues/48) - -#### Compatability notes - -[RFC 5389][rfc5389] obsoletes [RFC 3489][rfc3489], so implementation was ignored by purpose, however, -[RFC 3489][rfc3489] can be easily implemented as separate package. - -[rfc3489]: https://tools.ietf.org/html/rfc3489 -[rfc5389]: https://tools.ietf.org/html/rfc5389 -[rfc5769]: https://tools.ietf.org/html/rfc5769 -[rfc5780]: https://tools.ietf.org/html/rfc5780 -[rfc6062]: https://tools.ietf.org/html/rfc6062 -[rfc7064]: https://tools.ietf.org/html/rfc7064 -[rfc7065]: https://tools.ietf.org/html/rfc7065 - -### Stability +# Stability Package is currently stable, no backward incompatible changes are expected with exception of critical bugs or security fixes. Additional attributes are unlikely to be implemented in scope of stun package, the only exception is constants for attribute or message types. -### Requirements +# RFC 3489 notes +RFC 5389 obsoletes RFC 3489, so implementation was ignored by purpose, however, +RFC 3489 can be easily implemented as separate package. + +# Requirements Go 1.12 is currently supported and tested in CI. -### Testing +# Testing Client behavior is tested and verified in many ways: * End-To-End with long-term credentials * **coturn**: The coturn [server](https://github.com/coturn/coturn/wiki/turnserver) (linux) @@ -111,76 +123,62 @@ See [TeamCity project](https://tc.gortc.io/project.html?projectId=stun&guest=1) for more information. Also the Wireshark `.pcap` files are available for e2e test in artifacts for build. -### Benchmarks +# Benchmarks + Intel(R) Core(TM) i7-8700K: ``` -version: 1.22.2 +version: 1.16.5 goos: linux goarch: amd64 pkg: github.com/pion/stun PASS benchmark iter time/iter throughput bytes alloc allocs --------- ---- --------- ---------- ----------- ------ -BenchmarkMappedAddress_AddTo-12 32489450 38.30 ns/op 0 B/op 0 allocs/op -BenchmarkAlternateServer_AddTo-12 31230991 39.00 ns/op 0 B/op 0 allocs/op -BenchmarkAgent_GC-12 431390 2918.00 ns/op 0 B/op 0 allocs/op -BenchmarkAgent_Process-12 35901940 36.20 ns/op 0 B/op 0 allocs/op -BenchmarkMessage_GetNotFound-12 242004358 5.19 ns/op 0 B/op 0 allocs/op -BenchmarkMessage_Get-12 230520343 5.21 ns/op 0 B/op 0 allocs/op -BenchmarkClient_Do-12 1282231 943.00 ns/op 0 B/op 0 allocs/op -BenchmarkErrorCode_AddTo-12 16318916 75.50 ns/op 0 B/op 0 allocs/op -BenchmarkErrorCodeAttribute_AddTo-12 21584140 54.80 ns/op 0 B/op 0 allocs/op -BenchmarkErrorCodeAttribute_GetFrom-12 100000000 11.10 ns/op 0 B/op 0 allocs/op -BenchmarkFingerprint_AddTo-12 19368768 64.00 ns/op 687.81 MB/s 0 B/op 0 allocs/op -BenchmarkFingerprint_Check-12 24167007 49.10 ns/op 1057.99 MB/s 0 B/op 0 allocs/op -BenchmarkBuildOverhead/Build-12 5486252 224.00 ns/op 0 B/op 0 allocs/op -BenchmarkBuildOverhead/BuildNonPointer-12 2496544 517.00 ns/op 100 B/op 4 allocs/op -BenchmarkBuildOverhead/Raw-12 6652118 181.00 ns/op 0 B/op 0 allocs/op -BenchmarkMessage_ForEach-12 28254212 35.90 ns/op 0 B/op 0 allocs/op -BenchmarkMessageIntegrity_AddTo-12 1000000 1179.00 ns/op 16.96 MB/s 0 B/op 0 allocs/op -BenchmarkMessageIntegrity_Check-12 975954 1219.00 ns/op 26.24 MB/s 0 B/op 0 allocs/op -BenchmarkMessage_Write-12 41040598 30.40 ns/op 922.13 MB/s 0 B/op 0 allocs/op -BenchmarkMessageType_Value-12 1000000000 0.53 ns/op 0 B/op 0 allocs/op -BenchmarkMessage_WriteTo-12 94942935 11.30 ns/op 0 B/op 0 allocs/op -BenchmarkMessage_ReadFrom-12 43437718 29.30 ns/op 682.87 MB/s 0 B/op 0 allocs/op -BenchmarkMessage_ReadBytes-12 74693397 15.90 ns/op 1257.42 MB/s 0 B/op 0 allocs/op -BenchmarkIsMessage-12 1000000000 1.20 ns/op 16653.64 MB/s 0 B/op 0 allocs/op -BenchmarkMessage_NewTransactionID-12 521121 2450.00 ns/op 0 B/op 0 allocs/op -BenchmarkMessageFull-12 5389495 221.00 ns/op 0 B/op 0 allocs/op -BenchmarkMessageFullHardcore-12 12715876 94.40 ns/op 0 B/op 0 allocs/op -BenchmarkMessage_WriteHeader-12 100000000 11.60 ns/op 0 B/op 0 allocs/op -BenchmarkMessage_CloneTo-12 30199020 41.80 ns/op 1626.66 MB/s 0 B/op 0 allocs/op -BenchmarkMessage_AddTo-12 415257625 2.97 ns/op 0 B/op 0 allocs/op -BenchmarkDecode-12 49573747 23.60 ns/op 0 B/op 0 allocs/op -BenchmarkUsername_AddTo-12 56282674 22.50 ns/op 0 B/op 0 allocs/op -BenchmarkUsername_GetFrom-12 100000000 10.10 ns/op 0 B/op 0 allocs/op -BenchmarkNonce_AddTo-12 39419097 35.80 ns/op 0 B/op 0 allocs/op -BenchmarkNonce_AddTo_BadLength-12 196291666 6.04 ns/op 0 B/op 0 allocs/op -BenchmarkNonce_GetFrom-12 120857732 9.93 ns/op 0 B/op 0 allocs/op -BenchmarkUnknownAttributes/AddTo-12 28881430 37.20 ns/op 0 B/op 0 allocs/op -BenchmarkUnknownAttributes/GetFrom-12 64907534 19.80 ns/op 0 B/op 0 allocs/op -BenchmarkXOR-12 32868506 32.20 ns/op 31836.66 MB/s -BenchmarkXORSafe-12 5185776 234.00 ns/op 4378.74 MB/s -BenchmarkXORFast-12 30975679 32.50 ns/op 31525.28 MB/s -BenchmarkXORMappedAddress_AddTo-12 21518028 54.50 ns/op 0 B/op 0 allocs/op -BenchmarkXORMappedAddress_GetFrom-12 35597667 34.40 ns/op 0 B/op 0 allocs/op -ok github.com/pion/stun 60.973s +BenchmarkMappedAddress_AddTo-12 30000000 36.40 ns/op 0 B/op 0 allocs/op +BenchmarkAlternateServer_AddTo-12 50000000 36.70 ns/op 0 B/op 0 allocs/op +BenchmarkAgent_GC-12 500000 2552.00 ns/op 0 B/op 0 allocs/op +BenchmarkAgent_Process-12 50000000 38.00 ns/op 0 B/op 0 allocs/op +BenchmarkMessage_GetNotFound-12 200000000 6.90 ns/op 0 B/op 0 allocs/op +BenchmarkMessage_Get-12 200000000 7.61 ns/op 0 B/op 0 allocs/op +BenchmarkClient_Do-12 2000000 1072.00 ns/op 0 B/op 0 allocs/op +BenchmarkErrorCode_AddTo-12 20000000 67.00 ns/op 0 B/op 0 allocs/op +BenchmarkErrorCodeAttribute_AddTo-12 30000000 52.20 ns/op 0 B/op 0 allocs/op +BenchmarkErrorCodeAttribute_GetFrom-12 100000000 12.00 ns/op 0 B/op 0 allocs/op +BenchmarkFingerprint_AddTo-12 20000000 102.00 ns/op 430.08 MB/s 0 B/op 0 allocs/op +BenchmarkFingerprint_Check-12 30000000 54.80 ns/op 948.38 MB/s 0 B/op 0 allocs/op +BenchmarkBuildOverhead/Build-12 5000000 333.00 ns/op 0 B/op 0 allocs/op +BenchmarkBuildOverhead/BuildNonPointer-12 3000000 536.00 ns/op 100 B/op 4 allocs/op +BenchmarkBuildOverhead/Raw-12 10000000 181.00 ns/op 0 B/op 0 allocs/op +BenchmarkMessageIntegrity_AddTo-12 1000000 1053.00 ns/op 18.98 MB/s 0 B/op 0 allocs/op +BenchmarkMessageIntegrity_Check-12 1000000 1135.00 ns/op 28.17 MB/s 0 B/op 0 allocs/op +BenchmarkMessage_Write-12 100000000 27.70 ns/op 1011.09 MB/s 0 B/op 0 allocs/op +BenchmarkMessageType_Value-12 2000000000 0.49 ns/op 0 B/op 0 allocs/op +BenchmarkMessage_WriteTo-12 100000000 12.80 ns/op 0 B/op 0 allocs/op +BenchmarkMessage_ReadFrom-12 50000000 25.00 ns/op 801.19 MB/s 0 B/op 0 allocs/op +BenchmarkMessage_ReadBytes-12 100000000 18.00 ns/op 1113.03 MB/s 0 B/op 0 allocs/op +BenchmarkIsMessage-12 2000000000 1.08 ns/op 18535.57 MB/s 0 B/op 0 allocs/op +BenchmarkMessage_NewTransactionID-12 2000000 673.00 ns/op 0 B/op 0 allocs/op +BenchmarkMessageFull-12 5000000 316.00 ns/op 0 B/op 0 allocs/op +BenchmarkMessageFullHardcore-12 20000000 88.90 ns/op 0 B/op 0 allocs/op +BenchmarkMessage_WriteHeader-12 200000000 8.18 ns/op 0 B/op 0 allocs/op +BenchmarkMessage_CloneTo-12 30000000 37.90 ns/op 1795.32 MB/s 0 B/op 0 allocs/op +BenchmarkMessage_AddTo-12 300000000 4.77 ns/op 0 B/op 0 allocs/op +BenchmarkDecode-12 100000000 22.00 ns/op 0 B/op 0 allocs/op +BenchmarkUsername_AddTo-12 50000000 23.20 ns/op 0 B/op 0 allocs/op +BenchmarkUsername_GetFrom-12 100000000 17.90 ns/op 0 B/op 0 allocs/op +BenchmarkNonce_AddTo-12 50000000 34.40 ns/op 0 B/op 0 allocs/op +BenchmarkNonce_AddTo_BadLength-12 200000000 8.29 ns/op 0 B/op 0 allocs/op +BenchmarkNonce_GetFrom-12 100000000 17.50 ns/op 0 B/op 0 allocs/op +BenchmarkUnknownAttributes/AddTo-12 30000000 48.10 ns/op 0 B/op 0 allocs/op +BenchmarkUnknownAttributes/GetFrom-12 100000000 20.90 ns/op 0 B/op 0 allocs/op +BenchmarkXOR-12 50000000 25.80 ns/op 39652.86 MB/s 0 B/op 0 allocs/op +BenchmarkXORSafe-12 3000000 515.00 ns/op 1988.04 MB/s 0 B/op 0 allocs/op +BenchmarkXORFast-12 20000000 73.40 ns/op 13959.30 MB/s 0 B/op 0 allocs/op +BenchmarkXORMappedAddress_AddTo-12 20000000 56.70 ns/op 0 B/op 0 allocs/op +BenchmarkXORMappedAddress_GetFrom-12 50000000 37.40 ns/op 0 B/op 0 allocs/op +ok github.com/pion/stun 76.868s ``` -### Roadmap -The library is used as a part of our WebRTC implementation. Please refer to that [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones. - -### Community -Pion has an active community on the [Slack](https://pion.ly/slack). - -Follow the [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news. - -We are always looking to support **your projects**. Please reach out if you have something to build! -If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly) - -### Contributing -Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible: [AUTHORS.txt](./AUTHORS.txt) - ### License MIT License - see [LICENSE](LICENSE) for full text diff --git a/vendor/github.com/pion/stun/addr.go b/vendor/github.com/pion/stun/addr.go index d15e2bbd2..c4d9653d5 100644 --- a/vendor/github.com/pion/stun/addr.go +++ b/vendor/github.com/pion/stun/addr.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun import ( @@ -29,14 +26,6 @@ type AlternateServer struct { Port int } -// ResponseOrigin represents RESPONSE-ORIGIN attribute. -// -// RFC 5780 Section 7.3 -type ResponseOrigin struct { - IP net.IP - Port int -} - // OtherAddress represents OTHER-ADDRESS attribute. // // RFC 5780 Section 7.4 @@ -48,21 +37,20 @@ type OtherAddress struct { // AddTo adds ALTERNATE-SERVER attribute to message. func (s *AlternateServer) AddTo(m *Message) error { a := (*MappedAddress)(s) - return a.AddToAs(m, AttrAlternateServer) + return a.addAs(m, AttrAlternateServer) } // GetFrom decodes ALTERNATE-SERVER from message. func (s *AlternateServer) GetFrom(m *Message) error { a := (*MappedAddress)(s) - return a.GetFromAs(m, AttrAlternateServer) + return a.getAs(m, AttrAlternateServer) } func (a MappedAddress) String() string { return net.JoinHostPort(a.IP.String(), strconv.Itoa(a.Port)) } -// GetFromAs decodes MAPPED-ADDRESS value in message m as an attribute of type t. -func (a *MappedAddress) GetFromAs(m *Message, t AttrType) error { +func (a *MappedAddress) getAs(m *Message, t AttrType) error { v, err := m.Get(t) if err != nil { return err @@ -96,8 +84,7 @@ func (a *MappedAddress) GetFromAs(m *Message, t AttrType) error { return nil } -// AddToAs adds MAPPED-ADDRESS value to m as t attribute. -func (a *MappedAddress) AddToAs(m *Message, t AttrType) error { +func (a *MappedAddress) addAs(m *Message, t AttrType) error { var ( family = familyIPv4 ip = a.IP @@ -122,42 +109,26 @@ func (a *MappedAddress) AddToAs(m *Message, t AttrType) error { // AddTo adds MAPPED-ADDRESS to message. func (a *MappedAddress) AddTo(m *Message) error { - return a.AddToAs(m, AttrMappedAddress) + return a.addAs(m, AttrMappedAddress) } // GetFrom decodes MAPPED-ADDRESS from message. func (a *MappedAddress) GetFrom(m *Message) error { - return a.GetFromAs(m, AttrMappedAddress) + return a.getAs(m, AttrMappedAddress) } // AddTo adds OTHER-ADDRESS attribute to message. func (o *OtherAddress) AddTo(m *Message) error { a := (*MappedAddress)(o) - return a.AddToAs(m, AttrOtherAddress) + return a.addAs(m, AttrOtherAddress) } // GetFrom decodes OTHER-ADDRESS from message. func (o *OtherAddress) GetFrom(m *Message) error { a := (*MappedAddress)(o) - return a.GetFromAs(m, AttrOtherAddress) + return a.getAs(m, AttrOtherAddress) } func (o OtherAddress) String() string { return net.JoinHostPort(o.IP.String(), strconv.Itoa(o.Port)) } - -// AddTo adds RESPONSE-ORIGIN attribute to message. -func (o *ResponseOrigin) AddTo(m *Message) error { - a := (*MappedAddress)(o) - return a.AddToAs(m, AttrResponseOrigin) -} - -// GetFrom decodes RESPONSE-ORIGIN from message. -func (o *ResponseOrigin) GetFrom(m *Message) error { - a := (*MappedAddress)(o) - return a.GetFromAs(m, AttrResponseOrigin) -} - -func (o ResponseOrigin) String() string { - return net.JoinHostPort(o.IP.String(), strconv.Itoa(o.Port)) -} diff --git a/vendor/github.com/pion/stun/agent.go b/vendor/github.com/pion/stun/agent.go index f03efa3c0..6a8a47352 100644 --- a/vendor/github.com/pion/stun/agent.go +++ b/vendor/github.com/pion/stun/agent.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun import ( @@ -10,15 +7,13 @@ import ( ) // NoopHandler just discards any event. -func NoopHandler() Handler { - return func(e Event) {} -} +var NoopHandler Handler = func(e Event) {} // NewAgent initializes and returns new Agent with provided handler. // If h is nil, the NoopHandler will be used. func NewAgent(h Handler) *Agent { if h == nil { - h = NoopHandler() + h = NoopHandler } a := &Agent{ transactions: make(map[transactionID]agentTransaction), diff --git a/vendor/github.com/pion/stun/appveyor.yml b/vendor/github.com/pion/stun/appveyor.yml new file mode 100644 index 000000000..664099d5a --- /dev/null +++ b/vendor/github.com/pion/stun/appveyor.yml @@ -0,0 +1,22 @@ +version: "{build}" + +platform: x64 + +branches: + only: + - master + +skip_tags: true + +clone_folder: c:\gopath\src\github.com\pion\stun + +environment: + GOPATH: c:\gopath + GOVERSION: 1.12 + +install: + - go version + - go get -v -t . + +build_script: + - go test -v . diff --git a/vendor/github.com/pion/stun/attributes.go b/vendor/github.com/pion/stun/attributes.go index 8a1aa214c..7238234a7 100644 --- a/vendor/github.com/pion/stun/attributes.go +++ b/vendor/github.com/pion/stun/attributes.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun import ( @@ -79,20 +76,8 @@ const ( // Attributes from RFC 5780 NAT Behavior Discovery const ( - AttrChangeRequest AttrType = 0x0003 // CHANGE-REQUEST - AttrPadding AttrType = 0x0026 // PADDING - AttrResponsePort AttrType = 0x0027 // RESPONSE-PORT - AttrCacheTimeout AttrType = 0x8027 // CACHE-TIMEOUT - AttrResponseOrigin AttrType = 0x802b // RESPONSE-ORIGIN - AttrOtherAddress AttrType = 0x802C // OTHER-ADDRESS -) - -// Attributes from RFC 3489, removed by RFC 5389, -// -// but still used by RFC5389-implementing software like Vovida.org, reTURNServer, etc. -const ( - AttrSourceAddress AttrType = 0x0004 // SOURCE-ADDRESS - AttrChangedAddress AttrType = 0x0005 // CHANGED-ADDRESS + AttrOtherAddress AttrType = 0x802C // OTHER-ADDRESS + AttrChangeRequest AttrType = 0x0003 // CHANGE-REQUEST ) // Attributes from RFC 6062 TURN Extensions for TCP Allocations. @@ -110,58 +95,45 @@ const ( AttrOrigin AttrType = 0x802F ) -// Attributes from RFC 8489 STUN. -const ( - AttrMessageIntegritySHA256 AttrType = 0x001C // MESSAGE-INTEGRITY-SHA256 - AttrPasswordAlgorithm AttrType = 0x001D // PASSWORD-ALGORITHM - AttrUserhash AttrType = 0x001E // USERHASH - AttrPasswordAlgorithms AttrType = 0x8002 // PASSWORD-ALGORITHMS - AttrAlternateDomain AttrType = 0x8003 // ALTERNATE-DOMAIN -) - // Value returns uint16 representation of attribute type. func (t AttrType) Value() uint16 { return uint16(t) } -func attrNames() map[AttrType]string { - return map[AttrType]string{ - AttrMappedAddress: "MAPPED-ADDRESS", - AttrUsername: "USERNAME", - AttrErrorCode: "ERROR-CODE", - AttrMessageIntegrity: "MESSAGE-INTEGRITY", - AttrUnknownAttributes: "UNKNOWN-ATTRIBUTES", - AttrRealm: "REALM", - AttrNonce: "NONCE", - AttrXORMappedAddress: "XOR-MAPPED-ADDRESS", - AttrSoftware: "SOFTWARE", - AttrAlternateServer: "ALTERNATE-SERVER", - AttrFingerprint: "FINGERPRINT", - AttrPriority: "PRIORITY", - AttrUseCandidate: "USE-CANDIDATE", - AttrICEControlled: "ICE-CONTROLLED", - AttrICEControlling: "ICE-CONTROLLING", - AttrChannelNumber: "CHANNEL-NUMBER", - AttrLifetime: "LIFETIME", - AttrXORPeerAddress: "XOR-PEER-ADDRESS", - AttrData: "DATA", - AttrXORRelayedAddress: "XOR-RELAYED-ADDRESS", - AttrEvenPort: "EVEN-PORT", - AttrRequestedTransport: "REQUESTED-TRANSPORT", - AttrDontFragment: "DONT-FRAGMENT", - AttrReservationToken: "RESERVATION-TOKEN", - AttrConnectionID: "CONNECTION-ID", - AttrRequestedAddressFamily: "REQUESTED-ADDRESS-FAMILY", - AttrMessageIntegritySHA256: "MESSAGE-INTEGRITY-SHA256", - AttrPasswordAlgorithm: "PASSWORD-ALGORITHM", - AttrUserhash: "USERHASH", - AttrPasswordAlgorithms: "PASSWORD-ALGORITHMS", - AttrAlternateDomain: "ALTERNATE-DOMAIN", - } +var attrNames = map[AttrType]string{ + AttrMappedAddress: "MAPPED-ADDRESS", + AttrUsername: "USERNAME", + AttrErrorCode: "ERROR-CODE", + AttrMessageIntegrity: "MESSAGE-INTEGRITY", + AttrUnknownAttributes: "UNKNOWN-ATTRIBUTES", + AttrRealm: "REALM", + AttrNonce: "NONCE", + AttrXORMappedAddress: "XOR-MAPPED-ADDRESS", + AttrSoftware: "SOFTWARE", + AttrAlternateServer: "ALTERNATE-SERVER", + AttrOtherAddress: "OTHER-ADDRESS", + AttrChangeRequest: "CHANGE-REQUEST", + AttrFingerprint: "FINGERPRINT", + AttrPriority: "PRIORITY", + AttrUseCandidate: "USE-CANDIDATE", + AttrICEControlled: "ICE-CONTROLLED", + AttrICEControlling: "ICE-CONTROLLING", + AttrChannelNumber: "CHANNEL-NUMBER", + AttrLifetime: "LIFETIME", + AttrXORPeerAddress: "XOR-PEER-ADDRESS", + AttrData: "DATA", + AttrXORRelayedAddress: "XOR-RELAYED-ADDRESS", + AttrEvenPort: "EVEN-PORT", + AttrRequestedTransport: "REQUESTED-TRANSPORT", + AttrDontFragment: "DONT-FRAGMENT", + AttrReservationToken: "RESERVATION-TOKEN", + AttrConnectionID: "CONNECTION-ID", + AttrRequestedAddressFamily: "REQUESTED-ADDRESS-FAMILY", + AttrOrigin: "ORIGIN", } func (t AttrType) String() string { - s, ok := attrNames()[t] + s, ok := attrNames[t] if !ok { // Just return hex representation of unknown attribute type. return fmt.Sprintf("0x%x", uint16(t)) @@ -247,8 +219,8 @@ func nearestPaddedValueLength(l int) int { // type value, it also translates it to the new value to enable backward // compatibility. (See: https://github.com/pion/stun/issues/21) func compatAttrType(val uint16) AttrType { - if val == 0x8020 { // draft-ietf-behave-rfc3489bis-02, MS-TURN - return AttrXORMappedAddress // new: 0x0020 (from draft-ietf-behave-rfc3489bis-03 on) + if val == 0x8020 { + return AttrXORMappedAddress // new: 0x0020 } return AttrType(val) } diff --git a/vendor/github.com/pion/stun/attributes_debug.go b/vendor/github.com/pion/stun/attributes_debug.go index 836d79f13..7bf09af7c 100644 --- a/vendor/github.com/pion/stun/attributes_debug.go +++ b/vendor/github.com/pion/stun/attributes_debug.go @@ -1,7 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -//go:build debug // +build debug package stun diff --git a/vendor/github.com/pion/stun/checks.go b/vendor/github.com/pion/stun/checks.go index 6b678a06b..a7609973a 100644 --- a/vendor/github.com/pion/stun/checks.go +++ b/vendor/github.com/pion/stun/checks.go @@ -1,16 +1,8 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -//go:build !debug // +build !debug package stun -import ( - "errors" - - "github.com/pion/stun/internal/hmac" -) +import "github.com/pion/stun/internal/hmac" // CheckSize returns ErrAttrSizeInvalid if got is not equal to expected. func CheckSize(_ AttrType, got, expected int) error { @@ -36,7 +28,7 @@ func checkFingerprint(got, expected uint32) error { // IsAttrSizeInvalid returns true if error means that attribute size is invalid. func IsAttrSizeInvalid(err error) bool { - return errors.Is(err, ErrAttributeSizeInvalid) + return err == ErrAttributeSizeInvalid } // CheckOverflow returns ErrAttributeSizeOverflow if got is bigger that max. @@ -49,5 +41,5 @@ func CheckOverflow(_ AttrType, got, max int) error { // IsAttrSizeOverflow returns true if error means that attribute size is too big. func IsAttrSizeOverflow(err error) bool { - return errors.Is(err, ErrAttributeSizeOverflow) + return err == ErrAttributeSizeOverflow } diff --git a/vendor/github.com/pion/stun/checks_debug.go b/vendor/github.com/pion/stun/checks_debug.go index 0b5c67c83..955f555b0 100644 --- a/vendor/github.com/pion/stun/checks_debug.go +++ b/vendor/github.com/pion/stun/checks_debug.go @@ -1,7 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -//go:build debug // +build debug package stun diff --git a/vendor/github.com/pion/stun/client.go b/vendor/github.com/pion/stun/client.go index 5d02e51dc..62a0b6eb0 100644 --- a/vendor/github.com/pion/stun/client.go +++ b/vendor/github.com/pion/stun/client.go @@ -1,29 +1,17 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun import ( - "crypto/tls" "errors" "fmt" "io" "log" "net" "runtime" - "strconv" "sync" "sync/atomic" "time" - - "github.com/pion/dtls/v2" - "github.com/pion/transport/v2" - "github.com/pion/transport/v2/stdnet" ) -// ErrUnsupportedURI is an error thrown if the user passes an unsupported STUN or TURN URI -var ErrUnsupportedURI = fmt.Errorf("invalid schema or transport") - // Dial connects to the address on the named network and then // initializes Client on that connection, returning error if any. func Dial(network, address string) (*Client, error) { @@ -34,77 +22,6 @@ func Dial(network, address string) (*Client, error) { return NewClient(conn) } -// DialConfig is used to pass configuration to DialURI() -type DialConfig struct { - DTLSConfig dtls.Config - TLSConfig tls.Config - - Net transport.Net -} - -// DialURI connect to the STUN/TURN URI and then -// initializes Client on that connection, returning error if any. -func DialURI(uri *URI, cfg *DialConfig) (*Client, error) { - var conn Connection - var err error - - nw := cfg.Net - if nw == nil { - nw, err = stdnet.NewNet() - if err != nil { - return nil, fmt.Errorf("failed to create net: %w", err) - } - } - - addr := net.JoinHostPort(uri.Host, strconv.Itoa(uri.Port)) - - switch { - case uri.Scheme == SchemeTypeSTUN: - if conn, err = nw.Dial("udp", addr); err != nil { - return nil, fmt.Errorf("failed to listen: %w", err) - } - - case uri.Scheme == SchemeTypeTURN: - network := "udp" //nolint:goconst - if uri.Proto == ProtoTypeTCP { - network = "tcp" //nolint:goconst - } - - if conn, err = nw.Dial(network, addr); err != nil { - return nil, fmt.Errorf("failed to dial: %w", err) - } - - case uri.Scheme == SchemeTypeTURNS && uri.Proto == ProtoTypeUDP: - dtlsCfg := cfg.DTLSConfig // Copy - dtlsCfg.ServerName = uri.Host - - udpConn, err := nw.Dial("udp", addr) - if err != nil { - return nil, fmt.Errorf("failed to dial: %w", err) - } - - if conn, err = dtls.Client(udpConn, &dtlsCfg); err != nil { - return nil, fmt.Errorf("failed to connect to '%s': %w", addr, err) - } - - case (uri.Scheme == SchemeTypeTURNS || uri.Scheme == SchemeTypeSTUNS) && uri.Proto == ProtoTypeTCP: - tlsCfg := cfg.TLSConfig //nolint:govet - tlsCfg.ServerName = uri.Host - - tcpConn, err := nw.Dial("tcp", addr) - if err != nil { - return nil, fmt.Errorf("failed to dial: %w", err) - } - - conn = tls.Client(tcpConn, &tlsCfg) - - default: - return nil, ErrUnsupportedURI - } - - return NewClient(conn) -} - // ErrNoConnection means that ClientOptions.Connection is nil. var ErrNoConnection = errors.New("no connection provided") @@ -162,10 +79,8 @@ func WithCollector(coll Collector) ClientOption { // WithNoConnClose prevents client from closing underlying connection when // the Close() method is called. -func WithNoConnClose() ClientOption { - return func(c *Client) { - c.closeConn = false - } +var WithNoConnClose ClientOption = func(c *Client) { + c.closeConn = false } // WithNoRetransmit disables retransmissions and sets RTO to @@ -201,7 +116,7 @@ func NewClient(conn Connection, options ...ClientOption) (*Client, error) { c := &Client{ close: make(chan struct{}), c: conn, - clock: systemClock(), + clock: systemClock, rto: int64(defaultRTO), rtoRate: defaultTimeoutRate, t: make(map[transactionID]*clientTransaction, 100), @@ -242,7 +157,7 @@ func clientFinalizer(c *Client) { return } err := c.Close() - if errors.Is(err, ErrClientClosed) { + if err == ErrClientClosed { return } if err == nil { @@ -310,7 +225,7 @@ func (t *clientTransaction) handle(e Event) { } } -var clientTransactionPool = &sync.Pool{ //nolint:gochecknoglobals +var clientTransactionPool = &sync.Pool{ New: func() interface{} { return &clientTransaction{ raw: make([]byte, 1500), @@ -319,7 +234,7 @@ var clientTransactionPool = &sync.Pool{ //nolint:gochecknoglobals } func acquireClientTransaction() *clientTransaction { - return clientTransactionPool.Get().(*clientTransaction) //nolint:forcetypeassert + return clientTransactionPool.Get().(*clientTransaction) } func putClientTransaction(t *clientTransaction) { @@ -360,9 +275,7 @@ type systemClockService struct{} func (systemClockService) Now() time.Time { return time.Now() } -func systemClock() systemClockService { - return systemClockService{} -} +var systemClock = systemClockService{} // SetRTO sets current RTO value. func (c *Client) SetRTO(rto time.Duration) { @@ -371,8 +284,6 @@ func (c *Client) SetRTO(rto time.Duration) { // StopErr occurs when Client fails to stop transaction while // processing error. -// -//nolint:errname type StopErr struct { Err error // value returned by Stop() Cause error // error that caused Stop() call @@ -383,8 +294,6 @@ func (e StopErr) Error() string { } // CloseErr indicates client close failure. -// -//nolint:errname type CloseErr struct { AgentErr error ConnectionErr error @@ -392,7 +301,7 @@ type CloseErr struct { func sprintErr(err error) string { if err == nil { - return "" //nolint:goconst + return "" } return err.Error() } @@ -413,7 +322,7 @@ func (c *Client) readUntilClosed() { } _, err := m.ReadFrom(c.c) if err == nil { - if pErr := c.a.Process(m); errors.Is(pErr, ErrAgentClosed) { + if pErr := c.a.Process(m); pErr == ErrAgentClosed { return } } @@ -421,10 +330,10 @@ func (c *Client) readUntilClosed() { } func closedOrPanic(err error) { - if err == nil || errors.Is(err, ErrAgentClosed) { + if err == nil || err == ErrAgentClosed { return } - panic(err) //nolint + panic(err) // nolint } type tickerCollector struct { @@ -516,7 +425,7 @@ type callbackWaitHandler struct { func (s *callbackWaitHandler) HandleEvent(e Event) { s.cond.L.Lock() if s.callback == nil { - panic("s.callback is nil") //nolint + panic("s.callback is nil") // nolint } s.callback(e) s.processed = true @@ -536,7 +445,7 @@ func (s *callbackWaitHandler) wait() { func (s *callbackWaitHandler) setCallback(f func(event Event)) { if f == nil { - panic("f is nil") //nolint + panic("f is nil") // nolint } s.cond.L.Lock() s.callback = f @@ -546,7 +455,7 @@ func (s *callbackWaitHandler) setCallback(f func(event Event)) { s.cond.L.Unlock() } -var callbackWaitHandlerPool = sync.Pool{ //nolint:gochecknoglobals +var callbackWaitHandlerPool = sync.Pool{ New: func() interface{} { return &callbackWaitHandler{ cond: sync.NewCond(new(sync.Mutex)), @@ -576,7 +485,7 @@ func (c *Client) Do(m *Message, f func(Event)) error { if f == nil { return c.Indicate(m) } - h := callbackWaitHandlerPool.Get().(*callbackWaitHandler) //nolint:forcetypeassert + h := callbackWaitHandlerPool.Get().(*callbackWaitHandler) h.setCallback(f) defer func() { callbackWaitHandlerPool.Put(h) @@ -600,7 +509,7 @@ type buffer struct { buf []byte } -var bufferPool = &sync.Pool{ //nolint:gochecknoglobals +var bufferPool = &sync.Pool{ New: func() interface{} { return &buffer{buf: make([]byte, 2048)} }, @@ -618,7 +527,7 @@ func (c *Client) handleAgentCallback(e Event) { } c.mux.Unlock() if !found { - if c.handler != nil && !errors.Is(e.Error, ErrTransactionStopped) { + if c.handler != nil && e.Error != ErrTransactionStopped { c.handler(e) } // Ignoring. @@ -632,7 +541,7 @@ func (c *Client) handleAgentCallback(e Event) { } // Doing re-transmission. t.attempt++ - b := bufferPool.Get().(*buffer) //nolint:forcetypeassert + b := bufferPool.Get().(*buffer) b.buf = b.buf[:copy(b.buf[:cap(b.buf)], t.raw)] defer bufferPool.Put(b) var ( diff --git a/vendor/github.com/pion/stun/codecov.yml b/vendor/github.com/pion/stun/codecov.yml deleted file mode 100644 index 263e4d45c..000000000 --- a/vendor/github.com/pion/stun/codecov.yml +++ /dev/null @@ -1,22 +0,0 @@ -# -# DO NOT EDIT THIS FILE -# -# It is automatically copied from https://github.com/pion/.goassets repository. -# -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - -coverage: - status: - project: - default: - # Allow decreasing 2% of total coverage to avoid noise. - threshold: 2% - patch: - default: - target: 70% - only_pulls: true - -ignore: - - "examples/*" - - "examples/**/*" diff --git a/vendor/github.com/pion/stun/errorcode.go b/vendor/github.com/pion/stun/errorcode.go index c852eed69..8095048cd 100644 --- a/vendor/github.com/pion/stun/errorcode.go +++ b/vendor/github.com/pion/stun/errorcode.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun import ( @@ -32,7 +29,7 @@ const ( // AddTo adds ERROR-CODE to m. func (c ErrorCodeAttribute) AddTo(m *Message) error { - value := make([]byte, 0, errorCodeReasonStart+errorCodeReasonMaxB) + value := make([]byte, 0, errorCodeReasonMaxB) if err := CheckOverflow(AttrErrorCode, len(c.Reason)+errorCodeReasonStart, errorCodeReasonMaxB+errorCodeReasonStart, @@ -134,7 +131,6 @@ const ( CodePeerAddrFamilyMismatch ErrorCode = 443 // Peer Address Family Mismatch ) -//nolint:gochecknoglobals var errorReasons = map[ErrorCode][]byte{ CodeTryAlternate: []byte("Try Alternate"), CodeBadRequest: []byte("Bad Request"), diff --git a/vendor/github.com/pion/stun/errors.go b/vendor/github.com/pion/stun/errors.go index d5f59edd6..029c9e426 100644 --- a/vendor/github.com/pion/stun/errors.go +++ b/vendor/github.com/pion/stun/errors.go @@ -1,13 +1,8 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun import "errors" // DecodeErr records an error and place when it is occurred. -// -//nolint:errname type DecodeErr struct { Place DecodeErrPlace Message string @@ -55,6 +50,7 @@ func newDecodeErr(parent, children, message string) *DecodeErr { } } +// TODO(ar): rewrite errors to be more precise. func newAttrDecodeErr(children, message string) *DecodeErr { return newDecodeErr("attribute", children, message) } diff --git a/vendor/github.com/pion/stun/fingerprint.go b/vendor/github.com/pion/stun/fingerprint.go index b4126d267..aef80a206 100644 --- a/vendor/github.com/pion/stun/fingerprint.go +++ b/vendor/github.com/pion/stun/fingerprint.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun import ( @@ -20,9 +17,9 @@ var ErrFingerprintMismatch = errors.New("fingerprint check failed") // // Example: // -// m := New() -// Fingerprint.AddTo(m) -var Fingerprint FingerprintAttr //nolint:gochecknoglobals +// m := New() +// Fingerprint.AddTo(m) +var Fingerprint FingerprintAttr const ( fingerprintXORValue uint32 = 0x5354554e //nolint:staticcheck diff --git a/vendor/github.com/pion/stun/fingerprint_debug.go b/vendor/github.com/pion/stun/fingerprint_debug.go index 0e3471db8..6da074cd8 100644 --- a/vendor/github.com/pion/stun/fingerprint_debug.go +++ b/vendor/github.com/pion/stun/fingerprint_debug.go @@ -1,7 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -//go:build debug // +build debug package stun diff --git a/vendor/github.com/pion/stun/fuzz.go b/vendor/github.com/pion/stun/fuzz.go new file mode 100644 index 000000000..debfa8d1c --- /dev/null +++ b/vendor/github.com/pion/stun/fuzz.go @@ -0,0 +1,140 @@ +// +build gofuzz + +package stun + +import ( + "encoding/binary" + "fmt" +) + +var ( + m = New() +) + +// FuzzMessage is go-fuzz endpoint for message. +func FuzzMessage(data []byte) int { + m.Reset() + // fuzzer dont know about cookies + binary.BigEndian.PutUint32(data[4:8], magicCookie) + // trying to read data as message + if _, err := m.Write(data); err != nil { + return 0 + } + m2 := New() + if _, err := m2.Write(m.Raw); err != nil { + panic(err) // nolint + } + if m2.TransactionID != m.TransactionID { + panic("transaction ID mismatch") // nolint + } + if m2.Type != m.Type { + panic("type missmatch") // nolint + } + if len(m2.Attributes) != len(m.Attributes) { + panic("attributes length missmatch") // nolint + } + return 1 +} + +// FuzzType is go-fuzz endpoint for message type. +func FuzzType(data []byte) int { + t := MessageType{} + vt, _ := binary.Uvarint(data) + v := uint16(vt) & 0x1fff // first 3 bits are empty + t.ReadValue(v) + v2 := t.Value() + if v != v2 { + panic("v != v2") // nolint + } + t2 := MessageType{} + t2.ReadValue(v2) + if t2 != t { + panic("t2 != t") // nolint + } + return 0 +} + +type attr interface { + Getter + Setter +} + +type attrs []struct { + g attr + t AttrType +} + +func (a attrs) pick(v byte) struct { + g attr + t AttrType +} { + idx := int(v) % len(a) + return a[idx] +} + +func FuzzSetters(data []byte) int { + var ( + m1 = &Message{ + Raw: make([]byte, 0, 2048), + } + m2 = &Message{ + Raw: make([]byte, 0, 2048), + } + m3 = &Message{ + Raw: make([]byte, 0, 2048), + } + ) + attributes := attrs{ + {new(Realm), AttrRealm}, + {new(XORMappedAddress), AttrXORMappedAddress}, + {new(Nonce), AttrNonce}, + {new(Software), AttrSoftware}, + {new(AlternateServer), AttrAlternateServer}, + {new(ErrorCodeAttribute), AttrErrorCode}, + {new(UnknownAttributes), AttrUnknownAttributes}, + {new(Username), AttrUsername}, + {new(MappedAddress), AttrMappedAddress}, + {new(Realm), AttrRealm}, + } + var firstByte = byte(0) + if len(data) > 0 { + firstByte = data[0] + } + a := attributes.pick(firstByte) + value := data + if len(data) > 1 { + value = value[1:] + } + m1.WriteHeader() + m1.Add(a.t, value) + err := a.g.GetFrom(m1) + if err == ErrAttributeNotFound { + fmt.Println("unexpected 404") // nolint + panic(err) // nolint + } + if err != nil { + return 1 + } + m2.WriteHeader() + if err = a.g.AddTo(m2); err != nil { + // We allow decoding some text attributes + // when their length is too big, but + // not encoding. + if !IsAttrSizeOverflow(err) { + panic(err) // nolint + } + return 1 + } + m3.WriteHeader() + v, err := m2.Get(a.t) + if err != nil { + panic(err) // nolint + } + m3.Add(a.t, v) + + if !m2.Equal(m3) { + fmt.Println(m2, "not equal", m3) // nolint + panic("not equal") // nolint + } + return 1 +} diff --git a/vendor/github.com/pion/stun/go.test.sh b/vendor/github.com/pion/stun/go.test.sh new file mode 100644 index 000000000..25234e4b3 --- /dev/null +++ b/vendor/github.com/pion/stun/go.test.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +set -e +touch coverage.txt + +# test fuzz inputs +go test -tags gofuzz -run TestFuzz -v . + +# quick-test without -race +go test ./... + +# test with "debug" tag +go test -tags debug ./... + +# test concurrency +go test -race -cpu=1,2,4 -run TestClient_DoConcurrent + +for d in $(go list ./... | grep -v vendor); do + go test -race -coverprofile=profile.out -covermode=atomic "$d" + if [[ -f profile.out ]]; then + cat profile.out >> coverage.txt + rm profile.out + fi +done diff --git a/vendor/github.com/pion/stun/helpers.go b/vendor/github.com/pion/stun/helpers.go index d4056503c..158a51dd4 100644 --- a/vendor/github.com/pion/stun/helpers.go +++ b/vendor/github.com/pion/stun/helpers.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun // Interfaces that are implemented by message attributes, shorthands for them, @@ -24,16 +21,15 @@ type ( // first error. To prevent allocations, pass pointers to values. // // Example: -// -// var ( -// t = BindingRequest -// username = NewUsername("username") -// nonce = NewNonce("nonce") -// realm = NewRealm("example.org") -// ) -// m := new(Message) -// m.Build(t, username, nonce, realm) // 4 allocations -// m.Build(&t, &username, &nonce, &realm) // 0 allocations +// var ( +// t = BindingRequest +// username = NewUsername("username") +// nonce = NewNonce("nonce") +// realm = NewRealm("example.org") +// ) +// m := new(Message) +// m.Build(t, username, nonce, realm) // 4 allocations +// m.Build(&t, &username, &nonce, &realm) // 0 allocations // // See BenchmarkBuildOverhead. func (m *Message) Build(setters ...Setter) error { @@ -71,7 +67,7 @@ func (m *Message) Parse(getters ...Getter) error { func MustBuild(setters ...Setter) *Message { m, err := Build(setters...) if err != nil { - panic(err) //nolint + panic(err) // nolint } return m } diff --git a/vendor/github.com/pion/stun/integrity.go b/vendor/github.com/pion/stun/integrity.go index 0fee0b075..39b0d5073 100644 --- a/vendor/github.com/pion/stun/integrity.go +++ b/vendor/github.com/pion/stun/integrity.go @@ -1,11 +1,8 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun -import ( //nolint:gci - "crypto/md5" //nolint:gosec - "crypto/sha1" //nolint:gosec +import ( + "crypto/md5" // #nosec + "crypto/sha1" // #nosec "errors" "fmt" "strings" @@ -20,7 +17,8 @@ const credentialsSep = ":" // credentials. Password, username, and realm must be SASL-prepared. func NewLongTermIntegrity(username, realm, password string) MessageIntegrity { k := strings.Join([]string{username, realm, password}, credentialsSep) - h := md5.New() //nolint:gosec + // #nosec + h := md5.New() fmt.Fprint(h, k) return MessageIntegrity(h.Sum(nil)) } diff --git a/vendor/github.com/pion/stun/integrity_debug.go b/vendor/github.com/pion/stun/integrity_debug.go index 27fd0e275..6b8a30307 100644 --- a/vendor/github.com/pion/stun/integrity_debug.go +++ b/vendor/github.com/pion/stun/integrity_debug.go @@ -1,7 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -//go:build debug // +build debug package stun diff --git a/vendor/github.com/pion/stun/internal/hmac/hmac.go b/vendor/github.com/pion/stun/internal/hmac/hmac.go index b4db5c996..801ece67a 100644 --- a/vendor/github.com/pion/stun/internal/hmac/hmac.go +++ b/vendor/github.com/pion/stun/internal/hmac/hmac.go @@ -1,5 +1,6 @@ -// SPDX-FileCopyrightText: 2009 The Go Authors. All rights reserved. -// SPDX-License-Identifier: BSD-3-Clause +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. /* Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as @@ -33,37 +34,19 @@ import ( // opad = 0x5c byte repeated for key length // hmac = H([key ^ opad] H([key ^ ipad] text)) -// Marshalable is the combination of encoding.BinaryMarshaler and -// encoding.BinaryUnmarshaler. Their method definitions are repeated here to -// avoid a dependency on the encoding package. -type marshalable interface { - MarshalBinary() ([]byte, error) - UnmarshalBinary([]byte) error -} - type hmac struct { + size int + blocksize int opad, ipad []byte outer, inner hash.Hash - - // If marshaled is true, then opad and ipad do not contain a padded - // copy of the key, but rather the marshaled state of outer/inner after - // opad/ipad has been fed into it. - marshaled bool } func (h *hmac) Sum(in []byte) []byte { origLen := len(in) in = h.inner.Sum(in) - - if h.marshaled { - if err := h.outer.(marshalable).UnmarshalBinary(h.opad); err != nil { //nolint:forcetypeassert - panic(err) //nolint - } - } else { - h.outer.Reset() - h.outer.Write(h.opad) //nolint:errcheck,gosec - } - h.outer.Write(in[origLen:]) //nolint:errcheck,gosec + h.outer.Reset() + h.outer.Write(h.opad) + h.outer.Write(in[origLen:]) return h.outer.Sum(in[:origLen]) } @@ -71,51 +54,13 @@ func (h *hmac) Write(p []byte) (n int, err error) { return h.inner.Write(p) } -func (h *hmac) Size() int { return h.outer.Size() } -func (h *hmac) BlockSize() int { return h.inner.BlockSize() } +func (h *hmac) Size() int { return h.size } + +func (h *hmac) BlockSize() int { return h.blocksize } func (h *hmac) Reset() { - if h.marshaled { - if err := h.inner.(marshalable).UnmarshalBinary(h.ipad); err != nil { //nolint:forcetypeassert - panic(err) //nolint - } - return - } - h.inner.Reset() - h.inner.Write(h.ipad) //nolint:errcheck,gosec - - // If the underlying hash is marshalable, we can save some time by - // saving a copy of the hash state now, and restoring it on future - // calls to Reset and Sum instead of writing ipad/opad every time. - // - // If either hash is unmarshalable for whatever reason, - // it's safe to bail out here. - marshalableInner, innerOK := h.inner.(marshalable) - if !innerOK { - return - } - marshalableOuter, outerOK := h.outer.(marshalable) - if !outerOK { - return - } - - imarshal, err := marshalableInner.MarshalBinary() - if err != nil { - return - } - - h.outer.Reset() - h.outer.Write(h.opad) //nolint:errcheck,gosec - omarshal, err := marshalableOuter.MarshalBinary() - if err != nil { - return - } - - // Marshaling succeeded; save the marshaled state for later - h.ipad = imarshal - h.opad = omarshal - h.marshaled = true + h.inner.Write(h.ipad) } // New returns a new HMAC hash using the given hash.Hash type and key. @@ -126,12 +71,13 @@ func New(h func() hash.Hash, key []byte) hash.Hash { hm := new(hmac) hm.outer = h() hm.inner = h() - blocksize := hm.inner.BlockSize() - hm.ipad = make([]byte, blocksize) - hm.opad = make([]byte, blocksize) - if len(key) > blocksize { + hm.size = hm.inner.Size() + hm.blocksize = hm.inner.BlockSize() + hm.ipad = make([]byte, hm.blocksize) + hm.opad = make([]byte, hm.blocksize) + if len(key) > hm.blocksize { // If key is too big, hash it. - hm.outer.Write(key) //nolint:errcheck,gosec + hm.outer.Write(key) key = hm.outer.Sum(nil) } copy(hm.ipad, key) @@ -142,8 +88,7 @@ func New(h func() hash.Hash, key []byte) hash.Hash { for i := range hm.opad { hm.opad[i] ^= 0x5c } - hm.inner.Write(hm.ipad) //nolint:errcheck,gosec - + hm.inner.Write(hm.ipad) return hm } diff --git a/vendor/github.com/pion/stun/internal/hmac/pool.go b/vendor/github.com/pion/stun/internal/hmac/pool.go index d2ac14afa..4db61e540 100644 --- a/vendor/github.com/pion/stun/internal/hmac/pool.go +++ b/vendor/github.com/pion/stun/internal/hmac/pool.go @@ -1,27 +1,29 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package hmac -import ( //nolint:gci - "crypto/sha1" //nolint:gosec +import ( + "crypto/sha1" "crypto/sha256" "hash" "sync" ) +// setZeroes sets all bytes from b to zeroes. +// +// See https://github.com/golang/go/issues/5373 +func setZeroes(b []byte) { + for i := range b { + b[i] = 0 + } +} + func (h *hmac) resetTo(key []byte) { h.outer.Reset() h.inner.Reset() - blocksize := h.inner.BlockSize() - - // Reset size and zero of ipad and opad. - h.ipad = append(h.ipad[:0], make([]byte, blocksize)...) - h.opad = append(h.opad[:0], make([]byte, blocksize)...) - - if len(key) > blocksize { + setZeroes(h.ipad) + setZeroes(h.opad) + if len(key) > h.blocksize { // If key is too big, hash it. - h.outer.Write(key) //nolint:errcheck,gosec + h.outer.Write(key) key = h.outer.Sum(nil) } copy(h.ipad, key) @@ -32,12 +34,10 @@ func (h *hmac) resetTo(key []byte) { for i := range h.opad { h.opad[i] ^= 0x5c } - h.inner.Write(h.ipad) //nolint:errcheck,gosec - - h.marshaled = false + h.inner.Write(h.ipad) } -var hmacSHA1Pool = &sync.Pool{ //nolint:gochecknoglobals +var hmacSHA1Pool = &sync.Pool{ New: func() interface{} { h := New(sha1.New, make([]byte, sha1.BlockSize)) return h @@ -46,7 +46,7 @@ var hmacSHA1Pool = &sync.Pool{ //nolint:gochecknoglobals // AcquireSHA1 returns new HMAC from pool. func AcquireSHA1(key []byte) hash.Hash { - h := hmacSHA1Pool.Get().(*hmac) //nolint:forcetypeassert + h := hmacSHA1Pool.Get().(*hmac) assertHMACSize(h, sha1.Size, sha1.BlockSize) h.resetTo(key) return h @@ -54,12 +54,12 @@ func AcquireSHA1(key []byte) hash.Hash { // PutSHA1 puts h to pool. func PutSHA1(h hash.Hash) { - hm := h.(*hmac) //nolint:forcetypeassert + hm := h.(*hmac) assertHMACSize(hm, sha1.Size, sha1.BlockSize) hmacSHA1Pool.Put(hm) } -var hmacSHA256Pool = &sync.Pool{ //nolint:gochecknoglobals +var hmacSHA256Pool = &sync.Pool{ New: func() interface{} { h := New(sha256.New, make([]byte, sha256.BlockSize)) return h @@ -68,7 +68,7 @@ var hmacSHA256Pool = &sync.Pool{ //nolint:gochecknoglobals // AcquireSHA256 returns new HMAC from SHA256 pool. func AcquireSHA256(key []byte) hash.Hash { - h := hmacSHA256Pool.Get().(*hmac) //nolint:forcetypeassert + h := hmacSHA256Pool.Get().(*hmac) assertHMACSize(h, sha256.Size, sha256.BlockSize) h.resetTo(key) return h @@ -76,7 +76,7 @@ func AcquireSHA256(key []byte) hash.Hash { // PutSHA256 puts h to SHA256 pool. func PutSHA256(h hash.Hash) { - hm := h.(*hmac) //nolint:forcetypeassert + hm := h.(*hmac) assertHMACSize(hm, sha256.Size, sha256.BlockSize) hmacSHA256Pool.Put(hm) } @@ -85,8 +85,8 @@ func PutSHA256(h hash.Hash) { // // Put and Acquire functions are internal functions to project, so // checking it via such assert is optimal. -func assertHMACSize(h *hmac, size, blocksize int) { //nolint:unparam - if h.Size() != size || h.BlockSize() != blocksize { - panic("BUG: hmac size invalid") //nolint +func assertHMACSize(h *hmac, size, blocksize int) { + if h.size != size || h.blocksize != blocksize { + panic("BUG: hmac size invalid") // nolint } } diff --git a/vendor/github.com/pion/stun/internal/hmac/vendor.sh b/vendor/github.com/pion/stun/internal/hmac/vendor.sh index 190d2b9b7..83a2b32d3 100644 --- a/vendor/github.com/pion/stun/internal/hmac/vendor.sh +++ b/vendor/github.com/pion/stun/internal/hmac/vendor.sh @@ -1,7 +1,4 @@ -#!/bin/env bash - -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - +#!/bin/bash cp -v $GOROOT/src/crypto/hmac/{hmac,hmac_test}.go . git diff {hmac,hmac_test}.go + diff --git a/vendor/github.com/pion/stun/message.go b/vendor/github.com/pion/stun/message.go index 6a828d68b..381923530 100644 --- a/vendor/github.com/pion/stun/message.go +++ b/vendor/github.com/pion/stun/message.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun import ( @@ -66,7 +63,7 @@ func Decode(data []byte, m *Message) error { // buffering to enable zero-allocation encoding and decoding, // so there are some usage constraints: // -// Message, its fields, results of m.Get or any attribute a.GetFrom +// Message, its fields, results of m.Get or any attribute a.GetFrom // are valid only until Message.Raw is not modified. type Message struct { Type MessageType @@ -76,32 +73,6 @@ type Message struct { Raw []byte } -// MarshalBinary implements the encoding.BinaryMarshaler interface. -func (m Message) MarshalBinary() (data []byte, err error) { - // We can't return m.Raw, allocation is expected by implicit interface - // contract induced by other implementations. - b := make([]byte, len(m.Raw)) - copy(b, m.Raw) - return b, nil -} - -// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. -func (m *Message) UnmarshalBinary(data []byte) error { - // We can't retain data, copy is expected by interface contract. - m.Raw = append(m.Raw[:0], data...) - return m.Decode() -} - -// GobEncode implements the gob.GobEncoder interface. -func (m Message) GobEncode() ([]byte, error) { - return m.MarshalBinary() -} - -// GobDecode implements the gob.GobDecoder interface. -func (m *Message) GobDecode(data []byte) error { - return m.UnmarshalBinary(data) -} - // AddTo sets b.TransactionID to m.TransactionID. // // Implements Setter to aid in crafting responses. @@ -123,11 +94,7 @@ func (m *Message) NewTransactionID() error { func (m *Message) String() string { tID := base64.StdEncoding.EncodeToString(m.TransactionID[:]) - aInfo := "" - for k, a := range m.Attributes { - aInfo += fmt.Sprintf("attr%d=%s ", k, a.Type) - } - return fmt.Sprintf("%s l=%d attrs=%d id=%s, %s", m.Type, m.Length, len(m.Attributes), tID, aInfo) + return fmt.Sprintf("%s l=%d attrs=%d id=%s", m.Type, m.Length, len(m.Attributes), tID) } // Reset resets Message, attributes and underlying buffer length. @@ -417,6 +384,7 @@ func (m *Message) Write(tBuf []byte) (int, error) { // CloneTo clones m to b securing any further m mutations. func (m *Message) CloneTo(b *Message) error { + // TODO(ar): implement low-level copy. b.Raw = append(b.Raw[:0], m.Raw...) return b.Decode() } @@ -435,11 +403,11 @@ const ( // Common STUN message types. var ( // Binding request message type. - BindingRequest = NewType(MethodBinding, ClassRequest) //nolint:gochecknoglobals + BindingRequest = NewType(MethodBinding, ClassRequest) // Binding success response message type - BindingSuccess = NewType(MethodBinding, ClassSuccessResponse) //nolint:gochecknoglobals + BindingSuccess = NewType(MethodBinding, ClassSuccessResponse) // Binding error response message type. - BindingError = NewType(MethodBinding, ClassErrorResponse) //nolint:gochecknoglobals + BindingError = NewType(MethodBinding, ClassErrorResponse) ) func (c MessageClass) String() string { @@ -453,7 +421,7 @@ func (c MessageClass) String() string { case ClassErrorResponse: return "error response" default: - panic("unknown message class") //nolint + panic("unknown message class") // nolint: never happens unless wrongly casted } } @@ -478,25 +446,23 @@ const ( MethodConnectionAttempt Method = 0x000c ) -func methodName() map[Method]string { - return map[Method]string{ - MethodBinding: "Binding", - MethodAllocate: "Allocate", - MethodRefresh: "Refresh", - MethodSend: "Send", - MethodData: "Data", - MethodCreatePermission: "CreatePermission", - MethodChannelBind: "ChannelBind", +var methodName = map[Method]string{ + MethodBinding: "Binding", + MethodAllocate: "Allocate", + MethodRefresh: "Refresh", + MethodSend: "Send", + MethodData: "Data", + MethodCreatePermission: "CreatePermission", + MethodChannelBind: "ChannelBind", - // RFC 6062. - MethodConnect: "Connect", - MethodConnectionBind: "ConnectionBind", - MethodConnectionAttempt: "ConnectionAttempt", - } + // RFC 6062. + MethodConnect: "Connect", + MethodConnectionBind: "ConnectionBind", + MethodConnectionAttempt: "ConnectionAttempt", } func (m Method) String() string { - s, ok := methodName()[m] + s, ok := methodName[m] if !ok { // Falling back to hex representation. s = fmt.Sprintf("0x%x", uint16(m)) diff --git a/vendor/github.com/pion/stun/renovate.json b/vendor/github.com/pion/stun/renovate.json index f1bb98c6a..4400fd9b2 100644 --- a/vendor/github.com/pion/stun/renovate.json +++ b/vendor/github.com/pion/stun/renovate.json @@ -1,6 +1,15 @@ { - "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ - "github>pion/renovate-config" + "config:base" + ], + "postUpdateOptions": [ + "gomodTidy" + ], + "commitBody": "Generated by renovateBot", + "packageRules": [ + { + "packagePatterns": ["^golang.org/x/"], + "schedule": ["on the first day of the month"] + } ] } diff --git a/vendor/github.com/pion/stun/stun.go b/vendor/github.com/pion/stun/stun.go index 3a7954fd0..9f804d270 100644 --- a/vendor/github.com/pion/stun/stun.go +++ b/vendor/github.com/pion/stun/stun.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package stun implements Session Traversal Utilities for NAT (STUN) RFC 5389. // // The stun package is intended to use by package that implements extension @@ -20,12 +17,12 @@ import ( ) // bin is shorthand to binary.BigEndian. -var bin = binary.BigEndian //nolint:gochecknoglobals +var bin = binary.BigEndian func readFullOrPanic(r io.Reader, v []byte) int { n, err := io.ReadFull(r, v) if err != nil { - panic(err) //nolint + panic(err) // nolint } return n } @@ -33,7 +30,7 @@ func readFullOrPanic(r io.Reader, v []byte) int { func writeOrPanic(w io.Writer, v []byte) int { n, err := w.Write(v) if err != nil { - panic(err) //nolint + panic(err) // nolint } return n } @@ -51,4 +48,4 @@ func (transactionIDSetter) AddTo(m *Message) error { } // TransactionID is Setter for m.TransactionID. -var TransactionID Setter = transactionIDSetter{} //nolint:gochecknoglobals +var TransactionID Setter = transactionIDSetter{} diff --git a/vendor/github.com/pion/stun/textattrs.go b/vendor/github.com/pion/stun/textattrs.go index a98915a6b..efdfbd957 100644 --- a/vendor/github.com/pion/stun/textattrs.go +++ b/vendor/github.com/pion/stun/textattrs.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun // NewUsername returns Username with provided value. diff --git a/vendor/github.com/pion/stun/uattrs.go b/vendor/github.com/pion/stun/uattrs.go index 8b85d8a7a..238d32d10 100644 --- a/vendor/github.com/pion/stun/uattrs.go +++ b/vendor/github.com/pion/stun/uattrs.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun import "errors" diff --git a/vendor/github.com/pion/stun/uri.go b/vendor/github.com/pion/stun/uri.go deleted file mode 100644 index b9dab691f..000000000 --- a/vendor/github.com/pion/stun/uri.go +++ /dev/null @@ -1,257 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -package stun - -import ( - "errors" - "net" - "net/url" - "strconv" -) - -var ( - // ErrUnknownType indicates an error with Unknown info. - ErrUnknownType = errors.New("Unknown") - - // ErrSchemeType indicates the scheme type could not be parsed. - ErrSchemeType = errors.New("unknown scheme type") - - // ErrSTUNQuery indicates query arguments are provided in a STUN URL. - ErrSTUNQuery = errors.New("queries not supported in stun address") - - // ErrInvalidQuery indicates an malformed query is provided. - ErrInvalidQuery = errors.New("invalid query") - - // ErrHost indicates malformed hostname is provided. - ErrHost = errors.New("invalid hostname") - - // ErrPort indicates malformed port is provided. - ErrPort = errors.New("invalid port") - - // ErrProtoType indicates an unsupported transport type was provided. - ErrProtoType = errors.New("invalid transport protocol type") -) - -// SchemeType indicates the type of server used in the ice.URL structure. -type SchemeType int - -const ( - // SchemeTypeUnknown indicates an unknown or unsupported scheme. - SchemeTypeUnknown SchemeType = iota - - // SchemeTypeSTUN indicates the URL represents a STUN server. - SchemeTypeSTUN - - // SchemeTypeSTUNS indicates the URL represents a STUNS (secure) server. - SchemeTypeSTUNS - - // SchemeTypeTURN indicates the URL represents a TURN server. - SchemeTypeTURN - - // SchemeTypeTURNS indicates the URL represents a TURNS (secure) server. - SchemeTypeTURNS -) - -// NewSchemeType defines a procedure for creating a new SchemeType from a raw -// string naming the scheme type. -func NewSchemeType(raw string) SchemeType { - switch raw { - case "stun": - return SchemeTypeSTUN - case "stuns": - return SchemeTypeSTUNS - case "turn": - return SchemeTypeTURN - case "turns": - return SchemeTypeTURNS - default: - return SchemeTypeUnknown - } -} - -func (t SchemeType) String() string { - switch t { - case SchemeTypeSTUN: - return "stun" - case SchemeTypeSTUNS: - return "stuns" - case SchemeTypeTURN: - return "turn" - case SchemeTypeTURNS: - return "turns" - default: - return ErrUnknownType.Error() - } -} - -// ProtoType indicates the transport protocol type that is used in the ice.URL -// structure. -type ProtoType int - -const ( - // ProtoTypeUnknown indicates an unknown or unsupported protocol. - ProtoTypeUnknown ProtoType = iota - - // ProtoTypeUDP indicates the URL uses a UDP transport. - ProtoTypeUDP - - // ProtoTypeTCP indicates the URL uses a TCP transport. - ProtoTypeTCP -) - -// NewProtoType defines a procedure for creating a new ProtoType from a raw -// string naming the transport protocol type. -func NewProtoType(raw string) ProtoType { - switch raw { - case "udp": - return ProtoTypeUDP - case "tcp": - return ProtoTypeTCP - default: - return ProtoTypeUnknown - } -} - -func (t ProtoType) String() string { - switch t { - case ProtoTypeUDP: - return "udp" - case ProtoTypeTCP: - return "tcp" - default: - return ErrUnknownType.Error() - } -} - -// URI represents a STUN (rfc7064) or TURN (rfc7065) URI -type URI struct { - Scheme SchemeType - Host string - Port int - Username string - Password string - Proto ProtoType -} - -// ParseURI parses a STUN or TURN urls following the ABNF syntax described in -// https://tools.ietf.org/html/rfc7064 and https://tools.ietf.org/html/rfc7065 -// respectively. -func ParseURI(raw string) (*URI, error) { //nolint:gocognit - rawParts, err := url.Parse(raw) - if err != nil { - return nil, err - } - - var u URI - u.Scheme = NewSchemeType(rawParts.Scheme) - if u.Scheme == SchemeTypeUnknown { - return nil, ErrSchemeType - } - - var rawPort string - if u.Host, rawPort, err = net.SplitHostPort(rawParts.Opaque); err != nil { - var e *net.AddrError - if errors.As(err, &e) { - if e.Err == "missing port in address" { - nextRawURL := u.Scheme.String() + ":" + rawParts.Opaque - switch { - case u.Scheme == SchemeTypeSTUN || u.Scheme == SchemeTypeTURN: - nextRawURL += ":3478" - if rawParts.RawQuery != "" { - nextRawURL += "?" + rawParts.RawQuery - } - return ParseURI(nextRawURL) - case u.Scheme == SchemeTypeSTUNS || u.Scheme == SchemeTypeTURNS: - nextRawURL += ":5349" - if rawParts.RawQuery != "" { - nextRawURL += "?" + rawParts.RawQuery - } - return ParseURI(nextRawURL) - } - } - } - return nil, err - } - - if u.Host == "" { - return nil, ErrHost - } - - if u.Port, err = strconv.Atoi(rawPort); err != nil { - return nil, ErrPort - } - - switch u.Scheme { - case SchemeTypeSTUN: - qArgs, err := url.ParseQuery(rawParts.RawQuery) - if err != nil || len(qArgs) > 0 { - return nil, ErrSTUNQuery - } - u.Proto = ProtoTypeUDP - case SchemeTypeSTUNS: - qArgs, err := url.ParseQuery(rawParts.RawQuery) - if err != nil || len(qArgs) > 0 { - return nil, ErrSTUNQuery - } - u.Proto = ProtoTypeTCP - case SchemeTypeTURN: - proto, err := parseProto(rawParts.RawQuery) - if err != nil { - return nil, err - } - - u.Proto = proto - if u.Proto == ProtoTypeUnknown { - u.Proto = ProtoTypeUDP - } - case SchemeTypeTURNS: - proto, err := parseProto(rawParts.RawQuery) - if err != nil { - return nil, err - } - - u.Proto = proto - if u.Proto == ProtoTypeUnknown { - u.Proto = ProtoTypeTCP - } - - case SchemeTypeUnknown: - } - - return &u, nil -} - -func parseProto(raw string) (ProtoType, error) { - qArgs, err := url.ParseQuery(raw) - if err != nil || len(qArgs) > 1 { - return ProtoTypeUnknown, ErrInvalidQuery - } - - var proto ProtoType - if rawProto := qArgs.Get("transport"); rawProto != "" { - if proto = NewProtoType(rawProto); proto == ProtoType(0) { - return ProtoTypeUnknown, ErrProtoType - } - return proto, nil - } - - if len(qArgs) > 0 { - return ProtoTypeUnknown, ErrInvalidQuery - } - - return proto, nil -} - -func (u URI) String() string { - rawURL := u.Scheme.String() + ":" + net.JoinHostPort(u.Host, strconv.Itoa(u.Port)) - if u.Scheme == SchemeTypeTURN || u.Scheme == SchemeTypeTURNS { - rawURL += "?transport=" + u.Proto.String() - } - return rawURL -} - -// IsSecure returns whether the this URL's scheme describes secure scheme or not. -func (u URI) IsSecure() bool { - return u.Scheme == SchemeTypeSTUNS || u.Scheme == SchemeTypeTURNS -} diff --git a/vendor/github.com/pion/stun/xor.go b/vendor/github.com/pion/stun/xor.go new file mode 100644 index 000000000..34365eb26 --- /dev/null +++ b/vendor/github.com/pion/stun/xor.go @@ -0,0 +1,62 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package stun + +import ( + "runtime" + "unsafe" +) + +// #nosec +const wordSize = int(unsafe.Sizeof(uintptr(0))) + +var supportsUnaligned = runtime.GOARCH == "386" || runtime.GOARCH == "amd64" + +// fastXORBytes xors in bulk. It only works on architectures that +// support unaligned read/writes. +// +// #nosec +func fastXORBytes(dst, a, b []byte) int { + n := len(a) + if len(b) < n { + n = len(b) + } + + w := n / wordSize + if w > 0 { + dw := *(*[]uintptr)(unsafe.Pointer(&dst)) + aw := *(*[]uintptr)(unsafe.Pointer(&a)) + bw := *(*[]uintptr)(unsafe.Pointer(&b)) + for i := 0; i < w; i++ { + dw[i] = aw[i] ^ bw[i] + } + } + + for i := n - n%wordSize; i < n; i++ { + dst[i] = a[i] ^ b[i] + } + + return n +} + +func safeXORBytes(dst, a, b []byte) int { + n := len(a) + if len(b) < n { + n = len(b) + } + for i := 0; i < n; i++ { + dst[i] = a[i] ^ b[i] + } + return n +} + +// xorBytes xors the bytes in a and b. The destination is assumed to have enough +// space. Returns the number of bytes xor'd. +func xorBytes(dst, a, b []byte) int { + if supportsUnaligned { + return fastXORBytes(dst, a, b) + } + return safeXORBytes(dst, a, b) +} diff --git a/vendor/github.com/pion/stun/xoraddr.go b/vendor/github.com/pion/stun/xoraddr.go index fc423be86..23f7777c0 100644 --- a/vendor/github.com/pion/stun/xoraddr.go +++ b/vendor/github.com/pion/stun/xoraddr.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package stun import ( @@ -9,8 +6,6 @@ import ( "io" "net" "strconv" - - "github.com/pion/transport/v2/utils/xor" ) const ( @@ -71,7 +66,7 @@ func (a XORMappedAddress) AddToAs(m *Message, t AttrType) error { bin.PutUint32(xorValue[0:4], magicCookie) bin.PutUint16(value[0:2], family) bin.PutUint16(value[2:4], uint16(a.Port^magicCookie>>16)) - xor.XorBytes(value[4:4+len(ip)], ip, xorValue) + xorBytes(value[4:4+len(ip)], ip, xorValue) m.Add(t, value[:4+len(ip)]) return nil } @@ -120,7 +115,7 @@ func (a *XORMappedAddress) GetFromAs(m *Message, t AttrType) error { xorValue := make([]byte, 4+TransactionIDSize) bin.PutUint32(xorValue[0:4], magicCookie) copy(xorValue[4:], m.TransactionID[:]) - xor.XorBytes(a.IP, v[4:], xorValue) + xorBytes(a.IP, v[4:], xorValue) return nil } @@ -131,20 +126,20 @@ func (a *XORMappedAddress) GetFromAs(m *Message, t AttrType) error { // // Example: // -// expectedIP := net.ParseIP("213.141.156.236") -// expectedIP.String() // 213.141.156.236, 16 bytes, first 12 of them are zeroes -// expectedPort := 21254 -// addr := &XORMappedAddress{ -// IP: expectedIP, -// Port: expectedPort, -// } -// // addr were added to message that is decoded as newMessage -// // ... +// expectedIP := net.ParseIP("213.141.156.236") +// expectedIP.String() // 213.141.156.236, 16 bytes, first 12 of them are zeroes +// expectedPort := 21254 +// addr := &XORMappedAddress{ +// IP: expectedIP, +// Port: expectedPort, +// } +// // addr were added to message that is decoded as newMessage +// // ... // -// addr.GetFrom(newMessage) -// addr.IP.String() // 213.141.156.236, net.IPv4Len -// expectedIP.String() // d58d:9cec::ffff:d58d:9cec, 16 bytes, first 4 are IPv4 -// // now we have len(expectedIP) = 16 and len(addr.IP) = 4. +// addr.GetFrom(newMessage) +// addr.IP.String() // 213.141.156.236, net.IPv4Len +// expectedIP.String() // d58d:9cec::ffff:d58d:9cec, 16 bytes, first 4 are IPv4 +// // now we have len(expectedIP) = 16 and len(addr.IP) = 4. func (a *XORMappedAddress) GetFrom(m *Message) error { return a.GetFromAs(m, AttrXORMappedAddress) } diff --git a/vendor/github.com/pion/transport/v2/AUTHORS.txt b/vendor/github.com/pion/transport/AUTHORS.txt similarity index 66% rename from vendor/github.com/pion/transport/v2/AUTHORS.txt rename to vendor/github.com/pion/transport/AUTHORS.txt index 35bbec396..f2d46d70b 100644 --- a/vendor/github.com/pion/transport/v2/AUTHORS.txt +++ b/vendor/github.com/pion/transport/AUTHORS.txt @@ -2,27 +2,18 @@ # we would love to have you https://github.com/pion/webrtc/wiki/Contributing # # This file is auto generated, using git to list all individuals contributors. -# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting -Adrian Cable +# see `.github/generate-authors.sh` for the scripting Atsushi Watanabe backkem -cnderrauber Hugo Arregui -Jeremiah Millay Jozef Kralik Juliusz Chroboczek Luke Curley Mathis Engelbart OrlandoCo -Sean DuBois -Sean DuBois Sean DuBois Sean DuBois -Steffen Vogel Winlin Woodrow Douglass Yutaka Takeda ZHENK - -# List of contributors not appearing in Git history - diff --git a/vendor/github.com/libp2p/go-libp2p-mplex/LICENSE b/vendor/github.com/pion/transport/LICENSE similarity index 86% rename from vendor/github.com/libp2p/go-libp2p-mplex/LICENSE rename to vendor/github.com/pion/transport/LICENSE index c7386b3c9..ab602974d 100644 --- a/vendor/github.com/libp2p/go-libp2p-mplex/LICENSE +++ b/vendor/github.com/pion/transport/LICENSE @@ -1,6 +1,6 @@ -The MIT License (MIT) +MIT License -Copyright (c) 2014 Juan Batiz-Benet +Copyright (c) 2018 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -9,13 +9,13 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/pion/transport/v2/connctx/connctx.go b/vendor/github.com/pion/transport/connctx/connctx.go similarity index 91% rename from vendor/github.com/pion/transport/v2/connctx/connctx.go rename to vendor/github.com/pion/transport/connctx/connctx.go index 0bdd59509..19fe48498 100644 --- a/vendor/github.com/pion/transport/v2/connctx/connctx.go +++ b/vendor/github.com/pion/transport/connctx/connctx.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package connctx wraps net.Conn using context.Context. package connctx @@ -100,8 +97,8 @@ func (c *connCtx) ReadContext(ctx context.Context, b []byte) (int, error) { if e := ctx.Err(); e != nil && n == 0 { err = e } - if err2, ok := errSetDeadline.Load().(error); ok && err == nil && err2 != nil { - err = err2 + if err2 := errSetDeadline.Load(); err == nil && err2 != nil { + err = err2.(error) } return n, err } @@ -144,8 +141,8 @@ func (c *connCtx) WriteContext(ctx context.Context, b []byte) (int, error) { if e := ctx.Err(); e != nil && n == 0 { err = e } - if err2, ok := errSetDeadline.Load().(error); ok && err == nil && err2 != nil { - err = err2 + if err2 := errSetDeadline.Load(); err == nil && err2 != nil { + err = err2.(error) } return n, err } diff --git a/vendor/github.com/pion/transport/v2/connctx/pipe.go b/vendor/github.com/pion/transport/connctx/pipe.go similarity index 60% rename from vendor/github.com/pion/transport/v2/connctx/pipe.go rename to vendor/github.com/pion/transport/connctx/pipe.go index 96b802e43..e2f040928 100644 --- a/vendor/github.com/pion/transport/v2/connctx/pipe.go +++ b/vendor/github.com/pion/transport/connctx/pipe.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package connctx import ( diff --git a/vendor/github.com/pion/transport/v2/deadline/deadline.go b/vendor/github.com/pion/transport/deadline/deadline.go similarity index 90% rename from vendor/github.com/pion/transport/v2/deadline/deadline.go rename to vendor/github.com/pion/transport/deadline/deadline.go index abd39f06d..6f9738670 100644 --- a/vendor/github.com/pion/transport/v2/deadline/deadline.go +++ b/vendor/github.com/pion/transport/deadline/deadline.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package deadline provides deadline timer used to implement // net.Conn compatible connection package deadline @@ -62,15 +59,11 @@ func (d *Deadline) Set(t time.Time) { exceeded := d.exceeded stopped := d.stopped go func() { - timer := time.NewTimer(dur) select { - case <-timer.C: + case <-time.After(dur): close(exceeded) stopped <- false case <-d.stop: - if !timer.Stop() { - <-timer.C - } stopped <- true } }() diff --git a/vendor/github.com/pion/transport/v2/packetio/buffer.go b/vendor/github.com/pion/transport/packetio/buffer.go similarity index 85% rename from vendor/github.com/pion/transport/v2/packetio/buffer.go rename to vendor/github.com/pion/transport/packetio/buffer.go index 2d46d796a..97d86f8c8 100644 --- a/vendor/github.com/pion/transport/v2/packetio/buffer.go +++ b/vendor/github.com/pion/transport/packetio/buffer.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package packetio provides packet buffer package packetio @@ -10,7 +7,7 @@ import ( "sync" "time" - "github.com/pion/transport/v2/deadline" + "github.com/pion/transport/deadline" ) var errPacketTooBig = errors.New("packet too big") @@ -38,7 +35,8 @@ type Buffer struct { data []byte head, tail int - notify chan struct{} // non-nil when we have blocked readers + notify chan struct{} + subs bool closed bool count int @@ -56,6 +54,7 @@ const ( // NewBuffer creates a new Buffer. func NewBuffer() *Buffer { return &Buffer{ + notify: make(chan struct{}), readDeadline: deadline.New(), } } @@ -78,42 +77,42 @@ func (b *Buffer) available(size int) bool { // grow increases the size of the buffer. If it returns nil, then the // buffer has been grown. It returns ErrFull if hits a limit. func (b *Buffer) grow() error { - var newSize int + var newsize int if len(b.data) < cutoffSize { - newSize = 2 * len(b.data) + newsize = 2 * len(b.data) } else { - newSize = 5 * len(b.data) / 4 + newsize = 5 * len(b.data) / 4 } - if newSize < minSize { - newSize = minSize + if newsize < minSize { + newsize = minSize } - if (b.limitSize <= 0 || sizeHardLimit) && newSize > maxSize { - newSize = maxSize + if (b.limitSize <= 0 || sizeHardlimit) && newsize > maxSize { + newsize = maxSize } // one byte slack - if b.limitSize > 0 && newSize > b.limitSize+1 { - newSize = b.limitSize + 1 + if b.limitSize > 0 && newsize > b.limitSize+1 { + newsize = b.limitSize + 1 } - if newSize <= len(b.data) { + if newsize <= len(b.data) { return ErrFull } - newData := make([]byte, newSize) + newdata := make([]byte, newsize) var n int if b.head <= b.tail { // data was contiguous - n = copy(newData, b.data[b.head:b.tail]) + n = copy(newdata, b.data[b.head:b.tail]) } else { - // data was discontinuous - n = copy(newData, b.data[b.head:]) - n += copy(newData[n:], b.data[:b.tail]) + // data was discontiguous + n = copy(newdata, b.data[b.head:]) + n += copy(newdata[n:], b.data[:b.tail]) } b.head = 0 b.tail = n - b.data = newData + b.data = newdata return nil } @@ -150,11 +149,13 @@ func (b *Buffer) Write(packet []byte) (int, error) { } var notify chan struct{} - if b.notify != nil { - // Prepare to notify readers, but only + + if b.subs { + // readers are waiting. Prepare to notify, but only // actually do it after we release the lock. notify = b.notify - b.notify = nil + b.notify = make(chan struct{}) + b.subs = false } // store the length of the packet @@ -191,7 +192,7 @@ func (b *Buffer) Write(packet []byte) (int, error) { // Blocks until data is available or the buffer is closed. // Returns io.ErrShortBuffer is the packet is too small to copy the Write. // Returns io.EOF if the buffer is closed. -func (b *Buffer) Read(packet []byte) (n int, err error) { //nolint:gocognit +func (b *Buffer) Read(packet []byte) (n int, err error) { // Return immediately if the deadline is already exceeded. select { case <-b.readDeadline.Done(): @@ -258,10 +259,8 @@ func (b *Buffer) Read(packet []byte) (n int, err error) { //nolint:gocognit return 0, io.EOF } - if b.notify == nil { - b.notify = make(chan struct{}) - } notify := b.notify + b.subs = true b.mutex.Unlock() select { @@ -283,14 +282,11 @@ func (b *Buffer) Close() (err error) { } notify := b.notify - b.notify = nil b.closed = true b.mutex.Unlock() - if notify != nil { - close(notify) - } + close(notify) return nil } @@ -333,9 +329,9 @@ func (b *Buffer) size() int { // Causes Write to return ErrFull when this limit is reached. // A zero value means 4MB since v0.11.0. // -// User can set packetioSizeHardLimit build tag to enable 4MB hard limit. -// When packetioSizeHardLimit build tag is set, SetLimitSize exceeding -// the hard limit will be silently discarded. +// User can set packetioSizeHardlimit build tag to enable 4MB hardlimit. +// When packetioSizeHardlimit build tag is set, SetLimitSize exceeding +// the hardlimit will be silently discarded. func (b *Buffer) SetLimitSize(limit int) { b.mutex.Lock() defer b.mutex.Unlock() diff --git a/vendor/github.com/pion/transport/v2/packetio/errors.go b/vendor/github.com/pion/transport/packetio/errors.go similarity index 82% rename from vendor/github.com/pion/transport/v2/packetio/errors.go rename to vendor/github.com/pion/transport/packetio/errors.go index 4974a10b5..06f1b9d98 100644 --- a/vendor/github.com/pion/transport/v2/packetio/errors.go +++ b/vendor/github.com/pion/transport/packetio/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package packetio import ( diff --git a/vendor/github.com/pion/transport/packetio/hardlimit.go b/vendor/github.com/pion/transport/packetio/hardlimit.go new file mode 100644 index 000000000..5ddacc733 --- /dev/null +++ b/vendor/github.com/pion/transport/packetio/hardlimit.go @@ -0,0 +1,5 @@ +// +build packetioSizeHardlimit + +package packetio + +const sizeHardlimit = true diff --git a/vendor/github.com/pion/transport/packetio/no_hardlimit.go b/vendor/github.com/pion/transport/packetio/no_hardlimit.go new file mode 100644 index 000000000..55ea30865 --- /dev/null +++ b/vendor/github.com/pion/transport/packetio/no_hardlimit.go @@ -0,0 +1,5 @@ +// +build !packetioSizeHardlimit + +package packetio + +const sizeHardlimit = false diff --git a/vendor/github.com/pion/transport/v2/replaydetector/fixedbig.go b/vendor/github.com/pion/transport/replaydetector/fixedbig.go similarity index 93% rename from vendor/github.com/pion/transport/v2/replaydetector/fixedbig.go rename to vendor/github.com/pion/transport/replaydetector/fixedbig.go index 80cb6b305..a571a1aad 100644 --- a/vendor/github.com/pion/transport/v2/replaydetector/fixedbig.go +++ b/vendor/github.com/pion/transport/replaydetector/fixedbig.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package replaydetector import ( diff --git a/vendor/github.com/pion/transport/v2/replaydetector/replaydetector.go b/vendor/github.com/pion/transport/replaydetector/replaydetector.go similarity index 94% rename from vendor/github.com/pion/transport/v2/replaydetector/replaydetector.go rename to vendor/github.com/pion/transport/replaydetector/replaydetector.go index 4358d8f3b..d9420022b 100644 --- a/vendor/github.com/pion/transport/v2/replaydetector/replaydetector.go +++ b/vendor/github.com/pion/transport/replaydetector/replaydetector.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package replaydetector provides packet replay detection algorithm. package replaydetector @@ -58,7 +55,7 @@ func (d *slidingWindowDetector) Check(seq uint64) (accept func(), ok bool) { } // WithWrap creates ReplayDetector allowing sequence wrapping. -// This is suitable for short bit width counter like SRTP and SRTCP. +// This is suitable for short bitwidth counter like SRTP and SRTCP. func WithWrap(windowSize uint, maxSeq uint64) ReplayDetector { return &wrappedSlidingWindowDetector{ maxSeq: maxSeq, diff --git a/vendor/github.com/pion/transport/v2/.goreleaser.yml b/vendor/github.com/pion/transport/v2/.goreleaser.yml deleted file mode 100644 index 30093e9d6..000000000 --- a/vendor/github.com/pion/transport/v2/.goreleaser.yml +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - -builds: -- skip: true diff --git a/vendor/github.com/pion/transport/v2/LICENSE b/vendor/github.com/pion/transport/v2/LICENSE deleted file mode 100644 index 491caf6b0..000000000 --- a/vendor/github.com/pion/transport/v2/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) 2023 The Pion community - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/pion/transport/v2/README.md b/vendor/github.com/pion/transport/v2/README.md deleted file mode 100644 index b604b104d..000000000 --- a/vendor/github.com/pion/transport/v2/README.md +++ /dev/null @@ -1,34 +0,0 @@ -

-
- Pion Transport -
-

-

Transport testing for Pion

-

- Pion transport - Slack Widget -
- GitHub Workflow Status - Go Reference - Coverage Status - Go Report Card - License: MIT -

-
- -### Roadmap -The library is used as a part of our WebRTC implementation. Please refer to that [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones. - -### Community -Pion has an active community on the [Slack](https://pion.ly/slack). - -Follow the [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news. - -We are always looking to support **your projects**. Please reach out if you have something to build! -If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly) - -### Contributing -Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible: [AUTHORS.txt](./AUTHORS.txt) - -### License -MIT License - see [LICENSE](LICENSE) for full text diff --git a/vendor/github.com/pion/transport/v2/net.go b/vendor/github.com/pion/transport/v2/net.go deleted file mode 100644 index 86d3468f7..000000000 --- a/vendor/github.com/pion/transport/v2/net.go +++ /dev/null @@ -1,418 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -// Package transport implements various networking related -// functions used throughout the Pion modules. -package transport - -import ( - "errors" - "io" - "net" - "time" -) - -var ( - // ErrNoAddressAssigned ... - ErrNoAddressAssigned = errors.New("no address assigned") - // ErrNotSupported ... - ErrNotSupported = errors.New("not supported yey") - // ErrInterfaceNotFound ... - ErrInterfaceNotFound = errors.New("interface not found") - // ErrNotUDPAddress ... - ErrNotUDPAddress = errors.New("not a UDP address") -) - -// Net is an interface providing common networking functions which are -// similar to the functions provided by standard net package. -type Net interface { - // ListenPacket announces on the local network address. - // - // The network must be "udp", "udp4", "udp6", "unixgram", or an IP - // transport. The IP transports are "ip", "ip4", or "ip6" followed by - // a colon and a literal protocol number or a protocol name, as in - // "ip:1" or "ip:icmp". - // - // For UDP and IP networks, if the host in the address parameter is - // empty or a literal unspecified IP address, ListenPacket listens on - // all available IP addresses of the local system except multicast IP - // addresses. - // To only use IPv4, use network "udp4" or "ip4:proto". - // The address can use a host name, but this is not recommended, - // because it will create a listener for at most one of the host's IP - // addresses. - // If the port in the address parameter is empty or "0", as in - // "127.0.0.1:" or "[::1]:0", a port number is automatically chosen. - // The LocalAddr method of PacketConn can be used to discover the - // chosen port. - // - // See func Dial for a description of the network and address - // parameters. - // - // ListenPacket uses context.Background internally; to specify the context, use - // ListenConfig.ListenPacket. - ListenPacket(network string, address string) (net.PacketConn, error) - - // ListenUDP acts like ListenPacket for UDP networks. - // - // The network must be a UDP network name; see func Dial for details. - // - // If the IP field of laddr is nil or an unspecified IP address, - // ListenUDP listens on all available IP addresses of the local system - // except multicast IP addresses. - // If the Port field of laddr is 0, a port number is automatically - // chosen. - ListenUDP(network string, locAddr *net.UDPAddr) (UDPConn, error) - - // ListenTCP acts like Listen for TCP networks. - // - // The network must be a TCP network name; see func Dial for details. - // - // If the IP field of laddr is nil or an unspecified IP address, - // ListenTCP listens on all available unicast and anycast IP addresses - // of the local system. - // If the Port field of laddr is 0, a port number is automatically - // chosen. - ListenTCP(network string, laddr *net.TCPAddr) (TCPListener, error) - - // Dial connects to the address on the named network. - // - // Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), - // "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4" - // (IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and - // "unixpacket". - // - // For TCP and UDP networks, the address has the form "host:port". - // The host must be a literal IP address, or a host name that can be - // resolved to IP addresses. - // The port must be a literal port number or a service name. - // If the host is a literal IPv6 address it must be enclosed in square - // brackets, as in "[2001:db8::1]:80" or "[fe80::1%zone]:80". - // The zone specifies the scope of the literal IPv6 address as defined - // in RFC 4007. - // The functions JoinHostPort and SplitHostPort manipulate a pair of - // host and port in this form. - // When using TCP, and the host resolves to multiple IP addresses, - // Dial will try each IP address in order until one succeeds. - // - // Examples: - // - // Dial("tcp", "golang.org:http") - // Dial("tcp", "192.0.2.1:http") - // Dial("tcp", "198.51.100.1:80") - // Dial("udp", "[2001:db8::1]:domain") - // Dial("udp", "[fe80::1%lo0]:53") - // Dial("tcp", ":80") - // - // For IP networks, the network must be "ip", "ip4" or "ip6" followed - // by a colon and a literal protocol number or a protocol name, and - // the address has the form "host". The host must be a literal IP - // address or a literal IPv6 address with zone. - // It depends on each operating system how the operating system - // behaves with a non-well known protocol number such as "0" or "255". - // - // Examples: - // - // Dial("ip4:1", "192.0.2.1") - // Dial("ip6:ipv6-icmp", "2001:db8::1") - // Dial("ip6:58", "fe80::1%lo0") - // - // For TCP, UDP and IP networks, if the host is empty or a literal - // unspecified IP address, as in ":80", "0.0.0.0:80" or "[::]:80" for - // TCP and UDP, "", "0.0.0.0" or "::" for IP, the local system is - // assumed. - // - // For Unix networks, the address must be a file system path. - Dial(network, address string) (net.Conn, error) - - // DialUDP acts like Dial for UDP networks. - // - // The network must be a UDP network name; see func Dial for details. - // - // If laddr is nil, a local address is automatically chosen. - // If the IP field of raddr is nil or an unspecified IP address, the - // local system is assumed. - DialUDP(network string, laddr, raddr *net.UDPAddr) (UDPConn, error) - - // DialTCP acts like Dial for TCP networks. - // - // The network must be a TCP network name; see func Dial for details. - // - // If laddr is nil, a local address is automatically chosen. - // If the IP field of raddr is nil or an unspecified IP address, the - // local system is assumed. - DialTCP(network string, laddr, raddr *net.TCPAddr) (TCPConn, error) - - // ResolveIPAddr returns an address of IP end point. - // - // The network must be an IP network name. - // - // If the host in the address parameter is not a literal IP address, - // ResolveIPAddr resolves the address to an address of IP end point. - // Otherwise, it parses the address as a literal IP address. - // The address parameter can use a host name, but this is not - // recommended, because it will return at most one of the host name's - // IP addresses. - // - // See func Dial for a description of the network and address - // parameters. - ResolveIPAddr(network, address string) (*net.IPAddr, error) - - // ResolveUDPAddr returns an address of UDP end point. - // - // The network must be a UDP network name. - // - // If the host in the address parameter is not a literal IP address or - // the port is not a literal port number, ResolveUDPAddr resolves the - // address to an address of UDP end point. - // Otherwise, it parses the address as a pair of literal IP address - // and port number. - // The address parameter can use a host name, but this is not - // recommended, because it will return at most one of the host name's - // IP addresses. - // - // See func Dial for a description of the network and address - // parameters. - ResolveUDPAddr(network, address string) (*net.UDPAddr, error) - - // ResolveTCPAddr returns an address of TCP end point. - // - // The network must be a TCP network name. - // - // If the host in the address parameter is not a literal IP address or - // the port is not a literal port number, ResolveTCPAddr resolves the - // address to an address of TCP end point. - // Otherwise, it parses the address as a pair of literal IP address - // and port number. - // The address parameter can use a host name, but this is not - // recommended, because it will return at most one of the host name's - // IP addresses. - // - // See func Dial for a description of the network and address - // parameters. - ResolveTCPAddr(network, address string) (*net.TCPAddr, error) - - // Interfaces returns a list of the system's network interfaces. - Interfaces() ([]*Interface, error) - - // InterfaceByIndex returns the interface specified by index. - // - // On Solaris, it returns one of the logical network interfaces - // sharing the logical data link; for more precision use - // InterfaceByName. - InterfaceByIndex(index int) (*Interface, error) - - // InterfaceByName returns the interface specified by name. - InterfaceByName(name string) (*Interface, error) - - // The following functions are extensions to Go's standard net package - - CreateDialer(dialer *net.Dialer) Dialer -} - -// Dialer is identical to net.Dialer excepts that its methods -// (Dial, DialContext) are overridden to use the Net interface. -// Use vnet.CreateDialer() to create an instance of this Dialer. -type Dialer interface { - Dial(network, address string) (net.Conn, error) -} - -// UDPConn is packet-oriented connection for UDP. -type UDPConn interface { - // Close closes the connection. - // Any blocked Read or Write operations will be unblocked and return errors. - Close() error - - // LocalAddr returns the local network address, if known. - LocalAddr() net.Addr - - // RemoteAddr returns the remote network address, if known. - RemoteAddr() net.Addr - - // SetDeadline sets the read and write deadlines associated - // with the connection. It is equivalent to calling both - // SetReadDeadline and SetWriteDeadline. - // - // A deadline is an absolute time after which I/O operations - // fail instead of blocking. The deadline applies to all future - // and pending I/O, not just the immediately following call to - // Read or Write. After a deadline has been exceeded, the - // connection can be refreshed by setting a deadline in the future. - // - // If the deadline is exceeded a call to Read or Write or to other - // I/O methods will return an error that wraps os.ErrDeadlineExceeded. - // This can be tested using errors.Is(err, os.ErrDeadlineExceeded). - // The error's Timeout method will return true, but note that there - // are other possible errors for which the Timeout method will - // return true even if the deadline has not been exceeded. - // - // An idle timeout can be implemented by repeatedly extending - // the deadline after successful Read or Write calls. - // - // A zero value for t means I/O operations will not time out. - SetDeadline(t time.Time) error - - // SetReadDeadline sets the deadline for future Read calls - // and any currently-blocked Read call. - // A zero value for t means Read will not time out. - SetReadDeadline(t time.Time) error - - // SetWriteDeadline sets the deadline for future Write calls - // and any currently-blocked Write call. - // Even if write times out, it may return n > 0, indicating that - // some of the data was successfully written. - // A zero value for t means Write will not time out. - SetWriteDeadline(t time.Time) error - - // SetReadBuffer sets the size of the operating system's - // receive buffer associated with the connection. - SetReadBuffer(bytes int) error - - // SetWriteBuffer sets the size of the operating system's - // transmit buffer associated with the connection. - SetWriteBuffer(bytes int) error - - // Read reads data from the connection. - // Read can be made to time out and return an error after a fixed - // time limit; see SetDeadline and SetReadDeadline. - Read(b []byte) (n int, err error) - - // ReadFrom reads a packet from the connection, - // copying the payload into p. It returns the number of - // bytes copied into p and the return address that - // was on the packet. - // It returns the number of bytes read (0 <= n <= len(p)) - // and any error encountered. Callers should always process - // the n > 0 bytes returned before considering the error err. - // ReadFrom can be made to time out and return an error after a - // fixed time limit; see SetDeadline and SetReadDeadline. - ReadFrom(p []byte) (n int, addr net.Addr, err error) - - // ReadFromUDP acts like ReadFrom but returns a UDPAddr. - ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) - - // ReadMsgUDP reads a message from c, copying the payload into b and - // the associated out-of-band data into oob. It returns the number of - // bytes copied into b, the number of bytes copied into oob, the flags - // that were set on the message and the source address of the message. - // - // The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be - // used to manipulate IP-level socket options in oob. - ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAddr, err error) - - // Write writes data to the connection. - // Write can be made to time out and return an error after a fixed - // time limit; see SetDeadline and SetWriteDeadline. - Write(b []byte) (n int, err error) - - // WriteTo writes a packet with payload p to addr. - // WriteTo can be made to time out and return an Error after a - // fixed time limit; see SetDeadline and SetWriteDeadline. - // On packet-oriented connections, write timeouts are rare. - WriteTo(p []byte, addr net.Addr) (n int, err error) - - // WriteToUDP acts like WriteTo but takes a UDPAddr. - WriteToUDP(b []byte, addr *net.UDPAddr) (int, error) - - // WriteMsgUDP writes a message to addr via c if c isn't connected, or - // to c's remote address if c is connected (in which case addr must be - // nil). The payload is copied from b and the associated out-of-band - // data is copied from oob. It returns the number of payload and - // out-of-band bytes written. - // - // The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be - // used to manipulate IP-level socket options in oob. - WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, err error) -} - -// TCPConn is an interface for TCP network connections. -type TCPConn interface { - net.Conn - - // CloseRead shuts down the reading side of the TCP connection. - // Most callers should just use Close. - CloseRead() error - - // CloseWrite shuts down the writing side of the TCP connection. - // Most callers should just use Close. - CloseWrite() error - - // ReadFrom implements the io.ReaderFrom ReadFrom method. - ReadFrom(r io.Reader) (int64, error) - - // SetLinger sets the behavior of Close on a connection which still - // has data waiting to be sent or to be acknowledged. - // - // If sec < 0 (the default), the operating system finishes sending the - // data in the background. - // - // If sec == 0, the operating system discards any unsent or - // unacknowledged data. - // - // If sec > 0, the data is sent in the background as with sec < 0. On - // some operating systems after sec seconds have elapsed any remaining - // unsent data may be discarded. - SetLinger(sec int) error - - // SetKeepAlive sets whether the operating system should send - // keep-alive messages on the connection. - SetKeepAlive(keepalive bool) error - - // SetKeepAlivePeriod sets period between keep-alives. - SetKeepAlivePeriod(d time.Duration) error - - // SetNoDelay controls whether the operating system should delay - // packet transmission in hopes of sending fewer packets (Nagle's - // algorithm). The default is true (no delay), meaning that data is - // sent as soon as possible after a Write. - SetNoDelay(noDelay bool) error - - // SetWriteBuffer sets the size of the operating system's - // transmit buffer associated with the connection. - SetWriteBuffer(bytes int) error - - // SetReadBuffer sets the size of the operating system's - // receive buffer associated with the connection. - SetReadBuffer(bytes int) error -} - -// TCPListener is a TCP network listener. Clients should typically -// use variables of type Listener instead of assuming TCP. -type TCPListener interface { - net.Listener - - // AcceptTCP accepts the next incoming call and returns the new - // connection. - AcceptTCP() (TCPConn, error) - - // SetDeadline sets the deadline associated with the listener. - // A zero time value disables the deadline. - SetDeadline(t time.Time) error -} - -// Interface wraps a standard net.Interfaces and its assigned addresses -type Interface struct { - net.Interface - addrs []net.Addr -} - -// NewInterface creates a new interface based of a standard net.Interface -func NewInterface(ifc net.Interface) *Interface { - return &Interface{ - Interface: ifc, - addrs: nil, - } -} - -// AddAddress adds a new address to the interface -func (ifc *Interface) AddAddress(addr net.Addr) { - ifc.addrs = append(ifc.addrs, addr) -} - -// Addrs returns a slice of configured addresses on the interface -func (ifc *Interface) Addrs() ([]net.Addr, error) { - if len(ifc.addrs) == 0 { - return nil, ErrNoAddressAssigned - } - return ifc.addrs, nil -} diff --git a/vendor/github.com/pion/transport/v2/packetio/hardlimit.go b/vendor/github.com/pion/transport/v2/packetio/hardlimit.go deleted file mode 100644 index 8058e47fa..000000000 --- a/vendor/github.com/pion/transport/v2/packetio/hardlimit.go +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -//go:build packetioSizeHardlimit -// +build packetioSizeHardlimit - -package packetio - -const sizeHardLimit = true diff --git a/vendor/github.com/pion/transport/v2/packetio/no_hardlimit.go b/vendor/github.com/pion/transport/v2/packetio/no_hardlimit.go deleted file mode 100644 index a59e25957..000000000 --- a/vendor/github.com/pion/transport/v2/packetio/no_hardlimit.go +++ /dev/null @@ -1,9 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -//go:build !packetioSizeHardlimit -// +build !packetioSizeHardlimit - -package packetio - -const sizeHardLimit = false diff --git a/vendor/github.com/pion/transport/v2/renovate.json b/vendor/github.com/pion/transport/v2/renovate.json deleted file mode 100644 index f1bb98c6a..000000000 --- a/vendor/github.com/pion/transport/v2/renovate.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "$schema": "https://docs.renovatebot.com/renovate-schema.json", - "extends": [ - "github>pion/renovate-config" - ] -} diff --git a/vendor/github.com/pion/transport/v2/stdnet/net.go b/vendor/github.com/pion/transport/v2/stdnet/net.go deleted file mode 100644 index fa4753b51..000000000 --- a/vendor/github.com/pion/transport/v2/stdnet/net.go +++ /dev/null @@ -1,167 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -// Package stdnet implements the transport.Net interface -// using methods from Go's standard net package. -package stdnet - -import ( - "fmt" - "net" - - "github.com/pion/transport/v2" -) - -const ( - lo0String = "lo0String" - udpString = "udp" -) - -// Net is an implementation of the net.Net interface -// based on functions of the standard net package. -type Net struct { - interfaces []*transport.Interface -} - -// NewNet creates a new StdNet instance. -func NewNet() (*Net, error) { - n := &Net{} - - return n, n.UpdateInterfaces() -} - -// Compile-time assertion -var _ transport.Net = &Net{} - -// UpdateInterfaces updates the internal list of network interfaces -// and associated addresses. -func (n *Net) UpdateInterfaces() error { - ifs := []*transport.Interface{} - - oifs, err := net.Interfaces() - if err != nil { - return err - } - - for _, oif := range oifs { - ifc := transport.NewInterface(oif) - - addrs, err := oif.Addrs() - if err != nil { - return err - } - - for _, addr := range addrs { - ifc.AddAddress(addr) - } - - ifs = append(ifs, ifc) - } - - n.interfaces = ifs - - return nil -} - -// Interfaces returns a slice of interfaces which are available on the -// system -func (n *Net) Interfaces() ([]*transport.Interface, error) { - return n.interfaces, nil -} - -// InterfaceByIndex returns the interface specified by index. -// -// On Solaris, it returns one of the logical network interfaces -// sharing the logical data link; for more precision use -// InterfaceByName. -func (n *Net) InterfaceByIndex(index int) (*transport.Interface, error) { - for _, ifc := range n.interfaces { - if ifc.Index == index { - return ifc, nil - } - } - - return nil, fmt.Errorf("%w: index=%d", transport.ErrInterfaceNotFound, index) -} - -// InterfaceByName returns the interface specified by name. -func (n *Net) InterfaceByName(name string) (*transport.Interface, error) { - for _, ifc := range n.interfaces { - if ifc.Name == name { - return ifc, nil - } - } - - return nil, fmt.Errorf("%w: %s", transport.ErrInterfaceNotFound, name) -} - -// ListenPacket announces on the local network address. -func (n *Net) ListenPacket(network string, address string) (net.PacketConn, error) { - return net.ListenPacket(network, address) -} - -// ListenUDP acts like ListenPacket for UDP networks. -func (n *Net) ListenUDP(network string, locAddr *net.UDPAddr) (transport.UDPConn, error) { - return net.ListenUDP(network, locAddr) -} - -// Dial connects to the address on the named network. -func (n *Net) Dial(network, address string) (net.Conn, error) { - return net.Dial(network, address) -} - -// DialUDP acts like Dial for UDP networks. -func (n *Net) DialUDP(network string, laddr, raddr *net.UDPAddr) (transport.UDPConn, error) { - return net.DialUDP(network, laddr, raddr) -} - -// ResolveIPAddr returns an address of IP end point. -func (n *Net) ResolveIPAddr(network, address string) (*net.IPAddr, error) { - return net.ResolveIPAddr(network, address) -} - -// ResolveUDPAddr returns an address of UDP end point. -func (n *Net) ResolveUDPAddr(network, address string) (*net.UDPAddr, error) { - return net.ResolveUDPAddr(network, address) -} - -// ResolveTCPAddr returns an address of TCP end point. -func (n *Net) ResolveTCPAddr(network, address string) (*net.TCPAddr, error) { - return net.ResolveTCPAddr(network, address) -} - -// DialTCP acts like Dial for TCP networks. -func (n *Net) DialTCP(network string, laddr, raddr *net.TCPAddr) (transport.TCPConn, error) { - return net.DialTCP(network, laddr, raddr) -} - -// ListenTCP acts like Listen for TCP networks. -func (n *Net) ListenTCP(network string, laddr *net.TCPAddr) (transport.TCPListener, error) { - l, err := net.ListenTCP(network, laddr) - if err != nil { - return nil, err - } - - return tcpListener{l}, nil -} - -type tcpListener struct { - *net.TCPListener -} - -func (l tcpListener) AcceptTCP() (transport.TCPConn, error) { - return l.TCPListener.AcceptTCP() -} - -type stdDialer struct { - *net.Dialer -} - -func (d stdDialer) Dial(network, address string) (net.Conn, error) { - return d.Dialer.Dial(network, address) -} - -// CreateDialer creates an instance of vnet.Dialer -func (n *Net) CreateDialer(d *net.Dialer) transport.Dialer { - return stdDialer{d} -} diff --git a/vendor/github.com/pion/transport/v2/utils/xor/xor_amd64.go b/vendor/github.com/pion/transport/v2/utils/xor/xor_amd64.go deleted file mode 100644 index ded8e0d35..000000000 --- a/vendor/github.com/pion/transport/v2/utils/xor/xor_amd64.go +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-FileCopyrightText: 2018 The Go Authors. All rights reserved. -// SPDX-License-Identifier: BSD-3-Clause - -//go:build !gccgo -// +build !gccgo - -// Package xor provides utility functions used by other Pion -// packages. AMD64 arch. -package xor - -// XorBytes xors the bytes in a and b. The destination should have enough -// space, otherwise xorBytes will panic. Returns the number of bytes xor'd. -// -//revive:disable-next-line -func XorBytes(dst, a, b []byte) int { - n := len(a) - if len(b) < n { - n = len(b) - } - if n == 0 { - return 0 - } - _ = dst[n-1] - xorBytesSSE2(&dst[0], &a[0], &b[0], n) // amd64 must have SSE2 - return n -} - -//go:noescape -func xorBytesSSE2(dst, a, b *byte, n int) diff --git a/vendor/github.com/pion/transport/v2/utils/xor/xor_amd64.s b/vendor/github.com/pion/transport/v2/utils/xor/xor_amd64.s deleted file mode 100644 index f66ac95a2..000000000 --- a/vendor/github.com/pion/transport/v2/utils/xor/xor_amd64.s +++ /dev/null @@ -1,56 +0,0 @@ -// SPDX-FileCopyrightText: 2018 The Go Authors. All rights reserved. -// SPDX-License-Identifier: BSD-3-Clause - -// go:build !gccgo -// +build !gccgo - -#include "textflag.h" - -// func xorBytesSSE2(dst, a, b *byte, n int) -TEXT ·xorBytesSSE2(SB), NOSPLIT, $0 - MOVQ dst+0(FP), BX - MOVQ a+8(FP), SI - MOVQ b+16(FP), CX - MOVQ n+24(FP), DX - TESTQ $15, DX // AND 15 & len, if not zero jump to not_aligned. - JNZ not_aligned - -aligned: - MOVQ $0, AX // position in slices - -loop16b: - MOVOU (SI)(AX*1), X0 // XOR 16byte forwards. - MOVOU (CX)(AX*1), X1 - PXOR X1, X0 - MOVOU X0, (BX)(AX*1) - ADDQ $16, AX - CMPQ DX, AX - JNE loop16b - RET - -loop_1b: - SUBQ $1, DX // XOR 1byte backwards. - MOVB (SI)(DX*1), DI - MOVB (CX)(DX*1), AX - XORB AX, DI - MOVB DI, (BX)(DX*1) - TESTQ $7, DX // AND 7 & len, if not zero jump to loop_1b. - JNZ loop_1b - CMPQ DX, $0 // if len is 0, ret. - JE ret - TESTQ $15, DX // AND 15 & len, if zero jump to aligned. - JZ aligned - -not_aligned: - TESTQ $7, DX // AND $7 & len, if not zero jump to loop_1b. - JNE loop_1b - SUBQ $8, DX // XOR 8bytes backwards. - MOVQ (SI)(DX*1), DI - MOVQ (CX)(DX*1), AX - XORQ AX, DI - MOVQ DI, (BX)(DX*1) - CMPQ DX, $16 // if len is greater or equal 16 here, it must be aligned. - JGE aligned - -ret: - RET diff --git a/vendor/github.com/pion/transport/v2/utils/xor/xor_arm.go b/vendor/github.com/pion/transport/v2/utils/xor/xor_arm.go deleted file mode 100644 index 25d6b72d8..000000000 --- a/vendor/github.com/pion/transport/v2/utils/xor/xor_arm.go +++ /dev/null @@ -1,60 +0,0 @@ -// SPDX-FileCopyrightText: 2022 The Pion community -// SPDX-License-Identifier: MIT - -//go:build !gccgo -// +build !gccgo - -// Package xor provides utility functions used by other Pion -// packages. ARM arch. -package xor - -import ( - "unsafe" - - "golang.org/x/sys/cpu" -) - -const wordSize = int(unsafe.Sizeof(uintptr(0))) // nolint:gosec -var hasNEON = cpu.ARM.HasNEON // nolint:gochecknoglobals - -func isAligned(a *byte) bool { - return uintptr(unsafe.Pointer(a))%uintptr(wordSize) == 0 -} - -// XorBytes xors the bytes in a and b. The destination should have enough -// space, otherwise xorBytes will panic. Returns the number of bytes xor'd. -// -//revive:disable-next-line -func XorBytes(dst, a, b []byte) int { - n := len(a) - if len(b) < n { - n = len(b) - } - if n == 0 { - return 0 - } - // make sure dst has enough space - _ = dst[n-1] - - if hasNEON { - xorBytesNEON32(&dst[0], &a[0], &b[0], n) - } else if isAligned(&dst[0]) && isAligned(&a[0]) && isAligned(&b[0]) { - xorBytesARM32(&dst[0], &a[0], &b[0], n) - } else { - safeXORBytes(dst, a, b, n) - } - return n -} - -// n needs to be smaller or equal than the length of a and b. -func safeXORBytes(dst, a, b []byte, n int) { - for i := 0; i < n; i++ { - dst[i] = a[i] ^ b[i] - } -} - -//go:noescape -func xorBytesARM32(dst, a, b *byte, n int) - -//go:noescape -func xorBytesNEON32(dst, a, b *byte, n int) diff --git a/vendor/github.com/pion/transport/v2/utils/xor/xor_arm.s b/vendor/github.com/pion/transport/v2/utils/xor/xor_arm.s deleted file mode 100644 index 5e52a2d64..000000000 --- a/vendor/github.com/pion/transport/v2/utils/xor/xor_arm.s +++ /dev/null @@ -1,116 +0,0 @@ -// SPDX-FileCopyrightText: 2022 The Pion community -// SPDX-License-Identifier: MIT - -// go:build !gccgo -// +build !gccgo - -#include "textflag.h" - -// func xorBytesARM32(dst, a, b *byte, n int) -TEXT ·xorBytesARM32(SB), NOSPLIT|NOFRAME, $0 - MOVW dst+0(FP), R0 - MOVW a+4(FP), R1 - MOVW b+8(FP), R2 - MOVW n+12(FP), R3 - CMP $4, R3 - BLT less_than4 - -loop_4: - MOVW.P 4(R1), R4 - MOVW.P 4(R2), R5 - EOR R4, R5, R5 - MOVW.P R5, 4(R0) - - SUB $4, R3 - CMP $4, R3 - BGE loop_4 - -less_than4: - CMP $2, R3 - BLT less_than2 - MOVH.P 2(R1), R4 - MOVH.P 2(R2), R5 - EOR R4, R5, R5 - MOVH.P R5, 2(R0) - - SUB $2, R3 - -less_than2: - CMP $0, R3 - BEQ end - MOVB (R1), R4 - MOVB (R2), R5 - EOR R4, R5, R5 - MOVB R5, (R0) -end: - RET - -// func xorBytesNEON32(dst, a, b *byte, n int) -TEXT ·xorBytesNEON32(SB), NOSPLIT|NOFRAME, $0 - MOVW dst+0(FP), R0 - MOVW a+4(FP), R1 - MOVW b+8(FP), R2 - MOVW n+12(FP), R3 - CMP $32, R3 - BLT less_than32 - -loop_32: - WORD $0xF421020D // vld1.u8 {q0, q1}, [r1]! - WORD $0xF422420D // vld1.u8 {q2, q3}, [r2]! - WORD $0xF3004154 // veor q2, q0, q2 - WORD $0xF3026156 // veor q3, q1, q3 - WORD $0xF400420D // vst1.u8 {q2, q3}, [r0]! - - SUB $32, R3 - CMP $32, R3 - BGE loop_32 - -less_than32: - CMP $16, R3 - BLT less_than16 - WORD $0xF4210A0D // vld1.u8 q0, [r1]! - WORD $0xF4222A0D // vld1.u8 q1, [r2]! - WORD $0xF3002152 // veor q1, q0, q1 - WORD $0xF4002A0D // vst1.u8 {q1}, [r0]! - - SUB $16, R3 - -less_than16: - CMP $8, R3 - BLT less_than8 - WORD $0xF421070D // vld1.u8 d0, [r1]! - WORD $0xF422170D // vld1.u8 d1, [r2]! - WORD $0xF3001111 // veor d1, d0, d1 - WORD $0xF400170D // vst1.u8 {d1}, [r0]! - - SUB $8, R3 - -less_than8: - CMP $4, R3 - BLT less_than4 - MOVW.P 4(R1), R4 - MOVW.P 4(R2), R5 - EOR R4, R5, R5 - MOVW.P R5, 4(R0) - - SUB $4, R3 - -less_than4: - CMP $2, R3 - BLT less_than2 - MOVH.P 2(R1), R4 - MOVH.P 2(R2), R5 - EOR R4, R5, R5 - MOVH.P R5, 2(R0) - - SUB $2, R3 - -less_than2: - CMP $0, R3 - BEQ end - MOVB (R1), R4 - MOVB (R2), R5 - EOR R4, R5, R5 - MOVB R5, (R0) -end: - RET diff --git a/vendor/github.com/pion/transport/v2/utils/xor/xor_arm64.go b/vendor/github.com/pion/transport/v2/utils/xor/xor_arm64.go deleted file mode 100644 index 7002ab7c9..000000000 --- a/vendor/github.com/pion/transport/v2/utils/xor/xor_arm64.go +++ /dev/null @@ -1,31 +0,0 @@ -// SPDX-FileCopyrightText: 2020 The Go Authors. All rights reserved. -// SPDX-License-Identifier: BSD-3-Clause - -//go:build !gccgo -// +build !gccgo - -// Package xor provides utility functions used by other Pion -// packages. ARM64 arch. -package xor - -// XorBytes xors the bytes in a and b. The destination should have enough -// space, otherwise xorBytes will panic. Returns the number of bytes xor'd. -// -//revive:disable-next-line -func XorBytes(dst, a, b []byte) int { - n := len(a) - if len(b) < n { - n = len(b) - } - if n == 0 { - return 0 - } - // make sure dst has enough space - _ = dst[n-1] - - xorBytesARM64(&dst[0], &a[0], &b[0], n) - return n -} - -//go:noescape -func xorBytesARM64(dst, a, b *byte, n int) diff --git a/vendor/github.com/pion/transport/v2/utils/xor/xor_arm64.s b/vendor/github.com/pion/transport/v2/utils/xor/xor_arm64.s deleted file mode 100644 index 0b82d0992..000000000 --- a/vendor/github.com/pion/transport/v2/utils/xor/xor_arm64.s +++ /dev/null @@ -1,69 +0,0 @@ -// SPDX-FileCopyrightText: 2020 The Go Authors. All rights reserved. -// SPDX-License-Identifier: BSD-3-Clause - -//go:build !gccgo -// +build !gccgo - -#include "textflag.h" - -// func xorBytesARM64(dst, a, b *byte, n int) -TEXT ·xorBytesARM64(SB), NOSPLIT|NOFRAME, $0 - MOVD dst+0(FP), R0 - MOVD a+8(FP), R1 - MOVD b+16(FP), R2 - MOVD n+24(FP), R3 - CMP $64, R3 - BLT tail -loop_64: - VLD1.P 64(R1), [V0.B16, V1.B16, V2.B16, V3.B16] - VLD1.P 64(R2), [V4.B16, V5.B16, V6.B16, V7.B16] - VEOR V0.B16, V4.B16, V4.B16 - VEOR V1.B16, V5.B16, V5.B16 - VEOR V2.B16, V6.B16, V6.B16 - VEOR V3.B16, V7.B16, V7.B16 - VST1.P [V4.B16, V5.B16, V6.B16, V7.B16], 64(R0) - SUBS $64, R3 - CMP $64, R3 - BGE loop_64 -tail: - // quick end - CBZ R3, end - TBZ $5, R3, less_than32 - VLD1.P 32(R1), [V0.B16, V1.B16] - VLD1.P 32(R2), [V2.B16, V3.B16] - VEOR V0.B16, V2.B16, V2.B16 - VEOR V1.B16, V3.B16, V3.B16 - VST1.P [V2.B16, V3.B16], 32(R0) -less_than32: - TBZ $4, R3, less_than16 - LDP.P 16(R1), (R11, R12) - LDP.P 16(R2), (R13, R14) - EOR R11, R13, R13 - EOR R12, R14, R14 - STP.P (R13, R14), 16(R0) -less_than16: - TBZ $3, R3, less_than8 - MOVD.P 8(R1), R11 - MOVD.P 8(R2), R12 - EOR R11, R12, R12 - MOVD.P R12, 8(R0) -less_than8: - TBZ $2, R3, less_than4 - MOVWU.P 4(R1), R13 - MOVWU.P 4(R2), R14 - EORW R13, R14, R14 - MOVWU.P R14, 4(R0) -less_than4: - TBZ $1, R3, less_than2 - MOVHU.P 2(R1), R15 - MOVHU.P 2(R2), R16 - EORW R15, R16, R16 - MOVHU.P R16, 2(R0) -less_than2: - TBZ $0, R3, end - MOVBU (R1), R17 - MOVBU (R2), R19 - EORW R17, R19, R19 - MOVBU R19, (R0) -end: - RET diff --git a/vendor/github.com/pion/transport/v2/utils/xor/xor_generic.go b/vendor/github.com/pion/transport/v2/utils/xor/xor_generic.go deleted file mode 100644 index 967fed33a..000000000 --- a/vendor/github.com/pion/transport/v2/utils/xor/xor_generic.go +++ /dev/null @@ -1,78 +0,0 @@ -// SPDX-FileCopyrightText: 2013 The Go Authors. All rights reserved. -// SPDX-License-Identifier: BSD-3-Clause -// SPDX-FileCopyrightText: 2022 The Pion community -// SPDX-License-Identifier: MIT - -//go:build (!amd64 && !ppc64 && !ppc64le && !arm64 && !arm) || gccgo -// +build !amd64,!ppc64,!ppc64le,!arm64,!arm gccgo - -// Package xor provides utility functions used by other Pion -// packages. Generic arch. -package xor - -import ( - "runtime" - "unsafe" -) - -const ( - wordSize = int(unsafe.Sizeof(uintptr(0))) // nolint:gosec - supportsUnaligned = runtime.GOARCH == "386" || runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le" || runtime.GOARCH == "s390x" // nolint:gochecknoglobals -) - -func isAligned(a *byte) bool { - return uintptr(unsafe.Pointer(a))%uintptr(wordSize) == 0 -} - -// XorBytes xors the bytes in a and b. The destination should have enough -// space, otherwise xorBytes will panic. Returns the number of bytes xor'd. -// -//revive:disable-next-line -func XorBytes(dst, a, b []byte) int { - n := len(a) - if len(b) < n { - n = len(b) - } - if n == 0 { - return 0 - } - - switch { - case supportsUnaligned: - fastXORBytes(dst, a, b, n) - case isAligned(&dst[0]) && isAligned(&a[0]) && isAligned(&b[0]): - fastXORBytes(dst, a, b, n) - default: - safeXORBytes(dst, a, b, n) - } - return n -} - -// fastXORBytes xors in bulk. It only works on architectures that -// support unaligned read/writes. -// n needs to be smaller or equal than the length of a and b. -func fastXORBytes(dst, a, b []byte, n int) { - // Assert dst has enough space - _ = dst[n-1] - - w := n / wordSize - if w > 0 { - dw := *(*[]uintptr)(unsafe.Pointer(&dst)) // nolint:gosec - aw := *(*[]uintptr)(unsafe.Pointer(&a)) // nolint:gosec - bw := *(*[]uintptr)(unsafe.Pointer(&b)) // nolint:gosec - for i := 0; i < w; i++ { - dw[i] = aw[i] ^ bw[i] - } - } - - for i := (n - n%wordSize); i < n; i++ { - dst[i] = a[i] ^ b[i] - } -} - -// n needs to be smaller or equal than the length of a and b. -func safeXORBytes(dst, a, b []byte, n int) { - for i := 0; i < n; i++ { - dst[i] = a[i] ^ b[i] - } -} diff --git a/vendor/github.com/pion/transport/v2/utils/xor/xor_ppc64x.go b/vendor/github.com/pion/transport/v2/utils/xor/xor_ppc64x.go deleted file mode 100644 index bcc5926c4..000000000 --- a/vendor/github.com/pion/transport/v2/utils/xor/xor_ppc64x.go +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-FileCopyrightText: 2018 The Go Authors. All rights reserved. -// SPDX-License-Identifier: BSD-3-Clause - -//go:build (ppc64 && !gccgo) || (ppc64le && !gccgo) -// +build ppc64,!gccgo ppc64le,!gccgo - -// Package xor provides utility functions used by other Pion -// packages. PPC64 arch. -package xor - -// XorBytes xors the bytes in a and b. The destination should have enough -// space, otherwise xorBytes will panic. Returns the number of bytes xor'd. -// -//revive:disable-next-line -func XorBytes(dst, a, b []byte) int { - n := len(a) - if len(b) < n { - n = len(b) - } - if n == 0 { - return 0 - } - _ = dst[n-1] - xorBytesVSX(&dst[0], &a[0], &b[0], n) - return n -} - -//go:noescape -func xorBytesVSX(dst, a, b *byte, n int) diff --git a/vendor/github.com/pion/transport/v2/utils/xor/xor_ppc64x.s b/vendor/github.com/pion/transport/v2/utils/xor/xor_ppc64x.s deleted file mode 100644 index 22763535f..000000000 --- a/vendor/github.com/pion/transport/v2/utils/xor/xor_ppc64x.s +++ /dev/null @@ -1,87 +0,0 @@ -// SPDX-FileCopyrightText: 2018 The Go Authors. All rights reserved. -// SPDX-License-Identifier: BSD-3-Clause - -//go:build (ppc64 && !gccgo) || (ppc64le && !gccgo) -//+build ppc64,!gccgo ppc64le,!gccgo - -#include "textflag.h" - -// func xorBytesVSX(dst, a, b *byte, n int) -TEXT ·xorBytesVSX(SB), NOSPLIT, $0 - MOVD dst+0(FP), R3 // R3 = dst - MOVD a+8(FP), R4 // R4 = a - MOVD b+16(FP), R5 // R5 = b - MOVD n+24(FP), R6 // R6 = n - - CMPU R6, $32, CR7 // Check if n ≥ 32 bytes - MOVD R0, R8 // R8 = index - CMPU R6, $8, CR6 // Check if 8 ≤ n < 32 bytes - BLT CR6, small // Smaller than 8 - BLT CR7, xor16 // Case for 16 ≤ n < 32 bytes - - // Case for n ≥ 32 bytes -preloop32: - SRD $5, R6, R7 // Setup loop counter - MOVD R7, CTR - MOVD $16, R10 - ANDCC $31, R6, R9 // Check for tailing bytes for later -loop32: - LXVD2X (R4)(R8), VS32 // VS32 = a[i,...,i+15] - LXVD2X (R4)(R10), VS34 - LXVD2X (R5)(R8), VS33 // VS33 = b[i,...,i+15] - LXVD2X (R5)(R10), VS35 - XXLXOR VS32, VS33, VS32 // VS34 = a[] ^ b[] - XXLXOR VS34, VS35, VS34 - STXVD2X VS32, (R3)(R8) // Store to dst - STXVD2X VS34, (R3)(R10) - ADD $32, R8 // Update index - ADD $32, R10 - BC 16, 0, loop32 // bdnz loop16 - - BEQ CR0, done - - MOVD R9, R6 - CMP R6, $8 - BLT small -xor16: - CMP R6, $16 - BLT xor8 - LXVD2X (R4)(R8), VS32 - LXVD2X (R5)(R8), VS33 - XXLXOR VS32, VS33, VS32 - STXVD2X VS32, (R3)(R8) - ADD $16, R8 - ADD $-16, R6 - CMP R6, $8 - BLT small -xor8: - // Case for 8 ≤ n < 16 bytes - MOVD (R4)(R8), R14 // R14 = a[i,...,i+7] - MOVD (R5)(R8), R15 // R15 = b[i,...,i+7] - XOR R14, R15, R16 // R16 = a[] ^ b[] - SUB $8, R6 // n = n - 8 - MOVD R16, (R3)(R8) // Store to dst - ADD $8, R8 - - // Check if we're finished - CMP R6, R0 - BGT small - RET - - // Case for n < 8 bytes and tailing bytes from the - // previous cases. -small: - CMP R6, R0 - BEQ done - MOVD R6, CTR // Setup loop counter - -loop: - MOVBZ (R4)(R8), R14 // R14 = a[i] - MOVBZ (R5)(R8), R15 // R15 = b[i] - XOR R14, R15, R16 // R16 = a[i] ^ b[i] - MOVB R16, (R3)(R8) // Store to dst - ADD $1, R8 - BC 16, 0, loop // bdnz loop - -done: - RET diff --git a/vendor/github.com/pion/transport/v2/vnet/.gitignore b/vendor/github.com/pion/transport/v2/vnet/.gitignore deleted file mode 100644 index f2eef3e93..000000000 --- a/vendor/github.com/pion/transport/v2/vnet/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - -*.sw[poe] diff --git a/vendor/github.com/pion/transport/v2/vnet/vnet.go b/vendor/github.com/pion/transport/v2/vnet/vnet.go deleted file mode 100644 index 1d244f074..000000000 --- a/vendor/github.com/pion/transport/v2/vnet/vnet.go +++ /dev/null @@ -1,5 +0,0 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - -// Package vnet provides a virtual network layer for pion -package vnet diff --git a/vendor/github.com/pion/transport/vnet/.gitignore b/vendor/github.com/pion/transport/vnet/.gitignore new file mode 100644 index 000000000..d39fb86a3 --- /dev/null +++ b/vendor/github.com/pion/transport/vnet/.gitignore @@ -0,0 +1 @@ +*.sw[poe] diff --git a/vendor/github.com/pion/transport/v2/vnet/README.md b/vendor/github.com/pion/transport/vnet/README.md similarity index 72% rename from vendor/github.com/pion/transport/v2/vnet/README.md rename to vendor/github.com/pion/transport/vnet/README.md index bd0af2506..b502f9f8e 100644 --- a/vendor/github.com/pion/transport/v2/vnet/README.md +++ b/vendor/github.com/pion/transport/vnet/README.md @@ -38,8 +38,8 @@ A virtual network layer for pion. : +-------+ : ...................................... Note: - o: NIC (Network Interface Controller) - [1]: Net implements NIC interface. + o: NIC (Netork Interface Controller) + [1]: Net implments NIC interface. [2]: Root router has no NAT. All child routers have a NAT always. [3]: Router implements NIC interface for accesses from the parent router. @@ -61,12 +61,12 @@ Net provides 3 interfaces: +---------+ 1 * +-----------+ 1 * +-----------+ 1 * +------+ ..| :Router |----+------>o--| :Net |<>------|:Interface |<>------|:Addr | +---------+ | NIC +-----------+ +-----------+ +------+ - | <> (transport.Interface) (net.Addr) + | <> (vnet.Interface) (net.Addr) | | * +-----------+ 1 * +-----------+ 1 * +------+ +------>o--| :Router |<>------|:Interface |<>------|:Addr | NIC +-----------+ +-----------+ +------+ - <> (transport.Interface) (net.Addr) + <> (vnet.Interface) (net.Addr) ``` > The instance of `Net` will be the one passed around the project. @@ -76,8 +76,8 @@ Net provides 3 interfaces: ## Implementation ### Design Policy -* Each pion package should have config object which has `Net` (of type `transport.Net`) property. - - Just like how we distribute `LoggerFactory` throughout the pion project. +* Each pion package should have config object which has `Net` (of type vnet.Net) property. (just like how + we distribute `LoggerFactory` throughout the pion project. * DNS => a simple dictionary (global)? * Each Net has routing capability (a goroutine) * Use interface provided net package as much as possible @@ -86,8 +86,10 @@ Net provides 3 interfaces: - Easy to control / monitor (stats, etc) * Root router has no NAT (== Internet / WAN) * Non-root router has a NAT always -* When a Net is instantiated, it will automatically add `lo0` and `eth0` interface, and `lo0` will have one IP address, 127.0.0.1. (this is not used in pion/ice, however) -* When a Net is added to a router, the router automatically assign an IP address for `eth0` interface. +* When a Net is instantiated, it will automatically add `lo0` and `eth0` interface, and `lo0` will +have one IP address, 127.0.0.1. (this is not used in pion/ice, however) +* When a Net is added to a router, the router automatically assign an IP address for `eth0` +interface. - For simplicity * User data won't fragment, but optionally drop chunk larger than MTU * IPv6 is not supported @@ -96,14 +98,13 @@ Net provides 3 interfaces: 1. Create a root router (WAN) 1. Create child routers and add to its parent (forms a tree, don't create a loop!) 1. Add instances of Net to each routers -1. Call Stop(), or Stop(), on the top router, which propagates all other routers +1. Call Stop(), or Stop(), on the top router, which propages all other routers #### Example: WAN with one endpoint (vnet) ```go import ( "net" - "github.com/pion/transport" "github.com/pion/transport/vnet" "github.com/pion/logging" ) @@ -140,7 +141,7 @@ if err = wan.Start(); err != nil { // // Stop the router. -// This will stop all internal Go routines in the router tree. +// This will stop all internal goroutines in the router tree. // (No need to call Stop() on child routers) if err = wan.Stop(); err != nil { // handle error @@ -157,17 +158,17 @@ instance (`nw` in the above example) like this: ```go type AgentConfig struct { : - Net: transport.Net, + Net: *vnet.Net, } type Agent struct { : - net: transport.Net, + net: *vnet.Net, } func NetAgent(config *AgentConfig) *Agent { if config.Net == nil { - config.Net = vnet.NewNet() + config.Net = vnet.NewNet(nil) // defaults to native operation } return &Agent { @@ -188,25 +189,26 @@ func (a *Agent) listenUDP(...) error { } ``` + ### Compatibility and Support Status -|`net`
(built-in) |`vnet` |Note | -|:--- |:--- |:--- | -| net.Interfaces() | a.net.Interfaces() | | -| net.InterfaceByName() | a.net.InterfaceByName() | | -| net.ResolveUDPAddr() | a.net.ResolveUDPAddr() | | -| net.ListenPacket() | a.net.ListenPacket() | | -| net.ListenUDP() | a.net.ListenUDP() | ListenPacket() is recommended | -| net.Listen() | a.net.Listen() | TODO) | -| net.ListenTCP() | (not supported) | Listen() would be recommended | -| net.Dial() | a.net.Dial() | | -| net.DialUDP() | a.net.DialUDP() | | -| net.DialTCP() | (not supported) | | -| net.Interface | transport.Interface | | -| net.PacketConn | (use it as-is) | | -| net.UDPConn | transport.UDPConn | | -| net.TCPConn | transport.TCPConn | TODO: Use net.Conn in your code | -| net.Dialer | transport.Dialer | Use a.net.CreateDialer() to create it.
The use of vnet.Dialer is currently experimental. | +|`net`
(built-in)|`vnet`|Note| +|---|---|---| +|net.Interfaces()|a.net.Interfaces()|| +|net.InterfaceByName()|a.net.InterfaceByName()|| +|net.ResolveUDPAddr()|a.net.ResolveUDPAddr()|| +|net.ListenPacket()|a.net.ListenPacket()|| +|net.ListenUDP()|a.net.ListenUDP()|(ListenPacket() is recommended)| +|net.Listen()|a.net.Listen()|(TODO)| +|net.ListenTCP()|(not supported)|(Listen() would be recommended)| +|net.Dial()|a.net.Dial()|| +|net.DialUDP()|a.net.DialUDP()|| +|net.DialTCP()|(not supported)|| +|net.Interface|vnet.Interface|| +|net.PacketConn|(use it as-is)|| +|net.UDPConn|vnet.UDPConn|Use vnet.UDPPacketConn in your code| +|net.TCPConn|vnet.TCPConn|(TODO)|Use net.Conn in your code| +|net.Dialer|vnet.Dialer|Use a.net.CreateDialer() to create it.
The use of vnet.Dialer is currently experimental.| > `a.net` is an instance of Net class, and types are defined under the package name `vnet` @@ -219,7 +221,7 @@ func (a *Agent) listenUDP(...) error { * Support of IPv6 * Write a bunch of examples for building virtual networks. * Add network impairment features (on Router) - - Introduce latency / jitter + - Introduce lantecy / jitter - Packet filtering handler (allow selectively drop packets, etc.) * Add statistics data retrieval - Total number of packets forward by each router @@ -228,4 +230,10 @@ func (a *Agent) listenUDP(...) error { ## References * [Comparing Simulated Packet Loss and RealWorld Network Congestion](https://www.riverbed.com/document/fpo/WhitePaper-Riverbed-SimulatedPacketLoss.pdf) -* [wireguard-go using GVisor's netstack](https://github.com/WireGuard/wireguard-go/tree/master/tun/netstack) \ No newline at end of file + +### Code experiments +* [CIDR and IPMask](https://play.golang.org/p/B7OBhkZqjmj) +* [Test with net.IP](https://play.golang.org/p/AgXd23wKY4W) +* [ListenPacket](https://play.golang.org/p/d4vasbnRimQ) +* [isDottedIP()](https://play.golang.org/p/t4aZ47TgJfO) +* [SplitHostPort](https://play.golang.org/p/JtvurlcMbhn) diff --git a/vendor/github.com/pion/transport/v2/vnet/chunk.go b/vendor/github.com/pion/transport/vnet/chunk.go similarity index 96% rename from vendor/github.com/pion/transport/v2/vnet/chunk.go rename to vendor/github.com/pion/transport/vnet/chunk.go index 9f59c9ced..7a87a2fd7 100644 --- a/vendor/github.com/pion/transport/v2/vnet/chunk.go +++ b/vendor/github.com/pion/transport/vnet/chunk.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( @@ -158,7 +155,7 @@ func (c *chunkUDP) Clone() Chunk { } func (c *chunkUDP) Network() string { - return udp + return udpString } func (c *chunkUDP) String() string { @@ -173,7 +170,7 @@ func (c *chunkUDP) String() string { } func (c *chunkUDP) setSourceAddr(address string) error { - addr, err := net.ResolveUDPAddr(udp, address) + addr, err := net.ResolveUDPAddr(udpString, address) if err != nil { return err } @@ -183,7 +180,7 @@ func (c *chunkUDP) setSourceAddr(address string) error { } func (c *chunkUDP) setDestinationAddr(address string) error { - addr, err := net.ResolveUDPAddr(udp, address) + addr, err := net.ResolveUDPAddr(udpString, address) if err != nil { return err } diff --git a/vendor/github.com/pion/transport/v2/vnet/chunk_queue.go b/vendor/github.com/pion/transport/vnet/chunk_queue.go similarity index 91% rename from vendor/github.com/pion/transport/v2/vnet/chunk_queue.go rename to vendor/github.com/pion/transport/vnet/chunk_queue.go index 2393254a6..c424307ac 100644 --- a/vendor/github.com/pion/transport/v2/vnet/chunk_queue.go +++ b/vendor/github.com/pion/transport/vnet/chunk_queue.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( diff --git a/vendor/github.com/pion/transport/v2/vnet/conn.go b/vendor/github.com/pion/transport/vnet/conn.go similarity index 73% rename from vendor/github.com/pion/transport/v2/vnet/conn.go rename to vendor/github.com/pion/transport/vnet/conn.go index 8f6f34269..f4b8b9290 100644 --- a/vendor/github.com/pion/transport/v2/vnet/conn.go +++ b/vendor/github.com/pion/transport/vnet/conn.go @@ -1,18 +1,12 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( "errors" - "fmt" "io" "math" "net" "sync" "time" - - "github.com/pion/transport/v2" ) const ( @@ -28,6 +22,14 @@ var ( errNoRemAddr = errors.New("no remAddr defined") ) +// UDPPacketConn is packet-oriented connection for UDP. +type UDPPacketConn interface { + net.PacketConn + Read(b []byte) (int, error) + RemoteAddr() net.Addr + Write(b []byte) (int, error) +} + // vNet implements this type connObserver interface { write(c Chunk) error @@ -36,7 +38,7 @@ type connObserver interface { } // UDPConn is the implementation of the Conn and PacketConn interfaces for UDP network connections. -// compatible with net.PacketConn and net.Conn +// comatible with net.PacketConn and net.Conn type UDPConn struct { locAddr *net.UDPAddr // read-only remAddr *net.UDPAddr // read-only @@ -47,8 +49,6 @@ type UDPConn struct { readTimer *time.Timer // thread-safe } -var _ transport.UDPConn = &UDPConn{} - func newUDPConn(locAddr, remAddr *net.UDPAddr, obs connObserver) (*UDPConn, error) { if obs == nil { return nil, errObsCannotBeNil @@ -63,84 +63,6 @@ func newUDPConn(locAddr, remAddr *net.UDPAddr, obs connObserver) (*UDPConn, erro }, nil } -// Close closes the connection. -// Any blocked ReadFrom or WriteTo operations will be unblocked and return errors. -func (c *UDPConn) Close() error { - c.mu.Lock() - defer c.mu.Unlock() - - if c.closed { - return errAlreadyClosed - } - c.closed = true - close(c.readCh) - - c.obs.onClosed(c.locAddr) - return nil -} - -// LocalAddr returns the local network address. -func (c *UDPConn) LocalAddr() net.Addr { - return c.locAddr -} - -// RemoteAddr returns the remote network address. -func (c *UDPConn) RemoteAddr() net.Addr { - return c.remAddr -} - -// SetDeadline sets the read and write deadlines associated -// with the connection. It is equivalent to calling both -// SetReadDeadline and SetWriteDeadline. -// -// A deadline is an absolute time after which I/O operations -// fail with a timeout (see type Error) instead of -// blocking. The deadline applies to all future and pending -// I/O, not just the immediately following call to ReadFrom or -// WriteTo. After a deadline has been exceeded, the connection -// can be refreshed by setting a deadline in the future. -// -// An idle timeout can be implemented by repeatedly extending -// the deadline after successful ReadFrom or WriteTo calls. -// -// A zero value for t means I/O operations will not time out. -func (c *UDPConn) SetDeadline(t time.Time) error { - return c.SetReadDeadline(t) -} - -// SetReadDeadline sets the deadline for future ReadFrom calls -// and any currently-blocked ReadFrom call. -// A zero value for t means ReadFrom will not time out. -func (c *UDPConn) SetReadDeadline(t time.Time) error { - var d time.Duration - var noDeadline time.Time - if t == noDeadline { - d = time.Duration(math.MaxInt64) - } else { - d = time.Until(t) - } - c.readTimer.Reset(d) - return nil -} - -// SetWriteDeadline sets the deadline for future WriteTo calls -// and any currently-blocked WriteTo call. -// Even if write times out, it may return n > 0, indicating that -// some of the data was successfully written. -// A zero value for t means WriteTo will not time out. -func (c *UDPConn) SetWriteDeadline(time.Time) error { - // Write never blocks. - return nil -} - -// Read reads data from the connection. -// Read can be made to time out and return an Error with Timeout() == true -// after a fixed time limit; see SetDeadline and SetReadDeadline. -func (c *UDPConn) Read(b []byte) (int, error) { - n, _, err := c.ReadFrom(b) - return n, err -} - // ReadFrom reads a packet from the connection, // copying the payload into p. It returns the number of // bytes copied into p and the return address that @@ -191,40 +113,6 @@ loop: } } -// ReadFromUDP acts like ReadFrom but returns a UDPAddr. -func (c *UDPConn) ReadFromUDP(b []byte) (int, *net.UDPAddr, error) { - n, addr, err := c.ReadFrom(b) - - udpAddr, ok := addr.(*net.UDPAddr) - if !ok { - return -1, nil, fmt.Errorf("%w: %s", transport.ErrNotUDPAddress, addr) - } - - return n, udpAddr, err -} - -// ReadMsgUDP reads a message from c, copying the payload into b and -// the associated out-of-band data into oob. It returns the number of -// bytes copied into b, the number of bytes copied into oob, the flags -// that were set on the message and the source address of the message. -// -// The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be -// used to manipulate IP-level socket options in oob. -func (c *UDPConn) ReadMsgUDP([]byte, []byte) (n, oobn, flags int, addr *net.UDPAddr, err error) { - return -1, -1, -1, nil, transport.ErrNotSupported -} - -// Write writes data to the connection. -// Write can be made to time out and return an Error with Timeout() == true -// after a fixed time limit; see SetDeadline and SetWriteDeadline. -func (c *UDPConn) Write(b []byte) (int, error) { - if c.remAddr == nil { - return 0, errNoRemAddr - } - - return c.WriteTo(b, c.remAddr) -} - // WriteTo writes a packet with payload p to addr. // WriteTo can be made to time out and return // an Error with Timeout() == true after a fixed time limit; @@ -254,33 +142,93 @@ func (c *UDPConn) WriteTo(p []byte, addr net.Addr) (n int, err error) { return len(p), nil } -// WriteToUDP acts like WriteTo but takes a UDPAddr. -func (c *UDPConn) WriteToUDP(b []byte, addr *net.UDPAddr) (int, error) { - return c.WriteTo(b, addr) +// Close closes the connection. +// Any blocked ReadFrom or WriteTo operations will be unblocked and return errors. +func (c *UDPConn) Close() error { + c.mu.Lock() + defer c.mu.Unlock() + + if c.closed { + return errAlreadyClosed + } + c.closed = true + close(c.readCh) + + c.obs.onClosed(c.locAddr) + return nil } -// WriteMsgUDP writes a message to addr via c if c isn't connected, or -// to c's remote address if c is connected (in which case addr must be -// nil). The payload is copied from b and the associated out-of-band -// data is copied from oob. It returns the number of payload and -// out-of-band bytes written. +// LocalAddr returns the local network address. +func (c *UDPConn) LocalAddr() net.Addr { + return c.locAddr +} + +// SetDeadline sets the read and write deadlines associated +// with the connection. It is equivalent to calling both +// SetReadDeadline and SetWriteDeadline. // -// The packages golang.org/x/net/ipv4 and golang.org/x/net/ipv6 can be -// used to manipulate IP-level socket options in oob. -func (c *UDPConn) WriteMsgUDP([]byte, []byte, *net.UDPAddr) (n, oobn int, err error) { - return -1, -1, transport.ErrNotSupported +// A deadline is an absolute time after which I/O operations +// fail with a timeout (see type Error) instead of +// blocking. The deadline applies to all future and pending +// I/O, not just the immediately following call to ReadFrom or +// WriteTo. After a deadline has been exceeded, the connection +// can be refreshed by setting a deadline in the future. +// +// An idle timeout can be implemented by repeatedly extending +// the deadline after successful ReadFrom or WriteTo calls. +// +// A zero value for t means I/O operations will not time out. +func (c *UDPConn) SetDeadline(t time.Time) error { + return c.SetReadDeadline(t) } -// SetReadBuffer sets the size of the operating system's -// receive buffer associated with the connection. -func (c *UDPConn) SetReadBuffer(int) error { - return transport.ErrNotSupported +// SetReadDeadline sets the deadline for future ReadFrom calls +// and any currently-blocked ReadFrom call. +// A zero value for t means ReadFrom will not time out. +func (c *UDPConn) SetReadDeadline(t time.Time) error { + var d time.Duration + var noDeadline time.Time + if t == noDeadline { + d = time.Duration(math.MaxInt64) + } else { + d = time.Until(t) + } + c.readTimer.Reset(d) + return nil } -// SetWriteBuffer sets the size of the operating system's -// transmit buffer associated with the connection. -func (c *UDPConn) SetWriteBuffer(int) error { - return transport.ErrNotSupported +// SetWriteDeadline sets the deadline for future WriteTo calls +// and any currently-blocked WriteTo call. +// Even if write times out, it may return n > 0, indicating that +// some of the data was successfully written. +// A zero value for t means WriteTo will not time out. +func (c *UDPConn) SetWriteDeadline(t time.Time) error { + // Write never blocks. + return nil +} + +// Read reads data from the connection. +// Read can be made to time out and return an Error with Timeout() == true +// after a fixed time limit; see SetDeadline and SetReadDeadline. +func (c *UDPConn) Read(b []byte) (int, error) { + n, _, err := c.ReadFrom(b) + return n, err +} + +// RemoteAddr returns the remote network address. +func (c *UDPConn) RemoteAddr() net.Addr { + return c.remAddr +} + +// Write writes data to the connection. +// Write can be made to time out and return an Error with Timeout() == true +// after a fixed time limit; see SetDeadline and SetWriteDeadline. +func (c *UDPConn) Write(b []byte) (int, error) { + if c.remAddr == nil { + return 0, errNoRemAddr + } + + return c.WriteTo(b, c.remAddr) } func (c *UDPConn) onInboundChunk(chunk Chunk) { diff --git a/vendor/github.com/pion/transport/v2/vnet/conn_map.go b/vendor/github.com/pion/transport/vnet/conn_map.go similarity index 83% rename from vendor/github.com/pion/transport/v2/vnet/conn_map.go rename to vendor/github.com/pion/transport/vnet/conn_map.go index da22483ef..d52818d27 100644 --- a/vendor/github.com/pion/transport/v2/vnet/conn_map.go +++ b/vendor/github.com/pion/transport/vnet/conn_map.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( @@ -30,7 +27,7 @@ func (m *udpConnMap) insert(conn *UDPConn) error { m.mutex.Lock() defer m.mutex.Unlock() - udpAddr := conn.LocalAddr().(*net.UDPAddr) //nolint:forcetypeassert + udpAddr := conn.LocalAddr().(*net.UDPAddr) // check if the port has a listener conns, ok := m.portMap[udpAddr.Port] @@ -40,7 +37,7 @@ func (m *udpConnMap) insert(conn *UDPConn) error { } for _, conn := range conns { - laddr := conn.LocalAddr().(*net.UDPAddr) //nolint:forcetypeassert + laddr := conn.LocalAddr().(*net.UDPAddr) if laddr.IP.IsUnspecified() || laddr.IP.Equal(udpAddr.IP) { return errAddressAlreadyInUse } @@ -59,7 +56,7 @@ func (m *udpConnMap) find(addr net.Addr) (*UDPConn, bool) { m.mutex.Lock() // could be RLock, but we have delete() op defer m.mutex.Unlock() - udpAddr := addr.(*net.UDPAddr) //nolint:forcetypeassert + udpAddr := addr.(*net.UDPAddr) if conns, ok := m.portMap[udpAddr.Port]; ok { if udpAddr.IP.IsUnspecified() { @@ -73,7 +70,7 @@ func (m *udpConnMap) find(addr net.Addr) (*UDPConn, bool) { } for _, conn := range conns { - laddr := conn.LocalAddr().(*net.UDPAddr) //nolint:forcetypeassert + laddr := conn.LocalAddr().(*net.UDPAddr) if laddr.IP.IsUnspecified() || laddr.IP.Equal(udpAddr.IP) { return conn, ok } @@ -87,7 +84,7 @@ func (m *udpConnMap) delete(addr net.Addr) error { m.mutex.Lock() defer m.mutex.Unlock() - udpAddr := addr.(*net.UDPAddr) //nolint:forcetypeassert + udpAddr := addr.(*net.UDPAddr) conns, ok := m.portMap[udpAddr.Port] if !ok { @@ -103,7 +100,7 @@ func (m *udpConnMap) delete(addr net.Addr) error { newConns := []*UDPConn{} for _, conn := range conns { - laddr := conn.LocalAddr().(*net.UDPAddr) //nolint:forcetypeassert + laddr := conn.LocalAddr().(*net.UDPAddr) if laddr.IP.IsUnspecified() { // This can't happen! return errCannotRemoveUnspecifiedIP diff --git a/vendor/github.com/pion/transport/v2/vnet/delay_filter.go b/vendor/github.com/pion/transport/vnet/delay_filter.go similarity index 90% rename from vendor/github.com/pion/transport/v2/vnet/delay_filter.go rename to vendor/github.com/pion/transport/vnet/delay_filter.go index 119e34eac..327f40618 100644 --- a/vendor/github.com/pion/transport/v2/vnet/delay_filter.go +++ b/vendor/github.com/pion/transport/vnet/delay_filter.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( @@ -50,7 +47,7 @@ func (f *DelayFilter) Run(ctx context.Context) { case <-ctx.Done(): return case <-f.push: - next := f.queue.peek().(timedChunk) //nolint:forcetypeassert + next := f.queue.peek().(timedChunk) if !timer.Stop() { <-timer.C } diff --git a/vendor/github.com/pion/transport/v2/vnet/errors.go b/vendor/github.com/pion/transport/vnet/errors.go similarity index 71% rename from vendor/github.com/pion/transport/v2/vnet/errors.go rename to vendor/github.com/pion/transport/vnet/errors.go index 22c7c2d36..d0e9394f5 100644 --- a/vendor/github.com/pion/transport/v2/vnet/errors.go +++ b/vendor/github.com/pion/transport/vnet/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet type timeoutError struct { diff --git a/vendor/github.com/pion/transport/vnet/interface.go b/vendor/github.com/pion/transport/vnet/interface.go new file mode 100644 index 000000000..ec80c0b78 --- /dev/null +++ b/vendor/github.com/pion/transport/vnet/interface.go @@ -0,0 +1,40 @@ +package vnet + +import ( + "errors" + "net" +) + +var errNoAddressAssigned = errors.New("no address assigned") + +// See: https://play.golang.org/p/nBO9KGYEziv + +// InterfaceBase ... +type InterfaceBase net.Interface + +// Interface ... +type Interface struct { + InterfaceBase + addrs []net.Addr +} + +// NewInterface ... +func NewInterface(ifc net.Interface) *Interface { + return &Interface{ + InterfaceBase: InterfaceBase(ifc), + addrs: nil, + } +} + +// AddAddr ... +func (ifc *Interface) AddAddr(addr net.Addr) { + ifc.addrs = append(ifc.addrs, addr) +} + +// Addrs ... +func (ifc *Interface) Addrs() ([]net.Addr, error) { + if len(ifc.addrs) == 0 { + return nil, errNoAddressAssigned + } + return ifc.addrs, nil +} diff --git a/vendor/github.com/pion/transport/v2/vnet/loss_filter.go b/vendor/github.com/pion/transport/vnet/loss_filter.go similarity index 86% rename from vendor/github.com/pion/transport/v2/vnet/loss_filter.go rename to vendor/github.com/pion/transport/vnet/loss_filter.go index 4b2d75f38..b5a23f405 100644 --- a/vendor/github.com/pion/transport/v2/vnet/loss_filter.go +++ b/vendor/github.com/pion/transport/vnet/loss_filter.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( diff --git a/vendor/github.com/pion/transport/v2/vnet/nat.go b/vendor/github.com/pion/transport/vnet/nat.go similarity index 93% rename from vendor/github.com/pion/transport/v2/vnet/nat.go rename to vendor/github.com/pion/transport/vnet/nat.go index a4be36ecd..4ece5faad 100644 --- a/vendor/github.com/pion/transport/v2/vnet/nat.go +++ b/vendor/github.com/pion/transport/vnet/nat.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( @@ -25,9 +22,8 @@ var ( // EndpointDependencyType defines a type of behavioral dependendency on the // remote endpoint's IP address or port number. This is used for the two // kinds of behaviors: -// - Port mapping behavior -// - Filtering behavior -// +// - Port mapping behavior +// - Filtering behavior // See: https://tools.ietf.org/html/rfc4787 type EndpointDependencyType uint8 @@ -62,7 +58,7 @@ type NATType struct { Mode NATMode MappingBehavior EndpointDependencyType FilteringBehavior EndpointDependencyType - Hairpinning bool // Not implemented yet + Hairpining bool // Not implemented yet PortPreservation bool // Not implemented yet MappingLifeTime time.Duration } @@ -155,14 +151,14 @@ func (n *networkAddressTranslator) translateOutbound(from Chunk) (Chunk, error) to := from.Clone() - if from.Network() == udp { + if from.Network() == udpString { if n.natType.Mode == NATModeNAT1To1 { // 1:1 NAT behavior - srcAddr := from.SourceAddr().(*net.UDPAddr) //nolint:forcetypeassert + srcAddr := from.SourceAddr().(*net.UDPAddr) srcIP := n.getPairedMappedIP(srcAddr.IP) if srcIP == nil { n.log.Debugf("[%s] drop outbound chunk %s with not route", n.name, from.String()) - return nil, nil // nolint:nilnil + return nil, nil // silently discard } srcPort := srcAddr.Port if err := to.setSourceAddr(fmt.Sprintf("%s:%d", srcIP.String(), srcPort)); err != nil { @@ -210,16 +206,16 @@ func (n *networkAddressTranslator) translateOutbound(from Chunk) (Chunk, error) iKey := fmt.Sprintf("udp:%s", m.mapped) - n.log.Debugf("[%s] created a new NAT binding oKey=%s iKey=%s", + n.log.Debugf("[%s] created a new NAT binding oKey=%s iKey=%s\n", n.name, oKey, iKey) m.filters[filterKey] = struct{}{} - n.log.Debugf("[%s] permit access from %s to %s", n.name, filterKey, m.mapped) + n.log.Debugf("[%s] permit access from %s to %s\n", n.name, filterKey, m.mapped) n.inboundMap[iKey] = m } else if _, ok := m.filters[filterKey]; !ok { - n.log.Debugf("[%s] permit access from %s to %s", n.name, filterKey, m.mapped) + n.log.Debugf("[%s] permit access from %s to %s\n", n.name, filterKey, m.mapped) m.filters[filterKey] = struct{}{} } @@ -242,15 +238,15 @@ func (n *networkAddressTranslator) translateInbound(from Chunk) (Chunk, error) { to := from.Clone() - if from.Network() == udp { + if from.Network() == udpString { if n.natType.Mode == NATModeNAT1To1 { // 1:1 NAT behavior - dstAddr := from.DestinationAddr().(*net.UDPAddr) //nolint:forcetypeassert + dstAddr := from.DestinationAddr().(*net.UDPAddr) dstIP := n.getPairedLocalIP(dstAddr.IP) if dstIP == nil { return nil, fmt.Errorf("drop %s as %w", from.String(), errNoAssociatedLocalAddress) } - dstPort := from.DestinationAddr().(*net.UDPAddr).Port //nolint:forcetypeassert + dstPort := from.DestinationAddr().(*net.UDPAddr).Port if err := to.setDestinationAddr(fmt.Sprintf("%s:%d", dstIP, dstPort)); err != nil { return nil, err } diff --git a/vendor/github.com/pion/transport/v2/vnet/net.go b/vendor/github.com/pion/transport/vnet/net.go similarity index 62% rename from vendor/github.com/pion/transport/v2/vnet/net.go rename to vendor/github.com/pion/transport/vnet/net.go index 5d0938e64..4dc6a2a06 100644 --- a/vendor/github.com/pion/transport/v2/vnet/net.go +++ b/vendor/github.com/pion/transport/vnet/net.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( @@ -12,28 +9,27 @@ import ( "strconv" "strings" "sync" - - "github.com/pion/transport/v2" ) const ( lo0String = "lo0String" - udp = "udp" - udp4 = "udp4" + udpString = "udp" ) var ( macAddrCounter uint64 = 0xBEEFED910200 //nolint:gochecknoglobals errNoInterface = errors.New("no interface is available") + errNotFound = errors.New("not found") errUnexpectedNetwork = errors.New("unexpected network") errCantAssignRequestedAddr = errors.New("can't assign requested address") errUnknownNetwork = errors.New("unknown network") errNoRouterLinked = errors.New("no router linked") errInvalidPortNumber = errors.New("invalid port number") errUnexpectedTypeSwitchFailure = errors.New("unexpected type-switch failure") - errBindFailedFor = errors.New("bind failed for") + errBindFailerFor = errors.New("bind failed for") errEndPortLessThanStart = errors.New("end port is less than the start") errPortSpaceExhausted = errors.New("port space exhausted") + errVNetDisabled = errors.New("vnet is not enabled") ) func newMACAddress() net.HardwareAddr { @@ -43,20 +39,15 @@ func newMACAddress() net.HardwareAddr { return b[2:] } -// Net represents a local network stack equivalent to a set of layers from NIC -// up to the transport (UDP / TCP) layer. -type Net struct { - interfaces []*transport.Interface // read-only - staticIPs []net.IP // read-only - router *Router // read-only - udpConns *udpConnMap // read-only +type vNet struct { + interfaces []*Interface // read-only + staticIPs []net.IP // read-only + router *Router // read-only + udpConns *udpConnMap // read-only mutex sync.RWMutex } -// Compile-time assertion -var _ transport.Net = &Net{} - -func (v *Net) _getInterfaces() ([]*transport.Interface, error) { +func (v *vNet) _getInterfaces() ([]*Interface, error) { if len(v.interfaces) == 0 { return nil, errNoInterface } @@ -64,8 +55,7 @@ func (v *Net) _getInterfaces() ([]*transport.Interface, error) { return v.interfaces, nil } -// Interfaces returns a list of the system's network interfaces. -func (v *Net) Interfaces() ([]*transport.Interface, error) { +func (v *vNet) getInterfaces() ([]*Interface, error) { v.mutex.RLock() defer v.mutex.RUnlock() @@ -73,7 +63,7 @@ func (v *Net) Interfaces() ([]*transport.Interface, error) { } // caller must hold the mutex (read) -func (v *Net) _getInterface(ifName string) (*transport.Interface, error) { +func (v *vNet) _getInterface(ifName string) (*Interface, error) { ifs, err := v._getInterfaces() if err != nil { return nil, err @@ -84,38 +74,18 @@ func (v *Net) _getInterface(ifName string) (*transport.Interface, error) { } } - return nil, fmt.Errorf("%w: %s", transport.ErrInterfaceNotFound, ifName) + return nil, fmt.Errorf("interface %s %w", ifName, errNotFound) } -func (v *Net) getInterface(ifName string) (*transport.Interface, error) { +func (v *vNet) getInterface(ifName string) (*Interface, error) { v.mutex.RLock() defer v.mutex.RUnlock() return v._getInterface(ifName) } -// InterfaceByIndex returns the interface specified by index. -// -// On Solaris, it returns one of the logical network interfaces -// sharing the logical data link; for more precision use -// InterfaceByName. -func (v *Net) InterfaceByIndex(index int) (*transport.Interface, error) { - for _, ifc := range v.interfaces { - if ifc.Index == index { - return ifc, nil - } - } - - return nil, fmt.Errorf("%w: index=%d", transport.ErrInterfaceNotFound, index) -} - -// InterfaceByName returns the interface specified by name. -func (v *Net) InterfaceByName(ifName string) (*transport.Interface, error) { - return v.getInterface(ifName) -} - // caller must hold the mutex -func (v *Net) getAllIPAddrs(ipv6 bool) []net.IP { +func (v *vNet) getAllIPAddrs(ipv6 bool) []net.IP { ips := []net.IP{} for _, ifc := range v.interfaces { @@ -145,7 +115,7 @@ func (v *Net) getAllIPAddrs(ipv6 bool) []net.IP { return ips } -func (v *Net) setRouter(r *Router) error { +func (v *vNet) setRouter(r *Router) error { v.mutex.Lock() defer v.mutex.Unlock() @@ -153,11 +123,11 @@ func (v *Net) setRouter(r *Router) error { return nil } -func (v *Net) onInboundChunk(c Chunk) { +func (v *vNet) onInboundChunk(c Chunk) { v.mutex.Lock() defer v.mutex.Unlock() - if c.Network() == udp { + if c.Network() == udpString { if conn, ok := v.udpConns.find(c.DestinationAddr()); ok { conn.onInboundChunk(c) } @@ -165,9 +135,9 @@ func (v *Net) onInboundChunk(c Chunk) { } // caller must hold the mutex -func (v *Net) _dialUDP(network string, locAddr, remAddr *net.UDPAddr) (transport.UDPConn, error) { +func (v *vNet) _dialUDP(network string, locAddr, remAddr *net.UDPAddr) (UDPPacketConn, error) { // validate network - if network != udp && network != udp4 { + if network != udpString && network != "udp4" { return nil, fmt.Errorf("%w: %s", errUnexpectedNetwork, network) } @@ -223,12 +193,11 @@ func (v *Net) _dialUDP(network string, locAddr, remAddr *net.UDPAddr) (transport return conn, nil } -// ListenPacket announces on the local network address. -func (v *Net) ListenPacket(network string, address string) (net.PacketConn, error) { +func (v *vNet) listenPacket(network string, address string) (UDPPacketConn, error) { v.mutex.Lock() defer v.mutex.Unlock() - locAddr, err := v.ResolveUDPAddr(network, address) + locAddr, err := v.resolveUDPAddr(network, address) if err != nil { return nil, err } @@ -236,28 +205,25 @@ func (v *Net) ListenPacket(network string, address string) (net.PacketConn, erro return v._dialUDP(network, locAddr, nil) } -// ListenUDP acts like ListenPacket for UDP networks. -func (v *Net) ListenUDP(network string, locAddr *net.UDPAddr) (transport.UDPConn, error) { +func (v *vNet) listenUDP(network string, locAddr *net.UDPAddr) (UDPPacketConn, error) { v.mutex.Lock() defer v.mutex.Unlock() return v._dialUDP(network, locAddr, nil) } -// DialUDP acts like Dial for UDP networks. -func (v *Net) DialUDP(network string, locAddr, remAddr *net.UDPAddr) (transport.UDPConn, error) { +func (v *vNet) dialUDP(network string, locAddr, remAddr *net.UDPAddr) (UDPPacketConn, error) { v.mutex.Lock() defer v.mutex.Unlock() return v._dialUDP(network, locAddr, remAddr) } -// Dial connects to the address on the named network. -func (v *Net) Dial(network string, address string) (net.Conn, error) { +func (v *vNet) dial(network string, address string) (UDPPacketConn, error) { v.mutex.Lock() defer v.mutex.Unlock() - remAddr, err := v.ResolveUDPAddr(network, address) + remAddr, err := v.resolveUDPAddr(network, address) if err != nil { return nil, err } @@ -270,37 +236,8 @@ func (v *Net) Dial(network string, address string) (net.Conn, error) { return v._dialUDP(network, locAddr, remAddr) } -// ResolveIPAddr returns an address of IP end point. -func (v *Net) ResolveIPAddr(_, address string) (*net.IPAddr, error) { - var err error - - // Check if host is a domain name - ip := net.ParseIP(address) - if ip == nil { - address = strings.ToLower(address) - if address == "localhost" { - ip = net.IPv4(127, 0, 0, 1) - } else { - // host is a domain name. resolve IP address by the name - if v.router == nil { - return nil, errNoRouterLinked - } - - ip, err = v.router.resolver.lookUp(address) - if err != nil { - return nil, err - } - } - } - - return &net.IPAddr{ - IP: ip, - }, nil -} - -// ResolveUDPAddr returns an address of UDP end point. -func (v *Net) ResolveUDPAddr(network, address string) (*net.UDPAddr, error) { - if network != udp && network != udp4 { +func (v *vNet) resolveUDPAddr(network, address string) (*net.UDPAddr, error) { + if network != udpString && network != "udp4" { return nil, fmt.Errorf("%w %s", errUnknownNetwork, network) } @@ -309,9 +246,23 @@ func (v *Net) ResolveUDPAddr(network, address string) (*net.UDPAddr, error) { return nil, err } - ipAddress, err := v.ResolveIPAddr("ip", host) - if err != nil { - return nil, err + // Check if host is a domain name + ip := net.ParseIP(host) + if ip == nil { + host = strings.ToLower(host) + if host == "localhost" { + ip = net.IPv4(127, 0, 0, 1) + } else { + // host is a domain name. resolve IP address by the name + if v.router == nil { + return nil, errNoRouterLinked + } + + ip, err = v.router.resolver.lookUp(host) + if err != nil { + return nil, err + } + } } port, err := strconv.Atoi(sPort) @@ -320,46 +271,15 @@ func (v *Net) ResolveUDPAddr(network, address string) (*net.UDPAddr, error) { } udpAddr := &net.UDPAddr{ - IP: ipAddress.IP, - Zone: ipAddress.Zone, + IP: ip, Port: port, } return udpAddr, nil } -// ResolveTCPAddr returns an address of TCP end point. -func (v *Net) ResolveTCPAddr(network, address string) (*net.TCPAddr, error) { - if network != udp && network != "udp4" { - return nil, fmt.Errorf("%w %s", errUnknownNetwork, network) - } - - host, sPort, err := net.SplitHostPort(address) - if err != nil { - return nil, err - } - - ipAddr, err := v.ResolveIPAddr("ip", host) - if err != nil { - return nil, err - } - - port, err := strconv.Atoi(sPort) - if err != nil { - return nil, errInvalidPortNumber - } - - udpAddr := &net.TCPAddr{ - IP: ipAddr.IP, - Zone: ipAddr.Zone, - Port: port, - } - - return udpAddr, nil -} - -func (v *Net) write(c Chunk) error { - if c.Network() == udp { +func (v *vNet) write(c Chunk) error { + if c.Network() == udpString { if udp, ok := c.(*chunkUDP); ok { if c.getDestinationIP().IsLoopback() { if conn, ok := v.udpConns.find(udp.DestinationAddr()); ok { @@ -380,8 +300,8 @@ func (v *Net) write(c Chunk) error { return nil } -func (v *Net) onClosed(addr net.Addr) { - if addr.Network() == udp { +func (v *vNet) onClosed(addr net.Addr) { + if addr.Network() == udpString { //nolint:errcheck v.udpConns.delete(addr) // #nosec } @@ -391,7 +311,7 @@ func (v *Net) onClosed(addr net.Addr) { // is any IP address ("0.0.0.0" or "::"). If locIP is a non-any addr, // this method simply returns locIP. // caller must hold the mutex -func (v *Net) determineSourceIP(locIP, dstIP net.IP) net.IP { +func (v *vNet) determineSourceIP(locIP, dstIP net.IP) net.IP { if locIP != nil && !locIP.IsUnspecified() { return locIP } @@ -423,7 +343,7 @@ func (v *Net) determineSourceIP(locIP, dstIP net.IP) net.IP { } for _, addr := range addrs { - ip := addr.(*net.IPNet).IP //nolint:forcetypeassert + ip := addr.(*net.IPNet).IP if findIPv4 { if ip.To4() != nil { srcIP = ip @@ -442,7 +362,7 @@ func (v *Net) determineSourceIP(locIP, dstIP net.IP) net.IP { } // caller must hold the mutex -func (v *Net) hasIPAddr(ip net.IP) bool { //nolint:gocognit +func (v *vNet) hasIPAddr(ip net.IP) bool { //nolint:gocognit for _, ifc := range v.interfaces { if addrs, err := ifc.Addrs(); err == nil { for _, addr := range addrs { @@ -477,7 +397,7 @@ func (v *Net) hasIPAddr(ip net.IP) bool { //nolint:gocognit } // caller must hold the mutex -func (v *Net) allocateLocalAddr(ip net.IP, port int) error { +func (v *vNet) allocateLocalAddr(ip net.IP, port int) error { // gather local IP addresses to bind var ips []net.IP if ip.IsUnspecified() { @@ -487,7 +407,7 @@ func (v *Net) allocateLocalAddr(ip net.IP, port int) error { } if len(ips) == 0 { - return fmt.Errorf("%w %s", errBindFailedFor, ip.String()) + return fmt.Errorf("%w %s", errBindFailerFor, ip.String()) } // check if all these transport addresses are not in use @@ -499,7 +419,7 @@ func (v *Net) allocateLocalAddr(ip net.IP, port int) error { if _, ok := v.udpConns.find(addr); ok { return &net.OpError{ Op: "bind", - Net: udp, + Net: udpString, Addr: addr, Err: fmt.Errorf("bind: %w", errAddressAlreadyInUse), } @@ -510,7 +430,7 @@ func (v *Net) allocateLocalAddr(ip net.IP, port int) error { } // caller must hold the mutex -func (v *Net) assignPort(ip net.IP, start, end int) (int, error) { +func (v *vNet) assignPort(ip net.IP, start, end int) (int, error) { // choose randomly from the range between start and end (inclusive) if end < start { return -1, errEndPortLessThanStart @@ -530,10 +450,6 @@ func (v *Net) assignPort(ip net.IP, start, end int) (int, error) { return -1, errPortSpaceExhausted } -func (v *Net) getStaticIPs() []net.IP { - return v.staticIPs -} - // NetConfig is a bag of configuration parameters passed to NewNet(). type NetConfig struct { // StaticIPs is an array of static IP addresses to be assigned for this Net. @@ -545,25 +461,51 @@ type NetConfig struct { StaticIP string } -// NewNet creates an instance of a virtual network. -// +// Net represents a local network stack euivalent to a set of layers from NIC +// up to the transport (UDP / TCP) layer. +type Net struct { + v *vNet + ifs []*Interface +} + +// NewNet creates an instance of Net. +// If config is nil, the virtual network is disabled. (uses corresponding +// net.Xxxx() operations. // By design, it always have lo0 and eth0 interfaces. // The lo0 has the address 127.0.0.1 assigned by default. // IP address for eth0 will be assigned when this Net is added to a router. -func NewNet(config *NetConfig) (*Net, error) { - lo0 := transport.NewInterface(net.Interface{ +func NewNet(config *NetConfig) *Net { + if config == nil { + ifs := []*Interface{} + if orgIfs, err := net.Interfaces(); err == nil { + for _, orgIfc := range orgIfs { + ifc := NewInterface(orgIfc) + if addrs, err := orgIfc.Addrs(); err == nil { + for _, addr := range addrs { + ifc.AddAddr(addr) + } + } + + ifs = append(ifs, ifc) + } + } + + return &Net{ifs: ifs} + } + + lo0 := NewInterface(net.Interface{ Index: 1, MTU: 16384, Name: lo0String, HardwareAddr: nil, Flags: net.FlagUp | net.FlagLoopback | net.FlagMulticast, }) - lo0.AddAddress(&net.IPNet{ + lo0.AddAddr(&net.IPNet{ IP: net.ParseIP("127.0.0.1"), Mask: net.CIDRMask(8, 32), }) - eth0 := transport.NewInterface(net.Interface{ + eth0 := NewInterface(net.Interface{ Index: 2, MTU: 1500, Name: "eth0", @@ -583,36 +525,153 @@ func NewNet(config *NetConfig) (*Net, error) { } } - return &Net{ - interfaces: []*transport.Interface{lo0, eth0}, + v := &vNet{ + interfaces: []*Interface{lo0, eth0}, staticIPs: staticIPs, udpConns: newUDPConnMap(), - }, nil -} + } -// DialTCP acts like Dial for TCP networks. -func (v *Net) DialTCP(string, *net.TCPAddr, *net.TCPAddr) (transport.TCPConn, error) { - return nil, transport.ErrNotSupported -} - -// ListenTCP acts like Listen for TCP networks. -func (v *Net) ListenTCP(string, *net.TCPAddr) (transport.TCPListener, error) { - return nil, transport.ErrNotSupported -} - -// CreateDialer creates an instance of vnet.Dialer -func (v *Net) CreateDialer(d *net.Dialer) transport.Dialer { - return &dialer{ - dialer: d, - net: v, + return &Net{ + v: v, } } -type dialer struct { - dialer *net.Dialer - net *Net +// Interfaces returns a list of the system's network interfaces. +func (n *Net) Interfaces() ([]*Interface, error) { + if n.v == nil { + return n.ifs, nil + } + + return n.v.getInterfaces() } -func (d *dialer) Dial(network, address string) (net.Conn, error) { - return d.net.Dial(network, address) +// InterfaceByName returns the interface specified by name. +func (n *Net) InterfaceByName(name string) (*Interface, error) { + if n.v == nil { + for _, ifc := range n.ifs { + if ifc.Name == name { + return ifc, nil + } + } + + return nil, fmt.Errorf("interface %s %w", name, errNotFound) + } + + return n.v.getInterface(name) +} + +// ListenPacket announces on the local network address. +func (n *Net) ListenPacket(network string, address string) (net.PacketConn, error) { + if n.v == nil { + return net.ListenPacket(network, address) + } + + return n.v.listenPacket(network, address) +} + +// ListenUDP acts like ListenPacket for UDP networks. +func (n *Net) ListenUDP(network string, locAddr *net.UDPAddr) (UDPPacketConn, error) { + if n.v == nil { + return net.ListenUDP(network, locAddr) + } + + return n.v.listenUDP(network, locAddr) +} + +// Dial connects to the address on the named network. +func (n *Net) Dial(network, address string) (net.Conn, error) { + if n.v == nil { + return net.Dial(network, address) + } + + return n.v.dial(network, address) +} + +// CreateDialer creates an instance of vnet.Dialer +func (n *Net) CreateDialer(dialer *net.Dialer) Dialer { + if n.v == nil { + return &vDialer{ + dialer: dialer, + } + } + + return &vDialer{ + dialer: dialer, + v: n.v, + } +} + +// DialUDP acts like Dial for UDP networks. +func (n *Net) DialUDP(network string, laddr, raddr *net.UDPAddr) (UDPPacketConn, error) { + if n.v == nil { + return net.DialUDP(network, laddr, raddr) + } + + return n.v.dialUDP(network, laddr, raddr) +} + +// ResolveUDPAddr returns an address of UDP end point. +func (n *Net) ResolveUDPAddr(network, address string) (*net.UDPAddr, error) { + if n.v == nil { + return net.ResolveUDPAddr(network, address) + } + + return n.v.resolveUDPAddr(network, address) +} + +func (n *Net) getInterface(ifName string) (*Interface, error) { + if n.v == nil { + return nil, errVNetDisabled + } + + return n.v.getInterface(ifName) +} + +func (n *Net) setRouter(r *Router) error { + if n.v == nil { + return errVNetDisabled + } + + return n.v.setRouter(r) +} + +func (n *Net) onInboundChunk(c Chunk) { + if n.v == nil { + return + } + + n.v.onInboundChunk(c) +} + +func (n *Net) getStaticIPs() []net.IP { + if n.v == nil { + return nil + } + + return n.v.staticIPs +} + +// IsVirtual tests if the virtual network is enabled. +func (n *Net) IsVirtual() bool { + return n.v != nil +} + +// Dialer is identical to net.Dialer excepts that its methods +// (Dial, DialContext) are overridden to use virtual network. +// Use vnet.CreateDialer() to create an instance of this Dialer. +type Dialer interface { + Dial(network, address string) (net.Conn, error) +} + +type vDialer struct { + dialer *net.Dialer + v *vNet +} + +func (d *vDialer) Dial(network, address string) (net.Conn, error) { + if d.v == nil { + return d.dialer.Dial(network, address) + } + + return d.v.dial(network, address) } diff --git a/vendor/github.com/pion/transport/v2/vnet/resolver.go b/vendor/github.com/pion/transport/vnet/resolver.go similarity index 87% rename from vendor/github.com/pion/transport/v2/vnet/resolver.go rename to vendor/github.com/pion/transport/vnet/resolver.go index a391cc7f0..e5166e3cd 100644 --- a/vendor/github.com/pion/transport/v2/vnet/resolver.go +++ b/vendor/github.com/pion/transport/vnet/resolver.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( @@ -14,7 +11,7 @@ import ( var ( errHostnameEmpty = errors.New("host name must not be empty") - errFailedToParseIPAddr = errors.New("failed to parse IP address") + errFailedtoParseIPAddr = errors.New("failed to parse IP address") ) type resolverConfig struct { @@ -56,7 +53,7 @@ func (r *resolver) addHost(name string, ipAddr string) error { } ip := net.ParseIP(ipAddr) if ip == nil { - return fmt.Errorf("%w \"%s\"", errFailedToParseIPAddr, ipAddr) + return fmt.Errorf("%w \"%s\"", errFailedtoParseIPAddr, ipAddr) } r.hosts[name] = ip return nil diff --git a/vendor/github.com/pion/transport/v2/vnet/router.go b/vendor/github.com/pion/transport/vnet/router.go similarity index 93% rename from vendor/github.com/pion/transport/v2/vnet/router.go rename to vendor/github.com/pion/transport/vnet/router.go index cd4b88dc4..9e44f9edd 100644 --- a/vendor/github.com/pion/transport/v2/vnet/router.go +++ b/vendor/github.com/pion/transport/vnet/router.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( @@ -14,7 +11,6 @@ import ( "time" "github.com/pion/logging" - "github.com/pion/transport/v2" ) const ( @@ -67,9 +63,9 @@ type RouterConfig struct { LoggerFactory logging.LoggerFactory } -// NIC is a network interface controller that interfaces Router +// NIC is a nework inerface controller that interfaces Router type NIC interface { - getInterface(ifName string) (*transport.Interface, error) + getInterface(ifName string) (*Interface, error) onInboundChunk(c Chunk) getStaticIPs() []net.IP setRouter(r *Router) error @@ -82,7 +78,7 @@ type ChunkFilter func(c Chunk) bool // Router ... type Router struct { name string // read-only - interfaces []*transport.Interface // read-only + interfaces []*Interface // read-only ipv4Net *net.IPNet // read-only staticIPs []net.IP // read-only staticLocalIPs map[string]net.IP // read-only, @@ -120,17 +116,17 @@ func NewRouter(config *RouterConfig) (*Router, error) { } // set up network interface, lo0 - lo0 := transport.NewInterface(net.Interface{ + lo0 := NewInterface(net.Interface{ Index: 1, MTU: 16384, Name: lo0String, HardwareAddr: nil, Flags: net.FlagUp | net.FlagLoopback | net.FlagMulticast, }) - lo0.AddAddress(&net.IPAddr{IP: net.ParseIP("127.0.0.1"), Zone: ""}) + lo0.AddAddr(&net.IPAddr{IP: net.ParseIP("127.0.0.1"), Zone: ""}) // set up network interface, eth0 - eth0 := transport.NewInterface(net.Interface{ + eth0 := NewInterface(net.Interface{ Index: 2, MTU: 1500, Name: "eth0", @@ -181,7 +177,7 @@ func NewRouter(config *RouterConfig) (*Router, error) { return &Router{ name: name, - interfaces: []*transport.Interface{lo0, eth0}, + interfaces: []*Interface{lo0, eth0}, ipv4Net: ipv4Net, staticIPs: staticIPs, staticLocalIPs: staticLocalIPs, @@ -198,7 +194,7 @@ func NewRouter(config *RouterConfig) (*Router, error) { } // caller must hold the mutex -func (r *Router) getInterfaces() ([]*transport.Interface, error) { +func (r *Router) getInterfaces() ([]*Interface, error) { if len(r.interfaces) == 0 { return nil, fmt.Errorf("%w is available", errNoInterface) } @@ -206,7 +202,7 @@ func (r *Router) getInterfaces() ([]*transport.Interface, error) { return r.interfaces, nil } -func (r *Router) getInterface(ifName string) (*transport.Interface, error) { +func (r *Router) getInterface(ifName string) (*Interface, error) { r.mutex.RLock() defer r.mutex.RUnlock() @@ -220,7 +216,7 @@ func (r *Router) getInterface(ifName string) (*transport.Interface, error) { } } - return nil, fmt.Errorf("%w: %s", transport.ErrInterfaceNotFound, ifName) + return nil, fmt.Errorf("interface %s %w", ifName, errNotFound) } // Start ... @@ -320,7 +316,7 @@ func (r *Router) addNIC(nic NIC) error { return fmt.Errorf("%w: %s", errStaticIPisBeyondSubnet, r.ipv4Net.String()) } - ifc.AddAddress(&net.IPNet{ + ifc.AddAddr(&net.IPNet{ IP: ip, Mask: r.ipv4Net.Mask, }) @@ -328,10 +324,14 @@ func (r *Router) addNIC(nic NIC) error { r.nics[ip.String()] = nic } - return nic.setRouter(r) + if err = nic.setRouter(r); err != nil { + return err + } + + return nil } -// AddRouter adds a child Router. +// AddRouter adds a chile Router. func (r *Router) AddRouter(router *Router) error { r.mutex.Lock() defer r.mutex.Unlock() @@ -482,7 +482,7 @@ func (r *Router) processChunks() (time.Duration, error) { dstIP := c.getDestinationIP() - // check if the destination is in our subnet + // check if the desination is in our subnet if r.ipv4Net.Contains(dstIP) { // search for the destination NIC var nic NIC @@ -520,7 +520,7 @@ func (r *Router) processChunks() (time.Duration, error) { //nolint:godox /* FIXME: this implementation would introduce a duplicate packet! - if r.nat.natType.Hairpinning { + if r.nat.natType.Hairpining { hairpinned, err := r.nat.translateInbound(toParent) if err != nil { r.log.Warnf("[%s] %s", r.name, err.Error()) @@ -553,15 +553,14 @@ func (r *Router) setRouter(parent *Router) error { return err } - addrs, _ := ifc.Addrs() - if len(addrs) == 0 { + if len(ifc.addrs) == 0 { return errNoIPAddrEth0 } mappedIPs := []net.IP{} localIPs := []net.IP{} - for _, ifcAddr := range addrs { + for _, ifcAddr := range ifc.addrs { var ip net.IP switch addr := ifcAddr.(type) { case *net.IPNet: @@ -587,7 +586,7 @@ func (r *Router) setRouter(parent *Router) error { r.natType = &NATType{ MappingBehavior: EndpointIndependent, FilteringBehavior: EndpointAddrPortDependent, - Hairpinning: false, + Hairpining: false, PortPreservation: false, MappingLifeTime: 30 * time.Second, } diff --git a/vendor/github.com/pion/transport/v2/vnet/tbf.go b/vendor/github.com/pion/transport/vnet/tbf.go similarity index 68% rename from vendor/github.com/pion/transport/v2/vnet/tbf.go rename to vendor/github.com/pion/transport/vnet/tbf.go index e6188e31c..0bb0f740d 100644 --- a/vendor/github.com/pion/transport/v2/vnet/tbf.go +++ b/vendor/github.com/pion/transport/vnet/tbf.go @@ -1,14 +1,8 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( - "math" "sync" "time" - - "github.com/pion/logging" ) const ( @@ -23,20 +17,17 @@ const ( // TokenBucketFilter implements a token bucket rate limit algorithm. type TokenBucketFilter struct { NIC - currentTokensInBucket float64 + currentTokensInBucket int c chan Chunk queue *chunkQueue queueSize int // in bytes - mutex sync.Mutex - rate int - maxBurst int - minRefillDuration time.Duration + mutex sync.Mutex + rate int + maxBurst int wg sync.WaitGroup done chan struct{} - - log logging.LeveledLogger } // TBFOption is the option type to configure a TokenBucketFilter @@ -52,7 +43,7 @@ func TBFQueueSizeInBytes(bytes int) TBFOption { } } -// TBFRate sets the bit rate of a TokenBucketFilter +// TBFRate sets the bitrate of a TokenBucketFilter func TBFRate(rate int) TBFOption { return func(t *TokenBucketFilter) TBFOption { t.mutex.Lock() @@ -93,11 +84,9 @@ func NewTokenBucketFilter(n NIC, opts ...TBFOption) (*TokenBucketFilter, error) queueSize: 50000, mutex: sync.Mutex{}, rate: 1 * MBit, - maxBurst: 8 * KBit, - minRefillDuration: 100 * time.Millisecond, + maxBurst: 2 * KBit, wg: sync.WaitGroup{}, done: make(chan struct{}), - log: logging.NewDefaultLoggerFactory().NewLogger("tbf"), } tbf.Set(opts...) tbf.queue = newChunkQueue(0, tbf.queueSize) @@ -112,47 +101,40 @@ func (t *TokenBucketFilter) onInboundChunk(c Chunk) { func (t *TokenBucketFilter) run() { defer t.wg.Done() - - t.refillTokens(t.minRefillDuration) - lastRefill := time.Now() + ticker := time.NewTicker(1 * time.Millisecond) for { select { case <-t.done: + ticker.Stop() t.drainQueue() return - case chunk := <-t.c: - if time.Since(lastRefill) > t.minRefillDuration { - t.refillTokens(time.Since(lastRefill)) - lastRefill = time.Now() + case <-ticker.C: + t.mutex.Lock() + if t.currentTokensInBucket < t.maxBurst { + // add (bitrate * S) / 1000 converted to bytes (divide by 8) S + // is the update interval in milliseconds + t.currentTokensInBucket += (t.rate / 1000) / 8 } + t.mutex.Unlock() + t.drainQueue() + case chunk := <-t.c: t.queue.push(chunk) t.drainQueue() } } } -func (t *TokenBucketFilter) refillTokens(dt time.Duration) { - m := 1000.0 / float64(dt.Milliseconds()) - add := (float64(t.rate) / m) / 8.0 - t.mutex.Lock() - defer t.mutex.Unlock() - t.currentTokensInBucket = math.Min(float64(t.maxBurst), t.currentTokensInBucket+add) - t.log.Tracef("add=(%v / %v) / 8 = %v, currentTokensInBucket=%v, maxBurst=%v", t.rate, m, add, t.currentTokensInBucket, t.maxBurst) -} - func (t *TokenBucketFilter) drainQueue() { for { next := t.queue.peek() if next == nil { break } - tokens := float64(len(next.UserData())) + tokens := len(next.UserData()) if t.currentTokensInBucket < tokens { - t.log.Tracef("currentTokensInBucket=%v, tokens=%v, stop drain", t.currentTokensInBucket, tokens) break } - t.log.Tracef("currentTokensInBucket=%v, tokens=%v, pop chunk", t.currentTokensInBucket, tokens) t.queue.pop() t.NIC.onInboundChunk(next) t.currentTokensInBucket -= tokens diff --git a/vendor/github.com/pion/transport/v2/vnet/udpproxy.go b/vendor/github.com/pion/transport/vnet/udpproxy.go similarity index 73% rename from vendor/github.com/pion/transport/v2/vnet/udpproxy.go rename to vendor/github.com/pion/transport/vnet/udpproxy.go index c5b4f9965..caba86e0e 100644 --- a/vendor/github.com/pion/transport/v2/vnet/udpproxy.go +++ b/vendor/github.com/pion/transport/vnet/udpproxy.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( @@ -13,20 +10,19 @@ import ( // UDPProxy is a proxy between real server(net.UDPConn) and vnet.UDPConn. // // High level design: -// -// .............................................. -// : Virtual Network (vnet) : -// : : -// +-------+ * 1 +----+ +--------+ : -// | :App |------------>|:Net|--o<-----|:Router | ............................. -// +-------+ +----+ | | : UDPProxy : -// : | | +----+ +---------+ +---------+ +--------+ -// : | |--->o--|:Net|-->o-| vnet. |-->o-| net. |--->-| :Real | -// : | | +----+ | UDPConn | | UDPConn | | Server | -// : | | : +---------+ +---------+ +--------+ -// : | | ............................: -// : +--------+ : -// ............................................... +// .............................................. +// : Virtual Network (vnet) : +// : : +// +-------+ * 1 +----+ +--------+ : +// | :App |------------>|:Net|--o<-----|:Router | ............................. +// +-------+ +----+ | | : UDPProxy : +// : | | +----+ +---------+ +---------+ +--------+ +// : | |--->o--|:Net|-->o-| vnet. |-->o-| net. |--->-| :Real | +// : | | +----+ | UDPConn | | UDPConn | | Server | +// : | | : +---------+ +---------+ +--------+ +// : | | ............................: +// : +--------+ : +// ............................................... type UDPProxy struct { // The router bind to. router *Router @@ -56,7 +52,7 @@ func NewProxy(router *Router) (*UDPProxy, error) { // Close the proxy, stop all workers. func (v *UDPProxy) Close() error { v.workers.Range(func(key, value interface{}) bool { - _ = value.(*aUDPProxyWorker).Close() //nolint:forcetypeassert + _ = value.(*aUDPProxyWorker).Close() return true }) return nil @@ -111,16 +107,12 @@ func (v *aUDPProxyWorker) Close() error { return nil } -func (v *aUDPProxyWorker) Proxy(ctx context.Context, _ *Net, serverAddr *net.UDPAddr) error { // nolint:gocognit +func (v *aUDPProxyWorker) Proxy(ctx context.Context, client *Net, serverAddr *net.UDPAddr) error { // nolint:gocognit // Create vnet for real server by serverAddr. - nw, err := NewNet(&NetConfig{ + nw := NewNet(&NetConfig{ StaticIP: serverAddr.IP.String(), }) - if err != nil { - return err - } - - if err = v.router.AddNet(nw); err != nil { + if err := v.router.AddNet(nw); err != nil { return err } @@ -142,7 +134,7 @@ func (v *aUDPProxyWorker) Proxy(ctx context.Context, _ *Net, serverAddr *net.UDP // Exists binding. if value, ok := v.endpoints.Load(addr.String()); ok { // Exists endpoint, reuse it. - return value.(*net.UDPConn), nil //nolint:forcetypeassert + return value.(*net.UDPConn), nil } // The real server we proxy to, for utest to mock it. diff --git a/vendor/github.com/pion/transport/v2/vnet/udpproxy_direct.go b/vendor/github.com/pion/transport/vnet/udpproxy_direct.go similarity index 75% rename from vendor/github.com/pion/transport/v2/vnet/udpproxy_direct.go rename to vendor/github.com/pion/transport/vnet/udpproxy_direct.go index bb2aedfd0..9ab460e71 100644 --- a/vendor/github.com/pion/transport/v2/vnet/udpproxy_direct.go +++ b/vendor/github.com/pion/transport/vnet/udpproxy_direct.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package vnet import ( @@ -23,7 +20,7 @@ func (v *UDPProxy) Deliver(sourceAddr, destAddr net.Addr, b []byte) (nn int, err return } -func (v *aUDPProxyWorker) Deliver(sourceAddr, _ net.Addr, b []byte) (nn int, err error) { +func (v *aUDPProxyWorker) Deliver(sourceAddr, destAddr net.Addr, b []byte) (nn int, err error) { addr, ok := sourceAddr.(*net.UDPAddr) if !ok { return 0, fmt.Errorf("invalid addr %v", sourceAddr) // nolint:goerr113 @@ -32,13 +29,12 @@ func (v *aUDPProxyWorker) Deliver(sourceAddr, _ net.Addr, b []byte) (nn int, err // nolint:godox // TODO: Support deliver packet from real server to vnet. // If packet is from vnet, proxy to real server. var realSocket *net.UDPConn - value, ok := v.endpoints.Load(addr.String()) - if !ok { + if value, ok := v.endpoints.Load(addr.String()); !ok { return 0, nil + } else { // nolint:golint + realSocket = value.(*net.UDPConn) } - realSocket = value.(*net.UDPConn) // nolint:forcetypeassert - // Send to real server. if _, err := realSocket.Write(b); err != nil { return 0, err diff --git a/vendor/github.com/pion/transport/vnet/vnet.go b/vendor/github.com/pion/transport/vnet/vnet.go new file mode 100644 index 000000000..bfe0f0f27 --- /dev/null +++ b/vendor/github.com/pion/transport/vnet/vnet.go @@ -0,0 +1,2 @@ +// Package vnet provides a virtual network layer for pion +package vnet diff --git a/vendor/github.com/pion/turn/v2/.gitignore b/vendor/github.com/pion/turn/v2/.gitignore index f977e7485..83db74ba5 100644 --- a/vendor/github.com/pion/turn/v2/.gitignore +++ b/vendor/github.com/pion/turn/v2/.gitignore @@ -22,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/turn/v2/.golangci.yml b/vendor/github.com/pion/turn/v2/.golangci.yml index 48696f16b..d6162c970 100644 --- a/vendor/github.com/pion/turn/v2/.golangci.yml +++ b/vendor/github.com/pion/turn/v2/.golangci.yml @@ -15,21 +15,14 @@ linters-settings: linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - - decorder # check declaration order and count of types, constants, variables and functions + - deadcode # Finds unused code - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -42,60 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks + - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - - wastedassign # wastedassign finds wasted assignment statements + - varcheck # Finds unused global variables and constants - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - - forbidigo # Forbids identifiers - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: diff --git a/vendor/github.com/pion/turn/v2/.goreleaser.yml b/vendor/github.com/pion/turn/v2/.goreleaser.yml index 2caa5fbd3..c7f2efdc4 100644 --- a/vendor/github.com/pion/turn/v2/.goreleaser.yml +++ b/vendor/github.com/pion/turn/v2/.goreleaser.yml @@ -1,2 +1,109 @@ +before: + hooks: + - go mod tidy + +archives: +- replacements: + darwin: Darwin + linux: Linux + windows: Windows + 386: i386 + amd64: x86_64 + +checksum: + name_template: 'checksums.txt' + +snapshot: + name_template: "{{ .Tag }}-next" + +changelog: + sort: asc + filters: + exclude: + - '^docs:' + - '^test:' + builds: -- skip: true + - binary: turn-client-tcp + id: turn-client-tcp + goos: + - darwin + - windows + - linux + - freebsd + goarch: + - amd64 + - 386 + env: + - CGO_ENABLED=0 + main: ./examples/turn-client/tcp + + - binary: turn-client-udp + id: turn-client-udp + goos: + - darwin + - windows + - linux + - freebsd + goarch: + - amd64 + - 386 + env: + - CGO_ENABLED=0 + main: ./examples/turn-client/udp + + - binary: turn-server-add-software-attribute + id: turn-server-add-software-attribute + goos: + - darwin + - windows + - linux + - freebsd + goarch: + - amd64 + - 386 + env: + - CGO_ENABLED=0 + main: ./examples/turn-server/add-software-attribute + + - binary: turn-server-log + id: turn-server-log + goos: + - darwin + - windows + - linux + - freebsd + goarch: + - amd64 + - 386 + env: + - CGO_ENABLED=0 + main: ./examples/turn-server/log + + - binary: turn-server-simple + id: turn-server-simple + goos: + - darwin + - windows + - linux + - freebsd + goarch: + - amd64 + - 386 + env: + - CGO_ENABLED=0 + main: ./examples/turn-server/simple/ + + - binary: turn-server-tcp + id: turn-server-tcp + goos: + - darwin + - windows + - linux + - freebsd + goarch: + - amd64 + - 386 + env: + - CGO_ENABLED=0 + main: ./examples/turn-server/tcp/ diff --git a/vendor/github.com/pion/turn/v2/AUTHORS.txt b/vendor/github.com/pion/turn/v2/AUTHORS.txt index 3b38a5c1f..8515b5c5b 100644 --- a/vendor/github.com/pion/turn/v2/AUTHORS.txt +++ b/vendor/github.com/pion/turn/v2/AUTHORS.txt @@ -2,17 +2,14 @@ # we would love to have you https://github.com/pion/webrtc/wiki/Contributing # # This file is auto generated, using git to list all individuals contributors. -# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting +# see `.github/generate-authors.sh` for the scripting Aaron France Aleksandr Razumov andrefsp -Antonio Sorrentino Atsushi Watanabe backkem -Caleb Phillips cnderrauber David Colburn -Gabor Retvari Herman Banken Hugo Arregui Igor German @@ -28,16 +25,10 @@ Mészáros Mihály nindolabs <6729798+nindolabs@users.noreply.github.com> Onwuka Gideon Robert Eperjesi -Sean DuBois Sean DuBois Sean DuBois Sean DuBois songjiayang -Steffen Vogel -ted Tom Clift Yusuke Nakamura Yutaka Takeda - -# List of contributors not appearing in Git history - diff --git a/vendor/github.com/pion/turn/v2/FAQ.md b/vendor/github.com/pion/turn/v2/FAQ.md deleted file mode 100644 index a8ffd6491..000000000 --- a/vendor/github.com/pion/turn/v2/FAQ.md +++ /dev/null @@ -1,17 +0,0 @@ - - -## FAQ - -Q: Will pion/turn also act as a STUN server? - -A: Yes. - -Q: How do I implement token-based authentication? - -A: Replace the username with a token in the [AuthHandler](https://github.com/pion/turn/blob/6d0ff435910870eb9024b18321b93b61844fcfec/examples/turn-server/simple/main.go#L49). -The password sent by the client can be any non-empty string, as long as it matches that used by the [GenerateAuthKey](https://github.com/pion/turn/blob/6d0ff435910870eb9024b18321b93b61844fcfec/examples/turn-server/simple/main.go#L41) -function. - -Q: Will WebRTC prioritize using STUN over TURN? - -A: Yes. \ No newline at end of file diff --git a/vendor/github.com/pion/turn/v2/README.md b/vendor/github.com/pion/turn/v2/README.md index b8901fd30..2fa806a5a 100644 --- a/vendor/github.com/pion/turn/v2/README.md +++ b/vendor/github.com/pion/turn/v2/README.md @@ -13,7 +13,8 @@ Build Status GoDoc Coverage Status - Go Report Card + Go Report Card + Codacy Badge License: MIT


@@ -63,7 +64,7 @@ Pion has an active community on the [Golang Slack](https://pion.ly/slack). Sign We are always looking to support **your projects**. Please reach out if you have something to build! ### Contributing -Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible. +Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible: ### License MIT License - see [LICENSE.md](LICENSE.md) for full text diff --git a/vendor/github.com/pion/turn/v2/client.go b/vendor/github.com/pion/turn/v2/client.go index 5e675fd36..b04e7d186 100644 --- a/vendor/github.com/pion/turn/v2/client.go +++ b/vendor/github.com/pion/turn/v2/client.go @@ -10,9 +10,7 @@ import ( "github.com/pion/logging" "github.com/pion/stun" - "github.com/pion/transport/v2" - "github.com/pion/transport/v2/stdnet" - "github.com/pion/transport/v2/vnet" + "github.com/pion/transport/vnet" "github.com/pion/turn/v2/internal/client" "github.com/pion/turn/v2/internal/proto" ) @@ -36,7 +34,7 @@ const ( // ClientConfig is a bag of config parameters for Client. type ClientConfig struct { STUNServerAddr string // STUN server address (e.g. "stun.abc.com:3478") - TURNServerAddr string // TURN server address (e.g. "turn.abc.com:3478") + TURNServerAddr string // TURN server addrees (e.g. "turn.abc.com:3478") Username string Password string Realm string @@ -44,7 +42,7 @@ type ClientConfig struct { RTO time.Duration Conn net.PacketConn // Listening socket (net.PacketConn) LoggerFactory logging.LoggerFactory - Net transport.Net + Net *vnet.Net } // Client is a STUN server client @@ -52,8 +50,8 @@ type Client struct { conn net.PacketConn // read-only stunServ net.Addr // read-only turnServ net.Addr // read-only - stunServStr string // read-only, used for de-multiplexing - turnServStr string // read-only, used for de-multiplexing + stunServStr string // read-only, used for dmuxing + turnServStr string // read-only, used for dmuxing username stun.Username // read-only password string // read-only realm stun.Realm // read-only @@ -64,7 +62,7 @@ type Client struct { relayedConn *client.UDPConn // protected by mutex *** allocTryLock client.TryLock // thread-safe listenTryLock client.TryLock // thread-safe - net transport.Net // read-only + net *vnet.Net // read-only mutex sync.RWMutex // thread-safe mutexTrMap sync.Mutex // thread-safe log logging.LeveledLogger // read-only @@ -83,18 +81,15 @@ func NewClient(config *ClientConfig) (*Client, error) { return nil, errNilConn } - var err error if config.Net == nil { - config.Net, err = stdnet.NewNet() // defaults to native operation - if err != nil { - return nil, err - } - } else if _, ok := config.Net.(*vnet.Net); ok { - log.Warn("Virtual network is enabled") + config.Net = vnet.NewNet(nil) // defaults to native operation + } else if config.Net.IsVirtual() { + log.Warn("vnet is enabled") } var stunServ, turnServ net.Addr var stunServStr, turnServStr string + var err error if len(config.STUNServerAddr) > 0 { log.Debugf("resolving %s", config.STUNServerAddr) stunServ, err = config.Net.ResolveUDPAddr("udp4", config.STUNServerAddr) @@ -338,16 +333,9 @@ func (c *Client) Allocate() (net.PacketConn, error) { return relayedConn, nil } -// CreatePermission Issues a CreatePermission request for the supplied addresses -// as described in https://datatracker.ietf.org/doc/html/rfc5766#section-9 -func (c *Client) CreatePermission(addrs ...net.Addr) error { - return c.relayedUDPConn().CreatePermissions(addrs...) -} - // PerformTransaction performs STUN transaction func (c *Client) PerformTransaction(msg *stun.Message, to net.Addr, ignoreResult bool) (client.TransactionResult, - error, -) { + error) { trKey := b64.StdEncoding.EncodeToString(msg.TransactionID[:]) raw := make([]byte, len(msg.Raw)) @@ -383,16 +371,16 @@ func (c *Client) PerformTransaction(msg *stun.Message, to net.Addr, ignoreResult return res, nil } -// OnDeallocated is called when de-allocation of relay address has been complete. +// OnDeallocated is called when deallocation of relay address has been complete. // (Called by UDPConn) func (c *Client) OnDeallocated(relayedAddr net.Addr) { c.setRelayedUDPConn(nil) } // HandleInbound handles data received. -// This method handles incoming packet de-multiplex it by the source address +// This method handles incoming packet demultiplex it by the source address // and the types of the message. -// This return a boolean (handled or not) and if there was an error. +// This return a booleen (handled or not) and if there was an error. // Caller should check if the packet was handled by this client or not. // If not handled, it is assumed that the packet is application data. // If an error is returned, the caller should discard the packet regardless. @@ -425,7 +413,7 @@ func (c *Client) HandleInbound(data []byte, from net.Addr) (bool, error) { return true, errNonSTUNMessage default: // assume, this is an application data - c.log.Tracef("non-STUN/TURN packet, unhandled") + c.log.Tracef("non-STUN/TURN packect, unhandled") } return false, nil @@ -541,7 +529,7 @@ func (c *Client) onRtxTimeout(trKey string, nRtx int) { } if nRtx == maxRtxCount { - // all retransmissions failed + // all retransmisstions failed c.trMap.Delete(trKey) if !tr.WriteResult(client.TransactionResult{ Err: fmt.Errorf("%w %s", errAllRetransmissionsFailed, trKey), diff --git a/vendor/github.com/pion/turn/v2/internal/allocation/allocation.go b/vendor/github.com/pion/turn/v2/internal/allocation/allocation.go index 7a3ce1ddf..2b346f198 100644 --- a/vendor/github.com/pion/turn/v2/internal/allocation/allocation.go +++ b/vendor/github.com/pion/turn/v2/internal/allocation/allocation.go @@ -4,7 +4,6 @@ package allocation import ( "net" "sync" - "sync/atomic" "time" "github.com/pion/logging" @@ -13,11 +12,6 @@ import ( "github.com/pion/turn/v2/internal/proto" ) -type allocationResponse struct { - transactionID [stun.TransactionIDSize]byte - responseAttrs []stun.Setter -} - // Allocation is tied to a FiveTuple and relays traffic // use CreateAllocation and GetAllocation to operate type Allocation struct { @@ -33,12 +27,6 @@ type Allocation struct { lifetimeTimer *time.Timer closed chan interface{} log logging.LeveledLogger - - // some clients (Firefox or others using resiprocate's nICE lib) may retry allocation - // with same 5 tuple when received 413, for compatible with these clients, - // cache for response lost and client retry to implement 'stateless stack approach' - // https://datatracker.ietf.org/doc/html/rfc5766#section-6.2 - responseCache atomic.Value // *allocationResponse } func addr2IPFingerprint(addr net.Addr) string { @@ -48,7 +36,7 @@ func addr2IPFingerprint(addr net.Addr) string { case *net.TCPAddr: // Do we really need this case? return a.IP.String() } - return "" // should never happen + return "" // shoud never happen } // NewAllocation creates a new instance of NewAllocation. @@ -176,22 +164,6 @@ func (a *Allocation) Refresh(lifetime time.Duration) { } } -// SetResponseCache cache allocation response for retransmit allocation request -func (a *Allocation) SetResponseCache(transactionID [stun.TransactionIDSize]byte, attrs []stun.Setter) { - a.responseCache.Store(&allocationResponse{ - transactionID: transactionID, - responseAttrs: attrs, - }) -} - -// GetResponseCache return response cache for retransmit allocation request -func (a *Allocation) GetResponseCache() (id [stun.TransactionIDSize]byte, attrs []stun.Setter) { - if res, ok := a.responseCache.Load().(*allocationResponse); ok && res != nil { - id, attrs = res.transactionID, res.responseAttrs - } - return -} - // Close closes the allocation func (a *Allocation) Close() error { select { @@ -266,19 +238,13 @@ func (a *Allocation) packetHandler(m *Manager) { a.log.Errorf("Failed to send ChannelData from allocation %v %v", srcAddr, err) } } else if p := a.GetPermission(srcAddr); p != nil { - udpAddr, ok := srcAddr.(*net.UDPAddr) - if !ok { - a.log.Errorf("Failed to send DataIndication from allocation %v %v", srcAddr, err) - return - } - + udpAddr := srcAddr.(*net.UDPAddr) peerAddressAttr := proto.PeerAddress{IP: udpAddr.IP, Port: udpAddr.Port} dataAttr := proto.Data(buffer[:n]) msg, err := stun.Build(stun.TransactionID, stun.NewType(stun.MethodData, stun.ClassIndication), peerAddressAttr, dataAttr) if err != nil { a.log.Errorf("Failed to send DataIndication from allocation %v %v", srcAddr, err) - return } a.log.Debugf("relaying message from %s to client at %s", srcAddr.String(), diff --git a/vendor/github.com/pion/turn/v2/internal/allocation/allocation_manager.go b/vendor/github.com/pion/turn/v2/internal/allocation/allocation_manager.go index 5e924ac64..2fd79725c 100644 --- a/vendor/github.com/pion/turn/v2/internal/allocation/allocation_manager.go +++ b/vendor/github.com/pion/turn/v2/internal/allocation/allocation_manager.go @@ -14,7 +14,6 @@ type ManagerConfig struct { LeveledLogger logging.LeveledLogger AllocatePacketConn func(network string, requestedPort int) (net.PacketConn, net.Addr, error) AllocateConn func(network string, requestedPort int) (net.Conn, net.Addr, error) - PermissionHandler func(sourceAddr net.Addr, peerIP net.IP) bool } type reservation struct { @@ -32,7 +31,6 @@ type Manager struct { allocatePacketConn func(network string, requestedPort int) (net.PacketConn, net.Addr, error) allocateConn func(network string, requestedPort int) (net.Conn, net.Addr, error) - permissionHandler func(sourceAddr net.Addr, peerIP net.IP) bool } // NewManager creates a new instance of Manager. @@ -51,7 +49,6 @@ func NewManager(config ManagerConfig) (*Manager, error) { allocations: make(map[string]*Allocation, 64), allocatePacketConn: config.AllocatePacketConn, allocateConn: config.AllocateConn, - permissionHandler: config.PermissionHandler, }, nil } @@ -198,18 +195,3 @@ func (m *Manager) GetRandomEvenPort() (int, error) { } return 0, errFailedToAllocateEvenPort } - -// GrantPermission handles permission requests by calling the permission handler callback -// associated with the TURN server listener socket -func (m *Manager) GrantPermission(sourceAddr net.Addr, peerIP net.IP) error { - // no permission handler: open - if m.permissionHandler == nil { - return nil - } - - if m.permissionHandler(sourceAddr, peerIP) { - return nil - } - - return errAdminProhibited -} diff --git a/vendor/github.com/pion/turn/v2/internal/allocation/errors.go b/vendor/github.com/pion/turn/v2/internal/allocation/errors.go index b9677e11a..b92b78d8b 100644 --- a/vendor/github.com/pion/turn/v2/internal/allocation/errors.go +++ b/vendor/github.com/pion/turn/v2/internal/allocation/errors.go @@ -15,5 +15,4 @@ var ( errDupeFiveTuple = errors.New("allocation attempt created with duplicate FiveTuple") errFailedToCastUDPAddr = errors.New("failed to cast net.Addr to *net.UDPAddr") errFailedToAllocateEvenPort = errors.New("failed to allocate an even port") - errAdminProhibited = errors.New("permission request administratively prohibited") ) diff --git a/vendor/github.com/pion/turn/v2/internal/client/binding.go b/vendor/github.com/pion/turn/v2/internal/client/binding.go index f4d6fa2b4..ee52053cb 100644 --- a/vendor/github.com/pion/turn/v2/internal/client/binding.go +++ b/vendor/github.com/pion/turn/v2/internal/client/binding.go @@ -7,10 +7,9 @@ import ( "time" ) -// Channel number: -// -// 0x4000 through 0x7FFF: These values are the allowed channel -// numbers (16,383 possible values). +// Chanel number: +// 0x4000 through 0x7FFF: These values are the allowed channel +// numbers (16,383 possible values). const ( minChannelNumber uint16 = 0x4000 maxChannelNumber uint16 = 0x7fff diff --git a/vendor/github.com/pion/turn/v2/internal/client/conn.go b/vendor/github.com/pion/turn/v2/internal/client/conn.go index 8aeb742c3..8a2b1ae75 100644 --- a/vendor/github.com/pion/turn/v2/internal/client/conn.go +++ b/vendor/github.com/pion/turn/v2/internal/client/conn.go @@ -153,21 +153,6 @@ func (c *UDPConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) { } } -func (c *UDPConn) createPermission(perm *permission, addr net.Addr) error { - perm.mutex.Lock() - defer perm.mutex.Unlock() - - if perm.state() == permStateIdle { - // punch a hole! (this would block a bit..) - if err := c.CreatePermissions(addr); err != nil { - c.permMap.delete(addr) - return err - } - perm.setState(permStatePermitted) - } - return nil -} - // WriteTo writes a packet with payload p to addr. // WriteTo can be made to time out and return // an Error with Timeout() == true after a fixed time limit; @@ -187,15 +172,30 @@ func (c *UDPConn) WriteTo(p []byte, addr net.Addr) (int, error) { //nolint: goco c.permMap.insert(addr, perm) } + // This func-block would block, per destination IP (, or perm), until + // the perm state becomes "requested". Purpose of this is to guarantee + // the order of packets (within the same perm). + // Note that CreatePermission transaction may not be complete before + // all the data transmission. This is done assuming that the request + // will be mostly likely successful and we can tolerate some loss of + // UDP packet (or reorder), inorder to minimize the latency in most cases. + createPermission := func() error { + perm.mutex.Lock() + defer perm.mutex.Unlock() + + if perm.state() == permStateIdle { + // punch a hole! (this would block a bit..) + if err = c.createPermissions(addr); err != nil { + c.permMap.delete(addr) + return err + } + perm.setState(permStatePermitted) + } + return nil + } + for i := 0; i < maxRetryAttempts; i++ { - // c.createPermission() would block, per destination IP (, or perm), - // until the perm state becomes "requested". Purpose of this is to - // guarantee the order of packets (within the same perm). - // Note that CreatePermission transaction may not be complete before - // all the data transmission. This is done assuming that the request - // will be most likely successful and we can tolerate some loss of - // UDP packet (or reorder), inorder to minimize the latency in most cases. - if err = c.createPermission(perm, addr); !errors.Is(err, errTryAgain) { + if err = createPermission(); !errors.Is(err, errTryAgain) { break } } @@ -277,11 +277,7 @@ func (c *UDPConn) WriteTo(p []byte, addr net.Addr) (int, error) { //nolint: goco }() // send via ChannelData - _, err = c.sendChannelData(p, b.number) - if err != nil { - return 0, err - } - return len(p), nil + return c.sendChannelData(p, b.number) } // Close closes the connection. @@ -363,9 +359,7 @@ func addr2PeerAddress(addr net.Addr) proto.PeerAddress { return peerAddr } -// CreatePermissions Issues a CreatePermission request for the supplied addresses -// as described in https://datatracker.ietf.org/doc/html/rfc5766#section-9 -func (c *UDPConn) CreatePermissions(addrs ...net.Addr) error { +func (c *UDPConn) createPermissions(addrs ...net.Addr) error { setters := []stun.Setter{ stun.TransactionID, stun.NewType(stun.MethodCreatePermission, stun.ClassRequest), @@ -502,7 +496,7 @@ func (c *UDPConn) refreshPermissions() error { c.log.Debug("no permission to refresh") return nil } - if err := c.CreatePermissions(addrs...); err != nil { + if err := c.createPermissions(addrs...); err != nil { if errors.Is(err, errTryAgain) { return errTryAgain } @@ -555,11 +549,7 @@ func (c *UDPConn) sendChannelData(data []byte, chNum uint16) (int, error) { Number: proto.ChannelNumber(chNum), } chData.Encode() - _, err := c.obs.WriteTo(chData.Raw, c.obs.TURNServerAddr()) - if err != nil { - return 0, err - } - return len(data), nil + return c.obs.WriteTo(chData.Raw, c.obs.TURNServerAddr()) } func (c *UDPConn) onRefreshTimers(id int) { diff --git a/vendor/github.com/pion/turn/v2/internal/client/errors.go b/vendor/github.com/pion/turn/v2/internal/client/errors.go index 7fc816fd0..2d4bd30c4 100644 --- a/vendor/github.com/pion/turn/v2/internal/client/errors.go +++ b/vendor/github.com/pion/turn/v2/internal/client/errors.go @@ -5,7 +5,7 @@ import ( ) var ( - errFake = errors.New("fake error") + errFakeErr = errors.New("fake error") errTryAgain = errors.New("try again") errClosed = errors.New("use of closed network connection") errUDPAddrCast = errors.New("addr is not a net.UDPAddr") diff --git a/vendor/github.com/pion/turn/v2/internal/client/transaction.go b/vendor/github.com/pion/turn/v2/internal/client/transaction.go index 54024b447..610a4d4d2 100644 --- a/vendor/github.com/pion/turn/v2/internal/client/transaction.go +++ b/vendor/github.com/pion/turn/v2/internal/client/transaction.go @@ -139,7 +139,7 @@ func NewTransactionMap() *TransactionMap { } } -// Insert inserts a transaction to the map +// Insert inserts a trasaction to the map func (m *TransactionMap) Insert(key string, tr *Transaction) bool { m.mutex.Lock() defer m.mutex.Unlock() diff --git a/vendor/github.com/pion/turn/v2/internal/client/trylock.go b/vendor/github.com/pion/turn/v2/internal/client/trylock.go index 2d11a2d3c..48e25a054 100644 --- a/vendor/github.com/pion/turn/v2/internal/client/trylock.go +++ b/vendor/github.com/pion/turn/v2/internal/client/trylock.go @@ -10,7 +10,7 @@ type TryLock struct { } // Lock tries to lock the try-lock. If successful, it returns true. -// Otherwise, it returns false immediately. +// Otherwise, it returns false immedidately. func (c *TryLock) Lock() error { if !atomic.CompareAndSwapInt32(&c.n, 0, 1) { return errDoubleLock diff --git a/vendor/github.com/pion/turn/v2/internal/ipnet/util.go b/vendor/github.com/pion/turn/v2/internal/ipnet/util.go index 24256b0a0..9df7f5695 100644 --- a/vendor/github.com/pion/turn/v2/internal/ipnet/util.go +++ b/vendor/github.com/pion/turn/v2/internal/ipnet/util.go @@ -24,7 +24,7 @@ func AddrIPPort(a net.Addr) (net.IP, int, error) { } // AddrEqual asserts that two net.Addrs are equal -// Currently only supports UDP but will be extended in the future to support others +// Currently only supprots UDP but will be extended in the future to support others func AddrEqual(a, b net.Addr) bool { aUDP, ok := a.(*net.UDPAddr) if !ok { diff --git a/vendor/github.com/pion/turn/v2/internal/proto/chandata.go b/vendor/github.com/pion/turn/v2/internal/proto/chandata.go index 6f023e088..fb1295b1a 100644 --- a/vendor/github.com/pion/turn/v2/internal/proto/chandata.go +++ b/vendor/github.com/pion/turn/v2/internal/proto/chandata.go @@ -11,7 +11,7 @@ import ( // // See RFC 5766 Section 11.4 type ChannelData struct { - Data []byte // can be sub slice of Raw + Data []byte // can be subslice of Raw Length int // ignored while encoding, len(Data) is used Number ChannelNumber Raw []byte diff --git a/vendor/github.com/pion/turn/v2/internal/proto/connection_id.go b/vendor/github.com/pion/turn/v2/internal/proto/connection_id.go deleted file mode 100644 index 4984b474b..000000000 --- a/vendor/github.com/pion/turn/v2/internal/proto/connection_id.go +++ /dev/null @@ -1,39 +0,0 @@ -package proto - -import ( - "encoding/binary" - - "github.com/pion/stun" -) - -// ConnectionID represents CONNECTION-ID attribute. -// -// The CONNECTION-ID attribute uniquely identifies a peer data -// connection. It is a 32-bit unsigned integral value. -// -// RFC 6062 Section 6.2.1 -type ConnectionID uint32 - -const connectionIDSize = 4 // uint32: 4 bytes, 32 bits - -// AddTo adds CONNECTION-ID to message. -func (c ConnectionID) AddTo(m *stun.Message) error { - v := make([]byte, lifetimeSize) - binary.BigEndian.PutUint32(v, uint32(c)) - m.Add(stun.AttrConnectionID, v) - return nil -} - -// GetFrom decodes CONNECTION-ID from message. -func (c *ConnectionID) GetFrom(m *stun.Message) error { - v, err := m.Get(stun.AttrConnectionID) - if err != nil { - return err - } - if err = stun.CheckSize(stun.AttrConnectionID, len(v), connectionIDSize); err != nil { - return err - } - _ = v[connectionIDSize-1] // asserting length - *(*uint32)(c) = binary.BigEndian.Uint32(v) - return nil -} diff --git a/vendor/github.com/pion/turn/v2/internal/proto/dontfrag.go b/vendor/github.com/pion/turn/v2/internal/proto/dontfrag.go index ac52b2b51..eb4d8caf8 100644 --- a/vendor/github.com/pion/turn/v2/internal/proto/dontfrag.go +++ b/vendor/github.com/pion/turn/v2/internal/proto/dontfrag.go @@ -1,45 +1,18 @@ package proto -import ( - "github.com/pion/stun" -) +import "github.com/pion/stun" -// DontFragmentAttr is a deprecated alias for DontFragment -// Deprecated: Please use DontFragment -type DontFragmentAttr = DontFragment - -// DontFragment represents DONT-FRAGMENT attribute. -// -// This attribute is used by the client to request that the server set -// the DF (Don't Fragment) bit in the IP header when relaying the -// application data onward to the peer. This attribute has no value -// part and thus the attribute length field is 0. -// -// RFC 5766 Section 14.8 -type DontFragment struct{} - -const dontFragmentSize = 0 +// DontFragmentAttr represents DONT-FRAGMENT attribute. +type DontFragmentAttr struct{} // AddTo adds DONT-FRAGMENT attribute to message. -func (DontFragment) AddTo(m *stun.Message) error { +func (DontFragmentAttr) AddTo(m *stun.Message) error { m.Add(stun.AttrDontFragment, nil) return nil } -// GetFrom decodes DONT-FRAGMENT from message. -func (d *DontFragment) GetFrom(m *stun.Message) error { - v, err := m.Get(stun.AttrDontFragment) - if err != nil { - return err - } - if err = stun.CheckSize(stun.AttrDontFragment, len(v), dontFragmentSize); err != nil { - return err - } - return nil -} - // IsSet returns true if DONT-FRAGMENT attribute is set. -func (DontFragment) IsSet(m *stun.Message) bool { +func (DontFragmentAttr) IsSet(m *stun.Message) bool { _, err := m.Get(stun.AttrDontFragment) return err == nil } diff --git a/vendor/github.com/pion/turn/v2/internal/proto/fuzz.go b/vendor/github.com/pion/turn/v2/internal/proto/fuzz.go new file mode 100644 index 000000000..1a171fb74 --- /dev/null +++ b/vendor/github.com/pion/turn/v2/internal/proto/fuzz.go @@ -0,0 +1,111 @@ +// +build gofuzz + +package proto + +import ( + "fmt" + + "github.com/pion/stun" +) + +type attr interface { + stun.Getter + stun.Setter +} + +type attrs []struct { + g attr + t stun.AttrType +} + +func (a attrs) pick(v byte) struct { + g attr + t stun.AttrType +} { + idx := int(v) % len(a) + return a[idx] +} + +func FuzzSetters(data []byte) int { + var ( + m1 = &stun.Message{ + Raw: make([]byte, 0, 2048), + } + m2 = &stun.Message{ + Raw: make([]byte, 0, 2048), + } + m3 = &stun.Message{ + Raw: make([]byte, 0, 2048), + } + ) + attributes := attrs{ + {new(RequestedTransport), stun.AttrRequestedTransport}, + {new(RelayedAddress), stun.AttrXORRelayedAddress}, + {new(ChannelNumber), stun.AttrChannelNumber}, + {new(Data), stun.AttrData}, + {new(EvenPort), stun.AttrEvenPort}, + {new(Lifetime), stun.AttrLifetime}, + {new(ReservationToken), stun.AttrReservationToken}, + } + var firstByte = byte(0) + if len(data) > 0 { + firstByte = data[0] + } + a := attributes.pick(firstByte) + value := data + if len(data) > 1 { + value = value[1:] + } + m1.WriteHeader() + m1.Add(a.t, value) + err := a.g.GetFrom(m1) + if err == stun.ErrAttributeNotFound { + fmt.Println("unexpected 404") // nolint + panic(err) // nolint + } + if err != nil { + return 1 + } + m2.WriteHeader() + if err := a.g.AddTo(m2); err != nil { + fmt.Println("failed to add attribute to m2") // nolint + panic(err) // nolint + } + m3.WriteHeader() + v, err := m2.Get(a.t) + if err != nil { + panic(err) // nolint + } + m3.Add(a.t, v) + + if !m2.Equal(m3) { + fmt.Println(m2, "not equal", m3) // nolint + panic("not equal") // nolint + } + return 1 +} + +var d = &ChannelData{} + +func FuzzChannelData(data []byte) int { + d.Reset() + if b := bin.Uint16(data[0:4]); b > 20000 { + bin.PutUint16(data[0:4], MinChannelNumber-1) + } else if b > 40000 { + bin.PutUint16(data[0:4], MinChannelNumber+(MaxChannelNumber-MinChannelNumber)%b) + } + d.Raw = append(d.Raw, data...) + if d.Decode() != nil { + return 0 + } + d2 := &ChannelData{} + d.Encode() + if !d.Number.Valid() { + return 1 + } + d2.Raw = d.Raw + if err := d2.Decode(); err != nil { + panic(err) //nolint + } + return 1 +} diff --git a/vendor/github.com/pion/turn/v2/internal/proto/reqtrans.go b/vendor/github.com/pion/turn/v2/internal/proto/reqtrans.go index cc73a4713..a4e48639f 100644 --- a/vendor/github.com/pion/turn/v2/internal/proto/reqtrans.go +++ b/vendor/github.com/pion/turn/v2/internal/proto/reqtrans.go @@ -27,7 +27,7 @@ func (p Protocol) String() string { // // This attribute is used by the client to request a specific transport // protocol for the allocated transport address. RFC 5766 only allows the use of -// code point 17 (User Datagram Protocol). +// codepoint 17 (User Datagram Protocol). // // RFC 5766 Section 14.7 type RequestedTransport struct { diff --git a/vendor/github.com/pion/turn/v2/internal/server/turn.go b/vendor/github.com/pion/turn/v2/internal/server/turn.go index 4e7d25db0..cbac09c2d 100644 --- a/vendor/github.com/pion/turn/v2/internal/server/turn.go +++ b/vendor/github.com/pion/turn/v2/internal/server/turn.go @@ -33,20 +33,14 @@ func handleAllocateRequest(r Request, m *stun.Message) error { reservationToken := "" badRequestMsg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse), &stun.ErrorCodeAttribute{Code: stun.CodeBadRequest}) - insufficientCapacityMsg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse), &stun.ErrorCodeAttribute{Code: stun.CodeInsufficientCapacity}) + insufficentCapacityMsg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse), &stun.ErrorCodeAttribute{Code: stun.CodeInsufficientCapacity}) // 2. The server checks if the 5-tuple is currently in use by an // existing allocation. If yes, the server rejects the request with // a 437 (Allocation Mismatch) error. if alloc := r.AllocationManager.GetAllocation(fiveTuple); alloc != nil { - id, attrs := alloc.GetResponseCache() - if id != m.TransactionID { - msg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse), &stun.ErrorCodeAttribute{Code: stun.CodeAllocMismatch}) - return buildAndSendErr(r.Conn, r.SrcAddr, errRelayAlreadyAllocatedForFiveTuple, msg...) - } - // a retry allocation - msg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassSuccessResponse), append(attrs, messageIntegrity)...) - return buildAndSend(r.Conn, r.SrcAddr, msg...) + msg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassErrorResponse), &stun.ErrorCodeAttribute{Code: stun.CodeAllocMismatch}) + return buildAndSendErr(r.Conn, r.SrcAddr, errRelayAlreadyAllocatedForFiveTuple, msg...) } // 3. The server checks if the request contains a REQUESTED-TRANSPORT @@ -97,10 +91,10 @@ func handleAllocateRequest(r Request, m *stun.Message) error { // error. var evenPort proto.EvenPort if err = evenPort.GetFrom(m); err == nil { - var randomPort int + randomPort := 0 randomPort, err = r.AllocationManager.GetRandomEvenPort() if err != nil { - return buildAndSendErr(r.Conn, r.SrcAddr, err, insufficientCapacityMsg...) + return buildAndSendErr(r.Conn, r.SrcAddr, err, insufficentCapacityMsg...) } requestedPort = randomPort reservationToken = randSeq(8) @@ -124,7 +118,7 @@ func handleAllocateRequest(r Request, m *stun.Message) error { requestedPort, lifetimeDuration) if err != nil { - return buildAndSendErr(r.Conn, r.SrcAddr, err, insufficientCapacityMsg...) + return buildAndSendErr(r.Conn, r.SrcAddr, err, insufficentCapacityMsg...) } // Once the allocation is created, the server replies with a success @@ -168,7 +162,6 @@ func handleAllocateRequest(r Request, m *stun.Message) error { } msg := buildMsg(m.TransactionID, stun.NewType(stun.MethodAllocate, stun.ClassSuccessResponse), append(responseAttrs, messageIntegrity)...) - a.SetResponseCache(m.TransactionID, responseAttrs) return buildAndSend(r.Conn, r.SrcAddr, msg...) } @@ -231,15 +224,8 @@ func handleCreatePermissionRequest(r Request, m *stun.Message) error { return err } - if err := r.AllocationManager.GrantPermission(r.SrcAddr, peerAddress.IP); err != nil { - r.Log.Infof("permission denied for client %s to peer %s", r.SrcAddr.String(), - peerAddress.IP.String()) - return err - } - r.Log.Debugf("adding permission for %s", fmt.Sprintf("%s:%d", peerAddress.IP.String(), peerAddress.Port)) - a.AddPermission(allocation.NewPermission( &net.UDPAddr{ IP: peerAddress.IP, @@ -323,16 +309,6 @@ func handleChannelBindRequest(r Request, m *stun.Message) error { return buildAndSendErr(r.Conn, r.SrcAddr, err, badRequestMsg...) } - if err = r.AllocationManager.GrantPermission(r.SrcAddr, peerAddr.IP); err != nil { - r.Log.Infof("permission denied for client %s to peer %s", r.SrcAddr.String(), - peerAddr.IP.String()) - - unauthorizedRequestMsg := buildMsg(m.TransactionID, - stun.NewType(stun.MethodChannelBind, stun.ClassErrorResponse), - &stun.ErrorCodeAttribute{Code: stun.CodeUnauthorized}) - return buildAndSendErr(r.Conn, r.SrcAddr, err, unauthorizedRequestMsg...) - } - r.Log.Debugf("binding channel %d to %s", channel, fmt.Sprintf("%s:%d", peerAddr.IP.String(), peerAddr.Port)) diff --git a/vendor/github.com/pion/turn/v2/internal/server/util.go b/vendor/github.com/pion/turn/v2/internal/server/util.go index c9a339213..c6baffbd1 100644 --- a/vendor/github.com/pion/turn/v2/internal/server/util.go +++ b/vendor/github.com/pion/turn/v2/internal/server/util.go @@ -95,13 +95,8 @@ func authenticateRequest(r Request, m *stun.Message, callingMethod stun.Method) } // Assert Nonce exists and is not expired - nonceCreationTime, nonceFound := r.Nonces.Load(string(*nonceAttr)) - if !nonceFound { - r.Nonces.Delete(nonceAttr) - return respondWithNonce(stun.CodeStaleNonce) - } - - if timeValue, ok := nonceCreationTime.(time.Time); !ok || time.Since(timeValue) >= nonceLifetime { + nonceCreationTime, ok := r.Nonces.Load(string(*nonceAttr)) + if !ok || time.Since(nonceCreationTime.(time.Time)) >= nonceLifetime { r.Nonces.Delete(nonceAttr) return respondWithNonce(stun.CodeStaleNonce) } diff --git a/vendor/github.com/pion/turn/v2/lt_cred.go b/vendor/github.com/pion/turn/v2/lt_cred.go index d4e9ab565..f40f40c28 100644 --- a/vendor/github.com/pion/turn/v2/lt_cred.go +++ b/vendor/github.com/pion/turn/v2/lt_cred.go @@ -36,7 +36,7 @@ func NewLongTermAuthHandler(sharedSecret string, l logging.LeveledLogger) AuthHa l = logging.NewDefaultLoggerFactory().NewLogger("turn") } return func(username, realm string, srcAddr net.Addr) (key []byte, ok bool) { - l.Tracef("Authentication username=%q realm=%q srcAddr=%v", username, realm, srcAddr) + l.Tracef("Authentication username=%q realm=%q srcAddr=%v\n", username, realm, srcAddr) t, err := strconv.Atoi(username) if err != nil { l.Errorf("Invalid time-windowed username %q", username) diff --git a/vendor/github.com/pion/turn/v2/relay_address_generator_none.go b/vendor/github.com/pion/turn/v2/relay_address_generator_none.go index f453d0994..6fab06105 100644 --- a/vendor/github.com/pion/turn/v2/relay_address_generator_none.go +++ b/vendor/github.com/pion/turn/v2/relay_address_generator_none.go @@ -1,12 +1,10 @@ package turn import ( - "fmt" "net" "strconv" - "github.com/pion/transport/v2" - "github.com/pion/transport/v2/stdnet" + "github.com/pion/transport/vnet" ) // RelayAddressGeneratorNone returns the listener with no modifications @@ -14,17 +12,13 @@ type RelayAddressGeneratorNone struct { // Address is passed to Listen/ListenPacket when creating the Relay Address string - Net transport.Net + Net *vnet.Net } -// Validate is called on server startup and confirms the RelayAddressGenerator is properly configured +// Validate is caled on server startup and confirms the RelayAddressGenerator is properly configured func (r *RelayAddressGeneratorNone) Validate() error { if r.Net == nil { - var err error - r.Net, err = stdnet.NewNet() - if err != nil { - return fmt.Errorf("failed to create network: %w", err) - } + r.Net = vnet.NewNet(nil) } switch { diff --git a/vendor/github.com/pion/turn/v2/relay_address_generator_range.go b/vendor/github.com/pion/turn/v2/relay_address_generator_range.go index 48a0f2bbc..9f95429e2 100644 --- a/vendor/github.com/pion/turn/v2/relay_address_generator_range.go +++ b/vendor/github.com/pion/turn/v2/relay_address_generator_range.go @@ -5,8 +5,7 @@ import ( "net" "github.com/pion/randutil" - "github.com/pion/transport/v2" - "github.com/pion/transport/v2/stdnet" + "github.com/pion/transport/vnet" ) // RelayAddressGeneratorPortRange can be used to only allocate connections inside a defined port range. @@ -29,17 +28,13 @@ type RelayAddressGeneratorPortRange struct { // Address is passed to Listen/ListenPacket when creating the Relay Address string - Net transport.Net + Net *vnet.Net } // Validate is called on server startup and confirms the RelayAddressGenerator is properly configured func (r *RelayAddressGeneratorPortRange) Validate() error { if r.Net == nil { - var err error - r.Net, err = stdnet.NewNet() - if err != nil { - return fmt.Errorf("failed to create network: %w", err) - } + r.Net = vnet.NewNet(nil) } if r.Rand == nil { @@ -71,11 +66,7 @@ func (r *RelayAddressGeneratorPortRange) AllocatePacketConn(network string, requ if err != nil { return nil, nil, err } - relayAddr, ok := conn.LocalAddr().(*net.UDPAddr) - if !ok { - return nil, nil, errNilConn - } - + relayAddr := conn.LocalAddr().(*net.UDPAddr) relayAddr.IP = r.RelayAddress return conn, relayAddr, nil } @@ -87,11 +78,7 @@ func (r *RelayAddressGeneratorPortRange) AllocatePacketConn(network string, requ continue } - relayAddr, ok := conn.LocalAddr().(*net.UDPAddr) - if !ok { - return nil, nil, errNilConn - } - + relayAddr := conn.LocalAddr().(*net.UDPAddr) relayAddr.IP = r.RelayAddress return conn, relayAddr, nil } diff --git a/vendor/github.com/pion/turn/v2/relay_address_generator_static.go b/vendor/github.com/pion/turn/v2/relay_address_generator_static.go index ba2be9fd3..ae921e7f2 100644 --- a/vendor/github.com/pion/turn/v2/relay_address_generator_static.go +++ b/vendor/github.com/pion/turn/v2/relay_address_generator_static.go @@ -1,12 +1,10 @@ package turn import ( - "fmt" "net" "strconv" - "github.com/pion/transport/v2" - "github.com/pion/transport/v2/stdnet" + "github.com/pion/transport/vnet" ) // RelayAddressGeneratorStatic can be used to return static IP address each time a relay is created. @@ -18,17 +16,13 @@ type RelayAddressGeneratorStatic struct { // Address is passed to Listen/ListenPacket when creating the Relay Address string - Net transport.Net + Net *vnet.Net } -// Validate is called on server startup and confirms the RelayAddressGenerator is properly configured +// Validate is caled on server startup and confirms the RelayAddressGenerator is properly configured func (r *RelayAddressGeneratorStatic) Validate() error { if r.Net == nil { - var err error - r.Net, err = stdnet.NewNet() - if err != nil { - return fmt.Errorf("failed to create network: %w", err) - } + r.Net = vnet.NewNet(nil) } switch { @@ -49,11 +43,7 @@ func (r *RelayAddressGeneratorStatic) AllocatePacketConn(network string, request } // Replace actual listening IP with the user requested one of RelayAddressGeneratorStatic - relayAddr, ok := conn.LocalAddr().(*net.UDPAddr) - if !ok { - return nil, nil, errNilConn - } - + relayAddr := conn.LocalAddr().(*net.UDPAddr) relayAddr.IP = r.RelayAddress return conn, relayAddr, nil diff --git a/vendor/github.com/pion/turn/v2/renovate.json b/vendor/github.com/pion/turn/v2/renovate.json index f1bb98c6a..f1614058a 100644 --- a/vendor/github.com/pion/turn/v2/renovate.json +++ b/vendor/github.com/pion/turn/v2/renovate.json @@ -1,6 +1,27 @@ { - "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ - "github>pion/renovate-config" + "config:base", + ":disableDependencyDashboard" + ], + "postUpdateOptions": [ + "gomodTidy" + ], + "commitBody": "Generated by renovateBot", + "packageRules": [ + { + "matchUpdateTypes": ["minor", "patch", "pin", "digest"], + "automerge": true + }, + { + "packagePatterns": ["^golang.org/x/"], + "schedule": ["on the first day of the month"] + } + ], + "ignorePaths": [ + ".github/workflows/generate-authors.yml", + ".github/workflows/lint.yaml", + ".github/workflows/renovate-go-mod-fix.yaml", + ".github/workflows/test.yaml", + ".github/workflows/tidy-check.yaml" ] } diff --git a/vendor/github.com/pion/turn/v2/server.go b/vendor/github.com/pion/turn/v2/server.go index 3f57f9db0..fc36aef87 100644 --- a/vendor/github.com/pion/turn/v2/server.go +++ b/vendor/github.com/pion/turn/v2/server.go @@ -28,12 +28,11 @@ type Server struct { packetConnConfigs []PacketConnConfig listenerConfigs []ListenerConfig allocationManagers []*allocation.Manager - inboundMTU int + + inboundMTU int } // NewServer creates the Pion TURN server -// -//nolint:gocognit func NewServer(config ServerConfig) (*Server, error) { if err := config.validate(); err != nil { return nil, err @@ -56,6 +55,7 @@ func NewServer(config ServerConfig) (*Server, error) { channelBindTimeout: config.ChannelBindTimeout, packetConnConfigs: config.PacketConnConfigs, listenerConfigs: config.ListenerConfigs, + allocationManagers: make([]*allocation.Manager, len(config.PacketConnConfigs)+len(config.ListenerConfigs)), nonces: &sync.Map{}, inboundMTU: mtu, } @@ -64,22 +64,56 @@ func NewServer(config ServerConfig) (*Server, error) { s.channelBindTimeout = proto.DefaultLifetime } - for _, cfg := range s.packetConnConfigs { - am, err := s.createAllocationManager(cfg.RelayAddressGenerator, cfg.PermissionHandler) - if err != nil { - return nil, fmt.Errorf("failed to create AllocationManager: %w", err) - } + for i := range s.packetConnConfigs { + go func(i int, p PacketConnConfig) { + allocationManager, err := allocation.NewManager(allocation.ManagerConfig{ + AllocatePacketConn: p.RelayAddressGenerator.AllocatePacketConn, + AllocateConn: p.RelayAddressGenerator.AllocateConn, + LeveledLogger: s.log, + }) + if err != nil { + s.log.Errorf("exit read loop on error: %s", err.Error()) + return + } + s.allocationManagers[i] = allocationManager + defer func() { + if err := allocationManager.Close(); err != nil { + s.log.Errorf("Failed to close AllocationManager: %s", err.Error()) + } + }() - go s.readPacketConn(cfg, am) + s.readLoop(p.PacketConn, allocationManager) + }(i, s.packetConnConfigs[i]) } - for _, cfg := range s.listenerConfigs { - am, err := s.createAllocationManager(cfg.RelayAddressGenerator, cfg.PermissionHandler) - if err != nil { - return nil, fmt.Errorf("failed to create AllocationManager: %w", err) - } + for i, listener := range s.listenerConfigs { + go func(i int, l ListenerConfig) { + allocationManager, err := allocation.NewManager(allocation.ManagerConfig{ + AllocatePacketConn: l.RelayAddressGenerator.AllocatePacketConn, + AllocateConn: l.RelayAddressGenerator.AllocateConn, + LeveledLogger: s.log, + }) + if err != nil { + s.log.Errorf("exit read loop on error: %s", err.Error()) + return + } + s.allocationManagers[i] = allocationManager + defer func() { + if err := allocationManager.Close(); err != nil { + s.log.Errorf("Failed to close AllocationManager: %s", err.Error()) + } + }() - go s.readListener(cfg, am) + for { + conn, err := l.Listener.Accept() + if err != nil { + s.log.Debugf("exit accept loop on error: %s", err.Error()) + return + } + + go s.readLoop(NewSTUNConn(conn), allocationManager) + } + }(i+len(s.packetConnConfigs), listener) } return s, nil @@ -87,25 +121,27 @@ func NewServer(config ServerConfig) (*Server, error) { // AllocationCount returns the number of active allocations. It can be used to drain the server before closing func (s *Server) AllocationCount() int { - allocs := 0 - for _, am := range s.allocationManagers { - allocs += am.AllocationCount() + allocations := 0 + for _, manager := range s.allocationManagers { + if manager != nil { + allocations += manager.AllocationCount() + } } - return allocs + return allocations } // Close stops the TURN Server. It cleans up any associated state and closes all connections it is managing func (s *Server) Close() error { var errors []error - for _, cfg := range s.packetConnConfigs { - if err := cfg.PacketConn.Close(); err != nil { + for _, p := range s.packetConnConfigs { + if err := p.PacketConn.Close(); err != nil { errors = append(errors, err) } } - for _, cfg := range s.listenerConfigs { - if err := cfg.Listener.Close(); err != nil { + for _, l := range s.listenerConfigs { + if err := l.Listener.Close(); err != nil { errors = append(errors, err) } } @@ -116,58 +152,12 @@ func (s *Server) Close() error { err := errFailedToClose for _, e := range errors { - err = fmt.Errorf("%s; close error (%w) ", err, e) + err = fmt.Errorf("%s; Close error (%v) ", err.Error(), e) //nolint:goerr113 } return err } -func (s *Server) readPacketConn(p PacketConnConfig, am *allocation.Manager) { - s.readLoop(p.PacketConn, am) - - if err := am.Close(); err != nil { - s.log.Errorf("Failed to close AllocationManager: %s", err) - } -} - -func (s *Server) readListener(l ListenerConfig, am *allocation.Manager) { - defer func() { - if err := am.Close(); err != nil { - s.log.Errorf("Failed to close AllocationManager: %s", err) - } - }() - - for { - conn, err := l.Listener.Accept() - if err != nil { - s.log.Debugf("Failed to accept: %s", err) - return - } - - go s.readLoop(NewSTUNConn(conn), am) - } -} - -func (s *Server) createAllocationManager(addrGenerator RelayAddressGenerator, handler PermissionHandler) (*allocation.Manager, error) { - if handler == nil { - handler = DefaultPermissionHandler - } - - am, err := allocation.NewManager(allocation.ManagerConfig{ - AllocatePacketConn: addrGenerator.AllocatePacketConn, - AllocateConn: addrGenerator.AllocateConn, - PermissionHandler: handler, - LeveledLogger: s.log, - }) - if err != nil { - return am, err - } - - s.allocationManagers = append(s.allocationManagers, am) - - return am, err -} - func (s *Server) readLoop(p net.PacketConn, allocationManager *allocation.Manager) { buf := make([]byte, s.inboundMTU) for { diff --git a/vendor/github.com/pion/turn/v2/server_config.go b/vendor/github.com/pion/turn/v2/server_config.go index 5487900db..a506abe3a 100644 --- a/vendor/github.com/pion/turn/v2/server_config.go +++ b/vendor/github.com/pion/turn/v2/server_config.go @@ -23,19 +23,6 @@ type RelayAddressGenerator interface { AllocateConn(network string, requestedPort int) (net.Conn, net.Addr, error) } -// PermissionHandler is a callback to filter incoming CreatePermission and ChannelBindRequest -// requests based on the client IP address and port and the peer IP address the client intends to -// connect to. If the client is behind a NAT then the filter acts on the server reflexive -// ("mapped") address instead of the real client IP address and port. Note that TURN permissions -// are per-allocation and per-peer-IP-address, to mimic the address-restricted filtering mechanism -// of NATs that comply with [RFC4787], see https://tools.ietf.org/html/rfc5766#section-2.3. -type PermissionHandler func(clientAddr net.Addr, peerIP net.IP) (ok bool) - -// DefaultPermissionHandler is convince function that grants permission to all peers -func DefaultPermissionHandler(clientAddr net.Addr, peerIP net.IP) (ok bool) { - return true -} - // PacketConnConfig is a single net.PacketConn to listen/write on. This will be used for UDP listeners type PacketConnConfig struct { PacketConn net.PacketConn @@ -43,11 +30,6 @@ type PacketConnConfig struct { // When an allocation is generated the RelayAddressGenerator // creates the net.PacketConn and returns the IP/Port it is available at RelayAddressGenerator RelayAddressGenerator - - // PermissionHandler is a callback to filter peer addresses. Can be set as nil, in which - // case the DefaultPermissionHandler is automatically instantiated to admit all peer - // connections - PermissionHandler PermissionHandler } func (c *PacketConnConfig) validate() error { @@ -68,11 +50,6 @@ type ListenerConfig struct { // When an allocation is generated the RelayAddressGenerator // creates the net.PacketConn and returns the IP/Port it is available at RelayAddressGenerator RelayAddressGenerator - - // PermissionHandler is a callback to filter peer addresses. Can be set as nil, in which - // case the DefaultPermissionHandler is automatically instantiated to admit all peer - // connections - PermissionHandler PermissionHandler } func (c *ListenerConfig) validate() error { @@ -90,7 +67,7 @@ func (c *ListenerConfig) validate() error { // AuthHandler is a callback used to handle incoming auth requests, allowing users to customize Pion TURN with custom behavior type AuthHandler func(username, realm string, srcAddr net.Addr) (key []byte, ok bool) -// GenerateAuthKey is a convenience function to easily generate keys in the format used by AuthHandler +// GenerateAuthKey is a convince function to easily generate keys in the format used by AuthHandler func GenerateAuthKey(username, realm, password string) []byte { // #nosec h := md5.New() diff --git a/vendor/github.com/pion/transport/v2/.gitignore b/vendor/github.com/pion/udp/.gitignore similarity index 72% rename from vendor/github.com/pion/transport/v2/.gitignore rename to vendor/github.com/pion/udp/.gitignore index 6e2f206a9..83db74ba5 100644 --- a/vendor/github.com/pion/transport/v2/.gitignore +++ b/vendor/github.com/pion/udp/.gitignore @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - ### JetBrains IDE ### ##################### .idea/ @@ -25,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/transport/v2/.golangci.yml b/vendor/github.com/pion/udp/.golangci.yml similarity index 59% rename from vendor/github.com/pion/transport/v2/.golangci.yml rename to vendor/github.com/pion/udp/.golangci.yml index 4e3eddf42..d6162c970 100644 --- a/vendor/github.com/pion/transport/v2/.golangci.yml +++ b/vendor/github.com/pion/udp/.golangci.yml @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - linters-settings: govet: check-shadowing: true @@ -13,34 +10,19 @@ linters-settings: modules: - github.com/pkg/errors: recommendations: - - errors - forbidigo: - forbid: - - ^fmt.Print(f|ln)?$ - - ^log.(Panic|Fatal|Print)(f|ln)?$ - - ^os.Exit$ - - ^panic$ - - ^print(ln)?$ + - errors linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - - decorder # check declaration order and count of types, constants, variables and functions + - deadcode # Finds unused code - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forbidigo # Forbids identifiers - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -53,59 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks + - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - - wastedassign # wastedassign finds wasted assignment statements + - varcheck # Finds unused global variables and constants - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: @@ -115,23 +78,12 @@ issues: - path: _test\.go linters: - gocognit - - forbidigo # Allow complex main function in examples - path: examples text: "of func `main` is high" linters: - gocognit - - # Allow forbidden identifiers in examples - - path: examples - linters: - - forbidigo - - # Allow forbidden identifiers in CLI commands - - path: cmd - linters: - - forbidigo run: skip-dirs-use-default: false diff --git a/vendor/github.com/pion/udp/LICENSE b/vendor/github.com/pion/udp/LICENSE new file mode 100644 index 000000000..81f990d60 --- /dev/null +++ b/vendor/github.com/pion/udp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/pion/udp/README.md b/vendor/github.com/pion/udp/README.md new file mode 100644 index 000000000..63e7bcb2f --- /dev/null +++ b/vendor/github.com/pion/udp/README.md @@ -0,0 +1,41 @@ +

+
+ Pion UDP +
+

+

A connection-oriented listener over a UDP PacketConn

+

+ Pion UDP + + Slack Widget +
+ Build Status + GoDoc + Coverage Status + Go Report Card + + License: MIT +

+
+ +### Roadmap +This package is used in the [DTLS](https://github.com/pion/dtls) and [SCTP](https://github.com/pion/sctp) transport to provide a connection-oriented listener over a UDP. + +### Community +Pion has an active community on the [Golang Slack](https://pion.ly/slack/). You can also use [Pion mailing list](https://groups.google.com/forum/#!forum/pion). + +We are always looking to support **your projects**. Please reach out if you have something to build! + +If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly) + +### Contributing +Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible: + +* [Sean DuBois](https://github.com/Sean-Der) - *Original Author* +* [Michiel De Backker](https://github.com/backkem) - *Original Author* +* [Atsushi Watanabe](https://github.com/at-wat) - *Original Author* +* [ZHENK](https://github.com/scorpionknifes) +* [Daniel Beseda](https://github.com/besedad) + +### License +MIT License - see [LICENSE](LICENSE) for full text diff --git a/vendor/github.com/pion/transport/v2/codecov.yml b/vendor/github.com/pion/udp/codecov.yml similarity index 78% rename from vendor/github.com/pion/transport/v2/codecov.yml rename to vendor/github.com/pion/udp/codecov.yml index 263e4d45c..085200a48 100644 --- a/vendor/github.com/pion/transport/v2/codecov.yml +++ b/vendor/github.com/pion/udp/codecov.yml @@ -3,8 +3,6 @@ # # It is automatically copied from https://github.com/pion/.goassets repository. # -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT coverage: status: diff --git a/vendor/github.com/pion/transport/v2/udp/conn.go b/vendor/github.com/pion/udp/conn.go similarity index 83% rename from vendor/github.com/pion/transport/v2/udp/conn.go rename to vendor/github.com/pion/udp/conn.go index 2b57174a3..a845d4af5 100644 --- a/vendor/github.com/pion/transport/v2/udp/conn.go +++ b/vendor/github.com/pion/udp/conn.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package udp provides a connection-oriented listener over a UDP PacketConn package udp @@ -12,8 +9,8 @@ import ( "sync/atomic" "time" - "github.com/pion/transport/v2/deadline" - "github.com/pion/transport/v2/packetio" + "github.com/pion/transport/deadline" + "github.com/pion/transport/packetio" ) const ( @@ -25,7 +22,6 @@ const ( var ( ErrClosedListener = errors.New("udp: listener closed") ErrListenQueueExceeded = errors.New("udp: listen queue exceeded") - ErrReadBufferFailed = errors.New("udp: failed to get read buffer from pool") ) // listener augments a connection-oriented Listener over a UDP PacketConn @@ -41,13 +37,10 @@ type listener struct { connLock sync.Mutex conns map[string]*Conn - connWG *sync.WaitGroup + connWG sync.WaitGroup readWG sync.WaitGroup errClose atomic.Value // error - - readDoneCh chan struct{} - errRead atomic.Value // error } // Accept waits for and returns the next connection to the listener. @@ -57,10 +50,6 @@ func (l *listener) Accept() (net.Conn, error) { l.connWG.Add(1) return c, nil - case <-l.readDoneCh: - err, _ := l.errRead.Load().(error) - return nil, err - case <-l.doneCh: return nil, ErrClosedListener } @@ -76,7 +65,7 @@ func (l *listener) Close() error { l.connLock.Lock() // Close unaccepted connections - lclose: + L_CLOSE: for { select { case c := <-l.acceptCh: @@ -84,7 +73,7 @@ func (l *listener) Close() error { delete(l.conns, c.rAddr.String()) default: - break lclose + break L_CLOSE } } nConns := len(l.conns) @@ -149,8 +138,6 @@ func (lc *ListenConfig) Listen(network string, laddr *net.UDPAddr) (net.Listener return &buf }, }, - connWG: &sync.WaitGroup{}, - readDoneCh: make(chan struct{}), } l.accepting.Store(true) @@ -175,32 +162,24 @@ func Listen(network string, laddr *net.UDPAddr) (net.Listener, error) { } // readLoop has to tasks: -// 1. Dispatching incoming packets to the correct Conn. -// It can therefore not be ended until all Conns are closed. -// 2. Creating a new Conn when receiving from a new remote. +// 1. Dispatching incoming packets to the correct Conn. +// It can therefore not be ended until all Conns are closed. +// 2. Creating a new Conn when receiving from a new remote. func (l *listener) readLoop() { defer l.readWG.Done() - defer close(l.readDoneCh) - - buf, ok := l.readBufferPool.Get().(*[]byte) - if !ok { - l.errRead.Store(ErrReadBufferFailed) - return - } - defer l.readBufferPool.Put(buf) for { - n, raddr, err := l.pConn.ReadFrom(*buf) + buf := *(l.readBufferPool.Get().(*[]byte)) + n, raddr, err := l.pConn.ReadFrom(buf) if err != nil { - l.errRead.Store(err) return } - conn, ok, err := l.getConn(raddr, (*buf)[:n]) + conn, ok, err := l.getConn(raddr, buf[:n]) if err != nil { continue } if ok { - _, _ = conn.buffer.Write((*buf)[:n]) + _, _ = conn.buffer.Write(buf[:n]) } } } @@ -210,7 +189,7 @@ func (l *listener) getConn(raddr net.Addr, buf []byte) (*Conn, bool, error) { defer l.connLock.Unlock() conn, ok := l.conns[raddr.String()] if !ok { - if isAccepting, ok := l.accepting.Load().(bool); !isAccepting || !ok { + if !l.accepting.Load().(bool) { return nil, false, ErrClosedListener } if l.acceptFilter != nil { @@ -279,7 +258,7 @@ func (c *Conn) Close() error { nConns := len(c.listener.conns) c.listener.connLock.Unlock() - if isAccepting, ok := c.listener.accepting.Load().(bool); nConns == 0 && !isAccepting && ok { + if nConns == 0 && !c.listener.accepting.Load().(bool) { // Wait if this is the final connection c.listener.readWG.Wait() if errClose, ok := c.listener.errClose.Load().(error); ok { @@ -288,10 +267,6 @@ func (c *Conn) Close() error { } else { err = nil } - - if errBuf := c.buffer.Close(); errBuf != nil && err == nil { - err = errBuf - } }) return err diff --git a/vendor/github.com/pion/udp/renovate.json b/vendor/github.com/pion/udp/renovate.json new file mode 100644 index 000000000..4400fd9b2 --- /dev/null +++ b/vendor/github.com/pion/udp/renovate.json @@ -0,0 +1,15 @@ +{ + "extends": [ + "config:base" + ], + "postUpdateOptions": [ + "gomodTidy" + ], + "commitBody": "Generated by renovateBot", + "packageRules": [ + { + "packagePatterns": ["^golang.org/x/"], + "schedule": ["on the first day of the month"] + } + ] +} diff --git a/vendor/github.com/pion/webrtc/v3/.codacy.yaml b/vendor/github.com/pion/webrtc/v3/.codacy.yaml index aa0b11b39..a8c225b74 100644 --- a/vendor/github.com/pion/webrtc/v3/.codacy.yaml +++ b/vendor/github.com/pion/webrtc/v3/.codacy.yaml @@ -1,6 +1,3 @@ --- -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - exclude_paths: - examples/examples.json diff --git a/vendor/github.com/pion/webrtc/v3/.gitignore b/vendor/github.com/pion/webrtc/v3/.gitignore index 6e2f206a9..83db74ba5 100644 --- a/vendor/github.com/pion/webrtc/v3/.gitignore +++ b/vendor/github.com/pion/webrtc/v3/.gitignore @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - ### JetBrains IDE ### ##################### .idea/ @@ -25,4 +22,3 @@ cover.out *.wasm examples/sfu-ws/cert.pem examples/sfu-ws/key.pem -wasm_exec.js diff --git a/vendor/github.com/pion/webrtc/v3/.golangci.yml b/vendor/github.com/pion/webrtc/v3/.golangci.yml index 4e3eddf42..d6162c970 100644 --- a/vendor/github.com/pion/webrtc/v3/.golangci.yml +++ b/vendor/github.com/pion/webrtc/v3/.golangci.yml @@ -1,6 +1,3 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - linters-settings: govet: check-shadowing: true @@ -13,34 +10,19 @@ linters-settings: modules: - github.com/pkg/errors: recommendations: - - errors - forbidigo: - forbid: - - ^fmt.Print(f|ln)?$ - - ^log.(Panic|Fatal|Print)(f|ln)?$ - - ^os.Exit$ - - ^panic$ - - ^print(ln)?$ + - errors linters: enable: - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - - bidichk # Checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - - contextcheck # check the function whether use a non-inherited context - - decorder # check declaration order and count of types, constants, variables and functions + - deadcode # Finds unused code - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - - durationcheck # check for two durations multiplied together - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases - - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. - - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - exhaustive # check exhaustiveness of enum switch statements - exportloopref # checks for pointers to enclosing loop variables - - forbidigo # Forbids identifiers - - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - gochecknoglobals # Checks that no globals are present in Go code - gochecknoinits # Checks that no init functions are present in Go code @@ -53,59 +35,40 @@ linters: - gofumpt # Gofumpt checks whether code was gofumpt-ed. - goheader # Checks is file header matches to pattern - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports - - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. + - golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. - - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used - misspell # Finds commonly misspelled English words in comments - nakedret # Finds naked returns in functions greater than a specified function length - - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - noctx # noctx finds sending http request without context.Context - - predeclared # find code that shadows one of Go's predeclared identifiers - - revive # golint replacement, finds style mistakes + - scopelint # Scopelint checks for unpinned variables in go programs - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks + - structcheck # Finds unused struct fields - stylecheck # Stylecheck is a replacement for golint - - tagliatelle # Checks the struct tags. - - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - - wastedassign # wastedassign finds wasted assignment statements + - varcheck # Finds unused global variables and constants - whitespace # Tool for detection of leading and trailing whitespace disable: - - containedctx # containedctx is a linter that detects struct contained context.Context field - - cyclop # checks function and package cyclomatic complexity - - exhaustivestruct # Checks if all struct's fields are initialized - funlen # Tool for detection of long functions - gocyclo # Computes and checks the cyclomatic complexity of functions - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - - ifshort # Checks that your code uses short syntax for if-statements whenever possible - - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - - maintidx # maintidx measures the maintainability index of each function. - - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity - nolintlint # Reports ill-formed or insufficient nolint directives - - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - testpackage # linter that makes you use a separate _test package - - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers - - varnamelen # checks that the length of a variable's name matches its scope - - wrapcheck # Checks that errors returned from external packages are wrapped - wsl # Whitespace Linter - Forces you to use empty lines! issues: @@ -115,23 +78,12 @@ issues: - path: _test\.go linters: - gocognit - - forbidigo # Allow complex main function in examples - path: examples text: "of func `main` is high" linters: - gocognit - - # Allow forbidden identifiers in examples - - path: examples - linters: - - forbidigo - - # Allow forbidden identifiers in CLI commands - - path: cmd - linters: - - forbidigo run: skip-dirs-use-default: false diff --git a/vendor/github.com/pion/webrtc/v3/.goreleaser.yml b/vendor/github.com/pion/webrtc/v3/.goreleaser.yml deleted file mode 100644 index 30093e9d6..000000000 --- a/vendor/github.com/pion/webrtc/v3/.goreleaser.yml +++ /dev/null @@ -1,5 +0,0 @@ -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT - -builds: -- skip: true diff --git a/vendor/github.com/pion/webrtc/v3/AUTHORS.txt b/vendor/github.com/pion/webrtc/v3/AUTHORS.txt index 4ebd9a22f..0ef018685 100644 --- a/vendor/github.com/pion/webrtc/v3/AUTHORS.txt +++ b/vendor/github.com/pion/webrtc/v3/AUTHORS.txt @@ -2,13 +2,10 @@ # we would love to have you https://github.com/pion/webrtc/wiki/Contributing # # This file is auto generated, using git to list all individuals contributors. -# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting +# see `.github/generate-authors.sh` for the scripting a-wing <1@233.email> -Aaron Boushley Aaron France Adam Kiss -Aditya Kumar -Adrian Cable adwpc aggresss akil @@ -16,13 +13,11 @@ Aleksandr Razumov aler9 <46489434+aler9@users.noreply.github.com> Alex Browne Alex Harford -Alexey Khit AlexWoo(武杰) Ali Error Andrew N. Shalaev Antoine Baché Antoine Baché -Anton Artur Shellunts Assad Obaid Ato Araki @@ -44,17 +39,13 @@ Cedric Fung cgojin Chad Retz chenkaiC4 -Chinmay Kousik Chris Hiszpanski Christopher Fry Clayton McCray cnderrauber cyannuk -Daniele Sluijters David Hamilton David Zhao -David Zhao -david.s Dean Sheather decanus <7621705+decanus@users.noreply.github.com> Denis @@ -63,12 +54,8 @@ donotanswer earle Egon Elbre Eric Daniels -Eric Fontaine feixiao -Forest Johnson frank -funvit -Gabor Pongracz Gareth Hayes Guilherme Hanjun Kim @@ -85,16 +72,12 @@ Jake B Jamie Good Jason Jeff Tchang -jeremija Jerko Steiner -Jerry Tao jinleileiking John Berthels John Bradley -John Selbie JooYoung Jorropo -Josh Bleecher Snyder juberti Juliusz Chroboczek Justin Okamoto @@ -107,14 +90,11 @@ krishna chiatanya Kuzmin Vladimir lawl Len -Leslie Wang -lisa yan Lukas Herman Luke Luke Curley Luke S Magnus Wahlstrand -Manish Markus Tzoe Marouane <6729798+nindolabs@users.noreply.github.com> Marouane @@ -128,8 +108,6 @@ Michiel De Backker <38858977+backkem@users.noreply.github.com> Mike Coleman Mindgamesnl mission-liao -mohammadne -mr-shitij <21.shitijagrawal@gmail.com> mxmCherry Nam V. Do Nick Mykins @@ -143,11 +121,9 @@ opennota OrlandoCo Pascal Benoit pascal-ace <47424881+pascal-ace@users.noreply.github.com> -Patrice Ferlet Patrick Lange Patryk Rogalski Pieere Pi -Pouget-Abadie q191201771 <191201771@qq.com> Quentin Renard Rafael Viscarra @@ -155,7 +131,6 @@ rahulnakre Raphael Randschau Raphael Randschau Reese <3253971+figadore@users.noreply.github.com> -rob rob-deutsch Robert Eperjesi Robin Raymond @@ -165,24 +140,18 @@ ronan Ryan Shumate salmān aljammāz Sam Lancia -Sean DuBois Sean DuBois Sean DuBois Sean DuBois Sean DuBois Sean Knight Sebastian Waisbrot -Sidney San Martín Simon Eisenmann simonacca-fotokite <47634061+simonacca-fotokite@users.noreply.github.com> Simone Gotti Slugalisk -Somers Matthews soolaugust spaceCh1mp -Steffen Vogel -stephanrotolante -streamer45 Suhas Gaddam Suzuki Takeo sylba2050 @@ -191,17 +160,13 @@ tarrencev Thomas Miller Tobias Fridén Tomek -treyhakanson -Tristan Matthews Twometer Vicken Simonian wattanakorn495 Will Forcey Will Watson -WofWca Woodrow Douglass xsbchen -Yoon SeungYong Yuki Igarashi yusuke Yutaka Takeda @@ -209,6 +174,3 @@ ZHENK zigazeljko Štefan Uram 박종훈 - -# List of contributors not appearing in Git history - diff --git a/vendor/github.com/pion/webrtc/v3/LICENSE b/vendor/github.com/pion/webrtc/v3/LICENSE index 491caf6b0..ab602974d 100644 --- a/vendor/github.com/pion/webrtc/v3/LICENSE +++ b/vendor/github.com/pion/webrtc/v3/LICENSE @@ -1,9 +1,21 @@ MIT License -Copyright (c) 2023 The Pion community +Copyright (c) 2018 -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/pion/webrtc/v3/README.md b/vendor/github.com/pion/webrtc/v3/README.md index 80dd8c123..da1b3d67f 100644 --- a/vendor/github.com/pion/webrtc/v3/README.md +++ b/vendor/github.com/pion/webrtc/v3/README.md @@ -6,16 +6,17 @@

A pure Go implementation of the WebRTC API

- Pion WebRTC + Pion webrtc Sourcegraph Widget Slack Widget Twitter Widget
- GitHub Workflow Status - Go Reference + Build Status + PkgGoDev Coverage Status - Go Report Card + Go Report Card + Codacy Badge License: MIT


@@ -87,7 +88,7 @@ This book is vendor agnostic and will not have any Pion specific information. * [NACK](https://github.com/pion/interceptor/pull/4) * [Sender/Receiver Reports](https://github.com/pion/interceptor/tree/master/pkg/report) * [Transport Wide Congestion Control Feedback](https://github.com/pion/interceptor/tree/master/pkg/twcc) -* [Bandwidth Estimation](https://github.com/pion/webrtc/tree/master/examples/bandwidth-estimation-from-disk) +* Bandwidth Estimation is actively being implemented, see [pion/interceptor#25](https://github.com/pion/interceptor/issues/25) #### Security * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 and TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA for DTLS v1.2 @@ -106,14 +107,12 @@ This book is vendor agnostic and will not have any Pion specific information. * **Time to run entire test suite** - 25.60s user 9.40s system 45% cpu 1:16.69 total * Tools to measure performance [provided](https://github.com/pion/rtsp-bench) + ### Roadmap The library is in active development, please refer to the [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones. We also maintain a list of [Big Ideas](https://github.com/pion/webrtc/wiki/Big-Ideas) these are things we want to build but don't have a clear plan or the resources yet. If you are looking to get involved this is a great place to get started! We would also love to hear your ideas! Even if you can't implement it yourself, it could inspire others. -### Sponsoring -Work on Pion's congestion control and bandwidth estimation was funded through the [User-Operated Internet](https://nlnet.nl/useroperated/) fund, a fund established by [NLnet](https://nlnet.nl/) made possible by financial support from the [PKT Community](https://pkt.cash/)/[The Network Steward](https://pkt.cash/network-steward) and stichting [Technology Commons Trust](https://technologycommons.org/). - ### Community Pion has an active community on the [Slack](https://pion.ly/slack). @@ -123,7 +122,7 @@ We are always looking to support **your projects**. Please reach out if you have If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly) ### Contributing -Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible: [AUTHORS.txt](./AUTHORS.txt) +Check out the **[contributing wiki](https://github.com/pion/webrtc/wiki/Contributing)** to join the group of amazing people making this project possible: ### License MIT License - see [LICENSE](LICENSE) for full text diff --git a/vendor/github.com/pion/webrtc/v3/api.go b/vendor/github.com/pion/webrtc/v3/api.go index 716be1f38..85424df4d 100644 --- a/vendor/github.com/pion/webrtc/v3/api.go +++ b/vendor/github.com/pion/webrtc/v3/api.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -46,8 +43,6 @@ func NewAPI(options ...func(*API)) *API { // WithMediaEngine allows providing a MediaEngine to the API. // Settings can be changed after passing the engine to an API. -// When a PeerConnection is created the MediaEngine is copied -// and no more changes can be made. func WithMediaEngine(m *MediaEngine) func(a *API) { return func(a *API) { a.mediaEngine = m diff --git a/vendor/github.com/pion/webrtc/v3/api_js.go b/vendor/github.com/pion/webrtc/v3/api_js.go index fe94bff1f..3d81ed7b1 100644 --- a/vendor/github.com/pion/webrtc/v3/api_js.go +++ b/vendor/github.com/pion/webrtc/v3/api_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/atomicbool.go b/vendor/github.com/pion/webrtc/v3/atomicbool.go index cc6cdc1e8..1d4bf55ac 100644 --- a/vendor/github.com/pion/webrtc/v3/atomicbool.go +++ b/vendor/github.com/pion/webrtc/v3/atomicbool.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import "sync/atomic" @@ -23,7 +20,7 @@ func (b *atomicBool) get() bool { } func (b *atomicBool) swap(value bool) bool { - var i int32 + var i int32 = 0 if value { i = 1 } diff --git a/vendor/github.com/pion/webrtc/v3/bundlepolicy.go b/vendor/github.com/pion/webrtc/v3/bundlepolicy.go index ea6dad5ae..6d39a2773 100644 --- a/vendor/github.com/pion/webrtc/v3/bundlepolicy.go +++ b/vendor/github.com/pion/webrtc/v3/bundlepolicy.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/certificate.go b/vendor/github.com/pion/webrtc/v3/certificate.go index 1d5631bc4..99e359741 100644 --- a/vendor/github.com/pion/webrtc/v3/certificate.go +++ b/vendor/github.com/pion/webrtc/v3/certificate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -108,12 +105,10 @@ func (c Certificate) GetFingerprints() ([]DTLSFingerprint, error) { for _, algo := range fingerprintAlgorithms { name, err := fingerprint.StringFromHash(algo) if err != nil { - // nolint return nil, fmt.Errorf("%w: %v", ErrFailedToGenerateCertificateFingerprint, err) } value, err := fingerprint.Fingerprint(c.x509Cert, algo) if err != nil { - // nolint return nil, fmt.Errorf("%w: %v", ErrFailedToGenerateCertificateFingerprint, err) } res[i] = DTLSFingerprint{ diff --git a/vendor/github.com/pion/webrtc/v3/codecov.yml b/vendor/github.com/pion/webrtc/v3/codecov.yml index 263e4d45c..085200a48 100644 --- a/vendor/github.com/pion/webrtc/v3/codecov.yml +++ b/vendor/github.com/pion/webrtc/v3/codecov.yml @@ -3,8 +3,6 @@ # # It is automatically copied from https://github.com/pion/.goassets repository. # -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT coverage: status: diff --git a/vendor/github.com/pion/webrtc/v3/configuration.go b/vendor/github.com/pion/webrtc/v3/configuration.go index 90be318e9..608c5ab7e 100644 --- a/vendor/github.com/pion/webrtc/v3/configuration.go +++ b/vendor/github.com/pion/webrtc/v3/configuration.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js diff --git a/vendor/github.com/pion/webrtc/v3/configuration_common.go b/vendor/github.com/pion/webrtc/v3/configuration_common.go index a3acdf5b8..92fc22831 100644 --- a/vendor/github.com/pion/webrtc/v3/configuration_common.go +++ b/vendor/github.com/pion/webrtc/v3/configuration_common.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import "strings" diff --git a/vendor/github.com/pion/webrtc/v3/configuration_js.go b/vendor/github.com/pion/webrtc/v3/configuration_js.go index 097085f9b..2ba4d268e 100644 --- a/vendor/github.com/pion/webrtc/v3/configuration_js.go +++ b/vendor/github.com/pion/webrtc/v3/configuration_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/constants.go b/vendor/github.com/pion/webrtc/v3/constants.go index 94ba78494..825601ddb 100644 --- a/vendor/github.com/pion/webrtc/v3/constants.go +++ b/vendor/github.com/pion/webrtc/v3/constants.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import "github.com/pion/dtls/v2" @@ -39,5 +36,5 @@ const ( ) func defaultSrtpProtectionProfiles() []dtls.SRTPProtectionProfile { - return []dtls.SRTPProtectionProfile{dtls.SRTP_AEAD_AES_256_GCM, dtls.SRTP_AEAD_AES_128_GCM, dtls.SRTP_AES128_CM_HMAC_SHA1_80} + return []dtls.SRTPProtectionProfile{dtls.SRTP_AEAD_AES_128_GCM, dtls.SRTP_AES128_CM_HMAC_SHA1_80} } diff --git a/vendor/github.com/pion/webrtc/v3/datachannel.go b/vendor/github.com/pion/webrtc/v3/datachannel.go index 9c9154c8c..4af5ac940 100644 --- a/vendor/github.com/pion/webrtc/v3/datachannel.go +++ b/vendor/github.com/pion/webrtc/v3/datachannel.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -52,8 +49,6 @@ type DataChannel struct { onMessageHandler func(DataChannelMessage) openHandlerOnce sync.Once onOpenHandler func() - dialHandlerOnce sync.Once - onDialHandler func() onCloseHandler func() onBufferedAmountLow func() onErrorHandler func(error) @@ -70,7 +65,7 @@ type DataChannel struct { // This constructor is part of the ORTC API. It is not // meant to be used together with the basic WebRTC API. func (api *API) NewDataChannel(transport *SCTPTransport, params *DataChannelParameters) (*DataChannel, error) { - d, err := api.newDataChannel(params, nil, api.settingEngine.LoggerFactory.NewLogger("ortc")) + d, err := api.newDataChannel(params, api.settingEngine.LoggerFactory.NewLogger("ortc")) if err != nil { return nil, err } @@ -85,14 +80,13 @@ func (api *API) NewDataChannel(transport *SCTPTransport, params *DataChannelPara // newDataChannel is an internal constructor for the data channel used to // create the DataChannel object before the networking is set up. -func (api *API) newDataChannel(params *DataChannelParameters, sctpTransport *SCTPTransport, log logging.LeveledLogger) (*DataChannel, error) { +func (api *API) newDataChannel(params *DataChannelParameters, log logging.LeveledLogger) (*DataChannel, error) { // https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #5) if len(params.Label) > 65535 { return nil, &rtcerr.TypeError{Err: ErrStringSizeLimit} } d := &DataChannel{ - sctpTransport: sctpTransport, statsID: fmt.Sprintf("DataChannel-%d", time.Now().UnixNano()), label: params.Label, protocol: params.Protocol, @@ -181,7 +175,6 @@ func (d *DataChannel) open(sctpTransport *SCTPTransport) error { dc.OnBufferedAmountLow(d.onBufferedAmountLow) d.mu.Unlock() - d.onDial() d.handleOpen(dc, false, d.negotiated) return nil } @@ -235,30 +228,6 @@ func (d *DataChannel) onOpen() { } } -// OnDial sets an event handler which is invoked when the -// peer has been dialed, but before said peer has responsed -func (d *DataChannel) OnDial(f func()) { - d.mu.Lock() - d.dialHandlerOnce = sync.Once{} - d.onDialHandler = f - d.mu.Unlock() - - if d.ReadyState() == DataChannelStateOpen { - // If the data channel is already open, call the handler immediately. - go d.dialHandlerOnce.Do(f) - } -} - -func (d *DataChannel) onDial() { - d.mu.RLock() - handler := d.onDialHandler - d.mu.RUnlock() - - if handler != nil { - go d.dialHandlerOnce.Do(handler) - } -} - // OnClose sets an event handler which is invoked when // the underlying data transport has been closed. func (d *DataChannel) OnClose(f func()) { @@ -311,9 +280,6 @@ func (d *DataChannel) handleOpen(dc *datachannel.DataChannel, isRemote, isAlread // * remote datachannels should fire OnOpened. This isn't spec compliant, but we can't break behavior yet // * already negotiated datachannels should fire OnOpened if d.api.settingEngine.detach.DataChannels || isRemote || isAlreadyNegotiated { - // bufferedAmountLowThreshold and onBufferedAmountLow might be set earlier - d.dataChannel.SetBufferedAmountLowThreshold(d.bufferedAmountLowThreshold) - d.dataChannel.OnBufferedAmountLow(d.onBufferedAmountLow) d.onOpen() } else { dc.OnOpen(func() { @@ -355,12 +321,12 @@ var rlBufPool = sync.Pool{New: func() interface{} { func (d *DataChannel) readLoop() { for { - buffer := rlBufPool.Get().([]byte) //nolint:forcetypeassert + buffer := rlBufPool.Get().([]byte) n, isString, err := d.dataChannel.ReadDataChannel(buffer) if err != nil { rlBufPool.Put(buffer) // nolint:staticcheck d.setReadyState(DataChannelStateClosed) - if !errors.Is(err, io.EOF) { + if err != io.EOF { d.onError(err) } d.onClose() @@ -522,8 +488,8 @@ func (d *DataChannel) ID() *uint16 { // ReadyState represents the state of the DataChannel object. func (d *DataChannel) ReadyState() DataChannelState { - if v, ok := d.readyState.Load().(DataChannelState); ok { - return v + if v := d.readyState.Load(); v != nil { + return v.(DataChannelState) } return DataChannelState(0) } diff --git a/vendor/github.com/pion/webrtc/v3/datachannel_js.go b/vendor/github.com/pion/webrtc/v3/datachannel_js.go index a34ab6efd..55214b551 100644 --- a/vendor/github.com/pion/webrtc/v3/datachannel_js.go +++ b/vendor/github.com/pion/webrtc/v3/datachannel_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/datachannel_js_detach.go b/vendor/github.com/pion/webrtc/v3/datachannel_js_detach.go index 691e9d4c7..43186c5db 100644 --- a/vendor/github.com/pion/webrtc/v3/datachannel_js_detach.go +++ b/vendor/github.com/pion/webrtc/v3/datachannel_js_detach.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/datachannelinit.go b/vendor/github.com/pion/webrtc/v3/datachannelinit.go index b1775b7c5..a4320e463 100644 --- a/vendor/github.com/pion/webrtc/v3/datachannelinit.go +++ b/vendor/github.com/pion/webrtc/v3/datachannelinit.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // DataChannelInit can be used to configure properties of the underlying diff --git a/vendor/github.com/pion/webrtc/v3/datachannelmessage.go b/vendor/github.com/pion/webrtc/v3/datachannelmessage.go index ba12199f4..1e3c63b36 100644 --- a/vendor/github.com/pion/webrtc/v3/datachannelmessage.go +++ b/vendor/github.com/pion/webrtc/v3/datachannelmessage.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // DataChannelMessage represents a message received from the diff --git a/vendor/github.com/pion/webrtc/v3/datachannelparameters.go b/vendor/github.com/pion/webrtc/v3/datachannelparameters.go index 9b4f7efcc..d67a63b09 100644 --- a/vendor/github.com/pion/webrtc/v3/datachannelparameters.go +++ b/vendor/github.com/pion/webrtc/v3/datachannelparameters.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // DataChannelParameters describes the configuration of the DataChannel. diff --git a/vendor/github.com/pion/webrtc/v3/datachannelstate.go b/vendor/github.com/pion/webrtc/v3/datachannelstate.go index b2a85aaeb..a2c7b95de 100644 --- a/vendor/github.com/pion/webrtc/v3/datachannelstate.go +++ b/vendor/github.com/pion/webrtc/v3/datachannelstate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // DataChannelState indicates the state of a data channel. diff --git a/vendor/github.com/pion/webrtc/v3/dtlsfingerprint.go b/vendor/github.com/pion/webrtc/v3/dtlsfingerprint.go index b0d061481..db13d3ec6 100644 --- a/vendor/github.com/pion/webrtc/v3/dtlsfingerprint.go +++ b/vendor/github.com/pion/webrtc/v3/dtlsfingerprint.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // DTLSFingerprint specifies the hash function algorithm and certificate diff --git a/vendor/github.com/pion/webrtc/v3/dtlsparameters.go b/vendor/github.com/pion/webrtc/v3/dtlsparameters.go index 1dfa42a22..4b4b56836 100644 --- a/vendor/github.com/pion/webrtc/v3/dtlsparameters.go +++ b/vendor/github.com/pion/webrtc/v3/dtlsparameters.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // DTLSParameters holds information relating to DTLS configuration. diff --git a/vendor/github.com/pion/webrtc/v3/dtlsrole.go b/vendor/github.com/pion/webrtc/v3/dtlsrole.go index 9cee581d9..6e67f60e1 100644 --- a/vendor/github.com/pion/webrtc/v3/dtlsrole.go +++ b/vendor/github.com/pion/webrtc/v3/dtlsrole.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/dtlstransport.go b/vendor/github.com/pion/webrtc/v3/dtlstransport.go index df3472cf2..560eb4b84 100644 --- a/vendor/github.com/pion/webrtc/v3/dtlstransport.go +++ b/vendor/github.com/pion/webrtc/v3/dtlstransport.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -137,16 +134,18 @@ func (t *DTLSTransport) WriteRTCP(pkts []rtcp.Packet) (int, error) { srtcpSession, err := t.getSRTCPSession() if err != nil { - return 0, err + return 0, nil } writeStream, err := srtcpSession.OpenWriteStream() if err != nil { - // nolint return 0, fmt.Errorf("%w: %v", errPeerConnWriteRTCPOpenWriteStream, err) } - return writeStream.Write(raw) + if n, err := writeStream.Write(raw); err != nil { + return n, err + } + return 0, nil } // GetLocalParameters returns the DTLS parameters of the local DTLSTransport upon construction. @@ -213,19 +212,16 @@ func (t *DTLSTransport) startSRTP() error { connState := t.conn.ConnectionState() err := srtpConfig.ExtractSessionKeysFromDTLS(&connState, t.role() == DTLSRoleClient) if err != nil { - // nolint return fmt.Errorf("%w: %v", errDtlsKeyExtractionFailed, err) } srtpSession, err := srtp.NewSessionSRTP(t.srtpEndpoint, srtpConfig) if err != nil { - // nolint return fmt.Errorf("%w: %v", errFailedToStartSRTP, err) } srtcpSession, err := srtp.NewSessionSRTCP(t.srtcpEndpoint, srtpConfig) if err != nil { - // nolint return fmt.Errorf("%w: %v", errFailedToStartSRTCP, err) } @@ -236,16 +232,16 @@ func (t *DTLSTransport) startSRTP() error { } func (t *DTLSTransport) getSRTPSession() (*srtp.SessionSRTP, error) { - if value, ok := t.srtpSession.Load().(*srtp.SessionSRTP); ok { - return value, nil + if value := t.srtpSession.Load(); value != nil { + return value.(*srtp.SessionSRTP), nil } return nil, errDtlsTransportNotStarted } func (t *DTLSTransport) getSRTCPSession() (*srtp.SessionSRTCP, error) { - if value, ok := t.srtcpSession.Load().(*srtp.SessionSRTCP); ok { - return value, nil + if value := t.srtcpSession.Load(); value != nil { + return value.(*srtp.SessionSRTCP), nil } return nil, errDtlsTransportNotStarted @@ -316,7 +312,7 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error { }(), ClientAuth: dtls.RequireAnyClientCert, LoggerFactory: t.api.settingEngine.LoggerFactory, - InsecureSkipVerify: !t.api.settingEngine.dtls.disableInsecureSkipVerify, + InsecureSkipVerify: true, }, nil } @@ -331,18 +327,10 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error { dtlsConfig.ReplayProtectionWindow = int(*t.api.settingEngine.replayProtection.DTLS) } - if t.api.settingEngine.dtls.clientAuth != nil { - dtlsConfig.ClientAuth = *t.api.settingEngine.dtls.clientAuth + if t.api.settingEngine.dtls.retransmissionInterval != 0 { + dtlsConfig.FlightInterval = t.api.settingEngine.dtls.retransmissionInterval } - dtlsConfig.FlightInterval = t.api.settingEngine.dtls.retransmissionInterval - dtlsConfig.InsecureSkipVerifyHello = t.api.settingEngine.dtls.insecureSkipHelloVerify - dtlsConfig.EllipticCurves = t.api.settingEngine.dtls.ellipticCurves - dtlsConfig.ConnectContextMaker = t.api.settingEngine.dtls.connectContextMaker - dtlsConfig.ExtendedMasterSecret = t.api.settingEngine.dtls.extendedMasterSecret - dtlsConfig.ClientCAs = t.api.settingEngine.dtls.clientCAs - dtlsConfig.RootCAs = t.api.settingEngine.dtls.rootCAs - // Connect as DTLS Client/Server, function is blocking and we // must not hold the DTLSTransport lock if role == DTLSRoleClient { @@ -369,8 +357,6 @@ func (t *DTLSTransport) Start(remoteParameters DTLSParameters) error { switch srtpProfile { case dtls.SRTP_AEAD_AES_128_GCM: t.srtpProtectionProfile = srtp.ProtectionProfileAeadAes128Gcm - case dtls.SRTP_AEAD_AES_256_GCM: - t.srtpProtectionProfile = srtp.ProtectionProfileAeadAes256Gcm case dtls.SRTP_AES128_CM_HMAC_SHA1_80: t.srtpProtectionProfile = srtp.ProtectionProfileAes128CmHmacSha1_80 default: @@ -421,12 +407,12 @@ func (t *DTLSTransport) Stop() error { // Try closing everything and collect the errors var closeErrs []error - if srtpSession, err := t.getSRTPSession(); err == nil && srtpSession != nil { - closeErrs = append(closeErrs, srtpSession.Close()) + if srtpSessionValue := t.srtpSession.Load(); srtpSessionValue != nil { + closeErrs = append(closeErrs, srtpSessionValue.(*srtp.SessionSRTP).Close()) } - if srtcpSession, err := t.getSRTCPSession(); err == nil && srtcpSession != nil { - closeErrs = append(closeErrs, srtcpSession.Close()) + if srtcpSessionValue := t.srtcpSession.Load(); srtcpSessionValue != nil { + closeErrs = append(closeErrs, srtcpSessionValue.(*srtp.SessionSRTCP).Close()) } for i := range t.simulcastStreams { diff --git a/vendor/github.com/pion/webrtc/v3/dtlstransport_js.go b/vendor/github.com/pion/webrtc/v3/dtlstransport_js.go index bc3444e56..d4d8611ef 100644 --- a/vendor/github.com/pion/webrtc/v3/dtlstransport_js.go +++ b/vendor/github.com/pion/webrtc/v3/dtlstransport_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/dtlstransportstate.go b/vendor/github.com/pion/webrtc/v3/dtlstransportstate.go index f986e22cb..900b50b75 100644 --- a/vendor/github.com/pion/webrtc/v3/dtlstransportstate.go +++ b/vendor/github.com/pion/webrtc/v3/dtlstransportstate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // DTLSTransportState indicates the DTLS transport establishment state. diff --git a/vendor/github.com/pion/webrtc/v3/errors.go b/vendor/github.com/pion/webrtc/v3/errors.go index 009e91dd6..a28389f58 100644 --- a/vendor/github.com/pion/webrtc/v3/errors.go +++ b/vendor/github.com/pion/webrtc/v3/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( @@ -145,9 +142,6 @@ var ( // ErrRTPSenderNewTrackHasIncorrectKind indicates that the new track is of a different kind than the previous/original ErrRTPSenderNewTrackHasIncorrectKind = errors.New("new track must be of the same kind as previous") - // ErrRTPSenderNewTrackHasIncorrectEnvelope indicates that the new track has a different envelope than the previous/original - ErrRTPSenderNewTrackHasIncorrectEnvelope = errors.New("new track must have the same envelope as previous") - // ErrUnbindFailed indicates that a TrackLocal was not able to be unbind ErrUnbindFailed = errors.New("failed to unbind TrackLocal from PeerConnection") @@ -208,16 +202,10 @@ var ( errRTPReceiverWithSSRCTrackStreamNotFound = errors.New("unable to find stream for Track with SSRC") errRTPReceiverForRIDTrackStreamNotFound = errors.New("no trackStreams found for RID") - errRTPSenderTrackNil = errors.New("Track must not be nil") - errRTPSenderDTLSTransportNil = errors.New("DTLSTransport must not be nil") - errRTPSenderSendAlreadyCalled = errors.New("Send has already been called") - errRTPSenderStopped = errors.New("Sender has already been stopped") - errRTPSenderTrackRemoved = errors.New("Sender Track has been removed or replaced to nil") - errRTPSenderRidNil = errors.New("Sender cannot add encoding as rid is empty") - errRTPSenderNoBaseEncoding = errors.New("Sender cannot add encoding as there is no base track") - errRTPSenderBaseEncodingMismatch = errors.New("Sender cannot add encoding as provided track does not match base track") - errRTPSenderRIDCollision = errors.New("Sender cannot encoding due to RID collision") - errRTPSenderNoTrackForRID = errors.New("Sender does not have track for RID") + errRTPSenderTrackNil = errors.New("Track must not be nil") + errRTPSenderDTLSTransportNil = errors.New("DTLSTransport must not be nil") + errRTPSenderSendAlreadyCalled = errors.New("Send has already been called") + errRTPSenderTrackRemoved = errors.New("Sender Track has been removed or replaced to nil") errRTPTransceiverCannotChangeMid = errors.New("errRTPSenderTrackNil") errRTPTransceiverSetSendingInvalidState = errors.New("invalid state change in RTPTransceiver.setSending") @@ -236,9 +224,6 @@ var ( errStatsICECandidateStateInvalid = errors.New("cannot convert to StatsICECandidatePairStateSucceeded invalid ice candidate state") - errInvalidICECredentialTypeString = errors.New("invalid ICECredentialType") - errInvalidICEServer = errors.New("invalid ICEServer") - errICETransportNotInNew = errors.New("ICETransport can only be called in ICETransportStateNew") errCertificatePEMFormatError = errors.New("bad Certificate PEM format") diff --git a/vendor/github.com/pion/webrtc/v3/gathering_complete_promise.go b/vendor/github.com/pion/webrtc/v3/gathering_complete_promise.go index 12d3170d6..a4d52f943 100644 --- a/vendor/github.com/pion/webrtc/v3/gathering_complete_promise.go +++ b/vendor/github.com/pion/webrtc/v3/gathering_complete_promise.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/ice_go.go b/vendor/github.com/pion/webrtc/v3/ice_go.go index 9adcefbb6..992cd9cb4 100644 --- a/vendor/github.com/pion/webrtc/v3/ice_go.go +++ b/vendor/github.com/pion/webrtc/v3/ice_go.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js diff --git a/vendor/github.com/pion/webrtc/v3/icecandidate.go b/vendor/github.com/pion/webrtc/v3/icecandidate.go index fa0b68093..1b0fbfcdb 100644 --- a/vendor/github.com/pion/webrtc/v3/icecandidate.go +++ b/vendor/github.com/pion/webrtc/v3/icecandidate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/icecandidateinit.go b/vendor/github.com/pion/webrtc/v3/icecandidateinit.go index 30ad93c0b..31ebb4ba7 100644 --- a/vendor/github.com/pion/webrtc/v3/icecandidateinit.go +++ b/vendor/github.com/pion/webrtc/v3/icecandidateinit.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // ICECandidateInit is used to serialize ice candidates diff --git a/vendor/github.com/pion/webrtc/v3/icecandidatepair.go b/vendor/github.com/pion/webrtc/v3/icecandidatepair.go index b87884bce..7350fbe59 100644 --- a/vendor/github.com/pion/webrtc/v3/icecandidatepair.go +++ b/vendor/github.com/pion/webrtc/v3/icecandidatepair.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import "fmt" diff --git a/vendor/github.com/pion/webrtc/v3/icecandidatetype.go b/vendor/github.com/pion/webrtc/v3/icecandidatetype.go index a274c45db..e57bf14af 100644 --- a/vendor/github.com/pion/webrtc/v3/icecandidatetype.go +++ b/vendor/github.com/pion/webrtc/v3/icecandidatetype.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/icecomponent.go b/vendor/github.com/pion/webrtc/v3/icecomponent.go index c65a893dc..1f03ec5b0 100644 --- a/vendor/github.com/pion/webrtc/v3/icecomponent.go +++ b/vendor/github.com/pion/webrtc/v3/icecomponent.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // ICEComponent describes if the ice transport is used for RTP diff --git a/vendor/github.com/pion/webrtc/v3/iceconnectionstate.go b/vendor/github.com/pion/webrtc/v3/iceconnectionstate.go index e52e1328a..22fd26975 100644 --- a/vendor/github.com/pion/webrtc/v3/iceconnectionstate.go +++ b/vendor/github.com/pion/webrtc/v3/iceconnectionstate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // ICEConnectionState indicates signaling state of the ICE Connection. diff --git a/vendor/github.com/pion/webrtc/v3/icecredentialtype.go b/vendor/github.com/pion/webrtc/v3/icecredentialtype.go index 5d704a9bd..3967c16da 100644 --- a/vendor/github.com/pion/webrtc/v3/icecredentialtype.go +++ b/vendor/github.com/pion/webrtc/v3/icecredentialtype.go @@ -1,13 +1,5 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc -import ( - "encoding/json" - "fmt" -) - // ICECredentialType indicates the type of credentials used to connect to // an ICE server. type ICECredentialType int @@ -28,14 +20,14 @@ const ( iceCredentialTypeOauthStr = "oauth" ) -func newICECredentialType(raw string) (ICECredentialType, error) { +func newICECredentialType(raw string) ICECredentialType { switch raw { case iceCredentialTypePasswordStr: - return ICECredentialTypePassword, nil + return ICECredentialTypePassword case iceCredentialTypeOauthStr: - return ICECredentialTypeOauth, nil + return ICECredentialTypeOauth default: - return ICECredentialTypePassword, errInvalidICECredentialTypeString + return ICECredentialType(Unknown) } } @@ -49,24 +41,3 @@ func (t ICECredentialType) String() string { return ErrUnknownType.Error() } } - -// UnmarshalJSON parses the JSON-encoded data and stores the result -func (t *ICECredentialType) UnmarshalJSON(b []byte) error { - var val string - if err := json.Unmarshal(b, &val); err != nil { - return err - } - - tmp, err := newICECredentialType(val) - if err != nil { - return fmt.Errorf("%w: (%s)", err, val) - } - - *t = tmp - return nil -} - -// MarshalJSON returns the JSON encoding -func (t ICECredentialType) MarshalJSON() ([]byte, error) { - return json.Marshal(t.String()) -} diff --git a/vendor/github.com/pion/webrtc/v3/icegatherer.go b/vendor/github.com/pion/webrtc/v3/icegatherer.go index cf12b4206..c3a054080 100644 --- a/vendor/github.com/pion/webrtc/v3/icegatherer.go +++ b/vendor/github.com/pion/webrtc/v3/icegatherer.go @@ -1,19 +1,14 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js package webrtc import ( - "fmt" "sync" "sync/atomic" "github.com/pion/ice/v2" "github.com/pion/logging" - "github.com/pion/stun" ) // ICEGatherer gathers local host, server reflexive and relay @@ -25,7 +20,7 @@ type ICEGatherer struct { log logging.LeveledLogger state ICEGathererState - validatedServers []*stun.URI + validatedServers []*ice.URL gatherPolicy ICETransportPolicy agent *ice.Agent @@ -43,7 +38,7 @@ type ICEGatherer struct { // This constructor is part of the ORTC API. It is not // meant to be used together with the basic WebRTC API. func (api *API) NewICEGatherer(opts ICEGatherOptions) (*ICEGatherer, error) { - var validatedServers []*stun.URI + var validatedServers []*ice.URL if len(opts.ICEServers) > 0 { for _, server := range opts.ICEServers { url, err := server.urls() @@ -109,11 +104,9 @@ func (g *ICEGatherer) createAgent() error { PrflxAcceptanceMinWait: g.api.settingEngine.timeout.ICEPrflxAcceptanceMinWait, RelayAcceptanceMinWait: g.api.settingEngine.timeout.ICERelayAcceptanceMinWait, InterfaceFilter: g.api.settingEngine.candidates.InterfaceFilter, - IPFilter: g.api.settingEngine.candidates.IPFilter, NAT1To1IPs: g.api.settingEngine.candidates.NAT1To1IPs, NAT1To1IPCandidateType: nat1To1CandiTyp, - IncludeLoopback: g.api.settingEngine.candidates.IncludeLoopbackCandidate, - Net: g.api.settingEngine.net, + Net: g.api.settingEngine.vnet, MulticastDNSMode: mDNSMode, MulticastDNSHostName: g.api.settingEngine.candidates.MulticastDNSHostName, LocalUfrag: g.api.settingEngine.candidates.UsernameFragment, @@ -147,11 +140,9 @@ func (g *ICEGatherer) Gather() error { return err } - agent := g.getAgent() - // it is possible agent had just been closed - if agent == nil { - return fmt.Errorf("%w: unable to gather", errICEAgentNotExist) - } + g.lock.Lock() + agent := g.agent + g.lock.Unlock() g.setState(ICEGathererStateGathering) if err := agent.OnCandidate(func(candidate ice.Candidate) { @@ -207,13 +198,7 @@ func (g *ICEGatherer) GetLocalParameters() (ICEParameters, error) { return ICEParameters{}, err } - agent := g.getAgent() - // it is possible agent had just been closed - if agent == nil { - return ICEParameters{}, fmt.Errorf("%w: unable to get local parameters", errICEAgentNotExist) - } - - frag, pwd, err := agent.GetLocalUserCredentials() + frag, pwd, err := g.agent.GetLocalUserCredentials() if err != nil { return ICEParameters{}, err } @@ -230,14 +215,7 @@ func (g *ICEGatherer) GetLocalCandidates() ([]ICECandidate, error) { if err := g.createAgent(); err != nil { return nil, err } - - agent := g.getAgent() - // it is possible agent had just been closed - if agent == nil { - return nil, fmt.Errorf("%w: unable to get local candidates", errICEAgentNotExist) - } - - iceCandidates, err := agent.GetLocalCandidates() + iceCandidates, err := g.agent.GetLocalCandidates() if err != nil { return nil, err } @@ -246,7 +224,7 @@ func (g *ICEGatherer) GetLocalCandidates() ([]ICECandidate, error) { } // OnLocalCandidate sets an event handler which fires when a new local ICE candidate is available -// Take note that the handler will be called with a nil pointer when gathering is finished. +// Take note that the handler is gonna be called with a nil pointer when gathering is finished. func (g *ICEGatherer) OnLocalCandidate(f func(*ICECandidate)) { g.onLocalCandidateHandler.Store(f) } diff --git a/vendor/github.com/pion/webrtc/v3/icegathererstate.go b/vendor/github.com/pion/webrtc/v3/icegathererstate.go index b90acd33e..80dc77a2d 100644 --- a/vendor/github.com/pion/webrtc/v3/icegathererstate.go +++ b/vendor/github.com/pion/webrtc/v3/icegathererstate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/icegatheringstate.go b/vendor/github.com/pion/webrtc/v3/icegatheringstate.go index 1925dddbf..21361f912 100644 --- a/vendor/github.com/pion/webrtc/v3/icegatheringstate.go +++ b/vendor/github.com/pion/webrtc/v3/icegatheringstate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // ICEGatheringState describes the state of the candidate gathering process. diff --git a/vendor/github.com/pion/webrtc/v3/icegatheroptions.go b/vendor/github.com/pion/webrtc/v3/icegatheroptions.go index cca356fc7..88421c74e 100644 --- a/vendor/github.com/pion/webrtc/v3/icegatheroptions.go +++ b/vendor/github.com/pion/webrtc/v3/icegatheroptions.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // ICEGatherOptions provides options relating to the gathering of ICE candidates. diff --git a/vendor/github.com/pion/webrtc/v3/icemux.go b/vendor/github.com/pion/webrtc/v3/icemux.go index 1bae31310..8291a6c8b 100644 --- a/vendor/github.com/pion/webrtc/v3/icemux.go +++ b/vendor/github.com/pion/webrtc/v3/icemux.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/iceparameters.go b/vendor/github.com/pion/webrtc/v3/iceparameters.go index 459ec6007..0c03a88bf 100644 --- a/vendor/github.com/pion/webrtc/v3/iceparameters.go +++ b/vendor/github.com/pion/webrtc/v3/iceparameters.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // ICEParameters includes the ICE username fragment diff --git a/vendor/github.com/pion/webrtc/v3/iceprotocol.go b/vendor/github.com/pion/webrtc/v3/iceprotocol.go index 3582b6830..f9eb0cfab 100644 --- a/vendor/github.com/pion/webrtc/v3/iceprotocol.go +++ b/vendor/github.com/pion/webrtc/v3/iceprotocol.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/icerole.go b/vendor/github.com/pion/webrtc/v3/icerole.go index 99268bace..11187863b 100644 --- a/vendor/github.com/pion/webrtc/v3/icerole.go +++ b/vendor/github.com/pion/webrtc/v3/icerole.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // ICERole describes the role ice.Agent is playing in selecting the diff --git a/vendor/github.com/pion/webrtc/v3/iceserver.go b/vendor/github.com/pion/webrtc/v3/iceserver.go index 35d231fd5..b83a9e8b3 100644 --- a/vendor/github.com/pion/webrtc/v3/iceserver.go +++ b/vendor/github.com/pion/webrtc/v3/iceserver.go @@ -1,15 +1,10 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js package webrtc import ( - "encoding/json" - - "github.com/pion/stun" + "github.com/pion/ice/v2" "github.com/pion/webrtc/v3/pkg/rtcerr" ) @@ -22,8 +17,8 @@ type ICEServer struct { CredentialType ICECredentialType `json:"credentialType,omitempty"` } -func (s ICEServer) parseURL(i int) (*stun.URI, error) { - return stun.ParseURI(s.URLs[i]) +func (s ICEServer) parseURL(i int) (*ice.URL, error) { + return ice.ParseURL(s.URLs[i]) } func (s ICEServer) validate() error { @@ -31,8 +26,8 @@ func (s ICEServer) validate() error { return err } -func (s ICEServer) urls() ([]*stun.URI, error) { - urls := []*stun.URI{} +func (s ICEServer) urls() ([]*ice.URL, error) { + urls := []*ice.URL{} for i := range s.URLs { url, err := s.parseURL(i) @@ -40,7 +35,7 @@ func (s ICEServer) urls() ([]*stun.URI, error) { return nil, &rtcerr.InvalidAccessError{Err: err} } - if url.Scheme == stun.SchemeTypeTURN || url.Scheme == stun.SchemeTypeTURNS { + if url.Scheme == ice.SchemeTypeTURN || url.Scheme == ice.SchemeTypeTURNS { // https://www.w3.org/TR/webrtc/#set-the-configuration (step #11.3.2) if s.Username == "" || s.Credential == nil { return nil, &rtcerr.InvalidAccessError{Err: ErrNoTurnCredentials} @@ -72,111 +67,3 @@ func (s ICEServer) urls() ([]*stun.URI, error) { return urls, nil } - -func iceserverUnmarshalUrls(val interface{}) (*[]string, error) { - s, ok := val.([]interface{}) - if !ok { - return nil, errInvalidICEServer - } - out := make([]string, len(s)) - for idx, url := range s { - out[idx], ok = url.(string) - if !ok { - return nil, errInvalidICEServer - } - } - return &out, nil -} - -func iceserverUnmarshalOauth(val interface{}) (*OAuthCredential, error) { - c, ok := val.(map[string]interface{}) - if !ok { - return nil, errInvalidICEServer - } - MACKey, ok := c["MACKey"].(string) - if !ok { - return nil, errInvalidICEServer - } - AccessToken, ok := c["AccessToken"].(string) - if !ok { - return nil, errInvalidICEServer - } - return &OAuthCredential{ - MACKey: MACKey, - AccessToken: AccessToken, - }, nil -} - -func (s *ICEServer) iceserverUnmarshalFields(m map[string]interface{}) error { - if val, ok := m["urls"]; ok { - u, err := iceserverUnmarshalUrls(val) - if err != nil { - return err - } - s.URLs = *u - } else { - s.URLs = []string{} - } - - if val, ok := m["username"]; ok { - s.Username, ok = val.(string) - if !ok { - return errInvalidICEServer - } - } - if val, ok := m["credentialType"]; ok { - ct, ok := val.(string) - if !ok { - return errInvalidICEServer - } - tpe, err := newICECredentialType(ct) - if err != nil { - return err - } - s.CredentialType = tpe - } else { - s.CredentialType = ICECredentialTypePassword - } - if val, ok := m["credential"]; ok { - switch s.CredentialType { - case ICECredentialTypePassword: - s.Credential = val - case ICECredentialTypeOauth: - c, err := iceserverUnmarshalOauth(val) - if err != nil { - return err - } - s.Credential = *c - default: - return errInvalidICECredentialTypeString - } - } - return nil -} - -// UnmarshalJSON parses the JSON-encoded data and stores the result -func (s *ICEServer) UnmarshalJSON(b []byte) error { - var tmp interface{} - err := json.Unmarshal(b, &tmp) - if err != nil { - return err - } - if m, ok := tmp.(map[string]interface{}); ok { - return s.iceserverUnmarshalFields(m) - } - return errInvalidICEServer -} - -// MarshalJSON returns the JSON encoding -func (s ICEServer) MarshalJSON() ([]byte, error) { - m := make(map[string]interface{}) - m["urls"] = s.URLs - if s.Username != "" { - m["username"] = s.Username - } - if s.Credential != nil { - m["credential"] = s.Credential - } - m["credentialType"] = s.CredentialType - return json.Marshal(m) -} diff --git a/vendor/github.com/pion/webrtc/v3/iceserver_js.go b/vendor/github.com/pion/webrtc/v3/iceserver_js.go index e4061fa5f..3f4f9c3a9 100644 --- a/vendor/github.com/pion/webrtc/v3/iceserver_js.go +++ b/vendor/github.com/pion/webrtc/v3/iceserver_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/icetransport.go b/vendor/github.com/pion/webrtc/v3/icetransport.go index f3b6925c8..31cc4c9a5 100644 --- a/vendor/github.com/pion/webrtc/v3/icetransport.go +++ b/vendor/github.com/pion/webrtc/v3/icetransport.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -25,9 +22,8 @@ type ICETransport struct { role ICERole - onConnectionStateChangeHandler atomic.Value // func(ICETransportState) - internalOnConnectionStateChangeHandler atomic.Value // func(ICETransportState) - onSelectedCandidatePairChangeHandler atomic.Value // func(*ICECandidatePair) + onConnectionStateChangeHandler atomic.Value // func(ICETransportState) + onSelectedCandidatePairChangeHandler atomic.Value // func(*ICECandidatePair) state atomic.Value // ICETransportState @@ -48,7 +44,7 @@ type ICETransport struct { func (t *ICETransport) GetSelectedCandidatePair() (*ICECandidatePair, error) { agent := t.gatherer.getAgent() if agent == nil { - return nil, nil //nolint:nilnil + return nil, nil } icePair, err := agent.GetSelectedCandidatePair() @@ -211,8 +207,9 @@ func (t *ICETransport) OnSelectedCandidatePairChange(f func(*ICECandidatePair)) } func (t *ICETransport) onSelectedCandidatePairChange(pair *ICECandidatePair) { - if handler, ok := t.onSelectedCandidatePairChangeHandler.Load().(func(*ICECandidatePair)); ok { - handler(pair) + handler := t.onSelectedCandidatePairChangeHandler.Load() + if handler != nil { + handler.(func(*ICECandidatePair))(pair) } } @@ -223,11 +220,9 @@ func (t *ICETransport) OnConnectionStateChange(f func(ICETransportState)) { } func (t *ICETransport) onConnectionStateChange(state ICETransportState) { - if handler, ok := t.onConnectionStateChangeHandler.Load().(func(ICETransportState)); ok { - handler(state) - } - if handler, ok := t.internalOnConnectionStateChangeHandler.Load().(func(ICETransportState)); ok { - handler(state) + handler := t.onConnectionStateChangeHandler.Load() + if handler != nil { + handler.(func(ICETransportState))(state) } } @@ -297,8 +292,8 @@ func (t *ICETransport) AddRemoteCandidate(remoteCandidate *ICECandidate) error { // State returns the current ice transport state. func (t *ICETransport) State() ICETransportState { - if v, ok := t.state.Load().(ICETransportState); ok { - return v + if v := t.state.Load(); v != nil { + return v.(ICETransportState) } return ICETransportState(0) } diff --git a/vendor/github.com/pion/webrtc/v3/icetransport_js.go b/vendor/github.com/pion/webrtc/v3/icetransport_js.go index 3ca577b10..095f354bb 100644 --- a/vendor/github.com/pion/webrtc/v3/icetransport_js.go +++ b/vendor/github.com/pion/webrtc/v3/icetransport_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/icetransportpolicy.go b/vendor/github.com/pion/webrtc/v3/icetransportpolicy.go index a2629fdab..16273f569 100644 --- a/vendor/github.com/pion/webrtc/v3/icetransportpolicy.go +++ b/vendor/github.com/pion/webrtc/v3/icetransportpolicy.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/icetransportstate.go b/vendor/github.com/pion/webrtc/v3/icetransportstate.go index 4edbf0f47..da93e44d4 100644 --- a/vendor/github.com/pion/webrtc/v3/icetransportstate.go +++ b/vendor/github.com/pion/webrtc/v3/icetransportstate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import "github.com/pion/ice/v2" diff --git a/vendor/github.com/pion/webrtc/v3/interceptor.go b/vendor/github.com/pion/webrtc/v3/interceptor.go index 85232f35d..e93fc7666 100644 --- a/vendor/github.com/pion/webrtc/v3/interceptor.go +++ b/vendor/github.com/pion/webrtc/v3/interceptor.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -29,7 +26,11 @@ func RegisterDefaultInterceptors(mediaEngine *MediaEngine, interceptorRegistry * return err } - return ConfigureTWCCSender(mediaEngine, interceptorRegistry) + if err := ConfigureTWCCSender(mediaEngine, interceptorRegistry); err != nil { + return err + } + + return nil } // ConfigureRTCPReports will setup everything necessary for generating Sender and Receiver Reports diff --git a/vendor/github.com/pion/webrtc/v3/internal/fmtp/fmtp.go b/vendor/github.com/pion/webrtc/v3/internal/fmtp/fmtp.go index 5461c019b..86057594a 100644 --- a/vendor/github.com/pion/webrtc/v3/internal/fmtp/fmtp.go +++ b/vendor/github.com/pion/webrtc/v3/internal/fmtp/fmtp.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package fmtp implements per codec parsing of fmtp lines package fmtp @@ -70,7 +67,7 @@ func (g *genericFMTP) Match(b FMTP) bool { return false } - if !strings.EqualFold(g.mimeType, c.MimeType()) { + if g.mimeType != c.MimeType() { return false } diff --git a/vendor/github.com/pion/webrtc/v3/internal/fmtp/h264.go b/vendor/github.com/pion/webrtc/v3/internal/fmtp/h264.go index b89b97aa2..5a79b9e64 100644 --- a/vendor/github.com/pion/webrtc/v3/internal/fmtp/h264.go +++ b/vendor/github.com/pion/webrtc/v3/internal/fmtp/h264.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package fmtp import ( @@ -29,17 +26,16 @@ func (h *h264FMTP) MimeType() string { // Match returns true if h and b are compatible fmtp descriptions // Based on RFC6184 Section 8.2.2: -// -// The parameters identifying a media format configuration for H.264 -// are profile-level-id and packetization-mode. These media format -// configuration parameters (except for the level part of profile- -// level-id) MUST be used symmetrically; that is, the answerer MUST -// either maintain all configuration parameters or remove the media -// format (payload type) completely if one or more of the parameter -// values are not supported. -// Informative note: The requirement for symmetric use does not -// apply for the level part of profile-level-id and does not apply -// for the other stream properties and capability parameters. +// The parameters identifying a media format configuration for H.264 +// are profile-level-id and packetization-mode. These media format +// configuration parameters (except for the level part of profile- +// level-id) MUST be used symmetrically; that is, the answerer MUST +// either maintain all configuration parameters or remove the media +// format (payload type) completely if one or more of the parameter +// values are not supported. +// Informative note: The requirement for symmetric use does not +// apply for the level part of profile-level-id and does not apply +// for the other stream properties and capability parameters. func (h *h264FMTP) Match(b FMTP) bool { c, ok := b.(*h264FMTP) if !ok { diff --git a/vendor/github.com/pion/webrtc/v3/internal/mux/endpoint.go b/vendor/github.com/pion/webrtc/v3/internal/mux/endpoint.go index 3f53d16c5..afccc0778 100644 --- a/vendor/github.com/pion/webrtc/v3/internal/mux/endpoint.go +++ b/vendor/github.com/pion/webrtc/v3/internal/mux/endpoint.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package mux import ( @@ -10,7 +7,7 @@ import ( "time" "github.com/pion/ice/v2" - "github.com/pion/transport/v2/packetio" + "github.com/pion/transport/packetio" ) // Endpoint implements net.Conn. It is used to read muxed packets. @@ -63,16 +60,16 @@ func (e *Endpoint) RemoteAddr() net.Addr { } // SetDeadline is a stub -func (e *Endpoint) SetDeadline(time.Time) error { +func (e *Endpoint) SetDeadline(t time.Time) error { return nil } // SetReadDeadline is a stub -func (e *Endpoint) SetReadDeadline(time.Time) error { +func (e *Endpoint) SetReadDeadline(t time.Time) error { return nil } // SetWriteDeadline is a stub -func (e *Endpoint) SetWriteDeadline(time.Time) error { +func (e *Endpoint) SetWriteDeadline(t time.Time) error { return nil } diff --git a/vendor/github.com/pion/webrtc/v3/internal/mux/mux.go b/vendor/github.com/pion/webrtc/v3/internal/mux/mux.go index 1e167b897..00bf6ac24 100644 --- a/vendor/github.com/pion/webrtc/v3/internal/mux/mux.go +++ b/vendor/github.com/pion/webrtc/v3/internal/mux/mux.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package mux multiplexes packets on a single socket (RFC7983) package mux @@ -12,7 +9,7 @@ import ( "github.com/pion/ice/v2" "github.com/pion/logging" - "github.com/pion/transport/v2/packetio" + "github.com/pion/transport/packetio" ) // The maximum amount of data that can be buffered before returning errors. @@ -60,6 +57,8 @@ func (m *Mux) NewEndpoint(f MatchFunc) *Endpoint { } // Set a maximum size of the buffer in bytes. + // NOTE: We actually won't get anywhere close to this limit. + // SRTP will constantly read from the endpoint and drop packets if it's full. e.buffer.SetLimitSize(maxBufferSize) m.lock.Lock() @@ -80,8 +79,8 @@ func (m *Mux) RemoveEndpoint(e *Endpoint) { func (m *Mux) Close() error { m.lock.Lock() for e := range m.endpoints { - if err := e.close(); err != nil { - m.lock.Unlock() + err := e.close() + if err != nil { return err } @@ -112,15 +111,15 @@ func (m *Mux) readLoop() { case errors.Is(err, io.EOF), errors.Is(err, ice.ErrClosed): return case errors.Is(err, io.ErrShortBuffer), errors.Is(err, packetio.ErrTimeout): - m.log.Errorf("mux: failed to read from packetio.Buffer %s", err.Error()) + m.log.Errorf("mux: failed to read from packetio.Buffer %s\n", err.Error()) continue case err != nil: - m.log.Errorf("mux: ending readLoop packetio.Buffer error %s", err.Error()) + m.log.Errorf("mux: ending readLoop packetio.Buffer error %s\n", err.Error()) return } if err = m.dispatch(buf[:n]); err != nil { - m.log.Errorf("mux: ending readLoop dispatch error %s", err.Error()) + m.log.Errorf("mux: ending readLoop dispatch error %s\n", err.Error()) return } } @@ -140,7 +139,7 @@ func (m *Mux) dispatch(buf []byte) error { if endpoint == nil { if len(buf) > 0 { - m.log.Warnf("Warning: mux: no endpoint for packet starting with %d", buf[0]) + m.log.Warnf("Warning: mux: no endpoint for packet starting with %d\n", buf[0]) } else { m.log.Warnf("Warning: mux: no endpoint for zero length packet") } @@ -148,12 +147,9 @@ func (m *Mux) dispatch(buf []byte) error { } _, err := endpoint.buffer.Write(buf) - - // Expected when bytes are received faster than the endpoint can process them (#2152, #2180) - if errors.Is(err, packetio.ErrFull) { - m.log.Infof("mux: endpoint buffer is full, dropping packet") - return nil + if err != nil { + return err } - return err + return nil } diff --git a/vendor/github.com/pion/webrtc/v3/internal/mux/muxfunc.go b/vendor/github.com/pion/webrtc/v3/internal/mux/muxfunc.go index 69c3d14cd..fc8efc948 100644 --- a/vendor/github.com/pion/webrtc/v3/internal/mux/muxfunc.go +++ b/vendor/github.com/pion/webrtc/v3/internal/mux/muxfunc.go @@ -1,13 +1,10 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package mux // MatchFunc allows custom logic for mapping packets to an Endpoint type MatchFunc func([]byte) bool // MatchAll always returns true -func MatchAll([]byte) bool { +func MatchAll(b []byte) bool { return true } diff --git a/vendor/github.com/pion/webrtc/v3/internal/util/util.go b/vendor/github.com/pion/webrtc/v3/internal/util/util.go index 3f43c123e..6e12b6410 100644 --- a/vendor/github.com/pion/webrtc/v3/internal/util/util.go +++ b/vendor/github.com/pion/webrtc/v3/internal/util/util.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package util provides auxiliary functions internally used in webrtc package package util @@ -42,7 +39,7 @@ func FlattenErrs(errs []error) error { return multiError(errs2) } -type multiError []error //nolint:errname +type multiError []error func (me multiError) Error() string { var errstrings []string @@ -65,7 +62,7 @@ func (me multiError) Is(err error) bool { if errors.Is(e, err) { return true } - if me2, ok := e.(multiError); ok { //nolint:errorlint + if me2, ok := e.(multiError); ok { if me2.Is(err) { return true } diff --git a/vendor/github.com/pion/webrtc/v3/js_utils.go b/vendor/github.com/pion/webrtc/v3/js_utils.go index 7e7b5e190..7e40da9a6 100644 --- a/vendor/github.com/pion/webrtc/v3/js_utils.go +++ b/vendor/github.com/pion/webrtc/v3/js_utils.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/mediaengine.go b/vendor/github.com/pion/webrtc/v3/mediaengine.go index c824d1ed4..bdab6b9fb 100644 --- a/vendor/github.com/pion/webrtc/v3/mediaengine.go +++ b/vendor/github.com/pion/webrtc/v3/mediaengine.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -58,7 +55,8 @@ type mediaEngineHeaderExtension struct { } // A MediaEngine defines the codecs supported by a PeerConnection, and the -// configuration of those codecs. +// configuration of those codecs. A MediaEngine must not be shared between +// PeerConnections. type MediaEngine struct { // If we have attempted to negotiate a codec type yet. negotiatedVideo, negotiatedAudio bool @@ -396,7 +394,7 @@ func (m *MediaEngine) matchRemoteCodec(remoteCodec RTPCodecParameters, typ RTPCo remoteFmtp := fmtp.Parse(remoteCodec.RTPCodecCapability.MimeType, remoteCodec.RTPCodecCapability.SDPFmtpLine) if apt, hasApt := remoteFmtp.Parameter("apt"); hasApt { - payloadType, err := strconv.ParseUint(apt, 10, 8) + payloadType, err := strconv.Atoi(apt) if err != nil { return codecMatchNone, err } @@ -555,7 +553,7 @@ func (m *MediaEngine) getCodecsByKind(typ RTPCodecType) []RTPCodecParameters { return nil } -func (m *MediaEngine) getRTPParametersByKind(typ RTPCodecType, directions []RTPTransceiverDirection) RTPParameters { //nolint:gocognit +func (m *MediaEngine) getRTPParametersByKind(typ RTPCodecType, directions []RTPTransceiverDirection) RTPParameters { headerExtensions := make([]RTPHeaderExtensionParameter, 0) // perform before locking to prevent recursive RLocks @@ -571,33 +569,9 @@ func (m *MediaEngine) getRTPParametersByKind(typ RTPCodecType, directions []RTPT } } } else { - mediaHeaderExtensions := make(map[int]mediaEngineHeaderExtension) - for _, e := range m.headerExtensions { - usingNegotiatedID := false - for id := range m.negotiatedHeaderExtensions { - if m.negotiatedHeaderExtensions[id].uri == e.uri { - usingNegotiatedID = true - mediaHeaderExtensions[id] = e - break - } - } - if !usingNegotiatedID { - for id := 1; id < 15; id++ { - idAvailable := true - if _, ok := mediaHeaderExtensions[id]; ok { - idAvailable = false - } - if _, taken := m.negotiatedHeaderExtensions[id]; idAvailable && !taken { - mediaHeaderExtensions[id] = e - break - } - } - } - } - - for id, e := range mediaHeaderExtensions { + for id, e := range m.headerExtensions { if haveRTPTransceiverDirectionIntersection(e.allowedDirections, directions) && (e.isAudio && typ == RTPCodecTypeAudio || e.isVideo && typ == RTPCodecTypeVideo) { - headerExtensions = append(headerExtensions, RTPHeaderExtensionParameter{ID: id, URI: e.uri}) + headerExtensions = append(headerExtensions, RTPHeaderExtensionParameter{ID: id + 1, URI: e.uri}) } } } @@ -641,8 +615,6 @@ func payloaderForCodec(codec RTPCodecCapability) (rtp.Payloader, error) { }, nil case strings.ToLower(MimeTypeVP9): return &codecs.VP9Payloader{}, nil - case strings.ToLower(MimeTypeAV1): - return &codecs.AV1Payloader{}, nil case strings.ToLower(MimeTypeG722): return &codecs.G722Payloader{}, nil case strings.ToLower(MimeTypePCMU), strings.ToLower(MimeTypePCMA): diff --git a/vendor/github.com/pion/webrtc/v3/networktype.go b/vendor/github.com/pion/webrtc/v3/networktype.go index 601e73ff8..e5dd84073 100644 --- a/vendor/github.com/pion/webrtc/v3/networktype.go +++ b/vendor/github.com/pion/webrtc/v3/networktype.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/oauthcredential.go b/vendor/github.com/pion/webrtc/v3/oauthcredential.go index 16210f9da..46170c7a2 100644 --- a/vendor/github.com/pion/webrtc/v3/oauthcredential.go +++ b/vendor/github.com/pion/webrtc/v3/oauthcredential.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // OAuthCredential represents OAuth credential information which is used by diff --git a/vendor/github.com/pion/webrtc/v3/offeransweroptions.go b/vendor/github.com/pion/webrtc/v3/offeransweroptions.go index 528688975..2a34aed43 100644 --- a/vendor/github.com/pion/webrtc/v3/offeransweroptions.go +++ b/vendor/github.com/pion/webrtc/v3/offeransweroptions.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // OfferAnswerOptions is a base structure which describes the options that diff --git a/vendor/github.com/pion/webrtc/v3/operations.go b/vendor/github.com/pion/webrtc/v3/operations.go index d9dca4a8e..1eb85345c 100644 --- a/vendor/github.com/pion/webrtc/v3/operations.go +++ b/vendor/github.com/pion/webrtc/v3/operations.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( @@ -69,10 +66,7 @@ func (o *operations) pop() func() { e := o.ops.Front() o.ops.Remove(e) - if op, ok := e.Value.(operation); ok { - return op - } - return nil + return e.Value.(operation) } func (o *operations) start() { diff --git a/vendor/github.com/pion/webrtc/v3/peerconnection.go b/vendor/github.com/pion/webrtc/v3/peerconnection.go index b3c0ef427..1794e8d41 100644 --- a/vendor/github.com/pion/webrtc/v3/peerconnection.go +++ b/vendor/github.com/pion/webrtc/v3/peerconnection.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -24,7 +21,6 @@ import ( "github.com/pion/logging" "github.com/pion/rtcp" "github.com/pion/sdp/v3" - "github.com/pion/srtp/v2" "github.com/pion/webrtc/v3/internal/util" "github.com/pion/webrtc/v3/pkg/rtcerr" ) @@ -395,11 +391,7 @@ func (pc *PeerConnection) checkNegotiationNeeded() bool { //nolint:gocognit // Step 5.3.1 if t.Direction() == RTPTransceiverDirectionSendrecv || t.Direction() == RTPTransceiverDirectionSendonly { descMsid, okMsid := m.Attribute(sdp.AttrKeyMsid) - sender := t.Sender() - if sender == nil { - return true - } - track := sender.Track() + track := t.Sender().Track() if !okMsid || descMsid != track.StreamID()+" "+track.ID() { return true } @@ -436,9 +428,7 @@ func (pc *PeerConnection) checkNegotiationNeeded() bool { //nolint:gocognit // OnICECandidate sets an event handler which is invoked when a new ICE // candidate is found. -// ICE candidate gathering only begins when SetLocalDescription or -// SetRemoteDescription is called. -// Take note that the handler will be called with a nil pointer when +// Take note that the handler is gonna be called with a nil pointer when // gathering is finished. func (pc *PeerConnection) OnICECandidate(f func(*ICECandidate)) { pc.iceGatherer.OnLocalCandidate(f) @@ -643,8 +633,8 @@ func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription // in-parallel steps to create an offer // https://w3c.github.io/webrtc-pc/#dfn-in-parallel-steps-to-create-an-offer isPlanB := pc.configuration.SDPSemantics == SDPSemanticsPlanB - if pc.currentRemoteDescription != nil && isPlanB { - isPlanB = descriptionPossiblyPlanB(pc.currentRemoteDescription) + if pc.currentRemoteDescription != nil { + isPlanB = descriptionIsPlanB(pc.currentRemoteDescription) } // include unmatched local transceivers @@ -667,13 +657,7 @@ func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription } } for _, t := range currentTransceivers { - if mid := t.Mid(); mid != "" { - numericMid, errMid := strconv.Atoi(mid) - if errMid == nil { - if numericMid > pc.greaterMid { - pc.greaterMid = numericMid - } - } + if t.Mid() != "" { continue } pc.greaterMid++ @@ -751,23 +735,15 @@ func (pc *PeerConnection) updateConnectionState(iceConnectionState ICEConnection case iceConnectionState == ICEConnectionStateDisconnected: connectionState = PeerConnectionStateDisconnected - // None of the previous states apply and all RTCIceTransports are in the "new" or "closed" state, - // and all RTCDtlsTransports are in the "new" or "closed" state, or there are no transports. - case (iceConnectionState == ICEConnectionStateNew || iceConnectionState == ICEConnectionStateClosed) && - (dtlsTransportState == DTLSTransportStateNew || dtlsTransportState == DTLSTransportStateClosed): - connectionState = PeerConnectionStateNew - - // None of the previous states apply and any RTCIceTransport is in the "new" or "checking" state or - // any RTCDtlsTransport is in the "new" or "connecting" state. - case (iceConnectionState == ICEConnectionStateNew || iceConnectionState == ICEConnectionStateChecking) || - (dtlsTransportState == DTLSTransportStateNew || dtlsTransportState == DTLSTransportStateConnecting): - connectionState = PeerConnectionStateConnecting - // All RTCIceTransports and RTCDtlsTransports are in the "connected", "completed" or "closed" - // state and all RTCDtlsTransports are in the "connected" or "closed" state. - case (iceConnectionState == ICEConnectionStateConnected || iceConnectionState == ICEConnectionStateCompleted || iceConnectionState == ICEConnectionStateClosed) && - (dtlsTransportState == DTLSTransportStateConnected || dtlsTransportState == DTLSTransportStateClosed): + // state and at least one of them is in the "connected" or "completed" state. + case iceConnectionState == ICEConnectionStateConnected && dtlsTransportState == DTLSTransportStateConnected: connectionState = PeerConnectionStateConnected + + // Any of the RTCIceTransports or RTCDtlsTransports are in the "connecting" or + // "checking" state and none of them is in the "failed" state. + case iceConnectionState == ICEConnectionStateChecking && dtlsTransportState == DTLSTransportStateConnecting: + connectionState = PeerConnectionStateConnecting } if pc.connectionState.Load() == connectionState { @@ -779,7 +755,7 @@ func (pc *PeerConnection) updateConnectionState(iceConnectionState ICEConnection func (pc *PeerConnection) createICETransport() *ICETransport { t := pc.api.NewICETransport(pc.iceGatherer) - t.internalOnConnectionStateChangeHandler.Store(func(state ICETransportState) { + t.OnConnectionStateChange(func(state ICETransportState) { var cs ICEConnectionState switch state { case ICETransportStateNew: @@ -808,7 +784,7 @@ func (pc *PeerConnection) createICETransport() *ICETransport { } // CreateAnswer starts the PeerConnection and generates the localDescription -func (pc *PeerConnection) CreateAnswer(*AnswerOptions) (SessionDescription, error) { +func (pc *PeerConnection) CreateAnswer(options *AnswerOptions) (SessionDescription, error) { useIdentity := pc.idpLoginURL != nil remoteDesc := pc.RemoteDescription() switch { @@ -1006,7 +982,6 @@ func (pc *PeerConnection) SetLocalDescription(desc SessionDescription) error { weAnswer := desc.Type == SDPTypeAnswer remoteDesc := pc.RemoteDescription() if weAnswer && remoteDesc != nil { - _ = setRTPTransceiverCurrentDirection(&desc, currentTransceivers, false) if err := pc.startRTPSenders(currentTransceivers); err != nil { return err } @@ -1034,7 +1009,8 @@ func (pc *PeerConnection) LocalDescription() *SessionDescription { } // SetRemoteDescription sets the SessionDescription of the remote peer -func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { //nolint:gocognit,gocyclo +// nolint: gocyclo +func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { //nolint:gocognit if pc.isClosed.get() { return &rtcerr.InvalidStateError{Err: ErrConnectionClosed} } @@ -1054,11 +1030,7 @@ func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { var t *RTPTransceiver localTransceivers := append([]*RTPTransceiver{}, pc.GetTransceivers()...) - detectedPlanB := descriptionIsPlanB(pc.RemoteDescription(), pc.log) - if pc.configuration.SDPSemantics != SDPSemanticsUnifiedPlan { - detectedPlanB = descriptionPossiblyPlanB(pc.RemoteDescription()) - } - + detectedPlanB := descriptionIsPlanB(pc.RemoteDescription()) weOffer := desc.Type == SDPTypeAnswer if !weOffer && !detectedPlanB { @@ -1165,7 +1137,6 @@ func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { if isRenegotation { if weOffer { - _ = setRTPTransceiverCurrentDirection(&desc, currentTransceivers, true) if err = pc.startRTPSenders(currentTransceivers); err != nil { return err } @@ -1195,7 +1166,6 @@ func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { // Start the networking in a new routine since it will block until // the connection is actually established. if weOffer { - _ = setRTPTransceiverCurrentDirection(&desc, currentTransceivers, true) if err := pc.startRTPSenders(currentTransceivers); err != nil { return err } @@ -1254,53 +1224,6 @@ func (pc *PeerConnection) startReceiver(incoming trackDetails, receiver *RTPRece } } -func setRTPTransceiverCurrentDirection(answer *SessionDescription, currentTransceivers []*RTPTransceiver, weOffer bool) error { - currentTransceivers = append([]*RTPTransceiver{}, currentTransceivers...) - for _, media := range answer.parsed.MediaDescriptions { - midValue := getMidValue(media) - if midValue == "" { - return errPeerConnRemoteDescriptionWithoutMidValue - } - - if media.MediaName.Media == mediaSectionApplication { - continue - } - - var t *RTPTransceiver - t, currentTransceivers = findByMid(midValue, currentTransceivers) - - if t == nil { - return fmt.Errorf("%w: %q", errPeerConnTranscieverMidNil, midValue) - } - - direction := getPeerDirection(media) - if direction == RTPTransceiverDirection(Unknown) { - continue - } - - // reverse direction if it was a remote answer - if weOffer { - switch direction { - case RTPTransceiverDirectionSendonly: - direction = RTPTransceiverDirectionRecvonly - case RTPTransceiverDirectionRecvonly: - direction = RTPTransceiverDirectionSendonly - default: - } - } - - // If a transceiver is created by applying a remote description that has recvonly transceiver, - // it will have no sender. In this case, the transceiver's current direction is set to inactive so - // that the transceiver can be reused by next AddTrack. - if direction == RTPTransceiverDirectionSendonly && t.Sender() == nil { - direction = RTPTransceiverDirectionInactive - } - - t.setCurrentDirection(direction) - } - return nil -} - func runIfNewReceiver( incomingTrack trackDetails, transceivers []*RTPTransceiver, @@ -1342,7 +1265,6 @@ func (pc *PeerConnection) configureRTPReceivers(isRenegotiation bool, remoteDesc continue } - mid := t.Mid() receiverNeedsStopped := false func() { for _, t := range tracks { @@ -1350,7 +1272,7 @@ func (pc *PeerConnection) configureRTPReceivers(isRenegotiation bool, remoteDesc defer t.mu.Unlock() if t.rid != "" { - if details := trackDetailsForRID(incomingTracks, mid, t.rid); details != nil { + if details := trackDetailsForRID(incomingTracks, t.rid); details != nil { t.id = details.id t.streamID = details.streamID continue @@ -1431,7 +1353,7 @@ func (pc *PeerConnection) startRTPReceivers(remoteDesc *SessionDescription, curr case SDPSemanticsPlanB: remoteIsPlanB = true case SDPSemanticsUnifiedPlanWithFallback: - remoteIsPlanB = descriptionPossiblyPlanB(pc.RemoteDescription()) + remoteIsPlanB = descriptionIsPlanB(pc.RemoteDescription()) default: // none } @@ -1488,8 +1410,6 @@ func (pc *PeerConnection) handleUndeclaredSSRC(ssrc SSRC, remoteDescription *Ses onlyMediaSection := remoteDescription.parsed.MediaDescriptions[0] streamID := "" id := "" - hasRidAttribute := false - hasSSRCAttribute := false for _, a := range onlyMediaSection.Attributes { switch a.Key { @@ -1499,18 +1419,12 @@ func (pc *PeerConnection) handleUndeclaredSSRC(ssrc SSRC, remoteDescription *Ses id = split[1] } case sdp.AttrKeySSRC: - hasSSRCAttribute = true + return false, errPeerConnSingleMediaSectionHasExplicitSSRC case sdpAttributeRid: - hasRidAttribute = true + return false, nil } } - if hasRidAttribute { - return false, nil - } else if hasSSRCAttribute { - return false, errPeerConnSingleMediaSectionHasExplicitSSRC - } - incoming := trackDetails{ ssrcs: []SSRC{ssrc}, kind: RTPCodecTypeVideo, @@ -1525,7 +1439,6 @@ func (pc *PeerConnection) handleUndeclaredSSRC(ssrc SSRC, remoteDescription *Ses Direction: RTPTransceiverDirectionSendrecv, }) if err != nil { - // nolint return false, fmt.Errorf("%w: %d: %s", errPeerConnRemoteSSRCAddTransceiver, ssrc, err) } @@ -1634,71 +1547,61 @@ func (pc *PeerConnection) handleIncomingSSRC(rtpStream io.Reader, ssrc SSRC) err // undeclaredMediaProcessor handles RTP/RTCP packets that don't match any a:ssrc lines func (pc *PeerConnection) undeclaredMediaProcessor() { - go pc.undeclaredRTPMediaProcessor() - go pc.undeclaredRTCPMediaProcessor() -} - -func (pc *PeerConnection) undeclaredRTPMediaProcessor() { - var simulcastRoutineCount uint64 - for { - srtpSession, err := pc.dtlsTransport.getSRTPSession() - if err != nil { - pc.log.Warnf("undeclaredMediaProcessor failed to open SrtpSession: %v", err) - return - } - - stream, ssrc, err := srtpSession.AcceptStream() - if err != nil { - pc.log.Warnf("Failed to accept RTP %v", err) - return - } - - if pc.isClosed.get() { - if err = stream.Close(); err != nil { - pc.log.Warnf("Failed to close RTP stream %v", err) + go func() { + var simulcastRoutineCount uint64 + for { + srtpSession, err := pc.dtlsTransport.getSRTPSession() + if err != nil { + pc.log.Warnf("undeclaredMediaProcessor failed to open SrtpSession: %v", err) + return } - continue - } - if atomic.AddUint64(&simulcastRoutineCount, 1) >= simulcastMaxProbeRoutines { - atomic.AddUint64(&simulcastRoutineCount, ^uint64(0)) - pc.log.Warn(ErrSimulcastProbeOverflow.Error()) - pc.dtlsTransport.storeSimulcastStream(stream) - continue - } + stream, ssrc, err := srtpSession.AcceptStream() + if err != nil { + pc.log.Warnf("Failed to accept RTP %v", err) + return + } - go func(rtpStream io.Reader, ssrc SSRC) { - if err := pc.handleIncomingSSRC(rtpStream, ssrc); err != nil { - pc.log.Errorf(incomingUnhandledRTPSsrc, ssrc, err) + if pc.isClosed.get() { + if err = stream.Close(); err != nil { + pc.log.Warnf("Failed to close RTP stream %v", err) + } + continue + } + + if atomic.AddUint64(&simulcastRoutineCount, 1) >= simulcastMaxProbeRoutines { + atomic.AddUint64(&simulcastRoutineCount, ^uint64(0)) + pc.log.Warn(ErrSimulcastProbeOverflow.Error()) + continue + } + + go func(rtpStream io.Reader, ssrc SSRC) { pc.dtlsTransport.storeSimulcastStream(stream) - } - atomic.AddUint64(&simulcastRoutineCount, ^uint64(0)) - }(stream, SSRC(ssrc)) - } -} -func (pc *PeerConnection) undeclaredRTCPMediaProcessor() { - var unhandledStreams []*srtp.ReadStreamSRTCP - defer func() { - for _, s := range unhandledStreams { - _ = s.Close() + if err := pc.handleIncomingSSRC(rtpStream, ssrc); err != nil { + pc.log.Errorf(incomingUnhandledRTPSsrc, ssrc, err) + } + atomic.AddUint64(&simulcastRoutineCount, ^uint64(0)) + }(stream, SSRC(ssrc)) } }() - for { - srtcpSession, err := pc.dtlsTransport.getSRTCPSession() - if err != nil { - pc.log.Warnf("undeclaredMediaProcessor failed to open SrtcpSession: %v", err) - return - } - stream, ssrc, err := srtcpSession.AcceptStream() - if err != nil { - pc.log.Warnf("Failed to accept RTCP %v", err) - return + go func() { + for { + srtcpSession, err := pc.dtlsTransport.getSRTCPSession() + if err != nil { + pc.log.Warnf("undeclaredMediaProcessor failed to open SrtcpSession: %v", err) + return + } + + _, ssrc, err := srtcpSession.AcceptStream() + if err != nil { + pc.log.Warnf("Failed to accept RTCP %v", err) + return + } + pc.log.Warnf("Incoming unhandled RTCP ssrc(%d), OnTrack will not be fired", ssrc) } - pc.log.Warnf("Incoming unhandled RTCP ssrc(%d), OnTrack will not be fired", ssrc) - unhandledStreams = append(unhandledStreams, stream) - } + }() } // RemoteDescription returns pendingRemoteDescription if it is not null and @@ -1748,10 +1651,7 @@ func (pc *PeerConnection) AddICECandidate(candidate ICECandidateInit) error { // ICEConnectionState returns the ICE connection state of the // PeerConnection instance. func (pc *PeerConnection) ICEConnectionState() ICEConnectionState { - if state, ok := pc.iceConnectionState.Load().(ICEConnectionState); ok { - return state - } - return ICEConnectionState(0) + return pc.iceConnectionState.Load().(ICEConnectionState) } // GetSenders returns the RTPSender that are currently attached to this PeerConnection @@ -1797,13 +1697,7 @@ func (pc *PeerConnection) AddTrack(track TrackLocal) (*RTPSender, error) { pc.mu.Lock() defer pc.mu.Unlock() for _, t := range pc.rtpTransceivers { - currentDirection := t.getCurrentDirection() - // According to https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addtrack, if the - // transceiver can be reused only if it's currentDirection never be sendrecv or sendonly. - // But that will cause sdp inflate. So we only check currentDirection's current value, - // that's worked for all browsers. - if !t.stopped && t.kind == track.Kind() && t.Sender() == nil && - !(currentDirection == RTPTransceiverDirectionSendrecv || currentDirection == RTPTransceiverDirectionSendonly) { + if !t.stopped && t.kind == track.Kind() && t.Sender() == nil { sender, err := pc.api.NewRTPSender(track, pc.dtlsTransport) if err == nil { err = t.SetSender(sender, track) @@ -1993,7 +1887,7 @@ func (pc *PeerConnection) CreateDataChannel(label string, options *DataChannelIn } } - d, err := pc.api.newDataChannel(params, nil, pc.log) + d, err := pc.api.newDataChannel(params, pc.log) if err != nil { return nil, err } @@ -2023,7 +1917,7 @@ func (pc *PeerConnection) CreateDataChannel(label string, options *DataChannelIn } // SetIdentityProvider is used to configure an identity provider to generate identity assertions -func (pc *PeerConnection) SetIdentityProvider(string) error { +func (pc *PeerConnection) SetIdentityProvider(provider string) error { return errPeerConnSetIdentityProviderNotImplemented } @@ -2177,10 +2071,7 @@ func (pc *PeerConnection) ICEGatheringState() ICEGatheringState { // ConnectionState attribute returns the connection state of the // PeerConnection instance. func (pc *PeerConnection) ConnectionState() PeerConnectionState { - if state, ok := pc.connectionState.Load().(PeerConnectionState); ok { - return state - } - return PeerConnectionState(0) + return pc.connectionState.Load().(PeerConnectionState) } // GetStats return data providing statistics about the overall connection @@ -2353,7 +2244,7 @@ func (pc *PeerConnection) generateUnmatchedSDP(transceivers []*RTPTransceiver, u return nil, err } - return populateSDP(d, isPlanB, dtlsFingerprints, pc.api.settingEngine.sdpMediaLevelFingerprints, pc.api.settingEngine.candidates.ICELite, true, pc.api.mediaEngine, connectionRoleFromDtlsRole(defaultDtlsRoleOffer), candidates, iceParams, mediaSections, pc.ICEGatheringState()) + return populateSDP(d, isPlanB, dtlsFingerprints, pc.api.settingEngine.sdpMediaLevelFingerprints, pc.api.settingEngine.candidates.ICELite, pc.api.mediaEngine, connectionRoleFromDtlsRole(defaultDtlsRoleOffer), candidates, iceParams, mediaSections, pc.ICEGatheringState()) } // generateMatchedSDP generates a SDP and takes the remote state into account @@ -2380,14 +2271,8 @@ func (pc *PeerConnection) generateMatchedSDP(transceivers []*RTPTransceiver, use if pc.pendingRemoteDescription != nil { remoteDescription = pc.pendingRemoteDescription } - isExtmapAllowMixed := isExtMapAllowMixedSet(remoteDescription.parsed) localTransceivers := append([]*RTPTransceiver{}, transceivers...) - - detectedPlanB := descriptionIsPlanB(remoteDescription, pc.log) - if pc.configuration.SDPSemantics != SDPSemanticsUnifiedPlan { - detectedPlanB = descriptionPossiblyPlanB(remoteDescription) - } - + detectedPlanB := descriptionIsPlanB(remoteDescription) mediaSections := []mediaSection{} alreadyHaveApplicationMediaSection := false for _, media := range remoteDescription.parsed.MediaDescriptions { @@ -2480,7 +2365,7 @@ func (pc *PeerConnection) generateMatchedSDP(transceivers []*RTPTransceiver, use return nil, err } - return populateSDP(d, detectedPlanB, dtlsFingerprints, pc.api.settingEngine.sdpMediaLevelFingerprints, pc.api.settingEngine.candidates.ICELite, isExtmapAllowMixed, pc.api.mediaEngine, connectionRole, candidates, iceParams, mediaSections, pc.ICEGatheringState()) + return populateSDP(d, detectedPlanB, dtlsFingerprints, pc.api.settingEngine.sdpMediaLevelFingerprints, pc.api.settingEngine.candidates.ICELite, pc.api.mediaEngine, connectionRole, candidates, iceParams, mediaSections, pc.ICEGatheringState()) } func (pc *PeerConnection) setGatherCompleteHandler(handler func()) { diff --git a/vendor/github.com/pion/webrtc/v3/peerconnection_js.go b/vendor/github.com/pion/webrtc/v3/peerconnection_js.go index 8322e1be9..8e5557783 100644 --- a/vendor/github.com/pion/webrtc/v3/peerconnection_js.go +++ b/vendor/github.com/pion/webrtc/v3/peerconnection_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm @@ -569,31 +566,14 @@ func iceServersToValue(iceServers []ICEServer) js.Value { return js.ValueOf(maps) } -func oauthCredentialToValue(o OAuthCredential) js.Value { - out := map[string]interface{}{ - "MACKey": o.MACKey, - "AccessToken": o.AccessToken, - } - return js.ValueOf(out) -} - func iceServerToValue(server ICEServer) js.Value { - out := map[string]interface{}{ - "urls": stringsToValue(server.URLs), // required - } - if server.Username != "" { - out["username"] = stringToValueOrUndefined(server.Username) - } - if server.Credential != nil { - switch t := server.Credential.(type) { - case string: - out["credential"] = stringToValueOrUndefined(t) - case OAuthCredential: - out["credential"] = oauthCredentialToValue(t) - } - } - out["credentialType"] = stringEnumToValueOrUndefined(server.CredentialType.String()) - return js.ValueOf(out) + return js.ValueOf(map[string]interface{}{ + "urls": stringsToValue(server.URLs), // required + "username": stringToValueOrUndefined(server.Username), + // Note: credential and credentialType are not currently supported. + // "credential": interfaceToValueOrUndefined(server.Credential), + // "credentialType": stringEnumToValueOrUndefined(server.CredentialType.String()), + }) } func valueToConfiguration(configValue js.Value) Configuration { @@ -624,36 +604,14 @@ func valueToICEServers(iceServersValue js.Value) []ICEServer { return iceServers } -func valueToICECredential(iceCredentialValue js.Value) interface{} { - if iceCredentialValue.IsNull() || iceCredentialValue.IsUndefined() { - return nil - } - if iceCredentialValue.Type() == js.TypeString { - return iceCredentialValue.String() - } - if iceCredentialValue.Type() == js.TypeObject { - return OAuthCredential{ - MACKey: iceCredentialValue.Get("MACKey").String(), - AccessToken: iceCredentialValue.Get("AccessToken").String(), - } - } - return nil -} - func valueToICEServer(iceServerValue js.Value) ICEServer { - tpe, err := newICECredentialType(valueToStringOrZero(iceServerValue.Get("credentialType"))) - if err != nil { - tpe = ICECredentialTypePassword - } - s := ICEServer{ + return ICEServer{ URLs: valueToStrings(iceServerValue.Get("urls")), // required Username: valueToStringOrZero(iceServerValue.Get("username")), // Note: Credential and CredentialType are not currently supported. - Credential: valueToICECredential(iceServerValue.Get("credential")), - CredentialType: tpe, + // Credential: iceServerValue.Get("credential"), + // CredentialType: newICECredentialType(valueToStringOrZero(iceServerValue.Get("credentialType"))), } - - return s } func valueToICECandidate(val js.Value) *ICECandidate { diff --git a/vendor/github.com/pion/webrtc/v3/peerconnectionstate.go b/vendor/github.com/pion/webrtc/v3/peerconnectionstate.go index 1f1456882..66ac20eef 100644 --- a/vendor/github.com/pion/webrtc/v3/peerconnectionstate.go +++ b/vendor/github.com/pion/webrtc/v3/peerconnectionstate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // PeerConnectionState indicates the state of the PeerConnection. diff --git a/vendor/github.com/pion/webrtc/v3/pkg/media/media.go b/vendor/github.com/pion/webrtc/v3/pkg/media/media.go index 2ed5573f8..4b00edbe7 100644 --- a/vendor/github.com/pion/webrtc/v3/pkg/media/media.go +++ b/vendor/github.com/pion/webrtc/v3/pkg/media/media.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package media provides media writer and filters package media diff --git a/vendor/github.com/pion/webrtc/v3/pkg/rtcerr/errors.go b/vendor/github.com/pion/webrtc/v3/pkg/rtcerr/errors.go index 36205c7d0..aa94b7bf9 100644 --- a/vendor/github.com/pion/webrtc/v3/pkg/rtcerr/errors.go +++ b/vendor/github.com/pion/webrtc/v3/pkg/rtcerr/errors.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package rtcerr implements the error wrappers defined throughout the // WebRTC 1.0 specifications. package rtcerr diff --git a/vendor/github.com/pion/webrtc/v3/renovate.json b/vendor/github.com/pion/webrtc/v3/renovate.json index f1bb98c6a..f1614058a 100644 --- a/vendor/github.com/pion/webrtc/v3/renovate.json +++ b/vendor/github.com/pion/webrtc/v3/renovate.json @@ -1,6 +1,27 @@ { - "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ - "github>pion/renovate-config" + "config:base", + ":disableDependencyDashboard" + ], + "postUpdateOptions": [ + "gomodTidy" + ], + "commitBody": "Generated by renovateBot", + "packageRules": [ + { + "matchUpdateTypes": ["minor", "patch", "pin", "digest"], + "automerge": true + }, + { + "packagePatterns": ["^golang.org/x/"], + "schedule": ["on the first day of the month"] + } + ], + "ignorePaths": [ + ".github/workflows/generate-authors.yml", + ".github/workflows/lint.yaml", + ".github/workflows/renovate-go-mod-fix.yaml", + ".github/workflows/test.yaml", + ".github/workflows/tidy-check.yaml" ] } diff --git a/vendor/github.com/pion/webrtc/v3/rtcpfeedback.go b/vendor/github.com/pion/webrtc/v3/rtcpfeedback.go index ab6f555af..b377738f6 100644 --- a/vendor/github.com/pion/webrtc/v3/rtcpfeedback.go +++ b/vendor/github.com/pion/webrtc/v3/rtcpfeedback.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc const ( diff --git a/vendor/github.com/pion/webrtc/v3/rtcpmuxpolicy.go b/vendor/github.com/pion/webrtc/v3/rtcpmuxpolicy.go index bd68ab562..f74e440b3 100644 --- a/vendor/github.com/pion/webrtc/v3/rtcpmuxpolicy.go +++ b/vendor/github.com/pion/webrtc/v3/rtcpmuxpolicy.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/rtpcapabilities.go b/vendor/github.com/pion/webrtc/v3/rtpcapabilities.go index 3ac52e450..dc42230d1 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpcapabilities.go +++ b/vendor/github.com/pion/webrtc/v3/rtpcapabilities.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // RTPCapabilities represents the capabilities of a transceiver diff --git a/vendor/github.com/pion/webrtc/v3/rtpcodec.go b/vendor/github.com/pion/webrtc/v3/rtpcodec.go index 5692d5f56..cde2b8e71 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpcodec.go +++ b/vendor/github.com/pion/webrtc/v3/rtpcodec.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/rtpcodingparameters.go b/vendor/github.com/pion/webrtc/v3/rtpcodingparameters.go index f03d8c35f..c5e12efaf 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpcodingparameters.go +++ b/vendor/github.com/pion/webrtc/v3/rtpcodingparameters.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // RTPRtxParameters dictionary contains information relating to retransmission (RTX) settings. diff --git a/vendor/github.com/pion/webrtc/v3/rtpdecodingparameters.go b/vendor/github.com/pion/webrtc/v3/rtpdecodingparameters.go index 0c45f896f..77aa1fc1c 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpdecodingparameters.go +++ b/vendor/github.com/pion/webrtc/v3/rtpdecodingparameters.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // RTPDecodingParameters provides information relating to both encoding and decoding. diff --git a/vendor/github.com/pion/webrtc/v3/rtpencodingparameters.go b/vendor/github.com/pion/webrtc/v3/rtpencodingparameters.go index ffd4a8d78..09481a570 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpencodingparameters.go +++ b/vendor/github.com/pion/webrtc/v3/rtpencodingparameters.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // RTPEncodingParameters provides information relating to both encoding and decoding. diff --git a/vendor/github.com/pion/webrtc/v3/rtpreceiveparameters.go b/vendor/github.com/pion/webrtc/v3/rtpreceiveparameters.go index 26a667616..badf6b733 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpreceiveparameters.go +++ b/vendor/github.com/pion/webrtc/v3/rtpreceiveparameters.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // RTPReceiveParameters contains the RTP stack settings used by receivers diff --git a/vendor/github.com/pion/webrtc/v3/rtpreceiver.go b/vendor/github.com/pion/webrtc/v3/rtpreceiver.go index dac154be6..a836b2ff8 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpreceiver.go +++ b/vendor/github.com/pion/webrtc/v3/rtpreceiver.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -410,7 +407,10 @@ func (r *RTPReceiver) SetReadDeadline(t time.Time) error { r.mu.RLock() defer r.mu.RUnlock() - return r.tracks[0].rtcpReadStream.SetReadDeadline(t) + if err := r.tracks[0].rtcpReadStream.SetReadDeadline(t); err != nil { + return err + } + return nil } // SetReadDeadlineSimulcast sets the max amount of time the RTCP stream for a given rid will block before returning. 0 is forever. diff --git a/vendor/github.com/pion/webrtc/v3/rtpreceiver_go.go b/vendor/github.com/pion/webrtc/v3/rtpreceiver_go.go index 4d150f0f3..430169548 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpreceiver_go.go +++ b/vendor/github.com/pion/webrtc/v3/rtpreceiver_go.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js diff --git a/vendor/github.com/pion/webrtc/v3/rtpreceiver_js.go b/vendor/github.com/pion/webrtc/v3/rtpreceiver_js.go index 44cef72d1..866757fb8 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpreceiver_js.go +++ b/vendor/github.com/pion/webrtc/v3/rtpreceiver_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/rtpsender.go b/vendor/github.com/pion/webrtc/v3/rtpsender.go index 49ae4e82e..7319cf842 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpsender.go +++ b/vendor/github.com/pion/webrtc/v3/rtpsender.go @@ -1,13 +1,9 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js package webrtc import ( - "fmt" "io" "sync" "time" @@ -16,30 +12,23 @@ import ( "github.com/pion/randutil" "github.com/pion/rtcp" "github.com/pion/rtp" - "github.com/pion/webrtc/v3/internal/util" ) -type trackEncoding struct { +// RTPSender allows an application to control how a given Track is encoded and transmitted to a remote peer +type RTPSender struct { track TrackLocal - srtpStream *srtpWriterFuture - + srtpStream *srtpWriterFuture rtcpInterceptor interceptor.RTCPReader streamInfo interceptor.StreamInfo context TrackLocalContext - ssrc SSRC -} - -// RTPSender allows an application to control how a given Track is encoded and transmitted to a remote peer -type RTPSender struct { - trackEncodings []*trackEncoding - transport *DTLSTransport payloadType PayloadType kind RTPCodecType + ssrc SSRC // nolint:godox // TODO(sgotti) remove this when in future we'll avoid replacing @@ -71,15 +60,23 @@ func (api *API) NewRTPSender(track TrackLocal, transport *DTLSTransport) (*RTPSe } r := &RTPSender{ + track: track, transport: transport, api: api, sendCalled: make(chan struct{}), stopCalled: make(chan struct{}), + ssrc: SSRC(randutil.NewMathRandomGenerator().Uint32()), id: id, + srtpStream: &srtpWriterFuture{}, kind: track.Kind(), } - r.addEncoding(track) + r.srtpStream.rtpSender = r + + r.rtcpInterceptor = r.api.interceptor.BindRTCPReader(interceptor.RTPReaderFunc(func(in []byte, a interceptor.Attributes) (n int, attributes interceptor.Attributes, err error) { + n, err = r.srtpStream.Read(in) + return n, a, err + })) return r, nil } @@ -111,26 +108,24 @@ func (r *RTPSender) Transport() *DTLSTransport { } func (r *RTPSender) getParameters() RTPSendParameters { - var encodings []RTPEncodingParameters - for _, trackEncoding := range r.trackEncodings { - var rid string - if trackEncoding.track != nil { - rid = trackEncoding.track.RID() - } - encodings = append(encodings, RTPEncodingParameters{ - RTPCodingParameters: RTPCodingParameters{ - RID: rid, - SSRC: trackEncoding.ssrc, - PayloadType: r.payloadType, - }, - }) + var rid string + if r.track != nil { + rid = r.track.RID() } sendParameters := RTPSendParameters{ RTPParameters: r.api.mediaEngine.getRTPParametersByKind( r.kind, []RTPTransceiverDirection{RTPTransceiverDirectionSendonly}, ), - Encodings: encodings, + Encodings: []RTPEncodingParameters{ + { + RTPCodingParameters: RTPCodingParameters{ + RID: rid, + SSRC: r.ssrc, + PayloadType: r.payloadType, + }, + }, + }, } if r.rtpTransceiver != nil { sendParameters.Codecs = r.rtpTransceiver.getCodecs() @@ -148,81 +143,11 @@ func (r *RTPSender) GetParameters() RTPSendParameters { return r.getParameters() } -// AddEncoding adds an encoding to RTPSender. Used by simulcast senders. -func (r *RTPSender) AddEncoding(track TrackLocal) error { - r.mu.Lock() - defer r.mu.Unlock() - - if track == nil { - return errRTPSenderTrackNil - } - - if track.RID() == "" { - return errRTPSenderRidNil - } - - if r.hasStopped() { - return errRTPSenderStopped - } - - if r.hasSent() { - return errRTPSenderSendAlreadyCalled - } - - var refTrack TrackLocal - if len(r.trackEncodings) != 0 { - refTrack = r.trackEncodings[0].track - } - if refTrack == nil || refTrack.RID() == "" { - return errRTPSenderNoBaseEncoding - } - - if refTrack.ID() != track.ID() || refTrack.StreamID() != track.StreamID() || refTrack.Kind() != track.Kind() { - return errRTPSenderBaseEncodingMismatch - } - - for _, encoding := range r.trackEncodings { - if encoding.track == nil { - continue - } - - if encoding.track.RID() == track.RID() { - return errRTPSenderRIDCollision - } - } - - r.addEncoding(track) - return nil -} - -func (r *RTPSender) addEncoding(track TrackLocal) { - ssrc := SSRC(randutil.NewMathRandomGenerator().Uint32()) - trackEncoding := &trackEncoding{ - track: track, - srtpStream: &srtpWriterFuture{ssrc: ssrc}, - ssrc: ssrc, - } - trackEncoding.srtpStream.rtpSender = r - trackEncoding.rtcpInterceptor = r.api.interceptor.BindRTCPReader( - interceptor.RTPReaderFunc(func(in []byte, a interceptor.Attributes) (n int, attributes interceptor.Attributes, err error) { - n, err = trackEncoding.srtpStream.Read(in) - return n, a, err - }), - ) - - r.trackEncodings = append(r.trackEncodings, trackEncoding) -} - // Track returns the RTCRtpTransceiver track, or nil func (r *RTPSender) Track() TrackLocal { r.mu.RLock() defer r.mu.RUnlock() - - if len(r.trackEncodings) == 0 { - return nil - } - - return r.trackEncodings[0].track + return r.track } // ReplaceTrack replaces the track currently being used as the sender's source with a new TrackLocal. @@ -236,38 +161,26 @@ func (r *RTPSender) ReplaceTrack(track TrackLocal) error { return ErrRTPSenderNewTrackHasIncorrectKind } - // cannot replace simulcast envelope - if track != nil && len(r.trackEncodings) > 1 { - return ErrRTPSenderNewTrackHasIncorrectEnvelope - } - - var replacedTrack TrackLocal - var context *TrackLocalContext - if len(r.trackEncodings) != 0 { - replacedTrack = r.trackEncodings[0].track - context = &r.trackEncodings[0].context - } - if r.hasSent() && replacedTrack != nil { - if err := replacedTrack.Unbind(*context); err != nil { + if r.hasSent() && r.track != nil { + if err := r.track.Unbind(r.context); err != nil { return err } } if !r.hasSent() || track == nil { - r.trackEncodings[0].track = track + r.track = track return nil } codec, err := track.Bind(TrackLocalContext{ - id: context.id, - params: r.api.mediaEngine.getRTPParametersByKind(track.Kind(), []RTPTransceiverDirection{RTPTransceiverDirectionSendonly}), - ssrc: context.ssrc, - writeStream: context.writeStream, - rtcpInterceptor: context.rtcpInterceptor, + id: r.context.id, + params: r.api.mediaEngine.getRTPParametersByKind(track.Kind(), []RTPTransceiverDirection{RTPTransceiverDirectionSendonly}), + ssrc: r.context.ssrc, + writeStream: r.context.writeStream, }) if err != nil { // Re-bind the original track - if _, reBindErr := replacedTrack.Bind(*context); reBindErr != nil { + if _, reBindErr := r.track.Bind(r.context); reBindErr != nil { return reBindErr } @@ -276,10 +189,10 @@ func (r *RTPSender) ReplaceTrack(track TrackLocal) error { // Codec has changed if r.payloadType != codec.PayloadType { - context.params.Codecs = []RTPCodecParameters{codec} + r.context.params.Codecs = []RTPCodecParameters{codec} } - r.trackEncodings[0].track = track + r.track = track return nil } @@ -291,43 +204,30 @@ func (r *RTPSender) Send(parameters RTPSendParameters) error { switch { case r.hasSent(): return errRTPSenderSendAlreadyCalled - case r.trackEncodings[0].track == nil: + case r.track == nil: return errRTPSenderTrackRemoved } - for idx, trackEncoding := range r.trackEncodings { - writeStream := &interceptorToTrackLocalWriter{} - trackEncoding.context = TrackLocalContext{ - id: r.id, - params: r.api.mediaEngine.getRTPParametersByKind(trackEncoding.track.Kind(), []RTPTransceiverDirection{RTPTransceiverDirectionSendonly}), - ssrc: parameters.Encodings[idx].SSRC, - writeStream: writeStream, - rtcpInterceptor: trackEncoding.rtcpInterceptor, - } - - codec, err := trackEncoding.track.Bind(trackEncoding.context) - if err != nil { - return err - } - trackEncoding.context.params.Codecs = []RTPCodecParameters{codec} - - trackEncoding.streamInfo = *createStreamInfo( - r.id, - parameters.Encodings[idx].SSRC, - codec.PayloadType, - codec.RTPCodecCapability, - parameters.HeaderExtensions, - ) - srtpStream := trackEncoding.srtpStream - rtpInterceptor := r.api.interceptor.BindLocalStream( - &trackEncoding.streamInfo, - interceptor.RTPWriterFunc(func(header *rtp.Header, payload []byte, attributes interceptor.Attributes) (int, error) { - return srtpStream.WriteRTP(header, payload) - }), - ) - writeStream.interceptor.Store(rtpInterceptor) + writeStream := &interceptorToTrackLocalWriter{} + r.context = TrackLocalContext{ + id: r.id, + params: r.api.mediaEngine.getRTPParametersByKind(r.track.Kind(), []RTPTransceiverDirection{RTPTransceiverDirectionSendonly}), + ssrc: parameters.Encodings[0].SSRC, + writeStream: writeStream, } + codec, err := r.track.Bind(r.context) + if err != nil { + return err + } + r.context.params.Codecs = []RTPCodecParameters{codec} + + r.streamInfo = *createStreamInfo(r.id, parameters.Encodings[0].SSRC, codec.PayloadType, codec.RTPCodecCapability, parameters.HeaderExtensions) + rtpInterceptor := r.api.interceptor.BindLocalStream(&r.streamInfo, interceptor.RTPWriterFunc(func(header *rtp.Header, payload []byte, attributes interceptor.Attributes) (int, error) { + return r.srtpStream.WriteRTP(header, payload) + })) + writeStream.interceptor.Store(rtpInterceptor) + close(r.sendCalled) return nil } @@ -352,20 +252,16 @@ func (r *RTPSender) Stop() error { return err } - errs := []error{} - for _, trackEncoding := range r.trackEncodings { - r.api.interceptor.UnbindLocalStream(&trackEncoding.streamInfo) - errs = append(errs, trackEncoding.srtpStream.Close()) - } + r.api.interceptor.UnbindLocalStream(&r.streamInfo) - return util.FlattenErrs(errs) + return r.srtpStream.Close() } -// Read reads incoming RTCP for this RTPSender +// Read reads incoming RTCP for this RTPReceiver func (r *RTPSender) Read(b []byte) (n int, a interceptor.Attributes, err error) { select { case <-r.sendCalled: - return r.trackEncodings[0].rtcpInterceptor.Read(b, a) + return r.rtcpInterceptor.Read(b, a) case <-r.stopCalled: return 0, nil, io.ErrClosedPipe } @@ -387,50 +283,10 @@ func (r *RTPSender) ReadRTCP() ([]rtcp.Packet, interceptor.Attributes, error) { return pkts, attributes, nil } -// ReadSimulcast reads incoming RTCP for this RTPSender for given rid -func (r *RTPSender) ReadSimulcast(b []byte, rid string) (n int, a interceptor.Attributes, err error) { - select { - case <-r.sendCalled: - for _, t := range r.trackEncodings { - if t.track != nil && t.track.RID() == rid { - return t.rtcpInterceptor.Read(b, a) - } - } - return 0, nil, fmt.Errorf("%w: %s", errRTPSenderNoTrackForRID, rid) - case <-r.stopCalled: - return 0, nil, io.ErrClosedPipe - } -} - -// ReadSimulcastRTCP is a convenience method that wraps ReadSimulcast and unmarshal for you -func (r *RTPSender) ReadSimulcastRTCP(rid string) ([]rtcp.Packet, interceptor.Attributes, error) { - b := make([]byte, r.api.settingEngine.getReceiveMTU()) - i, attributes, err := r.ReadSimulcast(b, rid) - if err != nil { - return nil, nil, err - } - - pkts, err := rtcp.Unmarshal(b[:i]) - return pkts, attributes, err -} - // SetReadDeadline sets the deadline for the Read operation. // Setting to zero means no deadline. func (r *RTPSender) SetReadDeadline(t time.Time) error { - return r.trackEncodings[0].srtpStream.SetReadDeadline(t) -} - -// SetReadDeadlineSimulcast sets the max amount of time the RTCP stream for a given rid will block before returning. 0 is forever. -func (r *RTPSender) SetReadDeadlineSimulcast(deadline time.Time, rid string) error { - r.mu.RLock() - defer r.mu.RUnlock() - - for _, t := range r.trackEncodings { - if t.track != nil && t.track.RID() == rid { - return t.srtpStream.SetReadDeadline(deadline) - } - } - return fmt.Errorf("%w: %s", errRTPSenderNoTrackForRID, rid) + return r.srtpStream.SetReadDeadline(t) } // hasSent tells if data has been ever sent for this instance diff --git a/vendor/github.com/pion/webrtc/v3/rtpsender_js.go b/vendor/github.com/pion/webrtc/v3/rtpsender_js.go index 46ea599f7..cdb9dd595 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpsender_js.go +++ b/vendor/github.com/pion/webrtc/v3/rtpsender_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/rtpsendparameters.go b/vendor/github.com/pion/webrtc/v3/rtpsendparameters.go index b955c61ce..cc55e5dcc 100644 --- a/vendor/github.com/pion/webrtc/v3/rtpsendparameters.go +++ b/vendor/github.com/pion/webrtc/v3/rtpsendparameters.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // RTPSendParameters contains the RTP stack settings used by receivers diff --git a/vendor/github.com/pion/webrtc/v3/rtptransceiver.go b/vendor/github.com/pion/webrtc/v3/rtptransceiver.go index 02ddf7924..4ff4ead7d 100644 --- a/vendor/github.com/pion/webrtc/v3/rtptransceiver.go +++ b/vendor/github.com/pion/webrtc/v3/rtptransceiver.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -16,11 +13,10 @@ import ( // RTPTransceiver represents a combination of an RTPSender and an RTPReceiver that share a common mid. type RTPTransceiver struct { - mid atomic.Value // string - sender atomic.Value // *RTPSender - receiver atomic.Value // *RTPReceiver - direction atomic.Value // RTPTransceiverDirection - currentDirection atomic.Value // RTPTransceiverDirection + mid atomic.Value // string + sender atomic.Value // *RTPSender + receiver atomic.Value // *RTPReceiver + direction atomic.Value // RTPTransceiverDirection codecs []RTPCodecParameters // User provided codecs via SetCodecPreferences @@ -42,7 +38,6 @@ func newRTPTransceiver( t.setReceiver(receiver) t.setSender(sender) t.setDirection(direction) - t.setCurrentDirection(RTPTransceiverDirection(Unknown)) return t } @@ -87,8 +82,8 @@ func (t *RTPTransceiver) getCodecs() []RTPCodecParameters { // Sender returns the RTPTransceiver's RTPSender if it has one func (t *RTPTransceiver) Sender() *RTPSender { - if v, ok := t.sender.Load().(*RTPSender); ok { - return v + if v := t.sender.Load(); v != nil { + return v.(*RTPSender) } return nil @@ -114,8 +109,8 @@ func (t *RTPTransceiver) setSender(s *RTPSender) { // Receiver returns the RTPTransceiver's RTPReceiver if it has one func (t *RTPTransceiver) Receiver() *RTPReceiver { - if v, ok := t.receiver.Load().(*RTPReceiver); ok { - return v + if v := t.receiver.Load(); v != nil { + return v.(*RTPReceiver) } return nil @@ -132,8 +127,8 @@ func (t *RTPTransceiver) SetMid(mid string) error { // Mid gets the Transceiver's mid value. When not already set, this value will be set in CreateOffer or CreateAnswer. func (t *RTPTransceiver) Mid() string { - if v, ok := t.mid.Load().(string); ok { - return v + if v := t.mid.Load(); v != nil { + return v.(string) } return "" } @@ -145,10 +140,7 @@ func (t *RTPTransceiver) Kind() RTPCodecType { // Direction returns the RTPTransceiver's current direction func (t *RTPTransceiver) Direction() RTPTransceiverDirection { - if direction, ok := t.direction.Load().(RTPTransceiverDirection); ok { - return direction - } - return RTPTransceiverDirection(0) + return t.direction.Load().(RTPTransceiverDirection) } // Stop irreversibly stops the RTPTransceiver @@ -165,7 +157,6 @@ func (t *RTPTransceiver) Stop() error { } t.setDirection(RTPTransceiverDirectionInactive) - t.setCurrentDirection(RTPTransceiverDirectionInactive) return nil } @@ -185,17 +176,6 @@ func (t *RTPTransceiver) setDirection(d RTPTransceiverDirection) { t.direction.Store(d) } -func (t *RTPTransceiver) setCurrentDirection(d RTPTransceiverDirection) { - t.currentDirection.Store(d) -} - -func (t *RTPTransceiver) getCurrentDirection() RTPTransceiverDirection { - if v, ok := t.currentDirection.Load().(RTPTransceiverDirection); ok { - return v - } - return RTPTransceiverDirection(Unknown) -} - func (t *RTPTransceiver) setSendingTrack(track TrackLocal) error { if err := t.Sender().ReplaceTrack(track); err != nil { return err @@ -242,9 +222,9 @@ func satisfyTypeAndDirection(remoteKind RTPCodecType, remoteDirection RTPTransce getPreferredDirections := func() []RTPTransceiverDirection { switch remoteDirection { case RTPTransceiverDirectionSendrecv: - return []RTPTransceiverDirection{RTPTransceiverDirectionRecvonly, RTPTransceiverDirectionSendrecv, RTPTransceiverDirectionSendonly} - case RTPTransceiverDirectionSendonly: return []RTPTransceiverDirection{RTPTransceiverDirectionRecvonly, RTPTransceiverDirectionSendrecv} + case RTPTransceiverDirectionSendonly: + return []RTPTransceiverDirection{RTPTransceiverDirectionRecvonly} case RTPTransceiverDirectionRecvonly: return []RTPTransceiverDirection{RTPTransceiverDirectionSendonly, RTPTransceiverDirectionSendrecv} default: diff --git a/vendor/github.com/pion/webrtc/v3/rtptransceiver_js.go b/vendor/github.com/pion/webrtc/v3/rtptransceiver_js.go index 43e129af3..0e761315f 100644 --- a/vendor/github.com/pion/webrtc/v3/rtptransceiver_js.go +++ b/vendor/github.com/pion/webrtc/v3/rtptransceiver_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/rtptransceiverdirection.go b/vendor/github.com/pion/webrtc/v3/rtptransceiverdirection.go index 752cd5b9c..307301473 100644 --- a/vendor/github.com/pion/webrtc/v3/rtptransceiverdirection.go +++ b/vendor/github.com/pion/webrtc/v3/rtptransceiverdirection.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // RTPTransceiverDirection indicates the direction of the RTPTransceiver. @@ -8,19 +5,19 @@ type RTPTransceiverDirection int const ( // RTPTransceiverDirectionSendrecv indicates the RTPSender will offer - // to send RTP and the RTPReceiver will offer to receive RTP. + // to send RTP and RTPReceiver the will offer to receive RTP. RTPTransceiverDirectionSendrecv RTPTransceiverDirection = iota + 1 // RTPTransceiverDirectionSendonly indicates the RTPSender will offer // to send RTP. RTPTransceiverDirectionSendonly - // RTPTransceiverDirectionRecvonly indicates the RTPReceiver will + // RTPTransceiverDirectionRecvonly indicates the RTPReceiver the will // offer to receive RTP. RTPTransceiverDirectionRecvonly // RTPTransceiverDirectionInactive indicates the RTPSender won't offer - // to send RTP and the RTPReceiver won't offer to receive RTP. + // to send RTP and RTPReceiver the won't offer to receive RTP. RTPTransceiverDirectionInactive ) diff --git a/vendor/github.com/pion/webrtc/v3/rtptransceiverinit.go b/vendor/github.com/pion/webrtc/v3/rtptransceiverinit.go index 3aac1dc14..3c439b7f7 100644 --- a/vendor/github.com/pion/webrtc/v3/rtptransceiverinit.go +++ b/vendor/github.com/pion/webrtc/v3/rtptransceiverinit.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // RTPTransceiverInit dictionary is used when calling the WebRTC function addTransceiver() to provide configuration options for the new transceiver. diff --git a/vendor/github.com/pion/webrtc/v3/sctpcapabilities.go b/vendor/github.com/pion/webrtc/v3/sctpcapabilities.go index c4c5ff5eb..34399d3b0 100644 --- a/vendor/github.com/pion/webrtc/v3/sctpcapabilities.go +++ b/vendor/github.com/pion/webrtc/v3/sctpcapabilities.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // SCTPCapabilities indicates the capabilities of the SCTPTransport. diff --git a/vendor/github.com/pion/webrtc/v3/sctptransport.go b/vendor/github.com/pion/webrtc/v3/sctptransport.go index c96fd173f..27e02ea65 100644 --- a/vendor/github.com/pion/webrtc/v3/sctptransport.go +++ b/vendor/github.com/pion/webrtc/v3/sctptransport.go @@ -1,13 +1,9 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js package webrtc import ( - "errors" "io" "math" "sync" @@ -95,7 +91,7 @@ func (r *SCTPTransport) GetCapabilities() SCTPCapabilities { // Start the SCTPTransport. Since both local and remote parties must mutually // create an SCTPTransport, SCTP SO (Simultaneous Open) is used to establish // a connection over SCTP. -func (r *SCTPTransport) Start(SCTPCapabilities) error { +func (r *SCTPTransport) Start(remoteCaps SCTPCapabilities) error { if r.isStarted { return nil } @@ -107,9 +103,8 @@ func (r *SCTPTransport) Start(SCTPCapabilities) error { } sctpAssociation, err := sctp.Client(sctp.Config{ - NetConn: dtlsTransport.conn, - MaxReceiveBufferSize: r.api.settingEngine.sctp.maxReceiveBufferSize, - LoggerFactory: r.api.settingEngine.LoggerFactory, + NetConn: dtlsTransport.conn, + LoggerFactory: r.api.settingEngine.LoggerFactory, }) if err != nil { return err @@ -179,7 +174,7 @@ ACCEPT: LoggerFactory: r.api.settingEngine.LoggerFactory, }, dataChannels...) if err != nil { - if !errors.Is(err, io.EOF) { + if err != io.EOF { r.log.Errorf("Failed to accept data channel: %v", err) r.onError(err) } @@ -227,7 +222,7 @@ ACCEPT: Ordered: ordered, MaxPacketLifeTime: maxPacketLifeTime, MaxRetransmits: maxRetransmits, - }, r, r.api.settingEngine.LoggerFactory.NewLogger("ortc")) + }, r.api.settingEngine.LoggerFactory.NewLogger("ortc")) if err != nil { r.log.Errorf("Failed to accept data channel: %v", err) r.onError(err) diff --git a/vendor/github.com/pion/webrtc/v3/sctptransport_js.go b/vendor/github.com/pion/webrtc/v3/sctptransport_js.go index 7ab6c3900..5a4d1573e 100644 --- a/vendor/github.com/pion/webrtc/v3/sctptransport_js.go +++ b/vendor/github.com/pion/webrtc/v3/sctptransport_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/sctptransportstate.go b/vendor/github.com/pion/webrtc/v3/sctptransportstate.go index 5dd51d6f5..8dc794162 100644 --- a/vendor/github.com/pion/webrtc/v3/sctptransportstate.go +++ b/vendor/github.com/pion/webrtc/v3/sctptransportstate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc // SCTPTransportState indicates the state of the SCTP transport. diff --git a/vendor/github.com/pion/webrtc/v3/sdp.go b/vendor/github.com/pion/webrtc/v3/sdp.go index a1c8daaba..c181bfe60 100644 --- a/vendor/github.com/pion/webrtc/v3/sdp.go +++ b/vendor/github.com/pion/webrtc/v3/sdp.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -43,12 +40,8 @@ func trackDetailsForSSRC(trackDetails []trackDetails, ssrc SSRC) *trackDetails { return nil } -func trackDetailsForRID(trackDetails []trackDetails, mid, rid string) *trackDetails { +func trackDetailsForRID(trackDetails []trackDetails, rid string) *trackDetails { for i := range trackDetails { - if trackDetails[i].mid != mid { - continue - } - for j := range trackDetails[i].rids { if trackDetails[i].rids[j] == rid { return &trackDetails[i] @@ -347,60 +340,7 @@ func populateLocalCandidates(sessionDescription *SessionDescription, i *ICEGathe } } -func addSenderSDP( - mediaSection mediaSection, - isPlanB bool, - media *sdp.MediaDescription, -) { - for _, mt := range mediaSection.transceivers { - sender := mt.Sender() - if sender == nil { - continue - } - - track := sender.Track() - if track == nil { - continue - } - - sendParameters := sender.GetParameters() - for _, encoding := range sendParameters.Encodings { - media = media.WithMediaSource(uint32(encoding.SSRC), track.StreamID() /* cname */, track.StreamID() /* streamLabel */, track.ID()) - if !isPlanB { - media = media.WithPropertyAttribute("msid:" + track.StreamID() + " " + track.ID()) - } - } - - if len(sendParameters.Encodings) > 1 { - sendRids := make([]string, 0, len(sendParameters.Encodings)) - - for _, encoding := range sendParameters.Encodings { - media.WithValueAttribute(sdpAttributeRid, encoding.RID+" send") - sendRids = append(sendRids, encoding.RID) - } - // Simulcast - media.WithValueAttribute("simulcast", "send "+strings.Join(sendRids, ";")) - } - - if !isPlanB { - break - } - } -} - -func addTransceiverSDP( - d *sdp.SessionDescription, - isPlanB bool, - shouldAddCandidates bool, - dtlsFingerprints []DTLSFingerprint, - mediaEngine *MediaEngine, - midValue string, - iceParams ICEParameters, - candidates []ICECandidate, - dtlsRole sdp.ConnectionRole, - iceGatheringState ICEGatheringState, - mediaSection mediaSection, -) (bool, error) { +func addTransceiverSDP(d *sdp.SessionDescription, isPlanB, shouldAddCandidates bool, dtlsFingerprints []DTLSFingerprint, mediaEngine *MediaEngine, midValue string, iceParams ICEParameters, candidates []ICECandidate, dtlsRole sdp.ConnectionRole, iceGatheringState ICEGatheringState, mediaSection mediaSection) (bool, error) { transceivers := mediaSection.transceivers if len(transceivers) < 1 { return false, errSDPZeroTransceivers @@ -431,10 +371,6 @@ func addTransceiverSDP( } // Explicitly reject track if we don't have the codec - // We need to include connection information even if we're rejecting a track, otherwise Firefox will fail to - // parse the SDP with an error like: - // SIPCC Failed to parse SDP: SDP Parse Error on line 50: c= connection line not specified for every media level, validation failed. - // In addition this makes our SDP compliant with RFC 4566 Section 5.7: https://datatracker.ietf.org/doc/html/rfc4566#section-5.7 d.WithMedia(&sdp.MediaDescription{ MediaName: sdp.MediaName{ Media: t.kind.String(), @@ -442,13 +378,6 @@ func addTransceiverSDP( Protos: []string{"UDP", "TLS", "RTP", "SAVPF"}, Formats: []string{"0"}, }, - ConnectionInformation: &sdp.ConnectionInformation{ - NetworkType: "IN", - AddressType: "IP4", - Address: &sdp.Address{ - Address: "0.0.0.0", - }, - }, }) return false, nil } @@ -481,7 +410,16 @@ func addTransceiverSDP( media.WithValueAttribute("simulcast", "recv "+strings.Join(recvRids, ";")) } - addSenderSDP(mediaSection, isPlanB, media) + for _, mt := range transceivers { + if sender := mt.Sender(); sender != nil && sender.Track() != nil { + track := sender.Track() + media = media.WithMediaSource(uint32(sender.ssrc), track.StreamID() /* cname */, track.StreamID() /* streamLabel */, track.ID()) + if !isPlanB { + media = media.WithPropertyAttribute("msid:" + track.StreamID() + " " + track.ID()) + break + } + } + } media = media.WithPropertyAttribute(t.Direction().String()) @@ -508,7 +446,7 @@ type mediaSection struct { } // populateSDP serializes a PeerConnections state into an SDP -func populateSDP(d *sdp.SessionDescription, isPlanB bool, dtlsFingerprints []DTLSFingerprint, mediaDescriptionFingerprint bool, isICELite bool, isExtmapAllowMixed bool, mediaEngine *MediaEngine, connectionRole sdp.ConnectionRole, candidates []ICECandidate, iceParams ICEParameters, mediaSections []mediaSection, iceGatheringState ICEGatheringState) (*sdp.SessionDescription, error) { +func populateSDP(d *sdp.SessionDescription, isPlanB bool, dtlsFingerprints []DTLSFingerprint, mediaDescriptionFingerprint bool, isICELite bool, mediaEngine *MediaEngine, connectionRole sdp.ConnectionRole, candidates []ICECandidate, iceParams ICEParameters, mediaSections []mediaSection, iceGatheringState ICEGatheringState) (*sdp.SessionDescription, error) { var err error mediaDtlsFingerprints := []DTLSFingerprint{} @@ -556,11 +494,7 @@ func populateSDP(d *sdp.SessionDescription, isPlanB bool, dtlsFingerprints []DTL if isICELite { // RFC 5245 S15.3 - d = d.WithValueAttribute(sdp.AttrKeyICELite, "") - } - - if isExtmapAllowMixed { - d = d.WithPropertyAttribute(sdp.AttrKeyExtMapAllowMixed) + d = d.WithValueAttribute(sdp.AttrKeyICELite, sdp.AttrKeyICELite) } return d.WithValueAttribute(sdp.AttrKeyGroup, bundleValue), nil @@ -575,29 +509,7 @@ func getMidValue(media *sdp.MediaDescription) string { return "" } -// SessionDescription contains a MediaSection with Multiple SSRCs, it is Plan-B -func descriptionIsPlanB(desc *SessionDescription, log logging.LeveledLogger) bool { - if desc == nil || desc.parsed == nil { - return false - } - - // Store all MIDs that already contain a track - midWithTrack := map[string]bool{} - - for _, trackDetail := range trackDetailsFromSDP(log, desc.parsed) { - if _, ok := midWithTrack[trackDetail.mid]; ok { - return true - } - midWithTrack[trackDetail.mid] = true - } - - return false -} - -// SessionDescription contains a MediaSection with name `audio`, `video` or `data` -// If only one SSRC is set we can't know if it is Plan-B or Unified. If users have -// set fallback mode assume it is Plan-B -func descriptionPossiblyPlanB(desc *SessionDescription) bool { +func descriptionIsPlanB(desc *SessionDescription) bool { if desc == nil || desc.parsed == nil { return false } @@ -747,7 +659,7 @@ func codecsFromMediaDescription(m *sdp.MediaDescription) (out []RTPCodecParamete } for _, payloadStr := range m.MediaName.Formats { - payloadType, err := strconv.ParseUint(payloadStr, 10, 8) + payloadType, err := strconv.Atoi(payloadStr) if err != nil { return nil, err } @@ -761,7 +673,7 @@ func codecsFromMediaDescription(m *sdp.MediaDescription) (out []RTPCodecParamete } channels := uint16(0) - val, err := strconv.ParseUint(codec.EncodingParameters, 10, 16) + val, err := strconv.Atoi(codec.EncodingParameters) if err == nil { channels = uint16(val) } @@ -830,13 +742,3 @@ func isIceLiteSet(desc *sdp.SessionDescription) bool { return false } - -func isExtMapAllowMixedSet(desc *sdp.SessionDescription) bool { - for _, a := range desc.Attributes { - if strings.TrimSpace(a.Key) == sdp.AttrKeyExtMapAllowMixed { - return true - } - } - - return false -} diff --git a/vendor/github.com/pion/webrtc/v3/sdpsemantics.go b/vendor/github.com/pion/webrtc/v3/sdpsemantics.go index 6d6335047..b8d396c9b 100644 --- a/vendor/github.com/pion/webrtc/v3/sdpsemantics.go +++ b/vendor/github.com/pion/webrtc/v3/sdpsemantics.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/sdptype.go b/vendor/github.com/pion/webrtc/v3/sdptype.go index 0c6d1d464..bd49b6d14 100644 --- a/vendor/github.com/pion/webrtc/v3/sdptype.go +++ b/vendor/github.com/pion/webrtc/v3/sdptype.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/sessiondescription.go b/vendor/github.com/pion/webrtc/v3/sessiondescription.go index 12cdf0dd6..5b9339153 100644 --- a/vendor/github.com/pion/webrtc/v3/sessiondescription.go +++ b/vendor/github.com/pion/webrtc/v3/sessiondescription.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/settingengine.go b/vendor/github.com/pion/webrtc/v3/settingengine.go index b11c625e4..a2f5ef418 100644 --- a/vendor/github.com/pion/webrtc/v3/settingengine.go +++ b/vendor/github.com/pion/webrtc/v3/settingengine.go @@ -1,25 +1,17 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js package webrtc import ( - "context" - "crypto/x509" "io" - "net" "time" "github.com/pion/dtls/v2" - dtlsElliptic "github.com/pion/dtls/v2/pkg/crypto/elliptic" "github.com/pion/ice/v2" "github.com/pion/logging" - "github.com/pion/transport/v2" - "github.com/pion/transport/v2/packetio" - "github.com/pion/transport/v2/vnet" + "github.com/pion/transport/packetio" + "github.com/pion/transport/vnet" "golang.org/x/net/proxy" ) @@ -44,17 +36,15 @@ type SettingEngine struct { ICERelayAcceptanceMinWait *time.Duration } candidates struct { - ICELite bool - ICENetworkTypes []NetworkType - InterfaceFilter func(string) bool - IPFilter func(net.IP) bool - NAT1To1IPs []string - NAT1To1IPCandidateType ICECandidateType - MulticastDNSMode ice.MulticastDNSMode - MulticastDNSHostName string - UsernameFragment string - Password string - IncludeLoopbackCandidate bool + ICELite bool + ICENetworkTypes []NetworkType + InterfaceFilter func(string) bool + NAT1To1IPs []string + NAT1To1IPCandidateType ICECandidateType + MulticastDNSMode ice.MulticastDNSMode + MulticastDNSHostName string + UsernameFragment string + Password string } replayProtection struct { DTLS *uint @@ -62,25 +52,14 @@ type SettingEngine struct { SRTCP *uint } dtls struct { - insecureSkipHelloVerify bool - disableInsecureSkipVerify bool - retransmissionInterval time.Duration - ellipticCurves []dtlsElliptic.Curve - connectContextMaker func() (context.Context, func()) - extendedMasterSecret dtls.ExtendedMasterSecretType - clientAuth *dtls.ClientAuthType - clientCAs *x509.CertPool - rootCAs *x509.CertPool - } - sctp struct { - maxReceiveBufferSize uint32 + retransmissionInterval time.Duration } sdpMediaLevelFingerprints bool answeringDTLSRole DTLSRole disableCertificateFingerprintVerification bool disableSRTPReplayProtection bool disableSRTCPReplayProtection bool - net transport.Net + vnet *vnet.Net BufferFactory func(packetType packetio.BufferPacketType, ssrc uint32) io.ReadWriteCloser LoggerFactory logging.LoggerFactory iceTCPMux ice.TCPMux @@ -114,18 +93,9 @@ func (e *SettingEngine) SetSRTPProtectionProfiles(profiles ...dtls.SRTPProtectio } // SetICETimeouts sets the behavior around ICE Timeouts -// -// disconnectedTimeout: -// -// Duration without network activity before an Agent is considered disconnected. Default is 5 Seconds -// -// failedTimeout: -// -// Duration without network activity before an Agent is considered failed after disconnected. Default is 25 Seconds -// -// keepAliveInterval: -// -// How often the ICE Agent sends extra traffic if there is no activity, if media is flowing no traffic will be sent. Default is 2 seconds +// * disconnectedTimeout is the duration without network activity before a Agent is considered disconnected. Default is 5 Seconds +// * failedTimeout is the duration without network activity before a Agent is considered failed after disconnected. Default is 25 Seconds +// * keepAliveInterval is how often the ICE Agent sends extra traffic if there is no activity, if media is flowing no traffic will be sent. Default is 2 seconds func (e *SettingEngine) SetICETimeouts(disconnectedTimeout, failedTimeout, keepAliveInterval time.Duration) { e.timeout.ICEDisconnectedTimeout = &disconnectedTimeout e.timeout.ICEFailedTimeout = &failedTimeout @@ -155,9 +125,6 @@ func (e *SettingEngine) SetRelayAcceptanceMinWait(t time.Duration) { // SetEphemeralUDPPortRange limits the pool of ephemeral ports that // ICE UDP connections can allocate from. This affects both host candidates, // and the local address of server reflexive candidates. -// -// When portMin and portMax are left to the 0 default value, pion/ice candidate -// gatherer replaces them and uses 1 for portMin and 65535 for portMax. func (e *SettingEngine) SetEphemeralUDPPortRange(portMin, portMax uint16) error { if portMax < portMin { return ice.ErrPort @@ -187,17 +154,9 @@ func (e *SettingEngine) SetInterfaceFilter(filter func(string) bool) { e.candidates.InterfaceFilter = filter } -// SetIPFilter sets the filtering functions when gathering ICE candidates -// This can be used to exclude certain ip from ICE. Which may be -// useful if you know a certain ip will never succeed, or if you wish to reduce -// the amount of information you wish to expose to the remote peer -func (e *SettingEngine) SetIPFilter(filter func(net.IP) bool) { - e.candidates.IPFilter = filter -} - // SetNAT1To1IPs sets a list of external IP addresses of 1:1 (D)NAT // and a candidate type for which the external IP address is used. -// This is useful when you host a server using Pion on an AWS EC2 instance +// This is useful when you are host a server using Pion on an AWS EC2 instance // which has a private address, behind a 1:1 DNAT with a public IP (e.g. // Elastic IP). In this case, you can give the public IP address so that // Pion will use the public IP address in its candidate instead of the private @@ -206,12 +165,10 @@ func (e *SettingEngine) SetIPFilter(filter func(net.IP) bool) { // Two types of candidates are supported: // // ICECandidateTypeHost: -// -// The public IP address will be used for the host candidate in the SDP. -// +// The public IP address will be used for the host candidate in the SDP. // ICECandidateTypeSrflx: -// -// A server reflexive candidate with the given public IP address will be added to the SDP. +// A server reflexive candidate with the given public IP address will be added +// to the SDP. // // Please note that if you choose ICECandidateTypeHost, then the private IP address // won't be advertised with the peer. Also, this option cannot be used along with mDNS. @@ -225,23 +182,14 @@ func (e *SettingEngine) SetNAT1To1IPs(ips []string, candidateType ICECandidateTy e.candidates.NAT1To1IPCandidateType = candidateType } -// SetIncludeLoopbackCandidate enable pion to gather loopback candidates, it is useful -// for some VM have public IP mapped to loopback interface -func (e *SettingEngine) SetIncludeLoopbackCandidate(include bool) { - e.candidates.IncludeLoopbackCandidate = include -} - // SetAnsweringDTLSRole sets the DTLS role that is selected when offering // The DTLS role controls if the WebRTC Client as a client or server. This // may be useful when interacting with non-compliant clients or debugging issues. // // DTLSRoleActive: -// -// Act as DTLS Client, send the ClientHello and starts the handshake -// +// Act as DTLS Client, send the ClientHello and starts the handshake // DTLSRolePassive: -// -// Act as DTLS Server, wait for ClientHello +// Act as DTLS Server, wait for ClientHello func (e *SettingEngine) SetAnsweringDTLSRole(role DTLSRole) error { if role != DTLSRoleClient && role != DTLSRoleServer { return errSettingEngineSetAnsweringDTLSRole @@ -256,17 +204,8 @@ func (e *SettingEngine) SetAnsweringDTLSRole(role DTLSRole) error { // VNet is a virtual network layer for Pion, allowing users to simulate // different topologies, latency, loss and jitter. This can be useful for // learning WebRTC concepts or testing your application in a lab environment -// Deprecated: Please use SetNet() func (e *SettingEngine) SetVNet(vnet *vnet.Net) { - e.SetNet(vnet) -} - -// SetNet sets the Net instance that is passed to pion/ice -// -// Net is an network interface layer for Pion, allowing users to replace -// Pions network stack with a custom implementation. -func (e *SettingEngine) SetNet(net transport.Net) { - e.net = net + e.vnet = vnet } // SetICEMulticastDNSMode controls if pion/ice queries and generates mDNS ICE Candidates @@ -365,59 +304,3 @@ func (e *SettingEngine) SetReceiveMTU(receiveMTU uint) { func (e *SettingEngine) SetDTLSRetransmissionInterval(interval time.Duration) { e.dtls.retransmissionInterval = interval } - -// SetDTLSInsecureSkipHelloVerify sets the skip HelloVerify flag for DTLS. -// If true and when acting as DTLS server, will allow client to skip hello verify phase and -// receive ServerHello after initial ClientHello. This will mean faster connect times, -// but will have lower DoS attack resistance. -func (e *SettingEngine) SetDTLSInsecureSkipHelloVerify(skip bool) { - e.dtls.insecureSkipHelloVerify = skip -} - -// SetDTLSDisableInsecureSkipVerify sets the disable skip insecure verify flag for DTLS. -// This controls whether a client verifies the server's certificate chain and host name. -func (e *SettingEngine) SetDTLSDisableInsecureSkipVerify(disable bool) { - e.dtls.disableInsecureSkipVerify = disable -} - -// SetDTLSEllipticCurves sets the elliptic curves for DTLS. -func (e *SettingEngine) SetDTLSEllipticCurves(ellipticCurves ...dtlsElliptic.Curve) { - e.dtls.ellipticCurves = ellipticCurves -} - -// SetDTLSConnectContextMaker sets the context used during the DTLS Handshake. -// It can be used to extend or reduce the timeout on the DTLS Handshake. -// If nil, the default dtls.ConnectContextMaker is used. It can be implemented as following. -// -// func ConnectContextMaker() (context.Context, func()) { -// return context.WithTimeout(context.Background(), 30*time.Second) -// } -func (e *SettingEngine) SetDTLSConnectContextMaker(connectContextMaker func() (context.Context, func())) { - e.dtls.connectContextMaker = connectContextMaker -} - -// SetDTLSExtendedMasterSecret sets the extended master secret type for DTLS. -func (e *SettingEngine) SetDTLSExtendedMasterSecret(extendedMasterSecret dtls.ExtendedMasterSecretType) { - e.dtls.extendedMasterSecret = extendedMasterSecret -} - -// SetDTLSClientAuth sets the client auth type for DTLS. -func (e *SettingEngine) SetDTLSClientAuth(clientAuth dtls.ClientAuthType) { - e.dtls.clientAuth = &clientAuth -} - -// SetDTLSClientCAs sets the client CA certificate pool for DTLS certificate verification. -func (e *SettingEngine) SetDTLSClientCAs(clientCAs *x509.CertPool) { - e.dtls.clientCAs = clientCAs -} - -// SetDTLSRootCAs sets the root CA certificate pool for DTLS certificate verification. -func (e *SettingEngine) SetDTLSRootCAs(rootCAs *x509.CertPool) { - e.dtls.rootCAs = rootCAs -} - -// SetSCTPMaxReceiveBufferSize sets the maximum receive buffer size. -// Leave this 0 for the default maxReceiveBufferSize. -func (e *SettingEngine) SetSCTPMaxReceiveBufferSize(maxReceiveBufferSize uint32) { - e.sctp.maxReceiveBufferSize = maxReceiveBufferSize -} diff --git a/vendor/github.com/pion/webrtc/v3/settingengine_js.go b/vendor/github.com/pion/webrtc/v3/settingengine_js.go index 0069d04eb..a4ae0d0ee 100644 --- a/vendor/github.com/pion/webrtc/v3/settingengine_js.go +++ b/vendor/github.com/pion/webrtc/v3/settingengine_js.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build js && wasm // +build js,wasm diff --git a/vendor/github.com/pion/webrtc/v3/signalingstate.go b/vendor/github.com/pion/webrtc/v3/signalingstate.go index 42911c9af..b64dffca8 100644 --- a/vendor/github.com/pion/webrtc/v3/signalingstate.go +++ b/vendor/github.com/pion/webrtc/v3/signalingstate.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/srtp_writer_future.go b/vendor/github.com/pion/webrtc/v3/srtp_writer_future.go index 6855e8d30..942996748 100644 --- a/vendor/github.com/pion/webrtc/v3/srtp_writer_future.go +++ b/vendor/github.com/pion/webrtc/v3/srtp_writer_future.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -19,7 +16,6 @@ import ( // srtpWriterFuture blocks Read/Write calls until // the SRTP Session is available type srtpWriterFuture struct { - ssrc SSRC rtpSender *RTPSender rtcpReadStream atomic.Value // *srtp.ReadStreamSRTCP rtpWriteStream atomic.Value // *srtp.WriteStreamSRTP @@ -56,7 +52,7 @@ func (s *srtpWriterFuture) init(returnWhenNoSRTP bool) error { return err } - rtcpReadStream, err := srtcpSession.OpenReadStream(uint32(s.ssrc)) + rtcpReadStream, err := srtcpSession.OpenReadStream(uint32(s.rtpSender.ssrc)) if err != nil { return err } @@ -85,16 +81,16 @@ func (s *srtpWriterFuture) Close() error { } s.closed = true - if value, ok := s.rtcpReadStream.Load().(*srtp.ReadStreamSRTCP); ok { - return value.Close() + if value := s.rtcpReadStream.Load(); value != nil { + return value.(*srtp.ReadStreamSRTCP).Close() } return nil } func (s *srtpWriterFuture) Read(b []byte) (n int, err error) { - if value, ok := s.rtcpReadStream.Load().(*srtp.ReadStreamSRTCP); ok { - return value.Read(b) + if value := s.rtcpReadStream.Load(); value != nil { + return value.(*srtp.ReadStreamSRTCP).Read(b) } if err := s.init(false); err != nil || s.rtcpReadStream.Load() == nil { @@ -105,8 +101,8 @@ func (s *srtpWriterFuture) Read(b []byte) (n int, err error) { } func (s *srtpWriterFuture) SetReadDeadline(t time.Time) error { - if value, ok := s.rtcpReadStream.Load().(*srtp.ReadStreamSRTCP); ok { - return value.SetReadDeadline(t) + if value := s.rtcpReadStream.Load(); value != nil { + return value.(*srtp.ReadStreamSRTCP).SetReadDeadline(t) } if err := s.init(false); err != nil || s.rtcpReadStream.Load() == nil { @@ -117,8 +113,8 @@ func (s *srtpWriterFuture) SetReadDeadline(t time.Time) error { } func (s *srtpWriterFuture) WriteRTP(header *rtp.Header, payload []byte) (int, error) { - if value, ok := s.rtpWriteStream.Load().(*srtp.WriteStreamSRTP); ok { - return value.WriteRTP(header, payload) + if value := s.rtpWriteStream.Load(); value != nil { + return value.(*srtp.WriteStreamSRTP).WriteRTP(header, payload) } if err := s.init(true); err != nil || s.rtpWriteStream.Load() == nil { @@ -129,8 +125,8 @@ func (s *srtpWriterFuture) WriteRTP(header *rtp.Header, payload []byte) (int, er } func (s *srtpWriterFuture) Write(b []byte) (int, error) { - if value, ok := s.rtpWriteStream.Load().(*srtp.WriteStreamSRTP); ok { - return value.Write(b) + if value := s.rtpWriteStream.Load(); value != nil { + return value.(*srtp.WriteStreamSRTP).Write(b) } if err := s.init(true); err != nil || s.rtpWriteStream.Load() == nil { diff --git a/vendor/github.com/pion/webrtc/v3/stats.go b/vendor/github.com/pion/webrtc/v3/stats.go index 5a43cb722..a218d9e8f 100644 --- a/vendor/github.com/pion/webrtc/v3/stats.go +++ b/vendor/github.com/pion/webrtc/v3/stats.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc import ( diff --git a/vendor/github.com/pion/webrtc/v3/stats_go.go b/vendor/github.com/pion/webrtc/v3/stats_go.go index a9a8e2156..10ec55c96 100644 --- a/vendor/github.com/pion/webrtc/v3/stats_go.go +++ b/vendor/github.com/pion/webrtc/v3/stats_go.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js diff --git a/vendor/github.com/pion/webrtc/v3/track_local.go b/vendor/github.com/pion/webrtc/v3/track_local.go index a2e6599a5..0002e6095 100644 --- a/vendor/github.com/pion/webrtc/v3/track_local.go +++ b/vendor/github.com/pion/webrtc/v3/track_local.go @@ -1,12 +1,6 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - package webrtc -import ( - "github.com/pion/interceptor" - "github.com/pion/rtp" -) +import "github.com/pion/rtp" // TrackLocalWriter is the Writer for outbound RTP Packets type TrackLocalWriter interface { @@ -20,11 +14,10 @@ type TrackLocalWriter interface { // TrackLocalContext is the Context passed when a TrackLocal has been Binded/Unbinded from a PeerConnection, and used // in Interceptors. type TrackLocalContext struct { - id string - params RTPParameters - ssrc SSRC - writeStream TrackLocalWriter - rtcpInterceptor interceptor.RTCPReader + id string + params RTPParameters + ssrc SSRC + writeStream TrackLocalWriter } // CodecParameters returns the negotiated RTPCodecParameters. These are the codecs supported by both @@ -56,11 +49,6 @@ func (t *TrackLocalContext) ID() string { return t.id } -// RTCPReader returns the RTCP interceptor for this TrackLocal. Used to read RTCP of this TrackLocal. -func (t *TrackLocalContext) RTCPReader() interceptor.RTCPReader { - return t.rtcpInterceptor -} - // TrackLocal is an interface that controls how the user can send media // The user can provide their own TrackLocal implementations, or use // the implementations in pkg/media diff --git a/vendor/github.com/pion/webrtc/v3/track_local_static.go b/vendor/github.com/pion/webrtc/v3/track_local_static.go index 17ce0587a..f1ca8b9e0 100644 --- a/vendor/github.com/pion/webrtc/v3/track_local_static.go +++ b/vendor/github.com/pion/webrtc/v3/track_local_static.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js @@ -131,27 +128,18 @@ var rtpPacketPool = sync.Pool{ }, } -func resetPacketPoolAllocation(localPacket *rtp.Packet) { - *localPacket = rtp.Packet{} - rtpPacketPool.Put(localPacket) -} - -func getPacketAllocationFromPool() *rtp.Packet { - ipacket := rtpPacketPool.Get() - return ipacket.(*rtp.Packet) //nolint:forcetypeassert -} - // WriteRTP writes a RTP Packet to the TrackLocalStaticRTP // If one PeerConnection fails the packets will still be sent to // all PeerConnections. The error message will contain the ID of the failed // PeerConnections so you can remove them func (s *TrackLocalStaticRTP) WriteRTP(p *rtp.Packet) error { - packet := getPacketAllocationFromPool() - - defer resetPacketPoolAllocation(packet) - + ipacket := rtpPacketPool.Get() + packet := ipacket.(*rtp.Packet) + defer func() { + *packet = rtp.Packet{} + rtpPacketPool.Put(ipacket) + }() *packet = *p - return s.writeRTP(packet) } @@ -178,9 +166,12 @@ func (s *TrackLocalStaticRTP) writeRTP(p *rtp.Packet) error { // all PeerConnections. The error message will contain the ID of the failed // PeerConnections so you can remove them func (s *TrackLocalStaticRTP) Write(b []byte) (n int, err error) { - packet := getPacketAllocationFromPool() - - defer resetPacketPoolAllocation(packet) + ipacket := rtpPacketPool.Get() + packet := ipacket.(*rtp.Packet) + defer func() { + *packet = rtp.Packet{} + rtpPacketPool.Put(ipacket) + }() if err = packet.Unmarshal(b); err != nil { return 0, err @@ -291,9 +282,9 @@ func (s *TrackLocalStaticSample) WriteSample(sample media.Sample) error { samples := uint32(sample.Duration.Seconds() * clockRate) if sample.PrevDroppedPackets > 0 { - p.SkipSamples(samples * uint32(sample.PrevDroppedPackets)) + p.(rtp.Packetizer).SkipSamples(samples * uint32(sample.PrevDroppedPackets)) } - packets := p.Packetize(sample.Data, samples) + packets := p.(rtp.Packetizer).Packetize(sample.Data, samples) writeErrs := []error{} for _, p := range packets { diff --git a/vendor/github.com/pion/webrtc/v3/track_remote.go b/vendor/github.com/pion/webrtc/v3/track_remote.go index 150b91bc9..e98620c31 100644 --- a/vendor/github.com/pion/webrtc/v3/track_remote.go +++ b/vendor/github.com/pion/webrtc/v3/track_remote.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - //go:build !js // +build !js diff --git a/vendor/github.com/pion/webrtc/v3/webrtc.go b/vendor/github.com/pion/webrtc/v3/webrtc.go index 2781c8d1c..ff32a5578 100644 --- a/vendor/github.com/pion/webrtc/v3/webrtc.go +++ b/vendor/github.com/pion/webrtc/v3/webrtc.go @@ -1,6 +1,3 @@ -// SPDX-FileCopyrightText: 2023 The Pion community -// SPDX-License-Identifier: MIT - // Package webrtc implements the WebRTC 1.0 as defined in W3C WebRTC specification document. package webrtc diff --git a/vendor/github.com/pion/webrtc/v3/yarn.lock b/vendor/github.com/pion/webrtc/v3/yarn.lock index 01bf7823d..90f73c219 100644 --- a/vendor/github.com/pion/webrtc/v3/yarn.lock +++ b/vendor/github.com/pion/webrtc/v3/yarn.lock @@ -1,8 +1,6 @@ # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 -# SPDX-FileCopyrightText: 2023 The Pion community -# SPDX-License-Identifier: MIT abbrev@1: version "1.1.1" diff --git a/vendor/github.com/quic-go/qtls-go1-19/LICENSE b/vendor/github.com/quic-go/qtls-go1-19/LICENSE new file mode 100644 index 000000000..6a66aea5e --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2009 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/quic-go/qtls-go1-19/README.md b/vendor/github.com/quic-go/qtls-go1-19/README.md new file mode 100644 index 000000000..bf41f1c5f --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/README.md @@ -0,0 +1,6 @@ +# qtls + +[![Go Reference](https://pkg.go.dev/badge/github.com/quic-go/qtls-go1-19.svg)](https://pkg.go.dev/github.com/quic-go/qtls-go1-19) +[![.github/workflows/go-test.yml](https://github.com/quic-go/qtls-go1-19/actions/workflows/go-test.yml/badge.svg)](https://github.com/quic-go/qtls-go1-19/actions/workflows/go-test.yml) + +This repository contains a modified version of the standard library's TLS implementation, modified for the QUIC protocol. It is used by [quic-go](https://github.com/lucas-clemente/quic-go). diff --git a/vendor/github.com/quic-go/qtls-go1-19/alert.go b/vendor/github.com/quic-go/qtls-go1-19/alert.go new file mode 100644 index 000000000..3feac79be --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/alert.go @@ -0,0 +1,102 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import "strconv" + +type alert uint8 + +// Alert is a TLS alert +type Alert = alert + +const ( + // alert level + alertLevelWarning = 1 + alertLevelError = 2 +) + +const ( + alertCloseNotify alert = 0 + alertUnexpectedMessage alert = 10 + alertBadRecordMAC alert = 20 + alertDecryptionFailed alert = 21 + alertRecordOverflow alert = 22 + alertDecompressionFailure alert = 30 + alertHandshakeFailure alert = 40 + alertBadCertificate alert = 42 + alertUnsupportedCertificate alert = 43 + alertCertificateRevoked alert = 44 + alertCertificateExpired alert = 45 + alertCertificateUnknown alert = 46 + alertIllegalParameter alert = 47 + alertUnknownCA alert = 48 + alertAccessDenied alert = 49 + alertDecodeError alert = 50 + alertDecryptError alert = 51 + alertExportRestriction alert = 60 + alertProtocolVersion alert = 70 + alertInsufficientSecurity alert = 71 + alertInternalError alert = 80 + alertInappropriateFallback alert = 86 + alertUserCanceled alert = 90 + alertNoRenegotiation alert = 100 + alertMissingExtension alert = 109 + alertUnsupportedExtension alert = 110 + alertCertificateUnobtainable alert = 111 + alertUnrecognizedName alert = 112 + alertBadCertificateStatusResponse alert = 113 + alertBadCertificateHashValue alert = 114 + alertUnknownPSKIdentity alert = 115 + alertCertificateRequired alert = 116 + alertNoApplicationProtocol alert = 120 +) + +var alertText = map[alert]string{ + alertCloseNotify: "close notify", + alertUnexpectedMessage: "unexpected message", + alertBadRecordMAC: "bad record MAC", + alertDecryptionFailed: "decryption failed", + alertRecordOverflow: "record overflow", + alertDecompressionFailure: "decompression failure", + alertHandshakeFailure: "handshake failure", + alertBadCertificate: "bad certificate", + alertUnsupportedCertificate: "unsupported certificate", + alertCertificateRevoked: "revoked certificate", + alertCertificateExpired: "expired certificate", + alertCertificateUnknown: "unknown certificate", + alertIllegalParameter: "illegal parameter", + alertUnknownCA: "unknown certificate authority", + alertAccessDenied: "access denied", + alertDecodeError: "error decoding message", + alertDecryptError: "error decrypting message", + alertExportRestriction: "export restriction", + alertProtocolVersion: "protocol version not supported", + alertInsufficientSecurity: "insufficient security level", + alertInternalError: "internal error", + alertInappropriateFallback: "inappropriate fallback", + alertUserCanceled: "user canceled", + alertNoRenegotiation: "no renegotiation", + alertMissingExtension: "missing extension", + alertUnsupportedExtension: "unsupported extension", + alertCertificateUnobtainable: "certificate unobtainable", + alertUnrecognizedName: "unrecognized name", + alertBadCertificateStatusResponse: "bad certificate status response", + alertBadCertificateHashValue: "bad certificate hash value", + alertUnknownPSKIdentity: "unknown PSK identity", + alertCertificateRequired: "certificate required", + alertNoApplicationProtocol: "no application protocol", +} + +func (e alert) String() string { + s, ok := alertText[e] + if ok { + return "tls: " + s + } + return "tls: alert(" + strconv.Itoa(int(e)) + ")" +} + +func (e alert) Error() string { + return e.String() +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/auth.go b/vendor/github.com/quic-go/qtls-go1-19/auth.go new file mode 100644 index 000000000..effc9aced --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/auth.go @@ -0,0 +1,293 @@ +// Copyright 2017 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "bytes" + "crypto" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rsa" + "errors" + "fmt" + "hash" + "io" +) + +// verifyHandshakeSignature verifies a signature against pre-hashed +// (if required) handshake contents. +func verifyHandshakeSignature(sigType uint8, pubkey crypto.PublicKey, hashFunc crypto.Hash, signed, sig []byte) error { + switch sigType { + case signatureECDSA: + pubKey, ok := pubkey.(*ecdsa.PublicKey) + if !ok { + return fmt.Errorf("expected an ECDSA public key, got %T", pubkey) + } + if !ecdsa.VerifyASN1(pubKey, signed, sig) { + return errors.New("ECDSA verification failure") + } + case signatureEd25519: + pubKey, ok := pubkey.(ed25519.PublicKey) + if !ok { + return fmt.Errorf("expected an Ed25519 public key, got %T", pubkey) + } + if !ed25519.Verify(pubKey, signed, sig) { + return errors.New("Ed25519 verification failure") + } + case signaturePKCS1v15: + pubKey, ok := pubkey.(*rsa.PublicKey) + if !ok { + return fmt.Errorf("expected an RSA public key, got %T", pubkey) + } + if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, signed, sig); err != nil { + return err + } + case signatureRSAPSS: + pubKey, ok := pubkey.(*rsa.PublicKey) + if !ok { + return fmt.Errorf("expected an RSA public key, got %T", pubkey) + } + signOpts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash} + if err := rsa.VerifyPSS(pubKey, hashFunc, signed, sig, signOpts); err != nil { + return err + } + default: + return errors.New("internal error: unknown signature type") + } + return nil +} + +const ( + serverSignatureContext = "TLS 1.3, server CertificateVerify\x00" + clientSignatureContext = "TLS 1.3, client CertificateVerify\x00" +) + +var signaturePadding = []byte{ + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, +} + +// signedMessage returns the pre-hashed (if necessary) message to be signed by +// certificate keys in TLS 1.3. See RFC 8446, Section 4.4.3. +func signedMessage(sigHash crypto.Hash, context string, transcript hash.Hash) []byte { + if sigHash == directSigning { + b := &bytes.Buffer{} + b.Write(signaturePadding) + io.WriteString(b, context) + b.Write(transcript.Sum(nil)) + return b.Bytes() + } + h := sigHash.New() + h.Write(signaturePadding) + io.WriteString(h, context) + h.Write(transcript.Sum(nil)) + return h.Sum(nil) +} + +// typeAndHashFromSignatureScheme returns the corresponding signature type and +// crypto.Hash for a given TLS SignatureScheme. +func typeAndHashFromSignatureScheme(signatureAlgorithm SignatureScheme) (sigType uint8, hash crypto.Hash, err error) { + switch signatureAlgorithm { + case PKCS1WithSHA1, PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512: + sigType = signaturePKCS1v15 + case PSSWithSHA256, PSSWithSHA384, PSSWithSHA512: + sigType = signatureRSAPSS + case ECDSAWithSHA1, ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512: + sigType = signatureECDSA + case Ed25519: + sigType = signatureEd25519 + default: + return 0, 0, fmt.Errorf("unsupported signature algorithm: %v", signatureAlgorithm) + } + switch signatureAlgorithm { + case PKCS1WithSHA1, ECDSAWithSHA1: + hash = crypto.SHA1 + case PKCS1WithSHA256, PSSWithSHA256, ECDSAWithP256AndSHA256: + hash = crypto.SHA256 + case PKCS1WithSHA384, PSSWithSHA384, ECDSAWithP384AndSHA384: + hash = crypto.SHA384 + case PKCS1WithSHA512, PSSWithSHA512, ECDSAWithP521AndSHA512: + hash = crypto.SHA512 + case Ed25519: + hash = directSigning + default: + return 0, 0, fmt.Errorf("unsupported signature algorithm: %v", signatureAlgorithm) + } + return sigType, hash, nil +} + +// legacyTypeAndHashFromPublicKey returns the fixed signature type and crypto.Hash for +// a given public key used with TLS 1.0 and 1.1, before the introduction of +// signature algorithm negotiation. +func legacyTypeAndHashFromPublicKey(pub crypto.PublicKey) (sigType uint8, hash crypto.Hash, err error) { + switch pub.(type) { + case *rsa.PublicKey: + return signaturePKCS1v15, crypto.MD5SHA1, nil + case *ecdsa.PublicKey: + return signatureECDSA, crypto.SHA1, nil + case ed25519.PublicKey: + // RFC 8422 specifies support for Ed25519 in TLS 1.0 and 1.1, + // but it requires holding on to a handshake transcript to do a + // full signature, and not even OpenSSL bothers with the + // complexity, so we can't even test it properly. + return 0, 0, fmt.Errorf("tls: Ed25519 public keys are not supported before TLS 1.2") + default: + return 0, 0, fmt.Errorf("tls: unsupported public key: %T", pub) + } +} + +var rsaSignatureSchemes = []struct { + scheme SignatureScheme + minModulusBytes int + maxVersion uint16 +}{ + // RSA-PSS is used with PSSSaltLengthEqualsHash, and requires + // emLen >= hLen + sLen + 2 + {PSSWithSHA256, crypto.SHA256.Size()*2 + 2, VersionTLS13}, + {PSSWithSHA384, crypto.SHA384.Size()*2 + 2, VersionTLS13}, + {PSSWithSHA512, crypto.SHA512.Size()*2 + 2, VersionTLS13}, + // PKCS #1 v1.5 uses prefixes from hashPrefixes in crypto/rsa, and requires + // emLen >= len(prefix) + hLen + 11 + // TLS 1.3 dropped support for PKCS #1 v1.5 in favor of RSA-PSS. + {PKCS1WithSHA256, 19 + crypto.SHA256.Size() + 11, VersionTLS12}, + {PKCS1WithSHA384, 19 + crypto.SHA384.Size() + 11, VersionTLS12}, + {PKCS1WithSHA512, 19 + crypto.SHA512.Size() + 11, VersionTLS12}, + {PKCS1WithSHA1, 15 + crypto.SHA1.Size() + 11, VersionTLS12}, +} + +// signatureSchemesForCertificate returns the list of supported SignatureSchemes +// for a given certificate, based on the public key and the protocol version, +// and optionally filtered by its explicit SupportedSignatureAlgorithms. +// +// This function must be kept in sync with supportedSignatureAlgorithms. +// FIPS filtering is applied in the caller, selectSignatureScheme. +func signatureSchemesForCertificate(version uint16, cert *Certificate) []SignatureScheme { + priv, ok := cert.PrivateKey.(crypto.Signer) + if !ok { + return nil + } + + var sigAlgs []SignatureScheme + switch pub := priv.Public().(type) { + case *ecdsa.PublicKey: + if version != VersionTLS13 { + // In TLS 1.2 and earlier, ECDSA algorithms are not + // constrained to a single curve. + sigAlgs = []SignatureScheme{ + ECDSAWithP256AndSHA256, + ECDSAWithP384AndSHA384, + ECDSAWithP521AndSHA512, + ECDSAWithSHA1, + } + break + } + switch pub.Curve { + case elliptic.P256(): + sigAlgs = []SignatureScheme{ECDSAWithP256AndSHA256} + case elliptic.P384(): + sigAlgs = []SignatureScheme{ECDSAWithP384AndSHA384} + case elliptic.P521(): + sigAlgs = []SignatureScheme{ECDSAWithP521AndSHA512} + default: + return nil + } + case *rsa.PublicKey: + size := pub.Size() + sigAlgs = make([]SignatureScheme, 0, len(rsaSignatureSchemes)) + for _, candidate := range rsaSignatureSchemes { + if size >= candidate.minModulusBytes && version <= candidate.maxVersion { + sigAlgs = append(sigAlgs, candidate.scheme) + } + } + case ed25519.PublicKey: + sigAlgs = []SignatureScheme{Ed25519} + default: + return nil + } + + if cert.SupportedSignatureAlgorithms != nil { + var filteredSigAlgs []SignatureScheme + for _, sigAlg := range sigAlgs { + if isSupportedSignatureAlgorithm(sigAlg, cert.SupportedSignatureAlgorithms) { + filteredSigAlgs = append(filteredSigAlgs, sigAlg) + } + } + return filteredSigAlgs + } + return sigAlgs +} + +// selectSignatureScheme picks a SignatureScheme from the peer's preference list +// that works with the selected certificate. It's only called for protocol +// versions that support signature algorithms, so TLS 1.2 and 1.3. +func selectSignatureScheme(vers uint16, c *Certificate, peerAlgs []SignatureScheme) (SignatureScheme, error) { + supportedAlgs := signatureSchemesForCertificate(vers, c) + if len(supportedAlgs) == 0 { + return 0, unsupportedCertificateError(c) + } + if len(peerAlgs) == 0 && vers == VersionTLS12 { + // For TLS 1.2, if the client didn't send signature_algorithms then we + // can assume that it supports SHA1. See RFC 5246, Section 7.4.1.4.1. + peerAlgs = []SignatureScheme{PKCS1WithSHA1, ECDSAWithSHA1} + } + // Pick signature scheme in the peer's preference order, as our + // preference order is not configurable. + for _, preferredAlg := range peerAlgs { + if needFIPS() && !isSupportedSignatureAlgorithm(preferredAlg, fipsSupportedSignatureAlgorithms) { + continue + } + if isSupportedSignatureAlgorithm(preferredAlg, supportedAlgs) { + return preferredAlg, nil + } + } + return 0, errors.New("tls: peer doesn't support any of the certificate's signature algorithms") +} + +// unsupportedCertificateError returns a helpful error for certificates with +// an unsupported private key. +func unsupportedCertificateError(cert *Certificate) error { + switch cert.PrivateKey.(type) { + case rsa.PrivateKey, ecdsa.PrivateKey: + return fmt.Errorf("tls: unsupported certificate: private key is %T, expected *%T", + cert.PrivateKey, cert.PrivateKey) + case *ed25519.PrivateKey: + return fmt.Errorf("tls: unsupported certificate: private key is *ed25519.PrivateKey, expected ed25519.PrivateKey") + } + + signer, ok := cert.PrivateKey.(crypto.Signer) + if !ok { + return fmt.Errorf("tls: certificate private key (%T) does not implement crypto.Signer", + cert.PrivateKey) + } + + switch pub := signer.Public().(type) { + case *ecdsa.PublicKey: + switch pub.Curve { + case elliptic.P256(): + case elliptic.P384(): + case elliptic.P521(): + default: + return fmt.Errorf("tls: unsupported certificate curve (%s)", pub.Curve.Params().Name) + } + case *rsa.PublicKey: + return fmt.Errorf("tls: certificate RSA key size too small for supported signature algorithms") + case ed25519.PublicKey: + default: + return fmt.Errorf("tls: unsupported certificate key (%T)", pub) + } + + if cert.SupportedSignatureAlgorithms != nil { + return fmt.Errorf("tls: peer doesn't support the certificate custom signature algorithms") + } + + return fmt.Errorf("tls: internal error: unsupported key (%T)", cert.PrivateKey) +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/cipher_suites.go b/vendor/github.com/quic-go/qtls-go1-19/cipher_suites.go new file mode 100644 index 000000000..56dd45436 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/cipher_suites.go @@ -0,0 +1,693 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "crypto" + "crypto/aes" + "crypto/cipher" + "crypto/des" + "crypto/hmac" + "crypto/rc4" + "crypto/sha1" + "crypto/sha256" + "fmt" + "hash" + + "golang.org/x/crypto/chacha20poly1305" +) + +// CipherSuite is a TLS cipher suite. Note that most functions in this package +// accept and expose cipher suite IDs instead of this type. +type CipherSuite struct { + ID uint16 + Name string + + // Supported versions is the list of TLS protocol versions that can + // negotiate this cipher suite. + SupportedVersions []uint16 + + // Insecure is true if the cipher suite has known security issues + // due to its primitives, design, or implementation. + Insecure bool +} + +var ( + supportedUpToTLS12 = []uint16{VersionTLS10, VersionTLS11, VersionTLS12} + supportedOnlyTLS12 = []uint16{VersionTLS12} + supportedOnlyTLS13 = []uint16{VersionTLS13} +) + +// CipherSuites returns a list of cipher suites currently implemented by this +// package, excluding those with security issues, which are returned by +// InsecureCipherSuites. +// +// The list is sorted by ID. Note that the default cipher suites selected by +// this package might depend on logic that can't be captured by a static list, +// and might not match those returned by this function. +func CipherSuites() []*CipherSuite { + return []*CipherSuite{ + {TLS_RSA_WITH_AES_128_CBC_SHA, "TLS_RSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, false}, + {TLS_RSA_WITH_AES_256_CBC_SHA, "TLS_RSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, false}, + {TLS_RSA_WITH_AES_128_GCM_SHA256, "TLS_RSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, false}, + {TLS_RSA_WITH_AES_256_GCM_SHA384, "TLS_RSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, false}, + + {TLS_AES_128_GCM_SHA256, "TLS_AES_128_GCM_SHA256", supportedOnlyTLS13, false}, + {TLS_AES_256_GCM_SHA384, "TLS_AES_256_GCM_SHA384", supportedOnlyTLS13, false}, + {TLS_CHACHA20_POLY1305_SHA256, "TLS_CHACHA20_POLY1305_SHA256", supportedOnlyTLS13, false}, + + {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, false}, + {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, false}, + {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", supportedUpToTLS12, false}, + {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", supportedUpToTLS12, false}, + {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, false}, + {TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, false}, + {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", supportedOnlyTLS12, false}, + {TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", supportedOnlyTLS12, false}, + {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", supportedOnlyTLS12, false}, + {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", supportedOnlyTLS12, false}, + } +} + +// InsecureCipherSuites returns a list of cipher suites currently implemented by +// this package and which have security issues. +// +// Most applications should not use the cipher suites in this list, and should +// only use those returned by CipherSuites. +func InsecureCipherSuites() []*CipherSuite { + // This list includes RC4, CBC_SHA256, and 3DES cipher suites. See + // cipherSuitesPreferenceOrder for details. + return []*CipherSuite{ + {TLS_RSA_WITH_RC4_128_SHA, "TLS_RSA_WITH_RC4_128_SHA", supportedUpToTLS12, true}, + {TLS_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_RSA_WITH_3DES_EDE_CBC_SHA", supportedUpToTLS12, true}, + {TLS_RSA_WITH_AES_128_CBC_SHA256, "TLS_RSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true}, + {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA", supportedUpToTLS12, true}, + {TLS_ECDHE_RSA_WITH_RC4_128_SHA, "TLS_ECDHE_RSA_WITH_RC4_128_SHA", supportedUpToTLS12, true}, + {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", supportedUpToTLS12, true}, + {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true}, + {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", supportedOnlyTLS12, true}, + } +} + +// CipherSuiteName returns the standard name for the passed cipher suite ID +// (e.g. "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"), or a fallback representation +// of the ID value if the cipher suite is not implemented by this package. +func CipherSuiteName(id uint16) string { + for _, c := range CipherSuites() { + if c.ID == id { + return c.Name + } + } + for _, c := range InsecureCipherSuites() { + if c.ID == id { + return c.Name + } + } + return fmt.Sprintf("0x%04X", id) +} + +const ( + // suiteECDHE indicates that the cipher suite involves elliptic curve + // Diffie-Hellman. This means that it should only be selected when the + // client indicates that it supports ECC with a curve and point format + // that we're happy with. + suiteECDHE = 1 << iota + // suiteECSign indicates that the cipher suite involves an ECDSA or + // EdDSA signature and therefore may only be selected when the server's + // certificate is ECDSA or EdDSA. If this is not set then the cipher suite + // is RSA based. + suiteECSign + // suiteTLS12 indicates that the cipher suite should only be advertised + // and accepted when using TLS 1.2. + suiteTLS12 + // suiteSHA384 indicates that the cipher suite uses SHA384 as the + // handshake hash. + suiteSHA384 +) + +// A cipherSuite is a TLS 1.0–1.2 cipher suite, and defines the key exchange +// mechanism, as well as the cipher+MAC pair or the AEAD. +type cipherSuite struct { + id uint16 + // the lengths, in bytes, of the key material needed for each component. + keyLen int + macLen int + ivLen int + ka func(version uint16) keyAgreement + // flags is a bitmask of the suite* values, above. + flags int + cipher func(key, iv []byte, isRead bool) any + mac func(key []byte) hash.Hash + aead func(key, fixedNonce []byte) aead +} + +var cipherSuites = []*cipherSuite{ // TODO: replace with a map, since the order doesn't matter. + {TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadChaCha20Poly1305}, + {TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, 32, 0, 12, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, nil, nil, aeadChaCha20Poly1305}, + {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadAESGCM}, + {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, nil, nil, aeadAESGCM}, + {TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM}, + {TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM}, + {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheRSAKA, suiteECDHE | suiteTLS12, cipherAES, macSHA256, nil}, + {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil}, + {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, ecdheECDSAKA, suiteECDHE | suiteECSign | suiteTLS12, cipherAES, macSHA256, nil}, + {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherAES, macSHA1, nil}, + {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil}, + {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherAES, macSHA1, nil}, + {TLS_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, rsaKA, suiteTLS12, nil, nil, aeadAESGCM}, + {TLS_RSA_WITH_AES_256_GCM_SHA384, 32, 0, 4, rsaKA, suiteTLS12 | suiteSHA384, nil, nil, aeadAESGCM}, + {TLS_RSA_WITH_AES_128_CBC_SHA256, 16, 32, 16, rsaKA, suiteTLS12, cipherAES, macSHA256, nil}, + {TLS_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil}, + {TLS_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil}, + {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, ecdheRSAKA, suiteECDHE, cipher3DES, macSHA1, nil}, + {TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, rsaKA, 0, cipher3DES, macSHA1, nil}, + {TLS_RSA_WITH_RC4_128_SHA, 16, 20, 0, rsaKA, 0, cipherRC4, macSHA1, nil}, + {TLS_ECDHE_RSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheRSAKA, suiteECDHE, cipherRC4, macSHA1, nil}, + {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheECDSAKA, suiteECDHE | suiteECSign, cipherRC4, macSHA1, nil}, +} + +// selectCipherSuite returns the first TLS 1.0–1.2 cipher suite from ids which +// is also in supportedIDs and passes the ok filter. +func selectCipherSuite(ids, supportedIDs []uint16, ok func(*cipherSuite) bool) *cipherSuite { + for _, id := range ids { + candidate := cipherSuiteByID(id) + if candidate == nil || !ok(candidate) { + continue + } + + for _, suppID := range supportedIDs { + if id == suppID { + return candidate + } + } + } + return nil +} + +// A cipherSuiteTLS13 defines only the pair of the AEAD algorithm and hash +// algorithm to be used with HKDF. See RFC 8446, Appendix B.4. +type cipherSuiteTLS13 struct { + id uint16 + keyLen int + aead func(key, fixedNonce []byte) aead + hash crypto.Hash +} + +type CipherSuiteTLS13 struct { + ID uint16 + KeyLen int + Hash crypto.Hash + AEAD func(key, fixedNonce []byte) cipher.AEAD +} + +func (c *CipherSuiteTLS13) IVLen() int { + return aeadNonceLength +} + +var cipherSuitesTLS13 = []*cipherSuiteTLS13{ // TODO: replace with a map. + {TLS_AES_128_GCM_SHA256, 16, aeadAESGCMTLS13, crypto.SHA256}, + {TLS_CHACHA20_POLY1305_SHA256, 32, aeadChaCha20Poly1305, crypto.SHA256}, + {TLS_AES_256_GCM_SHA384, 32, aeadAESGCMTLS13, crypto.SHA384}, +} + +// cipherSuitesPreferenceOrder is the order in which we'll select (on the +// server) or advertise (on the client) TLS 1.0–1.2 cipher suites. +// +// Cipher suites are filtered but not reordered based on the application and +// peer's preferences, meaning we'll never select a suite lower in this list if +// any higher one is available. This makes it more defensible to keep weaker +// cipher suites enabled, especially on the server side where we get the last +// word, since there are no known downgrade attacks on cipher suites selection. +// +// The list is sorted by applying the following priority rules, stopping at the +// first (most important) applicable one: +// +// - Anything else comes before RC4 +// +// RC4 has practically exploitable biases. See https://www.rc4nomore.com. +// +// - Anything else comes before CBC_SHA256 +// +// SHA-256 variants of the CBC ciphersuites don't implement any Lucky13 +// countermeasures. See http://www.isg.rhul.ac.uk/tls/Lucky13.html and +// https://www.imperialviolet.org/2013/02/04/luckythirteen.html. +// +// - Anything else comes before 3DES +// +// 3DES has 64-bit blocks, which makes it fundamentally susceptible to +// birthday attacks. See https://sweet32.info. +// +// - ECDHE comes before anything else +// +// Once we got the broken stuff out of the way, the most important +// property a cipher suite can have is forward secrecy. We don't +// implement FFDHE, so that means ECDHE. +// +// - AEADs come before CBC ciphers +// +// Even with Lucky13 countermeasures, MAC-then-Encrypt CBC cipher suites +// are fundamentally fragile, and suffered from an endless sequence of +// padding oracle attacks. See https://eprint.iacr.org/2015/1129, +// https://www.imperialviolet.org/2014/12/08/poodleagain.html, and +// https://blog.cloudflare.com/yet-another-padding-oracle-in-openssl-cbc-ciphersuites/. +// +// - AES comes before ChaCha20 +// +// When AES hardware is available, AES-128-GCM and AES-256-GCM are faster +// than ChaCha20Poly1305. +// +// When AES hardware is not available, AES-128-GCM is one or more of: much +// slower, way more complex, and less safe (because not constant time) +// than ChaCha20Poly1305. +// +// We use this list if we think both peers have AES hardware, and +// cipherSuitesPreferenceOrderNoAES otherwise. +// +// - AES-128 comes before AES-256 +// +// The only potential advantages of AES-256 are better multi-target +// margins, and hypothetical post-quantum properties. Neither apply to +// TLS, and AES-256 is slower due to its four extra rounds (which don't +// contribute to the advantages above). +// +// - ECDSA comes before RSA +// +// The relative order of ECDSA and RSA cipher suites doesn't matter, +// as they depend on the certificate. Pick one to get a stable order. +var cipherSuitesPreferenceOrder = []uint16{ + // AEADs w/ ECDHE + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, + + // CBC w/ ECDHE + TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, + + // AEADs w/o ECDHE + TLS_RSA_WITH_AES_128_GCM_SHA256, + TLS_RSA_WITH_AES_256_GCM_SHA384, + + // CBC w/o ECDHE + TLS_RSA_WITH_AES_128_CBC_SHA, + TLS_RSA_WITH_AES_256_CBC_SHA, + + // 3DES + TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, + TLS_RSA_WITH_3DES_EDE_CBC_SHA, + + // CBC_SHA256 + TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, + TLS_RSA_WITH_AES_128_CBC_SHA256, + + // RC4 + TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, + TLS_RSA_WITH_RC4_128_SHA, +} + +var cipherSuitesPreferenceOrderNoAES = []uint16{ + // ChaCha20Poly1305 + TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, + + // AES-GCM w/ ECDHE + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + + // The rest of cipherSuitesPreferenceOrder. + TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, + TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, + TLS_RSA_WITH_AES_128_GCM_SHA256, + TLS_RSA_WITH_AES_256_GCM_SHA384, + TLS_RSA_WITH_AES_128_CBC_SHA, + TLS_RSA_WITH_AES_256_CBC_SHA, + TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, + TLS_RSA_WITH_3DES_EDE_CBC_SHA, + TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, + TLS_RSA_WITH_AES_128_CBC_SHA256, + TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, + TLS_RSA_WITH_RC4_128_SHA, +} + +// disabledCipherSuites are not used unless explicitly listed in +// Config.CipherSuites. They MUST be at the end of cipherSuitesPreferenceOrder. +var disabledCipherSuites = []uint16{ + // CBC_SHA256 + TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, + TLS_RSA_WITH_AES_128_CBC_SHA256, + + // RC4 + TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, + TLS_RSA_WITH_RC4_128_SHA, +} + +var ( + defaultCipherSuitesLen = len(cipherSuitesPreferenceOrder) - len(disabledCipherSuites) + defaultCipherSuites = cipherSuitesPreferenceOrder[:defaultCipherSuitesLen] +) + +// defaultCipherSuitesTLS13 is also the preference order, since there are no +// disabled by default TLS 1.3 cipher suites. The same AES vs ChaCha20 logic as +// cipherSuitesPreferenceOrder applies. +var defaultCipherSuitesTLS13 = []uint16{ + TLS_AES_128_GCM_SHA256, + TLS_AES_256_GCM_SHA384, + TLS_CHACHA20_POLY1305_SHA256, +} + +var defaultCipherSuitesTLS13NoAES = []uint16{ + TLS_CHACHA20_POLY1305_SHA256, + TLS_AES_128_GCM_SHA256, + TLS_AES_256_GCM_SHA384, +} + +var aesgcmCiphers = map[uint16]bool{ + // TLS 1.2 + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: true, + TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: true, + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: true, + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: true, + // TLS 1.3 + TLS_AES_128_GCM_SHA256: true, + TLS_AES_256_GCM_SHA384: true, +} + +var nonAESGCMAEADCiphers = map[uint16]bool{ + // TLS 1.2 + TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305: true, + TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305: true, + // TLS 1.3 + TLS_CHACHA20_POLY1305_SHA256: true, +} + +// aesgcmPreferred returns whether the first known cipher in the preference list +// is an AES-GCM cipher, implying the peer has hardware support for it. +func aesgcmPreferred(ciphers []uint16) bool { + for _, cID := range ciphers { + if c := cipherSuiteByID(cID); c != nil { + return aesgcmCiphers[cID] + } + if c := cipherSuiteTLS13ByID(cID); c != nil { + return aesgcmCiphers[cID] + } + } + return false +} + +func cipherRC4(key, iv []byte, isRead bool) any { + cipher, _ := rc4.NewCipher(key) + return cipher +} + +func cipher3DES(key, iv []byte, isRead bool) any { + block, _ := des.NewTripleDESCipher(key) + if isRead { + return cipher.NewCBCDecrypter(block, iv) + } + return cipher.NewCBCEncrypter(block, iv) +} + +func cipherAES(key, iv []byte, isRead bool) any { + block, _ := aes.NewCipher(key) + if isRead { + return cipher.NewCBCDecrypter(block, iv) + } + return cipher.NewCBCEncrypter(block, iv) +} + +// macSHA1 returns a SHA-1 based constant time MAC. +func macSHA1(key []byte) hash.Hash { + h := sha1.New + h = newConstantTimeHash(h) + return hmac.New(h, key) +} + +// macSHA256 returns a SHA-256 based MAC. This is only supported in TLS 1.2 and +// is currently only used in disabled-by-default cipher suites. +func macSHA256(key []byte) hash.Hash { + return hmac.New(sha256.New, key) +} + +type aead interface { + cipher.AEAD + + // explicitNonceLen returns the number of bytes of explicit nonce + // included in each record. This is eight for older AEADs and + // zero for modern ones. + explicitNonceLen() int +} + +const ( + aeadNonceLength = 12 + noncePrefixLength = 4 +) + +// prefixNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to +// each call. +type prefixNonceAEAD struct { + // nonce contains the fixed part of the nonce in the first four bytes. + nonce [aeadNonceLength]byte + aead cipher.AEAD +} + +func (f *prefixNonceAEAD) NonceSize() int { return aeadNonceLength - noncePrefixLength } +func (f *prefixNonceAEAD) Overhead() int { return f.aead.Overhead() } +func (f *prefixNonceAEAD) explicitNonceLen() int { return f.NonceSize() } + +func (f *prefixNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte { + copy(f.nonce[4:], nonce) + return f.aead.Seal(out, f.nonce[:], plaintext, additionalData) +} + +func (f *prefixNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) { + copy(f.nonce[4:], nonce) + return f.aead.Open(out, f.nonce[:], ciphertext, additionalData) +} + +// xoredNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce +// before each call. +type xorNonceAEAD struct { + nonceMask [aeadNonceLength]byte + aead cipher.AEAD +} + +func (f *xorNonceAEAD) NonceSize() int { return 8 } // 64-bit sequence number +func (f *xorNonceAEAD) Overhead() int { return f.aead.Overhead() } +func (f *xorNonceAEAD) explicitNonceLen() int { return 0 } + +func (f *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte { + for i, b := range nonce { + f.nonceMask[4+i] ^= b + } + result := f.aead.Seal(out, f.nonceMask[:], plaintext, additionalData) + for i, b := range nonce { + f.nonceMask[4+i] ^= b + } + + return result +} + +func (f *xorNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) { + for i, b := range nonce { + f.nonceMask[4+i] ^= b + } + result, err := f.aead.Open(out, f.nonceMask[:], ciphertext, additionalData) + for i, b := range nonce { + f.nonceMask[4+i] ^= b + } + + return result, err +} + +func aeadAESGCM(key, noncePrefix []byte) aead { + if len(noncePrefix) != noncePrefixLength { + panic("tls: internal error: wrong nonce length") + } + aes, err := aes.NewCipher(key) + if err != nil { + panic(err) + } + var aead cipher.AEAD + aead, err = cipher.NewGCM(aes) + if err != nil { + panic(err) + } + + ret := &prefixNonceAEAD{aead: aead} + copy(ret.nonce[:], noncePrefix) + return ret +} + +// AEADAESGCMTLS13 creates a new AES-GCM AEAD for TLS 1.3 +func AEADAESGCMTLS13(key, fixedNonce []byte) cipher.AEAD { + return aeadAESGCMTLS13(key, fixedNonce) +} + +func aeadAESGCMTLS13(key, nonceMask []byte) aead { + if len(nonceMask) != aeadNonceLength { + panic("tls: internal error: wrong nonce length") + } + aes, err := aes.NewCipher(key) + if err != nil { + panic(err) + } + aead, err := cipher.NewGCM(aes) + if err != nil { + panic(err) + } + + ret := &xorNonceAEAD{aead: aead} + copy(ret.nonceMask[:], nonceMask) + return ret +} + +func aeadChaCha20Poly1305(key, nonceMask []byte) aead { + if len(nonceMask) != aeadNonceLength { + panic("tls: internal error: wrong nonce length") + } + aead, err := chacha20poly1305.New(key) + if err != nil { + panic(err) + } + + ret := &xorNonceAEAD{aead: aead} + copy(ret.nonceMask[:], nonceMask) + return ret +} + +type constantTimeHash interface { + hash.Hash + ConstantTimeSum(b []byte) []byte +} + +// cthWrapper wraps any hash.Hash that implements ConstantTimeSum, and replaces +// with that all calls to Sum. It's used to obtain a ConstantTimeSum-based HMAC. +type cthWrapper struct { + h constantTimeHash +} + +func (c *cthWrapper) Size() int { return c.h.Size() } +func (c *cthWrapper) BlockSize() int { return c.h.BlockSize() } +func (c *cthWrapper) Reset() { c.h.Reset() } +func (c *cthWrapper) Write(p []byte) (int, error) { return c.h.Write(p) } +func (c *cthWrapper) Sum(b []byte) []byte { return c.h.ConstantTimeSum(b) } + +func newConstantTimeHash(h func() hash.Hash) func() hash.Hash { + return func() hash.Hash { + return &cthWrapper{h().(constantTimeHash)} + } +} + +// tls10MAC implements the TLS 1.0 MAC function. RFC 2246, Section 6.2.3. +func tls10MAC(h hash.Hash, out, seq, header, data, extra []byte) []byte { + h.Reset() + h.Write(seq) + h.Write(header) + h.Write(data) + res := h.Sum(out) + if extra != nil { + h.Write(extra) + } + return res +} + +func rsaKA(version uint16) keyAgreement { + return rsaKeyAgreement{} +} + +func ecdheECDSAKA(version uint16) keyAgreement { + return &ecdheKeyAgreement{ + isRSA: false, + version: version, + } +} + +func ecdheRSAKA(version uint16) keyAgreement { + return &ecdheKeyAgreement{ + isRSA: true, + version: version, + } +} + +// mutualCipherSuite returns a cipherSuite given a list of supported +// ciphersuites and the id requested by the peer. +func mutualCipherSuite(have []uint16, want uint16) *cipherSuite { + for _, id := range have { + if id == want { + return cipherSuiteByID(id) + } + } + return nil +} + +func cipherSuiteByID(id uint16) *cipherSuite { + for _, cipherSuite := range cipherSuites { + if cipherSuite.id == id { + return cipherSuite + } + } + return nil +} + +func mutualCipherSuiteTLS13(have []uint16, want uint16) *cipherSuiteTLS13 { + for _, id := range have { + if id == want { + return cipherSuiteTLS13ByID(id) + } + } + return nil +} + +func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13 { + for _, cipherSuite := range cipherSuitesTLS13 { + if cipherSuite.id == id { + return cipherSuite + } + } + return nil +} + +// A list of cipher suite IDs that are, or have been, implemented by this +// package. +// +// See https://www.iana.org/assignments/tls-parameters/tls-parameters.xml +const ( + // TLS 1.0 - 1.2 cipher suites. + TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005 + TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000a + TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002f + TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035 + TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003c + TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009c + TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009d + TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xc007 + TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xc009 + TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xc00a + TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xc011 + TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc012 + TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xc013 + TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xc014 + TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc023 + TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xc027 + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02f + TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b + TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc030 + TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc02c + TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca8 + TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xcca9 + + // TLS 1.3 cipher suites. + TLS_AES_128_GCM_SHA256 uint16 = 0x1301 + TLS_AES_256_GCM_SHA384 uint16 = 0x1302 + TLS_CHACHA20_POLY1305_SHA256 uint16 = 0x1303 + + // TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator + // that the client is doing version fallback. See RFC 7507. + TLS_FALLBACK_SCSV uint16 = 0x5600 + + // Legacy names for the corresponding cipher suites with the correct _SHA256 + // suffix, retained for backward compatibility. + TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 + TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 = TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 +) diff --git a/vendor/github.com/quic-go/qtls-go1-19/common.go b/vendor/github.com/quic-go/qtls-go1-19/common.go new file mode 100644 index 000000000..63e391bf6 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/common.go @@ -0,0 +1,1513 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "bytes" + "container/list" + "context" + "crypto" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/sha512" + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "io" + "net" + "strings" + "sync" + "time" +) + +const ( + VersionTLS10 = 0x0301 + VersionTLS11 = 0x0302 + VersionTLS12 = 0x0303 + VersionTLS13 = 0x0304 + + // Deprecated: SSLv3 is cryptographically broken, and is no longer + // supported by this package. See golang.org/issue/32716. + VersionSSL30 = 0x0300 +) + +const ( + maxPlaintext = 16384 // maximum plaintext payload length + maxCiphertext = 16384 + 2048 // maximum ciphertext payload length + maxCiphertextTLS13 = 16384 + 256 // maximum ciphertext length in TLS 1.3 + recordHeaderLen = 5 // record header length + maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB) + maxUselessRecords = 16 // maximum number of consecutive non-advancing records +) + +// TLS record types. +type recordType uint8 + +const ( + recordTypeChangeCipherSpec recordType = 20 + recordTypeAlert recordType = 21 + recordTypeHandshake recordType = 22 + recordTypeApplicationData recordType = 23 +) + +// TLS handshake message types. +const ( + typeHelloRequest uint8 = 0 + typeClientHello uint8 = 1 + typeServerHello uint8 = 2 + typeNewSessionTicket uint8 = 4 + typeEndOfEarlyData uint8 = 5 + typeEncryptedExtensions uint8 = 8 + typeCertificate uint8 = 11 + typeServerKeyExchange uint8 = 12 + typeCertificateRequest uint8 = 13 + typeServerHelloDone uint8 = 14 + typeCertificateVerify uint8 = 15 + typeClientKeyExchange uint8 = 16 + typeFinished uint8 = 20 + typeCertificateStatus uint8 = 22 + typeKeyUpdate uint8 = 24 + typeNextProtocol uint8 = 67 // Not IANA assigned + typeMessageHash uint8 = 254 // synthetic message +) + +// TLS compression types. +const ( + compressionNone uint8 = 0 +) + +type Extension struct { + Type uint16 + Data []byte +} + +// TLS extension numbers +const ( + extensionServerName uint16 = 0 + extensionStatusRequest uint16 = 5 + extensionSupportedCurves uint16 = 10 // supported_groups in TLS 1.3, see RFC 8446, Section 4.2.7 + extensionSupportedPoints uint16 = 11 + extensionSignatureAlgorithms uint16 = 13 + extensionALPN uint16 = 16 + extensionSCT uint16 = 18 + extensionSessionTicket uint16 = 35 + extensionPreSharedKey uint16 = 41 + extensionEarlyData uint16 = 42 + extensionSupportedVersions uint16 = 43 + extensionCookie uint16 = 44 + extensionPSKModes uint16 = 45 + extensionCertificateAuthorities uint16 = 47 + extensionSignatureAlgorithmsCert uint16 = 50 + extensionKeyShare uint16 = 51 + extensionRenegotiationInfo uint16 = 0xff01 +) + +// TLS signaling cipher suite values +const ( + scsvRenegotiation uint16 = 0x00ff +) + +type EncryptionLevel uint8 + +const ( + EncryptionHandshake EncryptionLevel = iota + Encryption0RTT + EncryptionApplication +) + +// CurveID is a tls.CurveID +type CurveID = tls.CurveID + +const ( + CurveP256 CurveID = 23 + CurveP384 CurveID = 24 + CurveP521 CurveID = 25 + X25519 CurveID = 29 +) + +// TLS 1.3 Key Share. See RFC 8446, Section 4.2.8. +type keyShare struct { + group CurveID + data []byte +} + +// TLS 1.3 PSK Key Exchange Modes. See RFC 8446, Section 4.2.9. +const ( + pskModePlain uint8 = 0 + pskModeDHE uint8 = 1 +) + +// TLS 1.3 PSK Identity. Can be a Session Ticket, or a reference to a saved +// session. See RFC 8446, Section 4.2.11. +type pskIdentity struct { + label []byte + obfuscatedTicketAge uint32 +} + +// TLS Elliptic Curve Point Formats +// https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9 +const ( + pointFormatUncompressed uint8 = 0 +) + +// TLS CertificateStatusType (RFC 3546) +const ( + statusTypeOCSP uint8 = 1 +) + +// Certificate types (for certificateRequestMsg) +const ( + certTypeRSASign = 1 + certTypeECDSASign = 64 // ECDSA or EdDSA keys, see RFC 8422, Section 3. +) + +// Signature algorithms (for internal signaling use). Starting at 225 to avoid overlap with +// TLS 1.2 codepoints (RFC 5246, Appendix A.4.1), with which these have nothing to do. +const ( + signaturePKCS1v15 uint8 = iota + 225 + signatureRSAPSS + signatureECDSA + signatureEd25519 +) + +// directSigning is a standard Hash value that signals that no pre-hashing +// should be performed, and that the input should be signed directly. It is the +// hash function associated with the Ed25519 signature scheme. +var directSigning crypto.Hash = 0 + +// defaultSupportedSignatureAlgorithms contains the signature and hash algorithms that +// the code advertises as supported in a TLS 1.2+ ClientHello and in a TLS 1.2+ +// CertificateRequest. The two fields are merged to match with TLS 1.3. +// Note that in TLS 1.2, the ECDSA algorithms are not constrained to P-256, etc. +var defaultSupportedSignatureAlgorithms = []SignatureScheme{ + PSSWithSHA256, + ECDSAWithP256AndSHA256, + Ed25519, + PSSWithSHA384, + PSSWithSHA512, + PKCS1WithSHA256, + PKCS1WithSHA384, + PKCS1WithSHA512, + ECDSAWithP384AndSHA384, + ECDSAWithP521AndSHA512, + PKCS1WithSHA1, + ECDSAWithSHA1, +} + +// helloRetryRequestRandom is set as the Random value of a ServerHello +// to signal that the message is actually a HelloRetryRequest. +var helloRetryRequestRandom = []byte{ // See RFC 8446, Section 4.1.3. + 0xCF, 0x21, 0xAD, 0x74, 0xE5, 0x9A, 0x61, 0x11, + 0xBE, 0x1D, 0x8C, 0x02, 0x1E, 0x65, 0xB8, 0x91, + 0xC2, 0xA2, 0x11, 0x16, 0x7A, 0xBB, 0x8C, 0x5E, + 0x07, 0x9E, 0x09, 0xE2, 0xC8, 0xA8, 0x33, 0x9C, +} + +const ( + // downgradeCanaryTLS12 or downgradeCanaryTLS11 is embedded in the server + // random as a downgrade protection if the server would be capable of + // negotiating a higher version. See RFC 8446, Section 4.1.3. + downgradeCanaryTLS12 = "DOWNGRD\x01" + downgradeCanaryTLS11 = "DOWNGRD\x00" +) + +// testingOnlyForceDowngradeCanary is set in tests to force the server side to +// include downgrade canaries even if it's using its highers supported version. +var testingOnlyForceDowngradeCanary bool + +type ConnectionState = tls.ConnectionState + +// ConnectionState records basic TLS details about the connection. +type connectionState struct { + // Version is the TLS version used by the connection (e.g. VersionTLS12). + Version uint16 + + // HandshakeComplete is true if the handshake has concluded. + HandshakeComplete bool + + // DidResume is true if this connection was successfully resumed from a + // previous session with a session ticket or similar mechanism. + DidResume bool + + // CipherSuite is the cipher suite negotiated for the connection (e.g. + // TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, TLS_AES_128_GCM_SHA256). + CipherSuite uint16 + + // NegotiatedProtocol is the application protocol negotiated with ALPN. + NegotiatedProtocol string + + // NegotiatedProtocolIsMutual used to indicate a mutual NPN negotiation. + // + // Deprecated: this value is always true. + NegotiatedProtocolIsMutual bool + + // ServerName is the value of the Server Name Indication extension sent by + // the client. It's available both on the server and on the client side. + ServerName string + + // PeerCertificates are the parsed certificates sent by the peer, in the + // order in which they were sent. The first element is the leaf certificate + // that the connection is verified against. + // + // On the client side, it can't be empty. On the server side, it can be + // empty if Config.ClientAuth is not RequireAnyClientCert or + // RequireAndVerifyClientCert. + PeerCertificates []*x509.Certificate + + // VerifiedChains is a list of one or more chains where the first element is + // PeerCertificates[0] and the last element is from Config.RootCAs (on the + // client side) or Config.ClientCAs (on the server side). + // + // On the client side, it's set if Config.InsecureSkipVerify is false. On + // the server side, it's set if Config.ClientAuth is VerifyClientCertIfGiven + // (and the peer provided a certificate) or RequireAndVerifyClientCert. + VerifiedChains [][]*x509.Certificate + + // SignedCertificateTimestamps is a list of SCTs provided by the peer + // through the TLS handshake for the leaf certificate, if any. + SignedCertificateTimestamps [][]byte + + // OCSPResponse is a stapled Online Certificate Status Protocol (OCSP) + // response provided by the peer for the leaf certificate, if any. + OCSPResponse []byte + + // TLSUnique contains the "tls-unique" channel binding value (see RFC 5929, + // Section 3). This value will be nil for TLS 1.3 connections and for all + // resumed connections. + // + // Deprecated: there are conditions in which this value might not be unique + // to a connection. See the Security Considerations sections of RFC 5705 and + // RFC 7627, and https://mitls.org/pages/attacks/3SHAKE#channelbindings. + TLSUnique []byte + + // ekm is a closure exposed via ExportKeyingMaterial. + ekm func(label string, context []byte, length int) ([]byte, error) +} + +type ConnectionStateWith0RTT struct { + ConnectionState + + Used0RTT bool // true if 0-RTT was both offered and accepted +} + +// ClientAuthType is tls.ClientAuthType +type ClientAuthType = tls.ClientAuthType + +const ( + NoClientCert = tls.NoClientCert + RequestClientCert = tls.RequestClientCert + RequireAnyClientCert = tls.RequireAnyClientCert + VerifyClientCertIfGiven = tls.VerifyClientCertIfGiven + RequireAndVerifyClientCert = tls.RequireAndVerifyClientCert +) + +// requiresClientCert reports whether the ClientAuthType requires a client +// certificate to be provided. +func requiresClientCert(c ClientAuthType) bool { + switch c { + case RequireAnyClientCert, RequireAndVerifyClientCert: + return true + default: + return false + } +} + +// ClientSessionState contains the state needed by clients to resume TLS +// sessions. +type ClientSessionState = tls.ClientSessionState + +type clientSessionState struct { + sessionTicket []uint8 // Encrypted ticket used for session resumption with server + vers uint16 // TLS version negotiated for the session + cipherSuite uint16 // Ciphersuite negotiated for the session + masterSecret []byte // Full handshake MasterSecret, or TLS 1.3 resumption_master_secret + serverCertificates []*x509.Certificate // Certificate chain presented by the server + verifiedChains [][]*x509.Certificate // Certificate chains we built for verification + receivedAt time.Time // When the session ticket was received from the server + ocspResponse []byte // Stapled OCSP response presented by the server + scts [][]byte // SCTs presented by the server + + // TLS 1.3 fields. + nonce []byte // Ticket nonce sent by the server, to derive PSK + useBy time.Time // Expiration of the ticket lifetime as set by the server + ageAdd uint32 // Random obfuscation factor for sending the ticket age +} + +// ClientSessionCache is a cache of ClientSessionState objects that can be used +// by a client to resume a TLS session with a given server. ClientSessionCache +// implementations should expect to be called concurrently from different +// goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not +// SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which +// are supported via this interface. +// +//go:generate sh -c "mockgen -package qtls -destination mock_client_session_cache_test.go github.com/quic-go/qtls-go1-19 ClientSessionCache" +type ClientSessionCache = tls.ClientSessionCache + +// SignatureScheme is a tls.SignatureScheme +type SignatureScheme = tls.SignatureScheme + +const ( + // RSASSA-PKCS1-v1_5 algorithms. + PKCS1WithSHA256 SignatureScheme = 0x0401 + PKCS1WithSHA384 SignatureScheme = 0x0501 + PKCS1WithSHA512 SignatureScheme = 0x0601 + + // RSASSA-PSS algorithms with public key OID rsaEncryption. + PSSWithSHA256 SignatureScheme = 0x0804 + PSSWithSHA384 SignatureScheme = 0x0805 + PSSWithSHA512 SignatureScheme = 0x0806 + + // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3. + ECDSAWithP256AndSHA256 SignatureScheme = 0x0403 + ECDSAWithP384AndSHA384 SignatureScheme = 0x0503 + ECDSAWithP521AndSHA512 SignatureScheme = 0x0603 + + // EdDSA algorithms. + Ed25519 SignatureScheme = 0x0807 + + // Legacy signature and hash algorithms for TLS 1.2. + PKCS1WithSHA1 SignatureScheme = 0x0201 + ECDSAWithSHA1 SignatureScheme = 0x0203 +) + +// ClientHelloInfo contains information from a ClientHello message in order to +// guide application logic in the GetCertificate and GetConfigForClient callbacks. +type ClientHelloInfo = tls.ClientHelloInfo + +type clientHelloInfo struct { + // CipherSuites lists the CipherSuites supported by the client (e.g. + // TLS_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256). + CipherSuites []uint16 + + // ServerName indicates the name of the server requested by the client + // in order to support virtual hosting. ServerName is only set if the + // client is using SNI (see RFC 4366, Section 3.1). + ServerName string + + // SupportedCurves lists the elliptic curves supported by the client. + // SupportedCurves is set only if the Supported Elliptic Curves + // Extension is being used (see RFC 4492, Section 5.1.1). + SupportedCurves []CurveID + + // SupportedPoints lists the point formats supported by the client. + // SupportedPoints is set only if the Supported Point Formats Extension + // is being used (see RFC 4492, Section 5.1.2). + SupportedPoints []uint8 + + // SignatureSchemes lists the signature and hash schemes that the client + // is willing to verify. SignatureSchemes is set only if the Signature + // Algorithms Extension is being used (see RFC 5246, Section 7.4.1.4.1). + SignatureSchemes []SignatureScheme + + // SupportedProtos lists the application protocols supported by the client. + // SupportedProtos is set only if the Application-Layer Protocol + // Negotiation Extension is being used (see RFC 7301, Section 3.1). + // + // Servers can select a protocol by setting Config.NextProtos in a + // GetConfigForClient return value. + SupportedProtos []string + + // SupportedVersions lists the TLS versions supported by the client. + // For TLS versions less than 1.3, this is extrapolated from the max + // version advertised by the client, so values other than the greatest + // might be rejected if used. + SupportedVersions []uint16 + + // Conn is the underlying net.Conn for the connection. Do not read + // from, or write to, this connection; that will cause the TLS + // connection to fail. + Conn net.Conn + + // config is embedded by the GetCertificate or GetConfigForClient caller, + // for use with SupportsCertificate. + config *Config + + // ctx is the context of the handshake that is in progress. + ctx context.Context +} + +// Context returns the context of the handshake that is in progress. +// This context is a child of the context passed to HandshakeContext, +// if any, and is canceled when the handshake concludes. +func (c *clientHelloInfo) Context() context.Context { + return c.ctx +} + +// CertificateRequestInfo contains information from a server's +// CertificateRequest message, which is used to demand a certificate and proof +// of control from a client. +type CertificateRequestInfo = tls.CertificateRequestInfo + +type certificateRequestInfo struct { + // AcceptableCAs contains zero or more, DER-encoded, X.501 + // Distinguished Names. These are the names of root or intermediate CAs + // that the server wishes the returned certificate to be signed by. An + // empty slice indicates that the server has no preference. + AcceptableCAs [][]byte + + // SignatureSchemes lists the signature schemes that the server is + // willing to verify. + SignatureSchemes []SignatureScheme + + // Version is the TLS version that was negotiated for this connection. + Version uint16 + + // ctx is the context of the handshake that is in progress. + ctx context.Context +} + +// Context returns the context of the handshake that is in progress. +// This context is a child of the context passed to HandshakeContext, +// if any, and is canceled when the handshake concludes. +func (c *certificateRequestInfo) Context() context.Context { + return c.ctx +} + +// RenegotiationSupport enumerates the different levels of support for TLS +// renegotiation. TLS renegotiation is the act of performing subsequent +// handshakes on a connection after the first. This significantly complicates +// the state machine and has been the source of numerous, subtle security +// issues. Initiating a renegotiation is not supported, but support for +// accepting renegotiation requests may be enabled. +// +// Even when enabled, the server may not change its identity between handshakes +// (i.e. the leaf certificate must be the same). Additionally, concurrent +// handshake and application data flow is not permitted so renegotiation can +// only be used with protocols that synchronise with the renegotiation, such as +// HTTPS. +// +// Renegotiation is not defined in TLS 1.3. +type RenegotiationSupport = tls.RenegotiationSupport + +const ( + // RenegotiateNever disables renegotiation. + RenegotiateNever = tls.RenegotiateNever + + // RenegotiateOnceAsClient allows a remote server to request + // renegotiation once per connection. + RenegotiateOnceAsClient = tls.RenegotiateOnceAsClient + + // RenegotiateFreelyAsClient allows a remote server to repeatedly + // request renegotiation. + RenegotiateFreelyAsClient = tls.RenegotiateFreelyAsClient +) + +// A Config structure is used to configure a TLS client or server. +// After one has been passed to a TLS function it must not be +// modified. A Config may be reused; the tls package will also not +// modify it. +type Config = tls.Config + +type config struct { + // Rand provides the source of entropy for nonces and RSA blinding. + // If Rand is nil, TLS uses the cryptographic random reader in package + // crypto/rand. + // The Reader must be safe for use by multiple goroutines. + Rand io.Reader + + // Time returns the current time as the number of seconds since the epoch. + // If Time is nil, TLS uses time.Now. + Time func() time.Time + + // Certificates contains one or more certificate chains to present to the + // other side of the connection. The first certificate compatible with the + // peer's requirements is selected automatically. + // + // Server configurations must set one of Certificates, GetCertificate or + // GetConfigForClient. Clients doing client-authentication may set either + // Certificates or GetClientCertificate. + // + // Note: if there are multiple Certificates, and they don't have the + // optional field Leaf set, certificate selection will incur a significant + // per-handshake performance cost. + Certificates []Certificate + + // NameToCertificate maps from a certificate name to an element of + // Certificates. Note that a certificate name can be of the form + // '*.example.com' and so doesn't have to be a domain name as such. + // + // Deprecated: NameToCertificate only allows associating a single + // certificate with a given name. Leave this field nil to let the library + // select the first compatible chain from Certificates. + NameToCertificate map[string]*Certificate + + // GetCertificate returns a Certificate based on the given + // ClientHelloInfo. It will only be called if the client supplies SNI + // information or if Certificates is empty. + // + // If GetCertificate is nil or returns nil, then the certificate is + // retrieved from NameToCertificate. If NameToCertificate is nil, the + // best element of Certificates will be used. + GetCertificate func(*ClientHelloInfo) (*Certificate, error) + + // GetClientCertificate, if not nil, is called when a server requests a + // certificate from a client. If set, the contents of Certificates will + // be ignored. + // + // If GetClientCertificate returns an error, the handshake will be + // aborted and that error will be returned. Otherwise + // GetClientCertificate must return a non-nil Certificate. If + // Certificate.Certificate is empty then no certificate will be sent to + // the server. If this is unacceptable to the server then it may abort + // the handshake. + // + // GetClientCertificate may be called multiple times for the same + // connection if renegotiation occurs or if TLS 1.3 is in use. + GetClientCertificate func(*CertificateRequestInfo) (*Certificate, error) + + // GetConfigForClient, if not nil, is called after a ClientHello is + // received from a client. It may return a non-nil Config in order to + // change the Config that will be used to handle this connection. If + // the returned Config is nil, the original Config will be used. The + // Config returned by this callback may not be subsequently modified. + // + // If GetConfigForClient is nil, the Config passed to Server() will be + // used for all connections. + // + // If SessionTicketKey was explicitly set on the returned Config, or if + // SetSessionTicketKeys was called on the returned Config, those keys will + // be used. Otherwise, the original Config keys will be used (and possibly + // rotated if they are automatically managed). + GetConfigForClient func(*ClientHelloInfo) (*Config, error) + + // VerifyPeerCertificate, if not nil, is called after normal + // certificate verification by either a TLS client or server. It + // receives the raw ASN.1 certificates provided by the peer and also + // any verified chains that normal processing found. If it returns a + // non-nil error, the handshake is aborted and that error results. + // + // If normal verification fails then the handshake will abort before + // considering this callback. If normal verification is disabled by + // setting InsecureSkipVerify, or (for a server) when ClientAuth is + // RequestClientCert or RequireAnyClientCert, then this callback will + // be considered but the verifiedChains argument will always be nil. + VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error + + // VerifyConnection, if not nil, is called after normal certificate + // verification and after VerifyPeerCertificate by either a TLS client + // or server. If it returns a non-nil error, the handshake is aborted + // and that error results. + // + // If normal verification fails then the handshake will abort before + // considering this callback. This callback will run for all connections + // regardless of InsecureSkipVerify or ClientAuth settings. + VerifyConnection func(ConnectionState) error + + // RootCAs defines the set of root certificate authorities + // that clients use when verifying server certificates. + // If RootCAs is nil, TLS uses the host's root CA set. + RootCAs *x509.CertPool + + // NextProtos is a list of supported application level protocols, in + // order of preference. If both peers support ALPN, the selected + // protocol will be one from this list, and the connection will fail + // if there is no mutually supported protocol. If NextProtos is empty + // or the peer doesn't support ALPN, the connection will succeed and + // ConnectionState.NegotiatedProtocol will be empty. + NextProtos []string + + // ServerName is used to verify the hostname on the returned + // certificates unless InsecureSkipVerify is given. It is also included + // in the client's handshake to support virtual hosting unless it is + // an IP address. + ServerName string + + // ClientAuth determines the server's policy for + // TLS Client Authentication. The default is NoClientCert. + ClientAuth ClientAuthType + + // ClientCAs defines the set of root certificate authorities + // that servers use if required to verify a client certificate + // by the policy in ClientAuth. + ClientCAs *x509.CertPool + + // InsecureSkipVerify controls whether a client verifies the server's + // certificate chain and host name. If InsecureSkipVerify is true, crypto/tls + // accepts any certificate presented by the server and any host name in that + // certificate. In this mode, TLS is susceptible to machine-in-the-middle + // attacks unless custom verification is used. This should be used only for + // testing or in combination with VerifyConnection or VerifyPeerCertificate. + InsecureSkipVerify bool + + // CipherSuites is a list of enabled TLS 1.0–1.2 cipher suites. The order of + // the list is ignored. Note that TLS 1.3 ciphersuites are not configurable. + // + // If CipherSuites is nil, a safe default list is used. The default cipher + // suites might change over time. + CipherSuites []uint16 + + // PreferServerCipherSuites is a legacy field and has no effect. + // + // It used to control whether the server would follow the client's or the + // server's preference. Servers now select the best mutually supported + // cipher suite based on logic that takes into account inferred client + // hardware, server hardware, and security. + // + // Deprecated: PreferServerCipherSuites is ignored. + PreferServerCipherSuites bool + + // SessionTicketsDisabled may be set to true to disable session ticket and + // PSK (resumption) support. Note that on clients, session ticket support is + // also disabled if ClientSessionCache is nil. + SessionTicketsDisabled bool + + // SessionTicketKey is used by TLS servers to provide session resumption. + // See RFC 5077 and the PSK mode of RFC 8446. If zero, it will be filled + // with random data before the first server handshake. + // + // Deprecated: if this field is left at zero, session ticket keys will be + // automatically rotated every day and dropped after seven days. For + // customizing the rotation schedule or synchronizing servers that are + // terminating connections for the same host, use SetSessionTicketKeys. + SessionTicketKey [32]byte + + // ClientSessionCache is a cache of ClientSessionState entries for TLS + // session resumption. It is only used by clients. + ClientSessionCache ClientSessionCache + + // MinVersion contains the minimum TLS version that is acceptable. + // + // By default, TLS 1.2 is currently used as the minimum when acting as a + // client, and TLS 1.0 when acting as a server. TLS 1.0 is the minimum + // supported by this package, both as a client and as a server. + // + // The client-side default can temporarily be reverted to TLS 1.0 by + // including the value "x509sha1=1" in the GODEBUG environment variable. + // Note that this option will be removed in Go 1.19 (but it will still be + // possible to set this field to VersionTLS10 explicitly). + MinVersion uint16 + + // MaxVersion contains the maximum TLS version that is acceptable. + // + // By default, the maximum version supported by this package is used, + // which is currently TLS 1.3. + MaxVersion uint16 + + // CurvePreferences contains the elliptic curves that will be used in + // an ECDHE handshake, in preference order. If empty, the default will + // be used. The client will use the first preference as the type for + // its key share in TLS 1.3. This may change in the future. + CurvePreferences []CurveID + + // DynamicRecordSizingDisabled disables adaptive sizing of TLS records. + // When true, the largest possible TLS record size is always used. When + // false, the size of TLS records may be adjusted in an attempt to + // improve latency. + DynamicRecordSizingDisabled bool + + // Renegotiation controls what types of renegotiation are supported. + // The default, none, is correct for the vast majority of applications. + Renegotiation RenegotiationSupport + + // KeyLogWriter optionally specifies a destination for TLS master secrets + // in NSS key log format that can be used to allow external programs + // such as Wireshark to decrypt TLS connections. + // See https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/Key_Log_Format. + // Use of KeyLogWriter compromises security and should only be + // used for debugging. + KeyLogWriter io.Writer + + // mutex protects sessionTicketKeys and autoSessionTicketKeys. + mutex sync.RWMutex + // sessionTicketKeys contains zero or more ticket keys. If set, it means the + // the keys were set with SessionTicketKey or SetSessionTicketKeys. The + // first key is used for new tickets and any subsequent keys can be used to + // decrypt old tickets. The slice contents are not protected by the mutex + // and are immutable. + sessionTicketKeys []ticketKey + // autoSessionTicketKeys is like sessionTicketKeys but is owned by the + // auto-rotation logic. See Config.ticketKeys. + autoSessionTicketKeys []ticketKey +} + +// A RecordLayer handles encrypting and decrypting of TLS messages. +type RecordLayer interface { + SetReadKey(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte) + SetWriteKey(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte) + ReadHandshakeMessage() ([]byte, error) + WriteRecord([]byte) (int, error) + SendAlert(uint8) +} + +type ExtraConfig struct { + // GetExtensions, if not nil, is called before a message that allows + // sending of extensions is sent. + // Currently only implemented for the ClientHello message (for the client) + // and for the EncryptedExtensions message (for the server). + // Only valid for TLS 1.3. + GetExtensions func(handshakeMessageType uint8) []Extension + + // ReceivedExtensions, if not nil, is called when a message that allows the + // inclusion of extensions is received. + // It is called with an empty slice of extensions, if the message didn't + // contain any extensions. + // Currently only implemented for the ClientHello message (sent by the + // client) and for the EncryptedExtensions message (sent by the server). + // Only valid for TLS 1.3. + ReceivedExtensions func(handshakeMessageType uint8, exts []Extension) + + // AlternativeRecordLayer is used by QUIC + AlternativeRecordLayer RecordLayer + + // Enforce the selection of a supported application protocol. + // Only works for TLS 1.3. + // If enabled, client and server have to agree on an application protocol. + // Otherwise, connection establishment fails. + EnforceNextProtoSelection bool + + // If MaxEarlyData is greater than 0, the client will be allowed to send early + // data when resuming a session. + // Requires the AlternativeRecordLayer to be set. + // + // It has no meaning on the client. + MaxEarlyData uint32 + + // The Accept0RTT callback is called when the client offers 0-RTT. + // The server then has to decide if it wants to accept or reject 0-RTT. + // It is only used for servers. + Accept0RTT func(appData []byte) bool + + // 0RTTRejected is called when the server rejectes 0-RTT. + // It is only used for clients. + Rejected0RTT func() + + // If set, the client will export the 0-RTT key when resuming a session that + // allows sending of early data. + // Requires the AlternativeRecordLayer to be set. + // + // It has no meaning to the server. + Enable0RTT bool + + // Is called when the client saves a session ticket to the session ticket. + // This gives the application the opportunity to save some data along with the ticket, + // which can be restored when the session ticket is used. + GetAppDataForSessionState func() []byte + + // Is called when the client uses a session ticket. + // Restores the application data that was saved earlier on GetAppDataForSessionTicket. + SetAppDataFromSessionState func([]byte) +} + +// Clone clones. +func (c *ExtraConfig) Clone() *ExtraConfig { + return &ExtraConfig{ + GetExtensions: c.GetExtensions, + ReceivedExtensions: c.ReceivedExtensions, + AlternativeRecordLayer: c.AlternativeRecordLayer, + EnforceNextProtoSelection: c.EnforceNextProtoSelection, + MaxEarlyData: c.MaxEarlyData, + Enable0RTT: c.Enable0RTT, + Accept0RTT: c.Accept0RTT, + Rejected0RTT: c.Rejected0RTT, + GetAppDataForSessionState: c.GetAppDataForSessionState, + SetAppDataFromSessionState: c.SetAppDataFromSessionState, + } +} + +func (c *ExtraConfig) usesAlternativeRecordLayer() bool { + return c != nil && c.AlternativeRecordLayer != nil +} + +const ( + // ticketKeyNameLen is the number of bytes of identifier that is prepended to + // an encrypted session ticket in order to identify the key used to encrypt it. + ticketKeyNameLen = 16 + + // ticketKeyLifetime is how long a ticket key remains valid and can be used to + // resume a client connection. + ticketKeyLifetime = 7 * 24 * time.Hour // 7 days + + // ticketKeyRotation is how often the server should rotate the session ticket key + // that is used for new tickets. + ticketKeyRotation = 24 * time.Hour +) + +// ticketKey is the internal representation of a session ticket key. +type ticketKey struct { + // keyName is an opaque byte string that serves to identify the session + // ticket key. It's exposed as plaintext in every session ticket. + keyName [ticketKeyNameLen]byte + aesKey [16]byte + hmacKey [16]byte + // created is the time at which this ticket key was created. See Config.ticketKeys. + created time.Time +} + +// ticketKeyFromBytes converts from the external representation of a session +// ticket key to a ticketKey. Externally, session ticket keys are 32 random +// bytes and this function expands that into sufficient name and key material. +func (c *config) ticketKeyFromBytes(b [32]byte) (key ticketKey) { + hashed := sha512.Sum512(b[:]) + copy(key.keyName[:], hashed[:ticketKeyNameLen]) + copy(key.aesKey[:], hashed[ticketKeyNameLen:ticketKeyNameLen+16]) + copy(key.hmacKey[:], hashed[ticketKeyNameLen+16:ticketKeyNameLen+32]) + key.created = c.time() + return key +} + +// maxSessionTicketLifetime is the maximum allowed lifetime of a TLS 1.3 session +// ticket, and the lifetime we set for tickets we send. +const maxSessionTicketLifetime = 7 * 24 * time.Hour + +// Clone returns a shallow clone of c or nil if c is nil. It is safe to clone a Config that is +// being used concurrently by a TLS client or server. +func (c *config) Clone() *config { + if c == nil { + return nil + } + c.mutex.RLock() + defer c.mutex.RUnlock() + return &config{ + Rand: c.Rand, + Time: c.Time, + Certificates: c.Certificates, + NameToCertificate: c.NameToCertificate, + GetCertificate: c.GetCertificate, + GetClientCertificate: c.GetClientCertificate, + GetConfigForClient: c.GetConfigForClient, + VerifyPeerCertificate: c.VerifyPeerCertificate, + VerifyConnection: c.VerifyConnection, + RootCAs: c.RootCAs, + NextProtos: c.NextProtos, + ServerName: c.ServerName, + ClientAuth: c.ClientAuth, + ClientCAs: c.ClientCAs, + InsecureSkipVerify: c.InsecureSkipVerify, + CipherSuites: c.CipherSuites, + PreferServerCipherSuites: c.PreferServerCipherSuites, + SessionTicketsDisabled: c.SessionTicketsDisabled, + SessionTicketKey: c.SessionTicketKey, + ClientSessionCache: c.ClientSessionCache, + MinVersion: c.MinVersion, + MaxVersion: c.MaxVersion, + CurvePreferences: c.CurvePreferences, + DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, + Renegotiation: c.Renegotiation, + KeyLogWriter: c.KeyLogWriter, + sessionTicketKeys: c.sessionTicketKeys, + autoSessionTicketKeys: c.autoSessionTicketKeys, + } +} + +// deprecatedSessionTicketKey is set as the prefix of SessionTicketKey if it was +// randomized for backwards compatibility but is not in use. +var deprecatedSessionTicketKey = []byte("DEPRECATED") + +// initLegacySessionTicketKeyRLocked ensures the legacy SessionTicketKey field is +// randomized if empty, and that sessionTicketKeys is populated from it otherwise. +func (c *config) initLegacySessionTicketKeyRLocked() { + // Don't write if SessionTicketKey is already defined as our deprecated string, + // or if it is defined by the user but sessionTicketKeys is already set. + if c.SessionTicketKey != [32]byte{} && + (bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) || len(c.sessionTicketKeys) > 0) { + return + } + + // We need to write some data, so get an exclusive lock and re-check any conditions. + c.mutex.RUnlock() + defer c.mutex.RLock() + c.mutex.Lock() + defer c.mutex.Unlock() + if c.SessionTicketKey == [32]byte{} { + if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil { + panic(fmt.Sprintf("tls: unable to generate random session ticket key: %v", err)) + } + // Write the deprecated prefix at the beginning so we know we created + // it. This key with the DEPRECATED prefix isn't used as an actual + // session ticket key, and is only randomized in case the application + // reuses it for some reason. + copy(c.SessionTicketKey[:], deprecatedSessionTicketKey) + } else if !bytes.HasPrefix(c.SessionTicketKey[:], deprecatedSessionTicketKey) && len(c.sessionTicketKeys) == 0 { + c.sessionTicketKeys = []ticketKey{c.ticketKeyFromBytes(c.SessionTicketKey)} + } + +} + +// ticketKeys returns the ticketKeys for this connection. +// If configForClient has explicitly set keys, those will +// be returned. Otherwise, the keys on c will be used and +// may be rotated if auto-managed. +// During rotation, any expired session ticket keys are deleted from +// c.sessionTicketKeys. If the session ticket key that is currently +// encrypting tickets (ie. the first ticketKey in c.sessionTicketKeys) +// is not fresh, then a new session ticket key will be +// created and prepended to c.sessionTicketKeys. +func (c *config) ticketKeys(configForClient *config) []ticketKey { + // If the ConfigForClient callback returned a Config with explicitly set + // keys, use those, otherwise just use the original Config. + if configForClient != nil { + configForClient.mutex.RLock() + if configForClient.SessionTicketsDisabled { + return nil + } + configForClient.initLegacySessionTicketKeyRLocked() + if len(configForClient.sessionTicketKeys) != 0 { + ret := configForClient.sessionTicketKeys + configForClient.mutex.RUnlock() + return ret + } + configForClient.mutex.RUnlock() + } + + c.mutex.RLock() + defer c.mutex.RUnlock() + if c.SessionTicketsDisabled { + return nil + } + c.initLegacySessionTicketKeyRLocked() + if len(c.sessionTicketKeys) != 0 { + return c.sessionTicketKeys + } + // Fast path for the common case where the key is fresh enough. + if len(c.autoSessionTicketKeys) > 0 && c.time().Sub(c.autoSessionTicketKeys[0].created) < ticketKeyRotation { + return c.autoSessionTicketKeys + } + + // autoSessionTicketKeys are managed by auto-rotation. + c.mutex.RUnlock() + defer c.mutex.RLock() + c.mutex.Lock() + defer c.mutex.Unlock() + // Re-check the condition in case it changed since obtaining the new lock. + if len(c.autoSessionTicketKeys) == 0 || c.time().Sub(c.autoSessionTicketKeys[0].created) >= ticketKeyRotation { + var newKey [32]byte + if _, err := io.ReadFull(c.rand(), newKey[:]); err != nil { + panic(fmt.Sprintf("unable to generate random session ticket key: %v", err)) + } + valid := make([]ticketKey, 0, len(c.autoSessionTicketKeys)+1) + valid = append(valid, c.ticketKeyFromBytes(newKey)) + for _, k := range c.autoSessionTicketKeys { + // While rotating the current key, also remove any expired ones. + if c.time().Sub(k.created) < ticketKeyLifetime { + valid = append(valid, k) + } + } + c.autoSessionTicketKeys = valid + } + return c.autoSessionTicketKeys +} + +// SetSessionTicketKeys updates the session ticket keys for a server. +// +// The first key will be used when creating new tickets, while all keys can be +// used for decrypting tickets. It is safe to call this function while the +// server is running in order to rotate the session ticket keys. The function +// will panic if keys is empty. +// +// Calling this function will turn off automatic session ticket key rotation. +// +// If multiple servers are terminating connections for the same host they should +// all have the same session ticket keys. If the session ticket keys leaks, +// previously recorded and future TLS connections using those keys might be +// compromised. +func (c *config) SetSessionTicketKeys(keys [][32]byte) { + if len(keys) == 0 { + panic("tls: keys must have at least one key") + } + + newKeys := make([]ticketKey, len(keys)) + for i, bytes := range keys { + newKeys[i] = c.ticketKeyFromBytes(bytes) + } + + c.mutex.Lock() + c.sessionTicketKeys = newKeys + c.mutex.Unlock() +} + +func (c *config) rand() io.Reader { + r := c.Rand + if r == nil { + return rand.Reader + } + return r +} + +func (c *config) time() time.Time { + t := c.Time + if t == nil { + t = time.Now + } + return t() +} + +func (c *config) cipherSuites() []uint16 { + if needFIPS() { + return fipsCipherSuites(c) + } + if c.CipherSuites != nil { + return c.CipherSuites + } + return defaultCipherSuites +} + +var supportedVersions = []uint16{ + VersionTLS13, + VersionTLS12, + VersionTLS11, + VersionTLS10, +} + +// roleClient and roleServer are meant to call supportedVersions and parents +// with more readability at the callsite. +const roleClient = true +const roleServer = false + +func (c *config) supportedVersions(isClient bool) []uint16 { + versions := make([]uint16, 0, len(supportedVersions)) + for _, v := range supportedVersions { + if needFIPS() && (v < fipsMinVersion(c) || v > fipsMaxVersion(c)) { + continue + } + if (c == nil || c.MinVersion == 0) && + isClient && v < VersionTLS12 { + continue + } + if c != nil && c.MinVersion != 0 && v < c.MinVersion { + continue + } + if c != nil && c.MaxVersion != 0 && v > c.MaxVersion { + continue + } + versions = append(versions, v) + } + return versions +} + +func (c *config) maxSupportedVersion(isClient bool) uint16 { + supportedVersions := c.supportedVersions(isClient) + if len(supportedVersions) == 0 { + return 0 + } + return supportedVersions[0] +} + +// supportedVersionsFromMax returns a list of supported versions derived from a +// legacy maximum version value. Note that only versions supported by this +// library are returned. Any newer peer will use supportedVersions anyway. +func supportedVersionsFromMax(maxVersion uint16) []uint16 { + versions := make([]uint16, 0, len(supportedVersions)) + for _, v := range supportedVersions { + if v > maxVersion { + continue + } + versions = append(versions, v) + } + return versions +} + +var defaultCurvePreferences = []CurveID{X25519, CurveP256, CurveP384, CurveP521} + +func (c *config) curvePreferences() []CurveID { + if needFIPS() { + return fipsCurvePreferences(c) + } + if c == nil || len(c.CurvePreferences) == 0 { + return defaultCurvePreferences + } + return c.CurvePreferences +} + +func (c *config) supportsCurve(curve CurveID) bool { + for _, cc := range c.curvePreferences() { + if cc == curve { + return true + } + } + return false +} + +// mutualVersion returns the protocol version to use given the advertised +// versions of the peer. Priority is given to the peer preference order. +func (c *config) mutualVersion(isClient bool, peerVersions []uint16) (uint16, bool) { + supportedVersions := c.supportedVersions(isClient) + for _, peerVersion := range peerVersions { + for _, v := range supportedVersions { + if v == peerVersion { + return v, true + } + } + } + return 0, false +} + +var errNoCertificates = errors.New("tls: no certificates configured") + +// getCertificate returns the best certificate for the given ClientHelloInfo, +// defaulting to the first element of c.Certificates. +func (c *config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) { + if c.GetCertificate != nil && + (len(c.Certificates) == 0 || len(clientHello.ServerName) > 0) { + cert, err := c.GetCertificate(clientHello) + if cert != nil || err != nil { + return cert, err + } + } + + if len(c.Certificates) == 0 { + return nil, errNoCertificates + } + + if len(c.Certificates) == 1 { + // There's only one choice, so no point doing any work. + return &c.Certificates[0], nil + } + + if c.NameToCertificate != nil { + name := strings.ToLower(clientHello.ServerName) + if cert, ok := c.NameToCertificate[name]; ok { + return cert, nil + } + if len(name) > 0 { + labels := strings.Split(name, ".") + labels[0] = "*" + wildcardName := strings.Join(labels, ".") + if cert, ok := c.NameToCertificate[wildcardName]; ok { + return cert, nil + } + } + } + + for _, cert := range c.Certificates { + if err := clientHello.SupportsCertificate(&cert); err == nil { + return &cert, nil + } + } + + // If nothing matches, return the first certificate. + return &c.Certificates[0], nil +} + +// SupportsCertificate returns nil if the provided certificate is supported by +// the client that sent the ClientHello. Otherwise, it returns an error +// describing the reason for the incompatibility. +// +// If this ClientHelloInfo was passed to a GetConfigForClient or GetCertificate +// callback, this method will take into account the associated Config. Note that +// if GetConfigForClient returns a different Config, the change can't be +// accounted for by this method. +// +// This function will call x509.ParseCertificate unless c.Leaf is set, which can +// incur a significant performance cost. +func (chi *clientHelloInfo) SupportsCertificate(c *Certificate) error { + // Note we don't currently support certificate_authorities nor + // signature_algorithms_cert, and don't check the algorithms of the + // signatures on the chain (which anyway are a SHOULD, see RFC 8446, + // Section 4.4.2.2). + + config := chi.config + if config == nil { + config = &Config{} + } + conf := fromConfig(config) + vers, ok := conf.mutualVersion(roleServer, chi.SupportedVersions) + if !ok { + return errors.New("no mutually supported protocol versions") + } + + // If the client specified the name they are trying to connect to, the + // certificate needs to be valid for it. + if chi.ServerName != "" { + x509Cert, err := leafCertificate(c) + if err != nil { + return fmt.Errorf("failed to parse certificate: %w", err) + } + if err := x509Cert.VerifyHostname(chi.ServerName); err != nil { + return fmt.Errorf("certificate is not valid for requested server name: %w", err) + } + } + + // supportsRSAFallback returns nil if the certificate and connection support + // the static RSA key exchange, and unsupported otherwise. The logic for + // supporting static RSA is completely disjoint from the logic for + // supporting signed key exchanges, so we just check it as a fallback. + supportsRSAFallback := func(unsupported error) error { + // TLS 1.3 dropped support for the static RSA key exchange. + if vers == VersionTLS13 { + return unsupported + } + // The static RSA key exchange works by decrypting a challenge with the + // RSA private key, not by signing, so check the PrivateKey implements + // crypto.Decrypter, like *rsa.PrivateKey does. + if priv, ok := c.PrivateKey.(crypto.Decrypter); ok { + if _, ok := priv.Public().(*rsa.PublicKey); !ok { + return unsupported + } + } else { + return unsupported + } + // Finally, there needs to be a mutual cipher suite that uses the static + // RSA key exchange instead of ECDHE. + rsaCipherSuite := selectCipherSuite(chi.CipherSuites, conf.cipherSuites(), func(c *cipherSuite) bool { + if c.flags&suiteECDHE != 0 { + return false + } + if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 { + return false + } + return true + }) + if rsaCipherSuite == nil { + return unsupported + } + return nil + } + + // If the client sent the signature_algorithms extension, ensure it supports + // schemes we can use with this certificate and TLS version. + if len(chi.SignatureSchemes) > 0 { + if _, err := selectSignatureScheme(vers, c, chi.SignatureSchemes); err != nil { + return supportsRSAFallback(err) + } + } + + // In TLS 1.3 we are done because supported_groups is only relevant to the + // ECDHE computation, point format negotiation is removed, cipher suites are + // only relevant to the AEAD choice, and static RSA does not exist. + if vers == VersionTLS13 { + return nil + } + + // The only signed key exchange we support is ECDHE. + if !supportsECDHE(conf, chi.SupportedCurves, chi.SupportedPoints) { + return supportsRSAFallback(errors.New("client doesn't support ECDHE, can only use legacy RSA key exchange")) + } + + var ecdsaCipherSuite bool + if priv, ok := c.PrivateKey.(crypto.Signer); ok { + switch pub := priv.Public().(type) { + case *ecdsa.PublicKey: + var curve CurveID + switch pub.Curve { + case elliptic.P256(): + curve = CurveP256 + case elliptic.P384(): + curve = CurveP384 + case elliptic.P521(): + curve = CurveP521 + default: + return supportsRSAFallback(unsupportedCertificateError(c)) + } + var curveOk bool + for _, c := range chi.SupportedCurves { + if c == curve && conf.supportsCurve(c) { + curveOk = true + break + } + } + if !curveOk { + return errors.New("client doesn't support certificate curve") + } + ecdsaCipherSuite = true + case ed25519.PublicKey: + if vers < VersionTLS12 || len(chi.SignatureSchemes) == 0 { + return errors.New("connection doesn't support Ed25519") + } + ecdsaCipherSuite = true + case *rsa.PublicKey: + default: + return supportsRSAFallback(unsupportedCertificateError(c)) + } + } else { + return supportsRSAFallback(unsupportedCertificateError(c)) + } + + // Make sure that there is a mutually supported cipher suite that works with + // this certificate. Cipher suite selection will then apply the logic in + // reverse to pick it. See also serverHandshakeState.cipherSuiteOk. + cipherSuite := selectCipherSuite(chi.CipherSuites, conf.cipherSuites(), func(c *cipherSuite) bool { + if c.flags&suiteECDHE == 0 { + return false + } + if c.flags&suiteECSign != 0 { + if !ecdsaCipherSuite { + return false + } + } else { + if ecdsaCipherSuite { + return false + } + } + if vers < VersionTLS12 && c.flags&suiteTLS12 != 0 { + return false + } + return true + }) + if cipherSuite == nil { + return supportsRSAFallback(errors.New("client doesn't support any cipher suites compatible with the certificate")) + } + + return nil +} + +// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate +// from the CommonName and SubjectAlternateName fields of each of the leaf +// certificates. +// +// Deprecated: NameToCertificate only allows associating a single certificate +// with a given name. Leave that field nil to let the library select the first +// compatible chain from Certificates. +func (c *config) BuildNameToCertificate() { + c.NameToCertificate = make(map[string]*Certificate) + for i := range c.Certificates { + cert := &c.Certificates[i] + x509Cert, err := leafCertificate(cert) + if err != nil { + continue + } + // If SANs are *not* present, some clients will consider the certificate + // valid for the name in the Common Name. + if x509Cert.Subject.CommonName != "" && len(x509Cert.DNSNames) == 0 { + c.NameToCertificate[x509Cert.Subject.CommonName] = cert + } + for _, san := range x509Cert.DNSNames { + c.NameToCertificate[san] = cert + } + } +} + +const ( + keyLogLabelTLS12 = "CLIENT_RANDOM" + keyLogLabelEarlyTraffic = "CLIENT_EARLY_TRAFFIC_SECRET" + keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET" + keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET" + keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0" + keyLogLabelServerTraffic = "SERVER_TRAFFIC_SECRET_0" +) + +func (c *config) writeKeyLog(label string, clientRandom, secret []byte) error { + if c.KeyLogWriter == nil { + return nil + } + + logLine := []byte(fmt.Sprintf("%s %x %x\n", label, clientRandom, secret)) + + writerMutex.Lock() + _, err := c.KeyLogWriter.Write(logLine) + writerMutex.Unlock() + + return err +} + +// writerMutex protects all KeyLogWriters globally. It is rarely enabled, +// and is only for debugging, so a global mutex saves space. +var writerMutex sync.Mutex + +// A Certificate is a chain of one or more certificates, leaf first. +type Certificate = tls.Certificate + +// leaf returns the parsed leaf certificate, either from c.Leaf or by parsing +// the corresponding c.Certificate[0]. +func leafCertificate(c *Certificate) (*x509.Certificate, error) { + if c.Leaf != nil { + return c.Leaf, nil + } + return x509.ParseCertificate(c.Certificate[0]) +} + +type handshakeMessage interface { + marshal() ([]byte, error) + unmarshal([]byte) bool +} + +// lruSessionCache is a ClientSessionCache implementation that uses an LRU +// caching strategy. +type lruSessionCache struct { + sync.Mutex + + m map[string]*list.Element + q *list.List + capacity int +} + +type lruSessionCacheEntry struct { + sessionKey string + state *ClientSessionState +} + +// NewLRUClientSessionCache returns a ClientSessionCache with the given +// capacity that uses an LRU strategy. If capacity is < 1, a default capacity +// is used instead. +func NewLRUClientSessionCache(capacity int) ClientSessionCache { + const defaultSessionCacheCapacity = 64 + + if capacity < 1 { + capacity = defaultSessionCacheCapacity + } + return &lruSessionCache{ + m: make(map[string]*list.Element), + q: list.New(), + capacity: capacity, + } +} + +// Put adds the provided (sessionKey, cs) pair to the cache. If cs is nil, the entry +// corresponding to sessionKey is removed from the cache instead. +func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) { + c.Lock() + defer c.Unlock() + + if elem, ok := c.m[sessionKey]; ok { + if cs == nil { + c.q.Remove(elem) + delete(c.m, sessionKey) + } else { + entry := elem.Value.(*lruSessionCacheEntry) + entry.state = cs + c.q.MoveToFront(elem) + } + return + } + + if c.q.Len() < c.capacity { + entry := &lruSessionCacheEntry{sessionKey, cs} + c.m[sessionKey] = c.q.PushFront(entry) + return + } + + elem := c.q.Back() + entry := elem.Value.(*lruSessionCacheEntry) + delete(c.m, entry.sessionKey) + entry.sessionKey = sessionKey + entry.state = cs + c.q.MoveToFront(elem) + c.m[sessionKey] = elem +} + +// Get returns the ClientSessionState value associated with a given key. It +// returns (nil, false) if no value is found. +func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) { + c.Lock() + defer c.Unlock() + + if elem, ok := c.m[sessionKey]; ok { + c.q.MoveToFront(elem) + return elem.Value.(*lruSessionCacheEntry).state, true + } + return nil, false +} + +var emptyConfig Config + +func defaultConfig() *Config { + return &emptyConfig +} + +func unexpectedMessageError(wanted, got any) error { + return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted) +} + +func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlgorithms []SignatureScheme) bool { + for _, s := range supportedSignatureAlgorithms { + if s == sigAlg { + return true + } + } + return false +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/conn.go b/vendor/github.com/quic-go/qtls-go1-19/conn.go new file mode 100644 index 000000000..19f24e95f --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/conn.go @@ -0,0 +1,1649 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// TLS low level connection and record layer + +package qtls + +import ( + "bytes" + "context" + "crypto/cipher" + "crypto/subtle" + "crypto/x509" + "errors" + "fmt" + "hash" + "io" + "net" + "sync" + "sync/atomic" + "time" +) + +// A Conn represents a secured connection. +// It implements the net.Conn interface. +type Conn struct { + // constant + conn net.Conn + isClient bool + handshakeFn func(context.Context) error // (*Conn).clientHandshake or serverHandshake + + // handshakeStatus is 1 if the connection is currently transferring + // application data (i.e. is not currently processing a handshake). + // handshakeStatus == 1 implies handshakeErr == nil. + // This field is only to be accessed with sync/atomic. + handshakeStatus uint32 + // constant after handshake; protected by handshakeMutex + handshakeMutex sync.Mutex + handshakeErr error // error resulting from handshake + vers uint16 // TLS version + haveVers bool // version has been negotiated + config *config // configuration passed to constructor + // handshakes counts the number of handshakes performed on the + // connection so far. If renegotiation is disabled then this is either + // zero or one. + extraConfig *ExtraConfig + + handshakes int + didResume bool // whether this connection was a session resumption + cipherSuite uint16 + ocspResponse []byte // stapled OCSP response + scts [][]byte // signed certificate timestamps from server + peerCertificates []*x509.Certificate + // verifiedChains contains the certificate chains that we built, as + // opposed to the ones presented by the server. + verifiedChains [][]*x509.Certificate + // serverName contains the server name indicated by the client, if any. + serverName string + // secureRenegotiation is true if the server echoed the secure + // renegotiation extension. (This is meaningless as a server because + // renegotiation is not supported in that case.) + secureRenegotiation bool + // ekm is a closure for exporting keying material. + ekm func(label string, context []byte, length int) ([]byte, error) + // For the client: + // resumptionSecret is the resumption_master_secret for handling + // NewSessionTicket messages. nil if config.SessionTicketsDisabled. + // For the server: + // resumptionSecret is the resumption_master_secret for generating + // NewSessionTicket messages. Only used when the alternative record + // layer is set. nil if config.SessionTicketsDisabled. + resumptionSecret []byte + + // ticketKeys is the set of active session ticket keys for this + // connection. The first one is used to encrypt new tickets and + // all are tried to decrypt tickets. + ticketKeys []ticketKey + + // clientFinishedIsFirst is true if the client sent the first Finished + // message during the most recent handshake. This is recorded because + // the first transmitted Finished message is the tls-unique + // channel-binding value. + clientFinishedIsFirst bool + + // closeNotifyErr is any error from sending the alertCloseNotify record. + closeNotifyErr error + // closeNotifySent is true if the Conn attempted to send an + // alertCloseNotify record. + closeNotifySent bool + + // clientFinished and serverFinished contain the Finished message sent + // by the client or server in the most recent handshake. This is + // retained to support the renegotiation extension and tls-unique + // channel-binding. + clientFinished [12]byte + serverFinished [12]byte + + // clientProtocol is the negotiated ALPN protocol. + clientProtocol string + + // input/output + in, out halfConn + rawInput bytes.Buffer // raw input, starting with a record header + input bytes.Reader // application data waiting to be read, from rawInput.Next + hand bytes.Buffer // handshake data waiting to be read + buffering bool // whether records are buffered in sendBuf + sendBuf []byte // a buffer of records waiting to be sent + + // bytesSent counts the bytes of application data sent. + // packetsSent counts packets. + bytesSent int64 + packetsSent int64 + + // retryCount counts the number of consecutive non-advancing records + // received by Conn.readRecord. That is, records that neither advance the + // handshake, nor deliver application data. Protected by in.Mutex. + retryCount int + + // activeCall is an atomic int32; the low bit is whether Close has + // been called. the rest of the bits are the number of goroutines + // in Conn.Write. + activeCall int32 + + used0RTT bool + + tmp [16]byte + + connStateMutex sync.Mutex + connState ConnectionStateWith0RTT +} + +// Access to net.Conn methods. +// Cannot just embed net.Conn because that would +// export the struct field too. + +// LocalAddr returns the local network address. +func (c *Conn) LocalAddr() net.Addr { + return c.conn.LocalAddr() +} + +// RemoteAddr returns the remote network address. +func (c *Conn) RemoteAddr() net.Addr { + return c.conn.RemoteAddr() +} + +// SetDeadline sets the read and write deadlines associated with the connection. +// A zero value for t means Read and Write will not time out. +// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. +func (c *Conn) SetDeadline(t time.Time) error { + return c.conn.SetDeadline(t) +} + +// SetReadDeadline sets the read deadline on the underlying connection. +// A zero value for t means Read will not time out. +func (c *Conn) SetReadDeadline(t time.Time) error { + return c.conn.SetReadDeadline(t) +} + +// SetWriteDeadline sets the write deadline on the underlying connection. +// A zero value for t means Write will not time out. +// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. +func (c *Conn) SetWriteDeadline(t time.Time) error { + return c.conn.SetWriteDeadline(t) +} + +// NetConn returns the underlying connection that is wrapped by c. +// Note that writing to or reading from this connection directly will corrupt the +// TLS session. +func (c *Conn) NetConn() net.Conn { + return c.conn +} + +// A halfConn represents one direction of the record layer +// connection, either sending or receiving. +type halfConn struct { + sync.Mutex + + err error // first permanent error + version uint16 // protocol version + cipher any // cipher algorithm + mac hash.Hash + seq [8]byte // 64-bit sequence number + + scratchBuf [13]byte // to avoid allocs; interface method args escape + + nextCipher any // next encryption state + nextMac hash.Hash // next MAC algorithm + + trafficSecret []byte // current TLS 1.3 traffic secret + + setKeyCallback func(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte) +} + +type permanentError struct { + err net.Error +} + +func (e *permanentError) Error() string { return e.err.Error() } +func (e *permanentError) Unwrap() error { return e.err } +func (e *permanentError) Timeout() bool { return e.err.Timeout() } +func (e *permanentError) Temporary() bool { return false } + +func (hc *halfConn) setErrorLocked(err error) error { + if e, ok := err.(net.Error); ok { + hc.err = &permanentError{err: e} + } else { + hc.err = err + } + return hc.err +} + +// prepareCipherSpec sets the encryption and MAC states +// that a subsequent changeCipherSpec will use. +func (hc *halfConn) prepareCipherSpec(version uint16, cipher any, mac hash.Hash) { + hc.version = version + hc.nextCipher = cipher + hc.nextMac = mac +} + +// changeCipherSpec changes the encryption and MAC states +// to the ones previously passed to prepareCipherSpec. +func (hc *halfConn) changeCipherSpec() error { + if hc.nextCipher == nil || hc.version == VersionTLS13 { + return alertInternalError + } + hc.cipher = hc.nextCipher + hc.mac = hc.nextMac + hc.nextCipher = nil + hc.nextMac = nil + for i := range hc.seq { + hc.seq[i] = 0 + } + return nil +} + +func (hc *halfConn) exportKey(encLevel EncryptionLevel, suite *cipherSuiteTLS13, trafficSecret []byte) { + if hc.setKeyCallback != nil { + s := &CipherSuiteTLS13{ + ID: suite.id, + KeyLen: suite.keyLen, + Hash: suite.hash, + AEAD: func(key, fixedNonce []byte) cipher.AEAD { return suite.aead(key, fixedNonce) }, + } + hc.setKeyCallback(encLevel, s, trafficSecret) + } +} + +func (hc *halfConn) setTrafficSecret(suite *cipherSuiteTLS13, secret []byte) { + hc.trafficSecret = secret + key, iv := suite.trafficKey(secret) + hc.cipher = suite.aead(key, iv) + for i := range hc.seq { + hc.seq[i] = 0 + } +} + +// incSeq increments the sequence number. +func (hc *halfConn) incSeq() { + for i := 7; i >= 0; i-- { + hc.seq[i]++ + if hc.seq[i] != 0 { + return + } + } + + // Not allowed to let sequence number wrap. + // Instead, must renegotiate before it does. + // Not likely enough to bother. + panic("TLS: sequence number wraparound") +} + +// explicitNonceLen returns the number of bytes of explicit nonce or IV included +// in each record. Explicit nonces are present only in CBC modes after TLS 1.0 +// and in certain AEAD modes in TLS 1.2. +func (hc *halfConn) explicitNonceLen() int { + if hc.cipher == nil { + return 0 + } + + switch c := hc.cipher.(type) { + case cipher.Stream: + return 0 + case aead: + return c.explicitNonceLen() + case cbcMode: + // TLS 1.1 introduced a per-record explicit IV to fix the BEAST attack. + if hc.version >= VersionTLS11 { + return c.BlockSize() + } + return 0 + default: + panic("unknown cipher type") + } +} + +// extractPadding returns, in constant time, the length of the padding to remove +// from the end of payload. It also returns a byte which is equal to 255 if the +// padding was valid and 0 otherwise. See RFC 2246, Section 6.2.3.2. +func extractPadding(payload []byte) (toRemove int, good byte) { + if len(payload) < 1 { + return 0, 0 + } + + paddingLen := payload[len(payload)-1] + t := uint(len(payload)-1) - uint(paddingLen) + // if len(payload) >= (paddingLen - 1) then the MSB of t is zero + good = byte(int32(^t) >> 31) + + // The maximum possible padding length plus the actual length field + toCheck := 256 + // The length of the padded data is public, so we can use an if here + if toCheck > len(payload) { + toCheck = len(payload) + } + + for i := 0; i < toCheck; i++ { + t := uint(paddingLen) - uint(i) + // if i <= paddingLen then the MSB of t is zero + mask := byte(int32(^t) >> 31) + b := payload[len(payload)-1-i] + good &^= mask&paddingLen ^ mask&b + } + + // We AND together the bits of good and replicate the result across + // all the bits. + good &= good << 4 + good &= good << 2 + good &= good << 1 + good = uint8(int8(good) >> 7) + + // Zero the padding length on error. This ensures any unchecked bytes + // are included in the MAC. Otherwise, an attacker that could + // distinguish MAC failures from padding failures could mount an attack + // similar to POODLE in SSL 3.0: given a good ciphertext that uses a + // full block's worth of padding, replace the final block with another + // block. If the MAC check passed but the padding check failed, the + // last byte of that block decrypted to the block size. + // + // See also macAndPaddingGood logic below. + paddingLen &= good + + toRemove = int(paddingLen) + 1 + return +} + +func roundUp(a, b int) int { + return a + (b-a%b)%b +} + +// cbcMode is an interface for block ciphers using cipher block chaining. +type cbcMode interface { + cipher.BlockMode + SetIV([]byte) +} + +// decrypt authenticates and decrypts the record if protection is active at +// this stage. The returned plaintext might overlap with the input. +func (hc *halfConn) decrypt(record []byte) ([]byte, recordType, error) { + var plaintext []byte + typ := recordType(record[0]) + payload := record[recordHeaderLen:] + + // In TLS 1.3, change_cipher_spec messages are to be ignored without being + // decrypted. See RFC 8446, Appendix D.4. + if hc.version == VersionTLS13 && typ == recordTypeChangeCipherSpec { + return payload, typ, nil + } + + paddingGood := byte(255) + paddingLen := 0 + + explicitNonceLen := hc.explicitNonceLen() + + if hc.cipher != nil { + switch c := hc.cipher.(type) { + case cipher.Stream: + c.XORKeyStream(payload, payload) + case aead: + if len(payload) < explicitNonceLen { + return nil, 0, alertBadRecordMAC + } + nonce := payload[:explicitNonceLen] + if len(nonce) == 0 { + nonce = hc.seq[:] + } + payload = payload[explicitNonceLen:] + + var additionalData []byte + if hc.version == VersionTLS13 { + additionalData = record[:recordHeaderLen] + } else { + additionalData = append(hc.scratchBuf[:0], hc.seq[:]...) + additionalData = append(additionalData, record[:3]...) + n := len(payload) - c.Overhead() + additionalData = append(additionalData, byte(n>>8), byte(n)) + } + + var err error + plaintext, err = c.Open(payload[:0], nonce, payload, additionalData) + if err != nil { + return nil, 0, alertBadRecordMAC + } + case cbcMode: + blockSize := c.BlockSize() + minPayload := explicitNonceLen + roundUp(hc.mac.Size()+1, blockSize) + if len(payload)%blockSize != 0 || len(payload) < minPayload { + return nil, 0, alertBadRecordMAC + } + + if explicitNonceLen > 0 { + c.SetIV(payload[:explicitNonceLen]) + payload = payload[explicitNonceLen:] + } + c.CryptBlocks(payload, payload) + + // In a limited attempt to protect against CBC padding oracles like + // Lucky13, the data past paddingLen (which is secret) is passed to + // the MAC function as extra data, to be fed into the HMAC after + // computing the digest. This makes the MAC roughly constant time as + // long as the digest computation is constant time and does not + // affect the subsequent write, modulo cache effects. + paddingLen, paddingGood = extractPadding(payload) + default: + panic("unknown cipher type") + } + + if hc.version == VersionTLS13 { + if typ != recordTypeApplicationData { + return nil, 0, alertUnexpectedMessage + } + if len(plaintext) > maxPlaintext+1 { + return nil, 0, alertRecordOverflow + } + // Remove padding and find the ContentType scanning from the end. + for i := len(plaintext) - 1; i >= 0; i-- { + if plaintext[i] != 0 { + typ = recordType(plaintext[i]) + plaintext = plaintext[:i] + break + } + if i == 0 { + return nil, 0, alertUnexpectedMessage + } + } + } + } else { + plaintext = payload + } + + if hc.mac != nil { + macSize := hc.mac.Size() + if len(payload) < macSize { + return nil, 0, alertBadRecordMAC + } + + n := len(payload) - macSize - paddingLen + n = subtle.ConstantTimeSelect(int(uint32(n)>>31), 0, n) // if n < 0 { n = 0 } + record[3] = byte(n >> 8) + record[4] = byte(n) + remoteMAC := payload[n : n+macSize] + localMAC := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload[:n], payload[n+macSize:]) + + // This is equivalent to checking the MACs and paddingGood + // separately, but in constant-time to prevent distinguishing + // padding failures from MAC failures. Depending on what value + // of paddingLen was returned on bad padding, distinguishing + // bad MAC from bad padding can lead to an attack. + // + // See also the logic at the end of extractPadding. + macAndPaddingGood := subtle.ConstantTimeCompare(localMAC, remoteMAC) & int(paddingGood) + if macAndPaddingGood != 1 { + return nil, 0, alertBadRecordMAC + } + + plaintext = payload[:n] + } + + hc.incSeq() + return plaintext, typ, nil +} + +func (c *Conn) setAlternativeRecordLayer() { + if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil { + c.in.setKeyCallback = c.extraConfig.AlternativeRecordLayer.SetReadKey + c.out.setKeyCallback = c.extraConfig.AlternativeRecordLayer.SetWriteKey + } +} + +// sliceForAppend extends the input slice by n bytes. head is the full extended +// slice, while tail is the appended part. If the original slice has sufficient +// capacity no allocation is performed. +func sliceForAppend(in []byte, n int) (head, tail []byte) { + if total := len(in) + n; cap(in) >= total { + head = in[:total] + } else { + head = make([]byte, total) + copy(head, in) + } + tail = head[len(in):] + return +} + +// encrypt encrypts payload, adding the appropriate nonce and/or MAC, and +// appends it to record, which must already contain the record header. +func (hc *halfConn) encrypt(record, payload []byte, rand io.Reader) ([]byte, error) { + if hc.cipher == nil { + return append(record, payload...), nil + } + + var explicitNonce []byte + if explicitNonceLen := hc.explicitNonceLen(); explicitNonceLen > 0 { + record, explicitNonce = sliceForAppend(record, explicitNonceLen) + if _, isCBC := hc.cipher.(cbcMode); !isCBC && explicitNonceLen < 16 { + // The AES-GCM construction in TLS has an explicit nonce so that the + // nonce can be random. However, the nonce is only 8 bytes which is + // too small for a secure, random nonce. Therefore we use the + // sequence number as the nonce. The 3DES-CBC construction also has + // an 8 bytes nonce but its nonces must be unpredictable (see RFC + // 5246, Appendix F.3), forcing us to use randomness. That's not + // 3DES' biggest problem anyway because the birthday bound on block + // collision is reached first due to its similarly small block size + // (see the Sweet32 attack). + copy(explicitNonce, hc.seq[:]) + } else { + if _, err := io.ReadFull(rand, explicitNonce); err != nil { + return nil, err + } + } + } + + var dst []byte + switch c := hc.cipher.(type) { + case cipher.Stream: + mac := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload, nil) + record, dst = sliceForAppend(record, len(payload)+len(mac)) + c.XORKeyStream(dst[:len(payload)], payload) + c.XORKeyStream(dst[len(payload):], mac) + case aead: + nonce := explicitNonce + if len(nonce) == 0 { + nonce = hc.seq[:] + } + + if hc.version == VersionTLS13 { + record = append(record, payload...) + + // Encrypt the actual ContentType and replace the plaintext one. + record = append(record, record[0]) + record[0] = byte(recordTypeApplicationData) + + n := len(payload) + 1 + c.Overhead() + record[3] = byte(n >> 8) + record[4] = byte(n) + + record = c.Seal(record[:recordHeaderLen], + nonce, record[recordHeaderLen:], record[:recordHeaderLen]) + } else { + additionalData := append(hc.scratchBuf[:0], hc.seq[:]...) + additionalData = append(additionalData, record[:recordHeaderLen]...) + record = c.Seal(record, nonce, payload, additionalData) + } + case cbcMode: + mac := tls10MAC(hc.mac, hc.scratchBuf[:0], hc.seq[:], record[:recordHeaderLen], payload, nil) + blockSize := c.BlockSize() + plaintextLen := len(payload) + len(mac) + paddingLen := blockSize - plaintextLen%blockSize + record, dst = sliceForAppend(record, plaintextLen+paddingLen) + copy(dst, payload) + copy(dst[len(payload):], mac) + for i := plaintextLen; i < len(dst); i++ { + dst[i] = byte(paddingLen - 1) + } + if len(explicitNonce) > 0 { + c.SetIV(explicitNonce) + } + c.CryptBlocks(dst, dst) + default: + panic("unknown cipher type") + } + + // Update length to include nonce, MAC and any block padding needed. + n := len(record) - recordHeaderLen + record[3] = byte(n >> 8) + record[4] = byte(n) + hc.incSeq() + + return record, nil +} + +// RecordHeaderError is returned when a TLS record header is invalid. +type RecordHeaderError struct { + // Msg contains a human readable string that describes the error. + Msg string + // RecordHeader contains the five bytes of TLS record header that + // triggered the error. + RecordHeader [5]byte + // Conn provides the underlying net.Conn in the case that a client + // sent an initial handshake that didn't look like TLS. + // It is nil if there's already been a handshake or a TLS alert has + // been written to the connection. + Conn net.Conn +} + +func (e RecordHeaderError) Error() string { return "tls: " + e.Msg } + +func (c *Conn) newRecordHeaderError(conn net.Conn, msg string) (err RecordHeaderError) { + err.Msg = msg + err.Conn = conn + copy(err.RecordHeader[:], c.rawInput.Bytes()) + return err +} + +func (c *Conn) readRecord() error { + return c.readRecordOrCCS(false) +} + +func (c *Conn) readChangeCipherSpec() error { + return c.readRecordOrCCS(true) +} + +// readRecordOrCCS reads one or more TLS records from the connection and +// updates the record layer state. Some invariants: +// - c.in must be locked +// - c.input must be empty +// +// During the handshake one and only one of the following will happen: +// - c.hand grows +// - c.in.changeCipherSpec is called +// - an error is returned +// +// After the handshake one and only one of the following will happen: +// - c.hand grows +// - c.input is set +// - an error is returned +func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error { + if c.in.err != nil { + return c.in.err + } + handshakeComplete := c.handshakeComplete() + + // This function modifies c.rawInput, which owns the c.input memory. + if c.input.Len() != 0 { + return c.in.setErrorLocked(errors.New("tls: internal error: attempted to read record with pending application data")) + } + c.input.Reset(nil) + + // Read header, payload. + if err := c.readFromUntil(c.conn, recordHeaderLen); err != nil { + // RFC 8446, Section 6.1 suggests that EOF without an alertCloseNotify + // is an error, but popular web sites seem to do this, so we accept it + // if and only if at the record boundary. + if err == io.ErrUnexpectedEOF && c.rawInput.Len() == 0 { + err = io.EOF + } + if e, ok := err.(net.Error); !ok || !e.Temporary() { + c.in.setErrorLocked(err) + } + return err + } + hdr := c.rawInput.Bytes()[:recordHeaderLen] + typ := recordType(hdr[0]) + + // No valid TLS record has a type of 0x80, however SSLv2 handshakes + // start with a uint16 length where the MSB is set and the first record + // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests + // an SSLv2 client. + if !handshakeComplete && typ == 0x80 { + c.sendAlert(alertProtocolVersion) + return c.in.setErrorLocked(c.newRecordHeaderError(nil, "unsupported SSLv2 handshake received")) + } + + vers := uint16(hdr[1])<<8 | uint16(hdr[2]) + n := int(hdr[3])<<8 | int(hdr[4]) + if c.haveVers && c.vers != VersionTLS13 && vers != c.vers { + c.sendAlert(alertProtocolVersion) + msg := fmt.Sprintf("received record with version %x when expecting version %x", vers, c.vers) + return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg)) + } + if !c.haveVers { + // First message, be extra suspicious: this might not be a TLS + // client. Bail out before reading a full 'body', if possible. + // The current max version is 3.3 so if the version is >= 16.0, + // it's probably not real. + if (typ != recordTypeAlert && typ != recordTypeHandshake) || vers >= 0x1000 { + return c.in.setErrorLocked(c.newRecordHeaderError(c.conn, "first record does not look like a TLS handshake")) + } + } + if c.vers == VersionTLS13 && n > maxCiphertextTLS13 || n > maxCiphertext { + c.sendAlert(alertRecordOverflow) + msg := fmt.Sprintf("oversized record received with length %d", n) + return c.in.setErrorLocked(c.newRecordHeaderError(nil, msg)) + } + if err := c.readFromUntil(c.conn, recordHeaderLen+n); err != nil { + if e, ok := err.(net.Error); !ok || !e.Temporary() { + c.in.setErrorLocked(err) + } + return err + } + + // Process message. + record := c.rawInput.Next(recordHeaderLen + n) + data, typ, err := c.in.decrypt(record) + if err != nil { + return c.in.setErrorLocked(c.sendAlert(err.(alert))) + } + if len(data) > maxPlaintext { + return c.in.setErrorLocked(c.sendAlert(alertRecordOverflow)) + } + + // Application Data messages are always protected. + if c.in.cipher == nil && typ == recordTypeApplicationData { + return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) + } + + if typ != recordTypeAlert && typ != recordTypeChangeCipherSpec && len(data) > 0 { + // This is a state-advancing message: reset the retry count. + c.retryCount = 0 + } + + // Handshake messages MUST NOT be interleaved with other record types in TLS 1.3. + if c.vers == VersionTLS13 && typ != recordTypeHandshake && c.hand.Len() > 0 { + return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) + } + + switch typ { + default: + return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) + + case recordTypeAlert: + if len(data) != 2 { + return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) + } + if alert(data[1]) == alertCloseNotify { + return c.in.setErrorLocked(io.EOF) + } + if c.vers == VersionTLS13 { + return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) + } + switch data[0] { + case alertLevelWarning: + // Drop the record on the floor and retry. + return c.retryReadRecord(expectChangeCipherSpec) + case alertLevelError: + return c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) + default: + return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) + } + + case recordTypeChangeCipherSpec: + if len(data) != 1 || data[0] != 1 { + return c.in.setErrorLocked(c.sendAlert(alertDecodeError)) + } + // Handshake messages are not allowed to fragment across the CCS. + if c.hand.Len() > 0 { + return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) + } + // In TLS 1.3, change_cipher_spec records are ignored until the + // Finished. See RFC 8446, Appendix D.4. Note that according to Section + // 5, a server can send a ChangeCipherSpec before its ServerHello, when + // c.vers is still unset. That's not useful though and suspicious if the + // server then selects a lower protocol version, so don't allow that. + if c.vers == VersionTLS13 { + return c.retryReadRecord(expectChangeCipherSpec) + } + if !expectChangeCipherSpec { + return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) + } + if err := c.in.changeCipherSpec(); err != nil { + return c.in.setErrorLocked(c.sendAlert(err.(alert))) + } + + case recordTypeApplicationData: + if !handshakeComplete || expectChangeCipherSpec { + return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) + } + // Some OpenSSL servers send empty records in order to randomize the + // CBC IV. Ignore a limited number of empty records. + if len(data) == 0 { + return c.retryReadRecord(expectChangeCipherSpec) + } + // Note that data is owned by c.rawInput, following the Next call above, + // to avoid copying the plaintext. This is safe because c.rawInput is + // not read from or written to until c.input is drained. + c.input.Reset(data) + + case recordTypeHandshake: + if len(data) == 0 || expectChangeCipherSpec { + return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) + } + c.hand.Write(data) + } + + return nil +} + +// retryReadRecord recurs into readRecordOrCCS to drop a non-advancing record, like +// a warning alert, empty application_data, or a change_cipher_spec in TLS 1.3. +func (c *Conn) retryReadRecord(expectChangeCipherSpec bool) error { + c.retryCount++ + if c.retryCount > maxUselessRecords { + c.sendAlert(alertUnexpectedMessage) + return c.in.setErrorLocked(errors.New("tls: too many ignored records")) + } + return c.readRecordOrCCS(expectChangeCipherSpec) +} + +// atLeastReader reads from R, stopping with EOF once at least N bytes have been +// read. It is different from an io.LimitedReader in that it doesn't cut short +// the last Read call, and in that it considers an early EOF an error. +type atLeastReader struct { + R io.Reader + N int64 +} + +func (r *atLeastReader) Read(p []byte) (int, error) { + if r.N <= 0 { + return 0, io.EOF + } + n, err := r.R.Read(p) + r.N -= int64(n) // won't underflow unless len(p) >= n > 9223372036854775809 + if r.N > 0 && err == io.EOF { + return n, io.ErrUnexpectedEOF + } + if r.N <= 0 && err == nil { + return n, io.EOF + } + return n, err +} + +// readFromUntil reads from r into c.rawInput until c.rawInput contains +// at least n bytes or else returns an error. +func (c *Conn) readFromUntil(r io.Reader, n int) error { + if c.rawInput.Len() >= n { + return nil + } + needs := n - c.rawInput.Len() + // There might be extra input waiting on the wire. Make a best effort + // attempt to fetch it so that it can be used in (*Conn).Read to + // "predict" closeNotify alerts. + c.rawInput.Grow(needs + bytes.MinRead) + _, err := c.rawInput.ReadFrom(&atLeastReader{r, int64(needs)}) + return err +} + +// sendAlert sends a TLS alert message. +func (c *Conn) sendAlertLocked(err alert) error { + switch err { + case alertNoRenegotiation, alertCloseNotify: + c.tmp[0] = alertLevelWarning + default: + c.tmp[0] = alertLevelError + } + c.tmp[1] = byte(err) + + _, writeErr := c.writeRecordLocked(recordTypeAlert, c.tmp[0:2]) + if err == alertCloseNotify { + // closeNotify is a special case in that it isn't an error. + return writeErr + } + + return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) +} + +// sendAlert sends a TLS alert message. +func (c *Conn) sendAlert(err alert) error { + if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil { + c.extraConfig.AlternativeRecordLayer.SendAlert(uint8(err)) + return &net.OpError{Op: "local error", Err: err} + } + + c.out.Lock() + defer c.out.Unlock() + return c.sendAlertLocked(err) +} + +const ( + // tcpMSSEstimate is a conservative estimate of the TCP maximum segment + // size (MSS). A constant is used, rather than querying the kernel for + // the actual MSS, to avoid complexity. The value here is the IPv6 + // minimum MTU (1280 bytes) minus the overhead of an IPv6 header (40 + // bytes) and a TCP header with timestamps (32 bytes). + tcpMSSEstimate = 1208 + + // recordSizeBoostThreshold is the number of bytes of application data + // sent after which the TLS record size will be increased to the + // maximum. + recordSizeBoostThreshold = 128 * 1024 +) + +// maxPayloadSizeForWrite returns the maximum TLS payload size to use for the +// next application data record. There is the following trade-off: +// +// - For latency-sensitive applications, such as web browsing, each TLS +// record should fit in one TCP segment. +// - For throughput-sensitive applications, such as large file transfers, +// larger TLS records better amortize framing and encryption overheads. +// +// A simple heuristic that works well in practice is to use small records for +// the first 1MB of data, then use larger records for subsequent data, and +// reset back to smaller records after the connection becomes idle. See "High +// Performance Web Networking", Chapter 4, or: +// https://www.igvita.com/2013/10/24/optimizing-tls-record-size-and-buffering-latency/ +// +// In the interests of simplicity and determinism, this code does not attempt +// to reset the record size once the connection is idle, however. +func (c *Conn) maxPayloadSizeForWrite(typ recordType) int { + if c.config.DynamicRecordSizingDisabled || typ != recordTypeApplicationData { + return maxPlaintext + } + + if c.bytesSent >= recordSizeBoostThreshold { + return maxPlaintext + } + + // Subtract TLS overheads to get the maximum payload size. + payloadBytes := tcpMSSEstimate - recordHeaderLen - c.out.explicitNonceLen() + if c.out.cipher != nil { + switch ciph := c.out.cipher.(type) { + case cipher.Stream: + payloadBytes -= c.out.mac.Size() + case cipher.AEAD: + payloadBytes -= ciph.Overhead() + case cbcMode: + blockSize := ciph.BlockSize() + // The payload must fit in a multiple of blockSize, with + // room for at least one padding byte. + payloadBytes = (payloadBytes & ^(blockSize - 1)) - 1 + // The MAC is appended before padding so affects the + // payload size directly. + payloadBytes -= c.out.mac.Size() + default: + panic("unknown cipher type") + } + } + if c.vers == VersionTLS13 { + payloadBytes-- // encrypted ContentType + } + + // Allow packet growth in arithmetic progression up to max. + pkt := c.packetsSent + c.packetsSent++ + if pkt > 1000 { + return maxPlaintext // avoid overflow in multiply below + } + + n := payloadBytes * int(pkt+1) + if n > maxPlaintext { + n = maxPlaintext + } + return n +} + +func (c *Conn) write(data []byte) (int, error) { + if c.buffering { + c.sendBuf = append(c.sendBuf, data...) + return len(data), nil + } + + n, err := c.conn.Write(data) + c.bytesSent += int64(n) + return n, err +} + +func (c *Conn) flush() (int, error) { + if len(c.sendBuf) == 0 { + return 0, nil + } + + n, err := c.conn.Write(c.sendBuf) + c.bytesSent += int64(n) + c.sendBuf = nil + c.buffering = false + return n, err +} + +// outBufPool pools the record-sized scratch buffers used by writeRecordLocked. +var outBufPool = sync.Pool{ + New: func() any { + return new([]byte) + }, +} + +// writeRecordLocked writes a TLS record with the given type and payload to the +// connection and updates the record layer state. +func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) { + outBufPtr := outBufPool.Get().(*[]byte) + outBuf := *outBufPtr + defer func() { + // You might be tempted to simplify this by just passing &outBuf to Put, + // but that would make the local copy of the outBuf slice header escape + // to the heap, causing an allocation. Instead, we keep around the + // pointer to the slice header returned by Get, which is already on the + // heap, and overwrite and return that. + *outBufPtr = outBuf + outBufPool.Put(outBufPtr) + }() + + var n int + for len(data) > 0 { + m := len(data) + if maxPayload := c.maxPayloadSizeForWrite(typ); m > maxPayload { + m = maxPayload + } + + _, outBuf = sliceForAppend(outBuf[:0], recordHeaderLen) + outBuf[0] = byte(typ) + vers := c.vers + if vers == 0 { + // Some TLS servers fail if the record version is + // greater than TLS 1.0 for the initial ClientHello. + vers = VersionTLS10 + } else if vers == VersionTLS13 { + // TLS 1.3 froze the record layer version to 1.2. + // See RFC 8446, Section 5.1. + vers = VersionTLS12 + } + outBuf[1] = byte(vers >> 8) + outBuf[2] = byte(vers) + outBuf[3] = byte(m >> 8) + outBuf[4] = byte(m) + + var err error + outBuf, err = c.out.encrypt(outBuf, data[:m], c.config.rand()) + if err != nil { + return n, err + } + if _, err := c.write(outBuf); err != nil { + return n, err + } + n += m + data = data[m:] + } + + if typ == recordTypeChangeCipherSpec && c.vers != VersionTLS13 { + if err := c.out.changeCipherSpec(); err != nil { + return n, c.sendAlertLocked(err.(alert)) + } + } + + return n, nil +} + +// writeHandshakeRecord writes a handshake message to the connection and updates +// the record layer state. If transcript is non-nil the marshalled message is +// written to it. +func (c *Conn) writeHandshakeRecord(msg handshakeMessage, transcript transcriptHash) (int, error) { + data, err := msg.marshal() + if err != nil { + return 0, err + } + + c.out.Lock() + defer c.out.Unlock() + + if transcript != nil { + transcript.Write(data) + } + + if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil { + return c.extraConfig.AlternativeRecordLayer.WriteRecord(data) + } + + return c.writeRecordLocked(recordTypeHandshake, data) +} + +// writeChangeCipherRecord writes a ChangeCipherSpec message to the connection and +// updates the record layer state. +func (c *Conn) writeChangeCipherRecord() error { + if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil { + return nil + } + + c.out.Lock() + defer c.out.Unlock() + _, err := c.writeRecordLocked(recordTypeChangeCipherSpec, []byte{1}) + return err +} + +// readHandshake reads the next handshake message from +// the record layer. If transcript is non-nil, the message +// is written to the passed transcriptHash. +func (c *Conn) readHandshake(transcript transcriptHash) (any, error) { + var data []byte + if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil { + var err error + data, err = c.extraConfig.AlternativeRecordLayer.ReadHandshakeMessage() + if err != nil { + return nil, err + } + } else { + for c.hand.Len() < 4 { + if err := c.readRecord(); err != nil { + return nil, err + } + } + + data = c.hand.Bytes() + n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) + if n > maxHandshake { + c.sendAlertLocked(alertInternalError) + return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake)) + } + for c.hand.Len() < 4+n { + if err := c.readRecord(); err != nil { + return nil, err + } + } + data = c.hand.Next(4 + n) + } + var m handshakeMessage + switch data[0] { + case typeHelloRequest: + m = new(helloRequestMsg) + case typeClientHello: + m = new(clientHelloMsg) + case typeServerHello: + m = new(serverHelloMsg) + case typeNewSessionTicket: + if c.vers == VersionTLS13 { + m = new(newSessionTicketMsgTLS13) + } else { + m = new(newSessionTicketMsg) + } + case typeCertificate: + if c.vers == VersionTLS13 { + m = new(certificateMsgTLS13) + } else { + m = new(certificateMsg) + } + case typeCertificateRequest: + if c.vers == VersionTLS13 { + m = new(certificateRequestMsgTLS13) + } else { + m = &certificateRequestMsg{ + hasSignatureAlgorithm: c.vers >= VersionTLS12, + } + } + case typeCertificateStatus: + m = new(certificateStatusMsg) + case typeServerKeyExchange: + m = new(serverKeyExchangeMsg) + case typeServerHelloDone: + m = new(serverHelloDoneMsg) + case typeClientKeyExchange: + m = new(clientKeyExchangeMsg) + case typeCertificateVerify: + m = &certificateVerifyMsg{ + hasSignatureAlgorithm: c.vers >= VersionTLS12, + } + case typeFinished: + m = new(finishedMsg) + case typeEncryptedExtensions: + m = new(encryptedExtensionsMsg) + case typeEndOfEarlyData: + m = new(endOfEarlyDataMsg) + case typeKeyUpdate: + m = new(keyUpdateMsg) + default: + return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) + } + + // The handshake message unmarshalers + // expect to be able to keep references to data, + // so pass in a fresh copy that won't be overwritten. + data = append([]byte(nil), data...) + + if !m.unmarshal(data) { + return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) + } + + if transcript != nil { + transcript.Write(data) + } + + return m, nil +} + +var ( + errShutdown = errors.New("tls: protocol is shutdown") +) + +// Write writes data to the connection. +// +// As Write calls Handshake, in order to prevent indefinite blocking a deadline +// must be set for both Read and Write before Write is called when the handshake +// has not yet completed. See SetDeadline, SetReadDeadline, and +// SetWriteDeadline. +func (c *Conn) Write(b []byte) (int, error) { + // interlock with Close below + for { + x := atomic.LoadInt32(&c.activeCall) + if x&1 != 0 { + return 0, net.ErrClosed + } + if atomic.CompareAndSwapInt32(&c.activeCall, x, x+2) { + break + } + } + defer atomic.AddInt32(&c.activeCall, -2) + + if err := c.Handshake(); err != nil { + return 0, err + } + + c.out.Lock() + defer c.out.Unlock() + + if err := c.out.err; err != nil { + return 0, err + } + + if !c.handshakeComplete() { + return 0, alertInternalError + } + + if c.closeNotifySent { + return 0, errShutdown + } + + // TLS 1.0 is susceptible to a chosen-plaintext + // attack when using block mode ciphers due to predictable IVs. + // This can be prevented by splitting each Application Data + // record into two records, effectively randomizing the IV. + // + // https://www.openssl.org/~bodo/tls-cbc.txt + // https://bugzilla.mozilla.org/show_bug.cgi?id=665814 + // https://www.imperialviolet.org/2012/01/15/beastfollowup.html + + var m int + if len(b) > 1 && c.vers == VersionTLS10 { + if _, ok := c.out.cipher.(cipher.BlockMode); ok { + n, err := c.writeRecordLocked(recordTypeApplicationData, b[:1]) + if err != nil { + return n, c.out.setErrorLocked(err) + } + m, b = 1, b[1:] + } + } + + n, err := c.writeRecordLocked(recordTypeApplicationData, b) + return n + m, c.out.setErrorLocked(err) +} + +// handleRenegotiation processes a HelloRequest handshake message. +func (c *Conn) handleRenegotiation() error { + if c.vers == VersionTLS13 { + return errors.New("tls: internal error: unexpected renegotiation") + } + + msg, err := c.readHandshake(nil) + if err != nil { + return err + } + + helloReq, ok := msg.(*helloRequestMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(helloReq, msg) + } + + if !c.isClient { + return c.sendAlert(alertNoRenegotiation) + } + + switch c.config.Renegotiation { + case RenegotiateNever: + return c.sendAlert(alertNoRenegotiation) + case RenegotiateOnceAsClient: + if c.handshakes > 1 { + return c.sendAlert(alertNoRenegotiation) + } + case RenegotiateFreelyAsClient: + // Ok. + default: + c.sendAlert(alertInternalError) + return errors.New("tls: unknown Renegotiation value") + } + + c.handshakeMutex.Lock() + defer c.handshakeMutex.Unlock() + + atomic.StoreUint32(&c.handshakeStatus, 0) + if c.handshakeErr = c.clientHandshake(context.Background()); c.handshakeErr == nil { + c.handshakes++ + } + return c.handshakeErr +} + +func (c *Conn) HandlePostHandshakeMessage() error { + return c.handlePostHandshakeMessage() +} + +// handlePostHandshakeMessage processes a handshake message arrived after the +// handshake is complete. Up to TLS 1.2, it indicates the start of a renegotiation. +func (c *Conn) handlePostHandshakeMessage() error { + if c.vers != VersionTLS13 { + return c.handleRenegotiation() + } + + msg, err := c.readHandshake(nil) + if err != nil { + return err + } + + c.retryCount++ + if c.retryCount > maxUselessRecords { + c.sendAlert(alertUnexpectedMessage) + return c.in.setErrorLocked(errors.New("tls: too many non-advancing records")) + } + + switch msg := msg.(type) { + case *newSessionTicketMsgTLS13: + return c.handleNewSessionTicket(msg) + case *keyUpdateMsg: + return c.handleKeyUpdate(msg) + default: + c.sendAlert(alertUnexpectedMessage) + return fmt.Errorf("tls: received unexpected handshake message of type %T", msg) + } +} + +func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error { + cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) + if cipherSuite == nil { + return c.in.setErrorLocked(c.sendAlert(alertInternalError)) + } + + newSecret := cipherSuite.nextTrafficSecret(c.in.trafficSecret) + c.in.setTrafficSecret(cipherSuite, newSecret) + + if keyUpdate.updateRequested { + c.out.Lock() + defer c.out.Unlock() + + msg := &keyUpdateMsg{} + msgBytes, err := msg.marshal() + if err != nil { + return err + } + _, err = c.writeRecordLocked(recordTypeHandshake, msgBytes) + if err != nil { + // Surface the error at the next write. + c.out.setErrorLocked(err) + return nil + } + + newSecret := cipherSuite.nextTrafficSecret(c.out.trafficSecret) + c.out.setTrafficSecret(cipherSuite, newSecret) + } + + return nil +} + +// Read reads data from the connection. +// +// As Read calls Handshake, in order to prevent indefinite blocking a deadline +// must be set for both Read and Write before Read is called when the handshake +// has not yet completed. See SetDeadline, SetReadDeadline, and +// SetWriteDeadline. +func (c *Conn) Read(b []byte) (int, error) { + if err := c.Handshake(); err != nil { + return 0, err + } + if len(b) == 0 { + // Put this after Handshake, in case people were calling + // Read(nil) for the side effect of the Handshake. + return 0, nil + } + + c.in.Lock() + defer c.in.Unlock() + + for c.input.Len() == 0 { + if err := c.readRecord(); err != nil { + return 0, err + } + for c.hand.Len() > 0 { + if err := c.handlePostHandshakeMessage(); err != nil { + return 0, err + } + } + } + + n, _ := c.input.Read(b) + + // If a close-notify alert is waiting, read it so that we can return (n, + // EOF) instead of (n, nil), to signal to the HTTP response reading + // goroutine that the connection is now closed. This eliminates a race + // where the HTTP response reading goroutine would otherwise not observe + // the EOF until its next read, by which time a client goroutine might + // have already tried to reuse the HTTP connection for a new request. + // See https://golang.org/cl/76400046 and https://golang.org/issue/3514 + if n != 0 && c.input.Len() == 0 && c.rawInput.Len() > 0 && + recordType(c.rawInput.Bytes()[0]) == recordTypeAlert { + if err := c.readRecord(); err != nil { + return n, err // will be io.EOF on closeNotify + } + } + + return n, nil +} + +// Close closes the connection. +func (c *Conn) Close() error { + // Interlock with Conn.Write above. + var x int32 + for { + x = atomic.LoadInt32(&c.activeCall) + if x&1 != 0 { + return net.ErrClosed + } + if atomic.CompareAndSwapInt32(&c.activeCall, x, x|1) { + break + } + } + if x != 0 { + // io.Writer and io.Closer should not be used concurrently. + // If Close is called while a Write is currently in-flight, + // interpret that as a sign that this Close is really just + // being used to break the Write and/or clean up resources and + // avoid sending the alertCloseNotify, which may block + // waiting on handshakeMutex or the c.out mutex. + return c.conn.Close() + } + + var alertErr error + if c.handshakeComplete() { + if err := c.closeNotify(); err != nil { + alertErr = fmt.Errorf("tls: failed to send closeNotify alert (but connection was closed anyway): %w", err) + } + } + + if err := c.conn.Close(); err != nil { + return err + } + return alertErr +} + +var errEarlyCloseWrite = errors.New("tls: CloseWrite called before handshake complete") + +// CloseWrite shuts down the writing side of the connection. It should only be +// called once the handshake has completed and does not call CloseWrite on the +// underlying connection. Most callers should just use Close. +func (c *Conn) CloseWrite() error { + if !c.handshakeComplete() { + return errEarlyCloseWrite + } + + return c.closeNotify() +} + +func (c *Conn) closeNotify() error { + c.out.Lock() + defer c.out.Unlock() + + if !c.closeNotifySent { + // Set a Write Deadline to prevent possibly blocking forever. + c.SetWriteDeadline(time.Now().Add(time.Second * 5)) + c.closeNotifyErr = c.sendAlertLocked(alertCloseNotify) + c.closeNotifySent = true + // Any subsequent writes will fail. + c.SetWriteDeadline(time.Now()) + } + return c.closeNotifyErr +} + +// Handshake runs the client or server handshake +// protocol if it has not yet been run. +// +// Most uses of this package need not call Handshake explicitly: the +// first Read or Write will call it automatically. +// +// For control over canceling or setting a timeout on a handshake, use +// HandshakeContext or the Dialer's DialContext method instead. +func (c *Conn) Handshake() error { + return c.HandshakeContext(context.Background()) +} + +// HandshakeContext runs the client or server handshake +// protocol if it has not yet been run. +// +// The provided Context must be non-nil. If the context is canceled before +// the handshake is complete, the handshake is interrupted and an error is returned. +// Once the handshake has completed, cancellation of the context will not affect the +// connection. +// +// Most uses of this package need not call HandshakeContext explicitly: the +// first Read or Write will call it automatically. +func (c *Conn) HandshakeContext(ctx context.Context) error { + // Delegate to unexported method for named return + // without confusing documented signature. + return c.handshakeContext(ctx) +} + +func (c *Conn) handshakeContext(ctx context.Context) (ret error) { + // Fast sync/atomic-based exit if there is no handshake in flight and the + // last one succeeded without an error. Avoids the expensive context setup + // and mutex for most Read and Write calls. + if c.handshakeComplete() { + return nil + } + + handshakeCtx, cancel := context.WithCancel(ctx) + // Note: defer this before starting the "interrupter" goroutine + // so that we can tell the difference between the input being canceled and + // this cancellation. In the former case, we need to close the connection. + defer cancel() + + // Start the "interrupter" goroutine, if this context might be canceled. + // (The background context cannot). + // + // The interrupter goroutine waits for the input context to be done and + // closes the connection if this happens before the function returns. + if ctx.Done() != nil { + done := make(chan struct{}) + interruptRes := make(chan error, 1) + defer func() { + close(done) + if ctxErr := <-interruptRes; ctxErr != nil { + // Return context error to user. + ret = ctxErr + } + }() + go func() { + select { + case <-handshakeCtx.Done(): + // Close the connection, discarding the error + _ = c.conn.Close() + interruptRes <- handshakeCtx.Err() + case <-done: + interruptRes <- nil + } + }() + } + + c.handshakeMutex.Lock() + defer c.handshakeMutex.Unlock() + + if err := c.handshakeErr; err != nil { + return err + } + if c.handshakeComplete() { + return nil + } + + c.in.Lock() + defer c.in.Unlock() + + c.handshakeErr = c.handshakeFn(handshakeCtx) + if c.handshakeErr == nil { + c.handshakes++ + } else { + // If an error occurred during the handshake try to flush the + // alert that might be left in the buffer. + c.flush() + } + + if c.handshakeErr == nil && !c.handshakeComplete() { + c.handshakeErr = errors.New("tls: internal error: handshake should have had a result") + } + if c.handshakeErr != nil && c.handshakeComplete() { + panic("tls: internal error: handshake returned an error but is marked successful") + } + + return c.handshakeErr +} + +// ConnectionState returns basic TLS details about the connection. +func (c *Conn) ConnectionState() ConnectionState { + c.connStateMutex.Lock() + defer c.connStateMutex.Unlock() + return c.connState.ConnectionState +} + +// ConnectionStateWith0RTT returns basic TLS details (incl. 0-RTT status) about the connection. +func (c *Conn) ConnectionStateWith0RTT() ConnectionStateWith0RTT { + c.connStateMutex.Lock() + defer c.connStateMutex.Unlock() + return c.connState +} + +func (c *Conn) connectionStateLocked() ConnectionState { + var state connectionState + state.HandshakeComplete = c.handshakeComplete() + state.Version = c.vers + state.NegotiatedProtocol = c.clientProtocol + state.DidResume = c.didResume + state.NegotiatedProtocolIsMutual = true + state.ServerName = c.serverName + state.CipherSuite = c.cipherSuite + state.PeerCertificates = c.peerCertificates + state.VerifiedChains = c.verifiedChains + state.SignedCertificateTimestamps = c.scts + state.OCSPResponse = c.ocspResponse + if !c.didResume && c.vers != VersionTLS13 { + if c.clientFinishedIsFirst { + state.TLSUnique = c.clientFinished[:] + } else { + state.TLSUnique = c.serverFinished[:] + } + } + if c.config.Renegotiation != RenegotiateNever { + state.ekm = noExportedKeyingMaterial + } else { + state.ekm = c.ekm + } + return toConnectionState(state) +} + +func (c *Conn) updateConnectionState() { + c.connStateMutex.Lock() + defer c.connStateMutex.Unlock() + c.connState = ConnectionStateWith0RTT{ + Used0RTT: c.used0RTT, + ConnectionState: c.connectionStateLocked(), + } +} + +// OCSPResponse returns the stapled OCSP response from the TLS server, if +// any. (Only valid for client connections.) +func (c *Conn) OCSPResponse() []byte { + c.handshakeMutex.Lock() + defer c.handshakeMutex.Unlock() + + return c.ocspResponse +} + +// VerifyHostname checks that the peer certificate chain is valid for +// connecting to host. If so, it returns nil; if not, it returns an error +// describing the problem. +func (c *Conn) VerifyHostname(host string) error { + c.handshakeMutex.Lock() + defer c.handshakeMutex.Unlock() + if !c.isClient { + return errors.New("tls: VerifyHostname called on TLS server connection") + } + if !c.handshakeComplete() { + return errors.New("tls: handshake has not yet been performed") + } + if len(c.verifiedChains) == 0 { + return errors.New("tls: handshake did not verify certificate chain") + } + return c.peerCertificates[0].VerifyHostname(host) +} + +func (c *Conn) handshakeComplete() bool { + return atomic.LoadUint32(&c.handshakeStatus) == 1 +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/cpu.go b/vendor/github.com/quic-go/qtls-go1-19/cpu.go new file mode 100644 index 000000000..121945087 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/cpu.go @@ -0,0 +1,22 @@ +//go:build !js +// +build !js + +package qtls + +import ( + "runtime" + + "golang.org/x/sys/cpu" +) + +var ( + hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ + hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL + // Keep in sync with crypto/aes/cipher_s390x.go. + hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && + (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM) + + hasAESGCMHardwareSupport = runtime.GOARCH == "amd64" && hasGCMAsmAMD64 || + runtime.GOARCH == "arm64" && hasGCMAsmARM64 || + runtime.GOARCH == "s390x" && hasGCMAsmS390X +) diff --git a/vendor/github.com/quic-go/qtls-go1-19/cpu_other.go b/vendor/github.com/quic-go/qtls-go1-19/cpu_other.go new file mode 100644 index 000000000..33f7d2194 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/cpu_other.go @@ -0,0 +1,12 @@ +//go:build js +// +build js + +package qtls + +var ( + hasGCMAsmAMD64 = false + hasGCMAsmARM64 = false + hasGCMAsmS390X = false + + hasAESGCMHardwareSupport = false +) diff --git a/vendor/github.com/quic-go/qtls-go1-19/handshake_client.go b/vendor/github.com/quic-go/qtls-go1-19/handshake_client.go new file mode 100644 index 000000000..8d1fae015 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/handshake_client.go @@ -0,0 +1,1131 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "bytes" + "context" + "crypto" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/rsa" + "crypto/subtle" + "crypto/x509" + "errors" + "fmt" + "hash" + "io" + "net" + "strings" + "sync/atomic" + "time" + + "golang.org/x/crypto/cryptobyte" +) + +const clientSessionStateVersion = 1 + +type clientHandshakeState struct { + c *Conn + ctx context.Context + serverHello *serverHelloMsg + hello *clientHelloMsg + suite *cipherSuite + finishedHash finishedHash + masterSecret []byte + session *clientSessionState +} + +var testingOnlyForceClientHelloSignatureAlgorithms []SignatureScheme + +func (c *Conn) makeClientHello() (*clientHelloMsg, ecdheParameters, error) { + config := c.config + if len(config.ServerName) == 0 && !config.InsecureSkipVerify { + return nil, nil, errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config") + } + + nextProtosLength := 0 + for _, proto := range config.NextProtos { + if l := len(proto); l == 0 || l > 255 { + return nil, nil, errors.New("tls: invalid NextProtos value") + } else { + nextProtosLength += 1 + l + } + } + if nextProtosLength > 0xffff { + return nil, nil, errors.New("tls: NextProtos values too large") + } + + var supportedVersions []uint16 + var clientHelloVersion uint16 + if c.extraConfig.usesAlternativeRecordLayer() { + if config.maxSupportedVersion(roleClient) < VersionTLS13 { + return nil, nil, errors.New("tls: MaxVersion prevents QUIC from using TLS 1.3") + } + // Only offer TLS 1.3 when QUIC is used. + supportedVersions = []uint16{VersionTLS13} + clientHelloVersion = VersionTLS13 + } else { + supportedVersions = config.supportedVersions(roleClient) + if len(supportedVersions) == 0 { + return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion") + } + clientHelloVersion = config.maxSupportedVersion(roleClient) + } + + // The version at the beginning of the ClientHello was capped at TLS 1.2 + // for compatibility reasons. The supported_versions extension is used + // to negotiate versions now. See RFC 8446, Section 4.2.1. + if clientHelloVersion > VersionTLS12 { + clientHelloVersion = VersionTLS12 + } + + hello := &clientHelloMsg{ + vers: clientHelloVersion, + compressionMethods: []uint8{compressionNone}, + random: make([]byte, 32), + ocspStapling: true, + scts: true, + serverName: hostnameInSNI(config.ServerName), + supportedCurves: config.curvePreferences(), + supportedPoints: []uint8{pointFormatUncompressed}, + secureRenegotiationSupported: true, + alpnProtocols: config.NextProtos, + supportedVersions: supportedVersions, + } + + if c.handshakes > 0 { + hello.secureRenegotiation = c.clientFinished[:] + } + + preferenceOrder := cipherSuitesPreferenceOrder + if !hasAESGCMHardwareSupport { + preferenceOrder = cipherSuitesPreferenceOrderNoAES + } + configCipherSuites := config.cipherSuites() + hello.cipherSuites = make([]uint16, 0, len(configCipherSuites)) + + for _, suiteId := range preferenceOrder { + suite := mutualCipherSuite(configCipherSuites, suiteId) + if suite == nil { + continue + } + // Don't advertise TLS 1.2-only cipher suites unless + // we're attempting TLS 1.2. + if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 { + continue + } + hello.cipherSuites = append(hello.cipherSuites, suiteId) + } + + _, err := io.ReadFull(config.rand(), hello.random) + if err != nil { + return nil, nil, errors.New("tls: short read from Rand: " + err.Error()) + } + + // A random session ID is used to detect when the server accepted a ticket + // and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as + // a compatibility measure (see RFC 8446, Section 4.1.2). + if c.extraConfig == nil || c.extraConfig.AlternativeRecordLayer == nil { + hello.sessionId = make([]byte, 32) + if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil { + return nil, nil, errors.New("tls: short read from Rand: " + err.Error()) + } + } + + if hello.vers >= VersionTLS12 { + hello.supportedSignatureAlgorithms = supportedSignatureAlgorithms() + } + if testingOnlyForceClientHelloSignatureAlgorithms != nil { + hello.supportedSignatureAlgorithms = testingOnlyForceClientHelloSignatureAlgorithms + } + + var params ecdheParameters + if hello.supportedVersions[0] == VersionTLS13 { + if len(hello.supportedVersions) == 1 { + hello.cipherSuites = hello.cipherSuites[:0] + } + if hasAESGCMHardwareSupport { + hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13...) + } else { + hello.cipherSuites = append(hello.cipherSuites, defaultCipherSuitesTLS13NoAES...) + } + + curveID := config.curvePreferences()[0] + if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { + return nil, nil, errors.New("tls: CurvePreferences includes unsupported curve") + } + params, err = generateECDHEParameters(config.rand(), curveID) + if err != nil { + return nil, nil, err + } + hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}} + } + + if hello.supportedVersions[0] == VersionTLS13 && c.extraConfig != nil && c.extraConfig.GetExtensions != nil { + hello.additionalExtensions = c.extraConfig.GetExtensions(typeClientHello) + } + + return hello, params, nil +} + +func (c *Conn) clientHandshake(ctx context.Context) (err error) { + if c.config == nil { + c.config = fromConfig(defaultConfig()) + } + c.setAlternativeRecordLayer() + + // This may be a renegotiation handshake, in which case some fields + // need to be reset. + c.didResume = false + + hello, ecdheParams, err := c.makeClientHello() + if err != nil { + return err + } + c.serverName = hello.serverName + + cacheKey, session, earlySecret, binderKey, err := c.loadSession(hello) + if err != nil { + return err + } + if cacheKey != "" && session != nil { + var deletedTicket bool + if session.vers == VersionTLS13 && hello.earlyData && c.extraConfig != nil && c.extraConfig.Enable0RTT { + // don't reuse a session ticket that enabled 0-RTT + c.config.ClientSessionCache.Put(cacheKey, nil) + deletedTicket = true + + if suite := cipherSuiteTLS13ByID(session.cipherSuite); suite != nil { + h := suite.hash.New() + helloBytes, err := hello.marshal() + if err != nil { + return err + } + h.Write(helloBytes) + clientEarlySecret := suite.deriveSecret(earlySecret, "c e traffic", h) + c.out.exportKey(Encryption0RTT, suite, clientEarlySecret) + if err := c.config.writeKeyLog(keyLogLabelEarlyTraffic, hello.random, clientEarlySecret); err != nil { + return err + } + } + } + if !deletedTicket { + defer func() { + // If we got a handshake failure when resuming a session, throw away + // the session ticket. See RFC 5077, Section 3.2. + // + // RFC 8446 makes no mention of dropping tickets on failure, but it + // does require servers to abort on invalid binders, so we need to + // delete tickets to recover from a corrupted PSK. + if err != nil { + c.config.ClientSessionCache.Put(cacheKey, nil) + } + }() + } + } + + if _, err := c.writeHandshakeRecord(hello, nil); err != nil { + return err + } + + // serverHelloMsg is not included in the transcript + msg, err := c.readHandshake(nil) + if err != nil { + return err + } + + serverHello, ok := msg.(*serverHelloMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(serverHello, msg) + } + + if err := c.pickTLSVersion(serverHello); err != nil { + return err + } + + // If we are negotiating a protocol version that's lower than what we + // support, check for the server downgrade canaries. + // See RFC 8446, Section 4.1.3. + maxVers := c.config.maxSupportedVersion(roleClient) + tls12Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS12 + tls11Downgrade := string(serverHello.random[24:]) == downgradeCanaryTLS11 + if maxVers == VersionTLS13 && c.vers <= VersionTLS12 && (tls12Downgrade || tls11Downgrade) || + maxVers == VersionTLS12 && c.vers <= VersionTLS11 && tls11Downgrade { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: downgrade attempt detected, possibly due to a MitM attack or a broken middlebox") + } + + if c.vers == VersionTLS13 { + hs := &clientHandshakeStateTLS13{ + c: c, + ctx: ctx, + serverHello: serverHello, + hello: hello, + ecdheParams: ecdheParams, + session: session, + earlySecret: earlySecret, + binderKey: binderKey, + } + + // In TLS 1.3, session tickets are delivered after the handshake. + return hs.handshake() + } + + hs := &clientHandshakeState{ + c: c, + ctx: ctx, + serverHello: serverHello, + hello: hello, + session: session, + } + + if err := hs.handshake(); err != nil { + return err + } + + // If we had a successful handshake and hs.session is different from + // the one already cached - cache a new one. + if cacheKey != "" && hs.session != nil && session != hs.session { + c.config.ClientSessionCache.Put(cacheKey, toClientSessionState(hs.session)) + } + + c.updateConnectionState() + return nil +} + +// extract the app data saved in the session.nonce, +// and set the session.nonce to the actual nonce value +func (c *Conn) decodeSessionState(session *clientSessionState) (uint32 /* max early data */, []byte /* app data */, bool /* ok */) { + s := cryptobyte.String(session.nonce) + var version uint16 + if !s.ReadUint16(&version) { + return 0, nil, false + } + if version != clientSessionStateVersion { + return 0, nil, false + } + var maxEarlyData uint32 + if !s.ReadUint32(&maxEarlyData) { + return 0, nil, false + } + var appData []byte + if !readUint16LengthPrefixed(&s, &appData) { + return 0, nil, false + } + var nonce []byte + if !readUint16LengthPrefixed(&s, &nonce) { + return 0, nil, false + } + session.nonce = nonce + return maxEarlyData, appData, true +} + +func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string, + session *clientSessionState, earlySecret, binderKey []byte, err error) { + if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil { + return "", nil, nil, nil, nil + } + + hello.ticketSupported = true + + if hello.supportedVersions[0] == VersionTLS13 { + // Require DHE on resumption as it guarantees forward secrecy against + // compromise of the session ticket key. See RFC 8446, Section 4.2.9. + hello.pskModes = []uint8{pskModeDHE} + } + + // Session resumption is not allowed if renegotiating because + // renegotiation is primarily used to allow a client to send a client + // certificate, which would be skipped if session resumption occurred. + if c.handshakes != 0 { + return "", nil, nil, nil, nil + } + + // Try to resume a previously negotiated TLS session, if available. + cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config) + sess, ok := c.config.ClientSessionCache.Get(cacheKey) + if !ok || sess == nil { + return cacheKey, nil, nil, nil, nil + } + session = fromClientSessionState(sess) + + var appData []byte + var maxEarlyData uint32 + if session.vers == VersionTLS13 { + var ok bool + maxEarlyData, appData, ok = c.decodeSessionState(session) + if !ok { // delete it, if parsing failed + c.config.ClientSessionCache.Put(cacheKey, nil) + return cacheKey, nil, nil, nil, nil + } + } + + // Check that version used for the previous session is still valid. + versOk := false + for _, v := range hello.supportedVersions { + if v == session.vers { + versOk = true + break + } + } + if !versOk { + return cacheKey, nil, nil, nil, nil + } + + // Check that the cached server certificate is not expired, and that it's + // valid for the ServerName. This should be ensured by the cache key, but + // protect the application from a faulty ClientSessionCache implementation. + if !c.config.InsecureSkipVerify { + if len(session.verifiedChains) == 0 { + // The original connection had InsecureSkipVerify, while this doesn't. + return cacheKey, nil, nil, nil, nil + } + serverCert := session.serverCertificates[0] + if c.config.time().After(serverCert.NotAfter) { + // Expired certificate, delete the entry. + c.config.ClientSessionCache.Put(cacheKey, nil) + return cacheKey, nil, nil, nil, nil + } + if err := serverCert.VerifyHostname(c.config.ServerName); err != nil { + return cacheKey, nil, nil, nil, nil + } + } + + if session.vers != VersionTLS13 { + // In TLS 1.2 the cipher suite must match the resumed session. Ensure we + // are still offering it. + if mutualCipherSuite(hello.cipherSuites, session.cipherSuite) == nil { + return cacheKey, nil, nil, nil, nil + } + + hello.sessionTicket = session.sessionTicket + return + } + + // Check that the session ticket is not expired. + if c.config.time().After(session.useBy) { + c.config.ClientSessionCache.Put(cacheKey, nil) + return cacheKey, nil, nil, nil, nil + } + + // In TLS 1.3 the KDF hash must match the resumed session. Ensure we + // offer at least one cipher suite with that hash. + cipherSuite := cipherSuiteTLS13ByID(session.cipherSuite) + if cipherSuite == nil { + return cacheKey, nil, nil, nil, nil + } + cipherSuiteOk := false + for _, offeredID := range hello.cipherSuites { + offeredSuite := cipherSuiteTLS13ByID(offeredID) + if offeredSuite != nil && offeredSuite.hash == cipherSuite.hash { + cipherSuiteOk = true + break + } + } + if !cipherSuiteOk { + return cacheKey, nil, nil, nil, nil + } + + // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1. + ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond) + identity := pskIdentity{ + label: session.sessionTicket, + obfuscatedTicketAge: ticketAge + session.ageAdd, + } + hello.pskIdentities = []pskIdentity{identity} + hello.pskBinders = [][]byte{make([]byte, cipherSuite.hash.Size())} + + // Compute the PSK binders. See RFC 8446, Section 4.2.11.2. + psk := cipherSuite.expandLabel(session.masterSecret, "resumption", + session.nonce, cipherSuite.hash.Size()) + earlySecret = cipherSuite.extract(psk, nil) + binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil) + if c.extraConfig != nil { + hello.earlyData = c.extraConfig.Enable0RTT && maxEarlyData > 0 + } + transcript := cipherSuite.hash.New() + helloBytes, err := hello.marshalWithoutBinders() + if err != nil { + return "", nil, nil, nil, err + } + transcript.Write(helloBytes) + pskBinders := [][]byte{cipherSuite.finishedHash(binderKey, transcript)} + if err := hello.updateBinders(pskBinders); err != nil { + return "", nil, nil, nil, err + } + + if session.vers == VersionTLS13 && c.extraConfig != nil && c.extraConfig.SetAppDataFromSessionState != nil { + c.extraConfig.SetAppDataFromSessionState(appData) + } + return +} + +func (c *Conn) pickTLSVersion(serverHello *serverHelloMsg) error { + peerVersion := serverHello.vers + if serverHello.supportedVersion != 0 { + peerVersion = serverHello.supportedVersion + } + + vers, ok := c.config.mutualVersion(roleClient, []uint16{peerVersion}) + if !ok { + c.sendAlert(alertProtocolVersion) + return fmt.Errorf("tls: server selected unsupported protocol version %x", peerVersion) + } + + c.vers = vers + c.haveVers = true + c.in.version = vers + c.out.version = vers + + return nil +} + +// Does the handshake, either a full one or resumes old session. Requires hs.c, +// hs.hello, hs.serverHello, and, optionally, hs.session to be set. +func (hs *clientHandshakeState) handshake() error { + c := hs.c + + isResume, err := hs.processServerHello() + if err != nil { + return err + } + + hs.finishedHash = newFinishedHash(c.vers, hs.suite) + + // No signatures of the handshake are needed in a resumption. + // Otherwise, in a full handshake, if we don't have any certificates + // configured then we will never send a CertificateVerify message and + // thus no signatures are needed in that case either. + if isResume || (len(c.config.Certificates) == 0 && c.config.GetClientCertificate == nil) { + hs.finishedHash.discardHandshakeBuffer() + } + + if err := transcriptMsg(hs.hello, &hs.finishedHash); err != nil { + return err + } + if err := transcriptMsg(hs.serverHello, &hs.finishedHash); err != nil { + return err + } + + c.buffering = true + c.didResume = isResume + if isResume { + if err := hs.establishKeys(); err != nil { + return err + } + if err := hs.readSessionTicket(); err != nil { + return err + } + if err := hs.readFinished(c.serverFinished[:]); err != nil { + return err + } + c.clientFinishedIsFirst = false + // Make sure the connection is still being verified whether or not this + // is a resumption. Resumptions currently don't reverify certificates so + // they don't call verifyServerCertificate. See Issue 31641. + if c.config.VerifyConnection != nil { + if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { + c.sendAlert(alertBadCertificate) + return err + } + } + if err := hs.sendFinished(c.clientFinished[:]); err != nil { + return err + } + if _, err := c.flush(); err != nil { + return err + } + } else { + if err := hs.doFullHandshake(); err != nil { + return err + } + if err := hs.establishKeys(); err != nil { + return err + } + if err := hs.sendFinished(c.clientFinished[:]); err != nil { + return err + } + if _, err := c.flush(); err != nil { + return err + } + c.clientFinishedIsFirst = true + if err := hs.readSessionTicket(); err != nil { + return err + } + if err := hs.readFinished(c.serverFinished[:]); err != nil { + return err + } + } + + c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random) + atomic.StoreUint32(&c.handshakeStatus, 1) + + return nil +} + +func (hs *clientHandshakeState) pickCipherSuite() error { + if hs.suite = mutualCipherSuite(hs.hello.cipherSuites, hs.serverHello.cipherSuite); hs.suite == nil { + hs.c.sendAlert(alertHandshakeFailure) + return errors.New("tls: server chose an unconfigured cipher suite") + } + + hs.c.cipherSuite = hs.suite.id + return nil +} + +func (hs *clientHandshakeState) doFullHandshake() error { + c := hs.c + + msg, err := c.readHandshake(&hs.finishedHash) + if err != nil { + return err + } + certMsg, ok := msg.(*certificateMsg) + if !ok || len(certMsg.certificates) == 0 { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(certMsg, msg) + } + + msg, err = c.readHandshake(&hs.finishedHash) + if err != nil { + return err + } + + cs, ok := msg.(*certificateStatusMsg) + if ok { + // RFC4366 on Certificate Status Request: + // The server MAY return a "certificate_status" message. + + if !hs.serverHello.ocspStapling { + // If a server returns a "CertificateStatus" message, then the + // server MUST have included an extension of type "status_request" + // with empty "extension_data" in the extended server hello. + + c.sendAlert(alertUnexpectedMessage) + return errors.New("tls: received unexpected CertificateStatus message") + } + + c.ocspResponse = cs.response + + msg, err = c.readHandshake(&hs.finishedHash) + if err != nil { + return err + } + } + + if c.handshakes == 0 { + // If this is the first handshake on a connection, process and + // (optionally) verify the server's certificates. + if err := c.verifyServerCertificate(certMsg.certificates); err != nil { + return err + } + } else { + // This is a renegotiation handshake. We require that the + // server's identity (i.e. leaf certificate) is unchanged and + // thus any previous trust decision is still valid. + // + // See https://mitls.org/pages/attacks/3SHAKE for the + // motivation behind this requirement. + if !bytes.Equal(c.peerCertificates[0].Raw, certMsg.certificates[0]) { + c.sendAlert(alertBadCertificate) + return errors.New("tls: server's identity changed during renegotiation") + } + } + + keyAgreement := hs.suite.ka(c.vers) + + skx, ok := msg.(*serverKeyExchangeMsg) + if ok { + err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, c.peerCertificates[0], skx) + if err != nil { + c.sendAlert(alertUnexpectedMessage) + return err + } + + msg, err = c.readHandshake(&hs.finishedHash) + if err != nil { + return err + } + } + + var chainToSend *Certificate + var certRequested bool + certReq, ok := msg.(*certificateRequestMsg) + if ok { + certRequested = true + + cri := certificateRequestInfoFromMsg(hs.ctx, c.vers, certReq) + if chainToSend, err = c.getClientCertificate(cri); err != nil { + c.sendAlert(alertInternalError) + return err + } + + msg, err = c.readHandshake(&hs.finishedHash) + if err != nil { + return err + } + } + + shd, ok := msg.(*serverHelloDoneMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(shd, msg) + } + + // If the server requested a certificate then we have to send a + // Certificate message, even if it's empty because we don't have a + // certificate to send. + if certRequested { + certMsg = new(certificateMsg) + certMsg.certificates = chainToSend.Certificate + if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil { + return err + } + } + + preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, c.peerCertificates[0]) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + if ckx != nil { + if _, err := hs.c.writeHandshakeRecord(ckx, &hs.finishedHash); err != nil { + return err + } + } + + if chainToSend != nil && len(chainToSend.Certificate) > 0 { + certVerify := &certificateVerifyMsg{} + + key, ok := chainToSend.PrivateKey.(crypto.Signer) + if !ok { + c.sendAlert(alertInternalError) + return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey) + } + + var sigType uint8 + var sigHash crypto.Hash + if c.vers >= VersionTLS12 { + signatureAlgorithm, err := selectSignatureScheme(c.vers, chainToSend, certReq.supportedSignatureAlgorithms) + if err != nil { + c.sendAlert(alertIllegalParameter) + return err + } + sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm) + if err != nil { + return c.sendAlert(alertInternalError) + } + certVerify.hasSignatureAlgorithm = true + certVerify.signatureAlgorithm = signatureAlgorithm + } else { + sigType, sigHash, err = legacyTypeAndHashFromPublicKey(key.Public()) + if err != nil { + c.sendAlert(alertIllegalParameter) + return err + } + } + + signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret) + signOpts := crypto.SignerOpts(sigHash) + if sigType == signatureRSAPSS { + signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} + } + certVerify.signature, err = key.Sign(c.config.rand(), signed, signOpts) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + + if _, err := hs.c.writeHandshakeRecord(certVerify, &hs.finishedHash); err != nil { + return err + } + } + + hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.hello.random, hs.serverHello.random) + if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.hello.random, hs.masterSecret); err != nil { + c.sendAlert(alertInternalError) + return errors.New("tls: failed to write to key log: " + err.Error()) + } + + hs.finishedHash.discardHandshakeBuffer() + + return nil +} + +func (hs *clientHandshakeState) establishKeys() error { + c := hs.c + + clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := + keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) + var clientCipher, serverCipher any + var clientHash, serverHash hash.Hash + if hs.suite.cipher != nil { + clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */) + clientHash = hs.suite.mac(clientMAC) + serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */) + serverHash = hs.suite.mac(serverMAC) + } else { + clientCipher = hs.suite.aead(clientKey, clientIV) + serverCipher = hs.suite.aead(serverKey, serverIV) + } + + c.in.prepareCipherSpec(c.vers, serverCipher, serverHash) + c.out.prepareCipherSpec(c.vers, clientCipher, clientHash) + return nil +} + +func (hs *clientHandshakeState) serverResumedSession() bool { + // If the server responded with the same sessionId then it means the + // sessionTicket is being used to resume a TLS session. + return hs.session != nil && hs.hello.sessionId != nil && + bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId) +} + +func (hs *clientHandshakeState) processServerHello() (bool, error) { + c := hs.c + + if err := hs.pickCipherSuite(); err != nil { + return false, err + } + + if hs.serverHello.compressionMethod != compressionNone { + c.sendAlert(alertUnexpectedMessage) + return false, errors.New("tls: server selected unsupported compression format") + } + + if c.handshakes == 0 && hs.serverHello.secureRenegotiationSupported { + c.secureRenegotiation = true + if len(hs.serverHello.secureRenegotiation) != 0 { + c.sendAlert(alertHandshakeFailure) + return false, errors.New("tls: initial handshake had non-empty renegotiation extension") + } + } + + if c.handshakes > 0 && c.secureRenegotiation { + var expectedSecureRenegotiation [24]byte + copy(expectedSecureRenegotiation[:], c.clientFinished[:]) + copy(expectedSecureRenegotiation[12:], c.serverFinished[:]) + if !bytes.Equal(hs.serverHello.secureRenegotiation, expectedSecureRenegotiation[:]) { + c.sendAlert(alertHandshakeFailure) + return false, errors.New("tls: incorrect renegotiation extension contents") + } + } + + if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol); err != nil { + c.sendAlert(alertUnsupportedExtension) + return false, err + } + c.clientProtocol = hs.serverHello.alpnProtocol + + c.scts = hs.serverHello.scts + + if !hs.serverResumedSession() { + return false, nil + } + + if hs.session.vers != c.vers { + c.sendAlert(alertHandshakeFailure) + return false, errors.New("tls: server resumed a session with a different version") + } + + if hs.session.cipherSuite != hs.suite.id { + c.sendAlert(alertHandshakeFailure) + return false, errors.New("tls: server resumed a session with a different cipher suite") + } + + // Restore masterSecret, peerCerts, and ocspResponse from previous state + hs.masterSecret = hs.session.masterSecret + c.peerCertificates = hs.session.serverCertificates + c.verifiedChains = hs.session.verifiedChains + c.ocspResponse = hs.session.ocspResponse + // Let the ServerHello SCTs override the session SCTs from the original + // connection, if any are provided + if len(c.scts) == 0 && len(hs.session.scts) != 0 { + c.scts = hs.session.scts + } + + return true, nil +} + +// checkALPN ensure that the server's choice of ALPN protocol is compatible with +// the protocols that we advertised in the Client Hello. +func checkALPN(clientProtos []string, serverProto string) error { + if serverProto == "" { + return nil + } + if len(clientProtos) == 0 { + return errors.New("tls: server advertised unrequested ALPN extension") + } + for _, proto := range clientProtos { + if proto == serverProto { + return nil + } + } + return errors.New("tls: server selected unadvertised ALPN protocol") +} + +func (hs *clientHandshakeState) readFinished(out []byte) error { + c := hs.c + + if err := c.readChangeCipherSpec(); err != nil { + return err + } + + // finishedMsg is included in the transcript, but not until after we + // check the client version, since the state before this message was + // sent is used during verification. + msg, err := c.readHandshake(nil) + if err != nil { + return err + } + serverFinished, ok := msg.(*finishedMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(serverFinished, msg) + } + + verify := hs.finishedHash.serverSum(hs.masterSecret) + if len(verify) != len(serverFinished.verifyData) || + subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 { + c.sendAlert(alertHandshakeFailure) + return errors.New("tls: server's Finished message was incorrect") + } + + if err := transcriptMsg(serverFinished, &hs.finishedHash); err != nil { + return err + } + + copy(out, verify) + return nil +} + +func (hs *clientHandshakeState) readSessionTicket() error { + if !hs.serverHello.ticketSupported { + return nil + } + + c := hs.c + msg, err := c.readHandshake(&hs.finishedHash) + if err != nil { + return err + } + sessionTicketMsg, ok := msg.(*newSessionTicketMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(sessionTicketMsg, msg) + } + + hs.session = &clientSessionState{ + sessionTicket: sessionTicketMsg.ticket, + vers: c.vers, + cipherSuite: hs.suite.id, + masterSecret: hs.masterSecret, + serverCertificates: c.peerCertificates, + verifiedChains: c.verifiedChains, + receivedAt: c.config.time(), + ocspResponse: c.ocspResponse, + scts: c.scts, + } + + return nil +} + +func (hs *clientHandshakeState) sendFinished(out []byte) error { + c := hs.c + + if err := c.writeChangeCipherRecord(); err != nil { + return err + } + + finished := new(finishedMsg) + finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret) + if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil { + return err + } + copy(out, finished.verifyData) + return nil +} + +// maxRSAKeySize is the maximum RSA key size in bits that we are willing +// to verify the signatures of during a TLS handshake. +const maxRSAKeySize = 8192 + +// verifyServerCertificate parses and verifies the provided chain, setting +// c.verifiedChains and c.peerCertificates or sending the appropriate alert. +func (c *Conn) verifyServerCertificate(certificates [][]byte) error { + certs := make([]*x509.Certificate, len(certificates)) + for i, asn1Data := range certificates { + cert, err := x509.ParseCertificate(asn1Data) + if err != nil { + c.sendAlert(alertBadCertificate) + return errors.New("tls: failed to parse certificate from server: " + err.Error()) + } + if cert.PublicKeyAlgorithm == x509.RSA && cert.PublicKey.(*rsa.PublicKey).N.BitLen() > maxRSAKeySize { + c.sendAlert(alertBadCertificate) + return fmt.Errorf("tls: server sent certificate containing RSA key larger than %d bits", maxRSAKeySize) + } + certs[i] = cert + } + + if !c.config.InsecureSkipVerify { + opts := x509.VerifyOptions{ + Roots: c.config.RootCAs, + CurrentTime: c.config.time(), + DNSName: c.config.ServerName, + Intermediates: x509.NewCertPool(), + } + + for _, cert := range certs[1:] { + opts.Intermediates.AddCert(cert) + } + var err error + c.verifiedChains, err = certs[0].Verify(opts) + if err != nil { + c.sendAlert(alertBadCertificate) + return err + } + } + + switch certs[0].PublicKey.(type) { + case *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey: + break + default: + c.sendAlert(alertUnsupportedCertificate) + return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey) + } + + c.peerCertificates = certs + + if c.config.VerifyPeerCertificate != nil { + if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil { + c.sendAlert(alertBadCertificate) + return err + } + } + + if c.config.VerifyConnection != nil { + if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { + c.sendAlert(alertBadCertificate) + return err + } + } + + return nil +} + +// certificateRequestInfoFromMsg generates a CertificateRequestInfo from a TLS +// <= 1.2 CertificateRequest, making an effort to fill in missing information. +func certificateRequestInfoFromMsg(ctx context.Context, vers uint16, certReq *certificateRequestMsg) *CertificateRequestInfo { + cri := &certificateRequestInfo{ + AcceptableCAs: certReq.certificateAuthorities, + Version: vers, + ctx: ctx, + } + + var rsaAvail, ecAvail bool + for _, certType := range certReq.certificateTypes { + switch certType { + case certTypeRSASign: + rsaAvail = true + case certTypeECDSASign: + ecAvail = true + } + } + + if !certReq.hasSignatureAlgorithm { + // Prior to TLS 1.2, signature schemes did not exist. In this case we + // make up a list based on the acceptable certificate types, to help + // GetClientCertificate and SupportsCertificate select the right certificate. + // The hash part of the SignatureScheme is a lie here, because + // TLS 1.0 and 1.1 always use MD5+SHA1 for RSA and SHA1 for ECDSA. + switch { + case rsaAvail && ecAvail: + cri.SignatureSchemes = []SignatureScheme{ + ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, + PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1, + } + case rsaAvail: + cri.SignatureSchemes = []SignatureScheme{ + PKCS1WithSHA256, PKCS1WithSHA384, PKCS1WithSHA512, PKCS1WithSHA1, + } + case ecAvail: + cri.SignatureSchemes = []SignatureScheme{ + ECDSAWithP256AndSHA256, ECDSAWithP384AndSHA384, ECDSAWithP521AndSHA512, + } + } + return toCertificateRequestInfo(cri) + } + + // Filter the signature schemes based on the certificate types. + // See RFC 5246, Section 7.4.4 (where it calls this "somewhat complicated"). + cri.SignatureSchemes = make([]SignatureScheme, 0, len(certReq.supportedSignatureAlgorithms)) + for _, sigScheme := range certReq.supportedSignatureAlgorithms { + sigType, _, err := typeAndHashFromSignatureScheme(sigScheme) + if err != nil { + continue + } + switch sigType { + case signatureECDSA, signatureEd25519: + if ecAvail { + cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme) + } + case signatureRSAPSS, signaturePKCS1v15: + if rsaAvail { + cri.SignatureSchemes = append(cri.SignatureSchemes, sigScheme) + } + } + } + + return toCertificateRequestInfo(cri) +} + +func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, error) { + if c.config.GetClientCertificate != nil { + return c.config.GetClientCertificate(cri) + } + + for _, chain := range c.config.Certificates { + if err := cri.SupportsCertificate(&chain); err != nil { + continue + } + return &chain, nil + } + + // No acceptable certificate found. Don't send a certificate. + return new(Certificate), nil +} + +const clientSessionCacheKeyPrefix = "qtls-" + +// clientSessionCacheKey returns a key used to cache sessionTickets that could +// be used to resume previously negotiated TLS sessions with a server. +func clientSessionCacheKey(serverAddr net.Addr, config *config) string { + if len(config.ServerName) > 0 { + return clientSessionCacheKeyPrefix + config.ServerName + } + return clientSessionCacheKeyPrefix + serverAddr.String() +} + +// hostnameInSNI converts name into an appropriate hostname for SNI. +// Literal IP addresses and absolute FQDNs are not permitted as SNI values. +// See RFC 6066, Section 3. +func hostnameInSNI(name string) string { + host := name + if len(host) > 0 && host[0] == '[' && host[len(host)-1] == ']' { + host = host[1 : len(host)-1] + } + if i := strings.LastIndex(host, "%"); i > 0 { + host = host[:i] + } + if net.ParseIP(host) != nil { + return "" + } + for len(name) > 0 && name[len(name)-1] == '.' { + name = name[:len(name)-1] + } + return name +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/handshake_client_tls13.go b/vendor/github.com/quic-go/qtls-go1-19/handshake_client_tls13.go new file mode 100644 index 000000000..05ca1333b --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/handshake_client_tls13.go @@ -0,0 +1,755 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "bytes" + "context" + "crypto" + "crypto/hmac" + "crypto/rsa" + "encoding/binary" + "errors" + "hash" + "sync/atomic" + "time" + + "golang.org/x/crypto/cryptobyte" +) + +type clientHandshakeStateTLS13 struct { + c *Conn + ctx context.Context + serverHello *serverHelloMsg + hello *clientHelloMsg + ecdheParams ecdheParameters + + session *clientSessionState + earlySecret []byte + binderKey []byte + + certReq *certificateRequestMsgTLS13 + usingPSK bool + sentDummyCCS bool + suite *cipherSuiteTLS13 + transcript hash.Hash + masterSecret []byte + trafficSecret []byte // client_application_traffic_secret_0 +} + +// handshake requires hs.c, hs.hello, hs.serverHello, hs.ecdheParams, and, +// optionally, hs.session, hs.earlySecret and hs.binderKey to be set. +func (hs *clientHandshakeStateTLS13) handshake() error { + c := hs.c + + if needFIPS() { + return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode") + } + + // The server must not select TLS 1.3 in a renegotiation. See RFC 8446, + // sections 4.1.2 and 4.1.3. + if c.handshakes > 0 { + c.sendAlert(alertProtocolVersion) + return errors.New("tls: server selected TLS 1.3 in a renegotiation") + } + + // Consistency check on the presence of a keyShare and its parameters. + if hs.ecdheParams == nil || len(hs.hello.keyShares) != 1 { + return c.sendAlert(alertInternalError) + } + + if err := hs.checkServerHelloOrHRR(); err != nil { + return err + } + + hs.transcript = hs.suite.hash.New() + + if err := transcriptMsg(hs.hello, hs.transcript); err != nil { + return err + } + + if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { + if err := hs.sendDummyChangeCipherSpec(); err != nil { + return err + } + if err := hs.processHelloRetryRequest(); err != nil { + return err + } + } + + if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil { + return err + } + + c.buffering = true + if err := hs.processServerHello(); err != nil { + return err + } + c.updateConnectionState() + if err := hs.sendDummyChangeCipherSpec(); err != nil { + return err + } + if err := hs.establishHandshakeKeys(); err != nil { + return err + } + if err := hs.readServerParameters(); err != nil { + return err + } + if err := hs.readServerCertificate(); err != nil { + return err + } + c.updateConnectionState() + if err := hs.readServerFinished(); err != nil { + return err + } + if err := hs.sendClientCertificate(); err != nil { + return err + } + if err := hs.sendClientFinished(); err != nil { + return err + } + if _, err := c.flush(); err != nil { + return err + } + + atomic.StoreUint32(&c.handshakeStatus, 1) + c.updateConnectionState() + return nil +} + +// checkServerHelloOrHRR does validity checks that apply to both ServerHello and +// HelloRetryRequest messages. It sets hs.suite. +func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error { + c := hs.c + + if hs.serverHello.supportedVersion == 0 { + c.sendAlert(alertMissingExtension) + return errors.New("tls: server selected TLS 1.3 using the legacy version field") + } + + if hs.serverHello.supportedVersion != VersionTLS13 { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server selected an invalid version after a HelloRetryRequest") + } + + if hs.serverHello.vers != VersionTLS12 { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server sent an incorrect legacy version") + } + + if hs.serverHello.ocspStapling || + hs.serverHello.ticketSupported || + hs.serverHello.secureRenegotiationSupported || + len(hs.serverHello.secureRenegotiation) != 0 || + len(hs.serverHello.alpnProtocol) != 0 || + len(hs.serverHello.scts) != 0 { + c.sendAlert(alertUnsupportedExtension) + return errors.New("tls: server sent a ServerHello extension forbidden in TLS 1.3") + } + + if !bytes.Equal(hs.hello.sessionId, hs.serverHello.sessionId) { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server did not echo the legacy session ID") + } + + if hs.serverHello.compressionMethod != compressionNone { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server selected unsupported compression format") + } + + selectedSuite := mutualCipherSuiteTLS13(hs.hello.cipherSuites, hs.serverHello.cipherSuite) + if hs.suite != nil && selectedSuite != hs.suite { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server changed cipher suite after a HelloRetryRequest") + } + if selectedSuite == nil { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server chose an unconfigured cipher suite") + } + hs.suite = selectedSuite + c.cipherSuite = hs.suite.id + + return nil +} + +// sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility +// with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. +func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error { + if hs.sentDummyCCS { + return nil + } + hs.sentDummyCCS = true + + return hs.c.writeChangeCipherRecord() +} + +// processHelloRetryRequest handles the HRR in hs.serverHello, modifies and +// resends hs.hello, and reads the new ServerHello into hs.serverHello. +func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error { + c := hs.c + + // The first ClientHello gets double-hashed into the transcript upon a + // HelloRetryRequest. (The idea is that the server might offload transcript + // storage to the client in the cookie.) See RFC 8446, Section 4.4.1. + chHash := hs.transcript.Sum(nil) + hs.transcript.Reset() + hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) + hs.transcript.Write(chHash) + if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil { + return err + } + + // The only HelloRetryRequest extensions we support are key_share and + // cookie, and clients must abort the handshake if the HRR would not result + // in any change in the ClientHello. + if hs.serverHello.selectedGroup == 0 && hs.serverHello.cookie == nil { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server sent an unnecessary HelloRetryRequest message") + } + + if hs.serverHello.cookie != nil { + hs.hello.cookie = hs.serverHello.cookie + } + + if hs.serverHello.serverShare.group != 0 { + c.sendAlert(alertDecodeError) + return errors.New("tls: received malformed key_share extension") + } + + // If the server sent a key_share extension selecting a group, ensure it's + // a group we advertised but did not send a key share for, and send a key + // share for it this time. + if curveID := hs.serverHello.selectedGroup; curveID != 0 { + curveOK := false + for _, id := range hs.hello.supportedCurves { + if id == curveID { + curveOK = true + break + } + } + if !curveOK { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server selected unsupported group") + } + if hs.ecdheParams.CurveID() == curveID { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server sent an unnecessary HelloRetryRequest key_share") + } + if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { + c.sendAlert(alertInternalError) + return errors.New("tls: CurvePreferences includes unsupported curve") + } + params, err := generateECDHEParameters(c.config.rand(), curveID) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + hs.ecdheParams = params + hs.hello.keyShares = []keyShare{{group: curveID, data: params.PublicKey()}} + } + + hs.hello.raw = nil + if len(hs.hello.pskIdentities) > 0 { + pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) + if pskSuite == nil { + return c.sendAlert(alertInternalError) + } + if pskSuite.hash == hs.suite.hash { + // Update binders and obfuscated_ticket_age. + ticketAge := uint32(c.config.time().Sub(hs.session.receivedAt) / time.Millisecond) + hs.hello.pskIdentities[0].obfuscatedTicketAge = ticketAge + hs.session.ageAdd + + transcript := hs.suite.hash.New() + transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) + transcript.Write(chHash) + if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil { + return err + } + helloBytes, err := hs.hello.marshalWithoutBinders() + if err != nil { + return err + } + transcript.Write(helloBytes) + pskBinders := [][]byte{hs.suite.finishedHash(hs.binderKey, transcript)} + if err := hs.hello.updateBinders(pskBinders); err != nil { + return err + } + } else { + // Server selected a cipher suite incompatible with the PSK. + hs.hello.pskIdentities = nil + hs.hello.pskBinders = nil + } + } + + if hs.hello.earlyData && c.extraConfig != nil && c.extraConfig.Rejected0RTT != nil { + c.extraConfig.Rejected0RTT() + } + hs.hello.earlyData = false // disable 0-RTT + if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil { + return err + } + + // serverHelloMsg is not included in the transcript + msg, err := c.readHandshake(nil) + if err != nil { + return err + } + + serverHello, ok := msg.(*serverHelloMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(serverHello, msg) + } + hs.serverHello = serverHello + + if err := hs.checkServerHelloOrHRR(); err != nil { + return err + } + + return nil +} + +func (hs *clientHandshakeStateTLS13) processServerHello() error { + c := hs.c + + if bytes.Equal(hs.serverHello.random, helloRetryRequestRandom) { + c.sendAlert(alertUnexpectedMessage) + return errors.New("tls: server sent two HelloRetryRequest messages") + } + + if len(hs.serverHello.cookie) != 0 { + c.sendAlert(alertUnsupportedExtension) + return errors.New("tls: server sent a cookie in a normal ServerHello") + } + + if hs.serverHello.selectedGroup != 0 { + c.sendAlert(alertDecodeError) + return errors.New("tls: malformed key_share extension") + } + + if hs.serverHello.serverShare.group == 0 { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server did not send a key share") + } + if hs.serverHello.serverShare.group != hs.ecdheParams.CurveID() { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server selected unsupported group") + } + + if !hs.serverHello.selectedIdentityPresent { + return nil + } + + if int(hs.serverHello.selectedIdentity) >= len(hs.hello.pskIdentities) { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server selected an invalid PSK") + } + + if len(hs.hello.pskIdentities) != 1 || hs.session == nil { + return c.sendAlert(alertInternalError) + } + pskSuite := cipherSuiteTLS13ByID(hs.session.cipherSuite) + if pskSuite == nil { + return c.sendAlert(alertInternalError) + } + if pskSuite.hash != hs.suite.hash { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: server selected an invalid PSK and cipher suite pair") + } + + hs.usingPSK = true + c.didResume = true + c.peerCertificates = hs.session.serverCertificates + c.verifiedChains = hs.session.verifiedChains + c.ocspResponse = hs.session.ocspResponse + c.scts = hs.session.scts + return nil +} + +func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error { + c := hs.c + + sharedKey := hs.ecdheParams.SharedKey(hs.serverHello.serverShare.data) + if sharedKey == nil { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: invalid server key share") + } + + earlySecret := hs.earlySecret + if !hs.usingPSK { + earlySecret = hs.suite.extract(nil, nil) + } + + handshakeSecret := hs.suite.extract(sharedKey, + hs.suite.deriveSecret(earlySecret, "derived", nil)) + + clientSecret := hs.suite.deriveSecret(handshakeSecret, + clientHandshakeTrafficLabel, hs.transcript) + c.out.exportKey(EncryptionHandshake, hs.suite, clientSecret) + c.out.setTrafficSecret(hs.suite, clientSecret) + serverSecret := hs.suite.deriveSecret(handshakeSecret, + serverHandshakeTrafficLabel, hs.transcript) + c.in.exportKey(EncryptionHandshake, hs.suite, serverSecret) + c.in.setTrafficSecret(hs.suite, serverSecret) + + err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.hello.random, serverSecret) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + + hs.masterSecret = hs.suite.extract(nil, + hs.suite.deriveSecret(handshakeSecret, "derived", nil)) + + return nil +} + +func (hs *clientHandshakeStateTLS13) readServerParameters() error { + c := hs.c + + msg, err := c.readHandshake(hs.transcript) + if err != nil { + return err + } + + encryptedExtensions, ok := msg.(*encryptedExtensionsMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(encryptedExtensions, msg) + } + // Notify the caller if 0-RTT was rejected. + if !encryptedExtensions.earlyData && hs.hello.earlyData && c.extraConfig != nil && c.extraConfig.Rejected0RTT != nil { + c.extraConfig.Rejected0RTT() + } + c.used0RTT = encryptedExtensions.earlyData + if hs.c.extraConfig != nil && hs.c.extraConfig.ReceivedExtensions != nil { + hs.c.extraConfig.ReceivedExtensions(typeEncryptedExtensions, encryptedExtensions.additionalExtensions) + } + + if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol); err != nil { + c.sendAlert(alertUnsupportedExtension) + return err + } + c.clientProtocol = encryptedExtensions.alpnProtocol + + if c.extraConfig != nil && c.extraConfig.EnforceNextProtoSelection { + if len(encryptedExtensions.alpnProtocol) == 0 { + // the server didn't select an ALPN + c.sendAlert(alertNoApplicationProtocol) + return errors.New("ALPN negotiation failed. Server didn't offer any protocols") + } + } + return nil +} + +func (hs *clientHandshakeStateTLS13) readServerCertificate() error { + c := hs.c + + // Either a PSK or a certificate is always used, but not both. + // See RFC 8446, Section 4.1.1. + if hs.usingPSK { + // Make sure the connection is still being verified whether or not this + // is a resumption. Resumptions currently don't reverify certificates so + // they don't call verifyServerCertificate. See Issue 31641. + if c.config.VerifyConnection != nil { + if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { + c.sendAlert(alertBadCertificate) + return err + } + } + return nil + } + + msg, err := c.readHandshake(hs.transcript) + if err != nil { + return err + } + + certReq, ok := msg.(*certificateRequestMsgTLS13) + if ok { + hs.certReq = certReq + + msg, err = c.readHandshake(hs.transcript) + if err != nil { + return err + } + } + + certMsg, ok := msg.(*certificateMsgTLS13) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(certMsg, msg) + } + if len(certMsg.certificate.Certificate) == 0 { + c.sendAlert(alertDecodeError) + return errors.New("tls: received empty certificates message") + } + + c.scts = certMsg.certificate.SignedCertificateTimestamps + c.ocspResponse = certMsg.certificate.OCSPStaple + + if err := c.verifyServerCertificate(certMsg.certificate.Certificate); err != nil { + return err + } + + // certificateVerifyMsg is included in the transcript, but not until + // after we verify the handshake signature, since the state before + // this message was sent is used. + msg, err = c.readHandshake(nil) + if err != nil { + return err + } + + certVerify, ok := msg.(*certificateVerifyMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(certVerify, msg) + } + + // See RFC 8446, Section 4.4.3. + if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: certificate used with invalid signature algorithm") + } + sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) + if err != nil { + return c.sendAlert(alertInternalError) + } + if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: certificate used with invalid signature algorithm") + } + signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) + if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, + sigHash, signed, certVerify.signature); err != nil { + c.sendAlert(alertDecryptError) + return errors.New("tls: invalid signature by the server certificate: " + err.Error()) + } + + if err := transcriptMsg(certVerify, hs.transcript); err != nil { + return err + } + + return nil +} + +func (hs *clientHandshakeStateTLS13) readServerFinished() error { + c := hs.c + + // finishedMsg is included in the transcript, but not until after we + // check the client version, since the state before this message was + // sent is used during verification. + msg, err := c.readHandshake(nil) + if err != nil { + return err + } + + finished, ok := msg.(*finishedMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(finished, msg) + } + + expectedMAC := hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) + if !hmac.Equal(expectedMAC, finished.verifyData) { + c.sendAlert(alertDecryptError) + return errors.New("tls: invalid server finished hash") + } + + if err := transcriptMsg(finished, hs.transcript); err != nil { + return err + } + + // Derive secrets that take context through the server Finished. + + hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, + clientApplicationTrafficLabel, hs.transcript) + serverSecret := hs.suite.deriveSecret(hs.masterSecret, + serverApplicationTrafficLabel, hs.transcript) + c.in.exportKey(EncryptionApplication, hs.suite, serverSecret) + c.in.setTrafficSecret(hs.suite, serverSecret) + + err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.hello.random, serverSecret) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + + c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) + + return nil +} + +func (hs *clientHandshakeStateTLS13) sendClientCertificate() error { + c := hs.c + + if hs.certReq == nil { + return nil + } + + cert, err := c.getClientCertificate(toCertificateRequestInfo(&certificateRequestInfo{ + AcceptableCAs: hs.certReq.certificateAuthorities, + SignatureSchemes: hs.certReq.supportedSignatureAlgorithms, + Version: c.vers, + ctx: hs.ctx, + })) + if err != nil { + return err + } + + certMsg := new(certificateMsgTLS13) + + certMsg.certificate = *cert + certMsg.scts = hs.certReq.scts && len(cert.SignedCertificateTimestamps) > 0 + certMsg.ocspStapling = hs.certReq.ocspStapling && len(cert.OCSPStaple) > 0 + + if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil { + return err + } + + // If we sent an empty certificate message, skip the CertificateVerify. + if len(cert.Certificate) == 0 { + return nil + } + + certVerifyMsg := new(certificateVerifyMsg) + certVerifyMsg.hasSignatureAlgorithm = true + + certVerifyMsg.signatureAlgorithm, err = selectSignatureScheme(c.vers, cert, hs.certReq.supportedSignatureAlgorithms) + if err != nil { + // getClientCertificate returned a certificate incompatible with the + // CertificateRequestInfo supported signature algorithms. + c.sendAlert(alertHandshakeFailure) + return err + } + + sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerifyMsg.signatureAlgorithm) + if err != nil { + return c.sendAlert(alertInternalError) + } + + signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) + signOpts := crypto.SignerOpts(sigHash) + if sigType == signatureRSAPSS { + signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} + } + sig, err := cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) + if err != nil { + c.sendAlert(alertInternalError) + return errors.New("tls: failed to sign handshake: " + err.Error()) + } + certVerifyMsg.signature = sig + + if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil { + return err + } + + return nil +} + +func (hs *clientHandshakeStateTLS13) sendClientFinished() error { + c := hs.c + + finished := &finishedMsg{ + verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), + } + + if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil { + return err + } + + c.out.exportKey(EncryptionApplication, hs.suite, hs.trafficSecret) + c.out.setTrafficSecret(hs.suite, hs.trafficSecret) + + if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil { + c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, + resumptionLabel, hs.transcript) + } + + return nil +} + +func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error { + if !c.isClient { + c.sendAlert(alertUnexpectedMessage) + return errors.New("tls: received new session ticket from a client") + } + + if c.config.SessionTicketsDisabled || c.config.ClientSessionCache == nil { + return nil + } + + // See RFC 8446, Section 4.6.1. + if msg.lifetime == 0 { + return nil + } + lifetime := time.Duration(msg.lifetime) * time.Second + if lifetime > maxSessionTicketLifetime { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: received a session ticket with invalid lifetime") + } + + cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) + if cipherSuite == nil || c.resumptionSecret == nil { + return c.sendAlert(alertInternalError) + } + + // We need to save the max_early_data_size that the server sent us, in order + // to decide if we're going to try 0-RTT with this ticket. + // However, at the same time, the qtls.ClientSessionTicket needs to be equal to + // the tls.ClientSessionTicket, so we can't just add a new field to the struct. + // We therefore abuse the nonce field (which is a byte slice) + nonceWithEarlyData := make([]byte, len(msg.nonce)+4) + binary.BigEndian.PutUint32(nonceWithEarlyData, msg.maxEarlyData) + copy(nonceWithEarlyData[4:], msg.nonce) + + var appData []byte + if c.extraConfig != nil && c.extraConfig.GetAppDataForSessionState != nil { + appData = c.extraConfig.GetAppDataForSessionState() + } + var b cryptobyte.Builder + b.AddUint16(clientSessionStateVersion) // revision + b.AddUint32(msg.maxEarlyData) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(appData) + }) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(msg.nonce) + }) + + // Save the resumption_master_secret and nonce instead of deriving the PSK + // to do the least amount of work on NewSessionTicket messages before we + // know if the ticket will be used. Forward secrecy of resumed connections + // is guaranteed by the requirement for pskModeDHE. + session := &clientSessionState{ + sessionTicket: msg.label, + vers: c.vers, + cipherSuite: c.cipherSuite, + masterSecret: c.resumptionSecret, + serverCertificates: c.peerCertificates, + verifiedChains: c.verifiedChains, + receivedAt: c.config.time(), + nonce: b.BytesOrPanic(), + useBy: c.config.time().Add(lifetime), + ageAdd: msg.ageAdd, + ocspResponse: c.ocspResponse, + scts: c.scts, + } + + cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config) + c.config.ClientSessionCache.Put(cacheKey, toClientSessionState(session)) + + return nil +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/handshake_messages.go b/vendor/github.com/quic-go/qtls-go1-19/handshake_messages.go new file mode 100644 index 000000000..c69fcefda --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/handshake_messages.go @@ -0,0 +1,1875 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "errors" + "fmt" + "strings" + + "golang.org/x/crypto/cryptobyte" +) + +// The marshalingFunction type is an adapter to allow the use of ordinary +// functions as cryptobyte.MarshalingValue. +type marshalingFunction func(b *cryptobyte.Builder) error + +func (f marshalingFunction) Marshal(b *cryptobyte.Builder) error { + return f(b) +} + +// addBytesWithLength appends a sequence of bytes to the cryptobyte.Builder. If +// the length of the sequence is not the value specified, it produces an error. +func addBytesWithLength(b *cryptobyte.Builder, v []byte, n int) { + b.AddValue(marshalingFunction(func(b *cryptobyte.Builder) error { + if len(v) != n { + return fmt.Errorf("invalid value length: expected %d, got %d", n, len(v)) + } + b.AddBytes(v) + return nil + })) +} + +// addUint64 appends a big-endian, 64-bit value to the cryptobyte.Builder. +func addUint64(b *cryptobyte.Builder, v uint64) { + b.AddUint32(uint32(v >> 32)) + b.AddUint32(uint32(v)) +} + +// readUint64 decodes a big-endian, 64-bit value into out and advances over it. +// It reports whether the read was successful. +func readUint64(s *cryptobyte.String, out *uint64) bool { + var hi, lo uint32 + if !s.ReadUint32(&hi) || !s.ReadUint32(&lo) { + return false + } + *out = uint64(hi)<<32 | uint64(lo) + return true +} + +// readUint8LengthPrefixed acts like s.ReadUint8LengthPrefixed, but targets a +// []byte instead of a cryptobyte.String. +func readUint8LengthPrefixed(s *cryptobyte.String, out *[]byte) bool { + return s.ReadUint8LengthPrefixed((*cryptobyte.String)(out)) +} + +// readUint16LengthPrefixed acts like s.ReadUint16LengthPrefixed, but targets a +// []byte instead of a cryptobyte.String. +func readUint16LengthPrefixed(s *cryptobyte.String, out *[]byte) bool { + return s.ReadUint16LengthPrefixed((*cryptobyte.String)(out)) +} + +// readUint24LengthPrefixed acts like s.ReadUint24LengthPrefixed, but targets a +// []byte instead of a cryptobyte.String. +func readUint24LengthPrefixed(s *cryptobyte.String, out *[]byte) bool { + return s.ReadUint24LengthPrefixed((*cryptobyte.String)(out)) +} + +type clientHelloMsg struct { + raw []byte + vers uint16 + random []byte + sessionId []byte + cipherSuites []uint16 + compressionMethods []uint8 + serverName string + ocspStapling bool + supportedCurves []CurveID + supportedPoints []uint8 + ticketSupported bool + sessionTicket []uint8 + supportedSignatureAlgorithms []SignatureScheme + supportedSignatureAlgorithmsCert []SignatureScheme + secureRenegotiationSupported bool + secureRenegotiation []byte + alpnProtocols []string + scts bool + supportedVersions []uint16 + cookie []byte + keyShares []keyShare + earlyData bool + pskModes []uint8 + pskIdentities []pskIdentity + pskBinders [][]byte + additionalExtensions []Extension +} + +func (m *clientHelloMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + var exts cryptobyte.Builder + if len(m.serverName) > 0 { + // RFC 6066, Section 3 + exts.AddUint16(extensionServerName) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint8(0) // name_type = host_name + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes([]byte(m.serverName)) + }) + }) + }) + } + if m.ocspStapling { + // RFC 4366, Section 3.6 + exts.AddUint16(extensionStatusRequest) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint8(1) // status_type = ocsp + exts.AddUint16(0) // empty responder_id_list + exts.AddUint16(0) // empty request_extensions + }) + } + if len(m.supportedCurves) > 0 { + // RFC 4492, sections 5.1.1 and RFC 8446, Section 4.2.7 + exts.AddUint16(extensionSupportedCurves) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + for _, curve := range m.supportedCurves { + exts.AddUint16(uint16(curve)) + } + }) + }) + } + if len(m.supportedPoints) > 0 { + // RFC 4492, Section 5.1.2 + exts.AddUint16(extensionSupportedPoints) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(m.supportedPoints) + }) + }) + } + if m.ticketSupported { + // RFC 5077, Section 3.2 + exts.AddUint16(extensionSessionTicket) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(m.sessionTicket) + }) + } + if len(m.supportedSignatureAlgorithms) > 0 { + // RFC 5246, Section 7.4.1.4.1 + exts.AddUint16(extensionSignatureAlgorithms) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + for _, sigAlgo := range m.supportedSignatureAlgorithms { + exts.AddUint16(uint16(sigAlgo)) + } + }) + }) + } + if len(m.supportedSignatureAlgorithmsCert) > 0 { + // RFC 8446, Section 4.2.3 + exts.AddUint16(extensionSignatureAlgorithmsCert) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + for _, sigAlgo := range m.supportedSignatureAlgorithmsCert { + exts.AddUint16(uint16(sigAlgo)) + } + }) + }) + } + if m.secureRenegotiationSupported { + // RFC 5746, Section 3.2 + exts.AddUint16(extensionRenegotiationInfo) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(m.secureRenegotiation) + }) + }) + } + if len(m.alpnProtocols) > 0 { + // RFC 7301, Section 3.1 + exts.AddUint16(extensionALPN) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + for _, proto := range m.alpnProtocols { + exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes([]byte(proto)) + }) + } + }) + }) + } + if m.scts { + // RFC 6962, Section 3.3.1 + exts.AddUint16(extensionSCT) + exts.AddUint16(0) // empty extension_data + } + if len(m.supportedVersions) > 0 { + // RFC 8446, Section 4.2.1 + exts.AddUint16(extensionSupportedVersions) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) { + for _, vers := range m.supportedVersions { + exts.AddUint16(vers) + } + }) + }) + } + if len(m.cookie) > 0 { + // RFC 8446, Section 4.2.2 + exts.AddUint16(extensionCookie) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(m.cookie) + }) + }) + } + if len(m.keyShares) > 0 { + // RFC 8446, Section 4.2.8 + exts.AddUint16(extensionKeyShare) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + for _, ks := range m.keyShares { + exts.AddUint16(uint16(ks.group)) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(ks.data) + }) + } + }) + }) + } + if m.earlyData { + // RFC 8446, Section 4.2.10 + exts.AddUint16(extensionEarlyData) + exts.AddUint16(0) // empty extension_data + } + if len(m.pskModes) > 0 { + // RFC 8446, Section 4.2.9 + exts.AddUint16(extensionPSKModes) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(m.pskModes) + }) + }) + } + for _, ext := range m.additionalExtensions { + exts.AddUint16(ext.Type) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(ext.Data) + }) + } + if len(m.pskIdentities) > 0 { // pre_shared_key must be the last extension + // RFC 8446, Section 4.2.11 + exts.AddUint16(extensionPreSharedKey) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + for _, psk := range m.pskIdentities { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(psk.label) + }) + exts.AddUint32(psk.obfuscatedTicketAge) + } + }) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + for _, binder := range m.pskBinders { + exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(binder) + }) + } + }) + }) + } + extBytes, err := exts.Bytes() + if err != nil { + return nil, err + } + + var b cryptobyte.Builder + b.AddUint8(typeClientHello) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint16(m.vers) + addBytesWithLength(b, m.random, 32) + b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(m.sessionId) + }) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + for _, suite := range m.cipherSuites { + b.AddUint16(suite) + } + }) + b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(m.compressionMethods) + }) + + if len(extBytes) > 0 { + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(extBytes) + }) + } + }) + + m.raw, err = b.Bytes() + return m.raw, err +} + +// marshalWithoutBinders returns the ClientHello through the +// PreSharedKeyExtension.identities field, according to RFC 8446, Section +// 4.2.11.2. Note that m.pskBinders must be set to slices of the correct length. +func (m *clientHelloMsg) marshalWithoutBinders() ([]byte, error) { + bindersLen := 2 // uint16 length prefix + for _, binder := range m.pskBinders { + bindersLen += 1 // uint8 length prefix + bindersLen += len(binder) + } + + fullMessage, err := m.marshal() + if err != nil { + return nil, err + } + return fullMessage[:len(fullMessage)-bindersLen], nil +} + +// updateBinders updates the m.pskBinders field, if necessary updating the +// cached marshaled representation. The supplied binders must have the same +// length as the current m.pskBinders. +func (m *clientHelloMsg) updateBinders(pskBinders [][]byte) error { + if len(pskBinders) != len(m.pskBinders) { + return errors.New("tls: internal error: pskBinders length mismatch") + } + for i := range m.pskBinders { + if len(pskBinders[i]) != len(m.pskBinders[i]) { + return errors.New("tls: internal error: pskBinders length mismatch") + } + } + m.pskBinders = pskBinders + if m.raw != nil { + helloBytes, err := m.marshalWithoutBinders() + if err != nil { + return err + } + lenWithoutBinders := len(helloBytes) + b := cryptobyte.NewFixedBuilder(m.raw[:lenWithoutBinders]) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + for _, binder := range m.pskBinders { + b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(binder) + }) + } + }) + if out, err := b.Bytes(); err != nil || len(out) != len(m.raw) { + return errors.New("tls: internal error: failed to update binders") + } + } + + return nil +} + +func (m *clientHelloMsg) unmarshal(data []byte) bool { + *m = clientHelloMsg{raw: data} + s := cryptobyte.String(data) + + if !s.Skip(4) || // message type and uint24 length field + !s.ReadUint16(&m.vers) || !s.ReadBytes(&m.random, 32) || + !readUint8LengthPrefixed(&s, &m.sessionId) { + return false + } + + var cipherSuites cryptobyte.String + if !s.ReadUint16LengthPrefixed(&cipherSuites) { + return false + } + m.cipherSuites = []uint16{} + m.secureRenegotiationSupported = false + for !cipherSuites.Empty() { + var suite uint16 + if !cipherSuites.ReadUint16(&suite) { + return false + } + if suite == scsvRenegotiation { + m.secureRenegotiationSupported = true + } + m.cipherSuites = append(m.cipherSuites, suite) + } + + if !readUint8LengthPrefixed(&s, &m.compressionMethods) { + return false + } + + if s.Empty() { + // ClientHello is optionally followed by extension data + return true + } + + var extensions cryptobyte.String + if !s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() { + return false + } + + seenExts := make(map[uint16]bool) + for !extensions.Empty() { + var extension uint16 + var extData cryptobyte.String + if !extensions.ReadUint16(&extension) || + !extensions.ReadUint16LengthPrefixed(&extData) { + return false + } + + if seenExts[extension] { + return false + } + seenExts[extension] = true + + switch extension { + case extensionServerName: + // RFC 6066, Section 3 + var nameList cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&nameList) || nameList.Empty() { + return false + } + for !nameList.Empty() { + var nameType uint8 + var serverName cryptobyte.String + if !nameList.ReadUint8(&nameType) || + !nameList.ReadUint16LengthPrefixed(&serverName) || + serverName.Empty() { + return false + } + if nameType != 0 { + continue + } + if len(m.serverName) != 0 { + // Multiple names of the same name_type are prohibited. + return false + } + m.serverName = string(serverName) + // An SNI value may not include a trailing dot. + if strings.HasSuffix(m.serverName, ".") { + return false + } + } + case extensionStatusRequest: + // RFC 4366, Section 3.6 + var statusType uint8 + var ignored cryptobyte.String + if !extData.ReadUint8(&statusType) || + !extData.ReadUint16LengthPrefixed(&ignored) || + !extData.ReadUint16LengthPrefixed(&ignored) { + return false + } + m.ocspStapling = statusType == statusTypeOCSP + case extensionSupportedCurves: + // RFC 4492, sections 5.1.1 and RFC 8446, Section 4.2.7 + var curves cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&curves) || curves.Empty() { + return false + } + for !curves.Empty() { + var curve uint16 + if !curves.ReadUint16(&curve) { + return false + } + m.supportedCurves = append(m.supportedCurves, CurveID(curve)) + } + case extensionSupportedPoints: + // RFC 4492, Section 5.1.2 + if !readUint8LengthPrefixed(&extData, &m.supportedPoints) || + len(m.supportedPoints) == 0 { + return false + } + case extensionSessionTicket: + // RFC 5077, Section 3.2 + m.ticketSupported = true + extData.ReadBytes(&m.sessionTicket, len(extData)) + case extensionSignatureAlgorithms: + // RFC 5246, Section 7.4.1.4.1 + var sigAndAlgs cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() { + return false + } + for !sigAndAlgs.Empty() { + var sigAndAlg uint16 + if !sigAndAlgs.ReadUint16(&sigAndAlg) { + return false + } + m.supportedSignatureAlgorithms = append( + m.supportedSignatureAlgorithms, SignatureScheme(sigAndAlg)) + } + case extensionSignatureAlgorithmsCert: + // RFC 8446, Section 4.2.3 + var sigAndAlgs cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() { + return false + } + for !sigAndAlgs.Empty() { + var sigAndAlg uint16 + if !sigAndAlgs.ReadUint16(&sigAndAlg) { + return false + } + m.supportedSignatureAlgorithmsCert = append( + m.supportedSignatureAlgorithmsCert, SignatureScheme(sigAndAlg)) + } + case extensionRenegotiationInfo: + // RFC 5746, Section 3.2 + if !readUint8LengthPrefixed(&extData, &m.secureRenegotiation) { + return false + } + m.secureRenegotiationSupported = true + case extensionALPN: + // RFC 7301, Section 3.1 + var protoList cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() { + return false + } + for !protoList.Empty() { + var proto cryptobyte.String + if !protoList.ReadUint8LengthPrefixed(&proto) || proto.Empty() { + return false + } + m.alpnProtocols = append(m.alpnProtocols, string(proto)) + } + case extensionSCT: + // RFC 6962, Section 3.3.1 + m.scts = true + case extensionSupportedVersions: + // RFC 8446, Section 4.2.1 + var versList cryptobyte.String + if !extData.ReadUint8LengthPrefixed(&versList) || versList.Empty() { + return false + } + for !versList.Empty() { + var vers uint16 + if !versList.ReadUint16(&vers) { + return false + } + m.supportedVersions = append(m.supportedVersions, vers) + } + case extensionCookie: + // RFC 8446, Section 4.2.2 + if !readUint16LengthPrefixed(&extData, &m.cookie) || + len(m.cookie) == 0 { + return false + } + case extensionKeyShare: + // RFC 8446, Section 4.2.8 + var clientShares cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&clientShares) { + return false + } + for !clientShares.Empty() { + var ks keyShare + if !clientShares.ReadUint16((*uint16)(&ks.group)) || + !readUint16LengthPrefixed(&clientShares, &ks.data) || + len(ks.data) == 0 { + return false + } + m.keyShares = append(m.keyShares, ks) + } + case extensionEarlyData: + // RFC 8446, Section 4.2.10 + m.earlyData = true + case extensionPSKModes: + // RFC 8446, Section 4.2.9 + if !readUint8LengthPrefixed(&extData, &m.pskModes) { + return false + } + case extensionPreSharedKey: + // RFC 8446, Section 4.2.11 + if !extensions.Empty() { + return false // pre_shared_key must be the last extension + } + var identities cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&identities) || identities.Empty() { + return false + } + for !identities.Empty() { + var psk pskIdentity + if !readUint16LengthPrefixed(&identities, &psk.label) || + !identities.ReadUint32(&psk.obfuscatedTicketAge) || + len(psk.label) == 0 { + return false + } + m.pskIdentities = append(m.pskIdentities, psk) + } + var binders cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&binders) || binders.Empty() { + return false + } + for !binders.Empty() { + var binder []byte + if !readUint8LengthPrefixed(&binders, &binder) || + len(binder) == 0 { + return false + } + m.pskBinders = append(m.pskBinders, binder) + } + default: + m.additionalExtensions = append(m.additionalExtensions, Extension{Type: extension, Data: extData}) + continue + } + + if !extData.Empty() { + return false + } + } + + return true +} + +type serverHelloMsg struct { + raw []byte + vers uint16 + random []byte + sessionId []byte + cipherSuite uint16 + compressionMethod uint8 + ocspStapling bool + ticketSupported bool + secureRenegotiationSupported bool + secureRenegotiation []byte + alpnProtocol string + scts [][]byte + supportedVersion uint16 + serverShare keyShare + selectedIdentityPresent bool + selectedIdentity uint16 + supportedPoints []uint8 + + // HelloRetryRequest extensions + cookie []byte + selectedGroup CurveID +} + +func (m *serverHelloMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + var exts cryptobyte.Builder + if m.ocspStapling { + exts.AddUint16(extensionStatusRequest) + exts.AddUint16(0) // empty extension_data + } + if m.ticketSupported { + exts.AddUint16(extensionSessionTicket) + exts.AddUint16(0) // empty extension_data + } + if m.secureRenegotiationSupported { + exts.AddUint16(extensionRenegotiationInfo) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(m.secureRenegotiation) + }) + }) + } + if len(m.alpnProtocol) > 0 { + exts.AddUint16(extensionALPN) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes([]byte(m.alpnProtocol)) + }) + }) + }) + } + if len(m.scts) > 0 { + exts.AddUint16(extensionSCT) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + for _, sct := range m.scts { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(sct) + }) + } + }) + }) + } + if m.supportedVersion != 0 { + exts.AddUint16(extensionSupportedVersions) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16(m.supportedVersion) + }) + } + if m.serverShare.group != 0 { + exts.AddUint16(extensionKeyShare) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16(uint16(m.serverShare.group)) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(m.serverShare.data) + }) + }) + } + if m.selectedIdentityPresent { + exts.AddUint16(extensionPreSharedKey) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16(m.selectedIdentity) + }) + } + + if len(m.cookie) > 0 { + exts.AddUint16(extensionCookie) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(m.cookie) + }) + }) + } + if m.selectedGroup != 0 { + exts.AddUint16(extensionKeyShare) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint16(uint16(m.selectedGroup)) + }) + } + if len(m.supportedPoints) > 0 { + exts.AddUint16(extensionSupportedPoints) + exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddUint8LengthPrefixed(func(exts *cryptobyte.Builder) { + exts.AddBytes(m.supportedPoints) + }) + }) + } + + extBytes, err := exts.Bytes() + if err != nil { + return nil, err + } + + var b cryptobyte.Builder + b.AddUint8(typeServerHello) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint16(m.vers) + addBytesWithLength(b, m.random, 32) + b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(m.sessionId) + }) + b.AddUint16(m.cipherSuite) + b.AddUint8(m.compressionMethod) + + if len(extBytes) > 0 { + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(extBytes) + }) + } + }) + + m.raw, err = b.Bytes() + return m.raw, err +} + +func (m *serverHelloMsg) unmarshal(data []byte) bool { + *m = serverHelloMsg{raw: data} + s := cryptobyte.String(data) + + if !s.Skip(4) || // message type and uint24 length field + !s.ReadUint16(&m.vers) || !s.ReadBytes(&m.random, 32) || + !readUint8LengthPrefixed(&s, &m.sessionId) || + !s.ReadUint16(&m.cipherSuite) || + !s.ReadUint8(&m.compressionMethod) { + return false + } + + if s.Empty() { + // ServerHello is optionally followed by extension data + return true + } + + var extensions cryptobyte.String + if !s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() { + return false + } + + seenExts := make(map[uint16]bool) + for !extensions.Empty() { + var extension uint16 + var extData cryptobyte.String + if !extensions.ReadUint16(&extension) || + !extensions.ReadUint16LengthPrefixed(&extData) { + return false + } + + if seenExts[extension] { + return false + } + seenExts[extension] = true + + switch extension { + case extensionStatusRequest: + m.ocspStapling = true + case extensionSessionTicket: + m.ticketSupported = true + case extensionRenegotiationInfo: + if !readUint8LengthPrefixed(&extData, &m.secureRenegotiation) { + return false + } + m.secureRenegotiationSupported = true + case extensionALPN: + var protoList cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() { + return false + } + var proto cryptobyte.String + if !protoList.ReadUint8LengthPrefixed(&proto) || + proto.Empty() || !protoList.Empty() { + return false + } + m.alpnProtocol = string(proto) + case extensionSCT: + var sctList cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&sctList) || sctList.Empty() { + return false + } + for !sctList.Empty() { + var sct []byte + if !readUint16LengthPrefixed(&sctList, &sct) || + len(sct) == 0 { + return false + } + m.scts = append(m.scts, sct) + } + case extensionSupportedVersions: + if !extData.ReadUint16(&m.supportedVersion) { + return false + } + case extensionCookie: + if !readUint16LengthPrefixed(&extData, &m.cookie) || + len(m.cookie) == 0 { + return false + } + case extensionKeyShare: + // This extension has different formats in SH and HRR, accept either + // and let the handshake logic decide. See RFC 8446, Section 4.2.8. + if len(extData) == 2 { + if !extData.ReadUint16((*uint16)(&m.selectedGroup)) { + return false + } + } else { + if !extData.ReadUint16((*uint16)(&m.serverShare.group)) || + !readUint16LengthPrefixed(&extData, &m.serverShare.data) { + return false + } + } + case extensionPreSharedKey: + m.selectedIdentityPresent = true + if !extData.ReadUint16(&m.selectedIdentity) { + return false + } + case extensionSupportedPoints: + // RFC 4492, Section 5.1.2 + if !readUint8LengthPrefixed(&extData, &m.supportedPoints) || + len(m.supportedPoints) == 0 { + return false + } + default: + // Ignore unknown extensions. + continue + } + + if !extData.Empty() { + return false + } + } + + return true +} + +type encryptedExtensionsMsg struct { + raw []byte + alpnProtocol string + earlyData bool + + additionalExtensions []Extension +} + +func (m *encryptedExtensionsMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + var b cryptobyte.Builder + b.AddUint8(typeEncryptedExtensions) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + if len(m.alpnProtocol) > 0 { + b.AddUint16(extensionALPN) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes([]byte(m.alpnProtocol)) + }) + }) + }) + } + if m.earlyData { + // RFC 8446, Section 4.2.10 + b.AddUint16(extensionEarlyData) + b.AddUint16(0) // empty extension_data + } + for _, ext := range m.additionalExtensions { + b.AddUint16(ext.Type) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(ext.Data) + }) + } + }) + }) + + var err error + m.raw, err = b.Bytes() + return m.raw, err +} + +func (m *encryptedExtensionsMsg) unmarshal(data []byte) bool { + *m = encryptedExtensionsMsg{raw: data} + s := cryptobyte.String(data) + + var extensions cryptobyte.String + if !s.Skip(4) || // message type and uint24 length field + !s.ReadUint16LengthPrefixed(&extensions) || !s.Empty() { + return false + } + + for !extensions.Empty() { + var ext uint16 + var extData cryptobyte.String + if !extensions.ReadUint16(&ext) || + !extensions.ReadUint16LengthPrefixed(&extData) { + return false + } + + switch ext { + case extensionALPN: + var protoList cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() { + return false + } + var proto cryptobyte.String + if !protoList.ReadUint8LengthPrefixed(&proto) || + proto.Empty() || !protoList.Empty() { + return false + } + m.alpnProtocol = string(proto) + case extensionEarlyData: + m.earlyData = true + default: + m.additionalExtensions = append(m.additionalExtensions, Extension{Type: ext, Data: extData}) + continue + } + + if !extData.Empty() { + return false + } + } + + return true +} + +type endOfEarlyDataMsg struct{} + +func (m *endOfEarlyDataMsg) marshal() ([]byte, error) { + x := make([]byte, 4) + x[0] = typeEndOfEarlyData + return x, nil +} + +func (m *endOfEarlyDataMsg) unmarshal(data []byte) bool { + return len(data) == 4 +} + +type keyUpdateMsg struct { + raw []byte + updateRequested bool +} + +func (m *keyUpdateMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + var b cryptobyte.Builder + b.AddUint8(typeKeyUpdate) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + if m.updateRequested { + b.AddUint8(1) + } else { + b.AddUint8(0) + } + }) + + var err error + m.raw, err = b.Bytes() + return m.raw, err +} + +func (m *keyUpdateMsg) unmarshal(data []byte) bool { + m.raw = data + s := cryptobyte.String(data) + + var updateRequested uint8 + if !s.Skip(4) || // message type and uint24 length field + !s.ReadUint8(&updateRequested) || !s.Empty() { + return false + } + switch updateRequested { + case 0: + m.updateRequested = false + case 1: + m.updateRequested = true + default: + return false + } + return true +} + +type newSessionTicketMsgTLS13 struct { + raw []byte + lifetime uint32 + ageAdd uint32 + nonce []byte + label []byte + maxEarlyData uint32 +} + +func (m *newSessionTicketMsgTLS13) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + var b cryptobyte.Builder + b.AddUint8(typeNewSessionTicket) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint32(m.lifetime) + b.AddUint32(m.ageAdd) + b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(m.nonce) + }) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(m.label) + }) + + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + if m.maxEarlyData > 0 { + b.AddUint16(extensionEarlyData) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint32(m.maxEarlyData) + }) + } + }) + }) + + var err error + m.raw, err = b.Bytes() + return m.raw, err +} + +func (m *newSessionTicketMsgTLS13) unmarshal(data []byte) bool { + *m = newSessionTicketMsgTLS13{raw: data} + s := cryptobyte.String(data) + + var extensions cryptobyte.String + if !s.Skip(4) || // message type and uint24 length field + !s.ReadUint32(&m.lifetime) || + !s.ReadUint32(&m.ageAdd) || + !readUint8LengthPrefixed(&s, &m.nonce) || + !readUint16LengthPrefixed(&s, &m.label) || + !s.ReadUint16LengthPrefixed(&extensions) || + !s.Empty() { + return false + } + + for !extensions.Empty() { + var extension uint16 + var extData cryptobyte.String + if !extensions.ReadUint16(&extension) || + !extensions.ReadUint16LengthPrefixed(&extData) { + return false + } + + switch extension { + case extensionEarlyData: + if !extData.ReadUint32(&m.maxEarlyData) { + return false + } + default: + // Ignore unknown extensions. + continue + } + + if !extData.Empty() { + return false + } + } + + return true +} + +type certificateRequestMsgTLS13 struct { + raw []byte + ocspStapling bool + scts bool + supportedSignatureAlgorithms []SignatureScheme + supportedSignatureAlgorithmsCert []SignatureScheme + certificateAuthorities [][]byte +} + +func (m *certificateRequestMsgTLS13) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + var b cryptobyte.Builder + b.AddUint8(typeCertificateRequest) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + // certificate_request_context (SHALL be zero length unless used for + // post-handshake authentication) + b.AddUint8(0) + + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + if m.ocspStapling { + b.AddUint16(extensionStatusRequest) + b.AddUint16(0) // empty extension_data + } + if m.scts { + // RFC 8446, Section 4.4.2.1 makes no mention of + // signed_certificate_timestamp in CertificateRequest, but + // "Extensions in the Certificate message from the client MUST + // correspond to extensions in the CertificateRequest message + // from the server." and it appears in the table in Section 4.2. + b.AddUint16(extensionSCT) + b.AddUint16(0) // empty extension_data + } + if len(m.supportedSignatureAlgorithms) > 0 { + b.AddUint16(extensionSignatureAlgorithms) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + for _, sigAlgo := range m.supportedSignatureAlgorithms { + b.AddUint16(uint16(sigAlgo)) + } + }) + }) + } + if len(m.supportedSignatureAlgorithmsCert) > 0 { + b.AddUint16(extensionSignatureAlgorithmsCert) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + for _, sigAlgo := range m.supportedSignatureAlgorithmsCert { + b.AddUint16(uint16(sigAlgo)) + } + }) + }) + } + if len(m.certificateAuthorities) > 0 { + b.AddUint16(extensionCertificateAuthorities) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + for _, ca := range m.certificateAuthorities { + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(ca) + }) + } + }) + }) + } + }) + }) + + var err error + m.raw, err = b.Bytes() + return m.raw, err +} + +func (m *certificateRequestMsgTLS13) unmarshal(data []byte) bool { + *m = certificateRequestMsgTLS13{raw: data} + s := cryptobyte.String(data) + + var context, extensions cryptobyte.String + if !s.Skip(4) || // message type and uint24 length field + !s.ReadUint8LengthPrefixed(&context) || !context.Empty() || + !s.ReadUint16LengthPrefixed(&extensions) || + !s.Empty() { + return false + } + + for !extensions.Empty() { + var extension uint16 + var extData cryptobyte.String + if !extensions.ReadUint16(&extension) || + !extensions.ReadUint16LengthPrefixed(&extData) { + return false + } + + switch extension { + case extensionStatusRequest: + m.ocspStapling = true + case extensionSCT: + m.scts = true + case extensionSignatureAlgorithms: + var sigAndAlgs cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() { + return false + } + for !sigAndAlgs.Empty() { + var sigAndAlg uint16 + if !sigAndAlgs.ReadUint16(&sigAndAlg) { + return false + } + m.supportedSignatureAlgorithms = append( + m.supportedSignatureAlgorithms, SignatureScheme(sigAndAlg)) + } + case extensionSignatureAlgorithmsCert: + var sigAndAlgs cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() { + return false + } + for !sigAndAlgs.Empty() { + var sigAndAlg uint16 + if !sigAndAlgs.ReadUint16(&sigAndAlg) { + return false + } + m.supportedSignatureAlgorithmsCert = append( + m.supportedSignatureAlgorithmsCert, SignatureScheme(sigAndAlg)) + } + case extensionCertificateAuthorities: + var auths cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&auths) || auths.Empty() { + return false + } + for !auths.Empty() { + var ca []byte + if !readUint16LengthPrefixed(&auths, &ca) || len(ca) == 0 { + return false + } + m.certificateAuthorities = append(m.certificateAuthorities, ca) + } + default: + // Ignore unknown extensions. + continue + } + + if !extData.Empty() { + return false + } + } + + return true +} + +type certificateMsg struct { + raw []byte + certificates [][]byte +} + +func (m *certificateMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + var i int + for _, slice := range m.certificates { + i += len(slice) + } + + length := 3 + 3*len(m.certificates) + i + x := make([]byte, 4+length) + x[0] = typeCertificate + x[1] = uint8(length >> 16) + x[2] = uint8(length >> 8) + x[3] = uint8(length) + + certificateOctets := length - 3 + x[4] = uint8(certificateOctets >> 16) + x[5] = uint8(certificateOctets >> 8) + x[6] = uint8(certificateOctets) + + y := x[7:] + for _, slice := range m.certificates { + y[0] = uint8(len(slice) >> 16) + y[1] = uint8(len(slice) >> 8) + y[2] = uint8(len(slice)) + copy(y[3:], slice) + y = y[3+len(slice):] + } + + m.raw = x + return m.raw, nil +} + +func (m *certificateMsg) unmarshal(data []byte) bool { + if len(data) < 7 { + return false + } + + m.raw = data + certsLen := uint32(data[4])<<16 | uint32(data[5])<<8 | uint32(data[6]) + if uint32(len(data)) != certsLen+7 { + return false + } + + numCerts := 0 + d := data[7:] + for certsLen > 0 { + if len(d) < 4 { + return false + } + certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2]) + if uint32(len(d)) < 3+certLen { + return false + } + d = d[3+certLen:] + certsLen -= 3 + certLen + numCerts++ + } + + m.certificates = make([][]byte, numCerts) + d = data[7:] + for i := 0; i < numCerts; i++ { + certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2]) + m.certificates[i] = d[3 : 3+certLen] + d = d[3+certLen:] + } + + return true +} + +type certificateMsgTLS13 struct { + raw []byte + certificate Certificate + ocspStapling bool + scts bool +} + +func (m *certificateMsgTLS13) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + var b cryptobyte.Builder + b.AddUint8(typeCertificate) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint8(0) // certificate_request_context + + certificate := m.certificate + if !m.ocspStapling { + certificate.OCSPStaple = nil + } + if !m.scts { + certificate.SignedCertificateTimestamps = nil + } + marshalCertificate(b, certificate) + }) + + var err error + m.raw, err = b.Bytes() + return m.raw, err +} + +func marshalCertificate(b *cryptobyte.Builder, certificate Certificate) { + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + for i, cert := range certificate.Certificate { + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(cert) + }) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + if i > 0 { + // This library only supports OCSP and SCT for leaf certificates. + return + } + if certificate.OCSPStaple != nil { + b.AddUint16(extensionStatusRequest) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint8(statusTypeOCSP) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(certificate.OCSPStaple) + }) + }) + } + if certificate.SignedCertificateTimestamps != nil { + b.AddUint16(extensionSCT) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + for _, sct := range certificate.SignedCertificateTimestamps { + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(sct) + }) + } + }) + }) + } + }) + } + }) +} + +func (m *certificateMsgTLS13) unmarshal(data []byte) bool { + *m = certificateMsgTLS13{raw: data} + s := cryptobyte.String(data) + + var context cryptobyte.String + if !s.Skip(4) || // message type and uint24 length field + !s.ReadUint8LengthPrefixed(&context) || !context.Empty() || + !unmarshalCertificate(&s, &m.certificate) || + !s.Empty() { + return false + } + + m.scts = m.certificate.SignedCertificateTimestamps != nil + m.ocspStapling = m.certificate.OCSPStaple != nil + + return true +} + +func unmarshalCertificate(s *cryptobyte.String, certificate *Certificate) bool { + var certList cryptobyte.String + if !s.ReadUint24LengthPrefixed(&certList) { + return false + } + for !certList.Empty() { + var cert []byte + var extensions cryptobyte.String + if !readUint24LengthPrefixed(&certList, &cert) || + !certList.ReadUint16LengthPrefixed(&extensions) { + return false + } + certificate.Certificate = append(certificate.Certificate, cert) + for !extensions.Empty() { + var extension uint16 + var extData cryptobyte.String + if !extensions.ReadUint16(&extension) || + !extensions.ReadUint16LengthPrefixed(&extData) { + return false + } + if len(certificate.Certificate) > 1 { + // This library only supports OCSP and SCT for leaf certificates. + continue + } + + switch extension { + case extensionStatusRequest: + var statusType uint8 + if !extData.ReadUint8(&statusType) || statusType != statusTypeOCSP || + !readUint24LengthPrefixed(&extData, &certificate.OCSPStaple) || + len(certificate.OCSPStaple) == 0 { + return false + } + case extensionSCT: + var sctList cryptobyte.String + if !extData.ReadUint16LengthPrefixed(&sctList) || sctList.Empty() { + return false + } + for !sctList.Empty() { + var sct []byte + if !readUint16LengthPrefixed(&sctList, &sct) || + len(sct) == 0 { + return false + } + certificate.SignedCertificateTimestamps = append( + certificate.SignedCertificateTimestamps, sct) + } + default: + // Ignore unknown extensions. + continue + } + + if !extData.Empty() { + return false + } + } + } + return true +} + +type serverKeyExchangeMsg struct { + raw []byte + key []byte +} + +func (m *serverKeyExchangeMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + length := len(m.key) + x := make([]byte, length+4) + x[0] = typeServerKeyExchange + x[1] = uint8(length >> 16) + x[2] = uint8(length >> 8) + x[3] = uint8(length) + copy(x[4:], m.key) + + m.raw = x + return x, nil +} + +func (m *serverKeyExchangeMsg) unmarshal(data []byte) bool { + m.raw = data + if len(data) < 4 { + return false + } + m.key = data[4:] + return true +} + +type certificateStatusMsg struct { + raw []byte + response []byte +} + +func (m *certificateStatusMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + var b cryptobyte.Builder + b.AddUint8(typeCertificateStatus) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddUint8(statusTypeOCSP) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(m.response) + }) + }) + + var err error + m.raw, err = b.Bytes() + return m.raw, err +} + +func (m *certificateStatusMsg) unmarshal(data []byte) bool { + m.raw = data + s := cryptobyte.String(data) + + var statusType uint8 + if !s.Skip(4) || // message type and uint24 length field + !s.ReadUint8(&statusType) || statusType != statusTypeOCSP || + !readUint24LengthPrefixed(&s, &m.response) || + len(m.response) == 0 || !s.Empty() { + return false + } + return true +} + +type serverHelloDoneMsg struct{} + +func (m *serverHelloDoneMsg) marshal() ([]byte, error) { + x := make([]byte, 4) + x[0] = typeServerHelloDone + return x, nil +} + +func (m *serverHelloDoneMsg) unmarshal(data []byte) bool { + return len(data) == 4 +} + +type clientKeyExchangeMsg struct { + raw []byte + ciphertext []byte +} + +func (m *clientKeyExchangeMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + length := len(m.ciphertext) + x := make([]byte, length+4) + x[0] = typeClientKeyExchange + x[1] = uint8(length >> 16) + x[2] = uint8(length >> 8) + x[3] = uint8(length) + copy(x[4:], m.ciphertext) + + m.raw = x + return x, nil +} + +func (m *clientKeyExchangeMsg) unmarshal(data []byte) bool { + m.raw = data + if len(data) < 4 { + return false + } + l := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) + if l != len(data)-4 { + return false + } + m.ciphertext = data[4:] + return true +} + +type finishedMsg struct { + raw []byte + verifyData []byte +} + +func (m *finishedMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + var b cryptobyte.Builder + b.AddUint8(typeFinished) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(m.verifyData) + }) + + var err error + m.raw, err = b.Bytes() + return m.raw, err +} + +func (m *finishedMsg) unmarshal(data []byte) bool { + m.raw = data + s := cryptobyte.String(data) + return s.Skip(1) && + readUint24LengthPrefixed(&s, &m.verifyData) && + s.Empty() +} + +type certificateRequestMsg struct { + raw []byte + // hasSignatureAlgorithm indicates whether this message includes a list of + // supported signature algorithms. This change was introduced with TLS 1.2. + hasSignatureAlgorithm bool + + certificateTypes []byte + supportedSignatureAlgorithms []SignatureScheme + certificateAuthorities [][]byte +} + +func (m *certificateRequestMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + // See RFC 4346, Section 7.4.4. + length := 1 + len(m.certificateTypes) + 2 + casLength := 0 + for _, ca := range m.certificateAuthorities { + casLength += 2 + len(ca) + } + length += casLength + + if m.hasSignatureAlgorithm { + length += 2 + 2*len(m.supportedSignatureAlgorithms) + } + + x := make([]byte, 4+length) + x[0] = typeCertificateRequest + x[1] = uint8(length >> 16) + x[2] = uint8(length >> 8) + x[3] = uint8(length) + + x[4] = uint8(len(m.certificateTypes)) + + copy(x[5:], m.certificateTypes) + y := x[5+len(m.certificateTypes):] + + if m.hasSignatureAlgorithm { + n := len(m.supportedSignatureAlgorithms) * 2 + y[0] = uint8(n >> 8) + y[1] = uint8(n) + y = y[2:] + for _, sigAlgo := range m.supportedSignatureAlgorithms { + y[0] = uint8(sigAlgo >> 8) + y[1] = uint8(sigAlgo) + y = y[2:] + } + } + + y[0] = uint8(casLength >> 8) + y[1] = uint8(casLength) + y = y[2:] + for _, ca := range m.certificateAuthorities { + y[0] = uint8(len(ca) >> 8) + y[1] = uint8(len(ca)) + y = y[2:] + copy(y, ca) + y = y[len(ca):] + } + + m.raw = x + return m.raw, nil +} + +func (m *certificateRequestMsg) unmarshal(data []byte) bool { + m.raw = data + + if len(data) < 5 { + return false + } + + length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3]) + if uint32(len(data))-4 != length { + return false + } + + numCertTypes := int(data[4]) + data = data[5:] + if numCertTypes == 0 || len(data) <= numCertTypes { + return false + } + + m.certificateTypes = make([]byte, numCertTypes) + if copy(m.certificateTypes, data) != numCertTypes { + return false + } + + data = data[numCertTypes:] + + if m.hasSignatureAlgorithm { + if len(data) < 2 { + return false + } + sigAndHashLen := uint16(data[0])<<8 | uint16(data[1]) + data = data[2:] + if sigAndHashLen&1 != 0 { + return false + } + if len(data) < int(sigAndHashLen) { + return false + } + numSigAlgos := sigAndHashLen / 2 + m.supportedSignatureAlgorithms = make([]SignatureScheme, numSigAlgos) + for i := range m.supportedSignatureAlgorithms { + m.supportedSignatureAlgorithms[i] = SignatureScheme(data[0])<<8 | SignatureScheme(data[1]) + data = data[2:] + } + } + + if len(data) < 2 { + return false + } + casLength := uint16(data[0])<<8 | uint16(data[1]) + data = data[2:] + if len(data) < int(casLength) { + return false + } + cas := make([]byte, casLength) + copy(cas, data) + data = data[casLength:] + + m.certificateAuthorities = nil + for len(cas) > 0 { + if len(cas) < 2 { + return false + } + caLen := uint16(cas[0])<<8 | uint16(cas[1]) + cas = cas[2:] + + if len(cas) < int(caLen) { + return false + } + + m.certificateAuthorities = append(m.certificateAuthorities, cas[:caLen]) + cas = cas[caLen:] + } + + return len(data) == 0 +} + +type certificateVerifyMsg struct { + raw []byte + hasSignatureAlgorithm bool // format change introduced in TLS 1.2 + signatureAlgorithm SignatureScheme + signature []byte +} + +func (m *certificateVerifyMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + var b cryptobyte.Builder + b.AddUint8(typeCertificateVerify) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + if m.hasSignatureAlgorithm { + b.AddUint16(uint16(m.signatureAlgorithm)) + } + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(m.signature) + }) + }) + + var err error + m.raw, err = b.Bytes() + return m.raw, err +} + +func (m *certificateVerifyMsg) unmarshal(data []byte) bool { + m.raw = data + s := cryptobyte.String(data) + + if !s.Skip(4) { // message type and uint24 length field + return false + } + if m.hasSignatureAlgorithm { + if !s.ReadUint16((*uint16)(&m.signatureAlgorithm)) { + return false + } + } + return readUint16LengthPrefixed(&s, &m.signature) && s.Empty() +} + +type newSessionTicketMsg struct { + raw []byte + ticket []byte +} + +func (m *newSessionTicketMsg) marshal() ([]byte, error) { + if m.raw != nil { + return m.raw, nil + } + + // See RFC 5077, Section 3.3. + ticketLen := len(m.ticket) + length := 2 + 4 + ticketLen + x := make([]byte, 4+length) + x[0] = typeNewSessionTicket + x[1] = uint8(length >> 16) + x[2] = uint8(length >> 8) + x[3] = uint8(length) + x[8] = uint8(ticketLen >> 8) + x[9] = uint8(ticketLen) + copy(x[10:], m.ticket) + + m.raw = x + + return m.raw, nil +} + +func (m *newSessionTicketMsg) unmarshal(data []byte) bool { + m.raw = data + + if len(data) < 10 { + return false + } + + length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3]) + if uint32(len(data))-4 != length { + return false + } + + ticketLen := int(data[8])<<8 + int(data[9]) + if len(data)-10 != ticketLen { + return false + } + + m.ticket = data[10:] + + return true +} + +type helloRequestMsg struct { +} + +func (*helloRequestMsg) marshal() ([]byte, error) { + return []byte{typeHelloRequest, 0, 0, 0}, nil +} + +func (*helloRequestMsg) unmarshal(data []byte) bool { + return len(data) == 4 +} + +type transcriptHash interface { + Write([]byte) (int, error) +} + +// transcriptMsg is a helper used to marshal and hash messages which typically +// are not written to the wire, and as such aren't hashed during Conn.writeRecord. +func transcriptMsg(msg handshakeMessage, h transcriptHash) error { + data, err := msg.marshal() + if err != nil { + return err + } + h.Write(data) + return nil +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/handshake_server.go b/vendor/github.com/quic-go/qtls-go1-19/handshake_server.go new file mode 100644 index 000000000..738fc9471 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/handshake_server.go @@ -0,0 +1,926 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "context" + "crypto" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/rsa" + "crypto/subtle" + "crypto/x509" + "errors" + "fmt" + "hash" + "io" + "sync/atomic" + "time" +) + +// serverHandshakeState contains details of a server handshake in progress. +// It's discarded once the handshake has completed. +type serverHandshakeState struct { + c *Conn + ctx context.Context + clientHello *clientHelloMsg + hello *serverHelloMsg + suite *cipherSuite + ecdheOk bool + ecSignOk bool + rsaDecryptOk bool + rsaSignOk bool + sessionState *sessionState + finishedHash finishedHash + masterSecret []byte + cert *Certificate +} + +// serverHandshake performs a TLS handshake as a server. +func (c *Conn) serverHandshake(ctx context.Context) error { + c.setAlternativeRecordLayer() + + clientHello, err := c.readClientHello(ctx) + if err != nil { + return err + } + + if c.vers == VersionTLS13 { + hs := serverHandshakeStateTLS13{ + c: c, + ctx: ctx, + clientHello: clientHello, + } + return hs.handshake() + } else if c.extraConfig.usesAlternativeRecordLayer() { + // This should already have been caught by the check that the ClientHello doesn't + // offer any (supported) versions older than TLS 1.3. + // Check again to make sure we can't be tricked into using an older version. + c.sendAlert(alertProtocolVersion) + return errors.New("tls: negotiated TLS < 1.3 when using QUIC") + } + + hs := serverHandshakeState{ + c: c, + ctx: ctx, + clientHello: clientHello, + } + return hs.handshake() +} + +func (hs *serverHandshakeState) handshake() error { + c := hs.c + + if err := hs.processClientHello(); err != nil { + return err + } + + // For an overview of TLS handshaking, see RFC 5246, Section 7.3. + c.buffering = true + if hs.checkForResumption() { + // The client has included a session ticket and so we do an abbreviated handshake. + c.didResume = true + if err := hs.doResumeHandshake(); err != nil { + return err + } + if err := hs.establishKeys(); err != nil { + return err + } + if err := hs.sendSessionTicket(); err != nil { + return err + } + if err := hs.sendFinished(c.serverFinished[:]); err != nil { + return err + } + if _, err := c.flush(); err != nil { + return err + } + c.clientFinishedIsFirst = false + if err := hs.readFinished(nil); err != nil { + return err + } + } else { + // The client didn't include a session ticket, or it wasn't + // valid so we do a full handshake. + if err := hs.pickCipherSuite(); err != nil { + return err + } + if err := hs.doFullHandshake(); err != nil { + return err + } + if err := hs.establishKeys(); err != nil { + return err + } + if err := hs.readFinished(c.clientFinished[:]); err != nil { + return err + } + c.clientFinishedIsFirst = true + c.buffering = true + if err := hs.sendSessionTicket(); err != nil { + return err + } + if err := hs.sendFinished(nil); err != nil { + return err + } + if _, err := c.flush(); err != nil { + return err + } + } + + c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random) + atomic.StoreUint32(&c.handshakeStatus, 1) + + c.updateConnectionState() + return nil +} + +// readClientHello reads a ClientHello message and selects the protocol version. +func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, error) { + // clientHelloMsg is included in the transcript, but we haven't initialized + // it yet. The respective handshake functions will record it themselves. + msg, err := c.readHandshake(nil) + if err != nil { + return nil, err + } + clientHello, ok := msg.(*clientHelloMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return nil, unexpectedMessageError(clientHello, msg) + } + + var configForClient *config + originalConfig := c.config + if c.config.GetConfigForClient != nil { + chi := newClientHelloInfo(ctx, c, clientHello) + if cfc, err := c.config.GetConfigForClient(chi); err != nil { + c.sendAlert(alertInternalError) + return nil, err + } else if cfc != nil { + configForClient = fromConfig(cfc) + c.config = configForClient + } + } + c.ticketKeys = originalConfig.ticketKeys(configForClient) + + clientVersions := clientHello.supportedVersions + if len(clientHello.supportedVersions) == 0 { + clientVersions = supportedVersionsFromMax(clientHello.vers) + } + if c.extraConfig.usesAlternativeRecordLayer() { + // In QUIC, the client MUST NOT offer any old TLS versions. + // Here, we can only check that none of the other supported versions of this library + // (TLS 1.0 - TLS 1.2) is offered. We don't check for any SSL versions here. + for _, ver := range clientVersions { + if ver == VersionTLS13 { + continue + } + for _, v := range supportedVersions { + if ver == v { + c.sendAlert(alertProtocolVersion) + return nil, fmt.Errorf("tls: client offered old TLS version %#x", ver) + } + } + } + // Make the config we're using allows us to use TLS 1.3. + if c.config.maxSupportedVersion(roleServer) < VersionTLS13 { + c.sendAlert(alertInternalError) + return nil, errors.New("tls: MaxVersion prevents QUIC from using TLS 1.3") + } + } + c.vers, ok = c.config.mutualVersion(roleServer, clientVersions) + if !ok { + c.sendAlert(alertProtocolVersion) + return nil, fmt.Errorf("tls: client offered only unsupported versions: %x", clientVersions) + } + c.haveVers = true + c.in.version = c.vers + c.out.version = c.vers + + return clientHello, nil +} + +func (hs *serverHandshakeState) processClientHello() error { + c := hs.c + + hs.hello = new(serverHelloMsg) + hs.hello.vers = c.vers + + foundCompression := false + // We only support null compression, so check that the client offered it. + for _, compression := range hs.clientHello.compressionMethods { + if compression == compressionNone { + foundCompression = true + break + } + } + + if !foundCompression { + c.sendAlert(alertHandshakeFailure) + return errors.New("tls: client does not support uncompressed connections") + } + + hs.hello.random = make([]byte, 32) + serverRandom := hs.hello.random + // Downgrade protection canaries. See RFC 8446, Section 4.1.3. + maxVers := c.config.maxSupportedVersion(roleServer) + if maxVers >= VersionTLS12 && c.vers < maxVers || testingOnlyForceDowngradeCanary { + if c.vers == VersionTLS12 { + copy(serverRandom[24:], downgradeCanaryTLS12) + } else { + copy(serverRandom[24:], downgradeCanaryTLS11) + } + serverRandom = serverRandom[:24] + } + _, err := io.ReadFull(c.config.rand(), serverRandom) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + + if len(hs.clientHello.secureRenegotiation) != 0 { + c.sendAlert(alertHandshakeFailure) + return errors.New("tls: initial handshake had non-empty renegotiation extension") + } + + hs.hello.secureRenegotiationSupported = hs.clientHello.secureRenegotiationSupported + hs.hello.compressionMethod = compressionNone + if len(hs.clientHello.serverName) > 0 { + c.serverName = hs.clientHello.serverName + } + + selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols) + if err != nil { + c.sendAlert(alertNoApplicationProtocol) + return err + } + hs.hello.alpnProtocol = selectedProto + c.clientProtocol = selectedProto + + hs.cert, err = c.config.getCertificate(newClientHelloInfo(hs.ctx, c, hs.clientHello)) + if err != nil { + if err == errNoCertificates { + c.sendAlert(alertUnrecognizedName) + } else { + c.sendAlert(alertInternalError) + } + return err + } + if hs.clientHello.scts { + hs.hello.scts = hs.cert.SignedCertificateTimestamps + } + + hs.ecdheOk = supportsECDHE(c.config, hs.clientHello.supportedCurves, hs.clientHello.supportedPoints) + + if hs.ecdheOk && len(hs.clientHello.supportedPoints) > 0 { + // Although omitting the ec_point_formats extension is permitted, some + // old OpenSSL version will refuse to handshake if not present. + // + // Per RFC 4492, section 5.1.2, implementations MUST support the + // uncompressed point format. See golang.org/issue/31943. + hs.hello.supportedPoints = []uint8{pointFormatUncompressed} + } + + if priv, ok := hs.cert.PrivateKey.(crypto.Signer); ok { + switch priv.Public().(type) { + case *ecdsa.PublicKey: + hs.ecSignOk = true + case ed25519.PublicKey: + hs.ecSignOk = true + case *rsa.PublicKey: + hs.rsaSignOk = true + default: + c.sendAlert(alertInternalError) + return fmt.Errorf("tls: unsupported signing key type (%T)", priv.Public()) + } + } + if priv, ok := hs.cert.PrivateKey.(crypto.Decrypter); ok { + switch priv.Public().(type) { + case *rsa.PublicKey: + hs.rsaDecryptOk = true + default: + c.sendAlert(alertInternalError) + return fmt.Errorf("tls: unsupported decryption key type (%T)", priv.Public()) + } + } + + return nil +} + +// negotiateALPN picks a shared ALPN protocol that both sides support in server +// preference order. If ALPN is not configured or the peer doesn't support it, +// it returns "" and no error. +func negotiateALPN(serverProtos, clientProtos []string) (string, error) { + if len(serverProtos) == 0 || len(clientProtos) == 0 { + return "", nil + } + var http11fallback bool + for _, s := range serverProtos { + for _, c := range clientProtos { + if s == c { + return s, nil + } + if s == "h2" && c == "http/1.1" { + http11fallback = true + } + } + } + // As a special case, let http/1.1 clients connect to h2 servers as if they + // didn't support ALPN. We used not to enforce protocol overlap, so over + // time a number of HTTP servers were configured with only "h2", but + // expected to accept connections from "http/1.1" clients. See Issue 46310. + if http11fallback { + return "", nil + } + return "", fmt.Errorf("tls: client requested unsupported application protocols (%s)", clientProtos) +} + +// supportsECDHE returns whether ECDHE key exchanges can be used with this +// pre-TLS 1.3 client. +func supportsECDHE(c *config, supportedCurves []CurveID, supportedPoints []uint8) bool { + supportsCurve := false + for _, curve := range supportedCurves { + if c.supportsCurve(curve) { + supportsCurve = true + break + } + } + + supportsPointFormat := false + for _, pointFormat := range supportedPoints { + if pointFormat == pointFormatUncompressed { + supportsPointFormat = true + break + } + } + // Per RFC 8422, Section 5.1.2, if the Supported Point Formats extension is + // missing, uncompressed points are supported. If supportedPoints is empty, + // the extension must be missing, as an empty extension body is rejected by + // the parser. See https://go.dev/issue/49126. + if len(supportedPoints) == 0 { + supportsPointFormat = true + } + + return supportsCurve && supportsPointFormat +} + +func (hs *serverHandshakeState) pickCipherSuite() error { + c := hs.c + + preferenceOrder := cipherSuitesPreferenceOrder + if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) { + preferenceOrder = cipherSuitesPreferenceOrderNoAES + } + + configCipherSuites := c.config.cipherSuites() + preferenceList := make([]uint16, 0, len(configCipherSuites)) + for _, suiteID := range preferenceOrder { + for _, id := range configCipherSuites { + if id == suiteID { + preferenceList = append(preferenceList, id) + break + } + } + } + + hs.suite = selectCipherSuite(preferenceList, hs.clientHello.cipherSuites, hs.cipherSuiteOk) + if hs.suite == nil { + c.sendAlert(alertHandshakeFailure) + return errors.New("tls: no cipher suite supported by both client and server") + } + c.cipherSuite = hs.suite.id + + for _, id := range hs.clientHello.cipherSuites { + if id == TLS_FALLBACK_SCSV { + // The client is doing a fallback connection. See RFC 7507. + if hs.clientHello.vers < c.config.maxSupportedVersion(roleServer) { + c.sendAlert(alertInappropriateFallback) + return errors.New("tls: client using inappropriate protocol fallback") + } + break + } + } + + return nil +} + +func (hs *serverHandshakeState) cipherSuiteOk(c *cipherSuite) bool { + if c.flags&suiteECDHE != 0 { + if !hs.ecdheOk { + return false + } + if c.flags&suiteECSign != 0 { + if !hs.ecSignOk { + return false + } + } else if !hs.rsaSignOk { + return false + } + } else if !hs.rsaDecryptOk { + return false + } + if hs.c.vers < VersionTLS12 && c.flags&suiteTLS12 != 0 { + return false + } + return true +} + +// checkForResumption reports whether we should perform resumption on this connection. +func (hs *serverHandshakeState) checkForResumption() bool { + c := hs.c + + if c.config.SessionTicketsDisabled { + return false + } + + plaintext, usedOldKey := c.decryptTicket(hs.clientHello.sessionTicket) + if plaintext == nil { + return false + } + hs.sessionState = &sessionState{usedOldKey: usedOldKey} + ok := hs.sessionState.unmarshal(plaintext) + if !ok { + return false + } + + createdAt := time.Unix(int64(hs.sessionState.createdAt), 0) + if c.config.time().Sub(createdAt) > maxSessionTicketLifetime { + return false + } + + // Never resume a session for a different TLS version. + if c.vers != hs.sessionState.vers { + return false + } + + cipherSuiteOk := false + // Check that the client is still offering the ciphersuite in the session. + for _, id := range hs.clientHello.cipherSuites { + if id == hs.sessionState.cipherSuite { + cipherSuiteOk = true + break + } + } + if !cipherSuiteOk { + return false + } + + // Check that we also support the ciphersuite from the session. + hs.suite = selectCipherSuite([]uint16{hs.sessionState.cipherSuite}, + c.config.cipherSuites(), hs.cipherSuiteOk) + if hs.suite == nil { + return false + } + + sessionHasClientCerts := len(hs.sessionState.certificates) != 0 + needClientCerts := requiresClientCert(c.config.ClientAuth) + if needClientCerts && !sessionHasClientCerts { + return false + } + if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { + return false + } + + return true +} + +func (hs *serverHandshakeState) doResumeHandshake() error { + c := hs.c + + hs.hello.cipherSuite = hs.suite.id + c.cipherSuite = hs.suite.id + // We echo the client's session ID in the ServerHello to let it know + // that we're doing a resumption. + hs.hello.sessionId = hs.clientHello.sessionId + hs.hello.ticketSupported = hs.sessionState.usedOldKey + hs.finishedHash = newFinishedHash(c.vers, hs.suite) + hs.finishedHash.discardHandshakeBuffer() + if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil { + return err + } + if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil { + return err + } + + if err := c.processCertsFromClient(Certificate{ + Certificate: hs.sessionState.certificates, + }); err != nil { + return err + } + + if c.config.VerifyConnection != nil { + if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { + c.sendAlert(alertBadCertificate) + return err + } + } + + hs.masterSecret = hs.sessionState.masterSecret + + return nil +} + +func (hs *serverHandshakeState) doFullHandshake() error { + c := hs.c + + if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 { + hs.hello.ocspStapling = true + } + + hs.hello.ticketSupported = hs.clientHello.ticketSupported && !c.config.SessionTicketsDisabled + hs.hello.cipherSuite = hs.suite.id + + hs.finishedHash = newFinishedHash(hs.c.vers, hs.suite) + if c.config.ClientAuth == NoClientCert { + // No need to keep a full record of the handshake if client + // certificates won't be used. + hs.finishedHash.discardHandshakeBuffer() + } + if err := transcriptMsg(hs.clientHello, &hs.finishedHash); err != nil { + return err + } + if _, err := hs.c.writeHandshakeRecord(hs.hello, &hs.finishedHash); err != nil { + return err + } + + certMsg := new(certificateMsg) + certMsg.certificates = hs.cert.Certificate + if _, err := hs.c.writeHandshakeRecord(certMsg, &hs.finishedHash); err != nil { + return err + } + + if hs.hello.ocspStapling { + certStatus := new(certificateStatusMsg) + certStatus.response = hs.cert.OCSPStaple + if _, err := hs.c.writeHandshakeRecord(certStatus, &hs.finishedHash); err != nil { + return err + } + } + + keyAgreement := hs.suite.ka(c.vers) + skx, err := keyAgreement.generateServerKeyExchange(c.config, hs.cert, hs.clientHello, hs.hello) + if err != nil { + c.sendAlert(alertHandshakeFailure) + return err + } + if skx != nil { + if _, err := hs.c.writeHandshakeRecord(skx, &hs.finishedHash); err != nil { + return err + } + } + + var certReq *certificateRequestMsg + if c.config.ClientAuth >= RequestClientCert { + // Request a client certificate + certReq = new(certificateRequestMsg) + certReq.certificateTypes = []byte{ + byte(certTypeRSASign), + byte(certTypeECDSASign), + } + if c.vers >= VersionTLS12 { + certReq.hasSignatureAlgorithm = true + certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms() + } + + // An empty list of certificateAuthorities signals to + // the client that it may send any certificate in response + // to our request. When we know the CAs we trust, then + // we can send them down, so that the client can choose + // an appropriate certificate to give to us. + if c.config.ClientCAs != nil { + certReq.certificateAuthorities = c.config.ClientCAs.Subjects() + } + if _, err := hs.c.writeHandshakeRecord(certReq, &hs.finishedHash); err != nil { + return err + } + } + + helloDone := new(serverHelloDoneMsg) + if _, err := hs.c.writeHandshakeRecord(helloDone, &hs.finishedHash); err != nil { + return err + } + + if _, err := c.flush(); err != nil { + return err + } + + var pub crypto.PublicKey // public key for client auth, if any + + msg, err := c.readHandshake(&hs.finishedHash) + if err != nil { + return err + } + + // If we requested a client certificate, then the client must send a + // certificate message, even if it's empty. + if c.config.ClientAuth >= RequestClientCert { + certMsg, ok := msg.(*certificateMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(certMsg, msg) + } + + if err := c.processCertsFromClient(Certificate{ + Certificate: certMsg.certificates, + }); err != nil { + return err + } + if len(certMsg.certificates) != 0 { + pub = c.peerCertificates[0].PublicKey + } + + msg, err = c.readHandshake(&hs.finishedHash) + if err != nil { + return err + } + } + if c.config.VerifyConnection != nil { + if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { + c.sendAlert(alertBadCertificate) + return err + } + } + + // Get client key exchange + ckx, ok := msg.(*clientKeyExchangeMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(ckx, msg) + } + + preMasterSecret, err := keyAgreement.processClientKeyExchange(c.config, hs.cert, ckx, c.vers) + if err != nil { + c.sendAlert(alertHandshakeFailure) + return err + } + hs.masterSecret = masterFromPreMasterSecret(c.vers, hs.suite, preMasterSecret, hs.clientHello.random, hs.hello.random) + if err := c.config.writeKeyLog(keyLogLabelTLS12, hs.clientHello.random, hs.masterSecret); err != nil { + c.sendAlert(alertInternalError) + return err + } + + // If we received a client cert in response to our certificate request message, + // the client will send us a certificateVerifyMsg immediately after the + // clientKeyExchangeMsg. This message is a digest of all preceding + // handshake-layer messages that is signed using the private key corresponding + // to the client's certificate. This allows us to verify that the client is in + // possession of the private key of the certificate. + if len(c.peerCertificates) > 0 { + // certificateVerifyMsg is included in the transcript, but not until + // after we verify the handshake signature, since the state before + // this message was sent is used. + msg, err = c.readHandshake(nil) + if err != nil { + return err + } + certVerify, ok := msg.(*certificateVerifyMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(certVerify, msg) + } + + var sigType uint8 + var sigHash crypto.Hash + if c.vers >= VersionTLS12 { + if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, certReq.supportedSignatureAlgorithms) { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: client certificate used with invalid signature algorithm") + } + sigType, sigHash, err = typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) + if err != nil { + return c.sendAlert(alertInternalError) + } + } else { + sigType, sigHash, err = legacyTypeAndHashFromPublicKey(pub) + if err != nil { + c.sendAlert(alertIllegalParameter) + return err + } + } + + signed := hs.finishedHash.hashForClientCertificate(sigType, sigHash, hs.masterSecret) + if err := verifyHandshakeSignature(sigType, pub, sigHash, signed, certVerify.signature); err != nil { + c.sendAlert(alertDecryptError) + return errors.New("tls: invalid signature by the client certificate: " + err.Error()) + } + + if err := transcriptMsg(certVerify, &hs.finishedHash); err != nil { + return err + } + } + + hs.finishedHash.discardHandshakeBuffer() + + return nil +} + +func (hs *serverHandshakeState) establishKeys() error { + c := hs.c + + clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := + keysFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) + + var clientCipher, serverCipher any + var clientHash, serverHash hash.Hash + + if hs.suite.aead == nil { + clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */) + clientHash = hs.suite.mac(clientMAC) + serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */) + serverHash = hs.suite.mac(serverMAC) + } else { + clientCipher = hs.suite.aead(clientKey, clientIV) + serverCipher = hs.suite.aead(serverKey, serverIV) + } + + c.in.prepareCipherSpec(c.vers, clientCipher, clientHash) + c.out.prepareCipherSpec(c.vers, serverCipher, serverHash) + + return nil +} + +func (hs *serverHandshakeState) readFinished(out []byte) error { + c := hs.c + + if err := c.readChangeCipherSpec(); err != nil { + return err + } + + // finishedMsg is included in the transcript, but not until after we + // check the client version, since the state before this message was + // sent is used during verification. + msg, err := c.readHandshake(nil) + if err != nil { + return err + } + clientFinished, ok := msg.(*finishedMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(clientFinished, msg) + } + + verify := hs.finishedHash.clientSum(hs.masterSecret) + if len(verify) != len(clientFinished.verifyData) || + subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 { + c.sendAlert(alertHandshakeFailure) + return errors.New("tls: client's Finished message is incorrect") + } + + if err := transcriptMsg(clientFinished, &hs.finishedHash); err != nil { + return err + } + + copy(out, verify) + return nil +} + +func (hs *serverHandshakeState) sendSessionTicket() error { + // ticketSupported is set in a resumption handshake if the + // ticket from the client was encrypted with an old session + // ticket key and thus a refreshed ticket should be sent. + if !hs.hello.ticketSupported { + return nil + } + + c := hs.c + m := new(newSessionTicketMsg) + + createdAt := uint64(c.config.time().Unix()) + if hs.sessionState != nil { + // If this is re-wrapping an old key, then keep + // the original time it was created. + createdAt = hs.sessionState.createdAt + } + + var certsFromClient [][]byte + for _, cert := range c.peerCertificates { + certsFromClient = append(certsFromClient, cert.Raw) + } + state := sessionState{ + vers: c.vers, + cipherSuite: hs.suite.id, + createdAt: createdAt, + masterSecret: hs.masterSecret, + certificates: certsFromClient, + } + stateBytes, err := state.marshal() + if err != nil { + return err + } + m.ticket, err = c.encryptTicket(stateBytes) + if err != nil { + return err + } + + if _, err := hs.c.writeHandshakeRecord(m, &hs.finishedHash); err != nil { + return err + } + + return nil +} + +func (hs *serverHandshakeState) sendFinished(out []byte) error { + c := hs.c + + if err := c.writeChangeCipherRecord(); err != nil { + return err + } + + finished := new(finishedMsg) + finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret) + if _, err := hs.c.writeHandshakeRecord(finished, &hs.finishedHash); err != nil { + return err + } + + copy(out, finished.verifyData) + + return nil +} + +// processCertsFromClient takes a chain of client certificates either from a +// Certificates message or from a sessionState and verifies them. It returns +// the public key of the leaf certificate. +func (c *Conn) processCertsFromClient(certificate Certificate) error { + certificates := certificate.Certificate + certs := make([]*x509.Certificate, len(certificates)) + var err error + for i, asn1Data := range certificates { + if certs[i], err = x509.ParseCertificate(asn1Data); err != nil { + c.sendAlert(alertBadCertificate) + return errors.New("tls: failed to parse client certificate: " + err.Error()) + } + if certs[i].PublicKeyAlgorithm == x509.RSA && certs[i].PublicKey.(*rsa.PublicKey).N.BitLen() > maxRSAKeySize { + c.sendAlert(alertBadCertificate) + return fmt.Errorf("tls: client sent certificate containing RSA key larger than %d bits", maxRSAKeySize) + } + } + + if len(certs) == 0 && requiresClientCert(c.config.ClientAuth) { + c.sendAlert(alertBadCertificate) + return errors.New("tls: client didn't provide a certificate") + } + + if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 { + opts := x509.VerifyOptions{ + Roots: c.config.ClientCAs, + CurrentTime: c.config.time(), + Intermediates: x509.NewCertPool(), + KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, + } + + for _, cert := range certs[1:] { + opts.Intermediates.AddCert(cert) + } + + chains, err := certs[0].Verify(opts) + if err != nil { + c.sendAlert(alertBadCertificate) + return errors.New("tls: failed to verify client certificate: " + err.Error()) + } + + c.verifiedChains = chains + } + + c.peerCertificates = certs + c.ocspResponse = certificate.OCSPStaple + c.scts = certificate.SignedCertificateTimestamps + + if len(certs) > 0 { + switch certs[0].PublicKey.(type) { + case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey: + default: + c.sendAlert(alertUnsupportedCertificate) + return fmt.Errorf("tls: client certificate contains an unsupported public key of type %T", certs[0].PublicKey) + } + } + + if c.config.VerifyPeerCertificate != nil { + if err := c.config.VerifyPeerCertificate(certificates, c.verifiedChains); err != nil { + c.sendAlert(alertBadCertificate) + return err + } + } + + return nil +} + +func newClientHelloInfo(ctx context.Context, c *Conn, clientHello *clientHelloMsg) *ClientHelloInfo { + supportedVersions := clientHello.supportedVersions + if len(clientHello.supportedVersions) == 0 { + supportedVersions = supportedVersionsFromMax(clientHello.vers) + } + + return toClientHelloInfo(&clientHelloInfo{ + CipherSuites: clientHello.cipherSuites, + ServerName: clientHello.serverName, + SupportedCurves: clientHello.supportedCurves, + SupportedPoints: clientHello.supportedPoints, + SignatureSchemes: clientHello.supportedSignatureAlgorithms, + SupportedProtos: clientHello.alpnProtocols, + SupportedVersions: supportedVersions, + Conn: c.conn, + config: toConfig(c.config), + ctx: ctx, + }) +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/handshake_server_tls13.go b/vendor/github.com/quic-go/qtls-go1-19/handshake_server_tls13.go new file mode 100644 index 000000000..c4706c44d --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/handshake_server_tls13.go @@ -0,0 +1,903 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "bytes" + "context" + "crypto" + "crypto/hmac" + "crypto/rsa" + "errors" + "hash" + "io" + "sync/atomic" + "time" +) + +// maxClientPSKIdentities is the number of client PSK identities the server will +// attempt to validate. It will ignore the rest not to let cheap ClientHello +// messages cause too much work in session ticket decryption attempts. +const maxClientPSKIdentities = 5 + +type serverHandshakeStateTLS13 struct { + c *Conn + ctx context.Context + clientHello *clientHelloMsg + hello *serverHelloMsg + alpnNegotiationErr error + encryptedExtensions *encryptedExtensionsMsg + sentDummyCCS bool + usingPSK bool + suite *cipherSuiteTLS13 + cert *Certificate + sigAlg SignatureScheme + earlySecret []byte + sharedKey []byte + handshakeSecret []byte + masterSecret []byte + trafficSecret []byte // client_application_traffic_secret_0 + transcript hash.Hash + clientFinished []byte +} + +func (hs *serverHandshakeStateTLS13) handshake() error { + c := hs.c + + if needFIPS() { + return errors.New("tls: internal error: TLS 1.3 reached in FIPS mode") + } + + // For an overview of the TLS 1.3 handshake, see RFC 8446, Section 2. + if err := hs.processClientHello(); err != nil { + return err + } + if err := hs.checkForResumption(); err != nil { + return err + } + c.updateConnectionState() + if err := hs.pickCertificate(); err != nil { + return err + } + c.buffering = true + if err := hs.sendServerParameters(); err != nil { + return err + } + if err := hs.sendServerCertificate(); err != nil { + return err + } + if err := hs.sendServerFinished(); err != nil { + return err + } + // Note that at this point we could start sending application data without + // waiting for the client's second flight, but the application might not + // expect the lack of replay protection of the ClientHello parameters. + if _, err := c.flush(); err != nil { + return err + } + if err := hs.readClientCertificate(); err != nil { + return err + } + c.updateConnectionState() + if err := hs.readClientFinished(); err != nil { + return err + } + + atomic.StoreUint32(&c.handshakeStatus, 1) + c.updateConnectionState() + return nil +} + +func (hs *serverHandshakeStateTLS13) processClientHello() error { + c := hs.c + + hs.hello = new(serverHelloMsg) + hs.encryptedExtensions = new(encryptedExtensionsMsg) + + // TLS 1.3 froze the ServerHello.legacy_version field, and uses + // supported_versions instead. See RFC 8446, sections 4.1.3 and 4.2.1. + hs.hello.vers = VersionTLS12 + hs.hello.supportedVersion = c.vers + + if len(hs.clientHello.supportedVersions) == 0 { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: client used the legacy version field to negotiate TLS 1.3") + } + + // Abort if the client is doing a fallback and landing lower than what we + // support. See RFC 7507, which however does not specify the interaction + // with supported_versions. The only difference is that with + // supported_versions a client has a chance to attempt a [TLS 1.2, TLS 1.4] + // handshake in case TLS 1.3 is broken but 1.2 is not. Alas, in that case, + // it will have to drop the TLS_FALLBACK_SCSV protection if it falls back to + // TLS 1.2, because a TLS 1.3 server would abort here. The situation before + // supported_versions was not better because there was just no way to do a + // TLS 1.4 handshake without risking the server selecting TLS 1.3. + for _, id := range hs.clientHello.cipherSuites { + if id == TLS_FALLBACK_SCSV { + // Use c.vers instead of max(supported_versions) because an attacker + // could defeat this by adding an arbitrary high version otherwise. + if c.vers < c.config.maxSupportedVersion(roleServer) { + c.sendAlert(alertInappropriateFallback) + return errors.New("tls: client using inappropriate protocol fallback") + } + break + } + } + + if len(hs.clientHello.compressionMethods) != 1 || + hs.clientHello.compressionMethods[0] != compressionNone { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: TLS 1.3 client supports illegal compression methods") + } + + hs.hello.random = make([]byte, 32) + if _, err := io.ReadFull(c.config.rand(), hs.hello.random); err != nil { + c.sendAlert(alertInternalError) + return err + } + + if len(hs.clientHello.secureRenegotiation) != 0 { + c.sendAlert(alertHandshakeFailure) + return errors.New("tls: initial handshake had non-empty renegotiation extension") + } + + hs.hello.sessionId = hs.clientHello.sessionId + hs.hello.compressionMethod = compressionNone + + preferenceList := defaultCipherSuitesTLS13 + if !hasAESGCMHardwareSupport || !aesgcmPreferred(hs.clientHello.cipherSuites) { + preferenceList = defaultCipherSuitesTLS13NoAES + } + for _, suiteID := range preferenceList { + hs.suite = mutualCipherSuiteTLS13(hs.clientHello.cipherSuites, suiteID) + if hs.suite != nil { + break + } + } + if hs.suite == nil { + c.sendAlert(alertHandshakeFailure) + return errors.New("tls: no cipher suite supported by both client and server") + } + c.cipherSuite = hs.suite.id + hs.hello.cipherSuite = hs.suite.id + hs.transcript = hs.suite.hash.New() + + // Pick the ECDHE group in server preference order, but give priority to + // groups with a key share, to avoid a HelloRetryRequest round-trip. + var selectedGroup CurveID + var clientKeyShare *keyShare +GroupSelection: + for _, preferredGroup := range c.config.curvePreferences() { + for _, ks := range hs.clientHello.keyShares { + if ks.group == preferredGroup { + selectedGroup = ks.group + clientKeyShare = &ks + break GroupSelection + } + } + if selectedGroup != 0 { + continue + } + for _, group := range hs.clientHello.supportedCurves { + if group == preferredGroup { + selectedGroup = group + break + } + } + } + if selectedGroup == 0 { + c.sendAlert(alertHandshakeFailure) + return errors.New("tls: no ECDHE curve supported by both client and server") + } + if clientKeyShare == nil { + if err := hs.doHelloRetryRequest(selectedGroup); err != nil { + return err + } + clientKeyShare = &hs.clientHello.keyShares[0] + } + + if _, ok := curveForCurveID(selectedGroup); selectedGroup != X25519 && !ok { + c.sendAlert(alertInternalError) + return errors.New("tls: CurvePreferences includes unsupported curve") + } + params, err := generateECDHEParameters(c.config.rand(), selectedGroup) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + hs.hello.serverShare = keyShare{group: selectedGroup, data: params.PublicKey()} + hs.sharedKey = params.SharedKey(clientKeyShare.data) + if hs.sharedKey == nil { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: invalid client key share") + } + + c.serverName = hs.clientHello.serverName + + if c.extraConfig != nil && c.extraConfig.ReceivedExtensions != nil { + c.extraConfig.ReceivedExtensions(typeClientHello, hs.clientHello.additionalExtensions) + } + + selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols) + if err != nil { + hs.alpnNegotiationErr = err + } + hs.encryptedExtensions.alpnProtocol = selectedProto + c.clientProtocol = selectedProto + + return nil +} + +func (hs *serverHandshakeStateTLS13) checkForResumption() error { + c := hs.c + + if c.config.SessionTicketsDisabled { + return nil + } + + modeOK := false + for _, mode := range hs.clientHello.pskModes { + if mode == pskModeDHE { + modeOK = true + break + } + } + if !modeOK { + return nil + } + + if len(hs.clientHello.pskIdentities) != len(hs.clientHello.pskBinders) { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: invalid or missing PSK binders") + } + if len(hs.clientHello.pskIdentities) == 0 { + return nil + } + + for i, identity := range hs.clientHello.pskIdentities { + if i >= maxClientPSKIdentities { + break + } + + plaintext, _ := c.decryptTicket(identity.label) + if plaintext == nil { + continue + } + sessionState := new(sessionStateTLS13) + if ok := sessionState.unmarshal(plaintext); !ok { + continue + } + + if hs.clientHello.earlyData { + if sessionState.maxEarlyData == 0 { + c.sendAlert(alertUnsupportedExtension) + return errors.New("tls: client sent unexpected early data") + } + + if hs.alpnNegotiationErr == nil && sessionState.alpn == c.clientProtocol && + c.extraConfig != nil && c.extraConfig.MaxEarlyData > 0 && + c.extraConfig.Accept0RTT != nil && c.extraConfig.Accept0RTT(sessionState.appData) { + hs.encryptedExtensions.earlyData = true + c.used0RTT = true + } + } + + createdAt := time.Unix(int64(sessionState.createdAt), 0) + if c.config.time().Sub(createdAt) > maxSessionTicketLifetime { + continue + } + + // We don't check the obfuscated ticket age because it's affected by + // clock skew and it's only a freshness signal useful for shrinking the + // window for replay attacks, which don't affect us as we don't do 0-RTT. + + pskSuite := cipherSuiteTLS13ByID(sessionState.cipherSuite) + if pskSuite == nil || pskSuite.hash != hs.suite.hash { + continue + } + + // PSK connections don't re-establish client certificates, but carry + // them over in the session ticket. Ensure the presence of client certs + // in the ticket is consistent with the configured requirements. + sessionHasClientCerts := len(sessionState.certificate.Certificate) != 0 + needClientCerts := requiresClientCert(c.config.ClientAuth) + if needClientCerts && !sessionHasClientCerts { + continue + } + if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { + continue + } + + psk := hs.suite.expandLabel(sessionState.resumptionSecret, "resumption", + nil, hs.suite.hash.Size()) + hs.earlySecret = hs.suite.extract(psk, nil) + binderKey := hs.suite.deriveSecret(hs.earlySecret, resumptionBinderLabel, nil) + // Clone the transcript in case a HelloRetryRequest was recorded. + transcript := cloneHash(hs.transcript, hs.suite.hash) + if transcript == nil { + c.sendAlert(alertInternalError) + return errors.New("tls: internal error: failed to clone hash") + } + clientHelloBytes, err := hs.clientHello.marshalWithoutBinders() + if err != nil { + c.sendAlert(alertInternalError) + return err + } + transcript.Write(clientHelloBytes) + pskBinder := hs.suite.finishedHash(binderKey, transcript) + if !hmac.Equal(hs.clientHello.pskBinders[i], pskBinder) { + c.sendAlert(alertDecryptError) + return errors.New("tls: invalid PSK binder") + } + + c.didResume = true + if err := c.processCertsFromClient(sessionState.certificate); err != nil { + return err + } + + h := cloneHash(hs.transcript, hs.suite.hash) + clientHelloWithBindersBytes, err := hs.clientHello.marshal() + if err != nil { + c.sendAlert(alertInternalError) + return err + } + h.Write(clientHelloWithBindersBytes) + if hs.encryptedExtensions.earlyData { + clientEarlySecret := hs.suite.deriveSecret(hs.earlySecret, "c e traffic", h) + c.in.exportKey(Encryption0RTT, hs.suite, clientEarlySecret) + if err := c.config.writeKeyLog(keyLogLabelEarlyTraffic, hs.clientHello.random, clientEarlySecret); err != nil { + c.sendAlert(alertInternalError) + return err + } + } + + hs.hello.selectedIdentityPresent = true + hs.hello.selectedIdentity = uint16(i) + hs.usingPSK = true + return nil + } + + return nil +} + +// cloneHash uses the encoding.BinaryMarshaler and encoding.BinaryUnmarshaler +// interfaces implemented by standard library hashes to clone the state of in +// to a new instance of h. It returns nil if the operation fails. +func cloneHash(in hash.Hash, h crypto.Hash) hash.Hash { + // Recreate the interface to avoid importing encoding. + type binaryMarshaler interface { + MarshalBinary() (data []byte, err error) + UnmarshalBinary(data []byte) error + } + marshaler, ok := in.(binaryMarshaler) + if !ok { + return nil + } + state, err := marshaler.MarshalBinary() + if err != nil { + return nil + } + out := h.New() + unmarshaler, ok := out.(binaryMarshaler) + if !ok { + return nil + } + if err := unmarshaler.UnmarshalBinary(state); err != nil { + return nil + } + return out +} + +func (hs *serverHandshakeStateTLS13) pickCertificate() error { + c := hs.c + + // Only one of PSK and certificates are used at a time. + if hs.usingPSK { + return nil + } + + // signature_algorithms is required in TLS 1.3. See RFC 8446, Section 4.2.3. + if len(hs.clientHello.supportedSignatureAlgorithms) == 0 { + return c.sendAlert(alertMissingExtension) + } + + certificate, err := c.config.getCertificate(newClientHelloInfo(hs.ctx, c, hs.clientHello)) + if err != nil { + if err == errNoCertificates { + c.sendAlert(alertUnrecognizedName) + } else { + c.sendAlert(alertInternalError) + } + return err + } + hs.sigAlg, err = selectSignatureScheme(c.vers, certificate, hs.clientHello.supportedSignatureAlgorithms) + if err != nil { + // getCertificate returned a certificate that is unsupported or + // incompatible with the client's signature algorithms. + c.sendAlert(alertHandshakeFailure) + return err + } + hs.cert = certificate + + return nil +} + +// sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility +// with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. +func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error { + if hs.sentDummyCCS { + return nil + } + hs.sentDummyCCS = true + + return hs.c.writeChangeCipherRecord() +} + +func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) error { + c := hs.c + + // The first ClientHello gets double-hashed into the transcript upon a + // HelloRetryRequest. See RFC 8446, Section 4.4.1. + if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil { + return err + } + chHash := hs.transcript.Sum(nil) + hs.transcript.Reset() + hs.transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) + hs.transcript.Write(chHash) + + helloRetryRequest := &serverHelloMsg{ + vers: hs.hello.vers, + random: helloRetryRequestRandom, + sessionId: hs.hello.sessionId, + cipherSuite: hs.hello.cipherSuite, + compressionMethod: hs.hello.compressionMethod, + supportedVersion: hs.hello.supportedVersion, + selectedGroup: selectedGroup, + } + + if _, err := hs.c.writeHandshakeRecord(helloRetryRequest, hs.transcript); err != nil { + return err + } + + if err := hs.sendDummyChangeCipherSpec(); err != nil { + return err + } + + // clientHelloMsg is not included in the transcript. + msg, err := c.readHandshake(nil) + if err != nil { + return err + } + + clientHello, ok := msg.(*clientHelloMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(clientHello, msg) + } + + if len(clientHello.keyShares) != 1 || clientHello.keyShares[0].group != selectedGroup { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: client sent invalid key share in second ClientHello") + } + + if clientHello.earlyData { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: client indicated early data in second ClientHello") + } + + if illegalClientHelloChange(clientHello, hs.clientHello) { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: client illegally modified second ClientHello") + } + + if clientHello.earlyData { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: client offered 0-RTT data in second ClientHello") + } + + hs.clientHello = clientHello + return nil +} + +// illegalClientHelloChange reports whether the two ClientHello messages are +// different, with the exception of the changes allowed before and after a +// HelloRetryRequest. See RFC 8446, Section 4.1.2. +func illegalClientHelloChange(ch, ch1 *clientHelloMsg) bool { + if len(ch.supportedVersions) != len(ch1.supportedVersions) || + len(ch.cipherSuites) != len(ch1.cipherSuites) || + len(ch.supportedCurves) != len(ch1.supportedCurves) || + len(ch.supportedSignatureAlgorithms) != len(ch1.supportedSignatureAlgorithms) || + len(ch.supportedSignatureAlgorithmsCert) != len(ch1.supportedSignatureAlgorithmsCert) || + len(ch.alpnProtocols) != len(ch1.alpnProtocols) { + return true + } + for i := range ch.supportedVersions { + if ch.supportedVersions[i] != ch1.supportedVersions[i] { + return true + } + } + for i := range ch.cipherSuites { + if ch.cipherSuites[i] != ch1.cipherSuites[i] { + return true + } + } + for i := range ch.supportedCurves { + if ch.supportedCurves[i] != ch1.supportedCurves[i] { + return true + } + } + for i := range ch.supportedSignatureAlgorithms { + if ch.supportedSignatureAlgorithms[i] != ch1.supportedSignatureAlgorithms[i] { + return true + } + } + for i := range ch.supportedSignatureAlgorithmsCert { + if ch.supportedSignatureAlgorithmsCert[i] != ch1.supportedSignatureAlgorithmsCert[i] { + return true + } + } + for i := range ch.alpnProtocols { + if ch.alpnProtocols[i] != ch1.alpnProtocols[i] { + return true + } + } + return ch.vers != ch1.vers || + !bytes.Equal(ch.random, ch1.random) || + !bytes.Equal(ch.sessionId, ch1.sessionId) || + !bytes.Equal(ch.compressionMethods, ch1.compressionMethods) || + ch.serverName != ch1.serverName || + ch.ocspStapling != ch1.ocspStapling || + !bytes.Equal(ch.supportedPoints, ch1.supportedPoints) || + ch.ticketSupported != ch1.ticketSupported || + !bytes.Equal(ch.sessionTicket, ch1.sessionTicket) || + ch.secureRenegotiationSupported != ch1.secureRenegotiationSupported || + !bytes.Equal(ch.secureRenegotiation, ch1.secureRenegotiation) || + ch.scts != ch1.scts || + !bytes.Equal(ch.cookie, ch1.cookie) || + !bytes.Equal(ch.pskModes, ch1.pskModes) +} + +func (hs *serverHandshakeStateTLS13) sendServerParameters() error { + c := hs.c + + if err := transcriptMsg(hs.clientHello, hs.transcript); err != nil { + return err + } + if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil { + return err + } + + if err := hs.sendDummyChangeCipherSpec(); err != nil { + return err + } + + earlySecret := hs.earlySecret + if earlySecret == nil { + earlySecret = hs.suite.extract(nil, nil) + } + hs.handshakeSecret = hs.suite.extract(hs.sharedKey, + hs.suite.deriveSecret(earlySecret, "derived", nil)) + + clientSecret := hs.suite.deriveSecret(hs.handshakeSecret, + clientHandshakeTrafficLabel, hs.transcript) + c.in.exportKey(EncryptionHandshake, hs.suite, clientSecret) + c.in.setTrafficSecret(hs.suite, clientSecret) + serverSecret := hs.suite.deriveSecret(hs.handshakeSecret, + serverHandshakeTrafficLabel, hs.transcript) + c.out.exportKey(EncryptionHandshake, hs.suite, serverSecret) + c.out.setTrafficSecret(hs.suite, serverSecret) + + err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + err = c.config.writeKeyLog(keyLogLabelServerHandshake, hs.clientHello.random, serverSecret) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + + if hs.alpnNegotiationErr != nil { + c.sendAlert(alertNoApplicationProtocol) + return hs.alpnNegotiationErr + } + if hs.c.extraConfig != nil && hs.c.extraConfig.GetExtensions != nil { + hs.encryptedExtensions.additionalExtensions = hs.c.extraConfig.GetExtensions(typeEncryptedExtensions) + } + + if _, err := hs.c.writeHandshakeRecord(hs.encryptedExtensions, hs.transcript); err != nil { + return err + } + + return nil +} + +func (hs *serverHandshakeStateTLS13) requestClientCert() bool { + return hs.c.config.ClientAuth >= RequestClientCert && !hs.usingPSK +} + +func (hs *serverHandshakeStateTLS13) sendServerCertificate() error { + c := hs.c + + // Only one of PSK and certificates are used at a time. + if hs.usingPSK { + return nil + } + + if hs.requestClientCert() { + // Request a client certificate + certReq := new(certificateRequestMsgTLS13) + certReq.ocspStapling = true + certReq.scts = true + certReq.supportedSignatureAlgorithms = supportedSignatureAlgorithms() + if c.config.ClientCAs != nil { + certReq.certificateAuthorities = c.config.ClientCAs.Subjects() + } + + if _, err := hs.c.writeHandshakeRecord(certReq, hs.transcript); err != nil { + return err + } + } + + certMsg := new(certificateMsgTLS13) + + certMsg.certificate = *hs.cert + certMsg.scts = hs.clientHello.scts && len(hs.cert.SignedCertificateTimestamps) > 0 + certMsg.ocspStapling = hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 + + if _, err := hs.c.writeHandshakeRecord(certMsg, hs.transcript); err != nil { + return err + } + + certVerifyMsg := new(certificateVerifyMsg) + certVerifyMsg.hasSignatureAlgorithm = true + certVerifyMsg.signatureAlgorithm = hs.sigAlg + + sigType, sigHash, err := typeAndHashFromSignatureScheme(hs.sigAlg) + if err != nil { + return c.sendAlert(alertInternalError) + } + + signed := signedMessage(sigHash, serverSignatureContext, hs.transcript) + signOpts := crypto.SignerOpts(sigHash) + if sigType == signatureRSAPSS { + signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} + } + sig, err := hs.cert.PrivateKey.(crypto.Signer).Sign(c.config.rand(), signed, signOpts) + if err != nil { + public := hs.cert.PrivateKey.(crypto.Signer).Public() + if rsaKey, ok := public.(*rsa.PublicKey); ok && sigType == signatureRSAPSS && + rsaKey.N.BitLen()/8 < sigHash.Size()*2+2 { // key too small for RSA-PSS + c.sendAlert(alertHandshakeFailure) + } else { + c.sendAlert(alertInternalError) + } + return errors.New("tls: failed to sign handshake: " + err.Error()) + } + certVerifyMsg.signature = sig + + if _, err := hs.c.writeHandshakeRecord(certVerifyMsg, hs.transcript); err != nil { + return err + } + + return nil +} + +func (hs *serverHandshakeStateTLS13) sendServerFinished() error { + c := hs.c + + finished := &finishedMsg{ + verifyData: hs.suite.finishedHash(c.out.trafficSecret, hs.transcript), + } + + if _, err := hs.c.writeHandshakeRecord(finished, hs.transcript); err != nil { + return err + } + + // Derive secrets that take context through the server Finished. + + hs.masterSecret = hs.suite.extract(nil, + hs.suite.deriveSecret(hs.handshakeSecret, "derived", nil)) + + hs.trafficSecret = hs.suite.deriveSecret(hs.masterSecret, + clientApplicationTrafficLabel, hs.transcript) + serverSecret := hs.suite.deriveSecret(hs.masterSecret, + serverApplicationTrafficLabel, hs.transcript) + c.out.exportKey(EncryptionApplication, hs.suite, serverSecret) + c.out.setTrafficSecret(hs.suite, serverSecret) + + err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + err = c.config.writeKeyLog(keyLogLabelServerTraffic, hs.clientHello.random, serverSecret) + if err != nil { + c.sendAlert(alertInternalError) + return err + } + + c.ekm = hs.suite.exportKeyingMaterial(hs.masterSecret, hs.transcript) + + // If we did not request client certificates, at this point we can + // precompute the client finished and roll the transcript forward to send + // session tickets in our first flight. + if !hs.requestClientCert() { + if err := hs.sendSessionTickets(); err != nil { + return err + } + } + + return nil +} + +func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool { + if hs.c.config.SessionTicketsDisabled { + return false + } + + // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9. + for _, pskMode := range hs.clientHello.pskModes { + if pskMode == pskModeDHE { + return true + } + } + return false +} + +func (hs *serverHandshakeStateTLS13) sendSessionTickets() error { + c := hs.c + + hs.clientFinished = hs.suite.finishedHash(c.in.trafficSecret, hs.transcript) + finishedMsg := &finishedMsg{ + verifyData: hs.clientFinished, + } + if err := transcriptMsg(finishedMsg, hs.transcript); err != nil { + return err + } + + if !hs.shouldSendSessionTickets() { + return nil + } + + c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, + resumptionLabel, hs.transcript) + + // Don't send session tickets when the alternative record layer is set. + // Instead, save the resumption secret on the Conn. + // Session tickets can then be generated by calling Conn.GetSessionTicket(). + if hs.c.extraConfig != nil && hs.c.extraConfig.AlternativeRecordLayer != nil { + return nil + } + + m, err := hs.c.getSessionTicketMsg(nil) + if err != nil { + return err + } + + if _, err := c.writeHandshakeRecord(m, nil); err != nil { + return err + } + + return nil +} + +func (hs *serverHandshakeStateTLS13) readClientCertificate() error { + c := hs.c + + if !hs.requestClientCert() { + // Make sure the connection is still being verified whether or not + // the server requested a client certificate. + if c.config.VerifyConnection != nil { + if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { + c.sendAlert(alertBadCertificate) + return err + } + } + return nil + } + + // If we requested a client certificate, then the client must send a + // certificate message. If it's empty, no CertificateVerify is sent. + + msg, err := c.readHandshake(hs.transcript) + if err != nil { + return err + } + + certMsg, ok := msg.(*certificateMsgTLS13) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(certMsg, msg) + } + + if err := c.processCertsFromClient(certMsg.certificate); err != nil { + return err + } + + if c.config.VerifyConnection != nil { + if err := c.config.VerifyConnection(c.connectionStateLocked()); err != nil { + c.sendAlert(alertBadCertificate) + return err + } + } + + if len(certMsg.certificate.Certificate) != 0 { + // certificateVerifyMsg is included in the transcript, but not until + // after we verify the handshake signature, since the state before + // this message was sent is used. + msg, err = c.readHandshake(nil) + if err != nil { + return err + } + + certVerify, ok := msg.(*certificateVerifyMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(certVerify, msg) + } + + // See RFC 8446, Section 4.4.3. + if !isSupportedSignatureAlgorithm(certVerify.signatureAlgorithm, supportedSignatureAlgorithms()) { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: client certificate used with invalid signature algorithm") + } + sigType, sigHash, err := typeAndHashFromSignatureScheme(certVerify.signatureAlgorithm) + if err != nil { + return c.sendAlert(alertInternalError) + } + if sigType == signaturePKCS1v15 || sigHash == crypto.SHA1 { + c.sendAlert(alertIllegalParameter) + return errors.New("tls: client certificate used with invalid signature algorithm") + } + signed := signedMessage(sigHash, clientSignatureContext, hs.transcript) + if err := verifyHandshakeSignature(sigType, c.peerCertificates[0].PublicKey, + sigHash, signed, certVerify.signature); err != nil { + c.sendAlert(alertDecryptError) + return errors.New("tls: invalid signature by the client certificate: " + err.Error()) + } + + if err := transcriptMsg(certVerify, hs.transcript); err != nil { + return err + } + } + + // If we waited until the client certificates to send session tickets, we + // are ready to do it now. + if err := hs.sendSessionTickets(); err != nil { + return err + } + + return nil +} + +func (hs *serverHandshakeStateTLS13) readClientFinished() error { + c := hs.c + + // finishedMsg is not included in the transcript. + msg, err := c.readHandshake(nil) + if err != nil { + return err + } + + finished, ok := msg.(*finishedMsg) + if !ok { + c.sendAlert(alertUnexpectedMessage) + return unexpectedMessageError(finished, msg) + } + + if !hmac.Equal(hs.clientFinished, finished.verifyData) { + c.sendAlert(alertDecryptError) + return errors.New("tls: invalid client finished hash") + } + + c.in.exportKey(EncryptionApplication, hs.suite, hs.trafficSecret) + c.in.setTrafficSecret(hs.suite, hs.trafficSecret) + + return nil +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/key_agreement.go b/vendor/github.com/quic-go/qtls-go1-19/key_agreement.go new file mode 100644 index 000000000..453a8dcf0 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/key_agreement.go @@ -0,0 +1,357 @@ +// Copyright 2010 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "crypto" + "crypto/md5" + "crypto/rsa" + "crypto/sha1" + "crypto/x509" + "errors" + "fmt" + "io" +) + +// a keyAgreement implements the client and server side of a TLS key agreement +// protocol by generating and processing key exchange messages. +type keyAgreement interface { + // On the server side, the first two methods are called in order. + + // In the case that the key agreement protocol doesn't use a + // ServerKeyExchange message, generateServerKeyExchange can return nil, + // nil. + generateServerKeyExchange(*config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error) + processClientKeyExchange(*config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error) + + // On the client side, the next two methods are called in order. + + // This method may not be called if the server doesn't send a + // ServerKeyExchange message. + processServerKeyExchange(*config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error + generateClientKeyExchange(*config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) +} + +var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message") +var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message") + +// rsaKeyAgreement implements the standard TLS key agreement where the client +// encrypts the pre-master secret to the server's public key. +type rsaKeyAgreement struct{} + +func (ka rsaKeyAgreement) generateServerKeyExchange(config *config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) { + return nil, nil +} + +func (ka rsaKeyAgreement) processClientKeyExchange(config *config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) { + if len(ckx.ciphertext) < 2 { + return nil, errClientKeyExchange + } + ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1]) + if ciphertextLen != len(ckx.ciphertext)-2 { + return nil, errClientKeyExchange + } + ciphertext := ckx.ciphertext[2:] + + priv, ok := cert.PrivateKey.(crypto.Decrypter) + if !ok { + return nil, errors.New("tls: certificate private key does not implement crypto.Decrypter") + } + // Perform constant time RSA PKCS #1 v1.5 decryption + preMasterSecret, err := priv.Decrypt(config.rand(), ciphertext, &rsa.PKCS1v15DecryptOptions{SessionKeyLen: 48}) + if err != nil { + return nil, err + } + // We don't check the version number in the premaster secret. For one, + // by checking it, we would leak information about the validity of the + // encrypted pre-master secret. Secondly, it provides only a small + // benefit against a downgrade attack and some implementations send the + // wrong version anyway. See the discussion at the end of section + // 7.4.7.1 of RFC 4346. + return preMasterSecret, nil +} + +func (ka rsaKeyAgreement) processServerKeyExchange(config *config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { + return errors.New("tls: unexpected ServerKeyExchange") +} + +func (ka rsaKeyAgreement) generateClientKeyExchange(config *config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { + preMasterSecret := make([]byte, 48) + preMasterSecret[0] = byte(clientHello.vers >> 8) + preMasterSecret[1] = byte(clientHello.vers) + _, err := io.ReadFull(config.rand(), preMasterSecret[2:]) + if err != nil { + return nil, nil, err + } + + rsaKey, ok := cert.PublicKey.(*rsa.PublicKey) + if !ok { + return nil, nil, errors.New("tls: server certificate contains incorrect key type for selected ciphersuite") + } + encrypted, err := rsa.EncryptPKCS1v15(config.rand(), rsaKey, preMasterSecret) + if err != nil { + return nil, nil, err + } + ckx := new(clientKeyExchangeMsg) + ckx.ciphertext = make([]byte, len(encrypted)+2) + ckx.ciphertext[0] = byte(len(encrypted) >> 8) + ckx.ciphertext[1] = byte(len(encrypted)) + copy(ckx.ciphertext[2:], encrypted) + return preMasterSecret, ckx, nil +} + +// sha1Hash calculates a SHA1 hash over the given byte slices. +func sha1Hash(slices [][]byte) []byte { + hsha1 := sha1.New() + for _, slice := range slices { + hsha1.Write(slice) + } + return hsha1.Sum(nil) +} + +// md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the +// concatenation of an MD5 and SHA1 hash. +func md5SHA1Hash(slices [][]byte) []byte { + md5sha1 := make([]byte, md5.Size+sha1.Size) + hmd5 := md5.New() + for _, slice := range slices { + hmd5.Write(slice) + } + copy(md5sha1, hmd5.Sum(nil)) + copy(md5sha1[md5.Size:], sha1Hash(slices)) + return md5sha1 +} + +// hashForServerKeyExchange hashes the given slices and returns their digest +// using the given hash function (for >= TLS 1.2) or using a default based on +// the sigType (for earlier TLS versions). For Ed25519 signatures, which don't +// do pre-hashing, it returns the concatenation of the slices. +func hashForServerKeyExchange(sigType uint8, hashFunc crypto.Hash, version uint16, slices ...[]byte) []byte { + if sigType == signatureEd25519 { + var signed []byte + for _, slice := range slices { + signed = append(signed, slice...) + } + return signed + } + if version >= VersionTLS12 { + h := hashFunc.New() + for _, slice := range slices { + h.Write(slice) + } + digest := h.Sum(nil) + return digest + } + if sigType == signatureECDSA { + return sha1Hash(slices) + } + return md5SHA1Hash(slices) +} + +// ecdheKeyAgreement implements a TLS key agreement where the server +// generates an ephemeral EC public/private key pair and signs it. The +// pre-master secret is then calculated using ECDH. The signature may +// be ECDSA, Ed25519 or RSA. +type ecdheKeyAgreement struct { + version uint16 + isRSA bool + params ecdheParameters + + // ckx and preMasterSecret are generated in processServerKeyExchange + // and returned in generateClientKeyExchange. + ckx *clientKeyExchangeMsg + preMasterSecret []byte +} + +func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) { + var curveID CurveID + for _, c := range clientHello.supportedCurves { + if config.supportsCurve(c) { + curveID = c + break + } + } + + if curveID == 0 { + return nil, errors.New("tls: no supported elliptic curves offered") + } + if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { + return nil, errors.New("tls: CurvePreferences includes unsupported curve") + } + + params, err := generateECDHEParameters(config.rand(), curveID) + if err != nil { + return nil, err + } + ka.params = params + + // See RFC 4492, Section 5.4. + ecdhePublic := params.PublicKey() + serverECDHEParams := make([]byte, 1+2+1+len(ecdhePublic)) + serverECDHEParams[0] = 3 // named curve + serverECDHEParams[1] = byte(curveID >> 8) + serverECDHEParams[2] = byte(curveID) + serverECDHEParams[3] = byte(len(ecdhePublic)) + copy(serverECDHEParams[4:], ecdhePublic) + + priv, ok := cert.PrivateKey.(crypto.Signer) + if !ok { + return nil, fmt.Errorf("tls: certificate private key of type %T does not implement crypto.Signer", cert.PrivateKey) + } + + var signatureAlgorithm SignatureScheme + var sigType uint8 + var sigHash crypto.Hash + if ka.version >= VersionTLS12 { + signatureAlgorithm, err = selectSignatureScheme(ka.version, cert, clientHello.supportedSignatureAlgorithms) + if err != nil { + return nil, err + } + sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm) + if err != nil { + return nil, err + } + } else { + sigType, sigHash, err = legacyTypeAndHashFromPublicKey(priv.Public()) + if err != nil { + return nil, err + } + } + if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA { + return nil, errors.New("tls: certificate cannot be used with the selected cipher suite") + } + + signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, hello.random, serverECDHEParams) + + signOpts := crypto.SignerOpts(sigHash) + if sigType == signatureRSAPSS { + signOpts = &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: sigHash} + } + sig, err := priv.Sign(config.rand(), signed, signOpts) + if err != nil { + return nil, errors.New("tls: failed to sign ECDHE parameters: " + err.Error()) + } + + skx := new(serverKeyExchangeMsg) + sigAndHashLen := 0 + if ka.version >= VersionTLS12 { + sigAndHashLen = 2 + } + skx.key = make([]byte, len(serverECDHEParams)+sigAndHashLen+2+len(sig)) + copy(skx.key, serverECDHEParams) + k := skx.key[len(serverECDHEParams):] + if ka.version >= VersionTLS12 { + k[0] = byte(signatureAlgorithm >> 8) + k[1] = byte(signatureAlgorithm) + k = k[2:] + } + k[0] = byte(len(sig) >> 8) + k[1] = byte(len(sig)) + copy(k[2:], sig) + + return skx, nil +} + +func (ka *ecdheKeyAgreement) processClientKeyExchange(config *config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) { + if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 { + return nil, errClientKeyExchange + } + + preMasterSecret := ka.params.SharedKey(ckx.ciphertext[1:]) + if preMasterSecret == nil { + return nil, errClientKeyExchange + } + + return preMasterSecret, nil +} + +func (ka *ecdheKeyAgreement) processServerKeyExchange(config *config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { + if len(skx.key) < 4 { + return errServerKeyExchange + } + if skx.key[0] != 3 { // named curve + return errors.New("tls: server selected unsupported curve") + } + curveID := CurveID(skx.key[1])<<8 | CurveID(skx.key[2]) + + publicLen := int(skx.key[3]) + if publicLen+4 > len(skx.key) { + return errServerKeyExchange + } + serverECDHEParams := skx.key[:4+publicLen] + publicKey := serverECDHEParams[4:] + + sig := skx.key[4+publicLen:] + if len(sig) < 2 { + return errServerKeyExchange + } + + if _, ok := curveForCurveID(curveID); curveID != X25519 && !ok { + return errors.New("tls: server selected unsupported curve") + } + + params, err := generateECDHEParameters(config.rand(), curveID) + if err != nil { + return err + } + ka.params = params + + ka.preMasterSecret = params.SharedKey(publicKey) + if ka.preMasterSecret == nil { + return errServerKeyExchange + } + + ourPublicKey := params.PublicKey() + ka.ckx = new(clientKeyExchangeMsg) + ka.ckx.ciphertext = make([]byte, 1+len(ourPublicKey)) + ka.ckx.ciphertext[0] = byte(len(ourPublicKey)) + copy(ka.ckx.ciphertext[1:], ourPublicKey) + + var sigType uint8 + var sigHash crypto.Hash + if ka.version >= VersionTLS12 { + signatureAlgorithm := SignatureScheme(sig[0])<<8 | SignatureScheme(sig[1]) + sig = sig[2:] + if len(sig) < 2 { + return errServerKeyExchange + } + + if !isSupportedSignatureAlgorithm(signatureAlgorithm, clientHello.supportedSignatureAlgorithms) { + return errors.New("tls: certificate used with invalid signature algorithm") + } + sigType, sigHash, err = typeAndHashFromSignatureScheme(signatureAlgorithm) + if err != nil { + return err + } + } else { + sigType, sigHash, err = legacyTypeAndHashFromPublicKey(cert.PublicKey) + if err != nil { + return err + } + } + if (sigType == signaturePKCS1v15 || sigType == signatureRSAPSS) != ka.isRSA { + return errServerKeyExchange + } + + sigLen := int(sig[0])<<8 | int(sig[1]) + if sigLen+2 != len(sig) { + return errServerKeyExchange + } + sig = sig[2:] + + signed := hashForServerKeyExchange(sigType, sigHash, ka.version, clientHello.random, serverHello.random, serverECDHEParams) + if err := verifyHandshakeSignature(sigType, cert.PublicKey, sigHash, signed, sig); err != nil { + return errors.New("tls: invalid signature by the server certificate: " + err.Error()) + } + return nil +} + +func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { + if ka.ckx == nil { + return nil, nil, errors.New("tls: missing ServerKeyExchange message") + } + + return ka.preMasterSecret, ka.ckx, nil +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/key_schedule.go b/vendor/github.com/quic-go/qtls-go1-19/key_schedule.go new file mode 100644 index 000000000..708bdc7c3 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/key_schedule.go @@ -0,0 +1,216 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "crypto/elliptic" + "crypto/hmac" + "errors" + "fmt" + "hash" + "io" + "math/big" + + "golang.org/x/crypto/cryptobyte" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/hkdf" +) + +// This file contains the functions necessary to compute the TLS 1.3 key +// schedule. See RFC 8446, Section 7. + +const ( + resumptionBinderLabel = "res binder" + clientHandshakeTrafficLabel = "c hs traffic" + serverHandshakeTrafficLabel = "s hs traffic" + clientApplicationTrafficLabel = "c ap traffic" + serverApplicationTrafficLabel = "s ap traffic" + exporterLabel = "exp master" + resumptionLabel = "res master" + trafficUpdateLabel = "traffic upd" +) + +// expandLabel implements HKDF-Expand-Label from RFC 8446, Section 7.1. +func (c *cipherSuiteTLS13) expandLabel(secret []byte, label string, context []byte, length int) []byte { + var hkdfLabel cryptobyte.Builder + hkdfLabel.AddUint16(uint16(length)) + hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes([]byte("tls13 ")) + b.AddBytes([]byte(label)) + }) + hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(context) + }) + hkdfLabelBytes, err := hkdfLabel.Bytes() + if err != nil { + // Rather than calling BytesOrPanic, we explicitly handle this error, in + // order to provide a reasonable error message. It should be basically + // impossible for this to panic, and routing errors back through the + // tree rooted in this function is quite painful. The labels are fixed + // size, and the context is either a fixed-length computed hash, or + // parsed from a field which has the same length limitation. As such, an + // error here is likely to only be caused during development. + // + // NOTE: another reasonable approach here might be to return a + // randomized slice if we encounter an error, which would break the + // connection, but avoid panicking. This would perhaps be safer but + // significantly more confusing to users. + panic(fmt.Errorf("failed to construct HKDF label: %s", err)) + } + out := make([]byte, length) + n, err := hkdf.Expand(c.hash.New, secret, hkdfLabelBytes).Read(out) + if err != nil || n != length { + panic("tls: HKDF-Expand-Label invocation failed unexpectedly") + } + return out +} + +// deriveSecret implements Derive-Secret from RFC 8446, Section 7.1. +func (c *cipherSuiteTLS13) deriveSecret(secret []byte, label string, transcript hash.Hash) []byte { + if transcript == nil { + transcript = c.hash.New() + } + return c.expandLabel(secret, label, transcript.Sum(nil), c.hash.Size()) +} + +// extract implements HKDF-Extract with the cipher suite hash. +func (c *cipherSuiteTLS13) extract(newSecret, currentSecret []byte) []byte { + if newSecret == nil { + newSecret = make([]byte, c.hash.Size()) + } + return hkdf.Extract(c.hash.New, newSecret, currentSecret) +} + +// nextTrafficSecret generates the next traffic secret, given the current one, +// according to RFC 8446, Section 7.2. +func (c *cipherSuiteTLS13) nextTrafficSecret(trafficSecret []byte) []byte { + return c.expandLabel(trafficSecret, trafficUpdateLabel, nil, c.hash.Size()) +} + +// trafficKey generates traffic keys according to RFC 8446, Section 7.3. +func (c *cipherSuiteTLS13) trafficKey(trafficSecret []byte) (key, iv []byte) { + key = c.expandLabel(trafficSecret, "key", nil, c.keyLen) + iv = c.expandLabel(trafficSecret, "iv", nil, aeadNonceLength) + return +} + +// finishedHash generates the Finished verify_data or PskBinderEntry according +// to RFC 8446, Section 4.4.4. See sections 4.4 and 4.2.11.2 for the baseKey +// selection. +func (c *cipherSuiteTLS13) finishedHash(baseKey []byte, transcript hash.Hash) []byte { + finishedKey := c.expandLabel(baseKey, "finished", nil, c.hash.Size()) + verifyData := hmac.New(c.hash.New, finishedKey) + verifyData.Write(transcript.Sum(nil)) + return verifyData.Sum(nil) +} + +// exportKeyingMaterial implements RFC5705 exporters for TLS 1.3 according to +// RFC 8446, Section 7.5. +func (c *cipherSuiteTLS13) exportKeyingMaterial(masterSecret []byte, transcript hash.Hash) func(string, []byte, int) ([]byte, error) { + expMasterSecret := c.deriveSecret(masterSecret, exporterLabel, transcript) + return func(label string, context []byte, length int) ([]byte, error) { + secret := c.deriveSecret(expMasterSecret, label, nil) + h := c.hash.New() + h.Write(context) + return c.expandLabel(secret, "exporter", h.Sum(nil), length), nil + } +} + +// ecdheParameters implements Diffie-Hellman with either NIST curves or X25519, +// according to RFC 8446, Section 4.2.8.2. +type ecdheParameters interface { + CurveID() CurveID + PublicKey() []byte + SharedKey(peerPublicKey []byte) []byte +} + +func generateECDHEParameters(rand io.Reader, curveID CurveID) (ecdheParameters, error) { + if curveID == X25519 { + privateKey := make([]byte, curve25519.ScalarSize) + if _, err := io.ReadFull(rand, privateKey); err != nil { + return nil, err + } + publicKey, err := curve25519.X25519(privateKey, curve25519.Basepoint) + if err != nil { + return nil, err + } + return &x25519Parameters{privateKey: privateKey, publicKey: publicKey}, nil + } + + curve, ok := curveForCurveID(curveID) + if !ok { + return nil, errors.New("tls: internal error: unsupported curve") + } + + p := &nistParameters{curveID: curveID} + var err error + p.privateKey, p.x, p.y, err = elliptic.GenerateKey(curve, rand) + if err != nil { + return nil, err + } + return p, nil +} + +func curveForCurveID(id CurveID) (elliptic.Curve, bool) { + switch id { + case CurveP256: + return elliptic.P256(), true + case CurveP384: + return elliptic.P384(), true + case CurveP521: + return elliptic.P521(), true + default: + return nil, false + } +} + +type nistParameters struct { + privateKey []byte + x, y *big.Int // public key + curveID CurveID +} + +func (p *nistParameters) CurveID() CurveID { + return p.curveID +} + +func (p *nistParameters) PublicKey() []byte { + curve, _ := curveForCurveID(p.curveID) + return elliptic.Marshal(curve, p.x, p.y) +} + +func (p *nistParameters) SharedKey(peerPublicKey []byte) []byte { + curve, _ := curveForCurveID(p.curveID) + // Unmarshal also checks whether the given point is on the curve. + x, y := elliptic.Unmarshal(curve, peerPublicKey) + if x == nil { + return nil + } + + xShared, _ := curve.ScalarMult(x, y, p.privateKey) + sharedKey := make([]byte, (curve.Params().BitSize+7)/8) + return xShared.FillBytes(sharedKey) +} + +type x25519Parameters struct { + privateKey []byte + publicKey []byte +} + +func (p *x25519Parameters) CurveID() CurveID { + return X25519 +} + +func (p *x25519Parameters) PublicKey() []byte { + return p.publicKey[:] +} + +func (p *x25519Parameters) SharedKey(peerPublicKey []byte) []byte { + sharedKey, err := curve25519.X25519(p.privateKey, peerPublicKey) + if err != nil { + return nil + } + return sharedKey +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/notboring.go b/vendor/github.com/quic-go/qtls-go1-19/notboring.go new file mode 100644 index 000000000..f292e4f02 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/notboring.go @@ -0,0 +1,18 @@ +// Copyright 2022 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +func needFIPS() bool { return false } + +func supportedSignatureAlgorithms() []SignatureScheme { + return defaultSupportedSignatureAlgorithms +} + +func fipsMinVersion(c *config) uint16 { panic("fipsMinVersion") } +func fipsMaxVersion(c *config) uint16 { panic("fipsMaxVersion") } +func fipsCurvePreferences(c *config) []CurveID { panic("fipsCurvePreferences") } +func fipsCipherSuites(c *config) []uint16 { panic("fipsCipherSuites") } + +var fipsSupportedSignatureAlgorithms []SignatureScheme diff --git a/vendor/github.com/quic-go/qtls-go1-19/prf.go b/vendor/github.com/quic-go/qtls-go1-19/prf.go new file mode 100644 index 000000000..9eb0221a0 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/prf.go @@ -0,0 +1,283 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "crypto" + "crypto/hmac" + "crypto/md5" + "crypto/sha1" + "crypto/sha256" + "crypto/sha512" + "errors" + "fmt" + "hash" +) + +// Split a premaster secret in two as specified in RFC 4346, Section 5. +func splitPreMasterSecret(secret []byte) (s1, s2 []byte) { + s1 = secret[0 : (len(secret)+1)/2] + s2 = secret[len(secret)/2:] + return +} + +// pHash implements the P_hash function, as defined in RFC 4346, Section 5. +func pHash(result, secret, seed []byte, hash func() hash.Hash) { + h := hmac.New(hash, secret) + h.Write(seed) + a := h.Sum(nil) + + j := 0 + for j < len(result) { + h.Reset() + h.Write(a) + h.Write(seed) + b := h.Sum(nil) + copy(result[j:], b) + j += len(b) + + h.Reset() + h.Write(a) + a = h.Sum(nil) + } +} + +// prf10 implements the TLS 1.0 pseudo-random function, as defined in RFC 2246, Section 5. +func prf10(result, secret, label, seed []byte) { + hashSHA1 := sha1.New + hashMD5 := md5.New + + labelAndSeed := make([]byte, len(label)+len(seed)) + copy(labelAndSeed, label) + copy(labelAndSeed[len(label):], seed) + + s1, s2 := splitPreMasterSecret(secret) + pHash(result, s1, labelAndSeed, hashMD5) + result2 := make([]byte, len(result)) + pHash(result2, s2, labelAndSeed, hashSHA1) + + for i, b := range result2 { + result[i] ^= b + } +} + +// prf12 implements the TLS 1.2 pseudo-random function, as defined in RFC 5246, Section 5. +func prf12(hashFunc func() hash.Hash) func(result, secret, label, seed []byte) { + return func(result, secret, label, seed []byte) { + labelAndSeed := make([]byte, len(label)+len(seed)) + copy(labelAndSeed, label) + copy(labelAndSeed[len(label):], seed) + + pHash(result, secret, labelAndSeed, hashFunc) + } +} + +const ( + masterSecretLength = 48 // Length of a master secret in TLS 1.1. + finishedVerifyLength = 12 // Length of verify_data in a Finished message. +) + +var masterSecretLabel = []byte("master secret") +var keyExpansionLabel = []byte("key expansion") +var clientFinishedLabel = []byte("client finished") +var serverFinishedLabel = []byte("server finished") + +func prfAndHashForVersion(version uint16, suite *cipherSuite) (func(result, secret, label, seed []byte), crypto.Hash) { + switch version { + case VersionTLS10, VersionTLS11: + return prf10, crypto.Hash(0) + case VersionTLS12: + if suite.flags&suiteSHA384 != 0 { + return prf12(sha512.New384), crypto.SHA384 + } + return prf12(sha256.New), crypto.SHA256 + default: + panic("unknown version") + } +} + +func prfForVersion(version uint16, suite *cipherSuite) func(result, secret, label, seed []byte) { + prf, _ := prfAndHashForVersion(version, suite) + return prf +} + +// masterFromPreMasterSecret generates the master secret from the pre-master +// secret. See RFC 5246, Section 8.1. +func masterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret, clientRandom, serverRandom []byte) []byte { + seed := make([]byte, 0, len(clientRandom)+len(serverRandom)) + seed = append(seed, clientRandom...) + seed = append(seed, serverRandom...) + + masterSecret := make([]byte, masterSecretLength) + prfForVersion(version, suite)(masterSecret, preMasterSecret, masterSecretLabel, seed) + return masterSecret +} + +// keysFromMasterSecret generates the connection keys from the master +// secret, given the lengths of the MAC key, cipher key and IV, as defined in +// RFC 2246, Section 6.3. +func keysFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte, macLen, keyLen, ivLen int) (clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV []byte) { + seed := make([]byte, 0, len(serverRandom)+len(clientRandom)) + seed = append(seed, serverRandom...) + seed = append(seed, clientRandom...) + + n := 2*macLen + 2*keyLen + 2*ivLen + keyMaterial := make([]byte, n) + prfForVersion(version, suite)(keyMaterial, masterSecret, keyExpansionLabel, seed) + clientMAC = keyMaterial[:macLen] + keyMaterial = keyMaterial[macLen:] + serverMAC = keyMaterial[:macLen] + keyMaterial = keyMaterial[macLen:] + clientKey = keyMaterial[:keyLen] + keyMaterial = keyMaterial[keyLen:] + serverKey = keyMaterial[:keyLen] + keyMaterial = keyMaterial[keyLen:] + clientIV = keyMaterial[:ivLen] + keyMaterial = keyMaterial[ivLen:] + serverIV = keyMaterial[:ivLen] + return +} + +func newFinishedHash(version uint16, cipherSuite *cipherSuite) finishedHash { + var buffer []byte + if version >= VersionTLS12 { + buffer = []byte{} + } + + prf, hash := prfAndHashForVersion(version, cipherSuite) + if hash != 0 { + return finishedHash{hash.New(), hash.New(), nil, nil, buffer, version, prf} + } + + return finishedHash{sha1.New(), sha1.New(), md5.New(), md5.New(), buffer, version, prf} +} + +// A finishedHash calculates the hash of a set of handshake messages suitable +// for including in a Finished message. +type finishedHash struct { + client hash.Hash + server hash.Hash + + // Prior to TLS 1.2, an additional MD5 hash is required. + clientMD5 hash.Hash + serverMD5 hash.Hash + + // In TLS 1.2, a full buffer is sadly required. + buffer []byte + + version uint16 + prf func(result, secret, label, seed []byte) +} + +func (h *finishedHash) Write(msg []byte) (n int, err error) { + h.client.Write(msg) + h.server.Write(msg) + + if h.version < VersionTLS12 { + h.clientMD5.Write(msg) + h.serverMD5.Write(msg) + } + + if h.buffer != nil { + h.buffer = append(h.buffer, msg...) + } + + return len(msg), nil +} + +func (h finishedHash) Sum() []byte { + if h.version >= VersionTLS12 { + return h.client.Sum(nil) + } + + out := make([]byte, 0, md5.Size+sha1.Size) + out = h.clientMD5.Sum(out) + return h.client.Sum(out) +} + +// clientSum returns the contents of the verify_data member of a client's +// Finished message. +func (h finishedHash) clientSum(masterSecret []byte) []byte { + out := make([]byte, finishedVerifyLength) + h.prf(out, masterSecret, clientFinishedLabel, h.Sum()) + return out +} + +// serverSum returns the contents of the verify_data member of a server's +// Finished message. +func (h finishedHash) serverSum(masterSecret []byte) []byte { + out := make([]byte, finishedVerifyLength) + h.prf(out, masterSecret, serverFinishedLabel, h.Sum()) + return out +} + +// hashForClientCertificate returns the handshake messages so far, pre-hashed if +// necessary, suitable for signing by a TLS client certificate. +func (h finishedHash) hashForClientCertificate(sigType uint8, hashAlg crypto.Hash, masterSecret []byte) []byte { + if (h.version >= VersionTLS12 || sigType == signatureEd25519) && h.buffer == nil { + panic("tls: handshake hash for a client certificate requested after discarding the handshake buffer") + } + + if sigType == signatureEd25519 { + return h.buffer + } + + if h.version >= VersionTLS12 { + hash := hashAlg.New() + hash.Write(h.buffer) + return hash.Sum(nil) + } + + if sigType == signatureECDSA { + return h.server.Sum(nil) + } + + return h.Sum() +} + +// discardHandshakeBuffer is called when there is no more need to +// buffer the entirety of the handshake messages. +func (h *finishedHash) discardHandshakeBuffer() { + h.buffer = nil +} + +// noExportedKeyingMaterial is used as a value of +// ConnectionState.ekm when renegotiation is enabled and thus +// we wish to fail all key-material export requests. +func noExportedKeyingMaterial(label string, context []byte, length int) ([]byte, error) { + return nil, errors.New("crypto/tls: ExportKeyingMaterial is unavailable when renegotiation is enabled") +} + +// ekmFromMasterSecret generates exported keying material as defined in RFC 5705. +func ekmFromMasterSecret(version uint16, suite *cipherSuite, masterSecret, clientRandom, serverRandom []byte) func(string, []byte, int) ([]byte, error) { + return func(label string, context []byte, length int) ([]byte, error) { + switch label { + case "client finished", "server finished", "master secret", "key expansion": + // These values are reserved and may not be used. + return nil, fmt.Errorf("crypto/tls: reserved ExportKeyingMaterial label: %s", label) + } + + seedLen := len(serverRandom) + len(clientRandom) + if context != nil { + seedLen += 2 + len(context) + } + seed := make([]byte, 0, seedLen) + + seed = append(seed, clientRandom...) + seed = append(seed, serverRandom...) + + if context != nil { + if len(context) >= 1<<16 { + return nil, fmt.Errorf("crypto/tls: ExportKeyingMaterial context too long") + } + seed = append(seed, byte(len(context)>>8), byte(len(context))) + seed = append(seed, context...) + } + + keyMaterial := make([]byte, length) + prfForVersion(version, suite)(keyMaterial, masterSecret, []byte(label), seed) + return keyMaterial, nil + } +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/ticket.go b/vendor/github.com/quic-go/qtls-go1-19/ticket.go new file mode 100644 index 000000000..fe1c7a884 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/ticket.go @@ -0,0 +1,277 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package qtls + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/hmac" + "crypto/sha256" + "crypto/subtle" + "encoding/binary" + "errors" + "io" + "time" + + "golang.org/x/crypto/cryptobyte" +) + +// sessionState contains the information that is serialized into a session +// ticket in order to later resume a connection. +type sessionState struct { + vers uint16 + cipherSuite uint16 + createdAt uint64 + masterSecret []byte // opaque master_secret<1..2^16-1>; + // struct { opaque certificate<1..2^24-1> } Certificate; + certificates [][]byte // Certificate certificate_list<0..2^24-1>; + + // usedOldKey is true if the ticket from which this session came from + // was encrypted with an older key and thus should be refreshed. + usedOldKey bool +} + +func (m *sessionState) marshal() ([]byte, error) { + var b cryptobyte.Builder + b.AddUint16(m.vers) + b.AddUint16(m.cipherSuite) + addUint64(&b, m.createdAt) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(m.masterSecret) + }) + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + for _, cert := range m.certificates { + b.AddUint24LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(cert) + }) + } + }) + return b.Bytes() +} + +func (m *sessionState) unmarshal(data []byte) bool { + *m = sessionState{usedOldKey: m.usedOldKey} + s := cryptobyte.String(data) + if ok := s.ReadUint16(&m.vers) && + s.ReadUint16(&m.cipherSuite) && + readUint64(&s, &m.createdAt) && + readUint16LengthPrefixed(&s, &m.masterSecret) && + len(m.masterSecret) != 0; !ok { + return false + } + var certList cryptobyte.String + if !s.ReadUint24LengthPrefixed(&certList) { + return false + } + for !certList.Empty() { + var cert []byte + if !readUint24LengthPrefixed(&certList, &cert) { + return false + } + m.certificates = append(m.certificates, cert) + } + return s.Empty() +} + +// sessionStateTLS13 is the content of a TLS 1.3 session ticket. Its first +// version (revision = 0) doesn't carry any of the information needed for 0-RTT +// validation and the nonce is always empty. +// version (revision = 1) carries the max_early_data_size sent in the ticket. +// version (revision = 2) carries the ALPN sent in the ticket. +type sessionStateTLS13 struct { + // uint8 version = 0x0304; + // uint8 revision = 2; + cipherSuite uint16 + createdAt uint64 + resumptionSecret []byte // opaque resumption_master_secret<1..2^8-1>; + certificate Certificate // CertificateEntry certificate_list<0..2^24-1>; + maxEarlyData uint32 + alpn string + + appData []byte +} + +func (m *sessionStateTLS13) marshal() ([]byte, error) { + var b cryptobyte.Builder + b.AddUint16(VersionTLS13) + b.AddUint8(2) // revision + b.AddUint16(m.cipherSuite) + addUint64(&b, m.createdAt) + b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(m.resumptionSecret) + }) + marshalCertificate(&b, m.certificate) + b.AddUint32(m.maxEarlyData) + b.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes([]byte(m.alpn)) + }) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(m.appData) + }) + return b.Bytes() +} + +func (m *sessionStateTLS13) unmarshal(data []byte) bool { + *m = sessionStateTLS13{} + s := cryptobyte.String(data) + var version uint16 + var revision uint8 + var alpn []byte + ret := s.ReadUint16(&version) && + version == VersionTLS13 && + s.ReadUint8(&revision) && + revision == 2 && + s.ReadUint16(&m.cipherSuite) && + readUint64(&s, &m.createdAt) && + readUint8LengthPrefixed(&s, &m.resumptionSecret) && + len(m.resumptionSecret) != 0 && + unmarshalCertificate(&s, &m.certificate) && + s.ReadUint32(&m.maxEarlyData) && + readUint8LengthPrefixed(&s, &alpn) && + readUint16LengthPrefixed(&s, &m.appData) && + s.Empty() + m.alpn = string(alpn) + return ret +} + +func (c *Conn) encryptTicket(state []byte) ([]byte, error) { + if len(c.ticketKeys) == 0 { + return nil, errors.New("tls: internal error: session ticket keys unavailable") + } + + encrypted := make([]byte, ticketKeyNameLen+aes.BlockSize+len(state)+sha256.Size) + keyName := encrypted[:ticketKeyNameLen] + iv := encrypted[ticketKeyNameLen : ticketKeyNameLen+aes.BlockSize] + macBytes := encrypted[len(encrypted)-sha256.Size:] + + if _, err := io.ReadFull(c.config.rand(), iv); err != nil { + return nil, err + } + key := c.ticketKeys[0] + copy(keyName, key.keyName[:]) + block, err := aes.NewCipher(key.aesKey[:]) + if err != nil { + return nil, errors.New("tls: failed to create cipher while encrypting ticket: " + err.Error()) + } + cipher.NewCTR(block, iv).XORKeyStream(encrypted[ticketKeyNameLen+aes.BlockSize:], state) + + mac := hmac.New(sha256.New, key.hmacKey[:]) + mac.Write(encrypted[:len(encrypted)-sha256.Size]) + mac.Sum(macBytes[:0]) + + return encrypted, nil +} + +func (c *Conn) decryptTicket(encrypted []byte) (plaintext []byte, usedOldKey bool) { + if len(encrypted) < ticketKeyNameLen+aes.BlockSize+sha256.Size { + return nil, false + } + + keyName := encrypted[:ticketKeyNameLen] + iv := encrypted[ticketKeyNameLen : ticketKeyNameLen+aes.BlockSize] + macBytes := encrypted[len(encrypted)-sha256.Size:] + ciphertext := encrypted[ticketKeyNameLen+aes.BlockSize : len(encrypted)-sha256.Size] + + keyIndex := -1 + for i, candidateKey := range c.ticketKeys { + if bytes.Equal(keyName, candidateKey.keyName[:]) { + keyIndex = i + break + } + } + if keyIndex == -1 { + return nil, false + } + key := &c.ticketKeys[keyIndex] + + mac := hmac.New(sha256.New, key.hmacKey[:]) + mac.Write(encrypted[:len(encrypted)-sha256.Size]) + expected := mac.Sum(nil) + + if subtle.ConstantTimeCompare(macBytes, expected) != 1 { + return nil, false + } + + block, err := aes.NewCipher(key.aesKey[:]) + if err != nil { + return nil, false + } + plaintext = make([]byte, len(ciphertext)) + cipher.NewCTR(block, iv).XORKeyStream(plaintext, ciphertext) + + return plaintext, keyIndex > 0 +} + +func (c *Conn) getSessionTicketMsg(appData []byte) (*newSessionTicketMsgTLS13, error) { + m := new(newSessionTicketMsgTLS13) + + var certsFromClient [][]byte + for _, cert := range c.peerCertificates { + certsFromClient = append(certsFromClient, cert.Raw) + } + state := sessionStateTLS13{ + cipherSuite: c.cipherSuite, + createdAt: uint64(c.config.time().Unix()), + resumptionSecret: c.resumptionSecret, + certificate: Certificate{ + Certificate: certsFromClient, + OCSPStaple: c.ocspResponse, + SignedCertificateTimestamps: c.scts, + }, + appData: appData, + alpn: c.clientProtocol, + } + if c.extraConfig != nil { + state.maxEarlyData = c.extraConfig.MaxEarlyData + } + stateBytes, err := state.marshal() + if err != nil { + return nil, err + } + m.label, err = c.encryptTicket(stateBytes) + if err != nil { + return nil, err + } + m.lifetime = uint32(maxSessionTicketLifetime / time.Second) + + // ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1 + // The value is not stored anywhere; we never need to check the ticket age + // because 0-RTT is not supported. + ageAdd := make([]byte, 4) + _, err = c.config.rand().Read(ageAdd) + if err != nil { + return nil, err + } + m.ageAdd = binary.LittleEndian.Uint32(ageAdd) + + // ticket_nonce, which must be unique per connection, is always left at + // zero because we only ever send one ticket per connection. + + if c.extraConfig != nil { + m.maxEarlyData = c.extraConfig.MaxEarlyData + } + return m, nil +} + +// GetSessionTicket generates a new session ticket. +// It should only be called after the handshake completes. +// It can only be used for servers, and only if the alternative record layer is set. +// The ticket may be nil if config.SessionTicketsDisabled is set, +// or if the client isn't able to receive session tickets. +func (c *Conn) GetSessionTicket(appData []byte) ([]byte, error) { + if c.isClient || !c.handshakeComplete() || c.extraConfig == nil || c.extraConfig.AlternativeRecordLayer == nil { + return nil, errors.New("GetSessionTicket is only valid for servers after completion of the handshake, and if an alternative record layer is set.") + } + if c.config.SessionTicketsDisabled { + return nil, nil + } + + m, err := c.getSessionTicketMsg(appData) + if err != nil { + return nil, err + } + return m.marshal() +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/tls.go b/vendor/github.com/quic-go/qtls-go1-19/tls.go new file mode 100644 index 000000000..42207c235 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/tls.go @@ -0,0 +1,362 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// package qtls partially implements TLS 1.2, as specified in RFC 5246, +// and TLS 1.3, as specified in RFC 8446. +package qtls + +// BUG(agl): The crypto/tls package only implements some countermeasures +// against Lucky13 attacks on CBC-mode encryption, and only on SHA1 +// variants. See http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and +// https://www.imperialviolet.org/2013/02/04/luckythirteen.html. + +import ( + "bytes" + "context" + "crypto" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "errors" + "fmt" + "net" + "os" + "strings" +) + +// Server returns a new TLS server side connection +// using conn as the underlying transport. +// The configuration config must be non-nil and must include +// at least one certificate or else set GetCertificate. +func Server(conn net.Conn, config *Config, extraConfig *ExtraConfig) *Conn { + c := &Conn{ + conn: conn, + config: fromConfig(config), + extraConfig: extraConfig, + } + c.handshakeFn = c.serverHandshake + return c +} + +// Client returns a new TLS client side connection +// using conn as the underlying transport. +// The config cannot be nil: users must set either ServerName or +// InsecureSkipVerify in the config. +func Client(conn net.Conn, config *Config, extraConfig *ExtraConfig) *Conn { + c := &Conn{ + conn: conn, + config: fromConfig(config), + extraConfig: extraConfig, + isClient: true, + } + c.handshakeFn = c.clientHandshake + return c +} + +// A listener implements a network listener (net.Listener) for TLS connections. +type listener struct { + net.Listener + config *Config + extraConfig *ExtraConfig +} + +// Accept waits for and returns the next incoming TLS connection. +// The returned connection is of type *Conn. +func (l *listener) Accept() (net.Conn, error) { + c, err := l.Listener.Accept() + if err != nil { + return nil, err + } + return Server(c, l.config, l.extraConfig), nil +} + +// NewListener creates a Listener which accepts connections from an inner +// Listener and wraps each connection with Server. +// The configuration config must be non-nil and must include +// at least one certificate or else set GetCertificate. +func NewListener(inner net.Listener, config *Config, extraConfig *ExtraConfig) net.Listener { + l := new(listener) + l.Listener = inner + l.config = config + l.extraConfig = extraConfig + return l +} + +// Listen creates a TLS listener accepting connections on the +// given network address using net.Listen. +// The configuration config must be non-nil and must include +// at least one certificate or else set GetCertificate. +func Listen(network, laddr string, config *Config, extraConfig *ExtraConfig) (net.Listener, error) { + if config == nil || len(config.Certificates) == 0 && + config.GetCertificate == nil && config.GetConfigForClient == nil { + return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config") + } + l, err := net.Listen(network, laddr) + if err != nil { + return nil, err + } + return NewListener(l, config, extraConfig), nil +} + +type timeoutError struct{} + +func (timeoutError) Error() string { return "tls: DialWithDialer timed out" } +func (timeoutError) Timeout() bool { return true } +func (timeoutError) Temporary() bool { return true } + +// DialWithDialer connects to the given network address using dialer.Dial and +// then initiates a TLS handshake, returning the resulting TLS connection. Any +// timeout or deadline given in the dialer apply to connection and TLS +// handshake as a whole. +// +// DialWithDialer interprets a nil configuration as equivalent to the zero +// configuration; see the documentation of Config for the defaults. +// +// DialWithDialer uses context.Background internally; to specify the context, +// use Dialer.DialContext with NetDialer set to the desired dialer. +func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config, extraConfig *ExtraConfig) (*Conn, error) { + return dial(context.Background(), dialer, network, addr, config, extraConfig) +} + +func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config, extraConfig *ExtraConfig) (*Conn, error) { + if netDialer.Timeout != 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, netDialer.Timeout) + defer cancel() + } + + if !netDialer.Deadline.IsZero() { + var cancel context.CancelFunc + ctx, cancel = context.WithDeadline(ctx, netDialer.Deadline) + defer cancel() + } + + rawConn, err := netDialer.DialContext(ctx, network, addr) + if err != nil { + return nil, err + } + + colonPos := strings.LastIndex(addr, ":") + if colonPos == -1 { + colonPos = len(addr) + } + hostname := addr[:colonPos] + + if config == nil { + config = defaultConfig() + } + // If no ServerName is set, infer the ServerName + // from the hostname we're connecting to. + if config.ServerName == "" { + // Make a copy to avoid polluting argument or default. + c := config.Clone() + c.ServerName = hostname + config = c + } + + conn := Client(rawConn, config, extraConfig) + if err := conn.HandshakeContext(ctx); err != nil { + rawConn.Close() + return nil, err + } + return conn, nil +} + +// Dial connects to the given network address using net.Dial +// and then initiates a TLS handshake, returning the resulting +// TLS connection. +// Dial interprets a nil configuration as equivalent to +// the zero configuration; see the documentation of Config +// for the defaults. +func Dial(network, addr string, config *Config, extraConfig *ExtraConfig) (*Conn, error) { + return DialWithDialer(new(net.Dialer), network, addr, config, extraConfig) +} + +// Dialer dials TLS connections given a configuration and a Dialer for the +// underlying connection. +type Dialer struct { + // NetDialer is the optional dialer to use for the TLS connections' + // underlying TCP connections. + // A nil NetDialer is equivalent to the net.Dialer zero value. + NetDialer *net.Dialer + + // Config is the TLS configuration to use for new connections. + // A nil configuration is equivalent to the zero + // configuration; see the documentation of Config for the + // defaults. + Config *Config + + ExtraConfig *ExtraConfig +} + +// Dial connects to the given network address and initiates a TLS +// handshake, returning the resulting TLS connection. +// +// The returned Conn, if any, will always be of type *Conn. +// +// Dial uses context.Background internally; to specify the context, +// use DialContext. +func (d *Dialer) Dial(network, addr string) (net.Conn, error) { + return d.DialContext(context.Background(), network, addr) +} + +func (d *Dialer) netDialer() *net.Dialer { + if d.NetDialer != nil { + return d.NetDialer + } + return new(net.Dialer) +} + +// DialContext connects to the given network address and initiates a TLS +// handshake, returning the resulting TLS connection. +// +// The provided Context must be non-nil. If the context expires before +// the connection is complete, an error is returned. Once successfully +// connected, any expiration of the context will not affect the +// connection. +// +// The returned Conn, if any, will always be of type *Conn. +func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { + c, err := dial(ctx, d.netDialer(), network, addr, d.Config, d.ExtraConfig) + if err != nil { + // Don't return c (a typed nil) in an interface. + return nil, err + } + return c, nil +} + +// LoadX509KeyPair reads and parses a public/private key pair from a pair +// of files. The files must contain PEM encoded data. The certificate file +// may contain intermediate certificates following the leaf certificate to +// form a certificate chain. On successful return, Certificate.Leaf will +// be nil because the parsed form of the certificate is not retained. +func LoadX509KeyPair(certFile, keyFile string) (Certificate, error) { + certPEMBlock, err := os.ReadFile(certFile) + if err != nil { + return Certificate{}, err + } + keyPEMBlock, err := os.ReadFile(keyFile) + if err != nil { + return Certificate{}, err + } + return X509KeyPair(certPEMBlock, keyPEMBlock) +} + +// X509KeyPair parses a public/private key pair from a pair of +// PEM encoded data. On successful return, Certificate.Leaf will be nil because +// the parsed form of the certificate is not retained. +func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) { + fail := func(err error) (Certificate, error) { return Certificate{}, err } + + var cert Certificate + var skippedBlockTypes []string + for { + var certDERBlock *pem.Block + certDERBlock, certPEMBlock = pem.Decode(certPEMBlock) + if certDERBlock == nil { + break + } + if certDERBlock.Type == "CERTIFICATE" { + cert.Certificate = append(cert.Certificate, certDERBlock.Bytes) + } else { + skippedBlockTypes = append(skippedBlockTypes, certDERBlock.Type) + } + } + + if len(cert.Certificate) == 0 { + if len(skippedBlockTypes) == 0 { + return fail(errors.New("tls: failed to find any PEM data in certificate input")) + } + if len(skippedBlockTypes) == 1 && strings.HasSuffix(skippedBlockTypes[0], "PRIVATE KEY") { + return fail(errors.New("tls: failed to find certificate PEM data in certificate input, but did find a private key; PEM inputs may have been switched")) + } + return fail(fmt.Errorf("tls: failed to find \"CERTIFICATE\" PEM block in certificate input after skipping PEM blocks of the following types: %v", skippedBlockTypes)) + } + + skippedBlockTypes = skippedBlockTypes[:0] + var keyDERBlock *pem.Block + for { + keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock) + if keyDERBlock == nil { + if len(skippedBlockTypes) == 0 { + return fail(errors.New("tls: failed to find any PEM data in key input")) + } + if len(skippedBlockTypes) == 1 && skippedBlockTypes[0] == "CERTIFICATE" { + return fail(errors.New("tls: found a certificate rather than a key in the PEM for the private key")) + } + return fail(fmt.Errorf("tls: failed to find PEM block with type ending in \"PRIVATE KEY\" in key input after skipping PEM blocks of the following types: %v", skippedBlockTypes)) + } + if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") { + break + } + skippedBlockTypes = append(skippedBlockTypes, keyDERBlock.Type) + } + + // We don't need to parse the public key for TLS, but we so do anyway + // to check that it looks sane and matches the private key. + x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) + if err != nil { + return fail(err) + } + + cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes) + if err != nil { + return fail(err) + } + + switch pub := x509Cert.PublicKey.(type) { + case *rsa.PublicKey: + priv, ok := cert.PrivateKey.(*rsa.PrivateKey) + if !ok { + return fail(errors.New("tls: private key type does not match public key type")) + } + if pub.N.Cmp(priv.N) != 0 { + return fail(errors.New("tls: private key does not match public key")) + } + case *ecdsa.PublicKey: + priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey) + if !ok { + return fail(errors.New("tls: private key type does not match public key type")) + } + if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 { + return fail(errors.New("tls: private key does not match public key")) + } + case ed25519.PublicKey: + priv, ok := cert.PrivateKey.(ed25519.PrivateKey) + if !ok { + return fail(errors.New("tls: private key type does not match public key type")) + } + if !bytes.Equal(priv.Public().(ed25519.PublicKey), pub) { + return fail(errors.New("tls: private key does not match public key")) + } + default: + return fail(errors.New("tls: unknown public key algorithm")) + } + + return cert, nil +} + +// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates +// PKCS #1 private keys by default, while OpenSSL 1.0.0 generates PKCS #8 keys. +// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. +func parsePrivateKey(der []byte) (crypto.PrivateKey, error) { + if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { + return key, nil + } + if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { + switch key := key.(type) { + case *rsa.PrivateKey, *ecdsa.PrivateKey, ed25519.PrivateKey: + return key, nil + default: + return nil, errors.New("tls: found unknown private key type in PKCS#8 wrapping") + } + } + if key, err := x509.ParseECPrivateKey(der); err == nil { + return key, nil + } + + return nil, errors.New("tls: failed to parse private key") +} diff --git a/vendor/github.com/quic-go/qtls-go1-19/unsafe.go b/vendor/github.com/quic-go/qtls-go1-19/unsafe.go new file mode 100644 index 000000000..55fa01b3d --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-19/unsafe.go @@ -0,0 +1,96 @@ +package qtls + +import ( + "crypto/tls" + "reflect" + "unsafe" +) + +func init() { + if !structsEqual(&tls.ConnectionState{}, &connectionState{}) { + panic("qtls.ConnectionState doesn't match") + } + if !structsEqual(&tls.ClientSessionState{}, &clientSessionState{}) { + panic("qtls.ClientSessionState doesn't match") + } + if !structsEqual(&tls.CertificateRequestInfo{}, &certificateRequestInfo{}) { + panic("qtls.CertificateRequestInfo doesn't match") + } + if !structsEqual(&tls.Config{}, &config{}) { + panic("qtls.Config doesn't match") + } + if !structsEqual(&tls.ClientHelloInfo{}, &clientHelloInfo{}) { + panic("qtls.ClientHelloInfo doesn't match") + } +} + +func toConnectionState(c connectionState) ConnectionState { + return *(*ConnectionState)(unsafe.Pointer(&c)) +} + +func toClientSessionState(s *clientSessionState) *ClientSessionState { + return (*ClientSessionState)(unsafe.Pointer(s)) +} + +func fromClientSessionState(s *ClientSessionState) *clientSessionState { + return (*clientSessionState)(unsafe.Pointer(s)) +} + +func toCertificateRequestInfo(i *certificateRequestInfo) *CertificateRequestInfo { + return (*CertificateRequestInfo)(unsafe.Pointer(i)) +} + +func toConfig(c *config) *Config { + return (*Config)(unsafe.Pointer(c)) +} + +func fromConfig(c *Config) *config { + return (*config)(unsafe.Pointer(c)) +} + +func toClientHelloInfo(chi *clientHelloInfo) *ClientHelloInfo { + return (*ClientHelloInfo)(unsafe.Pointer(chi)) +} + +func structsEqual(a, b interface{}) bool { + return compare(reflect.ValueOf(a), reflect.ValueOf(b)) +} + +func compare(a, b reflect.Value) bool { + sa := a.Elem() + sb := b.Elem() + if sa.NumField() != sb.NumField() { + return false + } + for i := 0; i < sa.NumField(); i++ { + fa := sa.Type().Field(i) + fb := sb.Type().Field(i) + if !reflect.DeepEqual(fa.Index, fb.Index) || fa.Name != fb.Name || fa.Anonymous != fb.Anonymous || fa.Offset != fb.Offset || !reflect.DeepEqual(fa.Type, fb.Type) { + if fa.Type.Kind() != fb.Type.Kind() { + return false + } + if fa.Type.Kind() == reflect.Slice { + if !compareStruct(fa.Type.Elem(), fb.Type.Elem()) { + return false + } + continue + } + return false + } + } + return true +} + +func compareStruct(a, b reflect.Type) bool { + if a.NumField() != b.NumField() { + return false + } + for i := 0; i < a.NumField(); i++ { + fa := a.Field(i) + fb := b.Field(i) + if !reflect.DeepEqual(fa.Index, fb.Index) || fa.Name != fb.Name || fa.Anonymous != fb.Anonymous || fa.Offset != fb.Offset || !reflect.DeepEqual(fa.Type, fb.Type) { + return false + } + } + return true +} diff --git a/vendor/github.com/quic-go/qtls-go1-20/alert.go b/vendor/github.com/quic-go/qtls-go1-20/alert.go index 687ada843..3feac79be 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/alert.go +++ b/vendor/github.com/quic-go/qtls-go1-20/alert.go @@ -6,18 +6,11 @@ package qtls import "strconv" -// An AlertError is a TLS alert. -// -// When using a QUIC transport, QUICConn methods will return an error -// which wraps AlertError rather than sending a TLS alert. -type AlertError uint8 - -func (e AlertError) Error() string { - return alert(e).String() -} - type alert uint8 +// Alert is a TLS alert +type Alert = alert + const ( // alert level alertLevelWarning = 1 diff --git a/vendor/github.com/quic-go/qtls-go1-20/cipher_suites.go b/vendor/github.com/quic-go/qtls-go1-20/cipher_suites.go index 2946ffb32..43d213157 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/cipher_suites.go +++ b/vendor/github.com/quic-go/qtls-go1-20/cipher_suites.go @@ -15,10 +15,8 @@ import ( "crypto/sha256" "fmt" "hash" - "runtime" "golang.org/x/crypto/chacha20poly1305" - "golang.org/x/sys/cpu" ) // CipherSuite is a TLS cipher suite. Note that most functions in this package @@ -197,6 +195,17 @@ type cipherSuiteTLS13 struct { hash crypto.Hash } +type CipherSuiteTLS13 struct { + ID uint16 + KeyLen int + Hash crypto.Hash + AEAD func(key, fixedNonce []byte) cipher.AEAD +} + +func (c *CipherSuiteTLS13) IVLen() int { + return aeadNonceLength +} + var cipherSuitesTLS13 = []*cipherSuiteTLS13{ // TODO: replace with a map. {TLS_AES_128_GCM_SHA256, 16, aeadAESGCMTLS13, crypto.SHA256}, {TLS_CHACHA20_POLY1305_SHA256, 32, aeadChaCha20Poly1305, crypto.SHA256}, @@ -353,18 +362,6 @@ var defaultCipherSuitesTLS13NoAES = []uint16{ TLS_AES_256_GCM_SHA384, } -var ( - hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ - hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL - // Keep in sync with crypto/aes/cipher_s390x.go. - hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && - (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM) - - hasAESGCMHardwareSupport = runtime.GOARCH == "amd64" && hasGCMAsmAMD64 || - runtime.GOARCH == "arm64" && hasGCMAsmARM64 || - runtime.GOARCH == "s390x" && hasGCMAsmS390X -) - var aesgcmCiphers = map[uint16]bool{ // TLS 1.2 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: true, @@ -522,6 +519,11 @@ func aeadAESGCM(key, noncePrefix []byte) aead { return ret } +// AEADAESGCMTLS13 creates a new AES-GCM AEAD for TLS 1.3 +func AEADAESGCMTLS13(key, fixedNonce []byte) cipher.AEAD { + return aeadAESGCMTLS13(key, fixedNonce) +} + func aeadAESGCMTLS13(key, nonceMask []byte) aead { if len(nonceMask) != aeadNonceLength { panic("tls: internal error: wrong nonce length") diff --git a/vendor/github.com/quic-go/qtls-go1-20/common.go b/vendor/github.com/quic-go/qtls-go1-20/common.go index 841c1a44b..074dd9dce 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/common.go +++ b/vendor/github.com/quic-go/qtls-go1-20/common.go @@ -82,6 +82,11 @@ const ( compressionNone uint8 = 0 ) +type Extension struct { + Type uint16 + Data []byte +} + // TLS extension numbers const ( extensionServerName uint16 = 0 @@ -100,7 +105,6 @@ const ( extensionCertificateAuthorities uint16 = 47 extensionSignatureAlgorithmsCert uint16 = 50 extensionKeyShare uint16 = 51 - extensionQUICTransportParameters uint16 = 57 extensionRenegotiationInfo uint16 = 0xff01 ) @@ -109,6 +113,14 @@ const ( scsvRenegotiation uint16 = 0x00ff ) +type EncryptionLevel uint8 + +const ( + EncryptionHandshake EncryptionLevel = iota + Encryption0RTT + EncryptionApplication +) + // CurveID is a tls.CurveID type CurveID = tls.CurveID @@ -282,6 +294,12 @@ type connectionState struct { ekm func(label string, context []byte, length int) ([]byte, error) } +type ConnectionStateWith0RTT struct { + ConnectionState + + Used0RTT bool // true if 0-RTT was both offered and accepted +} + // ClientAuthType is tls.ClientAuthType type ClientAuthType = tls.ClientAuthType @@ -331,6 +349,8 @@ type clientSessionState struct { // goroutines. Up to TLS 1.2, only ticket-based resumption is supported, not // SessionID-based resumption. In TLS 1.3 they were merged into PSK modes, which // are supported via this interface. +// +//go:generate sh -c "mockgen -package qtls -destination mock_client_session_cache_test.go github.com/quic-go/qtls-go1-20 ClientSessionCache" type ClientSessionCache = tls.ClientSessionCache // SignatureScheme is a tls.SignatureScheme @@ -716,22 +736,64 @@ type config struct { autoSessionTicketKeys []ticketKey } -type ExtraConfig struct { - // If Enable0RTT is enabled, the client will be allowed to send early data when resuming a session. - // - // It has no meaning on the client. - Enable0RTT bool +// A RecordLayer handles encrypting and decrypting of TLS messages. +type RecordLayer interface { + SetReadKey(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte) + SetWriteKey(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte) + ReadHandshakeMessage() ([]byte, error) + WriteRecord([]byte) (int, error) + SendAlert(uint8) +} - // GetAppDataForSessionTicket requests application data to be sent with a session ticket. +type ExtraConfig struct { + // GetExtensions, if not nil, is called before a message that allows + // sending of extensions is sent. + // Currently only implemented for the ClientHello message (for the client) + // and for the EncryptedExtensions message (for the server). + // Only valid for TLS 1.3. + GetExtensions func(handshakeMessageType uint8) []Extension + + // ReceivedExtensions, if not nil, is called when a message that allows the + // inclusion of extensions is received. + // It is called with an empty slice of extensions, if the message didn't + // contain any extensions. + // Currently only implemented for the ClientHello message (sent by the + // client) and for the EncryptedExtensions message (sent by the server). + // Only valid for TLS 1.3. + ReceivedExtensions func(handshakeMessageType uint8, exts []Extension) + + // AlternativeRecordLayer is used by QUIC + AlternativeRecordLayer RecordLayer + + // Enforce the selection of a supported application protocol. + // Only works for TLS 1.3. + // If enabled, client and server have to agree on an application protocol. + // Otherwise, connection establishment fails. + EnforceNextProtoSelection bool + + // If MaxEarlyData is greater than 0, the client will be allowed to send early + // data when resuming a session. + // Requires the AlternativeRecordLayer to be set. // // It has no meaning on the client. - GetAppDataForSessionTicket func() []byte + MaxEarlyData uint32 // The Accept0RTT callback is called when the client offers 0-RTT. // The server then has to decide if it wants to accept or reject 0-RTT. // It is only used for servers. Accept0RTT func(appData []byte) bool + // 0RTTRejected is called when the server rejectes 0-RTT. + // It is only used for clients. + Rejected0RTT func() + + // If set, the client will export the 0-RTT key when resuming a session that + // allows sending of early data. + // Requires the AlternativeRecordLayer to be set. + // + // It has no meaning to the server. + Enable0RTT bool + // Is called when the client saves a session ticket to the session ticket. // This gives the application the opportunity to save some data along with the ticket, // which can be restored when the session ticket is used. @@ -745,14 +807,23 @@ type ExtraConfig struct { // Clone clones. func (c *ExtraConfig) Clone() *ExtraConfig { return &ExtraConfig{ + GetExtensions: c.GetExtensions, + ReceivedExtensions: c.ReceivedExtensions, + AlternativeRecordLayer: c.AlternativeRecordLayer, + EnforceNextProtoSelection: c.EnforceNextProtoSelection, + MaxEarlyData: c.MaxEarlyData, Enable0RTT: c.Enable0RTT, - GetAppDataForSessionTicket: c.GetAppDataForSessionTicket, Accept0RTT: c.Accept0RTT, + Rejected0RTT: c.Rejected0RTT, GetAppDataForSessionState: c.GetAppDataForSessionState, SetAppDataFromSessionState: c.SetAppDataFromSessionState, } } +func (c *ExtraConfig) usesAlternativeRecordLayer() bool { + return c != nil && c.AlternativeRecordLayer != nil +} + const ( // ticketKeyNameLen is the number of bytes of identifier that is prepended to // an encrypted session ticket in order to identify the key used to encrypt it. @@ -1313,6 +1384,7 @@ func (c *config) BuildNameToCertificate() { const ( keyLogLabelTLS12 = "CLIENT_RANDOM" + keyLogLabelEarlyTraffic = "CLIENT_EARLY_TRAFFIC_SECRET" keyLogLabelClientHandshake = "CLIENT_HANDSHAKE_TRAFFIC_SECRET" keyLogLabelServerHandshake = "SERVER_HANDSHAKE_TRAFFIC_SECRET" keyLogLabelClientTraffic = "CLIENT_TRAFFIC_SECRET_0" @@ -1451,4 +1523,16 @@ func isSupportedSignatureAlgorithm(sigAlg SignatureScheme, supportedSignatureAlg } // CertificateVerificationError is returned when certificate verification fails during the handshake. -type CertificateVerificationError = tls.CertificateVerificationError +type CertificateVerificationError struct { + // UnverifiedCertificates and its contents should not be modified. + UnverifiedCertificates []*x509.Certificate + Err error +} + +func (e *CertificateVerificationError) Error() string { + return fmt.Sprintf("tls: failed to verify certificate: %s", e.Err) +} + +func (e *CertificateVerificationError) Unwrap() error { + return e.Err +} diff --git a/vendor/github.com/quic-go/qtls-go1-20/conn.go b/vendor/github.com/quic-go/qtls-go1-20/conn.go index b7ebdb0a7..656c83c71 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/conn.go +++ b/vendor/github.com/quic-go/qtls-go1-20/conn.go @@ -29,7 +29,6 @@ type Conn struct { conn net.Conn isClient bool handshakeFn func(context.Context) error // (*Conn).clientHandshake or serverHandshake - quic *quicState // nil for non-QUIC connections // isHandshakeComplete is true if the connection is currently transferring // application data (i.e. is not currently processing a handshake). @@ -41,10 +40,11 @@ type Conn struct { vers uint16 // TLS version haveVers bool // version has been negotiated config *config // configuration passed to constructor - extraConfig *ExtraConfig // handshakes counts the number of handshakes performed on the // connection so far. If renegotiation is disabled then this is either // zero or one. + extraConfig *ExtraConfig + handshakes int didResume bool // whether this connection was a session resumption cipherSuite uint16 @@ -65,8 +65,13 @@ type Conn struct { secureRenegotiation bool // ekm is a closure for exporting keying material. ekm func(label string, context []byte, length int) ([]byte, error) + // For the client: // resumptionSecret is the resumption_master_secret for handling - // or sending NewSessionTicket messages. + // NewSessionTicket messages. nil if config.SessionTicketsDisabled. + // For the server: + // resumptionSecret is the resumption_master_secret for generating + // NewSessionTicket messages. Only used when the alternative record + // layer is set. nil if config.SessionTicketsDisabled. resumptionSecret []byte // ticketKeys is the set of active session ticket keys for this @@ -118,7 +123,12 @@ type Conn struct { // the rest of the bits are the number of goroutines in Conn.Write. activeCall atomic.Int32 + used0RTT bool + tmp [16]byte + + connStateMutex sync.Mutex + connState ConnectionStateWith0RTT } // Access to net.Conn methods. @@ -178,8 +188,9 @@ type halfConn struct { nextCipher any // next encryption state nextMac hash.Hash // next MAC algorithm - level QUICEncryptionLevel // current QUIC encryption level - trafficSecret []byte // current TLS 1.3 traffic secret + trafficSecret []byte // current TLS 1.3 traffic secret + + setKeyCallback func(encLevel EncryptionLevel, suite *CipherSuiteTLS13, trafficSecret []byte) } type permanentError struct { @@ -224,9 +235,20 @@ func (hc *halfConn) changeCipherSpec() error { return nil } -func (hc *halfConn) setTrafficSecret(suite *cipherSuiteTLS13, level QUICEncryptionLevel, secret []byte) { +func (hc *halfConn) exportKey(encLevel EncryptionLevel, suite *cipherSuiteTLS13, trafficSecret []byte) { + if hc.setKeyCallback != nil { + s := &CipherSuiteTLS13{ + ID: suite.id, + KeyLen: suite.keyLen, + Hash: suite.hash, + AEAD: func(key, fixedNonce []byte) cipher.AEAD { return suite.aead(key, fixedNonce) }, + } + hc.setKeyCallback(encLevel, s, trafficSecret) + } +} + +func (hc *halfConn) setTrafficSecret(suite *cipherSuiteTLS13, secret []byte) { hc.trafficSecret = secret - hc.level = level key, iv := suite.trafficKey(secret) hc.cipher = suite.aead(key, iv) for i := range hc.seq { @@ -459,6 +481,13 @@ func (hc *halfConn) decrypt(record []byte) ([]byte, recordType, error) { return plaintext, typ, nil } +func (c *Conn) setAlternativeRecordLayer() { + if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil { + c.in.setKeyCallback = c.extraConfig.AlternativeRecordLayer.SetReadKey + c.out.setKeyCallback = c.extraConfig.AlternativeRecordLayer.SetWriteKey + } +} + // sliceForAppend extends the input slice by n bytes. head is the full extended // slice, while tail is the appended part. If the original slice has sufficient // capacity no allocation is performed. @@ -617,10 +646,6 @@ func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error { } c.input.Reset(nil) - if c.quic != nil { - return c.in.setErrorLocked(errors.New("tls: internal error: attempted to read record with QUIC transport")) - } - // Read header, payload. if err := c.readFromUntil(c.conn, recordHeaderLen); err != nil { // RFC 8446, Section 6.1 suggests that EOF without an alertCloseNotify @@ -704,9 +729,6 @@ func (c *Conn) readRecordOrCCS(expectChangeCipherSpec bool) error { return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) case recordTypeAlert: - if c.quic != nil { - return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } if len(data) != 2 { return c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) } @@ -824,9 +846,6 @@ func (c *Conn) readFromUntil(r io.Reader, n int) error { // sendAlert sends a TLS alert message. func (c *Conn) sendAlertLocked(err alert) error { - if c.quic != nil { - return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) - } switch err { case alertNoRenegotiation, alertCloseNotify: c.tmp[0] = alertLevelWarning @@ -846,6 +865,11 @@ func (c *Conn) sendAlertLocked(err alert) error { // sendAlert sends a TLS alert message. func (c *Conn) sendAlert(err alert) error { + if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil { + c.extraConfig.AlternativeRecordLayer.SendAlert(uint8(err)) + return &net.OpError{Op: "local error", Err: err} + } + c.out.Lock() defer c.out.Unlock() return c.sendAlertLocked(err) @@ -961,19 +985,6 @@ var outBufPool = sync.Pool{ // writeRecordLocked writes a TLS record with the given type and payload to the // connection and updates the record layer state. func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) { - if c.quic != nil { - if typ != recordTypeHandshake { - return 0, errors.New("tls: internal error: sending non-handshake message to QUIC transport") - } - c.quicWriteCryptoData(c.out.level, data) - if !c.buffering { - if _, err := c.flush(); err != nil { - return 0, err - } - } - return len(data), nil - } - outBufPtr := outBufPool.Get().(*[]byte) outBuf := *outBufPtr defer func() { @@ -1035,63 +1046,69 @@ func (c *Conn) writeRecordLocked(typ recordType, data []byte) (int, error) { // the record layer state. If transcript is non-nil the marshalled message is // written to it. func (c *Conn) writeHandshakeRecord(msg handshakeMessage, transcript transcriptHash) (int, error) { - c.out.Lock() - defer c.out.Unlock() - data, err := msg.marshal() if err != nil { return 0, err } + + c.out.Lock() + defer c.out.Unlock() + if transcript != nil { transcript.Write(data) } + if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil { + return c.extraConfig.AlternativeRecordLayer.WriteRecord(data) + } + return c.writeRecordLocked(recordTypeHandshake, data) } // writeChangeCipherRecord writes a ChangeCipherSpec message to the connection and // updates the record layer state. func (c *Conn) writeChangeCipherRecord() error { + if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil { + return nil + } + c.out.Lock() defer c.out.Unlock() _, err := c.writeRecordLocked(recordTypeChangeCipherSpec, []byte{1}) return err } -// readHandshakeBytes reads handshake data until c.hand contains at least n bytes. -func (c *Conn) readHandshakeBytes(n int) error { - if c.quic != nil { - return c.quicReadHandshakeBytes(n) - } - for c.hand.Len() < n { - if err := c.readRecord(); err != nil { - return err - } - } - return nil -} - // readHandshake reads the next handshake message from // the record layer. If transcript is non-nil, the message // is written to the passed transcriptHash. func (c *Conn) readHandshake(transcript transcriptHash) (any, error) { - if err := c.readHandshakeBytes(4); err != nil { - return nil, err - } - data := c.hand.Bytes() - n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) - if n > maxHandshake { - c.sendAlertLocked(alertInternalError) - return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake)) - } - if err := c.readHandshakeBytes(4 + n); err != nil { - return nil, err - } - data = c.hand.Next(4 + n) - return c.unmarshalHandshakeMessage(data, transcript) -} + var data []byte + if c.extraConfig != nil && c.extraConfig.AlternativeRecordLayer != nil { + var err error + data, err = c.extraConfig.AlternativeRecordLayer.ReadHandshakeMessage() + if err != nil { + return nil, err + } + } else { + for c.hand.Len() < 4 { + if err := c.readRecord(); err != nil { + return nil, err + } + } -func (c *Conn) unmarshalHandshakeMessage(data []byte, transcript transcriptHash) (handshakeMessage, error) { + data = c.hand.Bytes() + n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) + if n > maxHandshake { + c.sendAlertLocked(alertInternalError) + return nil, c.in.setErrorLocked(fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake)) + } + for c.hand.Len() < 4+n { + if err := c.readRecord(); err != nil { + return nil, err + } + } + data = c.hand.Next(4 + n) + } var m handshakeMessage switch data[0] { case typeHelloRequest: @@ -1271,6 +1288,10 @@ func (c *Conn) handleRenegotiation() error { return c.handshakeErr } +func (c *Conn) HandlePostHandshakeMessage() error { + return c.handlePostHandshakeMessage() +} + // handlePostHandshakeMessage processes a handshake message arrived after the // handshake is complete. Up to TLS 1.2, it indicates the start of a renegotiation. func (c *Conn) handlePostHandshakeMessage() error { @@ -1282,6 +1303,7 @@ func (c *Conn) handlePostHandshakeMessage() error { if err != nil { return err } + c.retryCount++ if c.retryCount > maxUselessRecords { c.sendAlert(alertUnexpectedMessage) @@ -1293,28 +1315,20 @@ func (c *Conn) handlePostHandshakeMessage() error { return c.handleNewSessionTicket(msg) case *keyUpdateMsg: return c.handleKeyUpdate(msg) + default: + c.sendAlert(alertUnexpectedMessage) + return fmt.Errorf("tls: received unexpected handshake message of type %T", msg) } - // The QUIC layer is supposed to treat an unexpected post-handshake CertificateRequest - // as a QUIC-level PROTOCOL_VIOLATION error (RFC 9001, Section 4.4). Returning an - // unexpected_message alert here doesn't provide it with enough information to distinguish - // this condition from other unexpected messages. This is probably fine. - c.sendAlert(alertUnexpectedMessage) - return fmt.Errorf("tls: received unexpected handshake message of type %T", msg) } func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error { - if c.quic != nil { - c.sendAlert(alertUnexpectedMessage) - return c.in.setErrorLocked(errors.New("tls: received unexpected key update message")) - } - cipherSuite := cipherSuiteTLS13ByID(c.cipherSuite) if cipherSuite == nil { return c.in.setErrorLocked(c.sendAlert(alertInternalError)) } newSecret := cipherSuite.nextTrafficSecret(c.in.trafficSecret) - c.in.setTrafficSecret(cipherSuite, QUICEncryptionLevelInitial, newSecret) + c.in.setTrafficSecret(cipherSuite, newSecret) if keyUpdate.updateRequested { c.out.Lock() @@ -1333,7 +1347,7 @@ func (c *Conn) handleKeyUpdate(keyUpdate *keyUpdateMsg) error { } newSecret := cipherSuite.nextTrafficSecret(c.out.trafficSecret) - c.out.setTrafficSecret(cipherSuite, QUICEncryptionLevelInitial, newSecret) + c.out.setTrafficSecret(cipherSuite, newSecret) } return nil @@ -1494,15 +1508,12 @@ func (c *Conn) handshakeContext(ctx context.Context) (ret error) { // this cancellation. In the former case, we need to close the connection. defer cancel() - if c.quic != nil { - c.quic.cancelc = handshakeCtx.Done() - c.quic.cancel = cancel - } else if ctx.Done() != nil { - // Start the "interrupter" goroutine, if this context might be canceled. - // (The background context cannot). - // - // The interrupter goroutine waits for the input context to be done and - // closes the connection if this happens before the function returns. + // Start the "interrupter" goroutine, if this context might be canceled. + // (The background context cannot). + // + // The interrupter goroutine waits for the input context to be done and + // closes the connection if this happens before the function returns. + if ctx.Done() != nil { done := make(chan struct{}) interruptRes := make(chan error, 1) defer func() { @@ -1553,38 +1564,21 @@ func (c *Conn) handshakeContext(ctx context.Context) (ret error) { panic("tls: internal error: handshake returned an error but is marked successful") } - if c.quic != nil { - if c.handshakeErr == nil { - c.quicHandshakeComplete() - // Provide the 1-RTT read secret now that the handshake is complete. - // The QUIC layer MUST NOT decrypt 1-RTT packets prior to completing - // the handshake (RFC 9001, Section 5.7). - c.quicSetReadSecret(QUICEncryptionLevelApplication, c.cipherSuite, c.in.trafficSecret) - } else { - var a alert - c.out.Lock() - if !errors.As(c.out.err, &a) { - a = alertInternalError - } - c.out.Unlock() - // Return an error which wraps both the handshake error and - // any alert error we may have sent, or alertInternalError - // if we didn't send an alert. - // Truncate the text of the alert to 0 characters. - c.handshakeErr = fmt.Errorf("%w%.0w", c.handshakeErr, AlertError(a)) - } - close(c.quic.blockedc) - close(c.quic.signalc) - } - return c.handshakeErr } // ConnectionState returns basic TLS details about the connection. func (c *Conn) ConnectionState() ConnectionState { - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - return c.connectionStateLocked() + c.connStateMutex.Lock() + defer c.connStateMutex.Unlock() + return c.connState.ConnectionState +} + +// ConnectionStateWith0RTT returns basic TLS details (incl. 0-RTT status) about the connection. +func (c *Conn) ConnectionStateWith0RTT() ConnectionStateWith0RTT { + c.connStateMutex.Lock() + defer c.connStateMutex.Unlock() + return c.connState } func (c *Conn) connectionStateLocked() ConnectionState { @@ -1615,6 +1609,15 @@ func (c *Conn) connectionStateLocked() ConnectionState { return toConnectionState(state) } +func (c *Conn) updateConnectionState() { + c.connStateMutex.Lock() + defer c.connStateMutex.Unlock() + c.connState = ConnectionStateWith0RTT{ + Used0RTT: c.used0RTT, + ConnectionState: c.connectionStateLocked(), + } +} + // OCSPResponse returns the stapled OCSP response from the TLS server, if // any. (Only valid for client connections.) func (c *Conn) OCSPResponse() []byte { diff --git a/vendor/github.com/quic-go/qtls-go1-20/cpu.go b/vendor/github.com/quic-go/qtls-go1-20/cpu.go new file mode 100644 index 000000000..121945087 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-20/cpu.go @@ -0,0 +1,22 @@ +//go:build !js +// +build !js + +package qtls + +import ( + "runtime" + + "golang.org/x/sys/cpu" +) + +var ( + hasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ + hasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL + // Keep in sync with crypto/aes/cipher_s390x.go. + hasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && + (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM) + + hasAESGCMHardwareSupport = runtime.GOARCH == "amd64" && hasGCMAsmAMD64 || + runtime.GOARCH == "arm64" && hasGCMAsmARM64 || + runtime.GOARCH == "s390x" && hasGCMAsmS390X +) diff --git a/vendor/github.com/quic-go/qtls-go1-20/cpu_other.go b/vendor/github.com/quic-go/qtls-go1-20/cpu_other.go new file mode 100644 index 000000000..33f7d2194 --- /dev/null +++ b/vendor/github.com/quic-go/qtls-go1-20/cpu_other.go @@ -0,0 +1,12 @@ +//go:build js +// +build js + +package qtls + +var ( + hasGCMAsmAMD64 = false + hasGCMAsmARM64 = false + hasGCMAsmS390X = false + + hasAESGCMHardwareSupport = false +) diff --git a/vendor/github.com/quic-go/qtls-go1-20/handshake_client.go b/vendor/github.com/quic-go/qtls-go1-20/handshake_client.go index a5fdd54ca..ebb56ebe1 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/handshake_client.go +++ b/vendor/github.com/quic-go/qtls-go1-20/handshake_client.go @@ -58,12 +58,23 @@ func (c *Conn) makeClientHello() (*clientHelloMsg, *ecdh.PrivateKey, error) { return nil, nil, errors.New("tls: NextProtos values too large") } - supportedVersions := config.supportedVersions(roleClient) - if len(supportedVersions) == 0 { - return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion") + var supportedVersions []uint16 + var clientHelloVersion uint16 + if c.extraConfig.usesAlternativeRecordLayer() { + if config.maxSupportedVersion(roleClient) < VersionTLS13 { + return nil, nil, errors.New("tls: MaxVersion prevents QUIC from using TLS 1.3") + } + // Only offer TLS 1.3 when QUIC is used. + supportedVersions = []uint16{VersionTLS13} + clientHelloVersion = VersionTLS13 + } else { + supportedVersions = config.supportedVersions(roleClient) + if len(supportedVersions) == 0 { + return nil, nil, errors.New("tls: no supported versions satisfy MinVersion and MaxVersion") + } + clientHelloVersion = config.maxSupportedVersion(roleClient) } - clientHelloVersion := config.maxSupportedVersion(roleClient) // The version at the beginning of the ClientHello was capped at TLS 1.2 // for compatibility reasons. The supported_versions extension is used // to negotiate versions now. See RFC 8446, Section 4.2.1. @@ -117,9 +128,7 @@ func (c *Conn) makeClientHello() (*clientHelloMsg, *ecdh.PrivateKey, error) { // A random session ID is used to detect when the server accepted a ticket // and is resuming a session (see RFC 5077). In TLS 1.3, it's always set as // a compatibility measure (see RFC 8446, Section 4.1.2). - // - // The session ID is not set for QUIC connections (see RFC 9001, Section 8.4). - if c.quic == nil { + if c.extraConfig == nil || c.extraConfig.AlternativeRecordLayer == nil { hello.sessionId = make([]byte, 32) if _, err := io.ReadFull(config.rand(), hello.sessionId); err != nil { return nil, nil, errors.New("tls: short read from Rand: " + err.Error()) @@ -155,15 +164,8 @@ func (c *Conn) makeClientHello() (*clientHelloMsg, *ecdh.PrivateKey, error) { hello.keyShares = []keyShare{{group: curveID, data: key.PublicKey().Bytes()}} } - if c.quic != nil { - p, err := c.quicGetTransportParameters() - if err != nil { - return nil, nil, err - } - if p == nil { - p = []byte{} - } - hello.quicTransportParameters = p + if hello.supportedVersions[0] == VersionTLS13 && c.extraConfig != nil && c.extraConfig.GetExtensions != nil { + hello.additionalExtensions = c.extraConfig.GetExtensions(typeClientHello) } return hello, key, nil @@ -173,6 +175,7 @@ func (c *Conn) clientHandshake(ctx context.Context) (err error) { if c.config == nil { c.config = fromConfig(defaultConfig()) } + c.setAlternativeRecordLayer() // This may be a renegotiation handshake, in which case some fields // need to be reset. @@ -189,33 +192,45 @@ func (c *Conn) clientHandshake(ctx context.Context) (err error) { return err } if cacheKey != "" && session != nil { - defer func() { - // If we got a handshake failure when resuming a session, throw away - // the session ticket. See RFC 5077, Section 3.2. - // - // RFC 8446 makes no mention of dropping tickets on failure, but it - // does require servers to abort on invalid binders, so we need to - // delete tickets to recover from a corrupted PSK. - if err != nil { - c.config.ClientSessionCache.Put(cacheKey, nil) + var deletedTicket bool + if session.vers == VersionTLS13 && hello.earlyData && c.extraConfig != nil && c.extraConfig.Enable0RTT { + // don't reuse a session ticket that enabled 0-RTT + c.config.ClientSessionCache.Put(cacheKey, nil) + deletedTicket = true + + if suite := cipherSuiteTLS13ByID(session.cipherSuite); suite != nil { + h := suite.hash.New() + helloBytes, err := hello.marshal() + if err != nil { + return err + } + h.Write(helloBytes) + clientEarlySecret := suite.deriveSecret(earlySecret, "c e traffic", h) + c.out.exportKey(Encryption0RTT, suite, clientEarlySecret) + if err := c.config.writeKeyLog(keyLogLabelEarlyTraffic, hello.random, clientEarlySecret); err != nil { + return err + } } - }() + } + if !deletedTicket { + defer func() { + // If we got a handshake failure when resuming a session, throw away + // the session ticket. See RFC 5077, Section 3.2. + // + // RFC 8446 makes no mention of dropping tickets on failure, but it + // does require servers to abort on invalid binders, so we need to + // delete tickets to recover from a corrupted PSK. + if err != nil { + c.config.ClientSessionCache.Put(cacheKey, nil) + } + }() + } } if _, err := c.writeHandshakeRecord(hello, nil); err != nil { return err } - if hello.earlyData { - suite := cipherSuiteTLS13ByID(session.cipherSuite) - transcript := suite.hash.New() - if err := transcriptMsg(hello, transcript); err != nil { - return err - } - earlyTrafficSecret := suite.deriveSecret(earlySecret, clientEarlyTrafficLabel, transcript) - c.quicSetWriteSecret(QUICEncryptionLevelEarly, suite.id, earlyTrafficSecret) - } - // serverHelloMsg is not included in the transcript msg, err := c.readHandshake(nil) if err != nil { @@ -278,6 +293,7 @@ func (c *Conn) clientHandshake(ctx context.Context) (err error) { c.config.ClientSessionCache.Put(cacheKey, toClientSessionState(hs.session)) } + c.updateConnectionState() return nil } @@ -330,10 +346,7 @@ func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string, } // Try to resume a previously negotiated TLS session, if available. - cacheKey = c.clientSessionCacheKey() - if cacheKey == "" { - return "", nil, nil, nil, nil - } + cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config) sess, ok := c.config.ClientSessionCache.Get(cacheKey) if !ok || sess == nil { return cacheKey, nil, nil, nil, nil @@ -417,13 +430,6 @@ func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string, return cacheKey, nil, nil, nil, nil } - if c.quic != nil && maxEarlyData > 0 { - // For 0-RTT, the cipher suite has to match exactly. - if mutualCipherSuiteTLS13(hello.cipherSuites, session.cipherSuite) != nil { - hello.earlyData = true - } - } - // Set the pre_shared_key extension. See RFC 8446, Section 4.2.11.1. ticketAge := uint32(c.config.time().Sub(session.receivedAt) / time.Millisecond) identity := pskIdentity{ @@ -438,6 +444,9 @@ func (c *Conn) loadSession(hello *clientHelloMsg) (cacheKey string, session.nonce, cipherSuite.hash.Size()) earlySecret = cipherSuite.extract(psk, nil) binderKey = cipherSuite.deriveSecret(earlySecret, resumptionBinderLabel, nil) + if c.extraConfig != nil { + hello.earlyData = c.extraConfig.Enable0RTT && maxEarlyData > 0 + } transcript := cipherSuite.hash.New() helloBytes, err := hello.marshalWithoutBinders() if err != nil { @@ -806,7 +815,7 @@ func (hs *clientHandshakeState) processServerHello() (bool, error) { } } - if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol, false); err != nil { + if err := checkALPN(hs.hello.alpnProtocols, hs.serverHello.alpnProtocol); err != nil { c.sendAlert(alertUnsupportedExtension) return false, err } @@ -844,12 +853,8 @@ func (hs *clientHandshakeState) processServerHello() (bool, error) { // checkALPN ensure that the server's choice of ALPN protocol is compatible with // the protocols that we advertised in the Client Hello. -func checkALPN(clientProtos []string, serverProto string, quic bool) error { +func checkALPN(clientProtos []string, serverProto string) error { if serverProto == "" { - if quic && len(clientProtos) > 0 { - // RFC 9001, Section 8.1 - return errors.New("tls: server did not select an ALPN protocol") - } return nil } if len(clientProtos) == 0 { @@ -1097,16 +1102,15 @@ func (c *Conn) getClientCertificate(cri *CertificateRequestInfo) (*Certificate, return new(Certificate), nil } +const clientSessionCacheKeyPrefix = "qtls-" + // clientSessionCacheKey returns a key used to cache sessionTickets that could // be used to resume previously negotiated TLS sessions with a server. -func (c *Conn) clientSessionCacheKey() string { - if len(c.config.ServerName) > 0 { - return c.config.ServerName +func clientSessionCacheKey(serverAddr net.Addr, config *config) string { + if len(config.ServerName) > 0 { + return clientSessionCacheKeyPrefix + config.ServerName } - if c.conn != nil { - return c.conn.RemoteAddr().String() - } - return "" + return clientSessionCacheKeyPrefix + serverAddr.String() } // hostnameInSNI converts name into an appropriate hostname for SNI. diff --git a/vendor/github.com/quic-go/qtls-go1-20/handshake_client_tls13.go b/vendor/github.com/quic-go/qtls-go1-20/handshake_client_tls13.go index e9d0a533e..60ae29954 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/handshake_client_tls13.go +++ b/vendor/github.com/quic-go/qtls-go1-20/handshake_client_tls13.go @@ -87,6 +87,7 @@ func (hs *clientHandshakeStateTLS13) handshake() error { if err := hs.processServerHello(); err != nil { return err } + c.updateConnectionState() if err := hs.sendDummyChangeCipherSpec(); err != nil { return err } @@ -99,6 +100,7 @@ func (hs *clientHandshakeStateTLS13) handshake() error { if err := hs.readServerCertificate(); err != nil { return err } + c.updateConnectionState() if err := hs.readServerFinished(); err != nil { return err } @@ -113,7 +115,7 @@ func (hs *clientHandshakeStateTLS13) handshake() error { } c.isHandshakeComplete.Store(true) - + c.updateConnectionState() return nil } @@ -175,9 +177,6 @@ func (hs *clientHandshakeStateTLS13) checkServerHelloOrHRR() error { // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. func (hs *clientHandshakeStateTLS13) sendDummyChangeCipherSpec() error { - if hs.c.quic != nil { - return nil - } if hs.sentDummyCCS { return nil } @@ -265,7 +264,7 @@ func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error { transcript := hs.suite.hash.New() transcript.Write([]byte{typeMessageHash, 0, 0, uint8(len(chHash))}) transcript.Write(chHash) - if err := transcriptMsg(hs.serverHello, transcript); err != nil { + if err := transcriptMsg(hs.serverHello, hs.transcript); err != nil { return err } helloBytes, err := hs.hello.marshalWithoutBinders() @@ -284,11 +283,10 @@ func (hs *clientHandshakeStateTLS13) processHelloRetryRequest() error { } } - if hs.hello.earlyData { - hs.hello.earlyData = false - c.quicRejectedEarlyData() + if hs.hello.earlyData && c.extraConfig != nil && c.extraConfig.Rejected0RTT != nil { + c.extraConfig.Rejected0RTT() } - + hs.hello.earlyData = false // disable 0-RTT if _, err := hs.c.writeHandshakeRecord(hs.hello, hs.transcript); err != nil { return err } @@ -394,18 +392,12 @@ func (hs *clientHandshakeStateTLS13) establishHandshakeKeys() error { clientSecret := hs.suite.deriveSecret(handshakeSecret, clientHandshakeTrafficLabel, hs.transcript) - c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret) + c.out.exportKey(EncryptionHandshake, hs.suite, clientSecret) + c.out.setTrafficSecret(hs.suite, clientSecret) serverSecret := hs.suite.deriveSecret(handshakeSecret, serverHandshakeTrafficLabel, hs.transcript) - c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret) - - if c.quic != nil { - if c.hand.Len() != 0 { - c.sendAlert(alertUnexpectedMessage) - } - c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret) - c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret) - } + c.in.exportKey(EncryptionHandshake, hs.suite, serverSecret) + c.in.setTrafficSecret(hs.suite, serverSecret) err = c.config.writeKeyLog(keyLogLabelClientHandshake, hs.hello.random, clientSecret) if err != nil { @@ -437,35 +429,28 @@ func (hs *clientHandshakeStateTLS13) readServerParameters() error { c.sendAlert(alertUnexpectedMessage) return unexpectedMessageError(encryptedExtensions, msg) } + // Notify the caller if 0-RTT was rejected. + if !encryptedExtensions.earlyData && hs.hello.earlyData && c.extraConfig != nil && c.extraConfig.Rejected0RTT != nil { + c.extraConfig.Rejected0RTT() + } + c.used0RTT = encryptedExtensions.earlyData + if hs.c.extraConfig != nil && hs.c.extraConfig.ReceivedExtensions != nil { + hs.c.extraConfig.ReceivedExtensions(typeEncryptedExtensions, encryptedExtensions.additionalExtensions) + } - if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol, c.quic != nil); err != nil { - // RFC 8446 specifies that no_application_protocol is sent by servers, but - // does not specify how clients handle the selection of an incompatible protocol. - // RFC 9001 Section 8.1 specifies that QUIC clients send no_application_protocol - // in this case. Always sending no_application_protocol seems reasonable. - c.sendAlert(alertNoApplicationProtocol) + if err := checkALPN(hs.hello.alpnProtocols, encryptedExtensions.alpnProtocol); err != nil { + c.sendAlert(alertUnsupportedExtension) return err } c.clientProtocol = encryptedExtensions.alpnProtocol - if c.quic != nil { - if encryptedExtensions.quicTransportParameters == nil { - // RFC 9001 Section 8.2. - c.sendAlert(alertMissingExtension) - return errors.New("tls: server did not send a quic_transport_parameters extension") - } - c.quicSetTransportParameters(encryptedExtensions.quicTransportParameters) - } else { - if encryptedExtensions.quicTransportParameters != nil { - c.sendAlert(alertUnsupportedExtension) - return errors.New("tls: server sent an unexpected quic_transport_parameters extension") + if c.extraConfig != nil && c.extraConfig.EnforceNextProtoSelection { + if len(encryptedExtensions.alpnProtocol) == 0 { + // the server didn't select an ALPN + c.sendAlert(alertNoApplicationProtocol) + return errors.New("ALPN negotiation failed. Server didn't offer any protocols") } } - - if hs.hello.earlyData && !encryptedExtensions.earlyData { - c.quicRejectedEarlyData() - } - return nil } @@ -593,7 +578,8 @@ func (hs *clientHandshakeStateTLS13) readServerFinished() error { clientApplicationTrafficLabel, hs.transcript) serverSecret := hs.suite.deriveSecret(hs.masterSecret, serverApplicationTrafficLabel, hs.transcript) - c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret) + c.in.exportKey(EncryptionApplication, hs.suite, serverSecret) + c.in.setTrafficSecret(hs.suite, serverSecret) err = c.config.writeKeyLog(keyLogLabelClientTraffic, hs.hello.random, hs.trafficSecret) if err != nil { @@ -689,20 +675,14 @@ func (hs *clientHandshakeStateTLS13) sendClientFinished() error { return err } - c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret) + c.out.exportKey(EncryptionApplication, hs.suite, hs.trafficSecret) + c.out.setTrafficSecret(hs.suite, hs.trafficSecret) if !c.config.SessionTicketsDisabled && c.config.ClientSessionCache != nil { c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, resumptionLabel, hs.transcript) } - if c.quic != nil { - if c.hand.Len() != 0 { - c.sendAlert(alertUnexpectedMessage) - } - c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, hs.trafficSecret) - } - return nil } @@ -773,10 +753,8 @@ func (c *Conn) handleNewSessionTicket(msg *newSessionTicketMsgTLS13) error { scts: c.scts, } - cacheKey := c.clientSessionCacheKey() - if cacheKey != "" { - c.config.ClientSessionCache.Put(cacheKey, toClientSessionState(session)) - } + cacheKey := clientSessionCacheKey(c.conn.RemoteAddr(), c.config) + c.config.ClientSessionCache.Put(cacheKey, toClientSessionState(session)) return nil } diff --git a/vendor/github.com/quic-go/qtls-go1-20/handshake_messages.go b/vendor/github.com/quic-go/qtls-go1-20/handshake_messages.go index 37b012363..c69fcefda 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/handshake_messages.go +++ b/vendor/github.com/quic-go/qtls-go1-20/handshake_messages.go @@ -93,7 +93,7 @@ type clientHelloMsg struct { pskModes []uint8 pskIdentities []pskIdentity pskBinders [][]byte - quicTransportParameters []byte + additionalExtensions []Extension } func (m *clientHelloMsg) marshal() ([]byte, error) { @@ -247,11 +247,10 @@ func (m *clientHelloMsg) marshal() ([]byte, error) { }) }) } - if m.quicTransportParameters != nil { // marshal zero-length parameters when present - // RFC 9001, Section 8.2 - exts.AddUint16(extensionQUICTransportParameters) + for _, ext := range m.additionalExtensions { + exts.AddUint16(ext.Type) exts.AddUint16LengthPrefixed(func(exts *cryptobyte.Builder) { - exts.AddBytes(m.quicTransportParameters) + exts.AddBytes(ext.Data) }) } if len(m.pskIdentities) > 0 { // pre_shared_key must be the last extension @@ -568,11 +567,6 @@ func (m *clientHelloMsg) unmarshal(data []byte) bool { if !readUint8LengthPrefixed(&extData, &m.pskModes) { return false } - case extensionQUICTransportParameters: - m.quicTransportParameters = make([]byte, len(extData)) - if !extData.CopyBytes(m.quicTransportParameters) { - return false - } case extensionPreSharedKey: // RFC 8446, Section 4.2.11 if !extensions.Empty() { @@ -604,7 +598,7 @@ func (m *clientHelloMsg) unmarshal(data []byte) bool { m.pskBinders = append(m.pskBinders, binder) } default: - // Ignore unknown extensions. + m.additionalExtensions = append(m.additionalExtensions, Extension{Type: extension, Data: extData}) continue } @@ -873,10 +867,11 @@ func (m *serverHelloMsg) unmarshal(data []byte) bool { } type encryptedExtensionsMsg struct { - raw []byte - alpnProtocol string - quicTransportParameters []byte - earlyData bool + raw []byte + alpnProtocol string + earlyData bool + + additionalExtensions []Extension } func (m *encryptedExtensionsMsg) marshal() ([]byte, error) { @@ -898,18 +893,17 @@ func (m *encryptedExtensionsMsg) marshal() ([]byte, error) { }) }) } - if m.quicTransportParameters != nil { // marshal zero-length parameters when present - // draft-ietf-quic-tls-32, Section 8.2 - b.AddUint16(extensionQUICTransportParameters) - b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { - b.AddBytes(m.quicTransportParameters) - }) - } if m.earlyData { // RFC 8446, Section 4.2.10 b.AddUint16(extensionEarlyData) b.AddUint16(0) // empty extension_data } + for _, ext := range m.additionalExtensions { + b.AddUint16(ext.Type) + b.AddUint16LengthPrefixed(func(b *cryptobyte.Builder) { + b.AddBytes(ext.Data) + }) + } }) }) @@ -929,14 +923,14 @@ func (m *encryptedExtensionsMsg) unmarshal(data []byte) bool { } for !extensions.Empty() { - var extension uint16 + var ext uint16 var extData cryptobyte.String - if !extensions.ReadUint16(&extension) || + if !extensions.ReadUint16(&ext) || !extensions.ReadUint16LengthPrefixed(&extData) { return false } - switch extension { + switch ext { case extensionALPN: var protoList cryptobyte.String if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() { @@ -948,15 +942,10 @@ func (m *encryptedExtensionsMsg) unmarshal(data []byte) bool { return false } m.alpnProtocol = string(proto) - case extensionQUICTransportParameters: - m.quicTransportParameters = make([]byte, len(extData)) - if !extData.CopyBytes(m.quicTransportParameters) { - return false - } case extensionEarlyData: m.earlyData = true default: - // Ignore unknown extensions. + m.additionalExtensions = append(m.additionalExtensions, Extension{Type: ext, Data: extData}) continue } diff --git a/vendor/github.com/quic-go/qtls-go1-20/handshake_server.go b/vendor/github.com/quic-go/qtls-go1-20/handshake_server.go index 7539c95d5..05321cfb6 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/handshake_server.go +++ b/vendor/github.com/quic-go/qtls-go1-20/handshake_server.go @@ -39,6 +39,8 @@ type serverHandshakeState struct { // serverHandshake performs a TLS handshake as a server. func (c *Conn) serverHandshake(ctx context.Context) error { + c.setAlternativeRecordLayer() + clientHello, err := c.readClientHello(ctx) if err != nil { return err @@ -51,6 +53,12 @@ func (c *Conn) serverHandshake(ctx context.Context) error { clientHello: clientHello, } return hs.handshake() + } else if c.extraConfig.usesAlternativeRecordLayer() { + // This should already have been caught by the check that the ClientHello doesn't + // offer any (supported) versions older than TLS 1.3. + // Check again to make sure we can't be tricked into using an older version. + c.sendAlert(alertProtocolVersion) + return errors.New("tls: negotiated TLS < 1.3 when using QUIC") } hs := serverHandshakeState{ @@ -123,6 +131,7 @@ func (hs *serverHandshakeState) handshake() error { c.ekm = ekmFromMasterSecret(c.vers, hs.suite, hs.masterSecret, hs.clientHello.random, hs.hello.random) c.isHandshakeComplete.Store(true) + c.updateConnectionState() return nil } @@ -158,6 +167,27 @@ func (c *Conn) readClientHello(ctx context.Context) (*clientHelloMsg, error) { if len(clientHello.supportedVersions) == 0 { clientVersions = supportedVersionsFromMax(clientHello.vers) } + if c.extraConfig.usesAlternativeRecordLayer() { + // In QUIC, the client MUST NOT offer any old TLS versions. + // Here, we can only check that none of the other supported versions of this library + // (TLS 1.0 - TLS 1.2) is offered. We don't check for any SSL versions here. + for _, ver := range clientVersions { + if ver == VersionTLS13 { + continue + } + for _, v := range supportedVersions { + if ver == v { + c.sendAlert(alertProtocolVersion) + return nil, fmt.Errorf("tls: client offered old TLS version %#x", ver) + } + } + } + // Make the config we're using allows us to use TLS 1.3. + if c.config.maxSupportedVersion(roleServer) < VersionTLS13 { + c.sendAlert(alertInternalError) + return nil, errors.New("tls: MaxVersion prevents QUIC from using TLS 1.3") + } + } c.vers, ok = c.config.mutualVersion(roleServer, clientVersions) if !ok { c.sendAlert(alertProtocolVersion) @@ -219,7 +249,7 @@ func (hs *serverHandshakeState) processClientHello() error { c.serverName = hs.clientHello.serverName } - selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, false) + selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols) if err != nil { c.sendAlert(alertNoApplicationProtocol) return err @@ -280,12 +310,8 @@ func (hs *serverHandshakeState) processClientHello() error { // negotiateALPN picks a shared ALPN protocol that both sides support in server // preference order. If ALPN is not configured or the peer doesn't support it, // it returns "" and no error. -func negotiateALPN(serverProtos, clientProtos []string, quic bool) (string, error) { +func negotiateALPN(serverProtos, clientProtos []string) (string, error) { if len(serverProtos) == 0 || len(clientProtos) == 0 { - if quic && len(serverProtos) != 0 { - // RFC 9001, Section 8.1 - return "", fmt.Errorf("tls: client did not request an application protocol") - } return "", nil } var http11fallback bool diff --git a/vendor/github.com/quic-go/qtls-go1-20/handshake_server_tls13.go b/vendor/github.com/quic-go/qtls-go1-20/handshake_server_tls13.go index 03bc5eb51..6189c7806 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/handshake_server_tls13.go +++ b/vendor/github.com/quic-go/qtls-go1-20/handshake_server_tls13.go @@ -40,7 +40,6 @@ type serverHandshakeStateTLS13 struct { trafficSecret []byte // client_application_traffic_secret_0 transcript hash.Hash clientFinished []byte - earlyData bool } func (hs *serverHandshakeStateTLS13) handshake() error { @@ -57,6 +56,7 @@ func (hs *serverHandshakeStateTLS13) handshake() error { if err := hs.checkForResumption(); err != nil { return err } + c.updateConnectionState() if err := hs.pickCertificate(); err != nil { return err } @@ -79,12 +79,13 @@ func (hs *serverHandshakeStateTLS13) handshake() error { if err := hs.readClientCertificate(); err != nil { return err } + c.updateConnectionState() if err := hs.readClientFinished(); err != nil { return err } c.isHandshakeComplete.Store(true) - + c.updateConnectionState() return nil } @@ -218,23 +219,13 @@ GroupSelection: return errors.New("tls: invalid client key share") } - if c.quic != nil { - if hs.clientHello.quicTransportParameters == nil { - // RFC 9001 Section 8.2. - c.sendAlert(alertMissingExtension) - return errors.New("tls: client did not send a quic_transport_parameters extension") - } - c.quicSetTransportParameters(hs.clientHello.quicTransportParameters) - } else { - if hs.clientHello.quicTransportParameters != nil { - c.sendAlert(alertUnsupportedExtension) - return errors.New("tls: client sent an unexpected quic_transport_parameters extension") - } - } - c.serverName = hs.clientHello.serverName - selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, c.quic != nil) + if c.extraConfig != nil && c.extraConfig.ReceivedExtensions != nil { + c.extraConfig.ReceivedExtensions(typeClientHello, hs.clientHello.additionalExtensions) + } + + selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols) if err != nil { hs.alpnNegotiationErr = err } @@ -291,9 +282,10 @@ func (hs *serverHandshakeStateTLS13) checkForResumption() error { } if hs.alpnNegotiationErr == nil && sessionState.alpn == c.clientProtocol && - c.extraConfig != nil && c.extraConfig.Enable0RTT && + c.extraConfig != nil && c.extraConfig.MaxEarlyData > 0 && c.extraConfig.Accept0RTT != nil && c.extraConfig.Accept0RTT(sessionState.appData) { hs.encryptedExtensions.earlyData = true + c.used0RTT = true } } @@ -345,23 +337,27 @@ func (hs *serverHandshakeStateTLS13) checkForResumption() error { return errors.New("tls: invalid PSK binder") } - if c.quic != nil && hs.clientHello.earlyData && hs.encryptedExtensions.earlyData && i == 0 && - sessionState.maxEarlyData > 0 && sessionState.cipherSuite == hs.suite.id { - hs.earlyData = true - - transcript := hs.suite.hash.New() - if err := transcriptMsg(hs.clientHello, transcript); err != nil { - return err - } - earlyTrafficSecret := hs.suite.deriveSecret(hs.earlySecret, clientEarlyTrafficLabel, transcript) - c.quicSetReadSecret(QUICEncryptionLevelEarly, hs.suite.id, earlyTrafficSecret) - } - c.didResume = true if err := c.processCertsFromClient(sessionState.certificate); err != nil { return err } + h := cloneHash(hs.transcript, hs.suite.hash) + clientHelloWithBindersBytes, err := hs.clientHello.marshal() + if err != nil { + c.sendAlert(alertInternalError) + return err + } + h.Write(clientHelloWithBindersBytes) + if hs.encryptedExtensions.earlyData { + clientEarlySecret := hs.suite.deriveSecret(hs.earlySecret, "c e traffic", h) + c.in.exportKey(Encryption0RTT, hs.suite, clientEarlySecret) + if err := c.config.writeKeyLog(keyLogLabelEarlyTraffic, hs.clientHello.random, clientEarlySecret); err != nil { + c.sendAlert(alertInternalError) + return err + } + } + hs.hello.selectedIdentityPresent = true hs.hello.selectedIdentity = uint16(i) hs.usingPSK = true @@ -436,9 +432,6 @@ func (hs *serverHandshakeStateTLS13) pickCertificate() error { // sendDummyChangeCipherSpec sends a ChangeCipherSpec record for compatibility // with middleboxes that didn't implement TLS correctly. See RFC 8446, Appendix D.4. func (hs *serverHandshakeStateTLS13) sendDummyChangeCipherSpec() error { - if hs.c.quic != nil { - return nil - } if hs.sentDummyCCS { return nil } @@ -505,9 +498,9 @@ func (hs *serverHandshakeStateTLS13) doHelloRetryRequest(selectedGroup CurveID) return errors.New("tls: client illegally modified second ClientHello") } - if illegalClientHelloChange(clientHello, hs.clientHello) { + if clientHello.earlyData { c.sendAlert(alertIllegalParameter) - return errors.New("tls: client illegally modified second ClientHello") + return errors.New("tls: client offered 0-RTT data in second ClientHello") } hs.clientHello = clientHello @@ -595,18 +588,12 @@ func (hs *serverHandshakeStateTLS13) sendServerParameters() error { clientSecret := hs.suite.deriveSecret(hs.handshakeSecret, clientHandshakeTrafficLabel, hs.transcript) - c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, clientSecret) + c.in.exportKey(EncryptionHandshake, hs.suite, clientSecret) + c.in.setTrafficSecret(hs.suite, clientSecret) serverSecret := hs.suite.deriveSecret(hs.handshakeSecret, serverHandshakeTrafficLabel, hs.transcript) - c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelHandshake, serverSecret) - - if c.quic != nil { - if c.hand.Len() != 0 { - c.sendAlert(alertUnexpectedMessage) - } - c.quicSetWriteSecret(QUICEncryptionLevelHandshake, hs.suite.id, serverSecret) - c.quicSetReadSecret(QUICEncryptionLevelHandshake, hs.suite.id, clientSecret) - } + c.out.exportKey(EncryptionHandshake, hs.suite, serverSecret) + c.out.setTrafficSecret(hs.suite, serverSecret) err := c.config.writeKeyLog(keyLogLabelClientHandshake, hs.clientHello.random, clientSecret) if err != nil { @@ -619,20 +606,12 @@ func (hs *serverHandshakeStateTLS13) sendServerParameters() error { return err } - selectedProto, err := negotiateALPN(c.config.NextProtos, hs.clientHello.alpnProtocols, c.quic != nil) - if err != nil { + if hs.alpnNegotiationErr != nil { c.sendAlert(alertNoApplicationProtocol) - return err + return hs.alpnNegotiationErr } - hs.encryptedExtensions.alpnProtocol = selectedProto - c.clientProtocol = selectedProto - - if c.quic != nil { - p, err := c.quicGetTransportParameters() - if err != nil { - return err - } - hs.encryptedExtensions.quicTransportParameters = p + if hs.c.extraConfig != nil && hs.c.extraConfig.GetExtensions != nil { + hs.encryptedExtensions.additionalExtensions = hs.c.extraConfig.GetExtensions(typeEncryptedExtensions) } if _, err := hs.c.writeHandshakeRecord(hs.encryptedExtensions, hs.transcript); err != nil { @@ -733,15 +712,8 @@ func (hs *serverHandshakeStateTLS13) sendServerFinished() error { clientApplicationTrafficLabel, hs.transcript) serverSecret := hs.suite.deriveSecret(hs.masterSecret, serverApplicationTrafficLabel, hs.transcript) - c.out.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, serverSecret) - - if c.quic != nil { - if c.hand.Len() != 0 { - // TODO: Handle this in setTrafficSecret? - c.sendAlert(alertUnexpectedMessage) - } - c.quicSetWriteSecret(QUICEncryptionLevelApplication, hs.suite.id, serverSecret) - } + c.out.exportKey(EncryptionApplication, hs.suite, serverSecret) + c.out.setTrafficSecret(hs.suite, serverSecret) err := c.config.writeKeyLog(keyLogLabelClientTraffic, hs.clientHello.random, hs.trafficSecret) if err != nil { @@ -773,10 +745,6 @@ func (hs *serverHandshakeStateTLS13) shouldSendSessionTickets() bool { return false } - // QUIC tickets are sent by QUICConn.SendSessionTicket, not automatically. - if hs.c.quic != nil { - return false - } // Don't send tickets the client wouldn't use. See RFC 8446, Section 4.2.9. for _, pskMode := range hs.clientHello.pskModes { if pskMode == pskModeDHE { @@ -796,66 +764,25 @@ func (hs *serverHandshakeStateTLS13) sendSessionTickets() error { if err := transcriptMsg(finishedMsg, hs.transcript); err != nil { return err } - c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, - resumptionLabel, hs.transcript) if !hs.shouldSendSessionTickets() { return nil } - return c.sendSessionTicket(false) -} -func (c *Conn) sendSessionTicket(earlyData bool) error { - suite := cipherSuiteTLS13ByID(c.cipherSuite) - if suite == nil { - return errors.New("tls: internal error: unknown cipher suite") + c.resumptionSecret = hs.suite.deriveSecret(hs.masterSecret, + resumptionLabel, hs.transcript) + + // Don't send session tickets when the alternative record layer is set. + // Instead, save the resumption secret on the Conn. + // Session tickets can then be generated by calling Conn.GetSessionTicket(). + if hs.c.extraConfig != nil && hs.c.extraConfig.AlternativeRecordLayer != nil { + return nil } - m := new(newSessionTicketMsgTLS13) - - var certsFromClient [][]byte - for _, cert := range c.peerCertificates { - certsFromClient = append(certsFromClient, cert.Raw) - } - state := sessionStateTLS13{ - cipherSuite: suite.id, - createdAt: uint64(c.config.time().Unix()), - resumptionSecret: c.resumptionSecret, - certificate: Certificate{ - Certificate: certsFromClient, - OCSPStaple: c.ocspResponse, - SignedCertificateTimestamps: c.scts, - }, - alpn: c.clientProtocol, - } - if earlyData { - state.maxEarlyData = 0xffffffff - state.appData = c.extraConfig.GetAppDataForSessionTicket() - } - stateBytes, err := state.marshal() - if err != nil { - c.sendAlert(alertInternalError) - return err - } - m.label, err = c.encryptTicket(stateBytes) + m, err := hs.c.getSessionTicketMsg(nil) if err != nil { return err } - m.lifetime = uint32(maxSessionTicketLifetime / time.Second) - - // ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1 - // The value is not stored anywhere; we never need to check the ticket age - // because 0-RTT is not supported. - ageAdd := make([]byte, 4) - _, err = c.config.rand().Read(ageAdd) - if err != nil { - return err - } - - if earlyData { - // RFC 9001, Section 4.6.1 - m.maxEarlyData = 0xffffffff - } if _, err := c.writeHandshakeRecord(m, nil); err != nil { return err @@ -973,7 +900,8 @@ func (hs *serverHandshakeStateTLS13) readClientFinished() error { return errors.New("tls: invalid client finished hash") } - c.in.setTrafficSecret(hs.suite, QUICEncryptionLevelApplication, hs.trafficSecret) + c.in.exportKey(EncryptionApplication, hs.suite, hs.trafficSecret) + c.in.setTrafficSecret(hs.suite, hs.trafficSecret) return nil } diff --git a/vendor/github.com/quic-go/qtls-go1-20/key_schedule.go b/vendor/github.com/quic-go/qtls-go1-20/key_schedule.go index a4568933d..c410a3e82 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/key_schedule.go +++ b/vendor/github.com/quic-go/qtls-go1-20/key_schedule.go @@ -21,7 +21,6 @@ import ( const ( resumptionBinderLabel = "res binder" - clientEarlyTrafficLabel = "c e traffic" clientHandshakeTrafficLabel = "c hs traffic" serverHandshakeTrafficLabel = "s hs traffic" clientApplicationTrafficLabel = "c ap traffic" diff --git a/vendor/github.com/quic-go/qtls-go1-20/quic.go b/vendor/github.com/quic-go/qtls-go1-20/quic.go deleted file mode 100644 index f146688b1..000000000 --- a/vendor/github.com/quic-go/qtls-go1-20/quic.go +++ /dev/null @@ -1,418 +0,0 @@ -// Copyright 2023 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package qtls - -import ( - "context" - "errors" - "fmt" -) - -// QUICEncryptionLevel represents a QUIC encryption level used to transmit -// handshake messages. -type QUICEncryptionLevel int - -const ( - QUICEncryptionLevelInitial = QUICEncryptionLevel(iota) - QUICEncryptionLevelEarly - QUICEncryptionLevelHandshake - QUICEncryptionLevelApplication -) - -func (l QUICEncryptionLevel) String() string { - switch l { - case QUICEncryptionLevelInitial: - return "Initial" - case QUICEncryptionLevelEarly: - return "Early" - case QUICEncryptionLevelHandshake: - return "Handshake" - case QUICEncryptionLevelApplication: - return "Application" - default: - return fmt.Sprintf("QUICEncryptionLevel(%v)", int(l)) - } -} - -// A QUICConn represents a connection which uses a QUIC implementation as the underlying -// transport as described in RFC 9001. -// -// Methods of QUICConn are not safe for concurrent use. -type QUICConn struct { - conn *Conn - - sessionTicketSent bool -} - -// A QUICConfig configures a QUICConn. -type QUICConfig struct { - TLSConfig *Config - ExtraConfig *ExtraConfig -} - -// A QUICEventKind is a type of operation on a QUIC connection. -type QUICEventKind int - -const ( - // QUICNoEvent indicates that there are no events available. - QUICNoEvent QUICEventKind = iota - - // QUICSetReadSecret and QUICSetWriteSecret provide the read and write - // secrets for a given encryption level. - // QUICEvent.Level, QUICEvent.Data, and QUICEvent.Suite are set. - // - // Secrets for the Initial encryption level are derived from the initial - // destination connection ID, and are not provided by the QUICConn. - QUICSetReadSecret - QUICSetWriteSecret - - // QUICWriteData provides data to send to the peer in CRYPTO frames. - // QUICEvent.Data is set. - QUICWriteData - - // QUICTransportParameters provides the peer's QUIC transport parameters. - // QUICEvent.Data is set. - QUICTransportParameters - - // QUICTransportParametersRequired indicates that the caller must provide - // QUIC transport parameters to send to the peer. The caller should set - // the transport parameters with QUICConn.SetTransportParameters and call - // QUICConn.NextEvent again. - // - // If transport parameters are set before calling QUICConn.Start, the - // connection will never generate a QUICTransportParametersRequired event. - QUICTransportParametersRequired - - // QUICRejectedEarlyData indicates that the server rejected 0-RTT data even - // if we offered it. It's returned before QUICEncryptionLevelApplication - // keys are returned. - QUICRejectedEarlyData - - // QUICHandshakeDone indicates that the TLS handshake has completed. - QUICHandshakeDone -) - -// A QUICEvent is an event occurring on a QUIC connection. -// -// The type of event is specified by the Kind field. -// The contents of the other fields are kind-specific. -type QUICEvent struct { - Kind QUICEventKind - - // Set for QUICSetReadSecret, QUICSetWriteSecret, and QUICWriteData. - Level QUICEncryptionLevel - - // Set for QUICTransportParameters, QUICSetReadSecret, QUICSetWriteSecret, and QUICWriteData. - // The contents are owned by crypto/tls, and are valid until the next NextEvent call. - Data []byte - - // Set for QUICSetReadSecret and QUICSetWriteSecret. - Suite uint16 -} - -type quicState struct { - events []QUICEvent - nextEvent int - - // eventArr is a statically allocated event array, large enough to handle - // the usual maximum number of events resulting from a single call: transport - // parameters, Initial data, Early read secret, Handshake write and read - // secrets, Handshake data, Application write secret, Application data. - eventArr [8]QUICEvent - - started bool - signalc chan struct{} // handshake data is available to be read - blockedc chan struct{} // handshake is waiting for data, closed when done - cancelc <-chan struct{} // handshake has been canceled - cancel context.CancelFunc - - // readbuf is shared between HandleData and the handshake goroutine. - // HandshakeCryptoData passes ownership to the handshake goroutine by - // reading from signalc, and reclaims ownership by reading from blockedc. - readbuf []byte - - transportParams []byte // to send to the peer -} - -// QUICClient returns a new TLS client side connection using QUICTransport as the -// underlying transport. The config cannot be nil. -// -// The config's MinVersion must be at least TLS 1.3. -func QUICClient(config *QUICConfig) *QUICConn { - return newQUICConn(Client(nil, config.TLSConfig), config.ExtraConfig) -} - -// QUICServer returns a new TLS server side connection using QUICTransport as the -// underlying transport. The config cannot be nil. -// -// The config's MinVersion must be at least TLS 1.3. -func QUICServer(config *QUICConfig) *QUICConn { - return newQUICConn(Server(nil, config.TLSConfig), config.ExtraConfig) -} - -func newQUICConn(conn *Conn, extraConfig *ExtraConfig) *QUICConn { - conn.quic = &quicState{ - signalc: make(chan struct{}), - blockedc: make(chan struct{}), - } - conn.quic.events = conn.quic.eventArr[:0] - conn.extraConfig = extraConfig - return &QUICConn{ - conn: conn, - } -} - -// Start starts the client or server handshake protocol. -// It may produce connection events, which may be read with NextEvent. -// -// Start must be called at most once. -func (q *QUICConn) Start(ctx context.Context) error { - if q.conn.quic.started { - return quicError(errors.New("tls: Start called more than once")) - } - q.conn.quic.started = true - if q.conn.config.MinVersion < VersionTLS13 { - return quicError(errors.New("tls: Config MinVersion must be at least TLS 1.13")) - } - go q.conn.HandshakeContext(ctx) - if _, ok := <-q.conn.quic.blockedc; !ok { - return q.conn.handshakeErr - } - return nil -} - -// NextEvent returns the next event occurring on the connection. -// It returns an event with a Kind of QUICNoEvent when no events are available. -func (q *QUICConn) NextEvent() QUICEvent { - qs := q.conn.quic - if last := qs.nextEvent - 1; last >= 0 && len(qs.events[last].Data) > 0 { - // Write over some of the previous event's data, - // to catch callers erroniously retaining it. - qs.events[last].Data[0] = 0 - } - if qs.nextEvent >= len(qs.events) { - qs.events = qs.events[:0] - qs.nextEvent = 0 - return QUICEvent{Kind: QUICNoEvent} - } - e := qs.events[qs.nextEvent] - qs.events[qs.nextEvent] = QUICEvent{} // zero out references to data - qs.nextEvent++ - return e -} - -// Close closes the connection and stops any in-progress handshake. -func (q *QUICConn) Close() error { - if q.conn.quic.cancel == nil { - return nil // never started - } - q.conn.quic.cancel() - for range q.conn.quic.blockedc { - // Wait for the handshake goroutine to return. - } - return q.conn.handshakeErr -} - -// HandleData handles handshake bytes received from the peer. -// It may produce connection events, which may be read with NextEvent. -func (q *QUICConn) HandleData(level QUICEncryptionLevel, data []byte) error { - c := q.conn - if c.in.level != level { - return quicError(c.in.setErrorLocked(errors.New("tls: handshake data received at wrong level"))) - } - c.quic.readbuf = data - <-c.quic.signalc - _, ok := <-c.quic.blockedc - if ok { - // The handshake goroutine is waiting for more data. - return nil - } - // The handshake goroutine has exited. - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - c.hand.Write(c.quic.readbuf) - c.quic.readbuf = nil - for q.conn.hand.Len() >= 4 && q.conn.handshakeErr == nil { - b := q.conn.hand.Bytes() - n := int(b[1])<<16 | int(b[2])<<8 | int(b[3]) - if n > maxHandshake { - q.conn.handshakeErr = fmt.Errorf("tls: handshake message of length %d bytes exceeds maximum of %d bytes", n, maxHandshake) - break - } - if len(b) < 4+n { - return nil - } - if err := q.conn.handlePostHandshakeMessage(); err != nil { - q.conn.handshakeErr = err - } - } - if q.conn.handshakeErr != nil { - return quicError(q.conn.handshakeErr) - } - return nil -} - -// SendSessionTicket sends a session ticket to the client. -// It produces connection events, which may be read with NextEvent. -// Currently, it can only be called once. -func (q *QUICConn) SendSessionTicket(earlyData bool) error { - c := q.conn - if !c.isHandshakeComplete.Load() { - return quicError(errors.New("tls: SendSessionTicket called before handshake completed")) - } - if c.isClient { - return quicError(errors.New("tls: SendSessionTicket called on the client")) - } - if q.sessionTicketSent { - return quicError(errors.New("tls: SendSessionTicket called multiple times")) - } - q.sessionTicketSent = true - return quicError(c.sendSessionTicket(earlyData)) -} - -// ConnectionState returns basic TLS details about the connection. -func (q *QUICConn) ConnectionState() ConnectionState { - return q.conn.ConnectionState() -} - -// SetTransportParameters sets the transport parameters to send to the peer. -// -// Server connections may delay setting the transport parameters until after -// receiving the client's transport parameters. See QUICTransportParametersRequired. -func (q *QUICConn) SetTransportParameters(params []byte) { - if params == nil { - params = []byte{} - } - q.conn.quic.transportParams = params - if q.conn.quic.started { - <-q.conn.quic.signalc - <-q.conn.quic.blockedc - } -} - -// quicError ensures err is an AlertError. -// If err is not already, quicError wraps it with alertInternalError. -func quicError(err error) error { - if err == nil { - return nil - } - var ae AlertError - if errors.As(err, &ae) { - return err - } - var a alert - if !errors.As(err, &a) { - a = alertInternalError - } - // Return an error wrapping the original error and an AlertError. - // Truncate the text of the alert to 0 characters. - return fmt.Errorf("%w%.0w", err, AlertError(a)) -} - -func (c *Conn) quicReadHandshakeBytes(n int) error { - for c.hand.Len() < n { - if err := c.quicWaitForSignal(); err != nil { - return err - } - } - return nil -} - -func (c *Conn) quicSetReadSecret(level QUICEncryptionLevel, suite uint16, secret []byte) { - c.quic.events = append(c.quic.events, QUICEvent{ - Kind: QUICSetReadSecret, - Level: level, - Suite: suite, - Data: secret, - }) -} - -func (c *Conn) quicSetWriteSecret(level QUICEncryptionLevel, suite uint16, secret []byte) { - c.quic.events = append(c.quic.events, QUICEvent{ - Kind: QUICSetWriteSecret, - Level: level, - Suite: suite, - Data: secret, - }) -} - -func (c *Conn) quicWriteCryptoData(level QUICEncryptionLevel, data []byte) { - var last *QUICEvent - if len(c.quic.events) > 0 { - last = &c.quic.events[len(c.quic.events)-1] - } - if last == nil || last.Kind != QUICWriteData || last.Level != level { - c.quic.events = append(c.quic.events, QUICEvent{ - Kind: QUICWriteData, - Level: level, - }) - last = &c.quic.events[len(c.quic.events)-1] - } - last.Data = append(last.Data, data...) -} - -func (c *Conn) quicSetTransportParameters(params []byte) { - c.quic.events = append(c.quic.events, QUICEvent{ - Kind: QUICTransportParameters, - Data: params, - }) -} - -func (c *Conn) quicGetTransportParameters() ([]byte, error) { - if c.quic.transportParams == nil { - c.quic.events = append(c.quic.events, QUICEvent{ - Kind: QUICTransportParametersRequired, - }) - } - for c.quic.transportParams == nil { - if err := c.quicWaitForSignal(); err != nil { - return nil, err - } - } - return c.quic.transportParams, nil -} - -func (c *Conn) quicHandshakeComplete() { - c.quic.events = append(c.quic.events, QUICEvent{ - Kind: QUICHandshakeDone, - }) -} - -func (c *Conn) quicRejectedEarlyData() { - c.quic.events = append(c.quic.events, QUICEvent{ - Kind: QUICRejectedEarlyData, - }) -} - -// quicWaitForSignal notifies the QUICConn that handshake progress is blocked, -// and waits for a signal that the handshake should proceed. -// -// The handshake may become blocked waiting for handshake bytes -// or for the user to provide transport parameters. -func (c *Conn) quicWaitForSignal() error { - // Drop the handshake mutex while blocked to allow the user - // to call ConnectionState before the handshake completes. - c.handshakeMutex.Unlock() - defer c.handshakeMutex.Lock() - // Send on blockedc to notify the QUICConn that the handshake is blocked. - // Exported methods of QUICConn wait for the handshake to become blocked - // before returning to the user. - select { - case c.quic.blockedc <- struct{}{}: - case <-c.quic.cancelc: - return c.sendAlertLocked(alertCloseNotify) - } - // The QUICConn reads from signalc to notify us that the handshake may - // be able to proceed. (The QUICConn reads, because we close signalc to - // indicate that the handshake has completed.) - select { - case c.quic.signalc <- struct{}{}: - c.hand.Write(c.quic.readbuf) - c.quic.readbuf = nil - case <-c.quic.cancelc: - return c.sendAlertLocked(alertCloseNotify) - } - return nil -} diff --git a/vendor/github.com/quic-go/qtls-go1-20/ticket.go b/vendor/github.com/quic-go/qtls-go1-20/ticket.go index 366620707..1b9289c2f 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/ticket.go +++ b/vendor/github.com/quic-go/qtls-go1-20/ticket.go @@ -11,9 +11,12 @@ import ( "crypto/hmac" "crypto/sha256" "crypto/subtle" + "encoding/binary" "errors" - "golang.org/x/crypto/cryptobyte" "io" + "time" + + "golang.org/x/crypto/cryptobyte" ) // sessionState contains the information that is serialized into a session @@ -201,3 +204,74 @@ func (c *Conn) decryptTicket(encrypted []byte) (plaintext []byte, usedOldKey boo return plaintext, keyIndex > 0 } + +func (c *Conn) getSessionTicketMsg(appData []byte) (*newSessionTicketMsgTLS13, error) { + m := new(newSessionTicketMsgTLS13) + + var certsFromClient [][]byte + for _, cert := range c.peerCertificates { + certsFromClient = append(certsFromClient, cert.Raw) + } + state := sessionStateTLS13{ + cipherSuite: c.cipherSuite, + createdAt: uint64(c.config.time().Unix()), + resumptionSecret: c.resumptionSecret, + certificate: Certificate{ + Certificate: certsFromClient, + OCSPStaple: c.ocspResponse, + SignedCertificateTimestamps: c.scts, + }, + appData: appData, + alpn: c.clientProtocol, + } + if c.extraConfig != nil { + state.maxEarlyData = c.extraConfig.MaxEarlyData + } + stateBytes, err := state.marshal() + if err != nil { + return nil, err + } + m.label, err = c.encryptTicket(stateBytes) + if err != nil { + return nil, err + } + m.lifetime = uint32(maxSessionTicketLifetime / time.Second) + + // ticket_age_add is a random 32-bit value. See RFC 8446, section 4.6.1 + // The value is not stored anywhere; we never need to check the ticket age + // because 0-RTT is not supported. + ageAdd := make([]byte, 4) + _, err = c.config.rand().Read(ageAdd) + if err != nil { + return nil, err + } + m.ageAdd = binary.LittleEndian.Uint32(ageAdd) + + // ticket_nonce, which must be unique per connection, is always left at + // zero because we only ever send one ticket per connection. + + if c.extraConfig != nil { + m.maxEarlyData = c.extraConfig.MaxEarlyData + } + return m, nil +} + +// GetSessionTicket generates a new session ticket. +// It should only be called after the handshake completes. +// It can only be used for servers, and only if the alternative record layer is set. +// The ticket may be nil if config.SessionTicketsDisabled is set, +// or if the client isn't able to receive session tickets. +func (c *Conn) GetSessionTicket(appData []byte) ([]byte, error) { + if c.isClient || !c.isHandshakeComplete.Load() || c.extraConfig == nil || c.extraConfig.AlternativeRecordLayer == nil { + return nil, errors.New("GetSessionTicket is only valid for servers after completion of the handshake, and if an alternative record layer is set.") + } + if c.config.SessionTicketsDisabled { + return nil, nil + } + + m, err := c.getSessionTicketMsg(appData) + if err != nil { + return nil, err + } + return m.marshal() +} diff --git a/vendor/github.com/quic-go/qtls-go1-20/tls.go b/vendor/github.com/quic-go/qtls-go1-20/tls.go index 47eed0855..42207c235 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/tls.go +++ b/vendor/github.com/quic-go/qtls-go1-20/tls.go @@ -31,10 +31,11 @@ import ( // using conn as the underlying transport. // The configuration config must be non-nil and must include // at least one certificate or else set GetCertificate. -func Server(conn net.Conn, config *Config) *Conn { +func Server(conn net.Conn, config *Config, extraConfig *ExtraConfig) *Conn { c := &Conn{ - conn: conn, - config: fromConfig(config), + conn: conn, + config: fromConfig(config), + extraConfig: extraConfig, } c.handshakeFn = c.serverHandshake return c @@ -44,11 +45,12 @@ func Server(conn net.Conn, config *Config) *Conn { // using conn as the underlying transport. // The config cannot be nil: users must set either ServerName or // InsecureSkipVerify in the config. -func Client(conn net.Conn, config *Config) *Conn { +func Client(conn net.Conn, config *Config, extraConfig *ExtraConfig) *Conn { c := &Conn{ - conn: conn, - config: fromConfig(config), - isClient: true, + conn: conn, + config: fromConfig(config), + extraConfig: extraConfig, + isClient: true, } c.handshakeFn = c.clientHandshake return c @@ -57,7 +59,8 @@ func Client(conn net.Conn, config *Config) *Conn { // A listener implements a network listener (net.Listener) for TLS connections. type listener struct { net.Listener - config *Config + config *Config + extraConfig *ExtraConfig } // Accept waits for and returns the next incoming TLS connection. @@ -67,17 +70,18 @@ func (l *listener) Accept() (net.Conn, error) { if err != nil { return nil, err } - return Server(c, l.config), nil + return Server(c, l.config, l.extraConfig), nil } // NewListener creates a Listener which accepts connections from an inner // Listener and wraps each connection with Server. // The configuration config must be non-nil and must include // at least one certificate or else set GetCertificate. -func NewListener(inner net.Listener, config *Config) net.Listener { +func NewListener(inner net.Listener, config *Config, extraConfig *ExtraConfig) net.Listener { l := new(listener) l.Listener = inner l.config = config + l.extraConfig = extraConfig return l } @@ -85,7 +89,7 @@ func NewListener(inner net.Listener, config *Config) net.Listener { // given network address using net.Listen. // The configuration config must be non-nil and must include // at least one certificate or else set GetCertificate. -func Listen(network, laddr string, config *Config) (net.Listener, error) { +func Listen(network, laddr string, config *Config, extraConfig *ExtraConfig) (net.Listener, error) { if config == nil || len(config.Certificates) == 0 && config.GetCertificate == nil && config.GetConfigForClient == nil { return nil, errors.New("tls: neither Certificates, GetCertificate, nor GetConfigForClient set in Config") @@ -94,7 +98,7 @@ func Listen(network, laddr string, config *Config) (net.Listener, error) { if err != nil { return nil, err } - return NewListener(l, config), nil + return NewListener(l, config, extraConfig), nil } type timeoutError struct{} @@ -113,11 +117,11 @@ func (timeoutError) Temporary() bool { return true } // // DialWithDialer uses context.Background internally; to specify the context, // use Dialer.DialContext with NetDialer set to the desired dialer. -func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) { - return dial(context.Background(), dialer, network, addr, config) +func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config, extraConfig *ExtraConfig) (*Conn, error) { + return dial(context.Background(), dialer, network, addr, config, extraConfig) } -func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config) (*Conn, error) { +func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, config *Config, extraConfig *ExtraConfig) (*Conn, error) { if netDialer.Timeout != 0 { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, netDialer.Timeout) @@ -153,7 +157,7 @@ func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, conf config = c } - conn := Client(rawConn, config) + conn := Client(rawConn, config, extraConfig) if err := conn.HandshakeContext(ctx); err != nil { rawConn.Close() return nil, err @@ -167,8 +171,8 @@ func dial(ctx context.Context, netDialer *net.Dialer, network, addr string, conf // Dial interprets a nil configuration as equivalent to // the zero configuration; see the documentation of Config // for the defaults. -func Dial(network, addr string, config *Config) (*Conn, error) { - return DialWithDialer(new(net.Dialer), network, addr, config) +func Dial(network, addr string, config *Config, extraConfig *ExtraConfig) (*Conn, error) { + return DialWithDialer(new(net.Dialer), network, addr, config, extraConfig) } // Dialer dials TLS connections given a configuration and a Dialer for the @@ -184,6 +188,8 @@ type Dialer struct { // configuration; see the documentation of Config for the // defaults. Config *Config + + ExtraConfig *ExtraConfig } // Dial connects to the given network address and initiates a TLS @@ -214,7 +220,7 @@ func (d *Dialer) netDialer() *net.Dialer { // // The returned Conn, if any, will always be of type *Conn. func (d *Dialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { - c, err := dial(ctx, d.netDialer(), network, addr, d.Config) + c, err := dial(ctx, d.netDialer(), network, addr, d.Config, d.ExtraConfig) if err != nil { // Don't return c (a typed nil) in an interface. return nil, err diff --git a/vendor/github.com/quic-go/qtls-go1-20/unsafe.go b/vendor/github.com/quic-go/qtls-go1-20/unsafe.go index 67a75677c..55fa01b3d 100644 --- a/vendor/github.com/quic-go/qtls-go1-20/unsafe.go +++ b/vendor/github.com/quic-go/qtls-go1-20/unsafe.go @@ -94,8 +94,3 @@ func compareStruct(a, b reflect.Type) bool { } return true } - -// InitSessionTicketKeys triggers the initialization of session ticket keys. -func InitSessionTicketKeys(conf *Config) { - fromConfig(conf).ticketKeys(nil) -} diff --git a/vendor/github.com/quic-go/quic-go/.golangci.yml b/vendor/github.com/quic-go/quic-go/.golangci.yml index 1315759bc..7820be8c9 100644 --- a/vendor/github.com/quic-go/quic-go/.golangci.yml +++ b/vendor/github.com/quic-go/quic-go/.golangci.yml @@ -1,6 +1,4 @@ run: - skip-files: - - internal/handshake/cipher_suite.go linters-settings: depguard: type: blacklist diff --git a/vendor/github.com/quic-go/quic-go/README.md b/vendor/github.com/quic-go/quic-go/README.md index 976a07ccd..53638882a 100644 --- a/vendor/github.com/quic-go/quic-go/README.md +++ b/vendor/github.com/quic-go/quic-go/README.md @@ -4,7 +4,6 @@ [![PkgGoDev](https://pkg.go.dev/badge/github.com/quic-go/quic-go)](https://pkg.go.dev/github.com/quic-go/quic-go) [![Code Coverage](https://img.shields.io/codecov/c/github/quic-go/quic-go/master.svg?style=flat-square)](https://codecov.io/gh/quic-go/quic-go/) -[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/quic-go.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:quic-go) quic-go is an implementation of the QUIC protocol ([RFC 9000](https://datatracker.ietf.org/doc/html/rfc9000), [RFC 9001](https://datatracker.ietf.org/doc/html/rfc9001), [RFC 9002](https://datatracker.ietf.org/doc/html/rfc9002)) in Go. It has support for HTTP/3 ([RFC 9114](https://datatracker.ietf.org/doc/html/rfc9114)), including QPACK ([RFC 9204](https://datatracker.ietf.org/doc/html/rfc9204)). @@ -13,6 +12,10 @@ In addition to these base RFCs, it also implements the following RFCs: * Datagram Packetization Layer Path MTU Discovery (DPLPMTUD, [RFC 8899](https://datatracker.ietf.org/doc/html/rfc8899)) * QUIC Version 2 ([RFC 9369](https://datatracker.ietf.org/doc/html/rfc9369)) +In addition to the RFCs listed above, it currently implements the [IETF QUIC draft-29](https://tools.ietf.org/html/draft-ietf-quic-transport-29). Support for draft-29 will eventually be dropped, as it is phased out of the ecosystem. + +This repository provides both a QUIC implementation, located in the `quic` package, as well as an HTTP/3 implementation, located in the `http3` package. + ## Using QUIC ### Running a Server @@ -33,7 +36,7 @@ go func() { // ... error handling // handle the connection, usually in a new Go routine } -}() +} ``` The listener `ln` can now be used to accept incoming QUIC connections by (repeatedly) calling the `Accept` method (see below for more information on the `quic.Connection`). @@ -133,7 +136,7 @@ The `quic.Transport` contains a few configuration options that don't apply to an #### When the remote Peer closes the Connection -In case the peer closes the QUIC connection, all calls to open streams, accept streams, as well as all methods on streams immediately return an error. Additionally, it is set as cancellation cause of the connection context. Users can use errors assertions to find out what exactly went wrong: +In case the peer closes the QUIC connection, all calls to open streams, accept streams, as well as all methods on streams immediately return an error. Users can use errors assertions to find out what exactly went wrong: * `quic.VersionNegotiationError`: Happens during the handshake, if there is no overlap between our and the remote's supported QUIC versions. * `quic.HandshakeTimeoutError`: Happens if the QUIC handshake doesn't complete within the time specified in `quic.Config.HandshakeTimeout`. @@ -200,13 +203,12 @@ http.Client{ ## Projects using quic-go | Project | Description | Stars | -| --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +|-----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------| | [AdGuardHome](https://github.com/AdguardTeam/AdGuardHome) | Free and open source, powerful network-wide ads & trackers blocking DNS server. | ![GitHub Repo stars](https://img.shields.io/github/stars/AdguardTeam/AdGuardHome?style=flat-square) | | [algernon](https://github.com/xyproto/algernon) | Small self-contained pure-Go web server with Lua, Markdown, HTTP/2, QUIC, Redis and PostgreSQL support | ![GitHub Repo stars](https://img.shields.io/github/stars/xyproto/algernon?style=flat-square) | | [caddy](https://github.com/caddyserver/caddy/) | Fast, multi-platform web server with automatic HTTPS | ![GitHub Repo stars](https://img.shields.io/github/stars/caddyserver/caddy?style=flat-square) | | [cloudflared](https://github.com/cloudflare/cloudflared) | A tunneling daemon that proxies traffic from the Cloudflare network to your origins | ![GitHub Repo stars](https://img.shields.io/github/stars/cloudflare/cloudflared?style=flat-square) | | [go-libp2p](https://github.com/libp2p/go-libp2p) | libp2p implementation in Go, powering [Kubo](https://github.com/ipfs/kubo) (IPFS) and [Lotus](https://github.com/filecoin-project/lotus) (Filecoin), among others | ![GitHub Repo stars](https://img.shields.io/github/stars/libp2p/go-libp2p?style=flat-square) | -| [Hysteria](https://github.com/apernet/hysteria) | A powerful, lightning fast and censorship resistant proxy | ![GitHub Repo stars](https://img.shields.io/github/stars/apernet/hysteria?style=flat-square) | | [Mercure](https://github.com/dunglas/mercure) | An open, easy, fast, reliable and battery-efficient solution for real-time communications | ![GitHub Repo stars](https://img.shields.io/github/stars/dunglas/mercure?style=flat-square) | | [OONI Probe](https://github.com/ooni/probe-cli) | Next generation OONI Probe. Library and CLI tool. | ![GitHub Repo stars](https://img.shields.io/github/stars/ooni/probe-cli?style=flat-square) | | [syncthing](https://github.com/syncthing/syncthing/) | Open Source Continuous File Synchronization | ![GitHub Repo stars](https://img.shields.io/github/stars/syncthing/syncthing?style=flat-square) | @@ -222,8 +224,7 @@ quic-go always aims to support the latest two Go releases. ### Dependency on forked crypto/tls -Since the standard library didn't provide any QUIC APIs before the Go 1.21 release, we had to fork crypto/tls to add the required APIs ourselves: [qtls for Go 1.20](https://github.com/quic-go/qtls-go1-20). -This had led to a lot of pain in the Go ecosystem, and we're happy that we can rely on Go 1.21 going forward. +Since the standard library didn't provide any QUIC APIs before the Go 1.21 release, we had to fork crypto/tls to add the required APIs ourselves: [qtls for Go 1.20](https://github.com/quic-go/qtls-go1-20) and [qtls for Go 1.19](https://github.com/quic-go/qtls-go1-19). This had led to a lot of pain in the Go ecosystem, and we're happy that we can rely on Go 1.21 going forward. ## Contributing diff --git a/vendor/github.com/quic-go/quic-go/client.go b/vendor/github.com/quic-go/quic-go/client.go index e0ae5d3cb..4dfacb50d 100644 --- a/vendor/github.com/quic-go/quic-go/client.go +++ b/vendor/github.com/quic-go/quic-go/client.go @@ -34,7 +34,7 @@ type client struct { conn quicConn - tracer *logging.ConnectionTracer + tracer logging.ConnectionTracer tracingID uint64 logger utils.Logger } @@ -55,11 +55,11 @@ func DialAddr(ctx context.Context, addr string, tlsConf *tls.Config, conf *Confi if err != nil { return nil, err } - tr, err := setupTransport(udpConn, tlsConf, true) + dl, err := setupTransport(udpConn, tlsConf, true) if err != nil { return nil, err } - return tr.dial(ctx, udpAddr, addr, tlsConf, conf, false) + return dl.Dial(ctx, udpAddr, tlsConf, conf) } // DialAddrEarly establishes a new 0-RTT QUIC connection to a server. @@ -73,13 +73,13 @@ func DialAddrEarly(ctx context.Context, addr string, tlsConf *tls.Config, conf * if err != nil { return nil, err } - tr, err := setupTransport(udpConn, tlsConf, true) + dl, err := setupTransport(udpConn, tlsConf, true) if err != nil { return nil, err } - conn, err := tr.dial(ctx, udpAddr, addr, tlsConf, conf, true) + conn, err := dl.DialEarly(ctx, udpAddr, tlsConf, conf) if err != nil { - tr.Close() + dl.Close() return nil, err } return conn, nil @@ -153,7 +153,7 @@ func dial( if c.config.Tracer != nil { c.tracer = c.config.Tracer(context.WithValue(ctx, ConnectionTracingKey, c.tracingID), protocol.PerspectiveClient, c.destConnID) } - if c.tracer != nil && c.tracer.StartedConnection != nil { + if c.tracer != nil { c.tracer.StartedConnection(c.sendConn.LocalAddr(), c.sendConn.RemoteAddr(), c.srcConnID, c.destConnID) } if err := c.dial(ctx); err != nil { @@ -163,6 +163,12 @@ func dial( } func newClient(sendConn sendConn, connIDGenerator ConnectionIDGenerator, config *Config, tlsConf *tls.Config, onClose func(), use0RTT bool) (*client, error) { + if tlsConf == nil { + tlsConf = &tls.Config{} + } else { + tlsConf = tlsConf.Clone() + } + srcConnID, err := connIDGenerator.GenerateConnectionID() if err != nil { return nil, err @@ -233,7 +239,7 @@ func (c *client) dial(ctx context.Context) error { select { case <-ctx.Done(): c.conn.shutdown() - return context.Cause(ctx) + return ctx.Err() case err := <-errorChan: return err case recreateErr := <-recreateChan: diff --git a/vendor/github.com/quic-go/quic-go/codecov.yml b/vendor/github.com/quic-go/quic-go/codecov.yml index a24c7a15e..074d98325 100644 --- a/vendor/github.com/quic-go/quic-go/codecov.yml +++ b/vendor/github.com/quic-go/quic-go/codecov.yml @@ -1,10 +1,18 @@ coverage: round: nearest ignore: + - streams_map_incoming_bidi.go + - streams_map_incoming_uni.go + - streams_map_outgoing_bidi.go + - streams_map_outgoing_uni.go - http3/gzip_reader.go - interop/ - - internal/handshake/cipher_suite.go + - internal/ackhandler/packet_linkedlist.go + - internal/utils/byteinterval_linkedlist.go + - internal/utils/newconnectionid_linkedlist.go + - internal/utils/packetinterval_linkedlist.go - internal/utils/linkedlist/linkedlist.go + - logging/null_tracer.go - fuzzing/ - metrics/ status: diff --git a/vendor/github.com/quic-go/quic-go/config.go b/vendor/github.com/quic-go/quic-go/config.go index 49b9fc3f0..59df4cfd9 100644 --- a/vendor/github.com/quic-go/quic-go/config.go +++ b/vendor/github.com/quic-go/quic-go/config.go @@ -6,6 +6,7 @@ import ( "time" "github.com/quic-go/quic-go/internal/protocol" + "github.com/quic-go/quic-go/internal/utils" "github.com/quic-go/quic-go/quicvarint" ) @@ -16,11 +17,7 @@ func (c *Config) Clone() *Config { } func (c *Config) handshakeTimeout() time.Duration { - return 2 * c.HandshakeIdleTimeout -} - -func (c *Config) maxRetryTokenAge() time.Duration { - return c.handshakeTimeout() + return utils.Max(protocol.DefaultHandshakeTimeout, 2*c.HandshakeIdleTimeout) } func validateConfig(config *Config) error { @@ -53,6 +50,12 @@ func validateConfig(config *Config) error { // it may be called with nil func populateServerConfig(config *Config) *Config { config = populateConfig(config) + if config.MaxTokenAge == 0 { + config.MaxTokenAge = protocol.TokenValidity + } + if config.MaxRetryTokenAge == 0 { + config.MaxRetryTokenAge = protocol.RetryTokenValidity + } if config.RequireAddressValidation == nil { config.RequireAddressValidation = func(net.Addr) bool { return false } } @@ -107,23 +110,26 @@ func populateConfig(config *Config) *Config { } return &Config{ - GetConfigForClient: config.GetConfigForClient, - Versions: versions, - HandshakeIdleTimeout: handshakeIdleTimeout, - MaxIdleTimeout: idleTimeout, - RequireAddressValidation: config.RequireAddressValidation, - KeepAlivePeriod: config.KeepAlivePeriod, - InitialStreamReceiveWindow: initialStreamReceiveWindow, - MaxStreamReceiveWindow: maxStreamReceiveWindow, - InitialConnectionReceiveWindow: initialConnectionReceiveWindow, - MaxConnectionReceiveWindow: maxConnectionReceiveWindow, - AllowConnectionWindowIncrease: config.AllowConnectionWindowIncrease, - MaxIncomingStreams: maxIncomingStreams, - MaxIncomingUniStreams: maxIncomingUniStreams, - TokenStore: config.TokenStore, - EnableDatagrams: config.EnableDatagrams, - DisablePathMTUDiscovery: config.DisablePathMTUDiscovery, - Allow0RTT: config.Allow0RTT, - Tracer: config.Tracer, + GetConfigForClient: config.GetConfigForClient, + Versions: versions, + HandshakeIdleTimeout: handshakeIdleTimeout, + MaxIdleTimeout: idleTimeout, + MaxTokenAge: config.MaxTokenAge, + MaxRetryTokenAge: config.MaxRetryTokenAge, + RequireAddressValidation: config.RequireAddressValidation, + KeepAlivePeriod: config.KeepAlivePeriod, + InitialStreamReceiveWindow: initialStreamReceiveWindow, + MaxStreamReceiveWindow: maxStreamReceiveWindow, + InitialConnectionReceiveWindow: initialConnectionReceiveWindow, + MaxConnectionReceiveWindow: maxConnectionReceiveWindow, + AllowConnectionWindowIncrease: config.AllowConnectionWindowIncrease, + MaxIncomingStreams: maxIncomingStreams, + MaxIncomingUniStreams: maxIncomingUniStreams, + TokenStore: config.TokenStore, + EnableDatagrams: config.EnableDatagrams, + DisablePathMTUDiscovery: config.DisablePathMTUDiscovery, + DisableVersionNegotiationPackets: config.DisableVersionNegotiationPackets, + Allow0RTT: config.Allow0RTT, + Tracer: config.Tracer, } } diff --git a/vendor/github.com/quic-go/quic-go/conn_id_manager.go b/vendor/github.com/quic-go/quic-go/conn_id_manager.go index ba65aec04..7840cdbf4 100644 --- a/vendor/github.com/quic-go/quic-go/conn_id_manager.go +++ b/vendor/github.com/quic-go/quic-go/conn_id_manager.go @@ -174,13 +174,13 @@ func (h *connIDManager) ChangeInitialConnID(newConnID protocol.ConnectionID) { h.activeConnectionID = newConnID } -// is called when the server provides a stateless reset token in the transport parameters +// SetStatelessResetToken is called when the server provides a stateless reset token in the transport parameters func (h *connIDManager) SetStatelessResetToken(token protocol.StatelessResetToken) { - if h.activeSequenceNumber != 0 { - panic("expected first connection ID to have sequence number 0") + // Only set the stateless reset token if we're still using the connection ID with sequence number 0. + if h.activeSequenceNumber == 0 { + h.activeStatelessResetToken = &token + h.addStatelessResetToken(token) } - h.activeStatelessResetToken = &token - h.addStatelessResetToken(token) } func (h *connIDManager) SentPacket() { diff --git a/vendor/github.com/quic-go/quic-go/connection.go b/vendor/github.com/quic-go/quic-go/connection.go index 09b522a9e..c544b591a 100644 --- a/vendor/github.com/quic-go/quic-go/connection.go +++ b/vendor/github.com/quic-go/quic-go/connection.go @@ -52,13 +52,11 @@ type streamManager interface { } type cryptoStreamHandler interface { - StartHandshake() error + RunHandshake() ChangeConnectionID(protocol.ConnectionID) SetLargest1RTTAcked(protocol.PacketNumber) error SetHandshakeConfirmed() GetSessionTicket() ([]byte, error) - NextEvent() handshake.Event - DiscardInitialKeys() io.Closer ConnectionState() handshake.ConnectionState } @@ -98,6 +96,18 @@ type connRunner interface { RemoveResetToken(protocol.StatelessResetToken) } +type handshakeRunner struct { + onReceivedParams func(*wire.TransportParameters) + onError func(error) + dropKeys func(protocol.EncryptionLevel) + onHandshakeComplete func() +} + +func (r *handshakeRunner) OnReceivedParams(tp *wire.TransportParameters) { r.onReceivedParams(tp) } +func (r *handshakeRunner) OnError(e error) { r.onError(e) } +func (r *handshakeRunner) DropKeys(el protocol.EncryptionLevel) { r.dropKeys(el) } +func (r *handshakeRunner) OnHandshakeComplete() { r.onHandshakeComplete() } + type closeError struct { err error remote bool @@ -155,8 +165,6 @@ type connection struct { packer packer mtuDiscoverer mtuDiscoverer // initialized when the handshake completes - initialStream cryptoStream - handshakeStream cryptoStream oneRTTStream cryptoStream // only set for the server cryptoStreamHandler cryptoStreamHandler @@ -168,17 +176,19 @@ type connection struct { closeChan chan closeError ctx context.Context - ctxCancel context.CancelCauseFunc + ctxCancel context.CancelFunc handshakeCtx context.Context handshakeCtxCancel context.CancelFunc undecryptablePackets []receivedPacket // undecryptable packets, waiting for a change in encryption level undecryptablePacketsToProcess []receivedPacket - earlyConnReadyChan chan struct{} - sentFirstPacket bool - handshakeComplete bool - handshakeConfirmed bool + clientHelloWritten <-chan *wire.TransportParameters + earlyConnReadyChan chan struct{} + handshakeCompleteChan chan struct{} // is closed when the handshake completes + sentFirstPacket bool + handshakeComplete bool + handshakeConfirmed bool receivedRetry bool versionNegotiated bool @@ -208,7 +218,7 @@ type connection struct { connState ConnectionState logID string - tracer *logging.ConnectionTracer + tracer logging.ConnectionTracer logger utils.Logger } @@ -232,22 +242,23 @@ var newConnection = func( tlsConf *tls.Config, tokenGenerator *handshake.TokenGenerator, clientAddressValidated bool, - tracer *logging.ConnectionTracer, + tracer logging.ConnectionTracer, tracingID uint64, logger utils.Logger, v protocol.VersionNumber, ) quicConn { s := &connection{ - conn: conn, - config: conf, - handshakeDestConnID: destConnID, - srcConnIDLen: srcConnID.Len(), - tokenGenerator: tokenGenerator, - oneRTTStream: newCryptoStream(), - perspective: protocol.PerspectiveServer, - tracer: tracer, - logger: logger, - version: v, + conn: conn, + config: conf, + handshakeDestConnID: destConnID, + srcConnIDLen: srcConnID.Len(), + tokenGenerator: tokenGenerator, + oneRTTStream: newCryptoStream(), + perspective: protocol.PerspectiveServer, + handshakeCompleteChan: make(chan struct{}), + tracer: tracer, + logger: logger, + version: v, } if origDestConnID.Len() > 0 { s.logID = origDestConnID.String() @@ -272,18 +283,19 @@ var newConnection = func( connIDGenerator, ) s.preSetup() - s.ctx, s.ctxCancel = context.WithCancelCause(context.WithValue(context.Background(), ConnectionTracingKey, tracingID)) + s.ctx, s.ctxCancel = context.WithCancel(context.WithValue(context.Background(), ConnectionTracingKey, tracingID)) s.sentPacketHandler, s.receivedPacketHandler = ackhandler.NewAckHandler( 0, getMaxPacketSize(s.conn.RemoteAddr()), s.rttStats, clientAddressValidated, - s.conn.capabilities().ECN, s.perspective, s.tracer, s.logger, ) s.mtuDiscoverer = newMTUDiscoverer(s.rttStats, getMaxPacketSize(s.conn.RemoteAddr()), s.sentPacketHandler.SetMaxDatagramSize) + initialStream := newCryptoStream() + handshakeStream := newCryptoStream() params := &wire.TransportParameters{ InitialMaxStreamDataBidiLocal: protocol.ByteCount(s.config.InitialStreamReceiveWindow), InitialMaxStreamDataBidiRemote: protocol.ByteCount(s.config.InitialStreamReceiveWindow), @@ -311,14 +323,25 @@ var newConnection = func( } else { params.MaxDatagramFrameSize = protocol.InvalidByteCount } - if s.tracer != nil && s.tracer.SentTransportParameters != nil { + if s.tracer != nil { s.tracer.SentTransportParameters(params) } cs := handshake.NewCryptoSetupServer( + initialStream, + handshakeStream, clientDestConnID, conn.LocalAddr(), conn.RemoteAddr(), params, + &handshakeRunner{ + onReceivedParams: s.handleTransportParameters, + onError: s.closeLocal, + dropKeys: s.dropEncryptionLevel, + onHandshakeComplete: func() { + runner.Retire(clientDestConnID) + close(s.handshakeCompleteChan) + }, + }, tlsConf, conf.Allow0RTT, s.rttStats, @@ -327,9 +350,9 @@ var newConnection = func( s.version, ) s.cryptoStreamHandler = cs - s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective) + s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, initialStream, handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective) s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen) - s.cryptoStreamManager = newCryptoStreamManager(cs, s.initialStream, s.handshakeStream, s.oneRTTStream) + s.cryptoStreamManager = newCryptoStreamManager(cs, initialStream, handshakeStream, s.oneRTTStream) return s } @@ -345,23 +368,24 @@ var newClientConnection = func( initialPacketNumber protocol.PacketNumber, enable0RTT bool, hasNegotiatedVersion bool, - tracer *logging.ConnectionTracer, + tracer logging.ConnectionTracer, tracingID uint64, logger utils.Logger, v protocol.VersionNumber, ) quicConn { s := &connection{ - conn: conn, - config: conf, - origDestConnID: destConnID, - handshakeDestConnID: destConnID, - srcConnIDLen: srcConnID.Len(), - perspective: protocol.PerspectiveClient, - logID: destConnID.String(), - logger: logger, - tracer: tracer, - versionNegotiated: hasNegotiatedVersion, - version: v, + conn: conn, + config: conf, + origDestConnID: destConnID, + handshakeDestConnID: destConnID, + srcConnIDLen: srcConnID.Len(), + perspective: protocol.PerspectiveClient, + handshakeCompleteChan: make(chan struct{}), + logID: destConnID.String(), + logger: logger, + tracer: tracer, + versionNegotiated: hasNegotiatedVersion, + version: v, } s.connIDManager = newConnIDManager( destConnID, @@ -381,19 +405,19 @@ var newClientConnection = func( connIDGenerator, ) s.preSetup() - s.ctx, s.ctxCancel = context.WithCancelCause(context.WithValue(context.Background(), ConnectionTracingKey, tracingID)) + s.ctx, s.ctxCancel = context.WithCancel(context.WithValue(context.Background(), ConnectionTracingKey, tracingID)) s.sentPacketHandler, s.receivedPacketHandler = ackhandler.NewAckHandler( initialPacketNumber, getMaxPacketSize(s.conn.RemoteAddr()), s.rttStats, - false, // has no effect - s.conn.capabilities().ECN, + false, /* has no effect */ s.perspective, s.tracer, s.logger, ) s.mtuDiscoverer = newMTUDiscoverer(s.rttStats, getMaxPacketSize(s.conn.RemoteAddr()), s.sentPacketHandler.SetMaxDatagramSize) - oneRTTStream := newCryptoStream() + initialStream := newCryptoStream() + handshakeStream := newCryptoStream() params := &wire.TransportParameters{ InitialMaxStreamDataBidiRemote: protocol.ByteCount(s.config.InitialStreamReceiveWindow), InitialMaxStreamDataBidiLocal: protocol.ByteCount(s.config.InitialStreamReceiveWindow), @@ -418,12 +442,22 @@ var newClientConnection = func( } else { params.MaxDatagramFrameSize = protocol.InvalidByteCount } - if s.tracer != nil && s.tracer.SentTransportParameters != nil { + if s.tracer != nil { s.tracer.SentTransportParameters(params) } - cs := handshake.NewCryptoSetupClient( + cs, clientHelloWritten := handshake.NewCryptoSetupClient( + initialStream, + handshakeStream, destConnID, + conn.LocalAddr(), + conn.RemoteAddr(), params, + &handshakeRunner{ + onReceivedParams: s.handleTransportParameters, + onError: s.closeLocal, + dropKeys: s.dropEncryptionLevel, + onHandshakeComplete: func() { close(s.handshakeCompleteChan) }, + }, tlsConf, enable0RTT, s.rttStats, @@ -431,10 +465,11 @@ var newClientConnection = func( logger, s.version, ) + s.clientHelloWritten = clientHelloWritten s.cryptoStreamHandler = cs - s.cryptoStreamManager = newCryptoStreamManager(cs, s.initialStream, s.handshakeStream, oneRTTStream) + s.cryptoStreamManager = newCryptoStreamManager(cs, initialStream, handshakeStream, newCryptoStream()) s.unpacker = newPacketUnpacker(cs, s.srcConnIDLen) - s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, s.initialStream, s.handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective) + s.packer = newPacketPacker(srcConnID, s.connIDManager.Get, initialStream, handshakeStream, s.sentPacketHandler, s.retransmissionQueue, cs, s.framer, s.receivedPacketHandler, s.datagramQueue, s.perspective) if len(tlsConf.ServerName) > 0 { s.tokenStoreKey = tlsConf.ServerName } else { @@ -449,8 +484,6 @@ var newClientConnection = func( } func (s *connection) preSetup() { - s.initialStream = newCryptoStream() - s.handshakeStream = newCryptoStream() s.sendQueue = newSendQueue(s.conn) s.retransmissionQueue = newRetransmissionQueue() s.frameParser = wire.NewFrameParser(s.config.EnableDatagrams) @@ -493,19 +526,15 @@ func (s *connection) preSetup() { // run the connection main loop func (s *connection) run() error { - var closeErr closeError - defer func() { - s.ctxCancel(closeErr.err) - }() + defer s.ctxCancel() s.timer = *newTimer() - if err := s.cryptoStreamHandler.StartHandshake(); err != nil { - return err - } - if err := s.handleHandshakeEvents(); err != nil { - return err - } + handshaking := make(chan struct{}) + go func() { + defer close(handshaking) + s.cryptoStreamHandler.RunHandshake() + }() go func() { if err := s.sendQueue.Run(); err != nil { s.destroyImpl(err) @@ -513,10 +542,23 @@ func (s *connection) run() error { }() if s.perspective == protocol.PerspectiveClient { - s.scheduleSending() // so the ClientHello actually gets sent + select { + case zeroRTTParams := <-s.clientHelloWritten: + s.scheduleSending() + if zeroRTTParams != nil { + s.restoreTransportParameters(zeroRTTParams) + close(s.earlyConnReadyChan) + } + case closeErr := <-s.closeChan: + // put the close error back into the channel, so that the run loop can receive it + s.closeChan <- closeErr + } } - var sendQueueAvailable <-chan struct{} + var ( + closeErr closeError + sendQueueAvailable <-chan struct{} + ) runLoop: for { @@ -524,6 +566,8 @@ runLoop: select { case closeErr = <-s.closeChan: break runLoop + case <-s.handshakeCompleteChan: + s.handleHandshakeComplete() default: } @@ -594,6 +638,8 @@ runLoop: if !wasProcessed { continue } + case <-s.handshakeCompleteChan: + s.handleHandshakeComplete() } } @@ -640,12 +686,11 @@ runLoop: } s.cryptoStreamHandler.Close() + <-handshaking s.sendQueue.Close() // close the send queue before sending the CONNECTION_CLOSE s.handleCloseError(&closeErr) - if s.tracer != nil && s.tracer.Close != nil { - if e := (&errCloseForRecreating{}); !errors.As(closeErr.err, &e) { - s.tracer.Close() - } + if e := (&errCloseForRecreating{}); !errors.As(closeErr.err, &e) && s.tracer != nil { + s.tracer.Close() } s.logger.Infof("Connection %s closed.", s.logID) s.timer.Stop() @@ -672,10 +717,7 @@ func (s *connection) supportsDatagrams() bool { func (s *connection) ConnectionState() ConnectionState { s.connStateMutex.Lock() defer s.connStateMutex.Unlock() - cs := s.cryptoStreamHandler.ConnectionState() - s.connState.TLS = cs.ConnectionState - s.connState.Used0RTT = cs.Used0RTT - s.connState.GSO = s.conn.capabilities().GSO + s.connState.TLS = s.cryptoStreamHandler.ConnectionState() return s.connState } @@ -722,32 +764,29 @@ func (s *connection) idleTimeoutStartTime() time.Time { return utils.MaxTime(s.lastPacketReceivedTime, s.firstAckElicitingPacketAfterIdleSentTime) } -func (s *connection) handleHandshakeComplete() error { +func (s *connection) handleHandshakeComplete() { + s.handshakeComplete = true + s.handshakeCompleteChan = nil // prevent this case from ever being selected again defer s.handshakeCtxCancel() // Once the handshake completes, we have derived 1-RTT keys. - // There's no point in queueing undecryptable packets for later decryption anymore. + // There's no point in queueing undecryptable packets for later decryption any more. s.undecryptablePackets = nil s.connIDManager.SetHandshakeComplete() s.connIDGenerator.SetHandshakeComplete() - // The server applies transport parameters right away, but the client side has to wait for handshake completion. - // During a 0-RTT connection, the client is only allowed to use the new transport parameters for 1-RTT packets. if s.perspective == protocol.PerspectiveClient { s.applyTransportParameters() - return nil + return } - // All these only apply to the server side. - if err := s.handleHandshakeConfirmed(); err != nil { - return err - } + s.handleHandshakeConfirmed() ticket, err := s.cryptoStreamHandler.GetSessionTicket() if err != nil { - return err + s.closeLocal(err) } - if ticket != nil { // may be nil if session tickets are disabled via tls.Config.SessionTicketsDisabled + if ticket != nil { s.oneRTTStream.Write(ticket) for s.oneRTTStream.HasData() { s.queueControlFrame(s.oneRTTStream.PopCryptoFrame(protocol.MaxPostHandshakeCryptoFrameSize)) @@ -755,18 +794,13 @@ func (s *connection) handleHandshakeComplete() error { } token, err := s.tokenGenerator.NewToken(s.conn.RemoteAddr()) if err != nil { - return err + s.closeLocal(err) } s.queueControlFrame(&wire.NewTokenFrame{Token: token}) s.queueControlFrame(&wire.HandshakeDoneFrame{}) - return nil } -func (s *connection) handleHandshakeConfirmed() error { - if err := s.dropEncryptionLevel(protocol.EncryptionHandshake); err != nil { - return err - } - +func (s *connection) handleHandshakeConfirmed() { s.handshakeConfirmed = true s.sentPacketHandler.SetHandshakeConfirmed() s.cryptoStreamHandler.SetHandshakeConfirmed() @@ -778,7 +812,6 @@ func (s *connection) handleHandshakeConfirmed() error { } s.mtuDiscoverer.Start(utils.Min(maxPacketSize, protocol.MaxPacketBufferSize)) } - return nil } func (s *connection) handlePacketImpl(rp receivedPacket) bool { @@ -803,14 +836,14 @@ func (s *connection) handlePacketImpl(rp receivedPacket) bool { var err error destConnID, err = wire.ParseConnectionID(p.data, s.srcConnIDLen) if err != nil { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.ByteCount(len(data)), logging.PacketDropHeaderParseError) } s.logger.Debugf("error parsing packet, couldn't parse connection ID: %s", err) break } if destConnID != lastConnID { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, protocol.ByteCount(len(data)), logging.PacketDropUnknownConnectionID) } s.logger.Debugf("coalesced packet has different destination connection ID: %s, expected %s", destConnID, lastConnID) @@ -821,7 +854,7 @@ func (s *connection) handlePacketImpl(rp receivedPacket) bool { if wire.IsLongHeaderPacket(p.data[0]) { hdr, packetData, rest, err := wire.ParsePacket(p.data) if err != nil { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { dropReason := logging.PacketDropHeaderParseError if err == wire.ErrUnsupportedVersion { dropReason = logging.PacketDropUnsupportedVersion @@ -834,7 +867,7 @@ func (s *connection) handlePacketImpl(rp receivedPacket) bool { lastConnID = hdr.DestConnectionID if hdr.Version != s.version { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeFromHeader(hdr), protocol.ByteCount(len(data)), logging.PacketDropUnexpectedVersion) } s.logger.Debugf("Dropping packet with version %x. Expected %x.", hdr.Version, s.version) @@ -893,14 +926,14 @@ func (s *connection) handleShortHeaderPacket(p receivedPacket, destConnID protoc if s.receivedPacketHandler.IsPotentiallyDuplicate(pn, protocol.Encryption1RTT) { s.logger.Debugf("Dropping (potentially) duplicate packet.") - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketType1RTT, p.Size(), logging.PacketDropDuplicate) } return false } var log func([]logging.Frame) - if s.tracer != nil && s.tracer.ReceivedShortHeaderPacket != nil { + if s.tracer != nil { log = func(frames []logging.Frame) { s.tracer.ReceivedShortHeaderPacket( &logging.ShortHeader{ @@ -910,7 +943,6 @@ func (s *connection) handleShortHeaderPacket(p receivedPacket, destConnID protoc KeyPhase: keyPhase, }, p.Size(), - p.ecn, frames, ) } @@ -933,13 +965,13 @@ func (s *connection) handleLongHeaderPacket(p receivedPacket, hdr *wire.Header) }() if hdr.Type == protocol.PacketTypeRetry { - return s.handleRetryPacket(hdr, p.data, p.rcvTime) + return s.handleRetryPacket(hdr, p.data) } // The server can change the source connection ID with the first Handshake packet. // After this, all packets with a different source connection have to be ignored. if s.receivedFirstPacket && hdr.Type == protocol.PacketTypeInitial && hdr.SrcConnectionID != s.handshakeDestConnID { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeInitial, p.Size(), logging.PacketDropUnknownConnectionID) } s.logger.Debugf("Dropping Initial packet (%d bytes) with unexpected source connection ID: %s (expected %s)", p.Size(), hdr.SrcConnectionID, s.handshakeDestConnID) @@ -947,7 +979,7 @@ func (s *connection) handleLongHeaderPacket(p receivedPacket, hdr *wire.Header) } // drop 0-RTT packets, if we are a client if s.perspective == protocol.PerspectiveClient && hdr.Type == protocol.PacketType0RTT { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketType0RTT, p.Size(), logging.PacketDropKeyUnavailable) } return false @@ -966,7 +998,7 @@ func (s *connection) handleLongHeaderPacket(p receivedPacket, hdr *wire.Header) if s.receivedPacketHandler.IsPotentiallyDuplicate(packet.hdr.PacketNumber, packet.encryptionLevel) { s.logger.Debugf("Dropping (potentially) duplicate packet.") - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeFromHeader(hdr), p.Size(), logging.PacketDropDuplicate) } return false @@ -982,7 +1014,7 @@ func (s *connection) handleLongHeaderPacket(p receivedPacket, hdr *wire.Header) func (s *connection) handleUnpackError(err error, p receivedPacket, pt logging.PacketType) (wasQueued bool) { switch err { case handshake.ErrKeysDropped: - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(pt, p.Size(), logging.PacketDropKeyUnavailable) } s.logger.Debugf("Dropping %s packet (%d bytes) because we already dropped the keys.", pt, p.Size()) @@ -998,7 +1030,7 @@ func (s *connection) handleUnpackError(err error, p receivedPacket, pt logging.P }) case handshake.ErrDecryptionFailed: // This might be a packet injected by an attacker. Drop it. - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(pt, p.Size(), logging.PacketDropPayloadDecryptError) } s.logger.Debugf("Dropping %s packet (%d bytes) that could not be unpacked. Error: %s", pt, p.Size(), err) @@ -1006,7 +1038,7 @@ func (s *connection) handleUnpackError(err error, p receivedPacket, pt logging.P var headerErr *headerParseError if errors.As(err, &headerErr) { // This might be a packet injected by an attacker. Drop it. - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(pt, p.Size(), logging.PacketDropHeaderParseError) } s.logger.Debugf("Dropping %s packet (%d bytes) for which we couldn't unpack the header. Error: %s", pt, p.Size(), err) @@ -1019,16 +1051,16 @@ func (s *connection) handleUnpackError(err error, p receivedPacket, pt logging.P return false } -func (s *connection) handleRetryPacket(hdr *wire.Header, data []byte, rcvTime time.Time) bool /* was this a valid Retry */ { +func (s *connection) handleRetryPacket(hdr *wire.Header, data []byte) bool /* was this a valid Retry */ { if s.perspective == protocol.PerspectiveServer { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket) } s.logger.Debugf("Ignoring Retry.") return false } if s.receivedFirstPacket { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket) } s.logger.Debugf("Ignoring Retry, since we already received a packet.") @@ -1036,7 +1068,7 @@ func (s *connection) handleRetryPacket(hdr *wire.Header, data []byte, rcvTime ti } destConnID := s.connIDManager.Get() if hdr.SrcConnectionID == destConnID { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.ByteCount(len(data)), logging.PacketDropUnexpectedPacket) } s.logger.Debugf("Ignoring Retry, since the server didn't change the Source Connection ID.") @@ -1051,7 +1083,7 @@ func (s *connection) handleRetryPacket(hdr *wire.Header, data []byte, rcvTime ti tag := handshake.GetRetryIntegrityTag(data[:len(data)-16], destConnID, hdr.Version) if !bytes.Equal(data[len(data)-16:], tag[:]) { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeRetry, protocol.ByteCount(len(data)), logging.PacketDropPayloadDecryptError) } s.logger.Debugf("Ignoring spoofed Retry. Integrity Tag doesn't match.") @@ -1063,12 +1095,12 @@ func (s *connection) handleRetryPacket(hdr *wire.Header, data []byte, rcvTime ti (&wire.ExtendedHeader{Header: *hdr}).Log(s.logger) s.logger.Debugf("Switching destination connection ID to: %s", hdr.SrcConnectionID) } - if s.tracer != nil && s.tracer.ReceivedRetry != nil { + if s.tracer != nil { s.tracer.ReceivedRetry(hdr) } newDestConnID := hdr.SrcConnectionID s.receivedRetry = true - if err := s.sentPacketHandler.ResetForRetry(rcvTime); err != nil { + if err := s.sentPacketHandler.ResetForRetry(); err != nil { s.closeLocal(err) return false } @@ -1084,7 +1116,7 @@ func (s *connection) handleRetryPacket(hdr *wire.Header, data []byte, rcvTime ti func (s *connection) handleVersionNegotiationPacket(p receivedPacket) { if s.perspective == protocol.PerspectiveServer || // servers never receive version negotiation packets s.receivedFirstPacket || s.versionNegotiated { // ignore delayed / duplicated version negotiation packets - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, p.Size(), logging.PacketDropUnexpectedPacket) } return @@ -1092,7 +1124,7 @@ func (s *connection) handleVersionNegotiationPacket(p receivedPacket) { src, dest, supportedVersions, err := wire.ParseVersionNegotiationPacket(p.data) if err != nil { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, p.Size(), logging.PacketDropHeaderParseError) } s.logger.Debugf("Error parsing Version Negotiation packet: %s", err) @@ -1101,7 +1133,7 @@ func (s *connection) handleVersionNegotiationPacket(p receivedPacket) { for _, v := range supportedVersions { if v == s.version { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeVersionNegotiation, p.Size(), logging.PacketDropUnexpectedVersion) } // The Version Negotiation packet contains the version that we offered. @@ -1111,7 +1143,7 @@ func (s *connection) handleVersionNegotiationPacket(p receivedPacket) { } s.logger.Infof("Received a Version Negotiation packet. Supported Versions: %s", supportedVersions) - if s.tracer != nil && s.tracer.ReceivedVersionNegotiationPacket != nil { + if s.tracer != nil { s.tracer.ReceivedVersionNegotiationPacket(dest, src, supportedVersions) } newVersion, ok := protocol.ChooseSupportedVersion(s.config.Versions, supportedVersions) @@ -1123,7 +1155,7 @@ func (s *connection) handleVersionNegotiationPacket(p receivedPacket) { s.logger.Infof("No compatible QUIC version found.") return } - if s.tracer != nil && s.tracer.NegotiatedVersion != nil { + if s.tracer != nil { s.tracer.NegotiatedVersion(newVersion, s.config.Versions, supportedVersions) } @@ -1143,7 +1175,7 @@ func (s *connection) handleUnpackedLongHeaderPacket( ) error { if !s.receivedFirstPacket { s.receivedFirstPacket = true - if !s.versionNegotiated && s.tracer != nil && s.tracer.NegotiatedVersion != nil { + if !s.versionNegotiated && s.tracer != nil { var clientVersions, serverVersions []protocol.VersionNumber switch s.perspective { case protocol.PerspectiveClient: @@ -1170,7 +1202,7 @@ func (s *connection) handleUnpackedLongHeaderPacket( s.handshakeDestConnID = packet.hdr.SrcConnectionID s.connIDManager.ChangeInitialConnID(packet.hdr.SrcConnectionID) } - if s.tracer != nil && s.tracer.StartedConnection != nil { + if s.tracer != nil { s.tracer.StartedConnection( s.conn.LocalAddr(), s.conn.RemoteAddr(), @@ -1181,22 +1213,14 @@ func (s *connection) handleUnpackedLongHeaderPacket( } } - if s.perspective == protocol.PerspectiveServer && packet.encryptionLevel == protocol.EncryptionHandshake { - // On the server side, Initial keys are dropped as soon as the first Handshake packet is received. - // See Section 4.9.1 of RFC 9001. - if err := s.dropEncryptionLevel(protocol.EncryptionInitial); err != nil { - return err - } - } - s.lastPacketReceivedTime = rcvTime s.firstAckElicitingPacketAfterIdleSentTime = time.Time{} s.keepAlivePingSent = false var log func([]logging.Frame) - if s.tracer != nil && s.tracer.ReceivedLongHeaderPacket != nil { + if s.tracer != nil { log = func(frames []logging.Frame) { - s.tracer.ReceivedLongHeaderPacket(packet.hdr, packetSize, ecn, frames) + s.tracer.ReceivedLongHeaderPacket(packet.hdr, packetSize, frames) } } isAckEliciting, err := s.handleFrames(packet.data, packet.hdr.DestConnectionID, packet.encryptionLevel, log) @@ -1237,7 +1261,6 @@ func (s *connection) handleFrames( if log != nil { frames = make([]logging.Frame, 0, 4) } - handshakeWasComplete := s.handshakeComplete var handleErr error for len(data) > 0 { l, frame, err := s.frameParser.ParseNext(data, encLevel, s.version) @@ -1274,17 +1297,6 @@ func (s *connection) handleFrames( return false, handleErr } } - - // Handle completion of the handshake after processing all the frames. - // This ensures that we correctly handle the following case on the server side: - // We receive a Handshake packet that contains the CRYPTO frame that allows us to complete the handshake, - // and an ACK serialized after that CRYPTO frame. In this case, we still want to process the ACK frame. - if !handshakeWasComplete && s.handshakeComplete { - if err := s.handleHandshakeComplete(); err != nil { - return false, err - } - } - return } @@ -1342,7 +1354,7 @@ func (s *connection) handlePacket(p receivedPacket) { select { case s.receivedPackets <- p: default: - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropDOSPrevention) } } @@ -1366,43 +1378,16 @@ func (s *connection) handleConnectionCloseFrame(frame *wire.ConnectionCloseFrame } func (s *connection) handleCryptoFrame(frame *wire.CryptoFrame, encLevel protocol.EncryptionLevel) error { - if err := s.cryptoStreamManager.HandleCryptoFrame(frame, encLevel); err != nil { + encLevelChanged, err := s.cryptoStreamManager.HandleCryptoFrame(frame, encLevel) + if err != nil { return err } - return s.handleHandshakeEvents() -} - -func (s *connection) handleHandshakeEvents() error { - for { - ev := s.cryptoStreamHandler.NextEvent() - var err error - switch ev.Kind { - case handshake.EventNoEvent: - return nil - case handshake.EventHandshakeComplete: - // Don't call handleHandshakeComplete yet. - // It's advantageous to process ACK frames that might be serialized after the CRYPTO frame first. - s.handshakeComplete = true - case handshake.EventReceivedTransportParameters: - err = s.handleTransportParameters(ev.TransportParameters) - case handshake.EventRestoredTransportParameters: - s.restoreTransportParameters(ev.TransportParameters) - close(s.earlyConnReadyChan) - case handshake.EventReceivedReadKeys: - // Queue all packets for decryption that have been undecryptable so far. - s.undecryptablePacketsToProcess = s.undecryptablePackets - s.undecryptablePackets = nil - case handshake.EventDiscard0RTTKeys: - err = s.dropEncryptionLevel(protocol.Encryption0RTT) - case handshake.EventWriteInitialData: - _, err = s.initialStream.Write(ev.Data) - case handshake.EventWriteHandshakeData: - _, err = s.handshakeStream.Write(ev.Data) - } - if err != nil { - return err - } + if encLevelChanged { + // Queue all packets for decryption that have been undecryptable so far. + s.undecryptablePacketsToProcess = s.undecryptablePackets + s.undecryptablePackets = nil } + return nil } func (s *connection) handleStreamFrame(frame *wire.StreamFrame) error { @@ -1497,7 +1482,7 @@ func (s *connection) handleHandshakeDoneFrame() error { } } if !s.handshakeConfirmed { - return s.handleHandshakeConfirmed() + s.handleHandshakeConfirmed() } return nil } @@ -1510,13 +1495,8 @@ func (s *connection) handleAckFrame(frame *wire.AckFrame, encLevel protocol.Encr if !acked1RTTPacket { return nil } - // On the client side: If the packet acknowledged a 1-RTT packet, this confirms the handshake. - // This is only possible if the ACK was sent in a 1-RTT packet. - // This is an optimization over simply waiting for a HANDSHAKE_DONE frame, see section 4.1.2 of RFC 9001. if s.perspective == protocol.PerspectiveClient && !s.handshakeConfirmed { - if err := s.handleHandshakeConfirmed(); err != nil { - return err - } + s.handleHandshakeConfirmed() } return s.cryptoStreamHandler.SetLargest1RTTAcked(frame.LargestAcked()) } @@ -1622,7 +1602,7 @@ func (s *connection) handleCloseError(closeErr *closeError) { s.datagramQueue.CloseWithError(e) } - if s.tracer != nil && s.tracer.ClosedConnection != nil && !errors.As(e, &recreateErr) { + if s.tracer != nil && !errors.As(e, &recreateErr) { s.tracer.ClosedConnection(e) } @@ -1648,24 +1628,21 @@ func (s *connection) handleCloseError(closeErr *closeError) { s.connIDGenerator.ReplaceWithClosed(s.perspective, connClosePacket) } -func (s *connection) dropEncryptionLevel(encLevel protocol.EncryptionLevel) error { - if s.tracer != nil && s.tracer.DroppedEncryptionLevel != nil { - s.tracer.DroppedEncryptionLevel(encLevel) - } +func (s *connection) dropEncryptionLevel(encLevel protocol.EncryptionLevel) { s.sentPacketHandler.DropPackets(encLevel) s.receivedPacketHandler.DropPackets(encLevel) - //nolint:exhaustive // only Initial and 0-RTT need special treatment - switch encLevel { - case protocol.EncryptionInitial: - s.cryptoStreamHandler.DiscardInitialKeys() - case protocol.Encryption0RTT: + if s.tracer != nil { + s.tracer.DroppedEncryptionLevel(encLevel) + } + if encLevel == protocol.Encryption0RTT { s.streamsMap.ResetFor0RTT() if err := s.connFlowController.Reset(); err != nil { - return err + s.closeLocal(err) + } + if err := s.framer.Handle0RTTRejection(); err != nil { + s.closeLocal(err) } - return s.framer.Handle0RTTRejection() } - return s.cryptoStreamManager.Drop(encLevel) } // is called for the client, when restoring transport parameters saved for 0-RTT @@ -1683,24 +1660,14 @@ func (s *connection) restoreTransportParameters(params *wire.TransportParameters s.connStateMutex.Unlock() } -func (s *connection) handleTransportParameters(params *wire.TransportParameters) error { - if s.tracer != nil && s.tracer.ReceivedTransportParameters != nil { - s.tracer.ReceivedTransportParameters(params) - } +func (s *connection) handleTransportParameters(params *wire.TransportParameters) { if err := s.checkTransportParameters(params); err != nil { - return &qerr.TransportError{ + s.closeLocal(&qerr.TransportError{ ErrorCode: qerr.TransportParameterError, ErrorMessage: err.Error(), - } + }) + return } - - if s.perspective == protocol.PerspectiveClient && s.peerParams != nil && s.ConnectionState().Used0RTT && !params.ValidForUpdate(s.peerParams) { - return &qerr.TransportError{ - ErrorCode: qerr.ProtocolViolation, - ErrorMessage: "server sent reduced limits after accepting 0-RTT data", - } - } - s.peerParams = params // On the client side we have to wait for handshake completion. // During a 0-RTT connection, we are only allowed to use the new transport parameters for 1-RTT packets. @@ -1714,13 +1681,15 @@ func (s *connection) handleTransportParameters(params *wire.TransportParameters) s.connStateMutex.Lock() s.connState.SupportsDatagrams = s.supportsDatagrams() s.connStateMutex.Unlock() - return nil } func (s *connection) checkTransportParameters(params *wire.TransportParameters) error { if s.logger.Debug() { s.logger.Debugf("Processed Transport Parameters: %s", params) } + if s.tracer != nil { + s.tracer.ReceivedTransportParameters(params) + } // check the initial_source_connection_id if params.InitialSourceConnectionID != s.handshakeDestConnID { @@ -1836,10 +1805,9 @@ func (s *connection) sendPackets(now time.Time) error { if err != nil { return err } - ecn := s.sentPacketHandler.ECNMode(true) - s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, buf.Len(), false) - s.registerPackedShortHeaderPacket(p, ecn, now) - s.sendQueue.Send(buf, 0, ecn) + s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, buf.Len(), false) + s.registerPackedShortHeaderPacket(p, now) + s.sendQueue.Send(buf, buf.Len()) // This is kind of a hack. We need to trigger sending again somehow. s.pacingDeadline = deadlineSendImmediately return nil @@ -1849,9 +1817,6 @@ func (s *connection) sendPackets(now time.Time) error { s.framer.QueueControlFrame(&wire.DataBlockedFrame{MaximumData: offset}) } s.windowUpdateQueue.QueueAll() - if cf := s.cryptoStreamManager.GetPostHandshakeData(protocol.MaxPostHandshakeCryptoFrameSize); cf != nil { - s.queueControlFrame(cf) - } if !s.handshakeConfirmed { packet, err := s.packer.PackCoalescedPacket(false, s.mtuDiscoverer.CurrentSize(), s.version) @@ -1859,9 +1824,7 @@ func (s *connection) sendPackets(now time.Time) error { return err } s.sentFirstPacket = true - if err := s.sendPackedCoalescedPacket(packet, s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket()), now); err != nil { - return err - } + s.sendPackedCoalescedPacket(packet, now) sendMode := s.sentPacketHandler.SendMode(now) if sendMode == ackhandler.SendPacingLimited { s.resetPacingDeadline() @@ -1880,8 +1843,7 @@ func (s *connection) sendPackets(now time.Time) error { func (s *connection) sendPacketsWithoutGSO(now time.Time) error { for { buf := getPacketBuffer() - ecn := s.sentPacketHandler.ECNMode(true) - if _, err := s.appendOneShortHeaderPacket(buf, s.mtuDiscoverer.CurrentSize(), ecn, now); err != nil { + if _, err := s.appendPacket(buf, s.mtuDiscoverer.CurrentSize(), now); err != nil { if err == errNothingToPack { buf.Release() return nil @@ -1889,7 +1851,7 @@ func (s *connection) sendPacketsWithoutGSO(now time.Time) error { return err } - s.sendQueue.Send(buf, 0, ecn) + s.sendQueue.Send(buf, buf.Len()) if s.sendQueue.WouldBlock() { return nil @@ -1914,10 +1876,9 @@ func (s *connection) sendPacketsWithGSO(now time.Time) error { buf := getLargePacketBuffer() maxSize := s.mtuDiscoverer.CurrentSize() - ecn := s.sentPacketHandler.ECNMode(true) for { var dontSendMore bool - size, err := s.appendOneShortHeaderPacket(buf, maxSize, ecn, now) + size, err := s.appendPacket(buf, maxSize, now) if err != nil { if err != errNothingToPack { return err @@ -1939,19 +1900,15 @@ func (s *connection) sendPacketsWithGSO(now time.Time) error { } } - // Don't send more packets in this batch if they require a different ECN marking than the previous ones. - nextECN := s.sentPacketHandler.ECNMode(true) - // Append another packet if // 1. The congestion controller and pacer allow sending more // 2. The last packet appended was a full-size packet - // 3. The next packet will have the same ECN marking - // 4. We still have enough space for another full-size packet in the buffer - if !dontSendMore && size == maxSize && nextECN == ecn && buf.Len()+maxSize <= buf.Cap() { + // 3. We still have enough space for another full-size packet in the buffer + if !dontSendMore && size == maxSize && buf.Len()+maxSize <= buf.Cap() { continue } - s.sendQueue.Send(buf, uint16(maxSize), ecn) + s.sendQueue.Send(buf, maxSize) if dontSendMore { return nil @@ -1980,7 +1937,6 @@ func (s *connection) resetPacingDeadline() { func (s *connection) maybeSendAckOnlyPacket(now time.Time) error { if !s.handshakeConfirmed { - ecn := s.sentPacketHandler.ECNMode(false) packet, err := s.packer.PackCoalescedPacket(true, s.mtuDiscoverer.CurrentSize(), s.version) if err != nil { return err @@ -1988,10 +1944,10 @@ func (s *connection) maybeSendAckOnlyPacket(now time.Time) error { if packet == nil { return nil } - return s.sendPackedCoalescedPacket(packet, ecn, time.Now()) + s.sendPackedCoalescedPacket(packet, time.Now()) + return nil } - ecn := s.sentPacketHandler.ECNMode(true) p, buf, err := s.packer.PackAckOnlyPacket(s.mtuDiscoverer.CurrentSize(), s.version) if err != nil { if err == errNothingToPack { @@ -1999,9 +1955,9 @@ func (s *connection) maybeSendAckOnlyPacket(now time.Time) error { } return err } - s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, buf.Len(), false) - s.registerPackedShortHeaderPacket(p, ecn, now) - s.sendQueue.Send(buf, 0, ecn) + s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, buf.Len(), false) + s.registerPackedShortHeaderPacket(p, now) + s.sendQueue.Send(buf, buf.Len()) return nil } @@ -2033,24 +1989,25 @@ func (s *connection) sendProbePacket(encLevel protocol.EncryptionLevel, now time if packet == nil || (len(packet.longHdrPackets) == 0 && packet.shortHdrPacket == nil) { return fmt.Errorf("connection BUG: couldn't pack %s probe packet", encLevel) } - return s.sendPackedCoalescedPacket(packet, s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket()), now) + s.sendPackedCoalescedPacket(packet, now) + return nil } -// appendOneShortHeaderPacket appends a new packet to the given packetBuffer. +// appendPacket appends a new packet to the given packetBuffer. // If there was nothing to pack, the returned size is 0. -func (s *connection) appendOneShortHeaderPacket(buf *packetBuffer, maxSize protocol.ByteCount, ecn protocol.ECN, now time.Time) (protocol.ByteCount, error) { +func (s *connection) appendPacket(buf *packetBuffer, maxSize protocol.ByteCount, now time.Time) (protocol.ByteCount, error) { startLen := buf.Len() p, err := s.packer.AppendPacket(buf, maxSize, s.version) if err != nil { return 0, err } size := buf.Len() - startLen - s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, size, false) - s.registerPackedShortHeaderPacket(p, ecn, now) + s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, size, false) + s.registerPackedShortHeaderPacket(p, now) return size, nil } -func (s *connection) registerPackedShortHeaderPacket(p shortHeaderPacket, ecn protocol.ECN, now time.Time) { +func (s *connection) registerPackedShortHeaderPacket(p shortHeaderPacket, now time.Time) { if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && (len(p.StreamFrames) > 0 || ackhandler.HasAckElicitingFrames(p.Frames)) { s.firstAckElicitingPacketAfterIdleSentTime = now } @@ -2059,12 +2016,12 @@ func (s *connection) registerPackedShortHeaderPacket(p shortHeaderPacket, ecn pr if p.Ack != nil { largestAcked = p.Ack.LargestAcked() } - s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, ecn, p.Length, p.IsPathMTUProbePacket) + s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, p.Length, p.IsPathMTUProbePacket) s.connIDManager.SentPacket() } -func (s *connection) sendPackedCoalescedPacket(packet *coalescedPacket, ecn protocol.ECN, now time.Time) error { - s.logCoalescedPacket(packet, ecn) +func (s *connection) sendPackedCoalescedPacket(packet *coalescedPacket, now time.Time) { + s.logCoalescedPacket(packet) for _, p := range packet.longHdrPackets { if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && p.IsAckEliciting() { s.firstAckElicitingPacketAfterIdleSentTime = now @@ -2073,14 +2030,7 @@ func (s *connection) sendPackedCoalescedPacket(packet *coalescedPacket, ecn prot if p.ack != nil { largestAcked = p.ack.LargestAcked() } - s.sentPacketHandler.SentPacket(now, p.header.PacketNumber, largestAcked, p.streamFrames, p.frames, p.EncryptionLevel(), ecn, p.length, false) - if s.perspective == protocol.PerspectiveClient && p.EncryptionLevel() == protocol.EncryptionHandshake { - // On the client side, Initial keys are dropped as soon as the first Handshake packet is sent. - // See Section 4.9.1 of RFC 9001. - if err := s.dropEncryptionLevel(protocol.EncryptionInitial); err != nil { - return err - } - } + s.sentPacketHandler.SentPacket(now, p.header.PacketNumber, largestAcked, p.streamFrames, p.frames, p.EncryptionLevel(), p.length, false) } if p := packet.shortHdrPacket; p != nil { if s.firstAckElicitingPacketAfterIdleSentTime.IsZero() && p.IsAckEliciting() { @@ -2090,11 +2040,10 @@ func (s *connection) sendPackedCoalescedPacket(packet *coalescedPacket, ecn prot if p.Ack != nil { largestAcked = p.Ack.LargestAcked() } - s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, ecn, p.Length, p.IsPathMTUProbePacket) + s.sentPacketHandler.SentPacket(now, p.PacketNumber, largestAcked, p.StreamFrames, p.Frames, protocol.Encryption1RTT, p.Length, p.IsPathMTUProbePacket) } s.connIDManager.SentPacket() - s.sendQueue.Send(packet.buffer, 0, ecn) - return nil + s.sendQueue.Send(packet.buffer, packet.buffer.Len()) } func (s *connection) sendConnectionClose(e error) ([]byte, error) { @@ -2115,12 +2064,11 @@ func (s *connection) sendConnectionClose(e error) ([]byte, error) { if err != nil { return nil, err } - ecn := s.sentPacketHandler.ECNMode(packet.IsOnlyShortHeaderPacket()) - s.logCoalescedPacket(packet, ecn) - return packet.buffer.Data, s.conn.Write(packet.buffer.Data, 0, ecn) + s.logCoalescedPacket(packet) + return packet.buffer.Data, s.conn.Write(packet.buffer.Data, packet.buffer.Len()) } -func (s *connection) logLongHeaderPacket(p *longHeaderPacket, ecn protocol.ECN) { +func (s *connection) logLongHeaderPacket(p *longHeaderPacket) { // quic-go logging if s.logger.Debug() { p.header.Log(s.logger) @@ -2130,25 +2078,19 @@ func (s *connection) logLongHeaderPacket(p *longHeaderPacket, ecn protocol.ECN) for _, frame := range p.frames { wire.LogFrame(s.logger, frame.Frame, true) } - for _, frame := range p.streamFrames { - wire.LogFrame(s.logger, frame.Frame, true) - } } // tracing - if s.tracer != nil && s.tracer.SentLongHeaderPacket != nil { + if s.tracer != nil { frames := make([]logging.Frame, 0, len(p.frames)) for _, f := range p.frames { frames = append(frames, logutils.ConvertFrame(f.Frame)) } - for _, f := range p.streamFrames { - frames = append(frames, logutils.ConvertFrame(f.Frame)) - } var ack *logging.AckFrame if p.ack != nil { ack = logutils.ConvertAckFrame(p.ack) } - s.tracer.SentLongHeaderPacket(p.header, p.length, ecn, ack, frames) + s.tracer.SentLongHeaderPacket(p.header, p.length, ack, frames) } } @@ -2160,12 +2102,11 @@ func (s *connection) logShortHeaderPacket( pn protocol.PacketNumber, pnLen protocol.PacketNumberLen, kp protocol.KeyPhaseBit, - ecn protocol.ECN, size protocol.ByteCount, isCoalesced bool, ) { if s.logger.Debug() && !isCoalesced { - s.logger.Debugf("-> Sending packet %d (%d bytes) for connection %s, 1-RTT (ECN: %s)", pn, size, s.logID, ecn) + s.logger.Debugf("-> Sending packet %d (%d bytes) for connection %s, 1-RTT", pn, size, s.logID) } // quic-go logging if s.logger.Debug() { @@ -2182,7 +2123,7 @@ func (s *connection) logShortHeaderPacket( } // tracing - if s.tracer != nil && s.tracer.SentShortHeaderPacket != nil { + if s.tracer != nil { fs := make([]logging.Frame, 0, len(frames)+len(streamFrames)) for _, f := range frames { fs = append(fs, logutils.ConvertFrame(f.Frame)) @@ -2202,14 +2143,13 @@ func (s *connection) logShortHeaderPacket( KeyPhase: kp, }, size, - ecn, ack, fs, ) } } -func (s *connection) logCoalescedPacket(packet *coalescedPacket, ecn protocol.ECN) { +func (s *connection) logCoalescedPacket(packet *coalescedPacket) { if s.logger.Debug() { // There's a short period between dropping both Initial and Handshake keys and completion of the handshake, // during which we might call PackCoalescedPacket but just pack a short header packet. @@ -2222,7 +2162,6 @@ func (s *connection) logCoalescedPacket(packet *coalescedPacket, ecn protocol.EC packet.shortHdrPacket.PacketNumber, packet.shortHdrPacket.PacketNumberLen, packet.shortHdrPacket.KeyPhase, - ecn, packet.shortHdrPacket.Length, false, ) @@ -2235,10 +2174,10 @@ func (s *connection) logCoalescedPacket(packet *coalescedPacket, ecn protocol.EC } } for _, p := range packet.longHdrPackets { - s.logLongHeaderPacket(p, ecn) + s.logLongHeaderPacket(p) } if p := packet.shortHdrPacket; p != nil { - s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, ecn, p.Length, true) + s.logShortHeaderPacket(p.DestConnID, p.Ack, p.Frames, p.StreamFrames, p.PacketNumber, p.PacketNumberLen, p.KeyPhase, p.Length, true) } } @@ -2304,14 +2243,14 @@ func (s *connection) tryQueueingUndecryptablePacket(p receivedPacket, pt logging panic("shouldn't queue undecryptable packets after handshake completion") } if len(s.undecryptablePackets)+1 > protocol.MaxUndecryptablePackets { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(pt, p.Size(), logging.PacketDropDOSPrevention) } s.logger.Infof("Dropping undecryptable packet (%d bytes). Undecryptable packet queue full.", p.Size()) return } s.logger.Infof("Queueing packet (%d bytes) for later decryption", p.Size()) - if s.tracer != nil && s.tracer.BufferedPacket != nil { + if s.tracer != nil { s.tracer.BufferedPacket(pt, p.Size()) } s.undecryptablePackets = append(s.undecryptablePackets, p) @@ -2357,11 +2296,11 @@ func (s *connection) SendMessage(p []byte) error { return s.datagramQueue.AddAndWait(f) } -func (s *connection) ReceiveMessage(ctx context.Context) ([]byte, error) { +func (s *connection) ReceiveMessage() ([]byte, error) { if !s.config.EnableDatagrams { return nil, errors.New("datagram support disabled") } - return s.datagramQueue.Receive(ctx) + return s.datagramQueue.Receive() } func (s *connection) LocalAddr() net.Addr { diff --git a/vendor/github.com/quic-go/quic-go/crypto_stream.go b/vendor/github.com/quic-go/quic-go/crypto_stream.go index 4be2a07ae..f10e91202 100644 --- a/vendor/github.com/quic-go/quic-go/crypto_stream.go +++ b/vendor/github.com/quic-go/quic-go/crypto_stream.go @@ -71,9 +71,17 @@ func (s *cryptoStreamImpl) HandleCryptoFrame(f *wire.CryptoFrame) error { // GetCryptoData retrieves data that was received in CRYPTO frames func (s *cryptoStreamImpl) GetCryptoData() []byte { - b := s.msgBuf - s.msgBuf = nil - return b + if len(s.msgBuf) < 4 { + return nil + } + msgLen := 4 + int(s.msgBuf[1])<<16 + int(s.msgBuf[2])<<8 + int(s.msgBuf[3]) + if len(s.msgBuf) < msgLen { + return nil + } + msg := make([]byte, msgLen) + copy(msg, s.msgBuf[:msgLen]) + s.msgBuf = s.msgBuf[msgLen:] + return msg } func (s *cryptoStreamImpl) Finish() error { diff --git a/vendor/github.com/quic-go/quic-go/crypto_stream_manager.go b/vendor/github.com/quic-go/quic-go/crypto_stream_manager.go index c48e238a7..91946acfa 100644 --- a/vendor/github.com/quic-go/quic-go/crypto_stream_manager.go +++ b/vendor/github.com/quic-go/quic-go/crypto_stream_manager.go @@ -3,14 +3,12 @@ package quic import ( "fmt" - "github.com/quic-go/quic-go/internal/handshake" "github.com/quic-go/quic-go/internal/protocol" "github.com/quic-go/quic-go/internal/wire" ) type cryptoDataHandler interface { - HandleMessage([]byte, protocol.EncryptionLevel) error - NextEvent() handshake.Event + HandleMessage([]byte, protocol.EncryptionLevel) bool } type cryptoStreamManager struct { @@ -35,7 +33,7 @@ func newCryptoStreamManager( } } -func (m *cryptoStreamManager) HandleCryptoFrame(frame *wire.CryptoFrame, encLevel protocol.EncryptionLevel) error { +func (m *cryptoStreamManager) HandleCryptoFrame(frame *wire.CryptoFrame, encLevel protocol.EncryptionLevel) (bool /* encryption level changed */, error) { var str cryptoStream //nolint:exhaustive // CRYPTO frames cannot be sent in 0-RTT packets. switch encLevel { @@ -46,37 +44,18 @@ func (m *cryptoStreamManager) HandleCryptoFrame(frame *wire.CryptoFrame, encLeve case protocol.Encryption1RTT: str = m.oneRTTStream default: - return fmt.Errorf("received CRYPTO frame with unexpected encryption level: %s", encLevel) + return false, fmt.Errorf("received CRYPTO frame with unexpected encryption level: %s", encLevel) } if err := str.HandleCryptoFrame(frame); err != nil { - return err + return false, err } for { data := str.GetCryptoData() if data == nil { - return nil + return false, nil } - if err := m.cryptoHandler.HandleMessage(data, encLevel); err != nil { - return err + if encLevelFinished := m.cryptoHandler.HandleMessage(data, encLevel); encLevelFinished { + return true, str.Finish() } } } - -func (m *cryptoStreamManager) GetPostHandshakeData(maxSize protocol.ByteCount) *wire.CryptoFrame { - if !m.oneRTTStream.HasData() { - return nil - } - return m.oneRTTStream.PopCryptoFrame(maxSize) -} - -func (m *cryptoStreamManager) Drop(encLevel protocol.EncryptionLevel) error { - //nolint:exhaustive // 1-RTT keys should never get dropped. - switch encLevel { - case protocol.EncryptionInitial: - return m.initialStream.Finish() - case protocol.EncryptionHandshake: - return m.handshakeStream.Finish() - default: - panic(fmt.Sprintf("dropped unexpected encryption level: %s", encLevel)) - } -} diff --git a/vendor/github.com/quic-go/quic-go/datagram_queue.go b/vendor/github.com/quic-go/quic-go/datagram_queue.go index ca80d404c..59c7d069b 100644 --- a/vendor/github.com/quic-go/quic-go/datagram_queue.go +++ b/vendor/github.com/quic-go/quic-go/datagram_queue.go @@ -1,7 +1,6 @@ package quic import ( - "context" "sync" "github.com/quic-go/quic-go/internal/protocol" @@ -99,7 +98,7 @@ func (h *datagramQueue) HandleDatagramFrame(f *wire.DatagramFrame) { } // Receive gets a received DATAGRAM frame. -func (h *datagramQueue) Receive(ctx context.Context) ([]byte, error) { +func (h *datagramQueue) Receive() ([]byte, error) { for { h.rcvMx.Lock() if len(h.rcvQueue) > 0 { @@ -114,8 +113,6 @@ func (h *datagramQueue) Receive(ctx context.Context) ([]byte, error) { continue case <-h.closed: return nil, h.closeErr - case <-ctx.Done(): - return nil, ctx.Err() } } } diff --git a/vendor/github.com/quic-go/quic-go/framer.go b/vendor/github.com/quic-go/quic-go/framer.go index d5c61bcf7..9409af4c2 100644 --- a/vendor/github.com/quic-go/quic-go/framer.go +++ b/vendor/github.com/quic-go/quic-go/framer.go @@ -23,8 +23,6 @@ type framer interface { Handle0RTTRejection() error } -const maxPathResponses = 256 - type framerI struct { mutex sync.Mutex @@ -35,7 +33,6 @@ type framerI struct { controlFrameMutex sync.Mutex controlFrames []wire.Frame - pathResponses []*wire.PathResponseFrame } var _ framer = &framerI{} @@ -55,43 +52,20 @@ func (f *framerI) HasData() bool { return true } f.controlFrameMutex.Lock() - defer f.controlFrameMutex.Unlock() - return len(f.controlFrames) > 0 || len(f.pathResponses) > 0 + hasData = len(f.controlFrames) > 0 + f.controlFrameMutex.Unlock() + return hasData } func (f *framerI) QueueControlFrame(frame wire.Frame) { f.controlFrameMutex.Lock() - defer f.controlFrameMutex.Unlock() - - if pr, ok := frame.(*wire.PathResponseFrame); ok { - // Only queue up to maxPathResponses PATH_RESPONSE frames. - // This limit should be high enough to never be hit in practice, - // unless the peer is doing something malicious. - if len(f.pathResponses) >= maxPathResponses { - return - } - f.pathResponses = append(f.pathResponses, pr) - return - } f.controlFrames = append(f.controlFrames, frame) + f.controlFrameMutex.Unlock() } func (f *framerI) AppendControlFrames(frames []ackhandler.Frame, maxLen protocol.ByteCount, v protocol.VersionNumber) ([]ackhandler.Frame, protocol.ByteCount) { - f.controlFrameMutex.Lock() - defer f.controlFrameMutex.Unlock() - var length protocol.ByteCount - // add a PATH_RESPONSE first, but only pack a single PATH_RESPONSE per packet - if len(f.pathResponses) > 0 { - frame := f.pathResponses[0] - frameLen := frame.Length(v) - if frameLen <= maxLen { - frames = append(frames, ackhandler.Frame{Frame: frame}) - length += frameLen - f.pathResponses = f.pathResponses[1:] - } - } - + f.controlFrameMutex.Lock() for len(f.controlFrames) > 0 { frame := f.controlFrames[len(f.controlFrames)-1] frameLen := frame.Length(v) @@ -102,6 +76,7 @@ func (f *framerI) AppendControlFrames(frames []ackhandler.Frame, maxLen protocol length += frameLen f.controlFrames = f.controlFrames[:len(f.controlFrames)-1] } + f.controlFrameMutex.Unlock() return frames, length } diff --git a/vendor/github.com/quic-go/quic-go/http3/body.go b/vendor/github.com/quic-go/quic-go/http3/body.go index dc168e9e8..63ff43664 100644 --- a/vendor/github.com/quic-go/quic-go/http3/body.go +++ b/vendor/github.com/quic-go/quic-go/http3/body.go @@ -63,8 +63,7 @@ func (r *body) wasStreamHijacked() bool { } func (r *body) Read(b []byte) (int, error) { - n, err := r.str.Read(b) - return n, maybeReplaceError(err) + return r.str.Read(b) } func (r *body) Close() error { @@ -107,7 +106,7 @@ func (r *hijackableBody) Read(b []byte) (int, error) { if err != nil { r.requestDone() } - return n, maybeReplaceError(err) + return n, err } func (r *hijackableBody) requestDone() { diff --git a/vendor/github.com/quic-go/quic-go/http3/client.go b/vendor/github.com/quic-go/quic-go/http3/client.go index 8aca48078..c54de5ea9 100644 --- a/vendor/github.com/quic-go/quic-go/http3/client.go +++ b/vendor/github.com/quic-go/quic-go/http3/client.go @@ -15,6 +15,7 @@ import ( "github.com/quic-go/quic-go" "github.com/quic-go/quic-go/internal/protocol" + "github.com/quic-go/quic-go/internal/qtls" "github.com/quic-go/quic-go/internal/utils" "github.com/quic-go/quic-go/quicvarint" @@ -318,52 +319,40 @@ func (c *client) RoundTripOpt(req *http.Request, opt RoundTripOpt) (*http.Respon } conn.CloseWithError(quic.ApplicationErrorCode(rerr.connErr), reason) } - return nil, maybeReplaceError(rerr.err) + return nil, rerr.err } if opt.DontCloseRequestStream { close(reqDone) <-done } - return rsp, maybeReplaceError(rerr.err) + return rsp, rerr.err } -// cancelingReader reads from the io.Reader. -// It cancels writing on the stream if any error other than io.EOF occurs. -type cancelingReader struct { - r io.Reader - str Stream -} - -func (r *cancelingReader) Read(b []byte) (int, error) { - n, err := r.r.Read(b) - if err != nil && err != io.EOF { - r.str.CancelWrite(quic.StreamErrorCode(ErrCodeRequestCanceled)) - } - return n, err -} - -func (c *client) sendRequestBody(str Stream, body io.ReadCloser, contentLength int64) error { +func (c *client) sendRequestBody(str Stream, body io.ReadCloser) error { defer body.Close() - buf := make([]byte, bodyCopyBufferSize) - sr := &cancelingReader{str: str, r: body} - if contentLength == -1 { - _, err := io.CopyBuffer(str, sr, buf) - return err + b := make([]byte, bodyCopyBufferSize) + for { + n, rerr := body.Read(b) + if n == 0 { + if rerr == nil { + continue + } + if rerr == io.EOF { + break + } + } + if _, err := str.Write(b[:n]); err != nil { + return err + } + if rerr != nil { + if rerr == io.EOF { + break + } + str.CancelWrite(quic.StreamErrorCode(ErrCodeRequestCanceled)) + return rerr + } } - - // make sure we don't send more bytes than the content length - n, err := io.CopyBuffer(str, io.LimitReader(sr, contentLength), buf) - if err != nil { - return err - } - var extra int64 - extra, err = io.CopyBuffer(io.Discard, sr, buf) - n += extra - if n > contentLength { - str.CancelWrite(quic.StreamErrorCode(ErrCodeRequestCanceled)) - return fmt.Errorf("http: ContentLength=%d with Body length %d", contentLength, n) - } - return err + return nil } func (c *client) doRequest(req *http.Request, conn quic.EarlyConnection, str quic.Stream, opt RoundTripOpt, reqDone chan<- struct{}) (*http.Response, requestError) { @@ -383,13 +372,7 @@ func (c *client) doRequest(req *http.Request, conn quic.EarlyConnection, str qui if req.Body != nil { // send the request body asynchronously go func() { - contentLength := int64(-1) - // According to the documentation for http.Request.ContentLength, - // a value of 0 with a non-nil Body is also treated as unknown content length. - if req.ContentLength > 0 { - contentLength = req.ContentLength - } - if err := c.sendRequestBody(hstr, req.Body, contentLength); err != nil { + if err := c.sendRequestBody(hstr, req.Body); err != nil { c.logger.Errorf("Error writing request: %s", err) } if !opt.DontCloseRequestStream { @@ -419,22 +402,28 @@ func (c *client) doRequest(req *http.Request, conn quic.EarlyConnection, str qui return nil, newConnError(ErrCodeGeneralProtocolError, err) } - res, err := responseFromHeaders(hfs) - if err != nil { - return nil, newStreamError(ErrCodeMessageError, err) + connState := qtls.ToTLSConnectionState(conn.ConnectionState().TLS) + res := &http.Response{ + Proto: "HTTP/3.0", + ProtoMajor: 3, + Header: http.Header{}, + TLS: &connState, + Request: req, } - connState := conn.ConnectionState().TLS - res.TLS = &connState - res.Request = req - // Check that the server doesn't send more data in DATA frames than indicated by the Content-Length header (if set). - // See section 4.1.2 of RFC 9114. - var httpStr Stream - if _, ok := res.Header["Content-Length"]; ok && res.ContentLength >= 0 { - httpStr = newLengthLimitedStream(hstr, res.ContentLength) - } else { - httpStr = hstr + for _, hf := range hfs { + switch hf.Name { + case ":status": + status, err := strconv.Atoi(hf.Value) + if err != nil { + return nil, newStreamError(ErrCodeGeneralProtocolError, errors.New("malformed non-numeric status pseudo header")) + } + res.StatusCode = status + res.Status = hf.Value + " " + http.StatusText(status) + default: + res.Header.Add(hf.Name, hf.Value) + } } - respBody := newResponseBody(httpStr, conn, reqDone) + respBody := newResponseBody(hstr, conn, reqDone) // Rules for when to set Content-Length are defined in https://tools.ietf.org/html/rfc7230#section-3.3.2. _, hasTransferEncoding := res.Header["Transfer-Encoding"] diff --git a/vendor/github.com/quic-go/quic-go/http3/error.go b/vendor/github.com/quic-go/quic-go/http3/error.go deleted file mode 100644 index b96ebeec0..000000000 --- a/vendor/github.com/quic-go/quic-go/http3/error.go +++ /dev/null @@ -1,58 +0,0 @@ -package http3 - -import ( - "errors" - "fmt" - - "github.com/quic-go/quic-go" -) - -// Error is returned from the round tripper (for HTTP clients) -// and inside the HTTP handler (for HTTP servers) if an HTTP/3 error occurs. -// See section 8 of RFC 9114. -type Error struct { - Remote bool - ErrorCode ErrCode - ErrorMessage string -} - -var _ error = &Error{} - -func (e *Error) Error() string { - s := e.ErrorCode.string() - if s == "" { - s = fmt.Sprintf("H3 error (%#x)", uint64(e.ErrorCode)) - } - // Usually errors are remote. Only make it explicit for local errors. - if !e.Remote { - s += " (local)" - } - if e.ErrorMessage != "" { - s += ": " + e.ErrorMessage - } - return s -} - -func maybeReplaceError(err error) error { - if err == nil { - return nil - } - - var ( - e Error - strErr *quic.StreamError - appErr *quic.ApplicationError - ) - switch { - default: - return err - case errors.As(err, &strErr): - e.Remote = strErr.Remote - e.ErrorCode = ErrCode(strErr.ErrorCode) - case errors.As(err, &appErr): - e.Remote = appErr.Remote - e.ErrorCode = ErrCode(appErr.ErrorCode) - e.ErrorMessage = appErr.ErrorMessage - } - return &e -} diff --git a/vendor/github.com/quic-go/quic-go/http3/error_codes.go b/vendor/github.com/quic-go/quic-go/http3/error_codes.go index ae646586a..67b215d85 100644 --- a/vendor/github.com/quic-go/quic-go/http3/error_codes.go +++ b/vendor/github.com/quic-go/quic-go/http3/error_codes.go @@ -26,18 +26,10 @@ const ( ErrCodeMessageError ErrCode = 0x10e ErrCodeConnectError ErrCode = 0x10f ErrCodeVersionFallback ErrCode = 0x110 - ErrCodeDatagramError ErrCode = 0x33 + ErrCodeDatagramError ErrCode = 0x4a1268 ) func (e ErrCode) String() string { - s := e.string() - if s != "" { - return s - } - return fmt.Sprintf("unknown error code: %#x", uint16(e)) -} - -func (e ErrCode) string() string { switch e { case ErrCodeNoError: return "H3_NO_ERROR" @@ -76,6 +68,6 @@ func (e ErrCode) string() string { case ErrCodeDatagramError: return "H3_DATAGRAM_ERROR" default: - return "" + return fmt.Sprintf("unknown error code: %#x", uint16(e)) } } diff --git a/vendor/github.com/quic-go/quic-go/http3/frames.go b/vendor/github.com/quic-go/quic-go/http3/frames.go index 454e5f945..cdd97bc5e 100644 --- a/vendor/github.com/quic-go/quic-go/http3/frames.go +++ b/vendor/github.com/quic-go/quic-go/http3/frames.go @@ -88,7 +88,7 @@ func (f *headersFrame) Append(b []byte) []byte { return quicvarint.Append(b, f.Length) } -const settingDatagram = 0x33 +const settingDatagram = 0xffd277 type settingsFrame struct { Datagram bool diff --git a/vendor/github.com/quic-go/quic-go/http3/headers.go b/vendor/github.com/quic-go/quic-go/http3/headers.go deleted file mode 100644 index 79c070b55..000000000 --- a/vendor/github.com/quic-go/quic-go/http3/headers.go +++ /dev/null @@ -1,198 +0,0 @@ -package http3 - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "strconv" - "strings" - - "golang.org/x/net/http/httpguts" - - "github.com/quic-go/qpack" -) - -type header struct { - // Pseudo header fields defined in RFC 9114 - Path string - Method string - Authority string - Scheme string - Status string - // for Extended connect - Protocol string - // parsed and deduplicated - ContentLength int64 - // all non-pseudo headers - Headers http.Header -} - -func parseHeaders(headers []qpack.HeaderField, isRequest bool) (header, error) { - hdr := header{Headers: make(http.Header, len(headers))} - var readFirstRegularHeader, readContentLength bool - var contentLengthStr string - for _, h := range headers { - // field names need to be lowercase, see section 4.2 of RFC 9114 - if strings.ToLower(h.Name) != h.Name { - return header{}, fmt.Errorf("header field is not lower-case: %s", h.Name) - } - if !httpguts.ValidHeaderFieldValue(h.Value) { - return header{}, fmt.Errorf("invalid header field value for %s: %q", h.Name, h.Value) - } - if h.IsPseudo() { - if readFirstRegularHeader { - // all pseudo headers must appear before regular header fields, see section 4.3 of RFC 9114 - return header{}, fmt.Errorf("received pseudo header %s after a regular header field", h.Name) - } - var isResponsePseudoHeader bool // pseudo headers are either valid for requests or for responses - switch h.Name { - case ":path": - hdr.Path = h.Value - case ":method": - hdr.Method = h.Value - case ":authority": - hdr.Authority = h.Value - case ":protocol": - hdr.Protocol = h.Value - case ":scheme": - hdr.Scheme = h.Value - case ":status": - hdr.Status = h.Value - isResponsePseudoHeader = true - default: - return header{}, fmt.Errorf("unknown pseudo header: %s", h.Name) - } - if isRequest && isResponsePseudoHeader { - return header{}, fmt.Errorf("invalid request pseudo header: %s", h.Name) - } - if !isRequest && !isResponsePseudoHeader { - return header{}, fmt.Errorf("invalid response pseudo header: %s", h.Name) - } - } else { - if !httpguts.ValidHeaderFieldName(h.Name) { - return header{}, fmt.Errorf("invalid header field name: %q", h.Name) - } - readFirstRegularHeader = true - switch h.Name { - case "content-length": - // Ignore duplicate Content-Length headers. - // Fail if the duplicates differ. - if !readContentLength { - readContentLength = true - contentLengthStr = h.Value - } else if contentLengthStr != h.Value { - return header{}, fmt.Errorf("contradicting content lengths (%s and %s)", contentLengthStr, h.Value) - } - default: - hdr.Headers.Add(h.Name, h.Value) - } - } - } - if len(contentLengthStr) > 0 { - // use ParseUint instead of ParseInt, so that parsing fails on negative values - cl, err := strconv.ParseUint(contentLengthStr, 10, 63) - if err != nil { - return header{}, fmt.Errorf("invalid content length: %w", err) - } - hdr.Headers.Set("Content-Length", contentLengthStr) - hdr.ContentLength = int64(cl) - } - return hdr, nil -} - -func requestFromHeaders(headerFields []qpack.HeaderField) (*http.Request, error) { - hdr, err := parseHeaders(headerFields, true) - if err != nil { - return nil, err - } - // concatenate cookie headers, see https://tools.ietf.org/html/rfc6265#section-5.4 - if len(hdr.Headers["Cookie"]) > 0 { - hdr.Headers.Set("Cookie", strings.Join(hdr.Headers["Cookie"], "; ")) - } - - isConnect := hdr.Method == http.MethodConnect - // Extended CONNECT, see https://datatracker.ietf.org/doc/html/rfc8441#section-4 - isExtendedConnected := isConnect && hdr.Protocol != "" - if isExtendedConnected { - if hdr.Scheme == "" || hdr.Path == "" || hdr.Authority == "" { - return nil, errors.New("extended CONNECT: :scheme, :path and :authority must not be empty") - } - } else if isConnect { - if hdr.Path != "" || hdr.Authority == "" { // normal CONNECT - return nil, errors.New(":path must be empty and :authority must not be empty") - } - } else if len(hdr.Path) == 0 || len(hdr.Authority) == 0 || len(hdr.Method) == 0 { - return nil, errors.New(":path, :authority and :method must not be empty") - } - - var u *url.URL - var requestURI string - var protocol string - - if isConnect { - u = &url.URL{} - if isExtendedConnected { - u, err = url.ParseRequestURI(hdr.Path) - if err != nil { - return nil, err - } - } else { - u.Path = hdr.Path - } - u.Scheme = hdr.Scheme - u.Host = hdr.Authority - requestURI = hdr.Authority - protocol = hdr.Protocol - } else { - protocol = "HTTP/3.0" - u, err = url.ParseRequestURI(hdr.Path) - if err != nil { - return nil, fmt.Errorf("invalid content length: %w", err) - } - requestURI = hdr.Path - } - - return &http.Request{ - Method: hdr.Method, - URL: u, - Proto: protocol, - ProtoMajor: 3, - ProtoMinor: 0, - Header: hdr.Headers, - Body: nil, - ContentLength: hdr.ContentLength, - Host: hdr.Authority, - RequestURI: requestURI, - }, nil -} - -func hostnameFromRequest(req *http.Request) string { - if req.URL != nil { - return req.URL.Host - } - return "" -} - -func responseFromHeaders(headerFields []qpack.HeaderField) (*http.Response, error) { - hdr, err := parseHeaders(headerFields, false) - if err != nil { - return nil, err - } - if hdr.Status == "" { - return nil, errors.New("missing status field") - } - rsp := &http.Response{ - Proto: "HTTP/3.0", - ProtoMajor: 3, - Header: hdr.Headers, - ContentLength: hdr.ContentLength, - } - status, err := strconv.Atoi(hdr.Status) - if err != nil { - return nil, fmt.Errorf("invalid status code: %w", err) - } - rsp.StatusCode = status - rsp.Status = hdr.Status + " " + http.StatusText(status) - return rsp, nil -} diff --git a/vendor/github.com/quic-go/quic-go/http3/http_stream.go b/vendor/github.com/quic-go/quic-go/http3/http_stream.go index 1c0ec4f18..2799e2b3c 100644 --- a/vendor/github.com/quic-go/quic-go/http3/http_stream.go +++ b/vendor/github.com/quic-go/quic-go/http3/http_stream.go @@ -1,11 +1,9 @@ package http3 import ( - "errors" "fmt" "github.com/quic-go/quic-go" - "github.com/quic-go/quic-go/internal/utils" ) // A Stream is a HTTP/3 stream. @@ -68,10 +66,6 @@ func (s *stream) Read(b []byte) (int, error) { return n, err } -func (s *stream) hasMoreData() bool { - return s.bytesRemainingInFrame > 0 -} - func (s *stream) Write(b []byte) (int, error) { s.buf = s.buf[:0] s.buf = (&dataFrame{Length: uint64(len(b))}).Append(s.buf) @@ -80,45 +74,3 @@ func (s *stream) Write(b []byte) (int, error) { } return s.Stream.Write(b) } - -var errTooMuchData = errors.New("peer sent too much data") - -type lengthLimitedStream struct { - *stream - contentLength int64 - read int64 - resetStream bool -} - -var _ Stream = &lengthLimitedStream{} - -func newLengthLimitedStream(str *stream, contentLength int64) *lengthLimitedStream { - return &lengthLimitedStream{ - stream: str, - contentLength: contentLength, - } -} - -func (s *lengthLimitedStream) checkContentLengthViolation() error { - if s.read > s.contentLength || s.read == s.contentLength && s.hasMoreData() { - if !s.resetStream { - s.CancelRead(quic.StreamErrorCode(ErrCodeMessageError)) - s.CancelWrite(quic.StreamErrorCode(ErrCodeMessageError)) - s.resetStream = true - } - return errTooMuchData - } - return nil -} - -func (s *lengthLimitedStream) Read(b []byte) (int, error) { - if err := s.checkContentLengthViolation(); err != nil { - return 0, err - } - n, err := s.stream.Read(b[:utils.Min(int64(len(b)), s.contentLength-s.read)]) - s.read += int64(n) - if err := s.checkContentLengthViolation(); err != nil { - return n, err - } - return n, err -} diff --git a/vendor/github.com/quic-go/quic-go/http3/mockgen.go b/vendor/github.com/quic-go/quic-go/http3/mockgen.go index ad0a8a26e..38939e605 100644 --- a/vendor/github.com/quic-go/quic-go/http3/mockgen.go +++ b/vendor/github.com/quic-go/quic-go/http3/mockgen.go @@ -2,7 +2,7 @@ package http3 -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package http3 -destination mock_roundtripcloser_test.go github.com/quic-go/quic-go/http3 RoundTripCloser" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package http3 -destination mock_roundtripcloser_test.go github.com/quic-go/quic-go/http3 RoundTripCloser" type RoundTripCloser = roundTripCloser -//go:generate sh -c "go run go.uber.org/mock/mockgen -package http3 -destination mock_quic_early_listener_test.go github.com/quic-go/quic-go/http3 QUICEarlyListener" +//go:generate sh -c "go run github.com/golang/mock/mockgen -package http3 -destination mock_quic_early_listener_test.go github.com/quic-go/quic-go/http3 QUICEarlyListener" diff --git a/vendor/github.com/quic-go/quic-go/http3/request.go b/vendor/github.com/quic-go/quic-go/http3/request.go new file mode 100644 index 000000000..9af25a570 --- /dev/null +++ b/vendor/github.com/quic-go/quic-go/http3/request.go @@ -0,0 +1,111 @@ +package http3 + +import ( + "errors" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/quic-go/qpack" +) + +func requestFromHeaders(headers []qpack.HeaderField) (*http.Request, error) { + var path, authority, method, protocol, scheme, contentLengthStr string + + httpHeaders := http.Header{} + for _, h := range headers { + switch h.Name { + case ":path": + path = h.Value + case ":method": + method = h.Value + case ":authority": + authority = h.Value + case ":protocol": + protocol = h.Value + case ":scheme": + scheme = h.Value + case "content-length": + contentLengthStr = h.Value + default: + if !h.IsPseudo() { + httpHeaders.Add(h.Name, h.Value) + } + } + } + + // concatenate cookie headers, see https://tools.ietf.org/html/rfc6265#section-5.4 + if len(httpHeaders["Cookie"]) > 0 { + httpHeaders.Set("Cookie", strings.Join(httpHeaders["Cookie"], "; ")) + } + + isConnect := method == http.MethodConnect + // Extended CONNECT, see https://datatracker.ietf.org/doc/html/rfc8441#section-4 + isExtendedConnected := isConnect && protocol != "" + if isExtendedConnected { + if scheme == "" || path == "" || authority == "" { + return nil, errors.New("extended CONNECT: :scheme, :path and :authority must not be empty") + } + } else if isConnect { + if path != "" || authority == "" { // normal CONNECT + return nil, errors.New(":path must be empty and :authority must not be empty") + } + } else if len(path) == 0 || len(authority) == 0 || len(method) == 0 { + return nil, errors.New(":path, :authority and :method must not be empty") + } + + var u *url.URL + var requestURI string + var err error + + if isConnect { + u = &url.URL{} + if isExtendedConnected { + u, err = url.ParseRequestURI(path) + if err != nil { + return nil, err + } + } else { + u.Path = path + } + u.Scheme = scheme + u.Host = authority + requestURI = authority + } else { + protocol = "HTTP/3.0" + u, err = url.ParseRequestURI(path) + if err != nil { + return nil, err + } + requestURI = path + } + + var contentLength int64 + if len(contentLengthStr) > 0 { + contentLength, err = strconv.ParseInt(contentLengthStr, 10, 64) + if err != nil { + return nil, err + } + } + + return &http.Request{ + Method: method, + URL: u, + Proto: protocol, + ProtoMajor: 3, + ProtoMinor: 0, + Header: httpHeaders, + Body: nil, + ContentLength: contentLength, + Host: authority, + RequestURI: requestURI, + }, nil +} + +func hostnameFromRequest(req *http.Request) string { + if req.URL != nil { + return req.URL.Host + } + return "" +} diff --git a/vendor/github.com/quic-go/quic-go/http3/response_writer.go b/vendor/github.com/quic-go/quic-go/http3/response_writer.go index 0d9314782..b7c79d50e 100644 --- a/vendor/github.com/quic-go/quic-go/http3/response_writer.go +++ b/vendor/github.com/quic-go/quic-go/http3/response_writer.go @@ -3,7 +3,6 @@ package http3 import ( "bufio" "bytes" - "fmt" "net/http" "strconv" "strings" @@ -15,61 +14,17 @@ import ( "github.com/quic-go/qpack" ) -// The maximum length of an encoded HTTP/3 frame header is 16: -// The frame has a type and length field, both QUIC varints (maximum 8 bytes in length) -const frameHeaderLen = 16 - -// headerWriter wraps the stream, so that the first Write call flushes the header to the stream -type headerWriter struct { - str quic.Stream - header http.Header - status int // status code passed to WriteHeader - written bool - - logger utils.Logger -} - -// writeHeader encodes and flush header to the stream -func (hw *headerWriter) writeHeader() error { - var headers bytes.Buffer - enc := qpack.NewEncoder(&headers) - enc.WriteField(qpack.HeaderField{Name: ":status", Value: strconv.Itoa(hw.status)}) - - for k, v := range hw.header { - for index := range v { - enc.WriteField(qpack.HeaderField{Name: strings.ToLower(k), Value: v[index]}) - } - } - - buf := make([]byte, 0, frameHeaderLen+headers.Len()) - buf = (&headersFrame{Length: uint64(headers.Len())}).Append(buf) - hw.logger.Infof("Responding with %d", hw.status) - buf = append(buf, headers.Bytes()...) - - _, err := hw.str.Write(buf) - return err -} - -// first Write will trigger flushing header -func (hw *headerWriter) Write(p []byte) (int, error) { - if !hw.written { - if err := hw.writeHeader(); err != nil { - return 0, err - } - hw.written = true - } - return hw.str.Write(p) -} - type responseWriter struct { - *headerWriter conn quic.Connection + str quic.Stream bufferedStr *bufio.Writer buf []byte + header http.Header + status int // status code passed to WriteHeader headerWritten bool - contentLen int64 // if handler set valid Content-Length header - numWritten int64 // bytes written + + logger utils.Logger } var ( @@ -79,16 +34,13 @@ var ( ) func newResponseWriter(str quic.Stream, conn quic.Connection, logger utils.Logger) *responseWriter { - hw := &headerWriter{ - str: str, - header: http.Header{}, - logger: logger, - } return &responseWriter{ - headerWriter: hw, - buf: make([]byte, frameHeaderLen), - conn: conn, - bufferedStr: bufio.NewWriter(hw), + header: http.Header{}, + buf: make([]byte, 16), + conn: conn, + str: str, + bufferedStr: bufio.NewWriter(str), + logger: logger, } } @@ -101,35 +53,32 @@ func (w *responseWriter) WriteHeader(status int) { return } - // http status must be 3 digits - if status < 100 || status > 999 { - panic(fmt.Sprintf("invalid WriteHeader code %v", status)) - } - - if status >= 200 { + if status < 100 || status >= 200 { w.headerWritten = true - // Add Date header. - // This is what the standard library does. - // Can be disabled by setting the Date header to nil. - if _, ok := w.header["Date"]; !ok { - w.header.Set("Date", time.Now().UTC().Format(http.TimeFormat)) - } - // Content-Length checking - // use ParseUint instead of ParseInt, as negative values are invalid - if clen := w.header.Get("Content-Length"); clen != "" { - if cl, err := strconv.ParseUint(clen, 10, 63); err == nil { - w.contentLen = int64(cl) - } else { - // emit a warning for malformed Content-Length and remove it - w.logger.Errorf("Malformed Content-Length %s", clen) - w.header.Del("Content-Length") - } - } } w.status = status + var headers bytes.Buffer + enc := qpack.NewEncoder(&headers) + enc.WriteField(qpack.HeaderField{Name: ":status", Value: strconv.Itoa(status)}) + + for k, v := range w.header { + for index := range v { + enc.WriteField(qpack.HeaderField{Name: strings.ToLower(k), Value: v[index]}) + } + } + + w.buf = w.buf[:0] + w.buf = (&headersFrame{Length: uint64(headers.Len())}).Append(w.buf) + w.logger.Infof("Responding with %d", status) + if _, err := w.bufferedStr.Write(w.buf); err != nil { + w.logger.Errorf("could not write headers frame: %s", err.Error()) + } + if _, err := w.bufferedStr.Write(headers.Bytes()); err != nil { + w.logger.Errorf("could not write header frame payload: %s", err.Error()) + } if !w.headerWritten { - w.writeHeader() + w.Flush() } } @@ -156,37 +105,17 @@ func (w *responseWriter) Write(p []byte) (int, error) { if !bodyAllowed { return 0, http.ErrBodyNotAllowed } - - w.numWritten += int64(len(p)) - if w.contentLen != 0 && w.numWritten > w.contentLen { - return 0, http.ErrContentLength - } - df := &dataFrame{Length: uint64(len(p))} w.buf = w.buf[:0] w.buf = df.Append(w.buf) if _, err := w.bufferedStr.Write(w.buf); err != nil { - return 0, maybeReplaceError(err) + return 0, err } - n, err := w.bufferedStr.Write(p) - return n, maybeReplaceError(err) -} - -func (w *responseWriter) FlushError() error { - if !w.headerWritten { - w.WriteHeader(http.StatusOK) - } - if !w.written { - if err := w.writeHeader(); err != nil { - return maybeReplaceError(err) - } - w.written = true - } - return w.bufferedStr.Flush() + return w.bufferedStr.Write(p) } func (w *responseWriter) Flush() { - if err := w.FlushError(); err != nil { + if err := w.bufferedStr.Flush(); err != nil { w.logger.Errorf("could not flush to stream: %s", err.Error()) } } diff --git a/vendor/github.com/quic-go/quic-go/http3/roundtrip.go b/vendor/github.com/quic-go/quic-go/http3/roundtrip.go index bed421030..066b762b8 100644 --- a/vendor/github.com/quic-go/quic-go/http3/roundtrip.go +++ b/vendor/github.com/quic-go/quic-go/http3/roundtrip.go @@ -52,7 +52,7 @@ type RoundTripper struct { // Enable support for HTTP/3 datagrams. // If set to true, QuicConfig.EnableDatagram will be set. - // See https://datatracker.ietf.org/doc/html/rfc9297. + // See https://www.ietf.org/archive/id/draft-schinazi-masque-h3-datagram-02.html. EnableDatagrams bool // Additional HTTP/3 settings. diff --git a/vendor/github.com/quic-go/quic-go/http3/server.go b/vendor/github.com/quic-go/quic-go/http3/server.go index 4587a1fca..a03b1fc53 100644 --- a/vendor/github.com/quic-go/quic-go/http3/server.go +++ b/vendor/github.com/quic-go/quic-go/http3/server.go @@ -9,7 +9,6 @@ import ( "net" "net/http" "runtime" - "strconv" "strings" "sync" "time" @@ -32,8 +31,12 @@ var ( } ) -// NextProtoH3 is the ALPN protocol negotiated during the TLS handshake, for QUIC v1 and v2. -const NextProtoH3 = "h3" +const ( + // NextProtoH3Draft29 is the ALPN protocol negotiated during the TLS handshake, for QUIC draft 29. + NextProtoH3Draft29 = "h3-29" + // NextProtoH3 is the ALPN protocol negotiated during the TLS handshake, for QUIC v1 and v2. + NextProtoH3 = "h3" +) // StreamType is the stream type of a unidirectional stream. type StreamType uint64 @@ -59,6 +62,8 @@ func versionToALPN(v protocol.VersionNumber) string { switch v { case protocol.Version1, protocol.Version2: return NextProtoH3 + case protocol.VersionDraft29: + return NextProtoH3Draft29 default: return "" } @@ -173,7 +178,7 @@ type Server struct { // EnableDatagrams enables support for HTTP/3 datagrams. // If set to true, QuicConfig.EnableDatagram will be set. - // See https://datatracker.ietf.org/doc/html/rfc9297. + // See https://datatracker.ietf.org/doc/html/draft-ietf-masque-h3-datagram-07. EnableDatagrams bool // MaxHeaderBytes controls the maximum number of bytes the server will @@ -570,22 +575,14 @@ func (s *Server) handleRequest(conn quic.Connection, str quic.Stream, decoder *q } req, err := requestFromHeaders(hfs) if err != nil { - return newStreamError(ErrCodeMessageError, err) + // TODO: use the right error code + return newStreamError(ErrCodeGeneralProtocolError, err) } - connState := conn.ConnectionState().TLS + connState := conn.ConnectionState().TLS.ConnectionState req.TLS = &connState req.RemoteAddr = conn.RemoteAddr().String() - - // Check that the client doesn't send more data in DATA frames than indicated by the Content-Length header (if set). - // See section 4.1.2 of RFC 9114. - var httpStr Stream - if _, ok := req.Header["Content-Length"]; ok && req.ContentLength >= 0 { - httpStr = newLengthLimitedStream(newStream(str, onFrameError), req.ContentLength) - } else { - httpStr = newStream(str, onFrameError) - } - body := newRequestBody(httpStr) + body := newRequestBody(newStream(str, onFrameError)) req.Body = body if s.logger.Debug() { @@ -599,6 +596,7 @@ func (s *Server) handleRequest(conn quic.Connection, str quic.Stream, decoder *q ctx = context.WithValue(ctx, http.LocalAddrContextKey, conn.LocalAddr()) req = req.WithContext(ctx) r := newResponseWriter(str, conn, s.logger) + defer r.Flush() handler := s.Handler if handler == nil { handler = http.DefaultServeMux @@ -626,15 +624,10 @@ func (s *Server) handleRequest(conn quic.Connection, str quic.Stream, decoder *q return requestError{err: errHijacked} } - // only write response when there is no panic - if !panicked { - // response not written to the client yet, set Content-Length - if !r.written { - if _, haveCL := r.header["Content-Length"]; !haveCL { - r.header.Set("Content-Length", strconv.FormatInt(r.numWritten, 10)) - } - } - r.Flush() + if panicked { + r.WriteHeader(http.StatusInternalServerError) + } else { + r.WriteHeader(http.StatusOK) } // If the EOF was read by the handler, CancelRead() is a no-op. str.CancelRead(quic.StreamErrorCode(ErrCodeNoError)) diff --git a/vendor/github.com/quic-go/quic-go/interface.go b/vendor/github.com/quic-go/quic-go/interface.go index 6eac385df..8486c7fe0 100644 --- a/vendor/github.com/quic-go/quic-go/interface.go +++ b/vendor/github.com/quic-go/quic-go/interface.go @@ -2,7 +2,6 @@ package quic import ( "context" - "crypto/tls" "errors" "io" "net" @@ -20,9 +19,10 @@ type StreamID = protocol.StreamID type VersionNumber = protocol.VersionNumber const ( + // VersionDraft29 is IETF QUIC draft-29 + VersionDraft29 = protocol.VersionDraft29 // Version1 is RFC 9000 Version1 = protocol.Version1 - // Version2 is RFC 9369 Version2 = protocol.Version2 ) @@ -122,8 +122,6 @@ type SendStream interface { // The Context is canceled as soon as the write-side of the stream is closed. // This happens when Close() or CancelWrite() is called, or when the peer // cancels the read-side of their stream. - // The cancellation cause is set to the error that caused the stream to - // close, or `context.Canceled` in case the stream is closed without error. Context() context.Context // SetWriteDeadline sets the deadline for future Write calls // and any currently-blocked Write call. @@ -180,8 +178,6 @@ type Connection interface { // The error string will be sent to the peer. CloseWithError(ApplicationErrorCode, string) error // Context returns a context that is cancelled when the connection is closed. - // The cancellation cause is set to the error that caused the connection to - // close, or `context.Canceled` in case the listener is closed first. Context() context.Context // ConnectionState returns basic details about the QUIC connection. // Warning: This API should not be considered stable and might change soon. @@ -190,7 +186,7 @@ type Connection interface { // SendMessage sends a message as a datagram, as specified in RFC 9221. SendMessage([]byte) error // ReceiveMessage gets a message received in a datagram, as specified in RFC 9221. - ReceiveMessage(context.Context) ([]byte, error) + ReceiveMessage() ([]byte, error) } // An EarlyConnection is a connection that is handshaking. @@ -212,9 +208,6 @@ type EarlyConnection interface { // StatelessResetKey is a key used to derive stateless reset tokens. type StatelessResetKey [32]byte -// TokenGeneratorKey is a key used to encrypt session resumption tokens. -type TokenGeneratorKey = handshake.TokenProtectorKey - // A ConnectionID is a QUIC Connection ID, as defined in RFC 9000. // It is not able to handle QUIC Connection IDs longer than 20 bytes, // as they are allowed by RFC 8999. @@ -253,8 +246,7 @@ type Config struct { // If not set, it uses all versions available. Versions []VersionNumber // HandshakeIdleTimeout is the idle timeout before completion of the handshake. - // If we don't receive any packet from the peer within this time, the connection attempt is aborted. - // Additionally, if the handshake doesn't complete in twice this time, the connection attempt is also aborted. + // Specifically, if we don't receive any packet from the peer within this time, the connection attempt is aborted. // If this value is zero, the timeout is set to 5 seconds. HandshakeIdleTimeout time.Duration // MaxIdleTimeout is the maximum duration that may pass without any incoming network activity. @@ -268,6 +260,13 @@ type Config struct { // See https://datatracker.ietf.org/doc/html/rfc9000#section-8 for details. // If not set, every client is forced to prove its remote address. RequireAddressValidation func(net.Addr) bool + // MaxRetryTokenAge is the maximum age of a Retry token. + // If not set, it defaults to 5 seconds. Only valid for a server. + MaxRetryTokenAge time.Duration + // MaxTokenAge is the maximum age of the token presented during the handshake, + // for tokens that were issued on a previous connection. + // If not set, it defaults to 24 hours. Only valid for a server. + MaxTokenAge time.Duration // The TokenStore stores tokens received from the server. // Tokens are used to skip address validation on future connection attempts. // The key used to store tokens is the ServerName from the tls.Config, if set @@ -319,12 +318,16 @@ type Config struct { // Path MTU discovery is only available on systems that allow setting of the Don't Fragment (DF) bit. // If unavailable or disabled, packets will be at most 1252 (IPv4) / 1232 (IPv6) bytes in size. DisablePathMTUDiscovery bool + // DisableVersionNegotiationPackets disables the sending of Version Negotiation packets. + // This can be useful if version information is exchanged out-of-band. + // It has no effect for a client. + DisableVersionNegotiationPackets bool // Allow0RTT allows the application to decide if a 0-RTT connection attempt should be accepted. // Only valid for the server. Allow0RTT bool // Enable QUIC datagram support (RFC 9221). EnableDatagrams bool - Tracer func(context.Context, logging.Perspective, ConnectionID) *logging.ConnectionTracer + Tracer func(context.Context, logging.Perspective, ConnectionID) logging.ConnectionTracer } type ClientHelloInfo struct { @@ -334,16 +337,12 @@ type ClientHelloInfo struct { // ConnectionState records basic details about a QUIC connection type ConnectionState struct { // TLS contains information about the TLS connection state, incl. the tls.ConnectionState. - TLS tls.ConnectionState + TLS handshake.ConnectionState // SupportsDatagrams says if support for QUIC datagrams (RFC 9221) was negotiated. // This requires both nodes to support and enable the datagram extensions (via Config.EnableDatagrams). // If datagram support was negotiated, datagrams can be sent and received using the // SendMessage and ReceiveMessage methods on the Connection. SupportsDatagrams bool - // Used0RTT says if 0-RTT resumption was used. - Used0RTT bool // Version is the QUIC version of the QUIC connection. Version VersionNumber - // GSO says if generic segmentation offload is used - GSO bool } diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/ackhandler.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/ackhandler.go index cb28582a3..2c7cc4fcf 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/ackhandler.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/ackhandler.go @@ -14,11 +14,10 @@ func NewAckHandler( initialMaxDatagramSize protocol.ByteCount, rttStats *utils.RTTStats, clientAddressValidated bool, - enableECN bool, pers protocol.Perspective, - tracer *logging.ConnectionTracer, + tracer logging.ConnectionTracer, logger utils.Logger, ) (SentPacketHandler, ReceivedPacketHandler) { - sph := newSentPacketHandler(initialPacketNumber, initialMaxDatagramSize, rttStats, clientAddressValidated, enableECN, pers, tracer, logger) + sph := newSentPacketHandler(initialPacketNumber, initialMaxDatagramSize, rttStats, clientAddressValidated, pers, tracer, logger) return sph, newReceivedPacketHandler(sph, rttStats, logger) } diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/ecn.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/ecn.go deleted file mode 100644 index 68415ac6c..000000000 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/ecn.go +++ /dev/null @@ -1,296 +0,0 @@ -package ackhandler - -import ( - "fmt" - - "github.com/quic-go/quic-go/internal/protocol" - "github.com/quic-go/quic-go/internal/utils" - "github.com/quic-go/quic-go/logging" -) - -type ecnState uint8 - -const ( - ecnStateInitial ecnState = iota - ecnStateTesting - ecnStateUnknown - ecnStateCapable - ecnStateFailed -) - -// must fit into an uint8, otherwise numSentTesting and numLostTesting must have a larger type -const numECNTestingPackets = 10 - -type ecnHandler interface { - SentPacket(protocol.PacketNumber, protocol.ECN) - Mode() protocol.ECN - HandleNewlyAcked(packets []*packet, ect0, ect1, ecnce int64) (congested bool) - LostPacket(protocol.PacketNumber) -} - -// The ecnTracker performs ECN validation of a path. -// Once failed, it doesn't do any re-validation of the path. -// It is designed only work for 1-RTT packets, it doesn't handle multiple packet number spaces. -// In order to avoid revealing any internal state to on-path observers, -// callers should make sure to start using ECN (i.e. calling Mode) for the very first 1-RTT packet sent. -// The validation logic implemented here strictly follows the algorithm described in RFC 9000 section 13.4.2 and A.4. -type ecnTracker struct { - state ecnState - numSentTesting, numLostTesting uint8 - - firstTestingPacket protocol.PacketNumber - lastTestingPacket protocol.PacketNumber - firstCapablePacket protocol.PacketNumber - - numSentECT0, numSentECT1 int64 - numAckedECT0, numAckedECT1, numAckedECNCE int64 - - tracer *logging.ConnectionTracer - logger utils.Logger -} - -var _ ecnHandler = &ecnTracker{} - -func newECNTracker(logger utils.Logger, tracer *logging.ConnectionTracer) *ecnTracker { - return &ecnTracker{ - firstTestingPacket: protocol.InvalidPacketNumber, - lastTestingPacket: protocol.InvalidPacketNumber, - firstCapablePacket: protocol.InvalidPacketNumber, - state: ecnStateInitial, - logger: logger, - tracer: tracer, - } -} - -func (e *ecnTracker) SentPacket(pn protocol.PacketNumber, ecn protocol.ECN) { - //nolint:exhaustive // These are the only ones we need to take care of. - switch ecn { - case protocol.ECNNon: - return - case protocol.ECT0: - e.numSentECT0++ - case protocol.ECT1: - e.numSentECT1++ - case protocol.ECNUnsupported: - if e.state != ecnStateFailed { - panic("didn't expect ECN to be unsupported") - } - default: - panic(fmt.Sprintf("sent packet with unexpected ECN marking: %s", ecn)) - } - - if e.state == ecnStateCapable && e.firstCapablePacket == protocol.InvalidPacketNumber { - e.firstCapablePacket = pn - } - - if e.state != ecnStateTesting { - return - } - - e.numSentTesting++ - if e.firstTestingPacket == protocol.InvalidPacketNumber { - e.firstTestingPacket = pn - } - if e.numSentECT0+e.numSentECT1 >= numECNTestingPackets { - if e.tracer != nil && e.tracer.ECNStateUpdated != nil { - e.tracer.ECNStateUpdated(logging.ECNStateUnknown, logging.ECNTriggerNoTrigger) - } - e.state = ecnStateUnknown - e.lastTestingPacket = pn - } -} - -func (e *ecnTracker) Mode() protocol.ECN { - switch e.state { - case ecnStateInitial: - if e.tracer != nil && e.tracer.ECNStateUpdated != nil { - e.tracer.ECNStateUpdated(logging.ECNStateTesting, logging.ECNTriggerNoTrigger) - } - e.state = ecnStateTesting - return e.Mode() - case ecnStateTesting, ecnStateCapable: - return protocol.ECT0 - case ecnStateUnknown, ecnStateFailed: - return protocol.ECNNon - default: - panic(fmt.Sprintf("unknown ECN state: %d", e.state)) - } -} - -func (e *ecnTracker) LostPacket(pn protocol.PacketNumber) { - if e.state != ecnStateTesting && e.state != ecnStateUnknown { - return - } - if !e.isTestingPacket(pn) { - return - } - e.numLostTesting++ - // Only proceed if we have sent all 10 testing packets. - if e.state != ecnStateUnknown { - return - } - if e.numLostTesting >= e.numSentTesting { - e.logger.Debugf("Disabling ECN. All testing packets were lost.") - if e.tracer != nil && e.tracer.ECNStateUpdated != nil { - e.tracer.ECNStateUpdated(logging.ECNStateFailed, logging.ECNFailedLostAllTestingPackets) - } - e.state = ecnStateFailed - return - } - // Path validation also fails if some testing packets are lost, and all other testing packets where CE-marked - e.failIfMangled() -} - -// HandleNewlyAcked handles the ECN counts on an ACK frame. -// It must only be called for ACK frames that increase the largest acknowledged packet number, -// see section 13.4.2.1 of RFC 9000. -func (e *ecnTracker) HandleNewlyAcked(packets []*packet, ect0, ect1, ecnce int64) (congested bool) { - if e.state == ecnStateFailed { - return false - } - - // ECN validation can fail if the received total count for either ECT(0) or ECT(1) exceeds - // the total number of packets sent with each corresponding ECT codepoint. - if ect0 > e.numSentECT0 || ect1 > e.numSentECT1 { - e.logger.Debugf("Disabling ECN. Received more ECT(0) / ECT(1) acknowledgements than packets sent.") - if e.tracer != nil && e.tracer.ECNStateUpdated != nil { - e.tracer.ECNStateUpdated(logging.ECNStateFailed, logging.ECNFailedMoreECNCountsThanSent) - } - e.state = ecnStateFailed - return false - } - - // Count ECT0 and ECT1 marks that we used when sending the packets that are now being acknowledged. - var ackedECT0, ackedECT1 int64 - for _, p := range packets { - //nolint:exhaustive // We only ever send ECT(0) and ECT(1). - switch e.ecnMarking(p.PacketNumber) { - case protocol.ECT0: - ackedECT0++ - case protocol.ECT1: - ackedECT1++ - } - } - - // If an ACK frame newly acknowledges a packet that the endpoint sent with either the ECT(0) or ECT(1) - // codepoint set, ECN validation fails if the corresponding ECN counts are not present in the ACK frame. - // This check detects: - // * paths that bleach all ECN marks, and - // * peers that don't report any ECN counts - if (ackedECT0 > 0 || ackedECT1 > 0) && ect0 == 0 && ect1 == 0 && ecnce == 0 { - e.logger.Debugf("Disabling ECN. ECN-marked packet acknowledged, but no ECN counts on ACK frame.") - if e.tracer != nil && e.tracer.ECNStateUpdated != nil { - e.tracer.ECNStateUpdated(logging.ECNStateFailed, logging.ECNFailedNoECNCounts) - } - e.state = ecnStateFailed - return false - } - - // Determine the increase in ECT0, ECT1 and ECNCE marks - newECT0 := ect0 - e.numAckedECT0 - newECT1 := ect1 - e.numAckedECT1 - newECNCE := ecnce - e.numAckedECNCE - - // We're only processing ACKs that increase the Largest Acked. - // Therefore, the ECN counters should only ever increase. - // Any decrease means that the peer's counting logic is broken. - if newECT0 < 0 || newECT1 < 0 || newECNCE < 0 { - e.logger.Debugf("Disabling ECN. ECN counts decreased unexpectedly.") - if e.tracer != nil && e.tracer.ECNStateUpdated != nil { - e.tracer.ECNStateUpdated(logging.ECNStateFailed, logging.ECNFailedDecreasedECNCounts) - } - e.state = ecnStateFailed - return false - } - - // ECN validation also fails if the sum of the increase in ECT(0) and ECN-CE counts is less than the number - // of newly acknowledged packets that were originally sent with an ECT(0) marking. - // This could be the result of (partial) bleaching. - if newECT0+newECNCE < ackedECT0 { - e.logger.Debugf("Disabling ECN. Received less ECT(0) + ECN-CE than packets sent with ECT(0).") - if e.tracer != nil && e.tracer.ECNStateUpdated != nil { - e.tracer.ECNStateUpdated(logging.ECNStateFailed, logging.ECNFailedTooFewECNCounts) - } - e.state = ecnStateFailed - return false - } - // Similarly, ECN validation fails if the sum of the increases to ECT(1) and ECN-CE counts is less than - // the number of newly acknowledged packets sent with an ECT(1) marking. - if newECT1+newECNCE < ackedECT1 { - e.logger.Debugf("Disabling ECN. Received less ECT(1) + ECN-CE than packets sent with ECT(1).") - if e.tracer != nil && e.tracer.ECNStateUpdated != nil { - e.tracer.ECNStateUpdated(logging.ECNStateFailed, logging.ECNFailedTooFewECNCounts) - } - e.state = ecnStateFailed - return false - } - - // update our counters - e.numAckedECT0 = ect0 - e.numAckedECT1 = ect1 - e.numAckedECNCE = ecnce - - // Detect mangling (a path remarking all ECN-marked testing packets as CE), - // once all 10 testing packets have been sent out. - if e.state == ecnStateUnknown { - e.failIfMangled() - if e.state == ecnStateFailed { - return false - } - } - if e.state == ecnStateTesting || e.state == ecnStateUnknown { - var ackedTestingPacket bool - for _, p := range packets { - if e.isTestingPacket(p.PacketNumber) { - ackedTestingPacket = true - break - } - } - // This check won't succeed if the path is mangling ECN-marks (i.e. rewrites all ECN-marked packets to CE). - if ackedTestingPacket && (newECT0 > 0 || newECT1 > 0) { - e.logger.Debugf("ECN capability confirmed.") - if e.tracer != nil && e.tracer.ECNStateUpdated != nil { - e.tracer.ECNStateUpdated(logging.ECNStateCapable, logging.ECNTriggerNoTrigger) - } - e.state = ecnStateCapable - } - } - - // Don't trust CE marks before having confirmed ECN capability of the path. - // Otherwise, mangling would be misinterpreted as actual congestion. - return e.state == ecnStateCapable && newECNCE > 0 -} - -// failIfMangled fails ECN validation if all testing packets are lost or CE-marked. -func (e *ecnTracker) failIfMangled() { - numAckedECNCE := e.numAckedECNCE + int64(e.numLostTesting) - if e.numSentECT0+e.numSentECT1 > numAckedECNCE { - return - } - if e.tracer != nil && e.tracer.ECNStateUpdated != nil { - e.tracer.ECNStateUpdated(logging.ECNStateFailed, logging.ECNFailedManglingDetected) - } - e.state = ecnStateFailed -} - -func (e *ecnTracker) ecnMarking(pn protocol.PacketNumber) protocol.ECN { - if pn < e.firstTestingPacket || e.firstTestingPacket == protocol.InvalidPacketNumber { - return protocol.ECNNon - } - if pn < e.lastTestingPacket || e.lastTestingPacket == protocol.InvalidPacketNumber { - return protocol.ECT0 - } - if pn < e.firstCapablePacket || e.firstCapablePacket == protocol.InvalidPacketNumber { - return protocol.ECNNon - } - // We don't need to deal with the case when ECN validation fails, - // since we're ignoring any ECN counts reported in ACK frames in that case. - return protocol.ECT0 -} - -func (e *ecnTracker) isTestingPacket(pn protocol.PacketNumber) bool { - if e.firstTestingPacket == protocol.InvalidPacketNumber { - return false - } - return pn >= e.firstTestingPacket && (pn <= e.lastTestingPacket || e.lastTestingPacket == protocol.InvalidPacketNumber) -} diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/interfaces.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/interfaces.go index ba8cbbdae..ba95f8a9b 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/interfaces.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/interfaces.go @@ -10,13 +10,13 @@ import ( // SentPacketHandler handles ACKs received for outgoing packets type SentPacketHandler interface { // SentPacket may modify the packet - SentPacket(t time.Time, pn, largestAcked protocol.PacketNumber, streamFrames []StreamFrame, frames []Frame, encLevel protocol.EncryptionLevel, ecn protocol.ECN, size protocol.ByteCount, isPathMTUProbePacket bool) + SentPacket(t time.Time, pn, largestAcked protocol.PacketNumber, streamFrames []StreamFrame, frames []Frame, encLevel protocol.EncryptionLevel, size protocol.ByteCount, isPathMTUProbePacket bool) // ReceivedAck processes an ACK frame. // It does not store a copy of the frame. - ReceivedAck(f *wire.AckFrame, encLevel protocol.EncryptionLevel, rcvTime time.Time) (bool /* 1-RTT packet acked */, error) + ReceivedAck(f *wire.AckFrame, encLevel protocol.EncryptionLevel, recvTime time.Time) (bool /* 1-RTT packet acked */, error) ReceivedBytes(protocol.ByteCount) DropPackets(protocol.EncryptionLevel) - ResetForRetry(rcvTime time.Time) error + ResetForRetry() error SetHandshakeConfirmed() // The SendMode determines if and what kind of packets can be sent. @@ -29,7 +29,6 @@ type SentPacketHandler interface { // only to be called once the handshake is complete QueueProbePacket(protocol.EncryptionLevel) bool /* was a packet queued */ - ECNMode(isShortHeaderPacket bool) protocol.ECN // isShortHeaderPacket should only be true for non-coalesced 1-RTT packets PeekPacketNumber(protocol.EncryptionLevel) (protocol.PacketNumber, protocol.PacketNumberLen) PopPacketNumber(protocol.EncryptionLevel) protocol.PacketNumber @@ -45,7 +44,7 @@ type sentPacketTracker interface { // ReceivedPacketHandler handles ACKs needed to send for incoming packets type ReceivedPacketHandler interface { IsPotentiallyDuplicate(protocol.PacketNumber, protocol.EncryptionLevel) bool - ReceivedPacket(pn protocol.PacketNumber, ecn protocol.ECN, encLevel protocol.EncryptionLevel, rcvTime time.Time, ackEliciting bool) error + ReceivedPacket(pn protocol.PacketNumber, ecn protocol.ECN, encLevel protocol.EncryptionLevel, rcvTime time.Time, shouldInstigateAck bool) error DropPackets(protocol.EncryptionLevel) GetAlarmTimeout() time.Time diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/mockgen.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/mockgen.go index dbf6ee2d1..d61783671 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/mockgen.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/mockgen.go @@ -2,8 +2,5 @@ package ackhandler -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package ackhandler -destination mock_sent_packet_tracker_test.go github.com/quic-go/quic-go/internal/ackhandler SentPacketTracker" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package ackhandler -destination mock_sent_packet_tracker_test.go github.com/quic-go/quic-go/internal/ackhandler SentPacketTracker" type SentPacketTracker = sentPacketTracker - -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package ackhandler -destination mock_ecn_handler_test.go github.com/quic-go/quic-go/internal/ackhandler ECNHandler" -type ECNHandler = ecnHandler diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_handler.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_handler.go index b37f91c5c..3675694f4 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_handler.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_handler.go @@ -40,29 +40,24 @@ func (h *receivedPacketHandler) ReceivedPacket( ecn protocol.ECN, encLevel protocol.EncryptionLevel, rcvTime time.Time, - ackEliciting bool, + shouldInstigateAck bool, ) error { h.sentPackets.ReceivedPacket(encLevel) switch encLevel { case protocol.EncryptionInitial: - return h.initialPackets.ReceivedPacket(pn, ecn, rcvTime, ackEliciting) + return h.initialPackets.ReceivedPacket(pn, ecn, rcvTime, shouldInstigateAck) case protocol.EncryptionHandshake: - // The Handshake packet number space might already have been dropped as a result - // of processing the CRYPTO frame that was contained in this packet. - if h.handshakePackets == nil { - return nil - } - return h.handshakePackets.ReceivedPacket(pn, ecn, rcvTime, ackEliciting) + return h.handshakePackets.ReceivedPacket(pn, ecn, rcvTime, shouldInstigateAck) case protocol.Encryption0RTT: if h.lowest1RTTPacket != protocol.InvalidPacketNumber && pn > h.lowest1RTTPacket { return fmt.Errorf("received packet number %d on a 0-RTT packet after receiving %d on a 1-RTT packet", pn, h.lowest1RTTPacket) } - return h.appDataPackets.ReceivedPacket(pn, ecn, rcvTime, ackEliciting) + return h.appDataPackets.ReceivedPacket(pn, ecn, rcvTime, shouldInstigateAck) case protocol.Encryption1RTT: if h.lowest1RTTPacket == protocol.InvalidPacketNumber || pn < h.lowest1RTTPacket { h.lowest1RTTPacket = pn } - if err := h.appDataPackets.ReceivedPacket(pn, ecn, rcvTime, ackEliciting); err != nil { + if err := h.appDataPackets.ReceivedPacket(pn, ecn, rcvTime, shouldInstigateAck); err != nil { return err } h.appDataPackets.IgnoreBelow(h.sentPackets.GetLowestPacketNotConfirmedAcked()) diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_tracker.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_tracker.go index 7fd071e68..b18838663 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_tracker.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/received_packet_tracker.go @@ -13,10 +13,10 @@ import ( const packetsBeforeAck = 2 type receivedPacketTracker struct { - largestObserved protocol.PacketNumber - ignoreBelow protocol.PacketNumber - largestObservedRcvdTime time.Time - ect0, ect1, ecnce uint64 + largestObserved protocol.PacketNumber + ignoreBelow protocol.PacketNumber + largestObservedReceivedTime time.Time + ect0, ect1, ecnce uint64 packetHistory *receivedPacketHistory @@ -45,25 +45,25 @@ func newReceivedPacketTracker( } } -func (h *receivedPacketTracker) ReceivedPacket(pn protocol.PacketNumber, ecn protocol.ECN, rcvTime time.Time, ackEliciting bool) error { - if isNew := h.packetHistory.ReceivedPacket(pn); !isNew { - return fmt.Errorf("recevedPacketTracker BUG: ReceivedPacket called for old / duplicate packet %d", pn) +func (h *receivedPacketTracker) ReceivedPacket(packetNumber protocol.PacketNumber, ecn protocol.ECN, rcvTime time.Time, shouldInstigateAck bool) error { + if isNew := h.packetHistory.ReceivedPacket(packetNumber); !isNew { + return fmt.Errorf("recevedPacketTracker BUG: ReceivedPacket called for old / duplicate packet %d", packetNumber) } - isMissing := h.isMissing(pn) - if pn >= h.largestObserved { - h.largestObserved = pn - h.largestObservedRcvdTime = rcvTime + isMissing := h.isMissing(packetNumber) + if packetNumber >= h.largestObserved { + h.largestObserved = packetNumber + h.largestObservedReceivedTime = rcvTime } - if ackEliciting { + if shouldInstigateAck { h.hasNewAck = true } - if ackEliciting { - h.maybeQueueACK(pn, rcvTime, isMissing) + if shouldInstigateAck { + h.maybeQueueAck(packetNumber, rcvTime, isMissing) } - //nolint:exhaustive // Only need to count ECT(0), ECT(1) and ECNCE. switch ecn { + case protocol.ECNNon: case protocol.ECT0: h.ect0++ case protocol.ECT1: @@ -76,14 +76,14 @@ func (h *receivedPacketTracker) ReceivedPacket(pn protocol.PacketNumber, ecn pro // IgnoreBelow sets a lower limit for acknowledging packets. // Packets with packet numbers smaller than p will not be acked. -func (h *receivedPacketTracker) IgnoreBelow(pn protocol.PacketNumber) { - if pn <= h.ignoreBelow { +func (h *receivedPacketTracker) IgnoreBelow(p protocol.PacketNumber) { + if p <= h.ignoreBelow { return } - h.ignoreBelow = pn - h.packetHistory.DeleteBelow(pn) + h.ignoreBelow = p + h.packetHistory.DeleteBelow(p) if h.logger.Debug() { - h.logger.Debugf("\tIgnoring all packets below %d.", pn) + h.logger.Debugf("\tIgnoring all packets below %d.", p) } } @@ -103,8 +103,8 @@ func (h *receivedPacketTracker) hasNewMissingPackets() bool { return highestRange.Smallest > h.lastAck.LargestAcked()+1 && highestRange.Len() == 1 } -// maybeQueueACK queues an ACK, if necessary. -func (h *receivedPacketTracker) maybeQueueACK(pn protocol.PacketNumber, rcvTime time.Time, wasMissing bool) { +// maybeQueueAck queues an ACK, if necessary. +func (h *receivedPacketTracker) maybeQueueAck(pn protocol.PacketNumber, rcvTime time.Time, wasMissing bool) { // always acknowledge the first packet if h.lastAck == nil { if !h.ackQueued { @@ -175,7 +175,7 @@ func (h *receivedPacketTracker) GetAckFrame(onlyIfQueued bool) *wire.AckFrame { ack = &wire.AckFrame{} } ack.Reset() - ack.DelayTime = utils.Max(0, now.Sub(h.largestObservedRcvdTime)) + ack.DelayTime = utils.Max(0, now.Sub(h.largestObservedReceivedTime)) ack.ECT0 = h.ect0 ack.ECT1 = h.ect1 ack.ECNCE = h.ecnce diff --git a/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_handler.go b/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_handler.go index c8265a78d..079789101 100644 --- a/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_handler.go +++ b/vendor/github.com/quic-go/quic-go/internal/ackhandler/sent_packet_handler.go @@ -92,12 +92,9 @@ type sentPacketHandler struct { // The alarm timeout alarm time.Time - enableECN bool - ecnTracker ecnHandler - perspective protocol.Perspective - tracer *logging.ConnectionTracer + tracer logging.ConnectionTracer logger utils.Logger } @@ -113,9 +110,8 @@ func newSentPacketHandler( initialMaxDatagramSize protocol.ByteCount, rttStats *utils.RTTStats, clientAddressValidated bool, - enableECN bool, pers protocol.Perspective, - tracer *logging.ConnectionTracer, + tracer logging.ConnectionTracer, logger utils.Logger, ) *sentPacketHandler { congestion := congestion.NewCubicSender( @@ -126,7 +122,7 @@ func newSentPacketHandler( tracer, ) - h := &sentPacketHandler{ + return &sentPacketHandler{ peerCompletedAddressValidation: pers == protocol.PerspectiveServer, peerAddressValidated: pers == protocol.PerspectiveClient || clientAddressValidated, initialPackets: newPacketNumberSpace(initialPN, false), @@ -138,11 +134,16 @@ func newSentPacketHandler( tracer: tracer, logger: logger, } - if enableECN { - h.enableECN = true - h.ecnTracker = newECNTracker(logger, tracer) +} + +func (h *sentPacketHandler) DropPackets(encLevel protocol.EncryptionLevel) { + if h.perspective == protocol.PerspectiveClient && encLevel == protocol.EncryptionInitial { + // This function is called when the crypto setup seals a Handshake packet. + // If this Handshake packet is coalesced behind an Initial packet, we would drop the Initial packet number space + // before SentPacket() was called for that Initial packet. + return } - return h + h.dropPackets(encLevel) } func (h *sentPacketHandler) removeFromBytesInFlight(p *packet) { @@ -155,7 +156,7 @@ func (h *sentPacketHandler) removeFromBytesInFlight(p *packet) { } } -func (h *sentPacketHandler) DropPackets(encLevel protocol.EncryptionLevel) { +func (h *sentPacketHandler) dropPackets(encLevel protocol.EncryptionLevel) { // The server won't await address validation after the handshake is confirmed. // This applies even if we didn't receive an ACK for a Handshake packet. if h.perspective == protocol.PerspectiveClient && encLevel == protocol.EncryptionHandshake { @@ -164,10 +165,6 @@ func (h *sentPacketHandler) DropPackets(encLevel protocol.EncryptionLevel) { // remove outstanding packets from bytes_in_flight if encLevel == protocol.EncryptionInitial || encLevel == protocol.EncryptionHandshake { pnSpace := h.getPacketNumberSpace(encLevel) - // We might already have dropped this packet number space. - if pnSpace == nil { - return - } pnSpace.history.Iterate(func(p *packet) (bool, error) { h.removeFromBytesInFlight(p) return true, nil @@ -196,7 +193,7 @@ func (h *sentPacketHandler) DropPackets(encLevel protocol.EncryptionLevel) { default: panic(fmt.Sprintf("Cannot drop keys for encryption level %s", encLevel)) } - if h.tracer != nil && h.tracer.UpdatedPTOCount != nil && h.ptoCount != 0 { + if h.tracer != nil && h.ptoCount != 0 { h.tracer.UpdatedPTOCount(0) } h.ptoCount = 0 @@ -237,11 +234,14 @@ func (h *sentPacketHandler) SentPacket( streamFrames []StreamFrame, frames []Frame, encLevel protocol.EncryptionLevel, - ecn protocol.ECN, size protocol.ByteCount, isPathMTUProbePacket bool, ) { h.bytesSent += size + // For the client, drop the Initial packet number space when the first Handshake packet is sent. + if h.perspective == protocol.PerspectiveClient && encLevel == protocol.EncryptionHandshake && h.initialPackets != nil { + h.dropPackets(protocol.EncryptionInitial) + } pnSpace := h.getPacketNumberSpace(encLevel) if h.logger.Debug() && pnSpace.history.HasOutstandingPackets() { @@ -262,10 +262,6 @@ func (h *sentPacketHandler) SentPacket( } h.congestion.OnPacketSent(t, h.bytesInFlight, pn, size, isAckEliciting) - if encLevel == protocol.Encryption1RTT && h.ecnTracker != nil { - h.ecnTracker.SentPacket(pn, ecn) - } - if !isAckEliciting { pnSpace.history.SentNonAckElicitingPacket(pn) if !h.peerCompletedAddressValidation { @@ -286,7 +282,7 @@ func (h *sentPacketHandler) SentPacket( p.includedInBytesInFlight = true pnSpace.history.SentAckElicitingPacket(p) - if h.tracer != nil && h.tracer.UpdatedMetrics != nil { + if h.tracer != nil { h.tracer.UpdatedMetrics(h.rttStats, h.congestion.GetCongestionWindow(), h.bytesInFlight, h.packetsInFlight()) } h.setLossDetectionTimer() @@ -316,6 +312,8 @@ func (h *sentPacketHandler) ReceivedAck(ack *wire.AckFrame, encLevel protocol.En } } + pnSpace.largestAcked = utils.Max(pnSpace.largestAcked, largestAcked) + // Servers complete address validation when a protected packet is received. if h.perspective == protocol.PerspectiveClient && !h.peerCompletedAddressValidation && (encLevel == protocol.EncryptionHandshake || encLevel == protocol.Encryption1RTT) { @@ -345,17 +343,6 @@ func (h *sentPacketHandler) ReceivedAck(ack *wire.AckFrame, encLevel protocol.En h.congestion.MaybeExitSlowStart() } } - - // Only inform the ECN tracker about new 1-RTT ACKs if the ACK increases the largest acked. - if encLevel == protocol.Encryption1RTT && h.ecnTracker != nil && largestAcked > pnSpace.largestAcked { - congested := h.ecnTracker.HandleNewlyAcked(ackedPackets, int64(ack.ECT0), int64(ack.ECT1), int64(ack.ECNCE)) - if congested { - h.congestion.OnCongestionEvent(largestAcked, 0, priorInFlight) - } - } - - pnSpace.largestAcked = utils.Max(pnSpace.largestAcked, largestAcked) - if err := h.detectLostPackets(rcvTime, encLevel); err != nil { return false, err } @@ -376,14 +363,14 @@ func (h *sentPacketHandler) ReceivedAck(ack *wire.AckFrame, encLevel protocol.En // Reset the pto_count unless the client is unsure if the server has validated the client's address. if h.peerCompletedAddressValidation { - if h.tracer != nil && h.tracer.UpdatedPTOCount != nil && h.ptoCount != 0 { + if h.tracer != nil && h.ptoCount != 0 { h.tracer.UpdatedPTOCount(0) } h.ptoCount = 0 } h.numProbesToSend = 0 - if h.tracer != nil && h.tracer.UpdatedMetrics != nil { + if h.tracer != nil { h.tracer.UpdatedMetrics(h.rttStats, h.congestion.GetCongestionWindow(), h.bytesInFlight, h.packetsInFlight()) } @@ -462,7 +449,7 @@ func (h *sentPacketHandler) detectAndRemoveAckedPackets(ack *wire.AckFrame, encL if err := pnSpace.history.Remove(p.PacketNumber); err != nil { return nil, err } - if h.tracer != nil && h.tracer.AcknowledgedPacket != nil { + if h.tracer != nil { h.tracer.AcknowledgedPacket(encLevel, p.PacketNumber) } } @@ -555,7 +542,7 @@ func (h *sentPacketHandler) setLossDetectionTimer() { if !lossTime.IsZero() { // Early retransmit timer or time loss detection. h.alarm = lossTime - if h.tracer != nil && h.tracer.SetLossTimer != nil && h.alarm != oldAlarm { + if h.tracer != nil && h.alarm != oldAlarm { h.tracer.SetLossTimer(logging.TimerTypeACK, encLevel, h.alarm) } return @@ -566,7 +553,7 @@ func (h *sentPacketHandler) setLossDetectionTimer() { h.alarm = time.Time{} if !oldAlarm.IsZero() { h.logger.Debugf("Canceling loss detection timer. Amplification limited.") - if h.tracer != nil && h.tracer.LossTimerCanceled != nil { + if h.tracer != nil { h.tracer.LossTimerCanceled() } } @@ -578,7 +565,7 @@ func (h *sentPacketHandler) setLossDetectionTimer() { h.alarm = time.Time{} if !oldAlarm.IsZero() { h.logger.Debugf("Canceling loss detection timer. No packets in flight.") - if h.tracer != nil && h.tracer.LossTimerCanceled != nil { + if h.tracer != nil { h.tracer.LossTimerCanceled() } } @@ -591,14 +578,14 @@ func (h *sentPacketHandler) setLossDetectionTimer() { if !oldAlarm.IsZero() { h.alarm = time.Time{} h.logger.Debugf("Canceling loss detection timer. No PTO needed..") - if h.tracer != nil && h.tracer.LossTimerCanceled != nil { + if h.tracer != nil { h.tracer.LossTimerCanceled() } } return } h.alarm = ptoTime - if h.tracer != nil && h.tracer.SetLossTimer != nil && h.alarm != oldAlarm { + if h.tracer != nil && h.alarm != oldAlarm { h.tracer.SetLossTimer(logging.TimerTypePTO, encLevel, h.alarm) } } @@ -629,7 +616,7 @@ func (h *sentPacketHandler) detectLostPackets(now time.Time, encLevel protocol.E if h.logger.Debug() { h.logger.Debugf("\tlost packet %d (time threshold)", p.PacketNumber) } - if h.tracer != nil && h.tracer.LostPacket != nil { + if h.tracer != nil { h.tracer.LostPacket(p.EncryptionLevel, p.PacketNumber, logging.PacketLossTimeThreshold) } } @@ -639,7 +626,7 @@ func (h *sentPacketHandler) detectLostPackets(now time.Time, encLevel protocol.E if h.logger.Debug() { h.logger.Debugf("\tlost packet %d (reordering threshold)", p.PacketNumber) } - if h.tracer != nil && h.tracer.LostPacket != nil { + if h.tracer != nil { h.tracer.LostPacket(p.EncryptionLevel, p.PacketNumber, logging.PacketLossReorderingThreshold) } } @@ -658,10 +645,7 @@ func (h *sentPacketHandler) detectLostPackets(now time.Time, encLevel protocol.E h.removeFromBytesInFlight(p) h.queueFramesForRetransmission(p) if !p.IsPathMTUProbePacket { - h.congestion.OnCongestionEvent(p.PacketNumber, p.Length, priorInFlight) - } - if encLevel == protocol.Encryption1RTT && h.ecnTracker != nil { - h.ecnTracker.LostPacket(p.PacketNumber) + h.congestion.OnPacketLost(p.PacketNumber, p.Length, priorInFlight) } } } @@ -676,7 +660,7 @@ func (h *sentPacketHandler) OnLossDetectionTimeout() error { if h.logger.Debug() { h.logger.Debugf("Loss detection alarm fired in loss timer mode. Loss time: %s", earliestLossTime) } - if h.tracer != nil && h.tracer.LossTimerExpired != nil { + if h.tracer != nil { h.tracer.LossTimerExpired(logging.TimerTypeACK, encLevel) } // Early retransmit or time loss detection @@ -713,12 +697,8 @@ func (h *sentPacketHandler) OnLossDetectionTimeout() error { h.logger.Debugf("Loss detection alarm for %s fired in PTO mode. PTO count: %d", encLevel, h.ptoCount) } if h.tracer != nil { - if h.tracer.LossTimerExpired != nil { - h.tracer.LossTimerExpired(logging.TimerTypePTO, encLevel) - } - if h.tracer.UpdatedPTOCount != nil { - h.tracer.UpdatedPTOCount(h.ptoCount) - } + h.tracer.LossTimerExpired(logging.TimerTypePTO, encLevel) + h.tracer.UpdatedPTOCount(h.ptoCount) } h.numProbesToSend += 2 //nolint:exhaustive // We never arm a PTO timer for 0-RTT packets. @@ -742,16 +722,6 @@ func (h *sentPacketHandler) GetLossDetectionTimeout() time.Time { return h.alarm } -func (h *sentPacketHandler) ECNMode(isShortHeaderPacket bool) protocol.ECN { - if !h.enableECN { - return protocol.ECNUnsupported - } - if !isShortHeaderPacket { - return protocol.ECNNon - } - return h.ecnTracker.Mode() -} - func (h *sentPacketHandler) PeekPacketNumber(encLevel protocol.EncryptionLevel) (protocol.PacketNumber, protocol.PacketNumberLen) { pnSpace := h.getPacketNumberSpace(encLevel) pn := pnSpace.pns.Peek() @@ -864,7 +834,7 @@ func (h *sentPacketHandler) queueFramesForRetransmission(p *packet) { p.Frames = nil } -func (h *sentPacketHandler) ResetForRetry(now time.Time) error { +func (h *sentPacketHandler) ResetForRetry() error { h.bytesInFlight = 0 var firstPacketSendTime time.Time h.initialPackets.history.Iterate(func(p *packet) (bool, error) { @@ -890,11 +860,12 @@ func (h *sentPacketHandler) ResetForRetry(now time.Time) error { // Otherwise, we don't know which Initial the Retry was sent in response to. if h.ptoCount == 0 { // Don't set the RTT to a value lower than 5ms here. + now := time.Now() h.rttStats.UpdateRTT(utils.Max(minRTTAfterRetry, now.Sub(firstPacketSendTime)), 0, now) if h.logger.Debug() { h.logger.Debugf("\tupdated RTT: %s (σ: %s)", h.rttStats.SmoothedRTT(), h.rttStats.MeanDeviation()) } - if h.tracer != nil && h.tracer.UpdatedMetrics != nil { + if h.tracer != nil { h.tracer.UpdatedMetrics(h.rttStats, h.congestion.GetCongestionWindow(), h.bytesInFlight, h.packetsInFlight()) } } @@ -903,10 +874,8 @@ func (h *sentPacketHandler) ResetForRetry(now time.Time) error { oldAlarm := h.alarm h.alarm = time.Time{} if h.tracer != nil { - if h.tracer.UpdatedPTOCount != nil { - h.tracer.UpdatedPTOCount(0) - } - if !oldAlarm.IsZero() && h.tracer.LossTimerCanceled != nil { + h.tracer.UpdatedPTOCount(0) + if !oldAlarm.IsZero() { h.tracer.LossTimerCanceled() } } @@ -915,12 +884,6 @@ func (h *sentPacketHandler) ResetForRetry(now time.Time) error { } func (h *sentPacketHandler) SetHandshakeConfirmed() { - if h.initialPackets != nil { - panic("didn't drop initial correctly") - } - if h.handshakePackets != nil { - panic("didn't drop handshake correctly") - } h.handshakeConfirmed = true // We don't send PTOs for application data packets before the handshake completes. // Make sure the timer is armed now, if necessary. diff --git a/vendor/github.com/quic-go/quic-go/internal/congestion/cubic_sender.go b/vendor/github.com/quic-go/quic-go/internal/congestion/cubic_sender.go index ee558f2d5..2e5084751 100644 --- a/vendor/github.com/quic-go/quic-go/internal/congestion/cubic_sender.go +++ b/vendor/github.com/quic-go/quic-go/internal/congestion/cubic_sender.go @@ -56,7 +56,7 @@ type cubicSender struct { maxDatagramSize protocol.ByteCount lastState logging.CongestionState - tracer *logging.ConnectionTracer + tracer logging.ConnectionTracer } var ( @@ -70,7 +70,7 @@ func NewCubicSender( rttStats *utils.RTTStats, initialMaxDatagramSize protocol.ByteCount, reno bool, - tracer *logging.ConnectionTracer, + tracer logging.ConnectionTracer, ) *cubicSender { return newCubicSender( clock, @@ -90,7 +90,7 @@ func newCubicSender( initialMaxDatagramSize, initialCongestionWindow, initialMaxCongestionWindow protocol.ByteCount, - tracer *logging.ConnectionTracer, + tracer logging.ConnectionTracer, ) *cubicSender { c := &cubicSender{ rttStats: rttStats, @@ -108,7 +108,7 @@ func newCubicSender( maxDatagramSize: initialMaxDatagramSize, } c.pacer = newPacer(c.BandwidthEstimate) - if c.tracer != nil && c.tracer.UpdatedCongestionState != nil { + if c.tracer != nil { c.lastState = logging.CongestionStateSlowStart c.tracer.UpdatedCongestionState(logging.CongestionStateSlowStart) } @@ -188,7 +188,7 @@ func (c *cubicSender) OnPacketAcked( } } -func (c *cubicSender) OnCongestionEvent(packetNumber protocol.PacketNumber, lostBytes, priorInFlight protocol.ByteCount) { +func (c *cubicSender) OnPacketLost(packetNumber protocol.PacketNumber, lostBytes, priorInFlight protocol.ByteCount) { // TCP NewReno (RFC6582) says that once a loss occurs, any losses in packets // already sent should be treated as a single loss event, since it's expected. if packetNumber <= c.largestSentAtLastCutback { @@ -296,7 +296,7 @@ func (c *cubicSender) OnConnectionMigration() { } func (c *cubicSender) maybeTraceStateChange(new logging.CongestionState) { - if c.tracer == nil || c.tracer.UpdatedCongestionState == nil || new == c.lastState { + if c.tracer == nil || new == c.lastState { return } c.tracer.UpdatedCongestionState(new) diff --git a/vendor/github.com/quic-go/quic-go/internal/congestion/interface.go b/vendor/github.com/quic-go/quic-go/internal/congestion/interface.go index 881f453b6..484bd5f81 100644 --- a/vendor/github.com/quic-go/quic-go/internal/congestion/interface.go +++ b/vendor/github.com/quic-go/quic-go/internal/congestion/interface.go @@ -14,7 +14,7 @@ type SendAlgorithm interface { CanSend(bytesInFlight protocol.ByteCount) bool MaybeExitSlowStart() OnPacketAcked(number protocol.PacketNumber, ackedBytes protocol.ByteCount, priorInFlight protocol.ByteCount, eventTime time.Time) - OnCongestionEvent(number protocol.PacketNumber, lostBytes protocol.ByteCount, priorInFlight protocol.ByteCount) + OnPacketLost(number protocol.PacketNumber, lostBytes protocol.ByteCount, priorInFlight protocol.ByteCount) OnRetransmissionTimeout(packetsRetransmitted bool) SetMaxDatagramSize(protocol.ByteCount) } diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/aead.go b/vendor/github.com/quic-go/quic-go/internal/handshake/aead.go index 6aa89fb3f..410745f1a 100644 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/aead.go +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/aead.go @@ -5,10 +5,11 @@ import ( "encoding/binary" "github.com/quic-go/quic-go/internal/protocol" + "github.com/quic-go/quic-go/internal/qtls" "github.com/quic-go/quic-go/internal/utils" ) -func createAEAD(suite *cipherSuite, trafficSecret []byte, v protocol.VersionNumber) cipher.AEAD { +func createAEAD(suite *qtls.CipherSuiteTLS13, trafficSecret []byte, v protocol.VersionNumber) cipher.AEAD { keyLabel := hkdfLabelKeyV1 ivLabel := hkdfLabelIVV1 if v == protocol.Version2 { @@ -92,3 +93,69 @@ func (o *longHeaderOpener) Open(dst, src []byte, pn protocol.PacketNumber, ad [] func (o *longHeaderOpener) DecryptHeader(sample []byte, firstByte *byte, pnBytes []byte) { o.headerProtector.DecryptHeader(sample, firstByte, pnBytes) } + +type handshakeSealer struct { + LongHeaderSealer + + dropInitialKeys func() + dropped bool +} + +func newHandshakeSealer( + aead cipher.AEAD, + headerProtector headerProtector, + dropInitialKeys func(), + perspective protocol.Perspective, +) LongHeaderSealer { + sealer := newLongHeaderSealer(aead, headerProtector) + // The client drops Initial keys when sending the first Handshake packet. + if perspective == protocol.PerspectiveServer { + return sealer + } + return &handshakeSealer{ + LongHeaderSealer: sealer, + dropInitialKeys: dropInitialKeys, + } +} + +func (s *handshakeSealer) Seal(dst, src []byte, pn protocol.PacketNumber, ad []byte) []byte { + data := s.LongHeaderSealer.Seal(dst, src, pn, ad) + if !s.dropped { + s.dropInitialKeys() + s.dropped = true + } + return data +} + +type handshakeOpener struct { + LongHeaderOpener + + dropInitialKeys func() + dropped bool +} + +func newHandshakeOpener( + aead cipher.AEAD, + headerProtector headerProtector, + dropInitialKeys func(), + perspective protocol.Perspective, +) LongHeaderOpener { + opener := newLongHeaderOpener(aead, headerProtector) + // The server drops Initial keys when first successfully processing a Handshake packet. + if perspective == protocol.PerspectiveClient { + return opener + } + return &handshakeOpener{ + LongHeaderOpener: opener, + dropInitialKeys: dropInitialKeys, + } +} + +func (o *handshakeOpener) Open(dst, src []byte, pn protocol.PacketNumber, ad []byte) ([]byte, error) { + dec, err := o.LongHeaderOpener.Open(dst, src, pn, ad) + if err == nil && !o.dropped { + o.dropInitialKeys() + o.dropped = true + } + return dec, err +} diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/cipher_suite.go b/vendor/github.com/quic-go/quic-go/internal/handshake/cipher_suite.go deleted file mode 100644 index 265231f0c..000000000 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/cipher_suite.go +++ /dev/null @@ -1,104 +0,0 @@ -package handshake - -import ( - "crypto" - "crypto/aes" - "crypto/cipher" - "crypto/tls" - "fmt" - - "golang.org/x/crypto/chacha20poly1305" -) - -// These cipher suite implementations are copied from the standard library crypto/tls package. - -const aeadNonceLength = 12 - -type cipherSuite struct { - ID uint16 - Hash crypto.Hash - KeyLen int - AEAD func(key, nonceMask []byte) cipher.AEAD -} - -func (s cipherSuite) IVLen() int { return aeadNonceLength } - -func getCipherSuite(id uint16) *cipherSuite { - switch id { - case tls.TLS_AES_128_GCM_SHA256: - return &cipherSuite{ID: tls.TLS_AES_128_GCM_SHA256, Hash: crypto.SHA256, KeyLen: 16, AEAD: aeadAESGCMTLS13} - case tls.TLS_CHACHA20_POLY1305_SHA256: - return &cipherSuite{ID: tls.TLS_CHACHA20_POLY1305_SHA256, Hash: crypto.SHA256, KeyLen: 32, AEAD: aeadChaCha20Poly1305} - case tls.TLS_AES_256_GCM_SHA384: - return &cipherSuite{ID: tls.TLS_AES_256_GCM_SHA384, Hash: crypto.SHA384, KeyLen: 32, AEAD: aeadAESGCMTLS13} - default: - panic(fmt.Sprintf("unknown cypher suite: %d", id)) - } -} - -func aeadAESGCMTLS13(key, nonceMask []byte) cipher.AEAD { - if len(nonceMask) != aeadNonceLength { - panic("tls: internal error: wrong nonce length") - } - aes, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - aead, err := cipher.NewGCM(aes) - if err != nil { - panic(err) - } - - ret := &xorNonceAEAD{aead: aead} - copy(ret.nonceMask[:], nonceMask) - return ret -} - -func aeadChaCha20Poly1305(key, nonceMask []byte) cipher.AEAD { - if len(nonceMask) != aeadNonceLength { - panic("tls: internal error: wrong nonce length") - } - aead, err := chacha20poly1305.New(key) - if err != nil { - panic(err) - } - - ret := &xorNonceAEAD{aead: aead} - copy(ret.nonceMask[:], nonceMask) - return ret -} - -// xorNonceAEAD wraps an AEAD by XORing in a fixed pattern to the nonce -// before each call. -type xorNonceAEAD struct { - nonceMask [aeadNonceLength]byte - aead cipher.AEAD -} - -func (f *xorNonceAEAD) NonceSize() int { return 8 } // 64-bit sequence number -func (f *xorNonceAEAD) Overhead() int { return f.aead.Overhead() } -func (f *xorNonceAEAD) explicitNonceLen() int { return 0 } - -func (f *xorNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte { - for i, b := range nonce { - f.nonceMask[4+i] ^= b - } - result := f.aead.Seal(out, f.nonceMask[:], plaintext, additionalData) - for i, b := range nonce { - f.nonceMask[4+i] ^= b - } - - return result -} - -func (f *xorNonceAEAD) Open(out, nonce, ciphertext, additionalData []byte) ([]byte, error) { - for i, b := range nonce { - f.nonceMask[4+i] ^= b - } - result, err := f.aead.Open(out, f.nonceMask[:], ciphertext, additionalData) - for i, b := range nonce { - f.nonceMask[4+i] ^= b - } - - return result, err -} diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/conn.go b/vendor/github.com/quic-go/quic-go/internal/handshake/conn.go deleted file mode 100644 index 54af823ba..000000000 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/conn.go +++ /dev/null @@ -1,21 +0,0 @@ -package handshake - -import ( - "net" - "time" -) - -type conn struct { - localAddr, remoteAddr net.Addr -} - -var _ net.Conn = &conn{} - -func (c *conn) Read([]byte) (int, error) { return 0, nil } -func (c *conn) Write([]byte) (int, error) { return 0, nil } -func (c *conn) Close() error { return nil } -func (c *conn) RemoteAddr() net.Addr { return c.remoteAddr } -func (c *conn) LocalAddr() net.Addr { return c.localAddr } -func (c *conn) SetReadDeadline(time.Time) error { return nil } -func (c *conn) SetWriteDeadline(time.Time) error { return nil } -func (c *conn) SetDeadline(time.Time) error { return nil } diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/crypto_setup.go b/vendor/github.com/quic-go/quic-go/internal/handshake/crypto_setup.go index 861494c47..8c9c2a8f8 100644 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/crypto_setup.go +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/crypto_setup.go @@ -6,10 +6,10 @@ import ( "crypto/tls" "errors" "fmt" + "io" + "math" "net" - "strings" "sync" - "sync/atomic" "time" "github.com/quic-go/quic-go/internal/protocol" @@ -25,25 +25,102 @@ type quicVersionContextKey struct{} var QUICVersionContextKey = &quicVersionContextKey{} +// TLS unexpected_message alert +const alertUnexpectedMessage uint8 = 10 + +type messageType uint8 + +// TLS handshake message types. +const ( + typeClientHello messageType = 1 + typeServerHello messageType = 2 + typeNewSessionTicket messageType = 4 + typeEncryptedExtensions messageType = 8 + typeCertificate messageType = 11 + typeCertificateRequest messageType = 13 + typeCertificateVerify messageType = 15 + typeFinished messageType = 20 +) + +func (m messageType) String() string { + switch m { + case typeClientHello: + return "ClientHello" + case typeServerHello: + return "ServerHello" + case typeNewSessionTicket: + return "NewSessionTicket" + case typeEncryptedExtensions: + return "EncryptedExtensions" + case typeCertificate: + return "Certificate" + case typeCertificateRequest: + return "CertificateRequest" + case typeCertificateVerify: + return "CertificateVerify" + case typeFinished: + return "Finished" + default: + return fmt.Sprintf("unknown message type: %d", m) + } +} + const clientSessionStateRevision = 3 -type cryptoSetup struct { - tlsConf *tls.Config - conn *qtls.QUICConn +type conn struct { + localAddr, remoteAddr net.Addr +} - events []Event +var _ net.Conn = &conn{} + +func newConn(local, remote net.Addr) net.Conn { + return &conn{ + localAddr: local, + remoteAddr: remote, + } +} + +func (c *conn) Read([]byte) (int, error) { return 0, nil } +func (c *conn) Write([]byte) (int, error) { return 0, nil } +func (c *conn) Close() error { return nil } +func (c *conn) RemoteAddr() net.Addr { return c.remoteAddr } +func (c *conn) LocalAddr() net.Addr { return c.localAddr } +func (c *conn) SetReadDeadline(time.Time) error { return nil } +func (c *conn) SetWriteDeadline(time.Time) error { return nil } +func (c *conn) SetDeadline(time.Time) error { return nil } + +type cryptoSetup struct { + tlsConf *tls.Config + extraConf *qtls.ExtraConfig + conn *qtls.Conn version protocol.VersionNumber + messageChan chan []byte + isReadingHandshakeMessage chan struct{} + readFirstHandshakeMessage bool + ourParams *wire.TransportParameters peerParams *wire.TransportParameters + paramsChan <-chan []byte - zeroRTTParameters *wire.TransportParameters - allow0RTT bool + runner handshakeRunner + + alertChan chan uint8 + // handshakeDone is closed as soon as the go routine running qtls.Handshake() returns + handshakeDone chan struct{} + // is closed when Close() is called + closeChan chan struct{} + + zeroRTTParameters *wire.TransportParameters + clientHelloWritten bool + clientHelloWrittenChan chan struct{} // is closed as soon as the ClientHello is written + zeroRTTParametersChan chan<- *wire.TransportParameters + allow0RTT bool rttStats *utils.RTTStats - tracer *logging.ConnectionTracer + tracer logging.ConnectionTracer logger utils.Logger perspective protocol.Perspective @@ -52,151 +129,169 @@ type cryptoSetup struct { handshakeCompleteTime time.Time + readEncLevel protocol.EncryptionLevel + writeEncLevel protocol.EncryptionLevel + zeroRTTOpener LongHeaderOpener // only set for the server zeroRTTSealer LongHeaderSealer // only set for the client + initialStream io.Writer initialOpener LongHeaderOpener initialSealer LongHeaderSealer + handshakeStream io.Writer handshakeOpener LongHeaderOpener handshakeSealer LongHeaderSealer - used0RTT atomic.Bool - aead *updatableAEAD has1RTTSealer bool has1RTTOpener bool } -var _ CryptoSetup = &cryptoSetup{} +var ( + _ qtls.RecordLayer = &cryptoSetup{} + _ CryptoSetup = &cryptoSetup{} +) // NewCryptoSetupClient creates a new crypto setup for the client func NewCryptoSetupClient( + initialStream io.Writer, + handshakeStream io.Writer, connID protocol.ConnectionID, + localAddr net.Addr, + remoteAddr net.Addr, tp *wire.TransportParameters, + runner handshakeRunner, tlsConf *tls.Config, enable0RTT bool, rttStats *utils.RTTStats, - tracer *logging.ConnectionTracer, + tracer logging.ConnectionTracer, logger utils.Logger, version protocol.VersionNumber, -) CryptoSetup { - cs := newCryptoSetup( +) (CryptoSetup, <-chan *wire.TransportParameters /* ClientHello written. Receive nil for non-0-RTT */) { + cs, clientHelloWritten := newCryptoSetup( + initialStream, + handshakeStream, connID, tp, + runner, + tlsConf, + enable0RTT, rttStats, tracer, logger, protocol.PerspectiveClient, version, ) - - tlsConf = tlsConf.Clone() - tlsConf.MinVersion = tls.VersionTLS13 - quicConf := &qtls.QUICConfig{TLSConfig: tlsConf} - qtls.SetupConfigForClient(quicConf, cs.marshalDataForSessionState, cs.handleDataFromSessionState) - cs.tlsConf = tlsConf - - cs.conn = qtls.QUICClient(quicConf) - cs.conn.SetTransportParameters(cs.ourParams.Marshal(protocol.PerspectiveClient)) - - return cs + cs.conn = qtls.Client(newConn(localAddr, remoteAddr), cs.tlsConf, cs.extraConf) + return cs, clientHelloWritten } // NewCryptoSetupServer creates a new crypto setup for the server func NewCryptoSetupServer( + initialStream io.Writer, + handshakeStream io.Writer, connID protocol.ConnectionID, - localAddr, remoteAddr net.Addr, + localAddr net.Addr, + remoteAddr net.Addr, tp *wire.TransportParameters, + runner handshakeRunner, tlsConf *tls.Config, allow0RTT bool, rttStats *utils.RTTStats, - tracer *logging.ConnectionTracer, + tracer logging.ConnectionTracer, logger utils.Logger, version protocol.VersionNumber, ) CryptoSetup { - cs := newCryptoSetup( + cs, _ := newCryptoSetup( + initialStream, + handshakeStream, connID, tp, + runner, + tlsConf, + allow0RTT, rttStats, tracer, logger, protocol.PerspectiveServer, version, ) - cs.allow0RTT = allow0RTT - - quicConf := &qtls.QUICConfig{TLSConfig: tlsConf} - qtls.SetupConfigForServer(quicConf, cs.allow0RTT, cs.getDataForSessionTicket, cs.handleSessionTicket) - addConnToClientHelloInfo(quicConf.TLSConfig, localAddr, remoteAddr) - - cs.tlsConf = quicConf.TLSConfig - cs.conn = qtls.QUICServer(quicConf) - + cs.conn = qtls.Server(newConn(localAddr, remoteAddr), cs.tlsConf, cs.extraConf) return cs } -// The tls.Config contains two callbacks that pass in a tls.ClientHelloInfo. -// Since crypto/tls doesn't do it, we need to make sure to set the Conn field with a fake net.Conn -// that allows the caller to get the local and the remote address. -func addConnToClientHelloInfo(conf *tls.Config, localAddr, remoteAddr net.Addr) { - if conf.GetConfigForClient != nil { - gcfc := conf.GetConfigForClient - conf.GetConfigForClient = func(info *tls.ClientHelloInfo) (*tls.Config, error) { - info.Conn = &conn{localAddr: localAddr, remoteAddr: remoteAddr} - c, err := gcfc(info) - if c != nil { - c = c.Clone() - // This won't be necessary anymore once https://github.com/golang/go/issues/63722 is accepted. - c.MinVersion = tls.VersionTLS13 - // We're returning a tls.Config here, so we need to apply this recursively. - addConnToClientHelloInfo(c, localAddr, remoteAddr) - } - return c, err - } - } - if conf.GetCertificate != nil { - gc := conf.GetCertificate - conf.GetCertificate = func(info *tls.ClientHelloInfo) (*tls.Certificate, error) { - info.Conn = &conn{localAddr: localAddr, remoteAddr: remoteAddr} - return gc(info) - } - } -} - func newCryptoSetup( + initialStream io.Writer, + handshakeStream io.Writer, connID protocol.ConnectionID, tp *wire.TransportParameters, + runner handshakeRunner, + tlsConf *tls.Config, + enable0RTT bool, rttStats *utils.RTTStats, - tracer *logging.ConnectionTracer, + tracer logging.ConnectionTracer, logger utils.Logger, perspective protocol.Perspective, version protocol.VersionNumber, -) *cryptoSetup { +) (*cryptoSetup, <-chan *wire.TransportParameters /* ClientHello written. Receive nil for non-0-RTT */) { initialSealer, initialOpener := NewInitialAEAD(connID, perspective, version) - if tracer != nil && tracer.UpdatedKeyFromTLS != nil { + if tracer != nil { tracer.UpdatedKeyFromTLS(protocol.EncryptionInitial, protocol.PerspectiveClient) tracer.UpdatedKeyFromTLS(protocol.EncryptionInitial, protocol.PerspectiveServer) } - return &cryptoSetup{ - initialSealer: initialSealer, - initialOpener: initialOpener, - aead: newUpdatableAEAD(rttStats, tracer, logger, version), - events: make([]Event, 0, 16), - ourParams: tp, - rttStats: rttStats, - tracer: tracer, - logger: logger, - perspective: perspective, - version: version, + extHandler := newExtensionHandler(tp.Marshal(perspective), perspective, version) + zeroRTTParametersChan := make(chan *wire.TransportParameters, 1) + cs := &cryptoSetup{ + tlsConf: tlsConf, + initialStream: initialStream, + initialSealer: initialSealer, + initialOpener: initialOpener, + handshakeStream: handshakeStream, + aead: newUpdatableAEAD(rttStats, tracer, logger, version), + readEncLevel: protocol.EncryptionInitial, + writeEncLevel: protocol.EncryptionInitial, + runner: runner, + allow0RTT: enable0RTT, + ourParams: tp, + paramsChan: extHandler.TransportParameters(), + rttStats: rttStats, + tracer: tracer, + logger: logger, + perspective: perspective, + handshakeDone: make(chan struct{}), + alertChan: make(chan uint8), + clientHelloWrittenChan: make(chan struct{}), + zeroRTTParametersChan: zeroRTTParametersChan, + messageChan: make(chan []byte, 1), + isReadingHandshakeMessage: make(chan struct{}), + closeChan: make(chan struct{}), + version: version, } + var maxEarlyData uint32 + if enable0RTT { + maxEarlyData = math.MaxUint32 + } + cs.extraConf = &qtls.ExtraConfig{ + GetExtensions: extHandler.GetExtensions, + ReceivedExtensions: extHandler.ReceivedExtensions, + AlternativeRecordLayer: cs, + EnforceNextProtoSelection: true, + MaxEarlyData: maxEarlyData, + Accept0RTT: cs.accept0RTT, + Rejected0RTT: cs.rejected0RTT, + Enable0RTT: enable0RTT, + GetAppDataForSessionState: cs.marshalDataForSessionState, + SetAppDataFromSessionState: cs.handleDataFromSessionState, + } + return cs, zeroRTTParametersChan } func (h *cryptoSetup) ChangeConnectionID(id protocol.ConnectionID) { initialSealer, initialOpener := NewInitialAEAD(id, h.perspective, h.version) h.initialSealer = initialSealer h.initialOpener = initialOpener - if h.tracer != nil && h.tracer.UpdatedKeyFromTLS != nil { + if h.tracer != nil { h.tracer.UpdatedKeyFromTLS(protocol.EncryptionInitial, protocol.PerspectiveClient) h.tracer.UpdatedKeyFromTLS(protocol.EncryptionInitial, protocol.PerspectiveServer) } @@ -206,109 +301,142 @@ func (h *cryptoSetup) SetLargest1RTTAcked(pn protocol.PacketNumber) error { return h.aead.SetLargestAcked(pn) } -func (h *cryptoSetup) StartHandshake() error { - err := h.conn.Start(context.WithValue(context.Background(), QUICVersionContextKey, h.version)) - if err != nil { - return wrapError(err) - } - for { - ev := h.conn.NextEvent() - done, err := h.handleEvent(ev) - if err != nil { - return wrapError(err) +func (h *cryptoSetup) RunHandshake() { + // Handle errors that might occur when HandleData() is called. + handshakeComplete := make(chan struct{}) + handshakeErrChan := make(chan error, 1) + go func() { + defer close(h.handshakeDone) + if err := h.conn.HandshakeContext(context.WithValue(context.Background(), QUICVersionContextKey, h.version)); err != nil { + handshakeErrChan <- err + return } - if done { - break - } - } + close(handshakeComplete) + }() + if h.perspective == protocol.PerspectiveClient { - if h.zeroRTTSealer != nil && h.zeroRTTParameters != nil { - h.logger.Debugf("Doing 0-RTT.") - h.events = append(h.events, Event{Kind: EventRestoredTransportParameters, TransportParameters: h.zeroRTTParameters}) - } else { - h.logger.Debugf("Not doing 0-RTT. Has sealer: %t, has params: %t", h.zeroRTTSealer != nil, h.zeroRTTParameters != nil) + select { + case err := <-handshakeErrChan: + h.onError(0, err.Error()) + return + case <-h.clientHelloWrittenChan: } } - return nil + + select { + case <-handshakeComplete: // return when the handshake is done + h.mutex.Lock() + h.handshakeCompleteTime = time.Now() + h.mutex.Unlock() + h.runner.OnHandshakeComplete() + case <-h.closeChan: + // wait until the Handshake() go routine has returned + <-h.handshakeDone + case alert := <-h.alertChan: + handshakeErr := <-handshakeErrChan + h.onError(alert, handshakeErr.Error()) + } +} + +func (h *cryptoSetup) onError(alert uint8, message string) { + var err error + if alert == 0 { + err = &qerr.TransportError{ErrorCode: qerr.InternalError, ErrorMessage: message} + } else { + err = qerr.NewLocalCryptoError(alert, message) + } + h.runner.OnError(err) } // Close closes the crypto setup. // It aborts the handshake, if it is still running. +// It must only be called once. func (h *cryptoSetup) Close() error { - return h.conn.Close() + close(h.closeChan) + // wait until qtls.Handshake() actually returned + <-h.handshakeDone + return nil } -// HandleMessage handles a TLS handshake message. +// handleMessage handles a TLS handshake message. // It is called by the crypto streams when a new message is available. -func (h *cryptoSetup) HandleMessage(data []byte, encLevel protocol.EncryptionLevel) error { - if err := h.handleMessage(data, encLevel); err != nil { - return wrapError(err) +// It returns if it is done with messages on the same encryption level. +func (h *cryptoSetup) HandleMessage(data []byte, encLevel protocol.EncryptionLevel) bool /* stream finished */ { + msgType := messageType(data[0]) + h.logger.Debugf("Received %s message (%d bytes, encryption level: %s)", msgType, len(data), encLevel) + if err := h.checkEncryptionLevel(msgType, encLevel); err != nil { + h.onError(alertUnexpectedMessage, err.Error()) + return false + } + if encLevel != protocol.Encryption1RTT { + select { + case h.messageChan <- data: + case <-h.handshakeDone: // handshake errored, nobody is going to consume this message + return false + } + } + if encLevel == protocol.Encryption1RTT { + h.messageChan <- data + h.handlePostHandshakeMessage() + return false + } +readLoop: + for { + select { + case data := <-h.paramsChan: + if data == nil { + h.onError(0x6d, "missing quic_transport_parameters extension") + } else { + h.handleTransportParameters(data) + } + case <-h.isReadingHandshakeMessage: + break readLoop + case <-h.handshakeDone: + break readLoop + case <-h.closeChan: + break readLoop + } + } + // We're done with the Initial encryption level after processing a ClientHello / ServerHello, + // but only if a handshake opener and sealer was created. + // Otherwise, a HelloRetryRequest was performed. + // We're done with the Handshake encryption level after processing the Finished message. + return ((msgType == typeClientHello || msgType == typeServerHello) && h.handshakeOpener != nil && h.handshakeSealer != nil) || + msgType == typeFinished +} + +func (h *cryptoSetup) checkEncryptionLevel(msgType messageType, encLevel protocol.EncryptionLevel) error { + var expected protocol.EncryptionLevel + switch msgType { + case typeClientHello, typeServerHello: + expected = protocol.EncryptionInitial + case typeEncryptedExtensions, + typeCertificate, + typeCertificateRequest, + typeCertificateVerify, + typeFinished: + expected = protocol.EncryptionHandshake + case typeNewSessionTicket: + expected = protocol.Encryption1RTT + default: + return fmt.Errorf("unexpected handshake message: %d", msgType) + } + if encLevel != expected { + return fmt.Errorf("expected handshake message %s to have encryption level %s, has %s", msgType, expected, encLevel) } return nil } -func (h *cryptoSetup) handleMessage(data []byte, encLevel protocol.EncryptionLevel) error { - if err := h.conn.HandleData(qtls.ToTLSEncryptionLevel(encLevel), data); err != nil { - return err - } - for { - ev := h.conn.NextEvent() - done, err := h.handleEvent(ev) - if err != nil { - return err - } - if done { - return nil - } - } -} - -func (h *cryptoSetup) handleEvent(ev qtls.QUICEvent) (done bool, err error) { - switch ev.Kind { - case qtls.QUICNoEvent: - return true, nil - case qtls.QUICSetReadSecret: - h.SetReadKey(ev.Level, ev.Suite, ev.Data) - return false, nil - case qtls.QUICSetWriteSecret: - h.SetWriteKey(ev.Level, ev.Suite, ev.Data) - return false, nil - case qtls.QUICTransportParameters: - return false, h.handleTransportParameters(ev.Data) - case qtls.QUICTransportParametersRequired: - h.conn.SetTransportParameters(h.ourParams.Marshal(h.perspective)) - return false, nil - case qtls.QUICRejectedEarlyData: - h.rejected0RTT() - return false, nil - case qtls.QUICWriteData: - h.WriteRecord(ev.Level, ev.Data) - return false, nil - case qtls.QUICHandshakeDone: - h.handshakeComplete() - return false, nil - default: - return false, fmt.Errorf("unexpected event: %d", ev.Kind) - } -} - -func (h *cryptoSetup) NextEvent() Event { - if len(h.events) == 0 { - return Event{Kind: EventNoEvent} - } - ev := h.events[0] - h.events = h.events[1:] - return ev -} - -func (h *cryptoSetup) handleTransportParameters(data []byte) error { +func (h *cryptoSetup) handleTransportParameters(data []byte) { var tp wire.TransportParameters if err := tp.Unmarshal(data, h.perspective.Opposite()); err != nil { - return err + h.runner.OnError(&qerr.TransportError{ + ErrorCode: qerr.TransportParameterError, + ErrorMessage: err.Error(), + }) } h.peerParams = &tp - h.events = append(h.events, Event{Kind: EventReceivedTransportParameters, TransportParameters: h.peerParams}) - return nil + h.runner.OnReceivedParams(h.peerParams) } // must be called after receiving the transport parameters @@ -349,52 +477,25 @@ func (h *cryptoSetup) handleDataFromSessionStateImpl(data []byte) (*wire.Transpo return &tp, nil } -func (h *cryptoSetup) getDataForSessionTicket() []byte { - ticket := &sessionTicket{ - RTT: h.rttStats.SmoothedRTT(), - } - if h.allow0RTT { - ticket.Parameters = h.ourParams - } - return ticket.Marshal() -} - -// GetSessionTicket generates a new session ticket. -// Due to limitations in crypto/tls, it's only possible to generate a single session ticket per connection. -// It is only valid for the server. +// only valid for the server func (h *cryptoSetup) GetSessionTicket() ([]byte, error) { - if err := qtls.SendSessionTicket(h.conn, h.allow0RTT); err != nil { - // Session tickets might be disabled by tls.Config.SessionTicketsDisabled. - // We can't check h.tlsConfig here, since the actual config might have been obtained from - // the GetConfigForClient callback. - // See https://github.com/golang/go/issues/62032. - // Once that issue is resolved, this error assertion can be removed. - if strings.Contains(err.Error(), "session ticket keys unavailable") { - return nil, nil - } - return nil, err + var appData []byte + // Save transport parameters to the session ticket if we're allowing 0-RTT. + if h.extraConf.MaxEarlyData > 0 { + appData = (&sessionTicket{ + Parameters: h.ourParams, + RTT: h.rttStats.SmoothedRTT(), + }).Marshal() } - ev := h.conn.NextEvent() - if ev.Kind != qtls.QUICWriteData || ev.Level != qtls.QUICEncryptionLevelApplication { - panic("crypto/tls bug: where's my session ticket?") - } - ticket := ev.Data - if ev := h.conn.NextEvent(); ev.Kind != qtls.QUICNoEvent { - panic("crypto/tls bug: why more than one ticket?") - } - return ticket, nil + return h.conn.GetSessionTicket(appData) } -// handleSessionTicket is called for the server when receiving the client's session ticket. -// It reads parameters from the session ticket and decides whether to accept 0-RTT when the session ticket is used for 0-RTT. -func (h *cryptoSetup) handleSessionTicket(sessionTicketData []byte, using0RTT bool) bool { +// accept0RTT is called for the server when receiving the client's session ticket. +// It decides whether to accept 0-RTT. +func (h *cryptoSetup) accept0RTT(sessionTicketData []byte) bool { var t sessionTicket - if err := t.Unmarshal(sessionTicketData, using0RTT); err != nil { - h.logger.Debugf("Unmarshalling session ticket failed: %s", err.Error()) - return false - } - h.rttStats.SetInitialRTT(t.RTT) - if !using0RTT { + if err := t.Unmarshal(sessionTicketData); err != nil { + h.logger.Debugf("Unmarshalling transport parameters from session ticket failed: %s", err.Error()) return false } valid := h.ourParams.ValidFor0RTT(t.Parameters) @@ -407,6 +508,7 @@ func (h *cryptoSetup) handleSessionTicket(sessionTicketData []byte, using0RTT bo return false } h.logger.Debugf("Accepting 0-RTT. Restoring RTT from session ticket: %s", t.RTT) + h.rttStats.SetInitialRTT(t.RTT) return true } @@ -420,16 +522,64 @@ func (h *cryptoSetup) rejected0RTT() { h.mutex.Unlock() if had0RTTKeys { - h.events = append(h.events, Event{Kind: EventDiscard0RTTKeys}) + h.runner.DropKeys(protocol.Encryption0RTT) } } -func (h *cryptoSetup) SetReadKey(el qtls.QUICEncryptionLevel, suiteID uint16, trafficSecret []byte) { - suite := getCipherSuite(suiteID) +func (h *cryptoSetup) handlePostHandshakeMessage() { + // make sure the handshake has already completed + <-h.handshakeDone + + done := make(chan struct{}) + defer close(done) + + // h.alertChan is an unbuffered channel. + // If an error occurs during conn.HandlePostHandshakeMessage, + // it will be sent on this channel. + // Read it from a go-routine so that HandlePostHandshakeMessage doesn't deadlock. + alertChan := make(chan uint8, 1) + go func() { + <-h.isReadingHandshakeMessage + select { + case alert := <-h.alertChan: + alertChan <- alert + case <-done: + } + }() + + if err := h.conn.HandlePostHandshakeMessage(); err != nil { + select { + case <-h.closeChan: + case alert := <-alertChan: + h.onError(alert, err.Error()) + } + } +} + +// ReadHandshakeMessage is called by TLS. +// It blocks until a new handshake message is available. +func (h *cryptoSetup) ReadHandshakeMessage() ([]byte, error) { + if !h.readFirstHandshakeMessage { + h.readFirstHandshakeMessage = true + } else { + select { + case h.isReadingHandshakeMessage <- struct{}{}: + case <-h.closeChan: + return nil, errors.New("error while handling the handshake message") + } + } + select { + case msg := <-h.messageChan: + return msg, nil + case <-h.closeChan: + return nil, errors.New("error while handling the handshake message") + } +} + +func (h *cryptoSetup) SetReadKey(encLevel qtls.EncryptionLevel, suite *qtls.CipherSuiteTLS13, trafficSecret []byte) { h.mutex.Lock() - //nolint:exhaustive // The TLS stack doesn't export Initial keys. - switch el { - case qtls.QUICEncryptionLevelEarly: + switch encLevel { + case qtls.Encryption0RTT: if h.perspective == protocol.PerspectiveClient { panic("Received 0-RTT read key for the client") } @@ -437,19 +587,27 @@ func (h *cryptoSetup) SetReadKey(el qtls.QUICEncryptionLevel, suiteID uint16, tr createAEAD(suite, trafficSecret, h.version), newHeaderProtector(suite, trafficSecret, true, h.version), ) - h.used0RTT.Store(true) + h.mutex.Unlock() if h.logger.Debug() { h.logger.Debugf("Installed 0-RTT Read keys (using %s)", tls.CipherSuiteName(suite.ID)) } - case qtls.QUICEncryptionLevelHandshake: - h.handshakeOpener = newLongHeaderOpener( + if h.tracer != nil { + h.tracer.UpdatedKeyFromTLS(protocol.Encryption0RTT, h.perspective.Opposite()) + } + return + case qtls.EncryptionHandshake: + h.readEncLevel = protocol.EncryptionHandshake + h.handshakeOpener = newHandshakeOpener( createAEAD(suite, trafficSecret, h.version), newHeaderProtector(suite, trafficSecret, true, h.version), + h.dropInitialKeys, + h.perspective, ) if h.logger.Debug() { h.logger.Debugf("Installed Handshake Read keys (using %s)", tls.CipherSuiteName(suite.ID)) } - case qtls.QUICEncryptionLevelApplication: + case qtls.EncryptionApplication: + h.readEncLevel = protocol.Encryption1RTT h.aead.SetReadKey(suite, trafficSecret) h.has1RTTOpener = true if h.logger.Debug() { @@ -459,18 +617,15 @@ func (h *cryptoSetup) SetReadKey(el qtls.QUICEncryptionLevel, suiteID uint16, tr panic("unexpected read encryption level") } h.mutex.Unlock() - h.events = append(h.events, Event{Kind: EventReceivedReadKeys}) - if h.tracer != nil && h.tracer.UpdatedKeyFromTLS != nil { - h.tracer.UpdatedKeyFromTLS(qtls.FromTLSEncryptionLevel(el), h.perspective.Opposite()) + if h.tracer != nil { + h.tracer.UpdatedKeyFromTLS(h.readEncLevel, h.perspective.Opposite()) } } -func (h *cryptoSetup) SetWriteKey(el qtls.QUICEncryptionLevel, suiteID uint16, trafficSecret []byte) { - suite := getCipherSuite(suiteID) +func (h *cryptoSetup) SetWriteKey(encLevel qtls.EncryptionLevel, suite *qtls.CipherSuiteTLS13, trafficSecret []byte) { h.mutex.Lock() - //nolint:exhaustive // The TLS stack doesn't export Initial keys. - switch el { - case qtls.QUICEncryptionLevelEarly: + switch encLevel { + case qtls.Encryption0RTT: if h.perspective == protocol.PerspectiveServer { panic("Received 0-RTT write key for the server") } @@ -482,31 +637,32 @@ func (h *cryptoSetup) SetWriteKey(el qtls.QUICEncryptionLevel, suiteID uint16, t if h.logger.Debug() { h.logger.Debugf("Installed 0-RTT Write keys (using %s)", tls.CipherSuiteName(suite.ID)) } - if h.tracer != nil && h.tracer.UpdatedKeyFromTLS != nil { + if h.tracer != nil { h.tracer.UpdatedKeyFromTLS(protocol.Encryption0RTT, h.perspective) } - // don't set used0RTT here. 0-RTT might still get rejected. return - case qtls.QUICEncryptionLevelHandshake: - h.handshakeSealer = newLongHeaderSealer( + case qtls.EncryptionHandshake: + h.writeEncLevel = protocol.EncryptionHandshake + h.handshakeSealer = newHandshakeSealer( createAEAD(suite, trafficSecret, h.version), newHeaderProtector(suite, trafficSecret, true, h.version), + h.dropInitialKeys, + h.perspective, ) if h.logger.Debug() { h.logger.Debugf("Installed Handshake Write keys (using %s)", tls.CipherSuiteName(suite.ID)) } - case qtls.QUICEncryptionLevelApplication: + case qtls.EncryptionApplication: + h.writeEncLevel = protocol.Encryption1RTT h.aead.SetWriteKey(suite, trafficSecret) h.has1RTTSealer = true if h.logger.Debug() { h.logger.Debugf("Installed 1-RTT Write keys (using %s)", tls.CipherSuiteName(suite.ID)) } if h.zeroRTTSealer != nil { - // Once we receive handshake keys, we know that 0-RTT was not rejected. - h.used0RTT.Store(true) h.zeroRTTSealer = nil h.logger.Debugf("Dropping 0-RTT keys.") - if h.tracer != nil && h.tracer.DroppedEncryptionLevel != nil { + if h.tracer != nil { h.tracer.DroppedEncryptionLevel(protocol.Encryption0RTT) } } @@ -514,40 +670,56 @@ func (h *cryptoSetup) SetWriteKey(el qtls.QUICEncryptionLevel, suiteID uint16, t panic("unexpected write encryption level") } h.mutex.Unlock() - if h.tracer != nil && h.tracer.UpdatedKeyFromTLS != nil { - h.tracer.UpdatedKeyFromTLS(qtls.FromTLSEncryptionLevel(el), h.perspective) + if h.tracer != nil { + h.tracer.UpdatedKeyFromTLS(h.writeEncLevel, h.perspective) } } // WriteRecord is called when TLS writes data -func (h *cryptoSetup) WriteRecord(encLevel qtls.QUICEncryptionLevel, p []byte) { - //nolint:exhaustive // handshake records can only be written for Initial and Handshake. - switch encLevel { - case qtls.QUICEncryptionLevelInitial: - h.events = append(h.events, Event{Kind: EventWriteInitialData, Data: p}) - case qtls.QUICEncryptionLevelHandshake: - h.events = append(h.events, Event{Kind: EventWriteHandshakeData, Data: p}) - case qtls.QUICEncryptionLevelApplication: - panic("unexpected write") +func (h *cryptoSetup) WriteRecord(p []byte) (int, error) { + h.mutex.Lock() + defer h.mutex.Unlock() + + //nolint:exhaustive // LS records can only be written for Initial and Handshake. + switch h.writeEncLevel { + case protocol.EncryptionInitial: + // assume that the first WriteRecord call contains the ClientHello + n, err := h.initialStream.Write(p) + if !h.clientHelloWritten && h.perspective == protocol.PerspectiveClient { + h.clientHelloWritten = true + close(h.clientHelloWrittenChan) + if h.zeroRTTSealer != nil && h.zeroRTTParameters != nil { + h.logger.Debugf("Doing 0-RTT.") + h.zeroRTTParametersChan <- h.zeroRTTParameters + } else { + h.logger.Debugf("Not doing 0-RTT.") + h.zeroRTTParametersChan <- nil + } + } + return n, err + case protocol.EncryptionHandshake: + return h.handshakeStream.Write(p) default: - panic(fmt.Sprintf("unexpected write encryption level: %s", encLevel)) + panic(fmt.Sprintf("unexpected write encryption level: %s", h.writeEncLevel)) } } -func (h *cryptoSetup) DiscardInitialKeys() { +func (h *cryptoSetup) SendAlert(alert uint8) { + select { + case h.alertChan <- alert: + case <-h.closeChan: + // no need to send an alert when we've already closed + } +} + +// used a callback in the handshakeSealer and handshakeOpener +func (h *cryptoSetup) dropInitialKeys() { h.mutex.Lock() - dropped := h.initialOpener != nil h.initialOpener = nil h.initialSealer = nil h.mutex.Unlock() - if dropped { - h.logger.Debugf("Dropping Initial keys.") - } -} - -func (h *cryptoSetup) handshakeComplete() { - h.handshakeCompleteTime = time.Now() - h.events = append(h.events, Event{Kind: EventHandshakeComplete}) + h.runner.DropKeys(protocol.EncryptionInitial) + h.logger.Debugf("Dropping Initial keys.") } func (h *cryptoSetup) SetHandshakeConfirmed() { @@ -562,6 +734,7 @@ func (h *cryptoSetup) SetHandshakeConfirmed() { } h.mutex.Unlock() if dropped { + h.runner.DropKeys(protocol.EncryptionHandshake) h.logger.Debugf("Dropping Handshake keys.") } } @@ -654,7 +827,7 @@ func (h *cryptoSetup) Get1RTTOpener() (ShortHeaderOpener, error) { if h.zeroRTTOpener != nil && time.Since(h.handshakeCompleteTime) > 3*h.rttStats.PTO(true) { h.zeroRTTOpener = nil h.logger.Debugf("Dropping 0-RTT keys.") - if h.tracer != nil && h.tracer.DroppedEncryptionLevel != nil { + if h.tracer != nil { h.tracer.DroppedEncryptionLevel(protocol.Encryption0RTT) } } @@ -666,16 +839,5 @@ func (h *cryptoSetup) Get1RTTOpener() (ShortHeaderOpener, error) { } func (h *cryptoSetup) ConnectionState() ConnectionState { - return ConnectionState{ - ConnectionState: h.conn.ConnectionState(), - Used0RTT: h.used0RTT.Load(), - } -} - -func wrapError(err error) error { - // alert 80 is an internal error - if alertErr := qtls.AlertError(0); errors.As(err, &alertErr) && alertErr != 80 { - return qerr.NewLocalCryptoError(uint8(alertErr), err) - } - return &qerr.TransportError{ErrorCode: qerr.InternalError, ErrorMessage: err.Error()} + return qtls.GetConnectionState(h.conn) } diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/header_protector.go b/vendor/github.com/quic-go/quic-go/internal/handshake/header_protector.go index fb6092e04..274fb30cb 100644 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/header_protector.go +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/header_protector.go @@ -10,6 +10,7 @@ import ( "golang.org/x/crypto/chacha20" "github.com/quic-go/quic-go/internal/protocol" + "github.com/quic-go/quic-go/internal/qtls" ) type headerProtector interface { @@ -24,7 +25,7 @@ func hkdfHeaderProtectionLabel(v protocol.VersionNumber) string { return "quic hp" } -func newHeaderProtector(suite *cipherSuite, trafficSecret []byte, isLongHeader bool, v protocol.VersionNumber) headerProtector { +func newHeaderProtector(suite *qtls.CipherSuiteTLS13, trafficSecret []byte, isLongHeader bool, v protocol.VersionNumber) headerProtector { hkdfLabel := hkdfHeaderProtectionLabel(v) switch suite.ID { case tls.TLS_AES_128_GCM_SHA256, tls.TLS_AES_256_GCM_SHA384: @@ -44,7 +45,7 @@ type aesHeaderProtector struct { var _ headerProtector = &aesHeaderProtector{} -func newAESHeaderProtector(suite *cipherSuite, trafficSecret []byte, isLongHeader bool, hkdfLabel string) headerProtector { +func newAESHeaderProtector(suite *qtls.CipherSuiteTLS13, trafficSecret []byte, isLongHeader bool, hkdfLabel string) headerProtector { hpKey := hkdfExpandLabel(suite.Hash, trafficSecret, []byte{}, hkdfLabel, suite.KeyLen) block, err := aes.NewCipher(hpKey) if err != nil { @@ -89,7 +90,7 @@ type chachaHeaderProtector struct { var _ headerProtector = &chachaHeaderProtector{} -func newChaChaHeaderProtector(suite *cipherSuite, trafficSecret []byte, isLongHeader bool, hkdfLabel string) headerProtector { +func newChaChaHeaderProtector(suite *qtls.CipherSuiteTLS13, trafficSecret []byte, isLongHeader bool, hkdfLabel string) headerProtector { hpKey := hkdfExpandLabel(suite.Hash, trafficSecret, []byte{}, hkdfLabel, suite.KeyLen) p := &chachaHeaderProtector{ diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/initial_aead.go b/vendor/github.com/quic-go/quic-go/internal/handshake/initial_aead.go index b0377c39a..3967fdb83 100644 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/initial_aead.go +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/initial_aead.go @@ -7,11 +7,13 @@ import ( "golang.org/x/crypto/hkdf" "github.com/quic-go/quic-go/internal/protocol" + "github.com/quic-go/quic-go/internal/qtls" ) var ( - quicSaltV1 = []byte{0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a} - quicSaltV2 = []byte{0x0d, 0xed, 0xe3, 0xde, 0xf7, 0x00, 0xa6, 0xdb, 0x81, 0x93, 0x81, 0xbe, 0x6e, 0x26, 0x9d, 0xcb, 0xf9, 0xbd, 0x2e, 0xd9} + quicSaltOld = []byte{0xaf, 0xbf, 0xec, 0x28, 0x99, 0x93, 0xd2, 0x4c, 0x9e, 0x97, 0x86, 0xf1, 0x9c, 0x61, 0x11, 0xe0, 0x43, 0x90, 0xa8, 0x99} + quicSaltV1 = []byte{0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a} + quicSaltV2 = []byte{0x0d, 0xed, 0xe3, 0xde, 0xf7, 0x00, 0xa6, 0xdb, 0x81, 0x93, 0x81, 0xbe, 0x6e, 0x26, 0x9d, 0xcb, 0xf9, 0xbd, 0x2e, 0xd9} ) const ( @@ -25,10 +27,18 @@ func getSalt(v protocol.VersionNumber) []byte { if v == protocol.Version2 { return quicSaltV2 } - return quicSaltV1 + if v == protocol.Version1 { + return quicSaltV1 + } + return quicSaltOld } -var initialSuite = getCipherSuite(tls.TLS_AES_128_GCM_SHA256) +var initialSuite = &qtls.CipherSuiteTLS13{ + ID: tls.TLS_AES_128_GCM_SHA256, + KeyLen: 16, + AEAD: qtls.AEADAESGCMTLS13, + Hash: crypto.SHA256, +} // NewInitialAEAD creates a new AEAD for Initial encryption / decryption. func NewInitialAEAD(connID protocol.ConnectionID, pers protocol.Perspective, v protocol.VersionNumber) (LongHeaderSealer, LongHeaderOpener) { @@ -44,8 +54,8 @@ func NewInitialAEAD(connID protocol.ConnectionID, pers protocol.Perspective, v p myKey, myIV := computeInitialKeyAndIV(mySecret, v) otherKey, otherIV := computeInitialKeyAndIV(otherSecret, v) - encrypter := initialSuite.AEAD(myKey, myIV) - decrypter := initialSuite.AEAD(otherKey, otherIV) + encrypter := qtls.AEADAESGCMTLS13(myKey, myIV) + decrypter := qtls.AEADAESGCMTLS13(otherKey, otherIV) return newLongHeaderSealer(encrypter, newHeaderProtector(initialSuite, mySecret, true, v)), newLongHeaderOpener(decrypter, newAESHeaderProtector(initialSuite, otherSecret, true, hkdfHeaderProtectionLabel(v))) diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/interface.go b/vendor/github.com/quic-go/quic-go/internal/handshake/interface.go index fab224f9b..f80b6e0e3 100644 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/interface.go +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/interface.go @@ -1,12 +1,12 @@ package handshake import ( - "crypto/tls" "errors" "io" "time" "github.com/quic-go/quic-go/internal/protocol" + "github.com/quic-go/quic-go/internal/qtls" "github.com/quic-go/quic-go/internal/wire" ) @@ -22,6 +22,9 @@ var ( ErrDecryptionFailed = errors.New("decryption failed") ) +// ConnectionState contains information about the state of the connection. +type ConnectionState = qtls.ConnectionState + type headerDecryptor interface { DecryptHeader(sample []byte, firstByte *byte, pnBytes []byte) } @@ -53,54 +56,29 @@ type ShortHeaderSealer interface { KeyPhase() protocol.KeyPhaseBit } -type ConnectionState struct { - tls.ConnectionState - Used0RTT bool +// A tlsExtensionHandler sends and received the QUIC TLS extension. +type tlsExtensionHandler interface { + GetExtensions(msgType uint8) []qtls.Extension + ReceivedExtensions(msgType uint8, exts []qtls.Extension) + TransportParameters() <-chan []byte } -// EventKind is the kind of handshake event. -type EventKind uint8 - -const ( - // EventNoEvent signals that there are no new handshake events - EventNoEvent EventKind = iota + 1 - // EventWriteInitialData contains new CRYPTO data to send at the Initial encryption level - EventWriteInitialData - // EventWriteHandshakeData contains new CRYPTO data to send at the Handshake encryption level - EventWriteHandshakeData - // EventReceivedReadKeys signals that new decryption keys are available. - // It doesn't say which encryption level those keys are for. - EventReceivedReadKeys - // EventDiscard0RTTKeys signals that the Handshake keys were discarded. - EventDiscard0RTTKeys - // EventReceivedTransportParameters contains the transport parameters sent by the peer. - EventReceivedTransportParameters - // EventRestoredTransportParameters contains the transport parameters restored from the session ticket. - // It is only used for the client. - EventRestoredTransportParameters - // EventHandshakeComplete signals that the TLS handshake was completed. - EventHandshakeComplete -) - -// Event is a handshake event. -type Event struct { - Kind EventKind - Data []byte - TransportParameters *wire.TransportParameters +type handshakeRunner interface { + OnReceivedParams(*wire.TransportParameters) + OnHandshakeComplete() + OnError(error) + DropKeys(protocol.EncryptionLevel) } // CryptoSetup handles the handshake and protecting / unprotecting packets type CryptoSetup interface { - StartHandshake() error + RunHandshake() io.Closer ChangeConnectionID(protocol.ConnectionID) GetSessionTicket() ([]byte, error) - HandleMessage([]byte, protocol.EncryptionLevel) error - NextEvent() Event - + HandleMessage([]byte, protocol.EncryptionLevel) bool SetLargest1RTTAcked(protocol.PacketNumber) error - DiscardInitialKeys() SetHandshakeConfirmed() ConnectionState() ConnectionState diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/mockgen.go b/vendor/github.com/quic-go/quic-go/internal/handshake/mockgen.go new file mode 100644 index 000000000..68b0988c6 --- /dev/null +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/mockgen.go @@ -0,0 +1,6 @@ +//go:build gomock || generate + +package handshake + +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package handshake -destination mock_handshake_runner_test.go github.com/quic-go/quic-go/internal/handshake HandshakeRunner" +type HandshakeRunner = handshakeRunner diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/retry.go b/vendor/github.com/quic-go/quic-go/internal/handshake/retry.go index 68fa53ed1..ff14f7e0d 100644 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/retry.go +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/retry.go @@ -11,11 +11,13 @@ import ( ) var ( - retryAEADv1 cipher.AEAD // used for QUIC v1 (RFC 9000) - retryAEADv2 cipher.AEAD // used for QUIC v2 (RFC 9369) + retryAEADdraft29 cipher.AEAD // used for QUIC draft versions up to 34 + retryAEADv1 cipher.AEAD // used for QUIC v1 (RFC 9000) + retryAEADv2 cipher.AEAD // used for QUIC v2 ) func init() { + retryAEADdraft29 = initAEAD([16]byte{0xcc, 0xce, 0x18, 0x7e, 0xd0, 0x9a, 0x09, 0xd0, 0x57, 0x28, 0x15, 0x5a, 0x6c, 0xb9, 0x6b, 0xe1}) retryAEADv1 = initAEAD([16]byte{0xbe, 0x0c, 0x69, 0x0b, 0x9f, 0x66, 0x57, 0x5a, 0x1d, 0x76, 0x6b, 0x54, 0xe3, 0x68, 0xc8, 0x4e}) retryAEADv2 = initAEAD([16]byte{0x8f, 0xb4, 0xb0, 0x1b, 0x56, 0xac, 0x48, 0xe2, 0x60, 0xfb, 0xcb, 0xce, 0xad, 0x7c, 0xcc, 0x92}) } @@ -33,10 +35,11 @@ func initAEAD(key [16]byte) cipher.AEAD { } var ( - retryBuf bytes.Buffer - retryMutex sync.Mutex - retryNonceV1 = [12]byte{0x46, 0x15, 0x99, 0xd3, 0x5d, 0x63, 0x2b, 0xf2, 0x23, 0x98, 0x25, 0xbb} - retryNonceV2 = [12]byte{0xd8, 0x69, 0x69, 0xbc, 0x2d, 0x7c, 0x6d, 0x99, 0x90, 0xef, 0xb0, 0x4a} + retryBuf bytes.Buffer + retryMutex sync.Mutex + retryNonceDraft29 = [12]byte{0xe5, 0x49, 0x30, 0xf9, 0x7f, 0x21, 0x36, 0xf0, 0x53, 0x0a, 0x8c, 0x1c} + retryNonceV1 = [12]byte{0x46, 0x15, 0x99, 0xd3, 0x5d, 0x63, 0x2b, 0xf2, 0x23, 0x98, 0x25, 0xbb} + retryNonceV2 = [12]byte{0xd8, 0x69, 0x69, 0xbc, 0x2d, 0x7c, 0x6d, 0x99, 0x90, 0xef, 0xb0, 0x4a} ) // GetRetryIntegrityTag calculates the integrity tag on a Retry packet @@ -51,10 +54,14 @@ func GetRetryIntegrityTag(retry []byte, origDestConnID protocol.ConnectionID, ve var tag [16]byte var sealed []byte - if version == protocol.Version2 { - sealed = retryAEADv2.Seal(tag[:0], retryNonceV2[:], nil, retryBuf.Bytes()) - } else { + //nolint:exhaustive // These are all the versions we support + switch version { + case protocol.Version1: sealed = retryAEADv1.Seal(tag[:0], retryNonceV1[:], nil, retryBuf.Bytes()) + case protocol.Version2: + sealed = retryAEADv2.Seal(tag[:0], retryNonceV2[:], nil, retryBuf.Bytes()) + default: + sealed = retryAEADdraft29.Seal(tag[:0], retryNonceDraft29[:], nil, retryBuf.Bytes()) } if len(sealed) != 16 { panic(fmt.Sprintf("unexpected Retry integrity tag length: %d", len(sealed))) diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/session_ticket.go b/vendor/github.com/quic-go/quic-go/internal/handshake/session_ticket.go index 9481af563..56bcbcd5d 100644 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/session_ticket.go +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/session_ticket.go @@ -10,7 +10,7 @@ import ( "github.com/quic-go/quic-go/quicvarint" ) -const sessionTicketRevision = 4 +const sessionTicketRevision = 2 type sessionTicket struct { Parameters *wire.TransportParameters @@ -21,13 +21,10 @@ func (t *sessionTicket) Marshal() []byte { b := make([]byte, 0, 256) b = quicvarint.Append(b, sessionTicketRevision) b = quicvarint.Append(b, uint64(t.RTT.Microseconds())) - if t.Parameters == nil { - return b - } return t.Parameters.MarshalForSessionTicket(b) } -func (t *sessionTicket) Unmarshal(b []byte, using0RTT bool) error { +func (t *sessionTicket) Unmarshal(b []byte) error { r := bytes.NewReader(b) rev, err := quicvarint.Read(r) if err != nil { @@ -40,15 +37,11 @@ func (t *sessionTicket) Unmarshal(b []byte, using0RTT bool) error { if err != nil { return errors.New("failed to read RTT") } - if using0RTT { - var tp wire.TransportParameters - if err := tp.UnmarshalFromSessionTicket(r); err != nil { - return fmt.Errorf("unmarshaling transport parameters from session ticket failed: %s", err.Error()) - } - t.Parameters = &tp - } else if r.Len() > 0 { - return fmt.Errorf("the session ticket has more bytes than expected") + var tp wire.TransportParameters + if err := tp.UnmarshalFromSessionTicket(r); err != nil { + return fmt.Errorf("unmarshaling transport parameters from session ticket failed: %s", err.Error()) } + t.Parameters = &tp t.RTT = time.Duration(rtt) * time.Microsecond return nil } diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/tls_extension_handler.go b/vendor/github.com/quic-go/quic-go/internal/handshake/tls_extension_handler.go new file mode 100644 index 000000000..6105fe401 --- /dev/null +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/tls_extension_handler.go @@ -0,0 +1,68 @@ +package handshake + +import ( + "github.com/quic-go/quic-go/internal/protocol" + "github.com/quic-go/quic-go/internal/qtls" +) + +const ( + quicTLSExtensionTypeOldDrafts = 0xffa5 + quicTLSExtensionType = 0x39 +) + +type extensionHandler struct { + ourParams []byte + paramsChan chan []byte + + extensionType uint16 + + perspective protocol.Perspective +} + +var _ tlsExtensionHandler = &extensionHandler{} + +// newExtensionHandler creates a new extension handler +func newExtensionHandler(params []byte, pers protocol.Perspective, v protocol.VersionNumber) tlsExtensionHandler { + et := uint16(quicTLSExtensionType) + if v == protocol.VersionDraft29 { + et = quicTLSExtensionTypeOldDrafts + } + return &extensionHandler{ + ourParams: params, + paramsChan: make(chan []byte), + perspective: pers, + extensionType: et, + } +} + +func (h *extensionHandler) GetExtensions(msgType uint8) []qtls.Extension { + if (h.perspective == protocol.PerspectiveClient && messageType(msgType) != typeClientHello) || + (h.perspective == protocol.PerspectiveServer && messageType(msgType) != typeEncryptedExtensions) { + return nil + } + return []qtls.Extension{{ + Type: h.extensionType, + Data: h.ourParams, + }} +} + +func (h *extensionHandler) ReceivedExtensions(msgType uint8, exts []qtls.Extension) { + if (h.perspective == protocol.PerspectiveClient && messageType(msgType) != typeEncryptedExtensions) || + (h.perspective == protocol.PerspectiveServer && messageType(msgType) != typeClientHello) { + return + } + + var data []byte + for _, ext := range exts { + if ext.Type == h.extensionType { + data = ext.Data + break + } + } + + h.paramsChan <- data +} + +func (h *extensionHandler) TransportParameters() <-chan []byte { + return h.paramsChan +} diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/token_generator.go b/vendor/github.com/quic-go/quic-go/internal/handshake/token_generator.go index 2d91e6b25..e5e90bb3b 100644 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/token_generator.go +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/token_generator.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/asn1" "fmt" + "io" "net" "time" @@ -44,9 +45,15 @@ type TokenGenerator struct { tokenProtector tokenProtector } -// NewTokenGenerator initializes a new TokenGenerator -func NewTokenGenerator(key TokenProtectorKey) *TokenGenerator { - return &TokenGenerator{tokenProtector: newTokenProtector(key)} +// NewTokenGenerator initializes a new TookenGenerator +func NewTokenGenerator(rand io.Reader) (*TokenGenerator, error) { + tokenProtector, err := newTokenProtector(rand) + if err != nil { + return nil, err + } + return &TokenGenerator{ + tokenProtector: tokenProtector, + }, nil } // NewRetryToken generates a new token for a Retry for a given source address diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/token_protector.go b/vendor/github.com/quic-go/quic-go/internal/handshake/token_protector.go index f3a99e411..650f230b2 100644 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/token_protector.go +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/token_protector.go @@ -3,7 +3,6 @@ package handshake import ( "crypto/aes" "crypto/cipher" - "crypto/rand" "crypto/sha256" "fmt" "io" @@ -11,9 +10,6 @@ import ( "golang.org/x/crypto/hkdf" ) -// TokenProtectorKey is the key used to encrypt both Retry and session resumption tokens. -type TokenProtectorKey [32]byte - // TokenProtector is used to create and verify a token type tokenProtector interface { // NewToken creates a new token @@ -22,29 +18,40 @@ type tokenProtector interface { DecodeToken([]byte) ([]byte, error) } -const tokenNonceSize = 32 +const ( + tokenSecretSize = 32 + tokenNonceSize = 32 +) // tokenProtector is used to create and verify a token type tokenProtectorImpl struct { - key TokenProtectorKey + rand io.Reader + secret []byte } // newTokenProtector creates a source for source address tokens -func newTokenProtector(key TokenProtectorKey) tokenProtector { - return &tokenProtectorImpl{key: key} +func newTokenProtector(rand io.Reader) (tokenProtector, error) { + secret := make([]byte, tokenSecretSize) + if _, err := rand.Read(secret); err != nil { + return nil, err + } + return &tokenProtectorImpl{ + rand: rand, + secret: secret, + }, nil } // NewToken encodes data into a new token. func (s *tokenProtectorImpl) NewToken(data []byte) ([]byte, error) { - var nonce [tokenNonceSize]byte - if _, err := rand.Read(nonce[:]); err != nil { + nonce := make([]byte, tokenNonceSize) + if _, err := s.rand.Read(nonce); err != nil { return nil, err } - aead, aeadNonce, err := s.createAEAD(nonce[:]) + aead, aeadNonce, err := s.createAEAD(nonce) if err != nil { return nil, err } - return append(nonce[:], aead.Seal(nil, aeadNonce, data, nil)...), nil + return append(nonce, aead.Seal(nil, aeadNonce, data, nil)...), nil } // DecodeToken decodes a token. @@ -61,7 +68,7 @@ func (s *tokenProtectorImpl) DecodeToken(p []byte) ([]byte, error) { } func (s *tokenProtectorImpl) createAEAD(nonce []byte) (cipher.AEAD, []byte, error) { - h := hkdf.New(sha256.New, s.key[:], nonce, []byte("quic-go token source")) + h := hkdf.New(sha256.New, s.secret, nonce, []byte("quic-go token source")) key := make([]byte, 32) // use a 32 byte key, in order to select AES-256 if _, err := io.ReadFull(h, key); err != nil { return nil, nil, err diff --git a/vendor/github.com/quic-go/quic-go/internal/handshake/updatable_aead.go b/vendor/github.com/quic-go/quic-go/internal/handshake/updatable_aead.go index a583f2773..ac01acdb1 100644 --- a/vendor/github.com/quic-go/quic-go/internal/handshake/updatable_aead.go +++ b/vendor/github.com/quic-go/quic-go/internal/handshake/updatable_aead.go @@ -10,6 +10,7 @@ import ( "github.com/quic-go/quic-go/internal/protocol" "github.com/quic-go/quic-go/internal/qerr" + "github.com/quic-go/quic-go/internal/qtls" "github.com/quic-go/quic-go/internal/utils" "github.com/quic-go/quic-go/logging" ) @@ -23,7 +24,7 @@ var KeyUpdateInterval uint64 = protocol.KeyUpdateInterval var FirstKeyUpdateInterval uint64 = 100 type updatableAEAD struct { - suite *cipherSuite + suite *qtls.CipherSuiteTLS13 keyPhase protocol.KeyPhase largestAcked protocol.PacketNumber @@ -57,7 +58,7 @@ type updatableAEAD struct { rttStats *utils.RTTStats - tracer *logging.ConnectionTracer + tracer logging.ConnectionTracer logger utils.Logger version protocol.VersionNumber @@ -70,7 +71,7 @@ var ( _ ShortHeaderSealer = &updatableAEAD{} ) -func newUpdatableAEAD(rttStats *utils.RTTStats, tracer *logging.ConnectionTracer, logger utils.Logger, version protocol.VersionNumber) *updatableAEAD { +func newUpdatableAEAD(rttStats *utils.RTTStats, tracer logging.ConnectionTracer, logger utils.Logger, version protocol.VersionNumber) *updatableAEAD { return &updatableAEAD{ firstPacketNumber: protocol.InvalidPacketNumber, largestAcked: protocol.InvalidPacketNumber, @@ -86,7 +87,7 @@ func newUpdatableAEAD(rttStats *utils.RTTStats, tracer *logging.ConnectionTracer func (a *updatableAEAD) rollKeys() { if a.prevRcvAEAD != nil { a.logger.Debugf("Dropping key phase %d ahead of scheduled time. Drop time was: %s", a.keyPhase-1, a.prevRcvAEADExpiry) - if a.tracer != nil && a.tracer.DroppedKey != nil { + if a.tracer != nil { a.tracer.DroppedKey(a.keyPhase - 1) } a.prevRcvAEADExpiry = time.Time{} @@ -120,7 +121,7 @@ func (a *updatableAEAD) getNextTrafficSecret(hash crypto.Hash, ts []byte) []byte // SetReadKey sets the read key. // For the client, this function is called before SetWriteKey. // For the server, this function is called after SetWriteKey. -func (a *updatableAEAD) SetReadKey(suite *cipherSuite, trafficSecret []byte) { +func (a *updatableAEAD) SetReadKey(suite *qtls.CipherSuiteTLS13, trafficSecret []byte) { a.rcvAEAD = createAEAD(suite, trafficSecret, a.version) a.headerDecrypter = newHeaderProtector(suite, trafficSecret, false, a.version) if a.suite == nil { @@ -134,7 +135,7 @@ func (a *updatableAEAD) SetReadKey(suite *cipherSuite, trafficSecret []byte) { // SetWriteKey sets the write key. // For the client, this function is called after SetReadKey. // For the server, this function is called before SetWriteKey. -func (a *updatableAEAD) SetWriteKey(suite *cipherSuite, trafficSecret []byte) { +func (a *updatableAEAD) SetWriteKey(suite *qtls.CipherSuiteTLS13, trafficSecret []byte) { a.sendAEAD = createAEAD(suite, trafficSecret, a.version) a.headerEncrypter = newHeaderProtector(suite, trafficSecret, false, a.version) if a.suite == nil { @@ -145,7 +146,7 @@ func (a *updatableAEAD) SetWriteKey(suite *cipherSuite, trafficSecret []byte) { a.nextSendAEAD = createAEAD(suite, a.nextSendTrafficSecret, a.version) } -func (a *updatableAEAD) setAEADParameters(aead cipher.AEAD, suite *cipherSuite) { +func (a *updatableAEAD) setAEADParameters(aead cipher.AEAD, suite *qtls.CipherSuiteTLS13) { a.nonceBuf = make([]byte, aead.NonceSize()) a.aeadOverhead = aead.Overhead() a.suite = suite @@ -182,7 +183,7 @@ func (a *updatableAEAD) open(dst, src []byte, rcvTime time.Time, pn protocol.Pac a.prevRcvAEAD = nil a.logger.Debugf("Dropping key phase %d", a.keyPhase-1) a.prevRcvAEADExpiry = time.Time{} - if a.tracer != nil && a.tracer.DroppedKey != nil { + if a.tracer != nil { a.tracer.DroppedKey(a.keyPhase - 1) } } @@ -216,7 +217,7 @@ func (a *updatableAEAD) open(dst, src []byte, rcvTime time.Time, pn protocol.Pac // The peer initiated this key update. It's safe to drop the keys for the previous generation now. // Start a timer to drop the previous key generation. a.startKeyDropTimer(rcvTime) - if a.tracer != nil && a.tracer.UpdatedKey != nil { + if a.tracer != nil { a.tracer.UpdatedKey(a.keyPhase, true) } a.firstRcvdWithCurrentKey = pn @@ -308,7 +309,7 @@ func (a *updatableAEAD) KeyPhase() protocol.KeyPhaseBit { if a.shouldInitiateKeyUpdate() { a.rollKeys() a.logger.Debugf("Initiating key update to key phase %d", a.keyPhase) - if a.tracer != nil && a.tracer.UpdatedKey != nil { + if a.tracer != nil { a.tracer.UpdatedKey(a.keyPhase, false) } } diff --git a/vendor/github.com/quic-go/quic-go/internal/protocol/params.go b/vendor/github.com/quic-go/quic-go/internal/protocol/params.go index 3ca68bf83..fe3a75625 100644 --- a/vendor/github.com/quic-go/quic-go/internal/protocol/params.go +++ b/vendor/github.com/quic-go/quic-go/internal/protocol/params.go @@ -65,6 +65,9 @@ const MaxAcceptQueueSize = 32 // TokenValidity is the duration that a (non-retry) token is considered valid const TokenValidity = 24 * time.Hour +// RetryTokenValidity is the duration that a retry token is considered valid +const RetryTokenValidity = 10 * time.Second + // MaxOutstandingSentPackets is maximum number of packets saved for retransmission. // When reached, it imposes a soft limit on sending new packets: // Sending ACKs and retransmission is still allowed, but now new regular packets can be sent. @@ -105,6 +108,9 @@ const DefaultIdleTimeout = 30 * time.Second // DefaultHandshakeIdleTimeout is the default idle timeout used before handshake completion. const DefaultHandshakeIdleTimeout = 5 * time.Second +// DefaultHandshakeTimeout is the default timeout for a connection until the crypto handshake succeeds. +const DefaultHandshakeTimeout = 10 * time.Second + // MaxKeepAliveInterval is the maximum time until we send a packet to keep a connection alive. // It should be shorter than the time that NATs clear their mapping. const MaxKeepAliveInterval = 20 * time.Second diff --git a/vendor/github.com/quic-go/quic-go/internal/protocol/protocol.go b/vendor/github.com/quic-go/quic-go/internal/protocol/protocol.go index d056cb9de..98bc9ffbc 100644 --- a/vendor/github.com/quic-go/quic-go/internal/protocol/protocol.go +++ b/vendor/github.com/quic-go/quic-go/internal/protocol/protocol.go @@ -37,61 +37,12 @@ func (t PacketType) String() string { type ECN uint8 const ( - ECNUnsupported ECN = iota - ECNNon // 00 - ECT1 // 01 - ECT0 // 10 - ECNCE // 11 + ECNNon ECN = iota // 00 + ECT1 // 01 + ECT0 // 10 + ECNCE // 11 ) -func ParseECNHeaderBits(bits byte) ECN { - switch bits { - case 0: - return ECNNon - case 0b00000010: - return ECT0 - case 0b00000001: - return ECT1 - case 0b00000011: - return ECNCE - default: - panic("invalid ECN bits") - } -} - -func (e ECN) ToHeaderBits() byte { - //nolint:exhaustive // There are only 4 values. - switch e { - case ECNNon: - return 0 - case ECT0: - return 0b00000010 - case ECT1: - return 0b00000001 - case ECNCE: - return 0b00000011 - default: - panic("ECN unsupported") - } -} - -func (e ECN) String() string { - switch e { - case ECNUnsupported: - return "ECN unsupported" - case ECNNon: - return "Not-ECT" - case ECT1: - return "ECT(1)" - case ECT0: - return "ECT(0)" - case ECNCE: - return "CE" - default: - return fmt.Sprintf("invalid ECN value: %d", e) - } -} - // A ByteCount in QUIC type ByteCount int64 diff --git a/vendor/github.com/quic-go/quic-go/internal/protocol/version.go b/vendor/github.com/quic-go/quic-go/internal/protocol/version.go index 5c2decbdc..20e8976e3 100644 --- a/vendor/github.com/quic-go/quic-go/internal/protocol/version.go +++ b/vendor/github.com/quic-go/quic-go/internal/protocol/version.go @@ -19,14 +19,14 @@ const ( // The version numbers, making grepping easier const ( VersionUnknown VersionNumber = math.MaxUint32 - versionDraft29 VersionNumber = 0xff00001d // draft-29 used to be a widely deployed version + VersionDraft29 VersionNumber = 0xff00001d Version1 VersionNumber = 0x1 Version2 VersionNumber = 0x6b3343cf ) // SupportedVersions lists the versions that the server supports // must be in sorted descending order -var SupportedVersions = []VersionNumber{Version1, Version2} +var SupportedVersions = []VersionNumber{Version1, Version2, VersionDraft29} // IsValidVersion says if the version is known to quic-go func IsValidVersion(v VersionNumber) bool { @@ -38,7 +38,7 @@ func (vn VersionNumber) String() string { switch vn { case VersionUnknown: return "unknown" - case versionDraft29: + case VersionDraft29: return "draft-29" case Version1: return "v1" diff --git a/vendor/github.com/quic-go/quic-go/internal/qerr/error_codes.go b/vendor/github.com/quic-go/quic-go/internal/qerr/error_codes.go index a037acd22..cc846df6a 100644 --- a/vendor/github.com/quic-go/quic-go/internal/qerr/error_codes.go +++ b/vendor/github.com/quic-go/quic-go/internal/qerr/error_codes.go @@ -40,7 +40,7 @@ func (e TransportErrorCode) Message() string { if !e.IsCryptoError() { return "" } - return qtls.AlertError(e - 0x100).Error() + return qtls.Alert(e - 0x100).Error() } func (e TransportErrorCode) String() string { diff --git a/vendor/github.com/quic-go/quic-go/internal/qerr/errors.go b/vendor/github.com/quic-go/quic-go/internal/qerr/errors.go index 2d8511f77..26ea34452 100644 --- a/vendor/github.com/quic-go/quic-go/internal/qerr/errors.go +++ b/vendor/github.com/quic-go/quic-go/internal/qerr/errors.go @@ -17,16 +17,15 @@ type TransportError struct { FrameType uint64 ErrorCode TransportErrorCode ErrorMessage string - error error // only set for local errors, sometimes } var _ error = &TransportError{} // NewLocalCryptoError create a new TransportError instance for a crypto error -func NewLocalCryptoError(tlsAlert uint8, err error) *TransportError { +func NewLocalCryptoError(tlsAlert uint8, errorMessage string) *TransportError { return &TransportError{ - ErrorCode: 0x100 + TransportErrorCode(tlsAlert), - error: err, + ErrorCode: 0x100 + TransportErrorCode(tlsAlert), + ErrorMessage: errorMessage, } } @@ -36,9 +35,6 @@ func (e *TransportError) Error() string { str += fmt.Sprintf(" (frame type: %#x)", e.FrameType) } msg := e.ErrorMessage - if len(msg) == 0 && e.error != nil { - msg = e.error.Error() - } if len(msg) == 0 { msg = e.ErrorCode.Message() } @@ -52,10 +48,6 @@ func (e *TransportError) Is(target error) bool { return target == net.ErrClosed } -func (e *TransportError) Unwrap() error { - return e.error -} - // An ApplicationErrorCode is an application-defined error code. type ApplicationErrorCode uint64 diff --git a/vendor/github.com/quic-go/quic-go/internal/qtls/cipher_suite_go121.go b/vendor/github.com/quic-go/quic-go/internal/qtls/cipher_suite_go121.go deleted file mode 100644 index aa8c768fd..000000000 --- a/vendor/github.com/quic-go/quic-go/internal/qtls/cipher_suite_go121.go +++ /dev/null @@ -1,66 +0,0 @@ -//go:build go1.21 - -package qtls - -import ( - "crypto" - "crypto/cipher" - "crypto/tls" - "fmt" - "unsafe" -) - -type cipherSuiteTLS13 struct { - ID uint16 - KeyLen int - AEAD func(key, fixedNonce []byte) cipher.AEAD - Hash crypto.Hash -} - -//go:linkname cipherSuiteTLS13ByID crypto/tls.cipherSuiteTLS13ByID -func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13 - -//go:linkname cipherSuitesTLS13 crypto/tls.cipherSuitesTLS13 -var cipherSuitesTLS13 []unsafe.Pointer - -//go:linkname defaultCipherSuitesTLS13 crypto/tls.defaultCipherSuitesTLS13 -var defaultCipherSuitesTLS13 []uint16 - -//go:linkname defaultCipherSuitesTLS13NoAES crypto/tls.defaultCipherSuitesTLS13NoAES -var defaultCipherSuitesTLS13NoAES []uint16 - -var cipherSuitesModified bool - -// SetCipherSuite modifies the cipherSuiteTLS13 slice of cipher suites inside qtls -// such that it only contains the cipher suite with the chosen id. -// The reset function returned resets them back to the original value. -func SetCipherSuite(id uint16) (reset func()) { - if cipherSuitesModified { - panic("cipher suites modified multiple times without resetting") - } - cipherSuitesModified = true - - origCipherSuitesTLS13 := append([]unsafe.Pointer{}, cipherSuitesTLS13...) - origDefaultCipherSuitesTLS13 := append([]uint16{}, defaultCipherSuitesTLS13...) - origDefaultCipherSuitesTLS13NoAES := append([]uint16{}, defaultCipherSuitesTLS13NoAES...) - // The order is given by the order of the slice elements in cipherSuitesTLS13 in qtls. - switch id { - case tls.TLS_AES_128_GCM_SHA256: - cipherSuitesTLS13 = cipherSuitesTLS13[:1] - case tls.TLS_CHACHA20_POLY1305_SHA256: - cipherSuitesTLS13 = cipherSuitesTLS13[1:2] - case tls.TLS_AES_256_GCM_SHA384: - cipherSuitesTLS13 = cipherSuitesTLS13[2:] - default: - panic(fmt.Sprintf("unexpected cipher suite: %d", id)) - } - defaultCipherSuitesTLS13 = []uint16{id} - defaultCipherSuitesTLS13NoAES = []uint16{id} - - return func() { - cipherSuitesTLS13 = origCipherSuitesTLS13 - defaultCipherSuitesTLS13 = origDefaultCipherSuitesTLS13 - defaultCipherSuitesTLS13NoAES = origDefaultCipherSuitesTLS13NoAES - cipherSuitesModified = false - } -} diff --git a/vendor/github.com/quic-go/quic-go/internal/qtls/client_session_cache.go b/vendor/github.com/quic-go/quic-go/internal/qtls/client_session_cache.go deleted file mode 100644 index 519895ee6..000000000 --- a/vendor/github.com/quic-go/quic-go/internal/qtls/client_session_cache.go +++ /dev/null @@ -1,61 +0,0 @@ -//go:build go1.21 - -package qtls - -import ( - "crypto/tls" -) - -type clientSessionCache struct { - getData func() []byte - setData func([]byte) - wrapped tls.ClientSessionCache -} - -var _ tls.ClientSessionCache = &clientSessionCache{} - -func (c clientSessionCache) Put(key string, cs *tls.ClientSessionState) { - if cs == nil { - c.wrapped.Put(key, nil) - return - } - ticket, state, err := cs.ResumptionState() - if err != nil || state == nil { - c.wrapped.Put(key, cs) - return - } - state.Extra = append(state.Extra, addExtraPrefix(c.getData())) - newCS, err := tls.NewResumptionState(ticket, state) - if err != nil { - // It's not clear why this would error. Just save the original state. - c.wrapped.Put(key, cs) - return - } - c.wrapped.Put(key, newCS) -} - -func (c clientSessionCache) Get(key string) (*tls.ClientSessionState, bool) { - cs, ok := c.wrapped.Get(key) - if !ok || cs == nil { - return cs, ok - } - ticket, state, err := cs.ResumptionState() - if err != nil { - // It's not clear why this would error. - // Remove the ticket from the session cache, so we don't run into this error over and over again - c.wrapped.Put(key, nil) - return nil, false - } - // restore QUIC transport parameters and RTT stored in state.Extra - if extra := findExtraData(state.Extra); extra != nil { - c.setData(extra) - } - session, err := tls.NewResumptionState(ticket, state) - if err != nil { - // It's not clear why this would error. - // Remove the ticket from the session cache, so we don't run into this error over and over again - c.wrapped.Put(key, nil) - return nil, false - } - return session, true -} diff --git a/vendor/github.com/quic-go/quic-go/internal/qtls/go119.go b/vendor/github.com/quic-go/quic-go/internal/qtls/go119.go new file mode 100644 index 000000000..f040b859c --- /dev/null +++ b/vendor/github.com/quic-go/quic-go/internal/qtls/go119.go @@ -0,0 +1,145 @@ +//go:build go1.19 && !go1.20 + +package qtls + +import ( + "crypto" + "crypto/cipher" + "crypto/tls" + "fmt" + "net" + "unsafe" + + "github.com/quic-go/qtls-go1-19" +) + +type ( + // Alert is a TLS alert + Alert = qtls.Alert + // A Certificate is qtls.Certificate. + Certificate = qtls.Certificate + // CertificateRequestInfo contains information about a certificate request. + CertificateRequestInfo = qtls.CertificateRequestInfo + // A CipherSuiteTLS13 is a cipher suite for TLS 1.3 + CipherSuiteTLS13 = qtls.CipherSuiteTLS13 + // ClientHelloInfo contains information about a ClientHello. + ClientHelloInfo = qtls.ClientHelloInfo + // ClientSessionCache is a cache used for session resumption. + ClientSessionCache = qtls.ClientSessionCache + // ClientSessionState is a state needed for session resumption. + ClientSessionState = qtls.ClientSessionState + // A Config is a qtls.Config. + Config = qtls.Config + // A Conn is a qtls.Conn. + Conn = qtls.Conn + // ConnectionState contains information about the state of the connection. + ConnectionState = qtls.ConnectionStateWith0RTT + // EncryptionLevel is the encryption level of a message. + EncryptionLevel = qtls.EncryptionLevel + // Extension is a TLS extension + Extension = qtls.Extension + // ExtraConfig is the qtls.ExtraConfig + ExtraConfig = qtls.ExtraConfig + // RecordLayer is a qtls RecordLayer. + RecordLayer = qtls.RecordLayer +) + +const ( + // EncryptionHandshake is the Handshake encryption level + EncryptionHandshake = qtls.EncryptionHandshake + // Encryption0RTT is the 0-RTT encryption level + Encryption0RTT = qtls.Encryption0RTT + // EncryptionApplication is the application data encryption level + EncryptionApplication = qtls.EncryptionApplication +) + +// AEADAESGCMTLS13 creates a new AES-GCM AEAD for TLS 1.3 +func AEADAESGCMTLS13(key, fixedNonce []byte) cipher.AEAD { + return qtls.AEADAESGCMTLS13(key, fixedNonce) +} + +// Client returns a new TLS client side connection. +func Client(conn net.Conn, config *Config, extraConfig *ExtraConfig) *Conn { + return qtls.Client(conn, config, extraConfig) +} + +// Server returns a new TLS server side connection. +func Server(conn net.Conn, config *Config, extraConfig *ExtraConfig) *Conn { + return qtls.Server(conn, config, extraConfig) +} + +func GetConnectionState(conn *Conn) ConnectionState { + return conn.ConnectionStateWith0RTT() +} + +// ToTLSConnectionState extracts the tls.ConnectionState +func ToTLSConnectionState(cs ConnectionState) tls.ConnectionState { + return cs.ConnectionState +} + +type cipherSuiteTLS13 struct { + ID uint16 + KeyLen int + AEAD func(key, fixedNonce []byte) cipher.AEAD + Hash crypto.Hash +} + +//go:linkname cipherSuiteTLS13ByID github.com/quic-go/qtls-go1-19.cipherSuiteTLS13ByID +func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13 + +// CipherSuiteTLS13ByID gets a TLS 1.3 cipher suite. +func CipherSuiteTLS13ByID(id uint16) *CipherSuiteTLS13 { + val := cipherSuiteTLS13ByID(id) + cs := (*cipherSuiteTLS13)(unsafe.Pointer(val)) + return &qtls.CipherSuiteTLS13{ + ID: cs.ID, + KeyLen: cs.KeyLen, + AEAD: cs.AEAD, + Hash: cs.Hash, + } +} + +//go:linkname cipherSuitesTLS13 github.com/quic-go/qtls-go1-19.cipherSuitesTLS13 +var cipherSuitesTLS13 []unsafe.Pointer + +//go:linkname defaultCipherSuitesTLS13 github.com/quic-go/qtls-go1-19.defaultCipherSuitesTLS13 +var defaultCipherSuitesTLS13 []uint16 + +//go:linkname defaultCipherSuitesTLS13NoAES github.com/quic-go/qtls-go1-19.defaultCipherSuitesTLS13NoAES +var defaultCipherSuitesTLS13NoAES []uint16 + +var cipherSuitesModified bool + +// SetCipherSuite modifies the cipherSuiteTLS13 slice of cipher suites inside qtls +// such that it only contains the cipher suite with the chosen id. +// The reset function returned resets them back to the original value. +func SetCipherSuite(id uint16) (reset func()) { + if cipherSuitesModified { + panic("cipher suites modified multiple times without resetting") + } + cipherSuitesModified = true + + origCipherSuitesTLS13 := append([]unsafe.Pointer{}, cipherSuitesTLS13...) + origDefaultCipherSuitesTLS13 := append([]uint16{}, defaultCipherSuitesTLS13...) + origDefaultCipherSuitesTLS13NoAES := append([]uint16{}, defaultCipherSuitesTLS13NoAES...) + // The order is given by the order of the slice elements in cipherSuitesTLS13 in qtls. + switch id { + case tls.TLS_AES_128_GCM_SHA256: + cipherSuitesTLS13 = cipherSuitesTLS13[:1] + case tls.TLS_CHACHA20_POLY1305_SHA256: + cipherSuitesTLS13 = cipherSuitesTLS13[1:2] + case tls.TLS_AES_256_GCM_SHA384: + cipherSuitesTLS13 = cipherSuitesTLS13[2:] + default: + panic(fmt.Sprintf("unexpected cipher suite: %d", id)) + } + defaultCipherSuitesTLS13 = []uint16{id} + defaultCipherSuitesTLS13NoAES = []uint16{id} + + return func() { + cipherSuitesTLS13 = origCipherSuitesTLS13 + defaultCipherSuitesTLS13 = origDefaultCipherSuitesTLS13 + defaultCipherSuitesTLS13NoAES = origDefaultCipherSuitesTLS13NoAES + cipherSuitesModified = false + } +} diff --git a/vendor/github.com/quic-go/quic-go/internal/qtls/go120.go b/vendor/github.com/quic-go/quic-go/internal/qtls/go120.go index 898f03526..a40146ab4 100644 --- a/vendor/github.com/quic-go/quic-go/internal/qtls/go120.go +++ b/vendor/github.com/quic-go/quic-go/internal/qtls/go120.go @@ -1,99 +1,101 @@ -//go:build go1.20 && !go1.21 +//go:build go1.20 package qtls import ( + "crypto" + "crypto/cipher" "crypto/tls" "fmt" + "net" "unsafe" - "github.com/quic-go/quic-go/internal/protocol" - "github.com/quic-go/qtls-go1-20" ) type ( - QUICConn = qtls.QUICConn - QUICConfig = qtls.QUICConfig - QUICEvent = qtls.QUICEvent - QUICEventKind = qtls.QUICEventKind - QUICEncryptionLevel = qtls.QUICEncryptionLevel - AlertError = qtls.AlertError + // Alert is a TLS alert + Alert = qtls.Alert + // A Certificate is qtls.Certificate. + Certificate = qtls.Certificate + // CertificateRequestInfo contains information about a certificate request. + CertificateRequestInfo = qtls.CertificateRequestInfo + // A CipherSuiteTLS13 is a cipher suite for TLS 1.3 + CipherSuiteTLS13 = qtls.CipherSuiteTLS13 + // ClientHelloInfo contains information about a ClientHello. + ClientHelloInfo = qtls.ClientHelloInfo + // ClientSessionCache is a cache used for session resumption. + ClientSessionCache = qtls.ClientSessionCache + // ClientSessionState is a state needed for session resumption. + ClientSessionState = qtls.ClientSessionState + // A Config is a qtls.Config. + Config = qtls.Config + // A Conn is a qtls.Conn. + Conn = qtls.Conn + // ConnectionState contains information about the state of the connection. + ConnectionState = qtls.ConnectionStateWith0RTT + // EncryptionLevel is the encryption level of a message. + EncryptionLevel = qtls.EncryptionLevel + // Extension is a TLS extension + Extension = qtls.Extension + // ExtraConfig is the qtls.ExtraConfig + ExtraConfig = qtls.ExtraConfig + // RecordLayer is a qtls RecordLayer. + RecordLayer = qtls.RecordLayer ) const ( - QUICEncryptionLevelInitial = qtls.QUICEncryptionLevelInitial - QUICEncryptionLevelEarly = qtls.QUICEncryptionLevelEarly - QUICEncryptionLevelHandshake = qtls.QUICEncryptionLevelHandshake - QUICEncryptionLevelApplication = qtls.QUICEncryptionLevelApplication + // EncryptionHandshake is the Handshake encryption level + EncryptionHandshake = qtls.EncryptionHandshake + // Encryption0RTT is the 0-RTT encryption level + Encryption0RTT = qtls.Encryption0RTT + // EncryptionApplication is the application data encryption level + EncryptionApplication = qtls.EncryptionApplication ) -const ( - QUICNoEvent = qtls.QUICNoEvent - QUICSetReadSecret = qtls.QUICSetReadSecret - QUICSetWriteSecret = qtls.QUICSetWriteSecret - QUICWriteData = qtls.QUICWriteData - QUICTransportParameters = qtls.QUICTransportParameters - QUICTransportParametersRequired = qtls.QUICTransportParametersRequired - QUICRejectedEarlyData = qtls.QUICRejectedEarlyData - QUICHandshakeDone = qtls.QUICHandshakeDone -) - -func SetupConfigForServer(conf *QUICConfig, enable0RTT bool, getDataForSessionTicket func() []byte, handleSessionTicket func([]byte, bool) bool) { - qtls.InitSessionTicketKeys(conf.TLSConfig) - conf.TLSConfig = conf.TLSConfig.Clone() - conf.TLSConfig.MinVersion = tls.VersionTLS13 - conf.ExtraConfig = &qtls.ExtraConfig{ - Enable0RTT: enable0RTT, - Accept0RTT: func(data []byte) bool { - return handleSessionTicket(data, true) - }, - GetAppDataForSessionTicket: getDataForSessionTicket, - } +// AEADAESGCMTLS13 creates a new AES-GCM AEAD for TLS 1.3 +func AEADAESGCMTLS13(key, fixedNonce []byte) cipher.AEAD { + return qtls.AEADAESGCMTLS13(key, fixedNonce) } -func SetupConfigForClient(conf *QUICConfig, getDataForSessionState func() []byte, setDataFromSessionState func([]byte)) { - conf.ExtraConfig = &qtls.ExtraConfig{ - GetAppDataForSessionState: getDataForSessionState, - SetAppDataFromSessionState: setDataFromSessionState, - } +// Client returns a new TLS client side connection. +func Client(conn net.Conn, config *Config, extraConfig *ExtraConfig) *Conn { + return qtls.Client(conn, config, extraConfig) } -func QUICServer(config *QUICConfig) *QUICConn { - return qtls.QUICServer(config) +// Server returns a new TLS server side connection. +func Server(conn net.Conn, config *Config, extraConfig *ExtraConfig) *Conn { + return qtls.Server(conn, config, extraConfig) } -func QUICClient(config *QUICConfig) *QUICConn { - return qtls.QUICClient(config) +func GetConnectionState(conn *Conn) ConnectionState { + return conn.ConnectionStateWith0RTT() } -func ToTLSEncryptionLevel(e protocol.EncryptionLevel) qtls.QUICEncryptionLevel { - switch e { - case protocol.EncryptionInitial: - return qtls.QUICEncryptionLevelInitial - case protocol.EncryptionHandshake: - return qtls.QUICEncryptionLevelHandshake - case protocol.Encryption1RTT: - return qtls.QUICEncryptionLevelApplication - case protocol.Encryption0RTT: - return qtls.QUICEncryptionLevelEarly - default: - panic(fmt.Sprintf("unexpected encryption level: %s", e)) - } +// ToTLSConnectionState extracts the tls.ConnectionState +func ToTLSConnectionState(cs ConnectionState) tls.ConnectionState { + return cs.ConnectionState } -func FromTLSEncryptionLevel(e qtls.QUICEncryptionLevel) protocol.EncryptionLevel { - switch e { - case qtls.QUICEncryptionLevelInitial: - return protocol.EncryptionInitial - case qtls.QUICEncryptionLevelHandshake: - return protocol.EncryptionHandshake - case qtls.QUICEncryptionLevelApplication: - return protocol.Encryption1RTT - case qtls.QUICEncryptionLevelEarly: - return protocol.Encryption0RTT - default: - panic(fmt.Sprintf("unexpect encryption level: %s", e)) +type cipherSuiteTLS13 struct { + ID uint16 + KeyLen int + AEAD func(key, fixedNonce []byte) cipher.AEAD + Hash crypto.Hash +} + +//go:linkname cipherSuiteTLS13ByID github.com/quic-go/qtls-go1-20.cipherSuiteTLS13ByID +func cipherSuiteTLS13ByID(id uint16) *cipherSuiteTLS13 + +// CipherSuiteTLS13ByID gets a TLS 1.3 cipher suite. +func CipherSuiteTLS13ByID(id uint16) *CipherSuiteTLS13 { + val := cipherSuiteTLS13ByID(id) + cs := (*cipherSuiteTLS13)(unsafe.Pointer(val)) + return &qtls.CipherSuiteTLS13{ + ID: cs.ID, + KeyLen: cs.KeyLen, + AEAD: cs.AEAD, + Hash: cs.Hash, } } @@ -141,7 +143,3 @@ func SetCipherSuite(id uint16) (reset func()) { cipherSuitesModified = false } } - -func SendSessionTicket(c *QUICConn, allow0RTT bool) error { - return c.SendSessionTicket(allow0RTT) -} diff --git a/vendor/github.com/quic-go/quic-go/internal/qtls/go121.go b/vendor/github.com/quic-go/quic-go/internal/qtls/go121.go index 65a274ac0..b33406397 100644 --- a/vendor/github.com/quic-go/quic-go/internal/qtls/go121.go +++ b/vendor/github.com/quic-go/quic-go/internal/qtls/go121.go @@ -2,158 +2,4 @@ package qtls -import ( - "bytes" - "crypto/tls" - "fmt" - - "github.com/quic-go/quic-go/internal/protocol" -) - -type ( - QUICConn = tls.QUICConn - QUICConfig = tls.QUICConfig - QUICEvent = tls.QUICEvent - QUICEventKind = tls.QUICEventKind - QUICEncryptionLevel = tls.QUICEncryptionLevel - QUICSessionTicketOptions = tls.QUICSessionTicketOptions - AlertError = tls.AlertError -) - -const ( - QUICEncryptionLevelInitial = tls.QUICEncryptionLevelInitial - QUICEncryptionLevelEarly = tls.QUICEncryptionLevelEarly - QUICEncryptionLevelHandshake = tls.QUICEncryptionLevelHandshake - QUICEncryptionLevelApplication = tls.QUICEncryptionLevelApplication -) - -const ( - QUICNoEvent = tls.QUICNoEvent - QUICSetReadSecret = tls.QUICSetReadSecret - QUICSetWriteSecret = tls.QUICSetWriteSecret - QUICWriteData = tls.QUICWriteData - QUICTransportParameters = tls.QUICTransportParameters - QUICTransportParametersRequired = tls.QUICTransportParametersRequired - QUICRejectedEarlyData = tls.QUICRejectedEarlyData - QUICHandshakeDone = tls.QUICHandshakeDone -) - -func QUICServer(config *QUICConfig) *QUICConn { return tls.QUICServer(config) } -func QUICClient(config *QUICConfig) *QUICConn { return tls.QUICClient(config) } - -func SetupConfigForServer(qconf *QUICConfig, _ bool, getData func() []byte, handleSessionTicket func([]byte, bool) bool) { - conf := qconf.TLSConfig - - // Workaround for https://github.com/golang/go/issues/60506. - // This initializes the session tickets _before_ cloning the config. - _, _ = conf.DecryptTicket(nil, tls.ConnectionState{}) - - conf = conf.Clone() - conf.MinVersion = tls.VersionTLS13 - qconf.TLSConfig = conf - - // add callbacks to save transport parameters into the session ticket - origWrapSession := conf.WrapSession - conf.WrapSession = func(cs tls.ConnectionState, state *tls.SessionState) ([]byte, error) { - // Add QUIC session ticket - state.Extra = append(state.Extra, addExtraPrefix(getData())) - - if origWrapSession != nil { - return origWrapSession(cs, state) - } - b, err := conf.EncryptTicket(cs, state) - return b, err - } - origUnwrapSession := conf.UnwrapSession - // UnwrapSession might be called multiple times, as the client can use multiple session tickets. - // However, using 0-RTT is only possible with the first session ticket. - // crypto/tls guarantees that this callback is called in the same order as the session ticket in the ClientHello. - var unwrapCount int - conf.UnwrapSession = func(identity []byte, connState tls.ConnectionState) (*tls.SessionState, error) { - unwrapCount++ - var state *tls.SessionState - var err error - if origUnwrapSession != nil { - state, err = origUnwrapSession(identity, connState) - } else { - state, err = conf.DecryptTicket(identity, connState) - } - if err != nil || state == nil { - return nil, err - } - - extra := findExtraData(state.Extra) - if extra != nil { - state.EarlyData = handleSessionTicket(extra, state.EarlyData && unwrapCount == 1) - } else { - state.EarlyData = false - } - - return state, nil - } -} - -func SetupConfigForClient(qconf *QUICConfig, getData func() []byte, setData func([]byte)) { - conf := qconf.TLSConfig - if conf.ClientSessionCache != nil { - origCache := conf.ClientSessionCache - conf.ClientSessionCache = &clientSessionCache{ - wrapped: origCache, - getData: getData, - setData: setData, - } - } -} - -func ToTLSEncryptionLevel(e protocol.EncryptionLevel) tls.QUICEncryptionLevel { - switch e { - case protocol.EncryptionInitial: - return tls.QUICEncryptionLevelInitial - case protocol.EncryptionHandshake: - return tls.QUICEncryptionLevelHandshake - case protocol.Encryption1RTT: - return tls.QUICEncryptionLevelApplication - case protocol.Encryption0RTT: - return tls.QUICEncryptionLevelEarly - default: - panic(fmt.Sprintf("unexpected encryption level: %s", e)) - } -} - -func FromTLSEncryptionLevel(e tls.QUICEncryptionLevel) protocol.EncryptionLevel { - switch e { - case tls.QUICEncryptionLevelInitial: - return protocol.EncryptionInitial - case tls.QUICEncryptionLevelHandshake: - return protocol.EncryptionHandshake - case tls.QUICEncryptionLevelApplication: - return protocol.Encryption1RTT - case tls.QUICEncryptionLevelEarly: - return protocol.Encryption0RTT - default: - panic(fmt.Sprintf("unexpect encryption level: %s", e)) - } -} - -const extraPrefix = "quic-go1" - -func addExtraPrefix(b []byte) []byte { - return append([]byte(extraPrefix), b...) -} - -func findExtraData(extras [][]byte) []byte { - prefix := []byte(extraPrefix) - for _, extra := range extras { - if len(extra) < len(prefix) || !bytes.Equal(prefix, extra[:len(prefix)]) { - continue - } - return extra[len(prefix):] - } - return nil -} - -func SendSessionTicket(c *QUICConn, allow0RTT bool) error { - return c.SendSessionTicket(tls.QUICSessionTicketOptions{ - EarlyData: allow0RTT, - }) -} +var _ int = "The version of quic-go you're using can't be built on Go 1.21 yet. For more details, please see https://github.com/quic-go/quic-go/wiki/quic-go-and-Go-versions." diff --git a/vendor/github.com/quic-go/quic-go/internal/qtls/go_oldversion.go b/vendor/github.com/quic-go/quic-go/internal/qtls/go_oldversion.go index 0fca80a38..e15f03629 100644 --- a/vendor/github.com/quic-go/quic-go/internal/qtls/go_oldversion.go +++ b/vendor/github.com/quic-go/quic-go/internal/qtls/go_oldversion.go @@ -1,4 +1,4 @@ -//go:build !go1.20 +//go:build !go1.19 package qtls diff --git a/vendor/github.com/quic-go/quic-go/internal/wire/header.go b/vendor/github.com/quic-go/quic-go/internal/wire/header.go index 0c60f4dd9..37f48cced 100644 --- a/vendor/github.com/quic-go/quic-go/internal/wire/header.go +++ b/vendor/github.com/quic-go/quic-go/internal/wire/header.go @@ -74,10 +74,6 @@ func parseArbitraryLenConnectionIDs(r *bytes.Reader) (dest, src protocol.Arbitra return destConnID, srcConnID, nil } -func IsPotentialQUICPacket(firstByte byte) bool { - return firstByte&0x40 > 0 -} - // IsLongHeaderPacket says if this is a Long Header packet func IsLongHeaderPacket(firstByte byte) bool { return firstByte&0x80 > 0 @@ -112,7 +108,7 @@ func Is0RTTPacket(b []byte) bool { version := protocol.VersionNumber(binary.BigEndian.Uint32(b[1:5])) //nolint:exhaustive // We only need to test QUIC versions that we support. switch version { - case protocol.Version1: + case protocol.Version1, protocol.VersionDraft29: return b[0]>>4&0b11 == 0b01 case protocol.Version2: return b[0]>>4&0b11 == 0b10 diff --git a/vendor/github.com/quic-go/quic-go/internal/wire/transport_parameters.go b/vendor/github.com/quic-go/quic-go/internal/wire/transport_parameters.go index 7226521b0..1ec1e59d3 100644 --- a/vendor/github.com/quic-go/quic-go/internal/wire/transport_parameters.go +++ b/vendor/github.com/quic-go/quic-go/internal/wire/transport_parameters.go @@ -454,10 +454,6 @@ func (p *TransportParameters) MarshalForSessionTicket(b []byte) []byte { b = p.marshalVarintParam(b, initialMaxStreamsBidiParameterID, uint64(p.MaxBidiStreamNum)) // initial_max_uni_streams b = p.marshalVarintParam(b, initialMaxStreamsUniParameterID, uint64(p.MaxUniStreamNum)) - // max_datagram_frame_size - if p.MaxDatagramFrameSize != protocol.InvalidByteCount { - b = p.marshalVarintParam(b, maxDatagramFrameSizeParameterID, uint64(p.MaxDatagramFrameSize)) - } // active_connection_id_limit return p.marshalVarintParam(b, activeConnectionIDLimitParameterID, p.ActiveConnectionIDLimit) } @@ -476,9 +472,6 @@ func (p *TransportParameters) UnmarshalFromSessionTicket(r *bytes.Reader) error // ValidFor0RTT checks if the transport parameters match those saved in the session ticket. func (p *TransportParameters) ValidFor0RTT(saved *TransportParameters) bool { - if saved.MaxDatagramFrameSize != protocol.InvalidByteCount && (p.MaxDatagramFrameSize == protocol.InvalidByteCount || p.MaxDatagramFrameSize < saved.MaxDatagramFrameSize) { - return false - } return p.InitialMaxStreamDataBidiLocal >= saved.InitialMaxStreamDataBidiLocal && p.InitialMaxStreamDataBidiRemote >= saved.InitialMaxStreamDataBidiRemote && p.InitialMaxStreamDataUni >= saved.InitialMaxStreamDataUni && @@ -488,21 +481,6 @@ func (p *TransportParameters) ValidFor0RTT(saved *TransportParameters) bool { p.ActiveConnectionIDLimit == saved.ActiveConnectionIDLimit } -// ValidForUpdate checks that the new transport parameters don't reduce limits after resuming a 0-RTT connection. -// It is only used on the client side. -func (p *TransportParameters) ValidForUpdate(saved *TransportParameters) bool { - if saved.MaxDatagramFrameSize != protocol.InvalidByteCount && (p.MaxDatagramFrameSize == protocol.InvalidByteCount || p.MaxDatagramFrameSize < saved.MaxDatagramFrameSize) { - return false - } - return p.ActiveConnectionIDLimit >= saved.ActiveConnectionIDLimit && - p.InitialMaxData >= saved.InitialMaxData && - p.InitialMaxStreamDataBidiLocal >= saved.InitialMaxStreamDataBidiLocal && - p.InitialMaxStreamDataBidiRemote >= saved.InitialMaxStreamDataBidiRemote && - p.InitialMaxStreamDataUni >= saved.InitialMaxStreamDataUni && - p.MaxBidiStreamNum >= saved.MaxBidiStreamNum && - p.MaxUniStreamNum >= saved.MaxUniStreamNum -} - // String returns a string representation, intended for logging. func (p *TransportParameters) String() string { logString := "&wire.TransportParameters{OriginalDestinationConnectionID: %s, InitialSourceConnectionID: %s, " diff --git a/vendor/github.com/quic-go/quic-go/internal/wire/version_negotiation.go b/vendor/github.com/quic-go/quic-go/internal/wire/version_negotiation.go index afde70fa4..3dc621135 100644 --- a/vendor/github.com/quic-go/quic-go/internal/wire/version_negotiation.go +++ b/vendor/github.com/quic-go/quic-go/internal/wire/version_negotiation.go @@ -40,10 +40,7 @@ func ComposeVersionNegotiation(destConnID, srcConnID protocol.ArbitraryLenConnec buf := bytes.NewBuffer(make([]byte, 0, expectedLen)) r := make([]byte, 1) _, _ = rand.Read(r) // ignore the error here. It is not critical to have perfect random here. - // Setting the "QUIC bit" (0x40) is not required by the RFC, - // but it allows clients to demultiplex QUIC with a long list of other protocols. - // See RFC 9443 and https://mailarchive.ietf.org/arch/msg/quic/oR4kxGKY6mjtPC1CZegY1ED4beg/ for details. - buf.WriteByte(r[0] | 0xc0) + buf.WriteByte(r[0] | 0x80) utils.BigEndian.WriteUint32(buf, 0) // version 0 buf.WriteByte(uint8(destConnID.Len())) buf.Write(destConnID.Bytes()) diff --git a/vendor/github.com/quic-go/quic-go/logging/connection_tracer.go b/vendor/github.com/quic-go/quic-go/logging/connection_tracer.go deleted file mode 100644 index e3f322d91..000000000 --- a/vendor/github.com/quic-go/quic-go/logging/connection_tracer.go +++ /dev/null @@ -1,255 +0,0 @@ -package logging - -import ( - "net" - "time" -) - -// A ConnectionTracer records events. -type ConnectionTracer struct { - StartedConnection func(local, remote net.Addr, srcConnID, destConnID ConnectionID) - NegotiatedVersion func(chosen VersionNumber, clientVersions, serverVersions []VersionNumber) - ClosedConnection func(error) - SentTransportParameters func(*TransportParameters) - ReceivedTransportParameters func(*TransportParameters) - RestoredTransportParameters func(parameters *TransportParameters) // for 0-RTT - SentLongHeaderPacket func(*ExtendedHeader, ByteCount, ECN, *AckFrame, []Frame) - SentShortHeaderPacket func(*ShortHeader, ByteCount, ECN, *AckFrame, []Frame) - ReceivedVersionNegotiationPacket func(dest, src ArbitraryLenConnectionID, _ []VersionNumber) - ReceivedRetry func(*Header) - ReceivedLongHeaderPacket func(*ExtendedHeader, ByteCount, ECN, []Frame) - ReceivedShortHeaderPacket func(*ShortHeader, ByteCount, ECN, []Frame) - BufferedPacket func(PacketType, ByteCount) - DroppedPacket func(PacketType, ByteCount, PacketDropReason) - UpdatedMetrics func(rttStats *RTTStats, cwnd, bytesInFlight ByteCount, packetsInFlight int) - AcknowledgedPacket func(EncryptionLevel, PacketNumber) - LostPacket func(EncryptionLevel, PacketNumber, PacketLossReason) - UpdatedCongestionState func(CongestionState) - UpdatedPTOCount func(value uint32) - UpdatedKeyFromTLS func(EncryptionLevel, Perspective) - UpdatedKey func(generation KeyPhase, remote bool) - DroppedEncryptionLevel func(EncryptionLevel) - DroppedKey func(generation KeyPhase) - SetLossTimer func(TimerType, EncryptionLevel, time.Time) - LossTimerExpired func(TimerType, EncryptionLevel) - LossTimerCanceled func() - ECNStateUpdated func(state ECNState, trigger ECNStateTrigger) - // Close is called when the connection is closed. - Close func() - Debug func(name, msg string) -} - -// NewMultiplexedConnectionTracer creates a new connection tracer that multiplexes events to multiple tracers. -func NewMultiplexedConnectionTracer(tracers ...*ConnectionTracer) *ConnectionTracer { - if len(tracers) == 0 { - return nil - } - if len(tracers) == 1 { - return tracers[0] - } - return &ConnectionTracer{ - StartedConnection: func(local, remote net.Addr, srcConnID, destConnID ConnectionID) { - for _, t := range tracers { - if t.StartedConnection != nil { - t.StartedConnection(local, remote, srcConnID, destConnID) - } - } - }, - NegotiatedVersion: func(chosen VersionNumber, clientVersions, serverVersions []VersionNumber) { - for _, t := range tracers { - if t.NegotiatedVersion != nil { - t.NegotiatedVersion(chosen, clientVersions, serverVersions) - } - } - }, - ClosedConnection: func(e error) { - for _, t := range tracers { - if t.ClosedConnection != nil { - t.ClosedConnection(e) - } - } - }, - SentTransportParameters: func(tp *TransportParameters) { - for _, t := range tracers { - if t.SentTransportParameters != nil { - t.SentTransportParameters(tp) - } - } - }, - ReceivedTransportParameters: func(tp *TransportParameters) { - for _, t := range tracers { - if t.ReceivedTransportParameters != nil { - t.ReceivedTransportParameters(tp) - } - } - }, - RestoredTransportParameters: func(tp *TransportParameters) { - for _, t := range tracers { - if t.RestoredTransportParameters != nil { - t.RestoredTransportParameters(tp) - } - } - }, - SentLongHeaderPacket: func(hdr *ExtendedHeader, size ByteCount, ecn ECN, ack *AckFrame, frames []Frame) { - for _, t := range tracers { - if t.SentLongHeaderPacket != nil { - t.SentLongHeaderPacket(hdr, size, ecn, ack, frames) - } - } - }, - SentShortHeaderPacket: func(hdr *ShortHeader, size ByteCount, ecn ECN, ack *AckFrame, frames []Frame) { - for _, t := range tracers { - if t.SentShortHeaderPacket != nil { - t.SentShortHeaderPacket(hdr, size, ecn, ack, frames) - } - } - }, - ReceivedVersionNegotiationPacket: func(dest, src ArbitraryLenConnectionID, versions []VersionNumber) { - for _, t := range tracers { - if t.ReceivedVersionNegotiationPacket != nil { - t.ReceivedVersionNegotiationPacket(dest, src, versions) - } - } - }, - ReceivedRetry: func(hdr *Header) { - for _, t := range tracers { - if t.ReceivedRetry != nil { - t.ReceivedRetry(hdr) - } - } - }, - ReceivedLongHeaderPacket: func(hdr *ExtendedHeader, size ByteCount, ecn ECN, frames []Frame) { - for _, t := range tracers { - if t.ReceivedLongHeaderPacket != nil { - t.ReceivedLongHeaderPacket(hdr, size, ecn, frames) - } - } - }, - ReceivedShortHeaderPacket: func(hdr *ShortHeader, size ByteCount, ecn ECN, frames []Frame) { - for _, t := range tracers { - if t.ReceivedShortHeaderPacket != nil { - t.ReceivedShortHeaderPacket(hdr, size, ecn, frames) - } - } - }, - BufferedPacket: func(typ PacketType, size ByteCount) { - for _, t := range tracers { - if t.BufferedPacket != nil { - t.BufferedPacket(typ, size) - } - } - }, - DroppedPacket: func(typ PacketType, size ByteCount, reason PacketDropReason) { - for _, t := range tracers { - if t.DroppedPacket != nil { - t.DroppedPacket(typ, size, reason) - } - } - }, - UpdatedMetrics: func(rttStats *RTTStats, cwnd, bytesInFlight ByteCount, packetsInFlight int) { - for _, t := range tracers { - if t.UpdatedMetrics != nil { - t.UpdatedMetrics(rttStats, cwnd, bytesInFlight, packetsInFlight) - } - } - }, - AcknowledgedPacket: func(encLevel EncryptionLevel, pn PacketNumber) { - for _, t := range tracers { - if t.AcknowledgedPacket != nil { - t.AcknowledgedPacket(encLevel, pn) - } - } - }, - LostPacket: func(encLevel EncryptionLevel, pn PacketNumber, reason PacketLossReason) { - for _, t := range tracers { - if t.LostPacket != nil { - t.LostPacket(encLevel, pn, reason) - } - } - }, - UpdatedCongestionState: func(state CongestionState) { - for _, t := range tracers { - if t.UpdatedCongestionState != nil { - t.UpdatedCongestionState(state) - } - } - }, - UpdatedPTOCount: func(value uint32) { - for _, t := range tracers { - if t.UpdatedPTOCount != nil { - t.UpdatedPTOCount(value) - } - } - }, - UpdatedKeyFromTLS: func(encLevel EncryptionLevel, perspective Perspective) { - for _, t := range tracers { - if t.UpdatedKeyFromTLS != nil { - t.UpdatedKeyFromTLS(encLevel, perspective) - } - } - }, - UpdatedKey: func(generation KeyPhase, remote bool) { - for _, t := range tracers { - if t.UpdatedKey != nil { - t.UpdatedKey(generation, remote) - } - } - }, - DroppedEncryptionLevel: func(encLevel EncryptionLevel) { - for _, t := range tracers { - if t.DroppedEncryptionLevel != nil { - t.DroppedEncryptionLevel(encLevel) - } - } - }, - DroppedKey: func(generation KeyPhase) { - for _, t := range tracers { - if t.DroppedKey != nil { - t.DroppedKey(generation) - } - } - }, - SetLossTimer: func(typ TimerType, encLevel EncryptionLevel, exp time.Time) { - for _, t := range tracers { - if t.SetLossTimer != nil { - t.SetLossTimer(typ, encLevel, exp) - } - } - }, - LossTimerExpired: func(typ TimerType, encLevel EncryptionLevel) { - for _, t := range tracers { - if t.LossTimerExpired != nil { - t.LossTimerExpired(typ, encLevel) - } - } - }, - LossTimerCanceled: func() { - for _, t := range tracers { - if t.LossTimerCanceled != nil { - t.LossTimerCanceled() - } - } - }, - ECNStateUpdated: func(state ECNState, trigger ECNStateTrigger) { - for _, t := range tracers { - if t.ECNStateUpdated != nil { - t.ECNStateUpdated(state, trigger) - } - } - }, - Close: func() { - for _, t := range tracers { - if t.Close != nil { - t.Close() - } - } - }, - Debug: func(name, msg string) { - for _, t := range tracers { - if t.Debug != nil { - t.Debug(name, msg) - } - } - }, - } -} diff --git a/vendor/github.com/quic-go/quic-go/logging/interface.go b/vendor/github.com/quic-go/quic-go/logging/interface.go index 10ac038fb..2ce8582ec 100644 --- a/vendor/github.com/quic-go/quic-go/logging/interface.go +++ b/vendor/github.com/quic-go/quic-go/logging/interface.go @@ -3,6 +3,9 @@ package logging import ( + "net" + "time" + "github.com/quic-go/quic-go/internal/protocol" "github.com/quic-go/quic-go/internal/qerr" "github.com/quic-go/quic-go/internal/utils" @@ -12,8 +15,6 @@ import ( type ( // A ByteCount is used to count bytes. ByteCount = protocol.ByteCount - // ECN is the ECN value - ECN = protocol.ECN // A ConnectionID is a QUIC Connection ID. ConnectionID = protocol.ConnectionID // An ArbitraryLenConnectionID is a QUIC Connection ID that can be up to 255 bytes long. @@ -57,19 +58,6 @@ type ( RTTStats = utils.RTTStats ) -const ( - // ECNUnsupported means that no ECN value was set / received - ECNUnsupported = protocol.ECNUnsupported - // ECTNot is Not-ECT - ECTNot = protocol.ECNNon - // ECT0 is ECT(0) - ECT0 = protocol.ECT0 - // ECT1 is ECT(1) - ECT1 = protocol.ECT1 - // ECNCE is CE - ECNCE = protocol.ECNCE -) - const ( // KeyPhaseZero is key phase bit 0 KeyPhaseZero KeyPhaseBit = protocol.KeyPhaseZero @@ -109,3 +97,43 @@ type ShortHeader struct { PacketNumberLen protocol.PacketNumberLen KeyPhase KeyPhaseBit } + +// A Tracer traces events. +type Tracer interface { + SentPacket(net.Addr, *Header, ByteCount, []Frame) + SentVersionNegotiationPacket(_ net.Addr, dest, src ArbitraryLenConnectionID, _ []VersionNumber) + DroppedPacket(net.Addr, PacketType, ByteCount, PacketDropReason) +} + +// A ConnectionTracer records events. +type ConnectionTracer interface { + StartedConnection(local, remote net.Addr, srcConnID, destConnID ConnectionID) + NegotiatedVersion(chosen VersionNumber, clientVersions, serverVersions []VersionNumber) + ClosedConnection(error) + SentTransportParameters(*TransportParameters) + ReceivedTransportParameters(*TransportParameters) + RestoredTransportParameters(parameters *TransportParameters) // for 0-RTT + SentLongHeaderPacket(hdr *ExtendedHeader, size ByteCount, ack *AckFrame, frames []Frame) + SentShortHeaderPacket(hdr *ShortHeader, size ByteCount, ack *AckFrame, frames []Frame) + ReceivedVersionNegotiationPacket(dest, src ArbitraryLenConnectionID, _ []VersionNumber) + ReceivedRetry(*Header) + ReceivedLongHeaderPacket(hdr *ExtendedHeader, size ByteCount, frames []Frame) + ReceivedShortHeaderPacket(hdr *ShortHeader, size ByteCount, frames []Frame) + BufferedPacket(PacketType, ByteCount) + DroppedPacket(PacketType, ByteCount, PacketDropReason) + UpdatedMetrics(rttStats *RTTStats, cwnd, bytesInFlight ByteCount, packetsInFlight int) + AcknowledgedPacket(EncryptionLevel, PacketNumber) + LostPacket(EncryptionLevel, PacketNumber, PacketLossReason) + UpdatedCongestionState(CongestionState) + UpdatedPTOCount(value uint32) + UpdatedKeyFromTLS(EncryptionLevel, Perspective) + UpdatedKey(generation KeyPhase, remote bool) + DroppedEncryptionLevel(EncryptionLevel) + DroppedKey(generation KeyPhase) + SetLossTimer(TimerType, EncryptionLevel, time.Time) + LossTimerExpired(TimerType, EncryptionLevel) + LossTimerCanceled() + // Close is called when the connection is closed. + Close() + Debug(name, msg string) +} diff --git a/vendor/github.com/quic-go/quic-go/logging/mockgen.go b/vendor/github.com/quic-go/quic-go/logging/mockgen.go new file mode 100644 index 000000000..d50916799 --- /dev/null +++ b/vendor/github.com/quic-go/quic-go/logging/mockgen.go @@ -0,0 +1,4 @@ +package logging + +//go:generate sh -c "go run github.com/golang/mock/mockgen -package logging -self_package github.com/quic-go/quic-go/logging -destination mock_connection_tracer_test.go github.com/quic-go/quic-go/logging ConnectionTracer" +//go:generate sh -c "go run github.com/golang/mock/mockgen -package logging -self_package github.com/quic-go/quic-go/logging -destination mock_tracer_test.go github.com/quic-go/quic-go/logging Tracer" diff --git a/vendor/github.com/quic-go/quic-go/logging/multiplex.go b/vendor/github.com/quic-go/quic-go/logging/multiplex.go new file mode 100644 index 000000000..672a5cdbd --- /dev/null +++ b/vendor/github.com/quic-go/quic-go/logging/multiplex.go @@ -0,0 +1,226 @@ +package logging + +import ( + "net" + "time" +) + +type tracerMultiplexer struct { + tracers []Tracer +} + +var _ Tracer = &tracerMultiplexer{} + +// NewMultiplexedTracer creates a new tracer that multiplexes events to multiple tracers. +func NewMultiplexedTracer(tracers ...Tracer) Tracer { + if len(tracers) == 0 { + return nil + } + if len(tracers) == 1 { + return tracers[0] + } + return &tracerMultiplexer{tracers} +} + +func (m *tracerMultiplexer) SentPacket(remote net.Addr, hdr *Header, size ByteCount, frames []Frame) { + for _, t := range m.tracers { + t.SentPacket(remote, hdr, size, frames) + } +} + +func (m *tracerMultiplexer) SentVersionNegotiationPacket(remote net.Addr, dest, src ArbitraryLenConnectionID, versions []VersionNumber) { + for _, t := range m.tracers { + t.SentVersionNegotiationPacket(remote, dest, src, versions) + } +} + +func (m *tracerMultiplexer) DroppedPacket(remote net.Addr, typ PacketType, size ByteCount, reason PacketDropReason) { + for _, t := range m.tracers { + t.DroppedPacket(remote, typ, size, reason) + } +} + +type connTracerMultiplexer struct { + tracers []ConnectionTracer +} + +var _ ConnectionTracer = &connTracerMultiplexer{} + +// NewMultiplexedConnectionTracer creates a new connection tracer that multiplexes events to multiple tracers. +func NewMultiplexedConnectionTracer(tracers ...ConnectionTracer) ConnectionTracer { + if len(tracers) == 0 { + return nil + } + if len(tracers) == 1 { + return tracers[0] + } + return &connTracerMultiplexer{tracers: tracers} +} + +func (m *connTracerMultiplexer) StartedConnection(local, remote net.Addr, srcConnID, destConnID ConnectionID) { + for _, t := range m.tracers { + t.StartedConnection(local, remote, srcConnID, destConnID) + } +} + +func (m *connTracerMultiplexer) NegotiatedVersion(chosen VersionNumber, clientVersions, serverVersions []VersionNumber) { + for _, t := range m.tracers { + t.NegotiatedVersion(chosen, clientVersions, serverVersions) + } +} + +func (m *connTracerMultiplexer) ClosedConnection(e error) { + for _, t := range m.tracers { + t.ClosedConnection(e) + } +} + +func (m *connTracerMultiplexer) SentTransportParameters(tp *TransportParameters) { + for _, t := range m.tracers { + t.SentTransportParameters(tp) + } +} + +func (m *connTracerMultiplexer) ReceivedTransportParameters(tp *TransportParameters) { + for _, t := range m.tracers { + t.ReceivedTransportParameters(tp) + } +} + +func (m *connTracerMultiplexer) RestoredTransportParameters(tp *TransportParameters) { + for _, t := range m.tracers { + t.RestoredTransportParameters(tp) + } +} + +func (m *connTracerMultiplexer) SentLongHeaderPacket(hdr *ExtendedHeader, size ByteCount, ack *AckFrame, frames []Frame) { + for _, t := range m.tracers { + t.SentLongHeaderPacket(hdr, size, ack, frames) + } +} + +func (m *connTracerMultiplexer) SentShortHeaderPacket(hdr *ShortHeader, size ByteCount, ack *AckFrame, frames []Frame) { + for _, t := range m.tracers { + t.SentShortHeaderPacket(hdr, size, ack, frames) + } +} + +func (m *connTracerMultiplexer) ReceivedVersionNegotiationPacket(dest, src ArbitraryLenConnectionID, versions []VersionNumber) { + for _, t := range m.tracers { + t.ReceivedVersionNegotiationPacket(dest, src, versions) + } +} + +func (m *connTracerMultiplexer) ReceivedRetry(hdr *Header) { + for _, t := range m.tracers { + t.ReceivedRetry(hdr) + } +} + +func (m *connTracerMultiplexer) ReceivedLongHeaderPacket(hdr *ExtendedHeader, size ByteCount, frames []Frame) { + for _, t := range m.tracers { + t.ReceivedLongHeaderPacket(hdr, size, frames) + } +} + +func (m *connTracerMultiplexer) ReceivedShortHeaderPacket(hdr *ShortHeader, size ByteCount, frames []Frame) { + for _, t := range m.tracers { + t.ReceivedShortHeaderPacket(hdr, size, frames) + } +} + +func (m *connTracerMultiplexer) BufferedPacket(typ PacketType, size ByteCount) { + for _, t := range m.tracers { + t.BufferedPacket(typ, size) + } +} + +func (m *connTracerMultiplexer) DroppedPacket(typ PacketType, size ByteCount, reason PacketDropReason) { + for _, t := range m.tracers { + t.DroppedPacket(typ, size, reason) + } +} + +func (m *connTracerMultiplexer) UpdatedCongestionState(state CongestionState) { + for _, t := range m.tracers { + t.UpdatedCongestionState(state) + } +} + +func (m *connTracerMultiplexer) UpdatedMetrics(rttStats *RTTStats, cwnd, bytesInFLight ByteCount, packetsInFlight int) { + for _, t := range m.tracers { + t.UpdatedMetrics(rttStats, cwnd, bytesInFLight, packetsInFlight) + } +} + +func (m *connTracerMultiplexer) AcknowledgedPacket(encLevel EncryptionLevel, pn PacketNumber) { + for _, t := range m.tracers { + t.AcknowledgedPacket(encLevel, pn) + } +} + +func (m *connTracerMultiplexer) LostPacket(encLevel EncryptionLevel, pn PacketNumber, reason PacketLossReason) { + for _, t := range m.tracers { + t.LostPacket(encLevel, pn, reason) + } +} + +func (m *connTracerMultiplexer) UpdatedPTOCount(value uint32) { + for _, t := range m.tracers { + t.UpdatedPTOCount(value) + } +} + +func (m *connTracerMultiplexer) UpdatedKeyFromTLS(encLevel EncryptionLevel, perspective Perspective) { + for _, t := range m.tracers { + t.UpdatedKeyFromTLS(encLevel, perspective) + } +} + +func (m *connTracerMultiplexer) UpdatedKey(generation KeyPhase, remote bool) { + for _, t := range m.tracers { + t.UpdatedKey(generation, remote) + } +} + +func (m *connTracerMultiplexer) DroppedEncryptionLevel(encLevel EncryptionLevel) { + for _, t := range m.tracers { + t.DroppedEncryptionLevel(encLevel) + } +} + +func (m *connTracerMultiplexer) DroppedKey(generation KeyPhase) { + for _, t := range m.tracers { + t.DroppedKey(generation) + } +} + +func (m *connTracerMultiplexer) SetLossTimer(typ TimerType, encLevel EncryptionLevel, exp time.Time) { + for _, t := range m.tracers { + t.SetLossTimer(typ, encLevel, exp) + } +} + +func (m *connTracerMultiplexer) LossTimerExpired(typ TimerType, encLevel EncryptionLevel) { + for _, t := range m.tracers { + t.LossTimerExpired(typ, encLevel) + } +} + +func (m *connTracerMultiplexer) LossTimerCanceled() { + for _, t := range m.tracers { + t.LossTimerCanceled() + } +} + +func (m *connTracerMultiplexer) Debug(name, msg string) { + for _, t := range m.tracers { + t.Debug(name, msg) + } +} + +func (m *connTracerMultiplexer) Close() { + for _, t := range m.tracers { + t.Close() + } +} diff --git a/vendor/github.com/quic-go/quic-go/logging/null_tracer.go b/vendor/github.com/quic-go/quic-go/logging/null_tracer.go new file mode 100644 index 000000000..de9703857 --- /dev/null +++ b/vendor/github.com/quic-go/quic-go/logging/null_tracer.go @@ -0,0 +1,58 @@ +package logging + +import ( + "net" + "time" +) + +// The NullTracer is a Tracer that does nothing. +// It is useful for embedding. +type NullTracer struct{} + +var _ Tracer = &NullTracer{} + +func (n NullTracer) SentPacket(net.Addr, *Header, ByteCount, []Frame) {} +func (n NullTracer) SentVersionNegotiationPacket(_ net.Addr, dest, src ArbitraryLenConnectionID, _ []VersionNumber) { +} +func (n NullTracer) DroppedPacket(net.Addr, PacketType, ByteCount, PacketDropReason) {} + +// The NullConnectionTracer is a ConnectionTracer that does nothing. +// It is useful for embedding. +type NullConnectionTracer struct{} + +var _ ConnectionTracer = &NullConnectionTracer{} + +func (n NullConnectionTracer) StartedConnection(local, remote net.Addr, srcConnID, destConnID ConnectionID) { +} + +func (n NullConnectionTracer) NegotiatedVersion(chosen VersionNumber, clientVersions, serverVersions []VersionNumber) { +} +func (n NullConnectionTracer) ClosedConnection(err error) {} +func (n NullConnectionTracer) SentTransportParameters(*TransportParameters) {} +func (n NullConnectionTracer) ReceivedTransportParameters(*TransportParameters) {} +func (n NullConnectionTracer) RestoredTransportParameters(*TransportParameters) {} +func (n NullConnectionTracer) SentLongHeaderPacket(*ExtendedHeader, ByteCount, *AckFrame, []Frame) {} +func (n NullConnectionTracer) SentShortHeaderPacket(*ShortHeader, ByteCount, *AckFrame, []Frame) {} +func (n NullConnectionTracer) ReceivedVersionNegotiationPacket(dest, src ArbitraryLenConnectionID, _ []VersionNumber) { +} +func (n NullConnectionTracer) ReceivedRetry(*Header) {} +func (n NullConnectionTracer) ReceivedLongHeaderPacket(*ExtendedHeader, ByteCount, []Frame) {} +func (n NullConnectionTracer) ReceivedShortHeaderPacket(*ShortHeader, ByteCount, []Frame) {} +func (n NullConnectionTracer) BufferedPacket(PacketType, ByteCount) {} +func (n NullConnectionTracer) DroppedPacket(PacketType, ByteCount, PacketDropReason) {} + +func (n NullConnectionTracer) UpdatedMetrics(rttStats *RTTStats, cwnd, bytesInFlight ByteCount, packetsInFlight int) { +} +func (n NullConnectionTracer) AcknowledgedPacket(EncryptionLevel, PacketNumber) {} +func (n NullConnectionTracer) LostPacket(EncryptionLevel, PacketNumber, PacketLossReason) {} +func (n NullConnectionTracer) UpdatedCongestionState(CongestionState) {} +func (n NullConnectionTracer) UpdatedPTOCount(uint32) {} +func (n NullConnectionTracer) UpdatedKeyFromTLS(EncryptionLevel, Perspective) {} +func (n NullConnectionTracer) UpdatedKey(keyPhase KeyPhase, remote bool) {} +func (n NullConnectionTracer) DroppedEncryptionLevel(EncryptionLevel) {} +func (n NullConnectionTracer) DroppedKey(KeyPhase) {} +func (n NullConnectionTracer) SetLossTimer(TimerType, EncryptionLevel, time.Time) {} +func (n NullConnectionTracer) LossTimerExpired(timerType TimerType, level EncryptionLevel) {} +func (n NullConnectionTracer) LossTimerCanceled() {} +func (n NullConnectionTracer) Close() {} +func (n NullConnectionTracer) Debug(name, msg string) {} diff --git a/vendor/github.com/quic-go/quic-go/logging/tracer.go b/vendor/github.com/quic-go/quic-go/logging/tracer.go deleted file mode 100644 index 5918f30f8..000000000 --- a/vendor/github.com/quic-go/quic-go/logging/tracer.go +++ /dev/null @@ -1,43 +0,0 @@ -package logging - -import "net" - -// A Tracer traces events. -type Tracer struct { - SentPacket func(net.Addr, *Header, ByteCount, []Frame) - SentVersionNegotiationPacket func(_ net.Addr, dest, src ArbitraryLenConnectionID, _ []VersionNumber) - DroppedPacket func(net.Addr, PacketType, ByteCount, PacketDropReason) -} - -// NewMultiplexedTracer creates a new tracer that multiplexes events to multiple tracers. -func NewMultiplexedTracer(tracers ...*Tracer) *Tracer { - if len(tracers) == 0 { - return nil - } - if len(tracers) == 1 { - return tracers[0] - } - return &Tracer{ - SentPacket: func(remote net.Addr, hdr *Header, size ByteCount, frames []Frame) { - for _, t := range tracers { - if t.SentPacket != nil { - t.SentPacket(remote, hdr, size, frames) - } - } - }, - SentVersionNegotiationPacket: func(remote net.Addr, dest, src ArbitraryLenConnectionID, versions []VersionNumber) { - for _, t := range tracers { - if t.SentVersionNegotiationPacket != nil { - t.SentVersionNegotiationPacket(remote, dest, src, versions) - } - } - }, - DroppedPacket: func(remote net.Addr, typ PacketType, size ByteCount, reason PacketDropReason) { - for _, t := range tracers { - if t.DroppedPacket != nil { - t.DroppedPacket(remote, typ, size, reason) - } - } - }, - } -} diff --git a/vendor/github.com/quic-go/quic-go/logging/types.go b/vendor/github.com/quic-go/quic-go/logging/types.go index 0d79b0a90..ad8006923 100644 --- a/vendor/github.com/quic-go/quic-go/logging/types.go +++ b/vendor/github.com/quic-go/quic-go/logging/types.go @@ -92,37 +92,3 @@ const ( // CongestionStateApplicationLimited means that the congestion controller is application limited CongestionStateApplicationLimited ) - -// ECNState is the state of the ECN state machine (see Appendix A.4 of RFC 9000) -type ECNState uint8 - -const ( - // ECNStateTesting is the testing state - ECNStateTesting ECNState = 1 + iota - // ECNStateUnknown is the unknown state - ECNStateUnknown - // ECNStateFailed is the failed state - ECNStateFailed - // ECNStateCapable is the capable state - ECNStateCapable -) - -// ECNStateTrigger is a trigger for an ECN state transition. -type ECNStateTrigger uint8 - -const ( - ECNTriggerNoTrigger ECNStateTrigger = iota - // ECNFailedNoECNCounts is emitted when an ACK acknowledges ECN-marked packets, - // but doesn't contain any ECN counts - ECNFailedNoECNCounts - // ECNFailedDecreasedECNCounts is emitted when an ACK frame decreases ECN counts - ECNFailedDecreasedECNCounts - // ECNFailedLostAllTestingPackets is emitted when all ECN testing packets are declared lost - ECNFailedLostAllTestingPackets - // ECNFailedMoreECNCountsThanSent is emitted when an ACK contains more ECN counts than ECN-marked packets were sent - ECNFailedMoreECNCountsThanSent - // ECNFailedTooFewECNCounts is emitted when an ACK contains fewer ECN counts than it acknowledges packets - ECNFailedTooFewECNCounts - // ECNFailedManglingDetected is emitted when the path marks all ECN-marked packets as CE - ECNFailedManglingDetected -) diff --git a/vendor/github.com/quic-go/quic-go/mockgen.go b/vendor/github.com/quic-go/quic-go/mockgen.go index eb2473863..eb700864a 100644 --- a/vendor/github.com/quic-go/quic-go/mockgen.go +++ b/vendor/github.com/quic-go/quic-go/mockgen.go @@ -2,73 +2,73 @@ package quic -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_send_conn_test.go github.com/quic-go/quic-go SendConn" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_send_conn_test.go github.com/quic-go/quic-go SendConn" type SendConn = sendConn -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_raw_conn_test.go github.com/quic-go/quic-go RawConn" -type RawConn = rawConn - -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_sender_test.go github.com/quic-go/quic-go Sender" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_sender_test.go github.com/quic-go/quic-go Sender" type Sender = sender -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_stream_internal_test.go github.com/quic-go/quic-go StreamI" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_stream_internal_test.go github.com/quic-go/quic-go StreamI" type StreamI = streamI -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_crypto_stream_test.go github.com/quic-go/quic-go CryptoStream" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_crypto_stream_test.go github.com/quic-go/quic-go CryptoStream" type CryptoStream = cryptoStream -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_receive_stream_internal_test.go github.com/quic-go/quic-go ReceiveStreamI" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_receive_stream_internal_test.go github.com/quic-go/quic-go ReceiveStreamI" type ReceiveStreamI = receiveStreamI -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_send_stream_internal_test.go github.com/quic-go/quic-go SendStreamI" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_send_stream_internal_test.go github.com/quic-go/quic-go SendStreamI" type SendStreamI = sendStreamI -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_stream_getter_test.go github.com/quic-go/quic-go StreamGetter" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_stream_getter_test.go github.com/quic-go/quic-go StreamGetter" type StreamGetter = streamGetter -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_stream_sender_test.go github.com/quic-go/quic-go StreamSender" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_stream_sender_test.go github.com/quic-go/quic-go StreamSender" type StreamSender = streamSender -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_crypto_data_handler_test.go github.com/quic-go/quic-go CryptoDataHandler" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_crypto_data_handler_test.go github.com/quic-go/quic-go CryptoDataHandler" type CryptoDataHandler = cryptoDataHandler -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_frame_source_test.go github.com/quic-go/quic-go FrameSource" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_frame_source_test.go github.com/quic-go/quic-go FrameSource" type FrameSource = frameSource -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_ack_frame_source_test.go github.com/quic-go/quic-go AckFrameSource" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_ack_frame_source_test.go github.com/quic-go/quic-go AckFrameSource" type AckFrameSource = ackFrameSource -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_stream_manager_test.go github.com/quic-go/quic-go StreamManager" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_stream_manager_test.go github.com/quic-go/quic-go StreamManager" type StreamManager = streamManager -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_sealing_manager_test.go github.com/quic-go/quic-go SealingManager" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_sealing_manager_test.go github.com/quic-go/quic-go SealingManager" type SealingManager = sealingManager -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_unpacker_test.go github.com/quic-go/quic-go Unpacker" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_unpacker_test.go github.com/quic-go/quic-go Unpacker" type Unpacker = unpacker -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_packer_test.go github.com/quic-go/quic-go Packer" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_packer_test.go github.com/quic-go/quic-go Packer" type Packer = packer -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_mtu_discoverer_test.go github.com/quic-go/quic-go MTUDiscoverer" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_mtu_discoverer_test.go github.com/quic-go/quic-go MTUDiscoverer" type MTUDiscoverer = mtuDiscoverer -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_conn_runner_test.go github.com/quic-go/quic-go ConnRunner" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_conn_runner_test.go github.com/quic-go/quic-go ConnRunner" type ConnRunner = connRunner -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_quic_conn_test.go github.com/quic-go/quic-go QUICConn" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_quic_conn_test.go github.com/quic-go/quic-go QUICConn" type QUICConn = quicConn -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_packet_handler_test.go github.com/quic-go/quic-go PacketHandler" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_packet_handler_test.go github.com/quic-go/quic-go PacketHandler" type PacketHandler = packetHandler -//go:generate sh -c "go run go.uber.org/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_packet_handler_manager_test.go github.com/quic-go/quic-go PacketHandlerManager" +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_unknown_packet_handler_test.go github.com/quic-go/quic-go UnknownPacketHandler" +type UnknownPacketHandler = unknownPacketHandler + +//go:generate sh -c "go run github.com/golang/mock/mockgen -build_flags=\"-tags=gomock\" -package quic -self_package github.com/quic-go/quic-go -destination mock_packet_handler_manager_test.go github.com/quic-go/quic-go PacketHandlerManager" type PacketHandlerManager = packetHandlerManager // Need to use source mode for the batchConn, since reflect mode follows type aliases. // See https://github.com/golang/mock/issues/244 for details. // -//go:generate sh -c "go run go.uber.org/mock/mockgen -package quic -self_package github.com/quic-go/quic-go -source sys_conn_oob.go -destination mock_batch_conn_test.go -mock_names batchConn=MockBatchConn" +//go:generate sh -c "go run github.com/golang/mock/mockgen -package quic -self_package github.com/quic-go/quic-go -source sys_conn_oob.go -destination mock_batch_conn_test.go -mock_names batchConn=MockBatchConn" -//go:generate sh -c "go run go.uber.org/mock/mockgen -package quic -self_package github.com/quic-go/quic-go -self_package github.com/quic-go/quic-go -destination mock_token_store_test.go github.com/quic-go/quic-go TokenStore" -//go:generate sh -c "go run go.uber.org/mock/mockgen -package quic -self_package github.com/quic-go/quic-go -self_package github.com/quic-go/quic-go -destination mock_packetconn_test.go net PacketConn" +//go:generate sh -c "go run github.com/golang/mock/mockgen -package quic -self_package github.com/quic-go/quic-go -self_package github.com/quic-go/quic-go -destination mock_token_store_test.go github.com/quic-go/quic-go TokenStore" +//go:generate sh -c "go run github.com/golang/mock/mockgen -package quic -self_package github.com/quic-go/quic-go -self_package github.com/quic-go/quic-go -destination mock_packetconn_test.go net PacketConn" diff --git a/vendor/github.com/quic-go/quic-go/oss-fuzz.sh b/vendor/github.com/quic-go/quic-go/oss-fuzz.sh deleted file mode 100644 index 1efe6baa6..000000000 --- a/vendor/github.com/quic-go/quic-go/oss-fuzz.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/bin/bash - -# Install Go manually, since oss-fuzz ships with an outdated Go version. -# See https://github.com/google/oss-fuzz/pull/10643. -export CXX="${CXX} -lresolv" # required by Go 1.20 -wget https://go.dev/dl/go1.20.5.linux-amd64.tar.gz \ - && mkdir temp-go \ - && rm -rf /root/.go/* \ - && tar -C temp-go/ -xzf go1.20.5.linux-amd64.tar.gz \ - && mv temp-go/go/* /root/.go/ \ - && rm -rf temp-go go1.20.5.linux-amd64.tar.gz - -( -# fuzz qpack -compile_go_fuzzer github.com/quic-go/qpack/fuzzing Fuzz qpack_fuzzer -) - -( -# fuzz quic-go -compile_go_fuzzer github.com/quic-go/quic-go/fuzzing/frames Fuzz frame_fuzzer -compile_go_fuzzer github.com/quic-go/quic-go/fuzzing/header Fuzz header_fuzzer -compile_go_fuzzer github.com/quic-go/quic-go/fuzzing/transportparameters Fuzz transportparameter_fuzzer -compile_go_fuzzer github.com/quic-go/quic-go/fuzzing/tokens Fuzz token_fuzzer -compile_go_fuzzer github.com/quic-go/quic-go/fuzzing/handshake Fuzz handshake_fuzzer - -if [ $SANITIZER == "coverage" ]; then - # no need for corpora if coverage - exit 0 -fi - -# generate seed corpora -cd $GOPATH/src/github.com/quic-go/quic-go/ -go generate -x ./fuzzing/... - -zip --quiet -r $OUT/header_fuzzer_seed_corpus.zip fuzzing/header/corpus -zip --quiet -r $OUT/frame_fuzzer_seed_corpus.zip fuzzing/frames/corpus -zip --quiet -r $OUT/transportparameter_fuzzer_seed_corpus.zip fuzzing/transportparameters/corpus -zip --quiet -r $OUT/handshake_fuzzer_seed_corpus.zip fuzzing/handshake/corpus -) - -# for debugging -ls -al $OUT diff --git a/vendor/github.com/quic-go/quic-go/packet_handler_map.go b/vendor/github.com/quic-go/quic-go/packet_handler_map.go index 006eadf92..2a16773c8 100644 --- a/vendor/github.com/quic-go/quic-go/packet_handler_map.go +++ b/vendor/github.com/quic-go/quic-go/packet_handler_map.go @@ -4,6 +4,7 @@ import ( "crypto/hmac" "crypto/rand" "crypto/sha256" + "errors" "hash" "io" "net" @@ -20,17 +21,14 @@ type connCapabilities struct { DF bool // GSO (Generic Segmentation Offload) supported GSO bool - // ECN (Explicit Congestion Notifications) supported - ECN bool } // rawConn is a connection that allow reading of a receivedPackeh. type rawConn interface { ReadPacket() (receivedPacket, error) - // WritePacket writes a packet on the wire. - // gsoSize is the size of a single packet, or 0 to disable GSO. - // It is invalid to set gsoSize if capabilities.GSO is not set. - WritePacket(b []byte, addr net.Addr, packetInfoOOB []byte, gsoSize uint16, ecn protocol.ECN) (int, error) + // The size parameter is used for GSO. + // If GSO is not support, len(b) must be equal to size. + WritePacket(b []byte, size uint16, addr net.Addr, oob []byte) (int, error) LocalAddr() net.Addr SetReadDeadline(time.Time) error io.Closer @@ -44,6 +42,13 @@ type closePacket struct { info packetInfo } +type unknownPacketHandler interface { + handlePacket(receivedPacket) + setCloseError(error) +} + +var errListenerAlreadySet = errors.New("listener already set") + type packetHandlerMap struct { mutex sync.Mutex handlers map[protocol.ConnectionID]packetHandler diff --git a/vendor/github.com/quic-go/quic-go/packet_packer.go b/vendor/github.com/quic-go/quic-go/packet_packer.go index a330632be..577f3b043 100644 --- a/vendor/github.com/quic-go/quic-go/packet_packer.go +++ b/vendor/github.com/quic-go/quic-go/packet_packer.go @@ -1,13 +1,9 @@ package quic import ( - crand "crypto/rand" - "encoding/binary" "errors" "fmt" - "golang.org/x/exp/rand" - "github.com/quic-go/quic-go/internal/ackhandler" "github.com/quic-go/quic-go/internal/handshake" "github.com/quic-go/quic-go/internal/protocol" @@ -71,11 +67,6 @@ type coalescedPacket struct { shortHdrPacket *shortHeaderPacket } -// IsOnlyShortHeaderPacket says if this packet only contains a short header packet (and no long header packets). -func (p *coalescedPacket) IsOnlyShortHeaderPacket() bool { - return len(p.longHdrPackets) == 0 && p.shortHdrPacket != nil -} - func (p *longHeaderPacket) EncryptionLevel() protocol.EncryptionLevel { //nolint:exhaustive // Will never be called for Retry packets (and they don't have encrypted data). switch p.header.Type { @@ -131,7 +122,6 @@ type packetPacker struct { acks ackFrameSource datagramQueue *datagramQueue retransmissionQueue *retransmissionQueue - rand rand.Rand numNonAckElicitingAcks int } @@ -150,9 +140,6 @@ func newPacketPacker( datagramQueue *datagramQueue, perspective protocol.Perspective, ) *packetPacker { - var b [8]byte - _, _ = crand.Read(b[:]) - return &packetPacker{ cryptoSetup: cryptoSetup, getDestConnID: getDestConnID, @@ -164,7 +151,6 @@ func newPacketPacker( perspective: perspective, framer: framer, acks: acks, - rand: *rand.New(rand.NewSource(binary.BigEndian.Uint64(b[:]))), pnManager: packetNumberManager, } } @@ -640,13 +626,7 @@ func (p *packetPacker) composeNextPacket(maxFrameSize protocol.ByteCount, onlyAc pl.length += lengthAdded // add handlers for the control frames that were added for i := startLen; i < len(pl.frames); i++ { - switch pl.frames[i].Frame.(type) { - case *wire.PathChallengeFrame, *wire.PathResponseFrame: - // Path probing is currently not supported, therefore we don't need to set the OnAcked callback yet. - // PATH_CHALLENGE and PATH_RESPONSE are never retransmitted. - default: - pl.frames[i].Handler = p.retransmissionQueue.AppDataAckHandler() - } + pl.frames[i].Handler = p.retransmissionQueue.AppDataAckHandler() } pl.streamFrames, lengthAdded = p.framer.AppendStreamFrames(pl.streamFrames, maxFrameSize-pl.length, v) @@ -852,8 +832,6 @@ func (p *packetPacker) appendShortHeaderPacket( }, nil } -// appendPacketPayload serializes the payload of a packet into the raw byte slice. -// It modifies the order of payload.frames. func (p *packetPacker) appendPacketPayload(raw []byte, pl payload, paddingLen protocol.ByteCount, v protocol.VersionNumber) ([]byte, error) { payloadOffset := len(raw) if pl.ack != nil { @@ -866,11 +844,6 @@ func (p *packetPacker) appendPacketPayload(raw []byte, pl payload, paddingLen pr if paddingLen > 0 { raw = append(raw, make([]byte, paddingLen)...) } - // Randomize the order of the control frames. - // This makes sure that the receiver doesn't rely on the order in which frames are packed. - if len(pl.frames) > 1 { - p.rand.Shuffle(len(pl.frames), func(i, j int) { pl.frames[i], pl.frames[j] = pl.frames[j], pl.frames[i] }) - } for _, f := range pl.frames { var err error raw, err = f.Frame.Append(raw, v) diff --git a/vendor/github.com/quic-go/quic-go/qlog/event.go b/vendor/github.com/quic-go/quic-go/qlog/event.go index 740d3c2e1..9dae74441 100644 --- a/vendor/github.com/quic-go/quic-go/qlog/event.go +++ b/vendor/github.com/quic-go/quic-go/qlog/event.go @@ -158,7 +158,6 @@ type eventPacketSent struct { PayloadLength logging.ByteCount Frames frames IsCoalesced bool - ECN logging.ECN Trigger string } @@ -173,9 +172,6 @@ func (e eventPacketSent) MarshalJSONObject(enc *gojay.Encoder) { enc.ObjectKey("raw", rawInfo{Length: e.Length, PayloadLength: e.PayloadLength}) enc.ArrayKeyOmitEmpty("frames", e.Frames) enc.BoolKeyOmitEmpty("is_coalesced", e.IsCoalesced) - if e.ECN != logging.ECNUnsupported { - enc.StringKey("ecn", ecn(e.ECN).String()) - } enc.StringKeyOmitEmpty("trigger", e.Trigger) } @@ -184,7 +180,6 @@ type eventPacketReceived struct { Length logging.ByteCount PayloadLength logging.ByteCount Frames frames - ECN logging.ECN IsCoalesced bool Trigger string } @@ -200,9 +195,6 @@ func (e eventPacketReceived) MarshalJSONObject(enc *gojay.Encoder) { enc.ObjectKey("raw", rawInfo{Length: e.Length, PayloadLength: e.PayloadLength}) enc.ArrayKeyOmitEmpty("frames", e.Frames) enc.BoolKeyOmitEmpty("is_coalesced", e.IsCoalesced) - if e.ECN != logging.ECNUnsupported { - enc.StringKey("ecn", ecn(e.ECN).String()) - } enc.StringKeyOmitEmpty("trigger", e.Trigger) } @@ -524,20 +516,6 @@ func (e eventCongestionStateUpdated) MarshalJSONObject(enc *gojay.Encoder) { enc.StringKey("new", e.state.String()) } -type eventECNStateUpdated struct { - state logging.ECNState - trigger logging.ECNStateTrigger -} - -func (e eventECNStateUpdated) Category() category { return categoryRecovery } -func (e eventECNStateUpdated) Name() string { return "ecn_state_updated" } -func (e eventECNStateUpdated) IsNil() bool { return false } - -func (e eventECNStateUpdated) MarshalJSONObject(enc *gojay.Encoder) { - enc.StringKey("new", ecnState(e.state).String()) - enc.StringKeyOmitEmpty("trigger", ecnStateTrigger(e.trigger).String()) -} - type eventGeneric struct { name string msg string diff --git a/vendor/github.com/quic-go/quic-go/qlog/qlog.go b/vendor/github.com/quic-go/quic-go/qlog/qlog.go index 7801b6463..4c480e260 100644 --- a/vendor/github.com/quic-go/quic-go/qlog/qlog.go +++ b/vendor/github.com/quic-go/quic-go/qlog/qlog.go @@ -63,9 +63,11 @@ type connectionTracer struct { lastMetrics *metrics } +var _ logging.ConnectionTracer = &connectionTracer{} + // NewConnectionTracer creates a new tracer to record a qlog for a connection. -func NewConnectionTracer(w io.WriteCloser, p protocol.Perspective, odcid protocol.ConnectionID) *logging.ConnectionTracer { - t := connectionTracer{ +func NewConnectionTracer(w io.WriteCloser, p protocol.Perspective, odcid protocol.ConnectionID) logging.ConnectionTracer { + t := &connectionTracer{ w: w, perspective: p, odcid: odcid, @@ -74,84 +76,7 @@ func NewConnectionTracer(w io.WriteCloser, p protocol.Perspective, odcid protoco referenceTime: time.Now(), } go t.run() - return &logging.ConnectionTracer{ - StartedConnection: func(local, remote net.Addr, srcConnID, destConnID logging.ConnectionID) { - t.StartedConnection(local, remote, srcConnID, destConnID) - }, - NegotiatedVersion: func(chosen logging.VersionNumber, clientVersions, serverVersions []logging.VersionNumber) { - t.NegotiatedVersion(chosen, clientVersions, serverVersions) - }, - ClosedConnection: func(e error) { t.ClosedConnection(e) }, - SentTransportParameters: func(tp *wire.TransportParameters) { t.SentTransportParameters(tp) }, - ReceivedTransportParameters: func(tp *wire.TransportParameters) { t.ReceivedTransportParameters(tp) }, - RestoredTransportParameters: func(tp *wire.TransportParameters) { t.RestoredTransportParameters(tp) }, - SentLongHeaderPacket: func(hdr *logging.ExtendedHeader, size logging.ByteCount, ecn logging.ECN, ack *logging.AckFrame, frames []logging.Frame) { - t.SentLongHeaderPacket(hdr, size, ecn, ack, frames) - }, - SentShortHeaderPacket: func(hdr *logging.ShortHeader, size logging.ByteCount, ecn logging.ECN, ack *logging.AckFrame, frames []logging.Frame) { - t.SentShortHeaderPacket(hdr, size, ecn, ack, frames) - }, - ReceivedLongHeaderPacket: func(hdr *logging.ExtendedHeader, size logging.ByteCount, ecn logging.ECN, frames []logging.Frame) { - t.ReceivedLongHeaderPacket(hdr, size, ecn, frames) - }, - ReceivedShortHeaderPacket: func(hdr *logging.ShortHeader, size logging.ByteCount, ecn logging.ECN, frames []logging.Frame) { - t.ReceivedShortHeaderPacket(hdr, size, ecn, frames) - }, - ReceivedRetry: func(hdr *wire.Header) { - t.ReceivedRetry(hdr) - }, - ReceivedVersionNegotiationPacket: func(dest, src logging.ArbitraryLenConnectionID, versions []logging.VersionNumber) { - t.ReceivedVersionNegotiationPacket(dest, src, versions) - }, - BufferedPacket: func(pt logging.PacketType, size protocol.ByteCount) { - t.BufferedPacket(pt, size) - }, - DroppedPacket: func(pt logging.PacketType, size protocol.ByteCount, reason logging.PacketDropReason) { - t.DroppedPacket(pt, size, reason) - }, - UpdatedMetrics: func(rttStats *utils.RTTStats, cwnd, bytesInFlight protocol.ByteCount, packetsInFlight int) { - t.UpdatedMetrics(rttStats, cwnd, bytesInFlight, packetsInFlight) - }, - LostPacket: func(encLevel protocol.EncryptionLevel, pn protocol.PacketNumber, lossReason logging.PacketLossReason) { - t.LostPacket(encLevel, pn, lossReason) - }, - UpdatedCongestionState: func(state logging.CongestionState) { - t.UpdatedCongestionState(state) - }, - UpdatedPTOCount: func(value uint32) { - t.UpdatedPTOCount(value) - }, - UpdatedKeyFromTLS: func(encLevel protocol.EncryptionLevel, pers protocol.Perspective) { - t.UpdatedKeyFromTLS(encLevel, pers) - }, - UpdatedKey: func(generation protocol.KeyPhase, remote bool) { - t.UpdatedKey(generation, remote) - }, - DroppedEncryptionLevel: func(encLevel protocol.EncryptionLevel) { - t.DroppedEncryptionLevel(encLevel) - }, - DroppedKey: func(generation protocol.KeyPhase) { - t.DroppedKey(generation) - }, - SetLossTimer: func(tt logging.TimerType, encLevel protocol.EncryptionLevel, timeout time.Time) { - t.SetLossTimer(tt, encLevel, timeout) - }, - LossTimerExpired: func(tt logging.TimerType, encLevel protocol.EncryptionLevel) { - t.LossTimerExpired(tt, encLevel) - }, - LossTimerCanceled: func() { - t.LossTimerCanceled() - }, - ECNStateUpdated: func(state logging.ECNState, trigger logging.ECNStateTrigger) { - t.ECNStateUpdated(state, trigger) - }, - Debug: func(name, msg string) { - t.Debug(name, msg) - }, - Close: func() { - t.Close() - }, - } + return t } func (t *connectionTracer) run() { @@ -328,33 +253,15 @@ func (t *connectionTracer) toTransportParameters(tp *wire.TransportParameters) * } } -func (t *connectionTracer) SentLongHeaderPacket( - hdr *logging.ExtendedHeader, - size logging.ByteCount, - ecn logging.ECN, - ack *logging.AckFrame, - frames []logging.Frame, -) { - t.sentPacket(*transformLongHeader(hdr), size, hdr.Length, ecn, ack, frames) +func (t *connectionTracer) SentLongHeaderPacket(hdr *logging.ExtendedHeader, packetSize logging.ByteCount, ack *logging.AckFrame, frames []logging.Frame) { + t.sentPacket(*transformLongHeader(hdr), packetSize, hdr.Length, ack, frames) } -func (t *connectionTracer) SentShortHeaderPacket( - hdr *logging.ShortHeader, - size logging.ByteCount, - ecn logging.ECN, - ack *logging.AckFrame, - frames []logging.Frame, -) { - t.sentPacket(*transformShortHeader(hdr), size, 0, ecn, ack, frames) +func (t *connectionTracer) SentShortHeaderPacket(hdr *logging.ShortHeader, packetSize logging.ByteCount, ack *logging.AckFrame, frames []logging.Frame) { + t.sentPacket(*transformShortHeader(hdr), packetSize, 0, ack, frames) } -func (t *connectionTracer) sentPacket( - hdr gojay.MarshalerJSONObject, - size, payloadLen logging.ByteCount, - ecn logging.ECN, - ack *logging.AckFrame, - frames []logging.Frame, -) { +func (t *connectionTracer) sentPacket(hdr gojay.MarshalerJSONObject, packetSize, payloadLen logging.ByteCount, ack *logging.AckFrame, frames []logging.Frame) { numFrames := len(frames) if ack != nil { numFrames++ @@ -369,15 +276,14 @@ func (t *connectionTracer) sentPacket( t.mutex.Lock() t.recordEvent(time.Now(), &eventPacketSent{ Header: hdr, - Length: size, + Length: packetSize, PayloadLength: payloadLen, - ECN: ecn, Frames: fs, }) t.mutex.Unlock() } -func (t *connectionTracer) ReceivedLongHeaderPacket(hdr *logging.ExtendedHeader, size logging.ByteCount, ecn logging.ECN, frames []logging.Frame) { +func (t *connectionTracer) ReceivedLongHeaderPacket(hdr *logging.ExtendedHeader, packetSize logging.ByteCount, frames []logging.Frame) { fs := make([]frame, len(frames)) for i, f := range frames { fs[i] = frame{Frame: f} @@ -386,15 +292,14 @@ func (t *connectionTracer) ReceivedLongHeaderPacket(hdr *logging.ExtendedHeader, t.mutex.Lock() t.recordEvent(time.Now(), &eventPacketReceived{ Header: header, - Length: size, + Length: packetSize, PayloadLength: hdr.Length, - ECN: ecn, Frames: fs, }) t.mutex.Unlock() } -func (t *connectionTracer) ReceivedShortHeaderPacket(hdr *logging.ShortHeader, size logging.ByteCount, ecn logging.ECN, frames []logging.Frame) { +func (t *connectionTracer) ReceivedShortHeaderPacket(hdr *logging.ShortHeader, packetSize logging.ByteCount, frames []logging.Frame) { fs := make([]frame, len(frames)) for i, f := range frames { fs[i] = frame{Frame: f} @@ -403,9 +308,8 @@ func (t *connectionTracer) ReceivedShortHeaderPacket(hdr *logging.ShortHeader, s t.mutex.Lock() t.recordEvent(time.Now(), &eventPacketReceived{ Header: header, - Length: size, - PayloadLength: size - wire.ShortHeaderLen(hdr.DestConnectionID, hdr.PacketNumberLen), - ECN: ecn, + Length: packetSize, + PayloadLength: packetSize - wire.ShortHeaderLen(hdr.DestConnectionID, hdr.PacketNumberLen), Frames: fs, }) t.mutex.Unlock() @@ -578,12 +482,6 @@ func (t *connectionTracer) LossTimerCanceled() { t.mutex.Unlock() } -func (t *connectionTracer) ECNStateUpdated(state logging.ECNState, trigger logging.ECNStateTrigger) { - t.mutex.Lock() - t.recordEvent(time.Now(), &eventECNStateUpdated{state: state, trigger: trigger}) - t.mutex.Unlock() -} - func (t *connectionTracer) Debug(name, msg string) { t.mutex.Lock() t.recordEvent(time.Now(), &eventGeneric{ diff --git a/vendor/github.com/quic-go/quic-go/qlog/types.go b/vendor/github.com/quic-go/quic-go/qlog/types.go index e0c0b2434..c47ad481e 100644 --- a/vendor/github.com/quic-go/quic-go/qlog/types.go +++ b/vendor/github.com/quic-go/quic-go/qlog/types.go @@ -312,61 +312,3 @@ func (s congestionState) String() string { return "unknown congestion state" } } - -type ecn logging.ECN - -func (e ecn) String() string { - //nolint:exhaustive // The unsupported value is never logged. - switch logging.ECN(e) { - case logging.ECTNot: - return "Not-ECT" - case logging.ECT0: - return "ECT(0)" - case logging.ECT1: - return "ECT(1)" - case logging.ECNCE: - return "CE" - default: - return "unknown ECN" - } -} - -type ecnState logging.ECNState - -func (e ecnState) String() string { - switch logging.ECNState(e) { - case logging.ECNStateTesting: - return "testing" - case logging.ECNStateUnknown: - return "unknown" - case logging.ECNStateCapable: - return "capable" - case logging.ECNStateFailed: - return "failed" - default: - return "unknown ECN state" - } -} - -type ecnStateTrigger logging.ECNStateTrigger - -func (e ecnStateTrigger) String() string { - switch logging.ECNStateTrigger(e) { - case logging.ECNTriggerNoTrigger: - return "" - case logging.ECNFailedNoECNCounts: - return "ACK doesn't contain ECN marks" - case logging.ECNFailedDecreasedECNCounts: - return "ACK decreases ECN counts" - case logging.ECNFailedLostAllTestingPackets: - return "all ECN testing packets declared lost" - case logging.ECNFailedMoreECNCountsThanSent: - return "ACK contains more ECN counts than ECN-marked packets sent" - case logging.ECNFailedTooFewECNCounts: - return "ACK contains fewer new ECN counts than acknowledged ECN-marked packets" - case logging.ECNFailedManglingDetected: - return "ECN mangling detected" - default: - return "unknown ECN state trigger" - } -} diff --git a/vendor/github.com/quic-go/quic-go/send_conn.go b/vendor/github.com/quic-go/quic-go/send_conn.go index 4fda14691..4e7007fad 100644 --- a/vendor/github.com/quic-go/quic-go/send_conn.go +++ b/vendor/github.com/quic-go/quic-go/send_conn.go @@ -1,15 +1,15 @@ package quic import ( + "math" "net" "github.com/quic-go/quic-go/internal/protocol" - "github.com/quic-go/quic-go/internal/utils" ) // A sendConn allows sending using a simple Write() on a non-connected packet conn. type sendConn interface { - Write(b []byte, gsoSize uint16, ecn protocol.ECN) error + Write(b []byte, size protocol.ByteCount) error Close() error LocalAddr() net.Addr RemoteAddr() net.Addr @@ -20,72 +20,61 @@ type sendConn interface { type sconn struct { rawConn - localAddr net.Addr remoteAddr net.Addr - - logger utils.Logger - - packetInfoOOB []byte - // If GSO enabled, and we receive a GSO error for this remote address, GSO is disabled. - gotGSOError bool + info packetInfo + oob []byte } var _ sendConn = &sconn{} -func newSendConn(c rawConn, remote net.Addr, info packetInfo, logger utils.Logger) *sconn { - localAddr := c.LocalAddr() - if info.addr.IsValid() { - if udpAddr, ok := localAddr.(*net.UDPAddr); ok { - addrCopy := *udpAddr - addrCopy.IP = info.addr.AsSlice() - localAddr = &addrCopy - } +func newSendConn(c rawConn, remote net.Addr) *sconn { + sc := &sconn{ + rawConn: c, + remoteAddr: remote, } + if c.capabilities().GSO { + // add 32 bytes, so we can add the UDP_SEGMENT msg + sc.oob = make([]byte, 0, 32) + } + return sc +} +func newSendConnWithPacketInfo(c rawConn, remote net.Addr, info packetInfo) *sconn { oob := info.OOB() - // increase oob slice capacity, so we can add the UDP_SEGMENT and ECN control messages without allocating - l := len(oob) - oob = append(oob, make([]byte, 64)...)[:l] + if c.capabilities().GSO { + // add 32 bytes, so we can add the UDP_SEGMENT msg + l := len(oob) + oob = append(oob, make([]byte, 32)...) + oob = oob[:l] + } return &sconn{ - rawConn: c, - localAddr: localAddr, - remoteAddr: remote, - packetInfoOOB: oob, - logger: logger, + rawConn: c, + remoteAddr: remote, + info: info, + oob: oob, } } -func (c *sconn) Write(p []byte, gsoSize uint16, ecn protocol.ECN) error { - _, err := c.WritePacket(p, c.remoteAddr, c.packetInfoOOB, gsoSize, ecn) - if err != nil && isGSOError(err) { - // disable GSO for future calls - c.gotGSOError = true - if c.logger.Debug() { - c.logger.Debugf("GSO failed when sending to %s", c.remoteAddr) - } - // send out the packets one by one - for len(p) > 0 { - l := len(p) - if l > int(gsoSize) { - l = int(gsoSize) - } - if _, err := c.WritePacket(p[:l], c.remoteAddr, c.packetInfoOOB, 0, ecn); err != nil { - return err - } - p = p[l:] - } - return nil +func (c *sconn) Write(p []byte, size protocol.ByteCount) error { + if size > math.MaxUint16 { + panic("size overflow") } + _, err := c.WritePacket(p, uint16(size), c.remoteAddr, c.oob) return err } -func (c *sconn) capabilities() connCapabilities { - capabilities := c.rawConn.capabilities() - if capabilities.GSO { - capabilities.GSO = !c.gotGSOError - } - return capabilities +func (c *sconn) RemoteAddr() net.Addr { + return c.remoteAddr } -func (c *sconn) RemoteAddr() net.Addr { return c.remoteAddr } -func (c *sconn) LocalAddr() net.Addr { return c.localAddr } +func (c *sconn) LocalAddr() net.Addr { + addr := c.rawConn.LocalAddr() + if c.info.addr.IsValid() { + if udpAddr, ok := addr.(*net.UDPAddr); ok { + addrCopy := *udpAddr + addrCopy.IP = c.info.addr.AsSlice() + addr = &addrCopy + } + } + return addr +} diff --git a/vendor/github.com/quic-go/quic-go/send_queue.go b/vendor/github.com/quic-go/quic-go/send_queue.go index bde023348..ab7a45ca8 100644 --- a/vendor/github.com/quic-go/quic-go/send_queue.go +++ b/vendor/github.com/quic-go/quic-go/send_queue.go @@ -3,7 +3,7 @@ package quic import "github.com/quic-go/quic-go/internal/protocol" type sender interface { - Send(p *packetBuffer, gsoSize uint16, ecn protocol.ECN) + Send(p *packetBuffer, packetSize protocol.ByteCount) Run() error WouldBlock() bool Available() <-chan struct{} @@ -11,9 +11,8 @@ type sender interface { } type queueEntry struct { - buf *packetBuffer - gsoSize uint16 - ecn protocol.ECN + buf *packetBuffer + size protocol.ByteCount } type sendQueue struct { @@ -41,9 +40,9 @@ func newSendQueue(conn sendConn) sender { // Send sends out a packet. It's guaranteed to not block. // Callers need to make sure that there's actually space in the send queue by calling WouldBlock. // Otherwise Send will panic. -func (h *sendQueue) Send(p *packetBuffer, gsoSize uint16, ecn protocol.ECN) { +func (h *sendQueue) Send(p *packetBuffer, size protocol.ByteCount) { select { - case h.queue <- queueEntry{buf: p, gsoSize: gsoSize, ecn: ecn}: + case h.queue <- queueEntry{buf: p, size: size}: // clear available channel if we've reached capacity if len(h.queue) == sendQueueCapacity { select { @@ -78,12 +77,12 @@ func (h *sendQueue) Run() error { // make sure that all queued packets are actually sent out shouldClose = true case e := <-h.queue: - if err := h.conn.Write(e.buf.Data, e.gsoSize, e.ecn); err != nil { + if err := h.conn.Write(e.buf.Data, e.size); err != nil { // This additional check enables: // 1. Checking for "datagram too large" message from the kernel, as such, // 2. Path MTU discovery,and // 3. Eventual detection of loss PingFrame. - if !isSendMsgSizeErr(err) { + if !isMsgSizeErr(err) { return err } } diff --git a/vendor/github.com/quic-go/quic-go/send_stream.go b/vendor/github.com/quic-go/quic-go/send_stream.go index 4113d9f0c..62ebe2ea5 100644 --- a/vendor/github.com/quic-go/quic-go/send_stream.go +++ b/vendor/github.com/quic-go/quic-go/send_stream.go @@ -30,7 +30,7 @@ type sendStream struct { retransmissionQueue []*wire.StreamFrame ctx context.Context - ctxCancel context.CancelCauseFunc + ctxCancel context.CancelFunc streamID protocol.StreamID sender streamSender @@ -71,7 +71,7 @@ func newSendStream( writeChan: make(chan struct{}, 1), writeOnce: make(chan struct{}, 1), // cap: 1, to protect against concurrent use of Write } - s.ctx, s.ctxCancel = context.WithCancelCause(context.Background()) + s.ctx, s.ctxCancel = context.WithCancel(context.Background()) return s } @@ -366,7 +366,7 @@ func (s *sendStream) Close() error { s.mutex.Unlock() return fmt.Errorf("close called for canceled stream %d", s.streamID) } - s.ctxCancel(nil) + s.ctxCancel() s.finishedWriting = true s.mutex.Unlock() @@ -385,8 +385,8 @@ func (s *sendStream) cancelWriteImpl(errorCode qerr.StreamErrorCode, remote bool s.mutex.Unlock() return } + s.ctxCancel() s.cancelWriteErr = &StreamError{StreamID: s.streamID, ErrorCode: errorCode, Remote: remote} - s.ctxCancel(s.cancelWriteErr) s.numOutstandingFrames = 0 s.retransmissionQueue = nil newlyCompleted := s.isNewlyCompleted() @@ -435,7 +435,7 @@ func (s *sendStream) SetWriteDeadline(t time.Time) error { // The peer will NOT be informed about this: the stream is closed without sending a FIN or RST. func (s *sendStream) closeForShutdown(err error) { s.mutex.Lock() - s.ctxCancel(err) + s.ctxCancel() s.closeForShutdownErr = err s.mutex.Unlock() s.signalWrite() diff --git a/vendor/github.com/quic-go/quic-go/server.go b/vendor/github.com/quic-go/quic-go/server.go index 119289b39..0f8219e3a 100644 --- a/vendor/github.com/quic-go/quic-go/server.go +++ b/vendor/github.com/quic-go/quic-go/server.go @@ -2,6 +2,7 @@ package quic import ( "context" + "crypto/rand" "crypto/tls" "errors" "fmt" @@ -58,8 +59,7 @@ type zeroRTTQueue struct { type baseServer struct { mutex sync.Mutex - disableVersionNegotiation bool - acceptEarlyConns bool + acceptEarlyConns bool tlsConf *tls.Config config *Config @@ -67,7 +67,6 @@ type baseServer struct { conn rawConn tokenGenerator *handshake.TokenGenerator - maxTokenAge time.Duration connIDGenerator ConnectionIDGenerator connHandler packetHandlerManager @@ -93,7 +92,7 @@ type baseServer struct { *tls.Config, *handshake.TokenGenerator, bool, /* client address validated by an address validation token */ - *logging.ConnectionTracer, + logging.ConnectionTracer, uint64, utils.Logger, protocol.VersionNumber, @@ -109,7 +108,7 @@ type baseServer struct { connQueue chan quicConn connQueueLen int32 // to be used as an atomic - tracer *logging.Tracer + tracer logging.Tracer logger utils.Logger } @@ -225,33 +224,32 @@ func newServer( connIDGenerator ConnectionIDGenerator, tlsConf *tls.Config, config *Config, - tracer *logging.Tracer, + tracer logging.Tracer, onClose func(), - tokenGeneratorKey TokenGeneratorKey, - maxTokenAge time.Duration, - disableVersionNegotiation bool, acceptEarly bool, -) *baseServer { +) (*baseServer, error) { + tokenGenerator, err := handshake.NewTokenGenerator(rand.Reader) + if err != nil { + return nil, err + } s := &baseServer{ - conn: conn, - tlsConf: tlsConf, - config: config, - tokenGenerator: handshake.NewTokenGenerator(tokenGeneratorKey), - maxTokenAge: maxTokenAge, - connIDGenerator: connIDGenerator, - connHandler: connHandler, - connQueue: make(chan quicConn), - errorChan: make(chan struct{}), - running: make(chan struct{}), - receivedPackets: make(chan receivedPacket, protocol.MaxServerUnprocessedPackets), - versionNegotiationQueue: make(chan receivedPacket, 4), - invalidTokenQueue: make(chan receivedPacket, 4), - newConn: newConnection, - tracer: tracer, - logger: utils.DefaultLogger.WithPrefix("server"), - acceptEarlyConns: acceptEarly, - disableVersionNegotiation: disableVersionNegotiation, - onClose: onClose, + conn: conn, + tlsConf: tlsConf, + config: config, + tokenGenerator: tokenGenerator, + connIDGenerator: connIDGenerator, + connHandler: connHandler, + connQueue: make(chan quicConn), + errorChan: make(chan struct{}), + running: make(chan struct{}), + receivedPackets: make(chan receivedPacket, protocol.MaxServerUnprocessedPackets), + versionNegotiationQueue: make(chan receivedPacket, 4), + invalidTokenQueue: make(chan receivedPacket, 4), + newConn: newConnection, + tracer: tracer, + logger: utils.DefaultLogger.WithPrefix("server"), + acceptEarlyConns: acceptEarly, + onClose: onClose, } if acceptEarly { s.zeroRTTQueues = map[protocol.ConnectionID]*zeroRTTQueue{} @@ -259,7 +257,7 @@ func newServer( go s.run() go s.runSendQueue() s.logger.Debugf("Listening for %s connections on %s", conn.LocalAddr().Network(), conn.LocalAddr().String()) - return s + return s, nil } func (s *baseServer) run() { @@ -352,7 +350,7 @@ func (s *baseServer) handlePacket(p receivedPacket) { case s.receivedPackets <- p: default: s.logger.Debugf("Dropping packet from %s (%d bytes). Server receive queue full.", p.remoteAddr, p.Size()) - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropDOSPrevention) } } @@ -365,7 +363,7 @@ func (s *baseServer) handlePacketImpl(p receivedPacket) bool /* is the buffer st if wire.IsVersionNegotiationPacket(p.data) { s.logger.Debugf("Dropping Version Negotiation packet.") - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeVersionNegotiation, p.Size(), logging.PacketDropUnexpectedPacket) } return false @@ -378,20 +376,20 @@ func (s *baseServer) handlePacketImpl(p receivedPacket) bool /* is the buffer st // drop the packet if we failed to parse the protocol version if err != nil { s.logger.Debugf("Dropping a packet with an unknown version") - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropUnexpectedPacket) } return false } // send a Version Negotiation Packet if the client is speaking a different protocol version if !protocol.IsSupportedVersion(s.config.Versions, v) { - if s.disableVersionNegotiation { + if s.config.DisableVersionNegotiationPackets { return false } if p.Size() < protocol.MinUnknownVersionPacketSize { s.logger.Debugf("Dropping a packet with an unsupported version number %d that is too small (%d bytes)", v, p.Size()) - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropUnexpectedPacket) } return false @@ -401,7 +399,7 @@ func (s *baseServer) handlePacketImpl(p receivedPacket) bool /* is the buffer st if wire.Is0RTTPacket(p.data) { if !s.acceptEarlyConns { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketType0RTT, p.Size(), logging.PacketDropUnexpectedPacket) } return false @@ -413,7 +411,7 @@ func (s *baseServer) handlePacketImpl(p receivedPacket) bool /* is the buffer st // The header will then be parsed again. hdr, _, _, err := wire.ParsePacket(p.data) if err != nil { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropHeaderParseError) } s.logger.Debugf("Error parsing packet: %s", err) @@ -421,7 +419,7 @@ func (s *baseServer) handlePacketImpl(p receivedPacket) bool /* is the buffer st } if hdr.Type == protocol.PacketTypeInitial && p.Size() < protocol.MinInitialPacketSize { s.logger.Debugf("Dropping a packet that is too small to be a valid Initial (%d bytes)", p.Size()) - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropUnexpectedPacket) } return false @@ -432,7 +430,7 @@ func (s *baseServer) handlePacketImpl(p receivedPacket) bool /* is the buffer st // There's little point in sending a Stateless Reset, since the client // might not have received the token yet. s.logger.Debugf("Dropping long header packet of type %s (%d bytes)", hdr.Type, len(p.data)) - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeFromHeader(hdr), p.Size(), logging.PacketDropUnexpectedPacket) } return false @@ -451,7 +449,7 @@ func (s *baseServer) handlePacketImpl(p receivedPacket) bool /* is the buffer st func (s *baseServer) handle0RTTPacket(p receivedPacket) bool { connID, err := wire.ParseConnectionID(p.data, 0) if err != nil { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketType0RTT, p.Size(), logging.PacketDropHeaderParseError) } return false @@ -465,7 +463,7 @@ func (s *baseServer) handle0RTTPacket(p receivedPacket) bool { if q, ok := s.zeroRTTQueues[connID]; ok { if len(q.packets) >= protocol.Max0RTTQueueLen { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketType0RTT, p.Size(), logging.PacketDropDOSPrevention) } return false @@ -475,7 +473,7 @@ func (s *baseServer) handle0RTTPacket(p receivedPacket) bool { } if len(s.zeroRTTQueues) >= protocol.Max0RTTQueues { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketType0RTT, p.Size(), logging.PacketDropDOSPrevention) } return false @@ -503,7 +501,7 @@ func (s *baseServer) cleanupZeroRTTQueues(now time.Time) { continue } for _, p := range q.packets { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketType0RTT, p.Size(), logging.PacketDropDOSPrevention) } p.buffer.Release() @@ -527,10 +525,10 @@ func (s *baseServer) validateToken(token *handshake.Token, addr net.Addr) bool { if !token.ValidateRemoteAddr(addr) { return false } - if !token.IsRetryToken && time.Since(token.SentTime) > s.maxTokenAge { + if !token.IsRetryToken && time.Since(token.SentTime) > s.config.MaxTokenAge { return false } - if token.IsRetryToken && time.Since(token.SentTime) > s.config.maxRetryTokenAge() { + if token.IsRetryToken && time.Since(token.SentTime) > s.config.MaxRetryTokenAge { return false } return true @@ -539,7 +537,7 @@ func (s *baseServer) validateToken(token *handshake.Token, addr net.Addr) bool { func (s *baseServer) handleInitialImpl(p receivedPacket, hdr *wire.Header) error { if len(hdr.Token) == 0 && hdr.DestConnectionID.Len() < protocol.MinConnectionIDLenInitial { p.buffer.Release() - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropUnexpectedPacket) } return errors.New("too short connection ID") @@ -624,7 +622,7 @@ func (s *baseServer) handleInitialImpl(p receivedPacket, hdr *wire.Header) error } config = populateConfig(conf) } - var tracer *logging.ConnectionTracer + var tracer logging.ConnectionTracer if config.Tracer != nil { // Use the same connection ID that is passed to the client's GetLogWriter callback. connID := hdr.DestConnectionID @@ -634,7 +632,7 @@ func (s *baseServer) handleInitialImpl(p receivedPacket, hdr *wire.Header) error tracer = config.Tracer(context.WithValue(context.Background(), ConnectionTracingKey, tracingID), protocol.PerspectiveServer, connID) } conn = s.newConn( - newSendConn(s.conn, p.remoteAddr, p.info, s.logger), + newSendConnWithPacketInfo(s.conn, p.remoteAddr, p.info), s.connHandler, origDestConnID, retrySrcConnID, @@ -741,10 +739,10 @@ func (s *baseServer) sendRetry(remoteAddr net.Addr, hdr *wire.Header, info packe // append the Retry integrity tag tag := handshake.GetRetryIntegrityTag(buf.Data, hdr.DestConnectionID, hdr.Version) buf.Data = append(buf.Data, tag[:]...) - if s.tracer != nil && s.tracer.SentPacket != nil { + if s.tracer != nil { s.tracer.SentPacket(remoteAddr, &replyHdr.Header, protocol.ByteCount(len(buf.Data)), nil) } - _, err = s.conn.WritePacket(buf.Data, remoteAddr, info.OOB(), 0, protocol.ECNUnsupported) + _, err = s.conn.WritePacket(buf.Data, uint16(len(buf.Data)), remoteAddr, info.OOB()) return err } @@ -762,7 +760,7 @@ func (s *baseServer) maybeSendInvalidToken(p receivedPacket) { hdr, _, _, err := wire.ParsePacket(p.data) if err != nil { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropHeaderParseError) } s.logger.Debugf("Error parsing packet: %s", err) @@ -777,14 +775,14 @@ func (s *baseServer) maybeSendInvalidToken(p receivedPacket) { // Only send INVALID_TOKEN if we can unprotect the packet. // This makes sure that we won't send it for packets that were corrupted. if err != nil { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropHeaderParseError) } return } hdrLen := extHdr.ParsedLen() if _, err := opener.Open(data[hdrLen:hdrLen], data[hdrLen:], extHdr.PacketNumber, data[:hdrLen]); err != nil { - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeInitial, p.Size(), logging.PacketDropPayloadDecryptError) } return @@ -840,10 +838,10 @@ func (s *baseServer) sendError(remoteAddr net.Addr, hdr *wire.Header, sealer han replyHdr.Log(s.logger) wire.LogFrame(s.logger, ccf, true) - if s.tracer != nil && s.tracer.SentPacket != nil { + if s.tracer != nil { s.tracer.SentPacket(remoteAddr, &replyHdr.Header, protocol.ByteCount(len(b.Data)), []logging.Frame{ccf}) } - _, err = s.conn.WritePacket(b.Data, remoteAddr, info.OOB(), 0, protocol.ECNUnsupported) + _, err = s.conn.WritePacket(b.Data, uint16(len(b.Data)), remoteAddr, info.OOB()) return err } @@ -869,7 +867,7 @@ func (s *baseServer) maybeSendVersionNegotiationPacket(p receivedPacket) { _, src, dest, err := wire.ParseArbitraryLenConnectionIDs(p.data) if err != nil { // should never happen s.logger.Debugf("Dropping a packet with an unknown version for which we failed to parse connection IDs") - if s.tracer != nil && s.tracer.DroppedPacket != nil { + if s.tracer != nil { s.tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropUnexpectedPacket) } return @@ -878,10 +876,10 @@ func (s *baseServer) maybeSendVersionNegotiationPacket(p receivedPacket) { s.logger.Debugf("Client offered version %s, sending Version Negotiation", v) data := wire.ComposeVersionNegotiation(dest, src, s.config.Versions) - if s.tracer != nil && s.tracer.SentVersionNegotiationPacket != nil { + if s.tracer != nil { s.tracer.SentVersionNegotiationPacket(p.remoteAddr, src, dest, s.config.Versions) } - if _, err := s.conn.WritePacket(data, p.remoteAddr, p.info.OOB(), 0, protocol.ECNUnsupported); err != nil { + if _, err := s.conn.WritePacket(data, uint16(len(data)), p.remoteAddr, p.info.OOB()); err != nil { s.logger.Debugf("Error sending Version Negotiation: %s", err) } } diff --git a/vendor/github.com/quic-go/quic-go/sys_conn.go b/vendor/github.com/quic-go/quic-go/sys_conn.go index 71cc46070..c68477c31 100644 --- a/vendor/github.com/quic-go/quic-go/sys_conn.go +++ b/vendor/github.com/quic-go/quic-go/sys_conn.go @@ -1,6 +1,7 @@ package quic import ( + "fmt" "log" "net" "os" @@ -26,7 +27,27 @@ type OOBCapablePacketConn interface { var _ OOBCapablePacketConn = &net.UDPConn{} -func wrapConn(pc net.PacketConn) (rawConn, error) { +// OptimizeConn takes a net.PacketConn and attempts to enable various optimizations that will improve QUIC performance: +// 1. It enables the Don't Fragment (DF) bit on the IP header. +// This is required to run DPLPMTUD (Path MTU Discovery, RFC 8899). +// 2. It enables reading of the ECN bits from the IP header. +// This allows the remote node to speed up its loss detection and recovery. +// 3. It uses batched syscalls (recvmmsg) to more efficiently receive packets from the socket. +// 4. It uses Generic Segmentation Offload (GSO) to efficiently send batches of packets (on Linux). +// +// In order for this to work, the connection needs to implement the OOBCapablePacketConn interface (as a *net.UDPConn does). +// +// It's only necessary to call this function explicitly if the application calls WriteTo +// after passing the connection to the Transport. +func OptimizeConn(c net.PacketConn) (net.PacketConn, error) { + return wrapConn(c) +} + +func wrapConn(pc net.PacketConn) (interface { + net.PacketConn + rawConn +}, error, +) { if err := setReceiveBuffer(pc); err != nil { if !strings.Contains(err.Error(), "use of closed network connection") { setBufferWarningOnce.Do(func() { @@ -104,12 +125,9 @@ func (c *basicConn) ReadPacket() (receivedPacket, error) { }, nil } -func (c *basicConn) WritePacket(b []byte, addr net.Addr, _ []byte, gsoSize uint16, ecn protocol.ECN) (n int, err error) { - if gsoSize != 0 { - panic("cannot use GSO with a basicConn") - } - if ecn != protocol.ECNUnsupported { - panic("cannot use ECN with a basicConn") +func (c *basicConn) WritePacket(b []byte, packetSize uint16, addr net.Addr, _ []byte) (n int, err error) { + if uint16(len(b)) != packetSize { + panic(fmt.Sprintf("inconsistent length. got: %d. expected %d", packetSize, len(b))) } return c.PacketConn.WriteTo(b, addr) } diff --git a/vendor/github.com/quic-go/quic-go/sys_conn_df.go b/vendor/github.com/quic-go/quic-go/sys_conn_df.go index 0db61509d..a21894122 100644 --- a/vendor/github.com/quic-go/quic-go/sys_conn_df.go +++ b/vendor/github.com/quic-go/quic-go/sys_conn_df.go @@ -1,4 +1,4 @@ -//go:build !linux && !windows && !darwin +//go:build !linux && !windows package quic @@ -11,12 +11,7 @@ func setDF(syscall.RawConn) (bool, error) { return false, nil } -func isSendMsgSizeErr(err error) bool { - // to be implemented for more specific platforms - return false -} - -func isRecvMsgSizeErr(err error) bool { +func isMsgSizeErr(err error) bool { // to be implemented for more specific platforms return false } diff --git a/vendor/github.com/quic-go/quic-go/sys_conn_df_darwin.go b/vendor/github.com/quic-go/quic-go/sys_conn_df_darwin.go deleted file mode 100644 index b51cd8f1a..000000000 --- a/vendor/github.com/quic-go/quic-go/sys_conn_df_darwin.go +++ /dev/null @@ -1,74 +0,0 @@ -//go:build darwin - -package quic - -import ( - "errors" - "strconv" - "strings" - "syscall" - - "golang.org/x/sys/unix" - - "github.com/quic-go/quic-go/internal/utils" -) - -func setDF(rawConn syscall.RawConn) (bool, error) { - // Setting DF bit is only supported from macOS11 - // https://github.com/chromium/chromium/blob/117.0.5881.2/net/socket/udp_socket_posix.cc#L555 - if supportsDF, err := isAtLeastMacOS11(); !supportsDF || err != nil { - return false, err - } - - // Enabling IP_DONTFRAG will force the kernel to return "sendto: message too long" - // and the datagram will not be fragmented - var errDFIPv4, errDFIPv6 error - if err := rawConn.Control(func(fd uintptr) { - errDFIPv4 = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_DONTFRAG, 1) - errDFIPv6 = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_DONTFRAG, 1) - }); err != nil { - return false, err - } - switch { - case errDFIPv4 == nil && errDFIPv6 == nil: - utils.DefaultLogger.Debugf("Setting DF for IPv4 and IPv6.") - case errDFIPv4 == nil && errDFIPv6 != nil: - utils.DefaultLogger.Debugf("Setting DF for IPv4.") - case errDFIPv4 != nil && errDFIPv6 == nil: - utils.DefaultLogger.Debugf("Setting DF for IPv6.") - // On macOS, the syscall for setting DF bit for IPv4 fails on dual-stack listeners. - // Treat the connection as not having DF enabled, even though the DF bit will be set - // when used for IPv6. - // See https://github.com/quic-go/quic-go/issues/3793 for details. - return false, nil - case errDFIPv4 != nil && errDFIPv6 != nil: - return false, errors.New("setting DF failed for both IPv4 and IPv6") - } - return true, nil -} - -func isSendMsgSizeErr(err error) bool { - return errors.Is(err, unix.EMSGSIZE) -} - -func isRecvMsgSizeErr(error) bool { return false } - -func isAtLeastMacOS11() (bool, error) { - uname := &unix.Utsname{} - err := unix.Uname(uname) - if err != nil { - return false, err - } - - release := string(uname.Release[:]) - if idx := strings.Index(release, "."); idx != -1 { - version, err := strconv.Atoi(release[:idx]) - if err != nil { - return false, err - } - // Darwin version 20 is macOS version 11 - // https://en.wikipedia.org/wiki/Darwin_(operating_system)#Darwin_20_onwards - return version >= 20, nil - } - return false, nil -} diff --git a/vendor/github.com/quic-go/quic-go/sys_conn_df_linux.go b/vendor/github.com/quic-go/quic-go/sys_conn_df_linux.go index f09eaa5df..92f7e725e 100644 --- a/vendor/github.com/quic-go/quic-go/sys_conn_df_linux.go +++ b/vendor/github.com/quic-go/quic-go/sys_conn_df_linux.go @@ -4,13 +4,22 @@ package quic import ( "errors" + "log" + "os" + "strconv" "syscall" + "unsafe" "golang.org/x/sys/unix" "github.com/quic-go/quic-go/internal/utils" ) +// UDP_SEGMENT controls GSO (Generic Segmentation Offload) +// +//nolint:stylecheck +const UDP_SEGMENT = 103 + func setDF(rawConn syscall.RawConn) (bool, error) { // Enabling IP_MTU_DISCOVER will force the kernel to return "sendto: message too long" // and the datagram will not be fragmented @@ -34,9 +43,41 @@ func setDF(rawConn syscall.RawConn) (bool, error) { return true, nil } -func isSendMsgSizeErr(err error) bool { +func maybeSetGSO(rawConn syscall.RawConn) bool { + enable, _ := strconv.ParseBool(os.Getenv("QUIC_GO_ENABLE_GSO")) + if !enable { + return false + } + + var setErr error + if err := rawConn.Control(func(fd uintptr) { + setErr = unix.SetsockoptInt(int(fd), syscall.IPPROTO_UDP, UDP_SEGMENT, 1) + }); err != nil { + setErr = err + } + if setErr != nil { + log.Println("failed to enable GSO") + return false + } + return true +} + +func isMsgSizeErr(err error) bool { // https://man7.org/linux/man-pages/man7/udp.7.html return errors.Is(err, unix.EMSGSIZE) } -func isRecvMsgSizeErr(error) bool { return false } +func appendUDPSegmentSizeMsg(b []byte, size uint16) []byte { + startLen := len(b) + const dataLen = 2 // payload is a uint16 + b = append(b, make([]byte, unix.CmsgSpace(dataLen))...) + h := (*unix.Cmsghdr)(unsafe.Pointer(&b[startLen])) + h.Level = syscall.IPPROTO_UDP + h.Type = UDP_SEGMENT + h.SetLen(unix.CmsgLen(dataLen)) + + // UnixRights uses the private `data` method, but I *think* this achieves the same goal. + offset := startLen + unix.CmsgSpace(0) + *(*uint16)(unsafe.Pointer(&b[offset])) = size + return b +} diff --git a/vendor/github.com/quic-go/quic-go/sys_conn_df_windows.go b/vendor/github.com/quic-go/quic-go/sys_conn_df_windows.go index e27635ec9..a7f1351a7 100644 --- a/vendor/github.com/quic-go/quic-go/sys_conn_df_windows.go +++ b/vendor/github.com/quic-go/quic-go/sys_conn_df_windows.go @@ -43,12 +43,7 @@ func setDF(rawConn syscall.RawConn) (bool, error) { return true, nil } -func isSendMsgSizeErr(err error) bool { - // https://docs.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2 - return errors.Is(err, windows.WSAEMSGSIZE) -} - -func isRecvMsgSizeErr(err error) bool { +func isMsgSizeErr(err error) bool { // https://docs.microsoft.com/en-us/windows/win32/winsock/windows-sockets-error-codes-2 return errors.Is(err, windows.WSAEMSGSIZE) } diff --git a/vendor/github.com/quic-go/quic-go/sys_conn_helper_darwin.go b/vendor/github.com/quic-go/quic-go/sys_conn_helper_darwin.go index d761072f2..7ad5f3af1 100644 --- a/vendor/github.com/quic-go/quic-go/sys_conn_helper_darwin.go +++ b/vendor/github.com/quic-go/quic-go/sys_conn_helper_darwin.go @@ -2,35 +2,20 @@ package quic -import ( - "encoding/binary" - "net/netip" - "syscall" +import "golang.org/x/sys/unix" - "golang.org/x/sys/unix" +const msgTypeIPTOS = unix.IP_RECVTOS + +const ( + ipv4RECVPKTINFO = unix.IP_RECVPKTINFO + ipv6RECVPKTINFO = 0x3d ) const ( - msgTypeIPTOS = unix.IP_RECVTOS - ipv4PKTINFO = unix.IP_RECVPKTINFO + msgTypeIPv4PKTINFO = unix.IP_PKTINFO + msgTypeIPv6PKTINFO = 0x2e ) -const ecnIPv4DataLen = 4 - // ReadBatch only returns a single packet on OSX, // see https://godoc.org/golang.org/x/net/ipv4#PacketConn.ReadBatch. const batchSize = 1 - -func parseIPv4PktInfo(body []byte) (ip netip.Addr, ifIndex uint32, ok bool) { - // struct in_pktinfo { - // unsigned int ipi_ifindex; /* Interface index */ - // struct in_addr ipi_spec_dst; /* Local address */ - // struct in_addr ipi_addr; /* Header Destination address */ - // }; - if len(body) != 12 { - return netip.Addr{}, 0, false - } - return netip.AddrFrom4(*(*[4]byte)(body[8:12])), binary.LittleEndian.Uint32(body), true -} - -func isGSOSupported(syscall.RawConn) bool { return false } diff --git a/vendor/github.com/quic-go/quic-go/sys_conn_helper_freebsd.go b/vendor/github.com/quic-go/quic-go/sys_conn_helper_freebsd.go index a53ca2eae..8d16d0b91 100644 --- a/vendor/github.com/quic-go/quic-go/sys_conn_helper_freebsd.go +++ b/vendor/github.com/quic-go/quic-go/sys_conn_helper_freebsd.go @@ -2,30 +2,20 @@ package quic -import ( - "net/netip" - "syscall" - - "golang.org/x/sys/unix" -) +import "golang.org/x/sys/unix" const ( msgTypeIPTOS = unix.IP_RECVTOS - ipv4PKTINFO = 0x7 ) -const ecnIPv4DataLen = 1 +const ( + ipv4RECVPKTINFO = 0x7 + ipv6RECVPKTINFO = 0x24 +) + +const ( + msgTypeIPv4PKTINFO = 0x7 + msgTypeIPv6PKTINFO = 0x2e +) const batchSize = 8 - -func parseIPv4PktInfo(body []byte) (ip netip.Addr, _ uint32, ok bool) { - // struct in_pktinfo { - // struct in_addr ipi_addr; /* Header Destination address */ - // }; - if len(body) != 4 { - return netip.Addr{}, 0, false - } - return netip.AddrFrom4(*(*[4]byte)(body)), 0, true -} - -func isGSOSupported(syscall.RawConn) bool { return false } diff --git a/vendor/github.com/quic-go/quic-go/sys_conn_helper_linux.go b/vendor/github.com/quic-go/quic-go/sys_conn_helper_linux.go index 310c83741..2c12233cb 100644 --- a/vendor/github.com/quic-go/quic-go/sys_conn_helper_linux.go +++ b/vendor/github.com/quic-go/quic-go/sys_conn_helper_linux.go @@ -3,23 +3,22 @@ package quic import ( - "encoding/binary" - "errors" - "net/netip" - "os" - "strconv" "syscall" - "unsafe" "golang.org/x/sys/unix" ) +const msgTypeIPTOS = unix.IP_TOS + const ( - msgTypeIPTOS = unix.IP_TOS - ipv4PKTINFO = unix.IP_PKTINFO + ipv4RECVPKTINFO = unix.IP_PKTINFO + ipv6RECVPKTINFO = unix.IPV6_RECVPKTINFO ) -const ecnIPv4DataLen = 1 +const ( + msgTypeIPv4PKTINFO = unix.IP_PKTINFO + msgTypeIPv6PKTINFO = unix.IPV6_PKTINFO +) const batchSize = 8 // needs to smaller than MaxUint8 (otherwise the type of oobConn.readPos has to be changed) @@ -42,58 +41,3 @@ func forceSetSendBuffer(c syscall.RawConn, bytes int) error { } return serr } - -func parseIPv4PktInfo(body []byte) (ip netip.Addr, ifIndex uint32, ok bool) { - // struct in_pktinfo { - // unsigned int ipi_ifindex; /* Interface index */ - // struct in_addr ipi_spec_dst; /* Local address */ - // struct in_addr ipi_addr; /* Header Destination address */ - // }; - if len(body) != 12 { - return netip.Addr{}, 0, false - } - return netip.AddrFrom4(*(*[4]byte)(body[8:12])), binary.LittleEndian.Uint32(body), true -} - -// isGSOSupported tests if the kernel supports GSO. -// Sending with GSO might still fail later on, if the interface doesn't support it (see isGSOError). -func isGSOSupported(conn syscall.RawConn) bool { - disabled, err := strconv.ParseBool(os.Getenv("QUIC_GO_DISABLE_GSO")) - if err == nil && disabled { - return false - } - var serr error - if err := conn.Control(func(fd uintptr) { - _, serr = unix.GetsockoptInt(int(fd), unix.IPPROTO_UDP, unix.UDP_SEGMENT) - }); err != nil { - return false - } - return serr == nil -} - -func appendUDPSegmentSizeMsg(b []byte, size uint16) []byte { - startLen := len(b) - const dataLen = 2 // payload is a uint16 - b = append(b, make([]byte, unix.CmsgSpace(dataLen))...) - h := (*unix.Cmsghdr)(unsafe.Pointer(&b[startLen])) - h.Level = syscall.IPPROTO_UDP - h.Type = unix.UDP_SEGMENT - h.SetLen(unix.CmsgLen(dataLen)) - - // UnixRights uses the private `data` method, but I *think* this achieves the same goal. - offset := startLen + unix.CmsgSpace(0) - *(*uint16)(unsafe.Pointer(&b[offset])) = size - return b -} - -func isGSOError(err error) bool { - var serr *os.SyscallError - if errors.As(err, &serr) { - // EIO is returned by udp_send_skb() if the device driver does not have tx checksums enabled, - // which is a hard requirement of UDP_SEGMENT. See: - // https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/tree/man7/udp.7?id=806eabd74910447f21005160e90957bde4db0183#n228 - // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/net/ipv4/udp.c?h=v6.2&id=c9c3395d5e3dcc6daee66c6908354d47bf98cb0c#n942 - return serr.Err == unix.EIO - } - return false -} diff --git a/vendor/github.com/quic-go/quic-go/sys_conn_helper_nonlinux.go b/vendor/github.com/quic-go/quic-go/sys_conn_helper_nonlinux.go index cace82d5d..80b795c33 100644 --- a/vendor/github.com/quic-go/quic-go/sys_conn_helper_nonlinux.go +++ b/vendor/github.com/quic-go/quic-go/sys_conn_helper_nonlinux.go @@ -4,6 +4,3 @@ package quic func forceSetReceiveBuffer(c any, bytes int) error { return nil } func forceSetSendBuffer(c any, bytes int) error { return nil } - -func appendUDPSegmentSizeMsg([]byte, uint16) []byte { return nil } -func isGSOError(error) bool { return false } diff --git a/vendor/github.com/quic-go/quic-go/sys_conn_no_gso.go b/vendor/github.com/quic-go/quic-go/sys_conn_no_gso.go new file mode 100644 index 000000000..6f6a8c917 --- /dev/null +++ b/vendor/github.com/quic-go/quic-go/sys_conn_no_gso.go @@ -0,0 +1,8 @@ +//go:build darwin || freebsd + +package quic + +import "syscall" + +func maybeSetGSO(_ syscall.RawConn) bool { return false } +func appendUDPSegmentSizeMsg(_ []byte, _ uint16) []byte { return nil } diff --git a/vendor/github.com/quic-go/quic-go/sys_conn_oob.go b/vendor/github.com/quic-go/quic-go/sys_conn_oob.go index 71a037d5a..fc28f94b7 100644 --- a/vendor/github.com/quic-go/quic-go/sys_conn_oob.go +++ b/vendor/github.com/quic-go/quic-go/sys_conn_oob.go @@ -5,15 +5,11 @@ package quic import ( "encoding/binary" "errors" - "log" + "fmt" "net" "net/netip" - "os" - "strconv" - "sync" "syscall" "time" - "unsafe" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" @@ -59,11 +55,6 @@ func inspectWriteBuffer(c syscall.RawConn) (int, error) { return size, serr } -func isECNDisabled() bool { - disabled, err := strconv.ParseBool(os.Getenv("QUIC_GO_DISABLE_ECN")) - return err == nil && disabled -} - type oobConn struct { OOBCapablePacketConn batchConn batchConn @@ -96,8 +87,8 @@ func newConn(c OOBCapablePacketConn, supportsDF bool) (*oobConn, error) { errECNIPv6 = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_RECVTCLASS, 1) if needsPacketInfo { - errPIIPv4 = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, ipv4PKTINFO, 1) - errPIIPv6 = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_RECVPKTINFO, 1) + errPIIPv4 = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, ipv4RECVPKTINFO, 1) + errPIIPv6 = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, ipv6RECVPKTINFO, 1) } }); err != nil { return nil, err @@ -135,6 +126,10 @@ func newConn(c OOBCapablePacketConn, supportsDF bool) (*oobConn, error) { bc = ipv4.NewPacketConn(c) } + // Try enabling GSO. + // This will only succeed on Linux, and only for kernels > 4.18. + supportsGSO := maybeSetGSO(rawConn) + msgs := make([]ipv4.Message, batchSize) for i := range msgs { // preallocate the [][]byte @@ -145,20 +140,15 @@ func newConn(c OOBCapablePacketConn, supportsDF bool) (*oobConn, error) { batchConn: bc, messages: msgs, readPos: batchSize, - cap: connCapabilities{ - DF: supportsDF, - GSO: isGSOSupported(rawConn), - ECN: !isECNDisabled(), - }, } + oobConn.cap.DF = supportsDF + oobConn.cap.GSO = supportsGSO for i := 0; i < batchSize; i++ { oobConn.messages[i].OOB = make([]byte, oobBufferSize) } return oobConn, nil } -var invalidCmsgOnceV4, invalidCmsgOnceV6 sync.Once - func (c *oobConn) ReadPacket() (receivedPacket, error) { if len(c.messages) == int(c.readPos) { // all messages read. Read the next batch of messages. c.messages = c.messages[:batchSize] @@ -197,37 +187,39 @@ func (c *oobConn) ReadPacket() (receivedPacket, error) { if hdr.Level == unix.IPPROTO_IP { switch hdr.Type { case msgTypeIPTOS: - p.ecn = protocol.ParseECNHeaderBits(body[0] & ecnMask) - case ipv4PKTINFO: - ip, ifIndex, ok := parseIPv4PktInfo(body) - if ok { - p.info.addr = ip - p.info.ifIndex = ifIndex - } else { - invalidCmsgOnceV4.Do(func() { - log.Printf("Received invalid IPv4 packet info control message: %+x. "+ - "This should never occur, please open a new issue and include details about the architecture.", body) - }) + p.ecn = protocol.ECN(body[0] & ecnMask) + case msgTypeIPv4PKTINFO: + // struct in_pktinfo { + // unsigned int ipi_ifindex; /* Interface index */ + // struct in_addr ipi_spec_dst; /* Local address */ + // struct in_addr ipi_addr; /* Header Destination + // address */ + // }; + var ip [4]byte + if len(body) == 12 { + copy(ip[:], body[8:12]) + p.info.ifIndex = binary.LittleEndian.Uint32(body) + } else if len(body) == 4 { + // FreeBSD + copy(ip[:], body) } + p.info.addr = netip.AddrFrom4(ip) } } if hdr.Level == unix.IPPROTO_IPV6 { switch hdr.Type { case unix.IPV6_TCLASS: - p.ecn = protocol.ParseECNHeaderBits(body[0] & ecnMask) - case unix.IPV6_PKTINFO: + p.ecn = protocol.ECN(body[0] & ecnMask) + case msgTypeIPv6PKTINFO: // struct in6_pktinfo { // struct in6_addr ipi6_addr; /* src/dst IPv6 address */ // unsigned int ipi6_ifindex; /* send/recv interface index */ // }; if len(body) == 20 { - p.info.addr = netip.AddrFrom16(*(*[16]byte)(body[:16])) + var ip [16]byte + copy(ip[:], body[:16]) + p.info.addr = netip.AddrFrom16(ip) p.info.ifIndex = binary.LittleEndian.Uint32(body[16:]) - } else { - invalidCmsgOnceV6.Do(func() { - log.Printf("Received invalid IPv6 packet info control message: %+x. "+ - "This should never occur, please open a new issue and include details about the architecture.", body) - }) } } } @@ -236,28 +228,25 @@ func (c *oobConn) ReadPacket() (receivedPacket, error) { return p, nil } +// WriteTo (re)implements the net.PacketConn method. +// This is needed for users who call OptimizeConn to be able to send (non-QUIC) packets on the underlying connection. +// With GSO enabled, this would otherwise not be needed, as the kernel requires the UDP_SEGMENT message to be set. +func (c *oobConn) WriteTo(p []byte, addr net.Addr) (int, error) { + return c.WritePacket(p, uint16(len(p)), addr, nil) +} + // WritePacket writes a new packet. -func (c *oobConn) WritePacket(b []byte, addr net.Addr, packetInfoOOB []byte, gsoSize uint16, ecn protocol.ECN) (int, error) { - oob := packetInfoOOB - if gsoSize > 0 { - if !c.capabilities().GSO { - panic("GSO disabled") - } - oob = appendUDPSegmentSizeMsg(oob, gsoSize) +// If the connection supports GSO (and we activated GSO support before), +// it appends the UDP_SEGMENT size message to oob. +// Callers are advised to make sure that oob has a sufficient capacity, +// such that appending the UDP_SEGMENT size message doesn't cause an allocation. +func (c *oobConn) WritePacket(b []byte, packetSize uint16, addr net.Addr, oob []byte) (n int, err error) { + if c.cap.GSO { + oob = appendUDPSegmentSizeMsg(oob, packetSize) + } else if uint16(len(b)) != packetSize { + panic(fmt.Sprintf("inconsistent length. got: %d. expected %d", packetSize, len(b))) } - if ecn != protocol.ECNUnsupported { - if !c.capabilities().ECN { - panic("tried to send a ECN-marked packet although ECN is disabled") - } - if remoteUDPAddr, ok := addr.(*net.UDPAddr); ok { - if remoteUDPAddr.IP.To4() != nil { - oob = appendIPv4ECNMsg(oob, ecn) - } else { - oob = appendIPv6ECNMsg(oob, ecn) - } - } - } - n, _, err := c.OOBCapablePacketConn.WriteMsgUDP(b, oob, addr.(*net.UDPAddr)) + n, _, err = c.OOBCapablePacketConn.WriteMsgUDP(b, oob, addr.(*net.UDPAddr)) return n, err } @@ -300,32 +289,3 @@ func (info *packetInfo) OOB() []byte { } return nil } - -func appendIPv4ECNMsg(b []byte, val protocol.ECN) []byte { - startLen := len(b) - b = append(b, make([]byte, unix.CmsgSpace(ecnIPv4DataLen))...) - h := (*unix.Cmsghdr)(unsafe.Pointer(&b[startLen])) - h.Level = syscall.IPPROTO_IP - h.Type = unix.IP_TOS - h.SetLen(unix.CmsgLen(ecnIPv4DataLen)) - - // UnixRights uses the private `data` method, but I *think* this achieves the same goal. - offset := startLen + unix.CmsgSpace(0) - b[offset] = val.ToHeaderBits() - return b -} - -func appendIPv6ECNMsg(b []byte, val protocol.ECN) []byte { - startLen := len(b) - const dataLen = 4 - b = append(b, make([]byte, unix.CmsgSpace(dataLen))...) - h := (*unix.Cmsghdr)(unsafe.Pointer(&b[startLen])) - h.Level = syscall.IPPROTO_IPV6 - h.Type = unix.IPV6_TCLASS - h.SetLen(unix.CmsgLen(dataLen)) - - // UnixRights uses the private `data` method, but I *think* this achieves the same goal. - offset := startLen + unix.CmsgSpace(0) - b[offset] = val.ToHeaderBits() - return b -} diff --git a/vendor/github.com/quic-go/quic-go/tools.go b/vendor/github.com/quic-go/quic-go/tools.go index d00ce748d..e848317f1 100644 --- a/vendor/github.com/quic-go/quic-go/tools.go +++ b/vendor/github.com/quic-go/quic-go/tools.go @@ -3,6 +3,6 @@ package quic import ( + _ "github.com/golang/mock/mockgen" _ "github.com/onsi/ginkgo/v2/ginkgo" - _ "go.uber.org/mock/mockgen" ) diff --git a/vendor/github.com/quic-go/quic-go/transport.go b/vendor/github.com/quic-go/quic-go/transport.go index 60d44a43e..57fdbfb4e 100644 --- a/vendor/github.com/quic-go/quic-go/transport.go +++ b/vendor/github.com/quic-go/quic-go/transport.go @@ -7,17 +7,15 @@ import ( "errors" "net" "sync" - "sync/atomic" "time" + "github.com/quic-go/quic-go/internal/wire" + "github.com/quic-go/quic-go/internal/protocol" "github.com/quic-go/quic-go/internal/utils" - "github.com/quic-go/quic-go/internal/wire" "github.com/quic-go/quic-go/logging" ) -var errListenerAlreadySet = errors.New("listener already set") - // The Transport is the central point to manage incoming and outgoing QUIC connections. // QUIC demultiplexes connections based on their QUIC Connection IDs, not based on the 4-tuple. // This means that a single UDP socket can be used for listening for incoming connections, as well as @@ -28,16 +26,9 @@ type Transport struct { // A single net.PacketConn can only be handled by one Transport. // Bad things will happen if passed to multiple Transports. // - // A number of optimizations will be enabled if the connections implements the OOBCapablePacketConn interface, - // as a *net.UDPConn does. - // 1. It enables the Don't Fragment (DF) bit on the IP header. - // This is required to run DPLPMTUD (Path MTU Discovery, RFC 8899). - // 2. It enables reading of the ECN bits from the IP header. - // This allows the remote node to speed up its loss detection and recovery. - // 3. It uses batched syscalls (recvmmsg) to more efficiently receive packets from the socket. - // 4. It uses Generic Segmentation Offload (GSO) to efficiently send batches of packets (on Linux). - // - // After passing the connection to the Transport, it's invalid to call ReadFrom or WriteTo on the connection. + // If not done by the user, the connection is passed through OptimizeConn to enable a number of optimizations. + // After passing the connection to the Transport, it's invalid to call ReadFrom on the connection. + // Calling WriteTo is only valid on the connection returned by OptimizeConn. Conn net.PacketConn // The length of the connection ID in bytes. @@ -59,26 +50,8 @@ type Transport struct { // See section 10.3 of RFC 9000 for details. StatelessResetKey *StatelessResetKey - // The TokenGeneratorKey is used to encrypt session resumption tokens. - // If no key is configured, a random key will be generated. - // If multiple servers are authoritative for the same domain, they should use the same key, - // see section 8.1.3 of RFC 9000 for details. - TokenGeneratorKey *TokenGeneratorKey - - // MaxTokenAge is the maximum age of the resumption token presented during the handshake. - // These tokens allow skipping address resumption when resuming a QUIC connection, - // and are especially useful when using 0-RTT. - // If not set, it defaults to 24 hours. - // See section 8.1.3 of RFC 9000 for details. - MaxTokenAge time.Duration - - // DisableVersionNegotiationPackets disables the sending of Version Negotiation packets. - // This can be useful if version information is exchanged out-of-band. - // It has no effect for clients. - DisableVersionNegotiationPackets bool - // A Tracer traces events that don't belong to a single QUIC connection. - Tracer *logging.Tracer + Tracer logging.Tracer handlerMap packetHandlerManager @@ -93,7 +66,7 @@ type Transport struct { // If no ConnectionIDGenerator is set, this is set to a default. connIDGenerator ConnectionIDGenerator - server *baseServer + server unknownPacketHandler conn rawConn @@ -105,9 +78,6 @@ type Transport struct { createdConn bool isSingleUse bool // was created for a single server or client, i.e. by calling quic.Listen or quic.Dial - readingNonQUICPackets atomic.Bool - nonQUICPackets chan receivedPacket - logger utils.Logger } @@ -115,25 +85,6 @@ type Transport struct { // There can only be a single listener on any net.PacketConn. // Listen may only be called again after the current Listener was closed. func (t *Transport) Listen(tlsConf *tls.Config, conf *Config) (*Listener, error) { - s, err := t.createServer(tlsConf, conf, false) - if err != nil { - return nil, err - } - return &Listener{baseServer: s}, nil -} - -// ListenEarly starts listening for incoming QUIC connections. -// There can only be a single listener on any net.PacketConn. -// Listen may only be called again after the current Listener was closed. -func (t *Transport) ListenEarly(tlsConf *tls.Config, conf *Config) (*EarlyListener, error) { - s, err := t.createServer(tlsConf, conf, true) - if err != nil { - return nil, err - } - return &EarlyListener{baseServer: s}, nil -} - -func (t *Transport) createServer(tlsConf *tls.Config, conf *Config, allow0RTT bool) (*baseServer, error) { if tlsConf == nil { return nil, errors.New("quic: tls.Config not set") } @@ -148,56 +99,82 @@ func (t *Transport) createServer(tlsConf *tls.Config, conf *Config, allow0RTT bo return nil, errListenerAlreadySet } conf = populateServerConfig(conf) - if err := t.init(false); err != nil { + if err := t.init(true); err != nil { + return nil, err + } + s, err := newServer(t.conn, t.handlerMap, t.connIDGenerator, tlsConf, conf, t.Tracer, t.closeServer, false) + if err != nil { return nil, err } - s := newServer( - t.conn, - t.handlerMap, - t.connIDGenerator, - tlsConf, - conf, - t.Tracer, - t.closeServer, - *t.TokenGeneratorKey, - t.MaxTokenAge, - t.DisableVersionNegotiationPackets, - allow0RTT, - ) t.server = s - return s, nil + return &Listener{baseServer: s}, nil +} + +// ListenEarly starts listening for incoming QUIC connections. +// There can only be a single listener on any net.PacketConn. +// Listen may only be called again after the current Listener was closed. +func (t *Transport) ListenEarly(tlsConf *tls.Config, conf *Config) (*EarlyListener, error) { + if tlsConf == nil { + return nil, errors.New("quic: tls.Config not set") + } + if err := validateConfig(conf); err != nil { + return nil, err + } + + t.mutex.Lock() + defer t.mutex.Unlock() + + if t.server != nil { + return nil, errListenerAlreadySet + } + conf = populateServerConfig(conf) + if err := t.init(true); err != nil { + return nil, err + } + s, err := newServer(t.conn, t.handlerMap, t.connIDGenerator, tlsConf, conf, t.Tracer, t.closeServer, true) + if err != nil { + return nil, err + } + t.server = s + return &EarlyListener{baseServer: s}, nil } // Dial dials a new connection to a remote host (not using 0-RTT). func (t *Transport) Dial(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (Connection, error) { - return t.dial(ctx, addr, "", tlsConf, conf, false) -} - -// DialEarly dials a new connection, attempting to use 0-RTT if possible. -func (t *Transport) DialEarly(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (EarlyConnection, error) { - return t.dial(ctx, addr, "", tlsConf, conf, true) -} - -func (t *Transport) dial(ctx context.Context, addr net.Addr, host string, tlsConf *tls.Config, conf *Config, use0RTT bool) (EarlyConnection, error) { if err := validateConfig(conf); err != nil { return nil, err } conf = populateConfig(conf) - if err := t.init(t.isSingleUse); err != nil { + if err := t.init(false); err != nil { return nil, err } var onClose func() if t.isSingleUse { onClose = func() { t.Close() } } - tlsConf = tlsConf.Clone() - tlsConf.MinVersion = tls.VersionTLS13 - setTLSConfigServerName(tlsConf, addr, host) - return dial(ctx, newSendConn(t.conn, addr, packetInfo{}, utils.DefaultLogger), t.connIDGenerator, t.handlerMap, tlsConf, conf, onClose, use0RTT) + return dial(ctx, newSendConn(t.conn, addr), t.connIDGenerator, t.handlerMap, tlsConf, conf, onClose, false) } -func (t *Transport) init(allowZeroLengthConnIDs bool) error { +// DialEarly dials a new connection, attempting to use 0-RTT if possible. +func (t *Transport) DialEarly(ctx context.Context, addr net.Addr, tlsConf *tls.Config, conf *Config) (EarlyConnection, error) { + if err := validateConfig(conf); err != nil { + return nil, err + } + conf = populateConfig(conf) + if err := t.init(false); err != nil { + return nil, err + } + var onClose func() + if t.isSingleUse { + onClose = func() { t.Close() } + } + return dial(ctx, newSendConn(t.conn, addr), t.connIDGenerator, t.handlerMap, tlsConf, conf, onClose, true) +} + +func (t *Transport) init(isServer bool) error { t.initOnce.Do(func() { + getMultiplexer().AddConn(t.Conn) + var conn rawConn if c, ok := t.Conn.(rawConn); ok { conn = c @@ -209,6 +186,7 @@ func (t *Transport) init(allowZeroLengthConnIDs bool) error { return } } + t.conn = conn t.logger = utils.DefaultLogger // TODO: make this configurable t.conn = conn @@ -217,42 +195,25 @@ func (t *Transport) init(allowZeroLengthConnIDs bool) error { t.closeQueue = make(chan closePacket, 4) t.statelessResetQueue = make(chan receivedPacket, 4) - if t.TokenGeneratorKey == nil { - var key TokenGeneratorKey - if _, err := rand.Read(key[:]); err != nil { - t.initErr = err - return - } - t.TokenGeneratorKey = &key - } if t.ConnectionIDGenerator != nil { t.connIDGenerator = t.ConnectionIDGenerator t.connIDLen = t.ConnectionIDGenerator.ConnectionIDLen() } else { connIDLen := t.ConnectionIDLength - if t.ConnectionIDLength == 0 && !allowZeroLengthConnIDs { + if t.ConnectionIDLength == 0 && (!t.isSingleUse || isServer) { connIDLen = protocol.DefaultConnectionIDLength } t.connIDLen = connIDLen t.connIDGenerator = &protocol.DefaultConnectionIDGenerator{ConnLen: t.connIDLen} } - getMultiplexer().AddConn(t.Conn) go t.listen(conn) go t.runSendQueue() }) return t.initErr } -// WriteTo sends a packet on the underlying connection. -func (t *Transport) WriteTo(b []byte, addr net.Addr) (int, error) { - if err := t.init(false); err != nil { - return 0, err - } - return t.conn.WritePacket(b, addr, nil, 0, protocol.ECNUnsupported) -} - func (t *Transport) enqueueClosePacket(p closePacket) { select { case t.closeQueue <- p: @@ -268,7 +229,7 @@ func (t *Transport) runSendQueue() { case <-t.listening: return case p := <-t.closeQueue: - t.conn.WritePacket(p.payload, p.addr, p.info.OOB(), 0, protocol.ECNUnsupported) + t.conn.WritePacket(p.payload, uint16(len(p.payload)), p.addr, p.info.OOB()) case p := <-t.statelessResetQueue: t.sendStatelessReset(p) } @@ -351,10 +312,6 @@ func (t *Transport) listen(conn rawConn) { continue } if err != nil { - // Windows returns an error when receiving a UDP datagram that doesn't fit into the provided buffer. - if isRecvMsgSizeErr(err) { - continue - } t.close(err) return } @@ -363,17 +320,10 @@ func (t *Transport) listen(conn rawConn) { } func (t *Transport) handlePacket(p receivedPacket) { - if len(p.data) == 0 { - return - } - if !wire.IsPotentialQUICPacket(p.data[0]) && !wire.IsLongHeaderPacket(p.data[0]) { - t.handleNonQUICPacket(p) - return - } connID, err := wire.ParseConnectionID(p.data, t.connIDLen) if err != nil { t.logger.Debugf("error parsing connection ID on packet from %s: %s", p.remoteAddr, err) - if t.Tracer != nil && t.Tracer.DroppedPacket != nil { + if t.Tracer != nil { t.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropHeaderParseError) } p.buffer.MaybeRelease() @@ -436,7 +386,7 @@ func (t *Transport) sendStatelessReset(p receivedPacket) { rand.Read(data) data[0] = (data[0] & 0x7f) | 0x40 data = append(data, token[:]...) - if _, err := t.conn.WritePacket(data, p.remoteAddr, p.info.OOB(), 0, protocol.ECNUnsupported); err != nil { + if _, err := t.conn.WritePacket(data, uint16(len(data)), p.remoteAddr, p.info.OOB()); err != nil { t.logger.Debugf("Error sending Stateless Reset to %s: %s", p.remoteAddr, err) } } @@ -458,61 +408,3 @@ func (t *Transport) maybeHandleStatelessReset(data []byte) bool { } return false } - -func (t *Transport) handleNonQUICPacket(p receivedPacket) { - // Strictly speaking, this is racy, - // but we only care about receiving packets at some point after ReadNonQUICPacket has been called. - if !t.readingNonQUICPackets.Load() { - return - } - select { - case t.nonQUICPackets <- p: - default: - if t.Tracer != nil && t.Tracer.DroppedPacket != nil { - t.Tracer.DroppedPacket(p.remoteAddr, logging.PacketTypeNotDetermined, p.Size(), logging.PacketDropDOSPrevention) - } - } -} - -const maxQueuedNonQUICPackets = 32 - -// ReadNonQUICPacket reads non-QUIC packets received on the underlying connection. -// The detection logic is very simple: Any packet that has the first and second bit of the packet set to 0. -// Note that this is stricter than the detection logic defined in RFC 9443. -func (t *Transport) ReadNonQUICPacket(ctx context.Context, b []byte) (int, net.Addr, error) { - if err := t.init(false); err != nil { - return 0, nil, err - } - if !t.readingNonQUICPackets.Load() { - t.nonQUICPackets = make(chan receivedPacket, maxQueuedNonQUICPackets) - t.readingNonQUICPackets.Store(true) - } - select { - case <-ctx.Done(): - return 0, nil, ctx.Err() - case p := <-t.nonQUICPackets: - n := copy(b, p.data) - return n, p.remoteAddr, nil - case <-t.listening: - return 0, nil, errors.New("closed") - } -} - -func setTLSConfigServerName(tlsConf *tls.Config, addr net.Addr, host string) { - // If no ServerName is set, infer the ServerName from the host we're connecting to. - if tlsConf.ServerName != "" { - return - } - if host == "" { - if udpAddr, ok := addr.(*net.UDPAddr); ok { - tlsConf.ServerName = udpAddr.IP.String() - return - } - } - h, _, err := net.SplitHostPort(host) - if err != nil { // This happens if the host doesn't contain a port number. - tlsConf.ServerName = host - return - } - tlsConf.ServerName = h -} diff --git a/vendor/github.com/quic-go/webtransport-go/client.go b/vendor/github.com/quic-go/webtransport-go/client.go index 8efe4d75a..ffcb7497d 100644 --- a/vendor/github.com/quic-go/webtransport-go/client.go +++ b/vendor/github.com/quic-go/webtransport-go/client.go @@ -92,7 +92,7 @@ func (d *Dialer) Dial(ctx context.Context, urlStr string, reqHdr http.Header) (* if reqHdr == nil { reqHdr = http.Header{} } - reqHdr.Set(webTransportDraftOfferHeaderKey, "1") + reqHdr.Add(webTransportDraftOfferHeaderKey, "1") req := &http.Request{ Method: http.MethodConnect, Header: reqHdr, diff --git a/vendor/github.com/quic-go/webtransport-go/errors.go b/vendor/github.com/quic-go/webtransport-go/errors.go index 108627f6a..9929513e4 100644 --- a/vendor/github.com/quic-go/webtransport-go/errors.go +++ b/vendor/github.com/quic-go/webtransport-go/errors.go @@ -8,14 +8,14 @@ import ( ) // StreamErrorCode is an error code used for stream termination. -type StreamErrorCode uint32 +type StreamErrorCode uint8 // SessionErrorCode is an error code for session termination. type SessionErrorCode uint32 const ( firstErrorCode = 0x52e4a40fa8db - lastErrorCode = 0x52e5ac983162 + lastErrorCode = 0x52e4a40fa9e2 ) func webtransportCodeToHTTPCode(n StreamErrorCode) quic.StreamErrorCode { diff --git a/vendor/github.com/quic-go/webtransport-go/version.json b/vendor/github.com/quic-go/webtransport-go/version.json index 42c14d1be..ef97c9ca1 100644 --- a/vendor/github.com/quic-go/webtransport-go/version.json +++ b/vendor/github.com/quic-go/webtransport-go/version.json @@ -1,3 +1,3 @@ { - "version": "v0.6.0" + "version": "v0.5.3" } diff --git a/vendor/github.com/status-im/rendezvous/server/server.go b/vendor/github.com/status-im/rendezvous/server/server.go index f6559c46e..ef452e5f4 100644 --- a/vendor/github.com/status-im/rendezvous/server/server.go +++ b/vendor/github.com/status-im/rendezvous/server/server.go @@ -154,7 +154,7 @@ func (srv *Server) startListener() error { } } }) - addr, err := ma.NewMultiaddr(fmt.Sprintf("/ethv4/%s", h.ID())) + addr, err := ma.NewMultiaddr(fmt.Sprintf("/ethv4/%s", h.ID().Pretty())) if err != nil { return err } diff --git a/vendor/github.com/waku-org/go-libp2p-rendezvous/svc.go b/vendor/github.com/waku-org/go-libp2p-rendezvous/svc.go index 64a5eed64..f2dfa9457 100644 --- a/vendor/github.com/waku-org/go-libp2p-rendezvous/svc.go +++ b/vendor/github.com/waku-org/go-libp2p-rendezvous/svc.go @@ -32,7 +32,7 @@ func (rz *RendezvousService) handleStream(s inet.Stream) { defer s.Reset() pid := s.Conn().RemotePeer() - log.Debugf("New stream from %s", pid.String()) + log.Debugf("New stream from %s", pid.Pretty()) r := pbio.NewDelimitedReader(s, inet.MessageSizeMax) w := pbio.NewDelimitedWriter(s) diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/node/wakunode2.go b/vendor/github.com/waku-org/go-waku/waku/v2/node/wakunode2.go index 378ac06b4..578d4cdd9 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/node/wakunode2.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/node/wakunode2.go @@ -11,7 +11,6 @@ import ( golog "github.com/ipfs/go-log/v2" "github.com/libp2p/go-libp2p" "go.uber.org/zap" - "golang.org/x/exp/maps" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/p2p/enode" @@ -200,7 +199,7 @@ func New(opts ...WakuNodeOption) (*WakuNode, error) { w.log = params.logger.Named("node2") w.wg = &sync.WaitGroup{} w.keepAliveFails = make(map[peer.ID]int) - w.wakuFlag = enr.NewWakuEnrBitfield(w.opts.enableLightPush, w.opts.enableFilterFullNode || w.opts.enableLegacyFilter, w.opts.enableStore, w.opts.enableRelay) + w.wakuFlag = enr.NewWakuEnrBitfield(w.opts.enableLightPush, w.opts.enableLegacyFilter, w.opts.enableStore, w.opts.enableRelay) w.circuitRelayNodes = make(chan peer.AddrInfo) w.metrics = newMetrics(params.prometheusReg) @@ -325,13 +324,13 @@ func (w *WakuNode) watchMultiaddressChanges(ctx context.Context) { case <-ctx.Done(): return case <-first: - addr := maps.Keys(addrsSet) + addr := utils.MultiAddrFromSet(addrsSet) w.log.Info("listening", logging.MultiAddrs("multiaddr", addr...)) case <-w.addressChangesSub.Out(): newAddrs := utils.MultiAddrSet(w.ListenAddresses()...) - if !maps.Equal(addrsSet, newAddrs) { + if !utils.MultiAddrSetEquals(addrsSet, newAddrs) { addrsSet = newAddrs - addrs := maps.Keys(addrsSet) + addrs := utils.MultiAddrFromSet(addrsSet) w.log.Info("listening addresses update received", logging.MultiAddrs("multiaddr", addrs...)) err := w.setupENR(ctx, addrs) if err != nil { @@ -344,7 +343,7 @@ func (w *WakuNode) watchMultiaddressChanges(ctx context.Context) { // Start initializes all the protocols that were setup in the WakuNode func (w *WakuNode) Start(ctx context.Context) error { - connGater := peermanager.NewConnectionGater(w.opts.maxConnectionsPerIP, w.log) + connGater := peermanager.NewConnectionGater(w.log) ctx, cancel := context.WithCancel(ctx) w.cancel = cancel @@ -562,7 +561,7 @@ func (w *WakuNode) Host() host.Host { // ID returns the base58 encoded ID from the host func (w *WakuNode) ID() string { - return w.host.ID().String() + return w.host.ID().Pretty() } func (w *WakuNode) watchENRChanges(ctx context.Context) { diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/node/wakuoptions.go b/vendor/github.com/waku-org/go-waku/waku/v2/node/wakuoptions.go index fcfb02d33..dd6d9958e 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/node/wakuoptions.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/node/wakuoptions.go @@ -12,12 +12,12 @@ import ( "github.com/ethereum/go-ethereum/p2p/enode" logging "github.com/ipfs/go-log/v2" "github.com/libp2p/go-libp2p" - mplex "github.com/libp2p/go-libp2p-mplex" pubsub "github.com/libp2p/go-libp2p-pubsub" "github.com/libp2p/go-libp2p/config" "github.com/libp2p/go-libp2p/core/crypto" "github.com/libp2p/go-libp2p/core/peerstore" basichost "github.com/libp2p/go-libp2p/p2p/host/basic" + "github.com/libp2p/go-libp2p/p2p/muxer/mplex" "github.com/libp2p/go-libp2p/p2p/muxer/yamux" "github.com/libp2p/go-libp2p/p2p/net/connmgr" quic "github.com/libp2p/go-libp2p/p2p/transport/quic" @@ -37,26 +37,23 @@ import ( "go.uber.org/zap/zapcore" ) -// Default UserAgent -const UserAgent string = "go-waku" +// Default userAgent +const userAgent string = "go-waku" // Default minRelayPeersToPublish const defaultMinRelayPeersToPublish = 0 -const DefaultMaxConnectionsPerIP = 5 - type WakuNodeParameters struct { - hostAddr *net.TCPAddr - maxConnectionsPerIP int - clusterID uint16 - dns4Domain string - advertiseAddrs []multiaddr.Multiaddr - multiAddr []multiaddr.Multiaddr - addressFactory basichost.AddrsFactory - privKey *ecdsa.PrivateKey - libP2POpts []libp2p.Option - peerstore peerstore.Peerstore - prometheusReg prometheus.Registerer + hostAddr *net.TCPAddr + clusterID uint16 + dns4Domain string + advertiseAddrs []multiaddr.Multiaddr + multiAddr []multiaddr.Multiaddr + addressFactory basichost.AddrsFactory + privKey *ecdsa.PrivateKey + libP2POpts []libp2p.Option + peerstore peerstore.Peerstore + prometheusReg prometheus.Registerer circuitRelayMinInterval time.Duration circuitRelayBootDelay time.Duration @@ -127,7 +124,6 @@ type WakuNodeOption func(*WakuNodeParameters) error var DefaultWakuNodeOptions = []WakuNodeOption{ WithPrometheusRegisterer(prometheus.NewRegistry()), WithMaxPeerConnections(50), - WithMaxConnectionsPerIP(DefaultMaxConnectionsPerIP), WithCircuitRelayParams(2*time.Second, 3*time.Minute), } @@ -308,14 +304,6 @@ func WithClusterID(clusterID uint16) WakuNodeOption { } } -// WithMaxConnectionsPerIP sets the max number of allowed peers from the same IP -func WithMaxConnectionsPerIP(limit int) WakuNodeOption { - return func(params *WakuNodeParameters) error { - params.maxConnectionsPerIP = limit - return nil - } -} - // WithNTP is used to use ntp for any operation that requires obtaining time // A list of ntp servers can be passed but if none is specified, some defaults // will be used @@ -572,7 +560,7 @@ var DefaultLibP2POptions = []libp2p.Option{ libp2p.Transport(quic.NewTransport), libp2p.Transport(libp2pwebtransport.New), ), - libp2p.UserAgent(UserAgent), + libp2p.UserAgent(userAgent), libp2p.ChainOptions( libp2p.Muxer("/yamux/1.0.0", yamux.DefaultTransport), libp2p.Muxer("/mplex/6.7.0", mplex.DefaultTransport), diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/peermanager/connection_gater.go b/vendor/github.com/waku-org/go-waku/waku/v2/peermanager/connection_gater.go index d08008139..5b9b761bd 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/peermanager/connection_gater.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/peermanager/connection_gater.go @@ -16,20 +16,18 @@ import ( // the number of connections per IP address type ConnectionGater struct { sync.Mutex - logger *zap.Logger - limiter map[string]int - maxConnsPerIP int + logger *zap.Logger + limiter map[string]int } -// NewConnectionGater creates a new instance of ConnectionGater -func NewConnectionGater(maxConnsPerIP int, logger *zap.Logger) *ConnectionGater { - c := &ConnectionGater{ - logger: logger.Named("connection-gater"), - maxConnsPerIP: maxConnsPerIP, - limiter: make(map[string]int), - } +const maxConnsPerIP = 10 - c.logger.Info("configured settings", zap.Int("maxConnsPerIP", maxConnsPerIP)) +// NewConnectionGater creates a new instance of ConnectionGater +func NewConnectionGater(logger *zap.Logger) *ConnectionGater { + c := &ConnectionGater{ + logger: logger.Named("connection-gater"), + limiter: make(map[string]int), + } return c } @@ -105,7 +103,7 @@ func (c *ConnectionGater) validateInboundConn(addr multiaddr.Multiaddr) bool { c.Lock() defer c.Unlock() - if currConnections := c.limiter[ip.String()]; c.maxConnsPerIP > 0 && currConnections+1 > c.maxConnsPerIP { + if currConnections := c.limiter[ip.String()]; currConnections+1 > maxConnsPerIP { return false } diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/enr/enr.go b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/enr/enr.go index b5b7bbd90..7f8d9e56a 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/enr/enr.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/enr/enr.go @@ -113,7 +113,7 @@ func Multiaddress(node *enode.Node) (peer.ID, []multiaddr.Multiaddr, error) { return "", nil, fmt.Errorf("invalid multiaddress field length") } - hostInfoStr := fmt.Sprintf("/p2p/%s", peerID.String()) + hostInfoStr := fmt.Sprintf("/p2p/%s", peerID.Pretty()) _, pID := peer.SplitAddr(addr) if pID != "" && pID != peerID { // Addresses in the ENR that contain a p2p component are circuit relay addr diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/filter/client.go b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/filter/client.go index 6916590d8..b6fc3092f 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/filter/client.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/filter/client.go @@ -475,7 +475,7 @@ func (wf *WakuFilterLightNode) Unsubscribe(ctx context.Context, contentFilter pr return nil, errors.New("at least one content topic is required") } - if slices.Contains(contentFilter.ContentTopicsList(), "") { + if slices.Contains[string](contentFilter.ContentTopicsList(), "") { return nil, errors.New("one or more content topics specified is empty") } diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/filter/pb/validation.go b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/filter/pb/validation.go index ba761f915..2e0d450dd 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/filter/pb/validation.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/filter/pb/validation.go @@ -7,7 +7,7 @@ import ( "golang.org/x/exp/slices" ) -const MaxContentTopicsPerRequest = 100 +const MaxContentTopicsPerRequest = 30 var ( errMissingRequestID = errors.New("missing RequestId field") @@ -32,7 +32,7 @@ func (x *FilterSubscribeRequest) Validate() error { return errNoContentTopics } - if slices.Contains(x.ContentTopics, "") { + if slices.Contains[string](x.ContentTopics, "") { return errEmptyContentTopics } diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/relay/subscription.go b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/relay/subscription.go index fc1df406e..a7bb6a362 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/relay/subscription.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/relay/subscription.go @@ -30,7 +30,7 @@ func (s *Subscription) Submit(ctx context.Context, msg *protocol.Envelope) { // - if contentFilter doesn't have a contentTopic // - if contentFilter has contentTopics and it matches with message if !s.noConsume && (len(s.contentFilter.ContentTopicsList()) == 0 || - (len(s.contentFilter.ContentTopicsList()) > 0 && slices.Contains(s.contentFilter.ContentTopicsList(), msg.Message().ContentTopic))) { + (len(s.contentFilter.ContentTopicsList()) > 0 && slices.Contains[string](s.contentFilter.ContentTopicsList(), msg.Message().ContentTopic))) { select { case <-ctx.Done(): return diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/rln/waku_rln_relay.go b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/rln/waku_rln_relay.go index 39b718061..ad7bc368c 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/rln/waku_rln_relay.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/rln/waku_rln_relay.go @@ -108,9 +108,8 @@ func (rlnRelay *WakuRLNRelay) ValidateMessage(msg *pb.WakuMessage, optionalTime msgProof, err := BytesToRateLimitProof(msg.RateLimitProof) if err != nil { - rlnRelay.log.Debug("invalid message: could not extract proof") + rlnRelay.log.Debug("invalid message: could not extract proof", zap.Error(err)) rlnRelay.metrics.RecordInvalidMessage(proofExtractionErr) - return validationError, err } if msgProof == nil { @@ -147,9 +146,9 @@ func (rlnRelay *WakuRLNRelay) ValidateMessage(msg *pb.WakuMessage, optionalTime start := time.Now() valid, err := rlnRelay.verifyProof(msg, msgProof) if err != nil { - rlnRelay.log.Debug("could not verify proof") + rlnRelay.log.Debug("could not verify proof", zap.Error(err)) rlnRelay.metrics.RecordError(proofVerificationErr) - return validationError, err + return invalidMessage, nil } rlnRelay.metrics.RecordProofVerification(time.Since(start)) @@ -271,7 +270,7 @@ func (rlnRelay *WakuRLNRelay) Validator( return false default: - log.Error("unhandled validation result", zap.Int("validationResult", int(validationRes))) + log.Debug("unhandled validation result", zap.Int("validationResult", int(validationRes))) return false } } diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/rendezvous/db.go b/vendor/github.com/waku-org/go-waku/waku/v2/rendezvous/db.go index 1d751fede..883c1f0c5 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/rendezvous/db.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/rendezvous/db.go @@ -165,7 +165,7 @@ func (db *DB) prepareStmts() error { } func (db *DB) Register(p peer.ID, ns string, signedPeerRecord []byte, ttl int) (uint64, error) { - pid := p.String() + pid := p.Pretty() expire := time.Now().Unix() + int64(ttl) tx, err := db.db.Begin() @@ -202,7 +202,7 @@ func (db *DB) Register(p peer.ID, ns string, signedPeerRecord []byte, ttl int) ( } func (db *DB) CountRegistrations(p peer.ID) (int, error) { - pid := p.String() + pid := p.Pretty() row := db.countPeerRegistrations.QueryRow(pid) @@ -213,7 +213,7 @@ func (db *DB) CountRegistrations(p peer.ID) (int, error) { } func (db *DB) Unregister(p peer.ID, ns string) error { - pid := p.String() + pid := p.Pretty() var err error diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/utils/multiaddr.go b/vendor/github.com/waku-org/go-waku/waku/v2/utils/multiaddr.go index b60d4a879..537403440 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/utils/multiaddr.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/utils/multiaddr.go @@ -9,7 +9,7 @@ import ( // EncapsulatePeerID takes a peer.ID and adds a p2p component to all multiaddresses it receives func EncapsulatePeerID(peerID peer.ID, addrs ...multiaddr.Multiaddr) []multiaddr.Multiaddr { - hostInfo, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/p2p/%s", peerID.String())) + hostInfo, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/p2p/%s", peerID.Pretty())) var result []multiaddr.Multiaddr for _, addr := range addrs { result = append(result, addr.Encapsulate(hostInfo)) @@ -24,3 +24,26 @@ func MultiAddrSet(addr ...multiaddr.Multiaddr) map[multiaddr.Multiaddr]struct{} } return r } + +func MultiAddrSetEquals(m1 map[multiaddr.Multiaddr]struct{}, m2 map[multiaddr.Multiaddr]struct{}) bool { + if len(m1) != len(m2) { + return false + } + + for k := range m1 { + _, ok := m2[k] + if !ok { + return false + } + } + + return true +} + +func MultiAddrFromSet(m map[multiaddr.Multiaddr]struct{}) []multiaddr.Multiaddr { + var r []multiaddr.Multiaddr + for k := range m { + r = append(r, k) + } + return r +} diff --git a/vendor/go.uber.org/dig/CHANGELOG.md b/vendor/go.uber.org/dig/CHANGELOG.md index f191bc5ae..2989c1bba 100644 --- a/vendor/go.uber.org/dig/CHANGELOG.md +++ b/vendor/go.uber.org/dig/CHANGELOG.md @@ -4,28 +4,13 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). -## [1.17.1] - 2023-10-19 -### Added -- Suggestions for value vs. pointer elements for slice and array types. - -### Fixed -- An issue where value group values were not getting decorated - by decorators within the same module when using dig.Export(true). -- A typo in docs. -- An issue where false positives in cycle detection were occurring - when providing to a child scope. - -Thanks to @paullen and @lcarilla for their contributions to this release. - -[1.17.1]: https://github.com/uber-go/dig/compare/v1.17.0...v1.17.1 - ## [1.17.0] - 2023-05-02 ### Added - Allow using `dig.As` with `dig.Group`. - Add `FillInvokeInfo` Option and `InvokeInfo` struct to help extract the types requested by an `Invoke` statement. - To get visibility into constructor and decorator calls, introduce - `WithProviderCallback` and `WithDecoratorCallback` Options to provide callback functions. + `WithCallback` Option to provide callback functions. [1.17.0]: https://github.com/uber-go/dig/compare/v1.16.1...v1.17.0 diff --git a/vendor/go.uber.org/dig/constructor.go b/vendor/go.uber.org/dig/constructor.go index 034c41c22..208659d98 100644 --- a/vendor/go.uber.org/dig/constructor.go +++ b/vendor/go.uber.org/dig/constructor.go @@ -129,11 +129,6 @@ func (n *constructorNode) CType() reflect.Type { return n.ctype } func (n *constructorNode) Order(s *Scope) int { return n.orders[s] } func (n *constructorNode) OrigScope() *Scope { return n.origS } -// CopyOrder copies the order for the given parent scope to the given child scope. -func (n *constructorNode) CopyOrder(parent, child *Scope) { - n.orders[child] = n.orders[parent] -} - func (n *constructorNode) String() string { return fmt.Sprintf("deps: %v, ctor: %v", n.paramList, n.ctype) } diff --git a/vendor/go.uber.org/dig/doc.go b/vendor/go.uber.org/dig/doc.go index 77b01d045..3f9ab85c1 100644 --- a/vendor/go.uber.org/dig/doc.go +++ b/vendor/go.uber.org/dig/doc.go @@ -207,7 +207,7 @@ // // func NewUserGateway(p UserGatewayParams, log *log.Logger) (*UserGateway, error) { // if p.Cache == nil { -// log.Print("Caching disabled") +// log.Print("Logging disabled") // } // // ... // } diff --git a/vendor/go.uber.org/dig/error.go b/vendor/go.uber.org/dig/error.go index 8aba9ee5a..24c5685be 100644 --- a/vendor/go.uber.org/dig/error.go +++ b/vendor/go.uber.org/dig/error.go @@ -414,28 +414,6 @@ func newErrMissingTypes(c containerStore, k key) errMissingTypes { suggestions = append(suggestions, k.t.Elem()) } - if k.t.Kind() == reflect.Slice { - // Maybe the user meant a slice of pointers while we have the slice of elements - suggestions = append(suggestions, reflect.SliceOf(reflect.PtrTo(k.t.Elem()))) - - // Maybe the user meant a slice of elements while we have the slice of pointers - sliceElement := k.t.Elem() - if sliceElement.Kind() == reflect.Ptr { - suggestions = append(suggestions, reflect.SliceOf(sliceElement.Elem())) - } - } - - if k.t.Kind() == reflect.Array { - // Maybe the user meant an array of pointers while we have the array of elements - suggestions = append(suggestions, reflect.ArrayOf(k.t.Len(), reflect.PtrTo(k.t.Elem()))) - - // Maybe the user meant an array of elements while we have the array of pointers - arrayElement := k.t.Elem() - if arrayElement.Kind() == reflect.Ptr { - suggestions = append(suggestions, reflect.ArrayOf(k.t.Len(), arrayElement.Elem())) - } - } - knownTypes := c.knownTypes() if k.t.Kind() == reflect.Interface { // Maybe we have an implementation of the interface. diff --git a/vendor/go.uber.org/dig/param.go b/vendor/go.uber.org/dig/param.go index ca0689759..d584fc237 100644 --- a/vendor/go.uber.org/dig/param.go +++ b/vendor/go.uber.org/dig/param.go @@ -606,7 +606,7 @@ func (pt paramGroupedSlice) callGroupProviders(c containerStore) (int, error) { providers := c.getGroupProviders(pt.Group, pt.Type.Elem()) itemCount += len(providers) for _, n := range providers { - if err := n.Call(n.OrigScope()); err != nil { + if err := n.Call(c); err != nil { return 0, errParamGroupFailed{ CtorID: n.ID(), Key: key{group: pt.Group, t: pt.Type.Elem()}, diff --git a/vendor/go.uber.org/dig/scope.go b/vendor/go.uber.org/dig/scope.go index dc0c7ac5b..216cf18a1 100644 --- a/vendor/go.uber.org/dig/scope.go +++ b/vendor/go.uber.org/dig/scope.go @@ -121,12 +121,7 @@ func (s *Scope) Scope(name string, opts ...ScopeOption) *Scope { child.recoverFromPanics = s.recoverFromPanics // child copies the parent's graph nodes. - for _, node := range s.gh.nodes { - child.gh.nodes = append(child.gh.nodes, node) - if ctrNode, ok := node.Wrapped.(*constructorNode); ok { - ctrNode.CopyOrder(s, child) - } - } + child.gh.nodes = append(child.gh.nodes, s.gh.nodes...) for _, opt := range opts { opt.noScopeOption() diff --git a/vendor/go.uber.org/dig/version.go b/vendor/go.uber.org/dig/version.go index 7c92d4ab0..0b55dc929 100644 --- a/vendor/go.uber.org/dig/version.go +++ b/vendor/go.uber.org/dig/version.go @@ -21,4 +21,4 @@ package dig // Version of the library. -const Version = "1.17.1" +const Version = "1.17.0" diff --git a/vendor/go.uber.org/fx/CHANGELOG.md b/vendor/go.uber.org/fx/CHANGELOG.md index 7c43848c4..e3a746f22 100644 --- a/vendor/go.uber.org/fx/CHANGELOG.md +++ b/vendor/go.uber.org/fx/CHANGELOG.md @@ -10,13 +10,6 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [1.20.1](https://github.com/uber-go/fx/compare/v1.20.0...v1.20.1) - 2023-10-17 - -### Added -- Provided, Decorated, Supplied, and Replaced events now include a trace - of module locations through which the option was given to the App. -- wasi support. - ## [1.20.0](https://github.com/uber-go/fx/compare/v1.19.3...v1.20.0) - 2023-06-12 ### Added diff --git a/vendor/go.uber.org/fx/app.go b/vendor/go.uber.org/fx/app.go index e07bd5bdc..d524a5e98 100644 --- a/vendor/go.uber.org/fx/app.go +++ b/vendor/go.uber.org/fx/app.go @@ -432,8 +432,7 @@ func New(opts ...Option) *App { // user gave us. For the last case, however, we need to fall // back to what was provided to fx.Logger if fx.WithLogger // fails. - log: logger, - trace: []string{fxreflect.CallerStack(1, 2)[0].String()}, + log: logger, } app.modules = append(app.modules, app.root) diff --git a/vendor/go.uber.org/fx/app_wasm.go b/vendor/go.uber.org/fx/app_wasm.go index 5e2ca8d01..2468fed7e 100644 --- a/vendor/go.uber.org/fx/app_wasm.go +++ b/vendor/go.uber.org/fx/app_wasm.go @@ -18,8 +18,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -//go:build (js && wasm) || (wasip1 && wasm) -// +build js,wasm wasip1,wasm +//go:build js && wasm +// +build js,wasm package fx diff --git a/vendor/go.uber.org/fx/fxevent/event.go b/vendor/go.uber.org/fx/fxevent/event.go index 7babcd4a0..c87f9a303 100644 --- a/vendor/go.uber.org/fx/fxevent/event.go +++ b/vendor/go.uber.org/fx/fxevent/event.go @@ -113,9 +113,6 @@ type Supplied struct { // StackTrace is the stack trace of the call to Supply. StackTrace []string - // ModuleTrace contains the module locations through which this value was added. - ModuleTrace []string - // ModuleName is the name of the module in which the value was added to. ModuleName string @@ -132,9 +129,6 @@ type Provided struct { // StackTrace is the stack trace of where the constructor was provided to Fx. StackTrace []string - // ModuleTrace contains the module locations through which this was provided to Fx. - ModuleTrace []string - // OutputTypeNames is a list of names of types that are produced by // this constructor. OutputTypeNames []string @@ -158,9 +152,6 @@ type Replaced struct { // StackTrace is the stack trace of the call to Replace. StackTrace []string - // ModuleTrace contains the module locations through which this value was added. - ModuleTrace []string - // ModuleName is the name of the module in which the value was added to. ModuleName string @@ -177,9 +168,6 @@ type Decorated struct { // StackTrace is the stack trace of where the decorator was given to Fx. StackTrace []string - // ModuleTrace contains the module locations through which this value was added. - ModuleTrace []string - // ModuleName is the name of the module in which the value was added to. ModuleName string diff --git a/vendor/go.uber.org/fx/fxevent/zap.go b/vendor/go.uber.org/fx/fxevent/zap.go index 613eb8653..c304ea058 100644 --- a/vendor/go.uber.org/fx/fxevent/zap.go +++ b/vendor/go.uber.org/fx/fxevent/zap.go @@ -105,14 +105,12 @@ func (l *ZapLogger) LogEvent(event Event) { l.logError("error encountered while applying options", zap.String("type", e.TypeName), zap.Strings("stacktrace", e.StackTrace), - zap.Strings("moduletrace", e.ModuleTrace), moduleField(e.ModuleName), zap.Error(e.Err)) } else { l.logEvent("supplied", zap.String("type", e.TypeName), zap.Strings("stacktrace", e.StackTrace), - zap.Strings("moduletrace", e.ModuleTrace), moduleField(e.ModuleName), ) } @@ -121,7 +119,6 @@ func (l *ZapLogger) LogEvent(event Event) { l.logEvent("provided", zap.String("constructor", e.ConstructorName), zap.Strings("stacktrace", e.StackTrace), - zap.Strings("moduletrace", e.ModuleTrace), moduleField(e.ModuleName), zap.String("type", rtype), maybeBool("private", e.Private), @@ -131,14 +128,12 @@ func (l *ZapLogger) LogEvent(event Event) { l.logError("error encountered while applying options", moduleField(e.ModuleName), zap.Strings("stacktrace", e.StackTrace), - zap.Strings("moduletrace", e.ModuleTrace), zap.Error(e.Err)) } case *Replaced: for _, rtype := range e.OutputTypeNames { l.logEvent("replaced", zap.Strings("stacktrace", e.StackTrace), - zap.Strings("moduletrace", e.ModuleTrace), moduleField(e.ModuleName), zap.String("type", rtype), ) @@ -146,7 +141,6 @@ func (l *ZapLogger) LogEvent(event Event) { if e.Err != nil { l.logError("error encountered while replacing", zap.Strings("stacktrace", e.StackTrace), - zap.Strings("moduletrace", e.ModuleTrace), moduleField(e.ModuleName), zap.Error(e.Err)) } @@ -155,7 +149,6 @@ func (l *ZapLogger) LogEvent(event Event) { l.logEvent("decorated", zap.String("decorator", e.DecoratorName), zap.Strings("stacktrace", e.StackTrace), - zap.Strings("moduletrace", e.ModuleTrace), moduleField(e.ModuleName), zap.String("type", rtype), ) @@ -163,7 +156,6 @@ func (l *ZapLogger) LogEvent(event Event) { if e.Err != nil { l.logError("error encountered while applying options", zap.Strings("stacktrace", e.StackTrace), - zap.Strings("moduletrace", e.ModuleTrace), moduleField(e.ModuleName), zap.Error(e.Err)) } diff --git a/vendor/go.uber.org/fx/module.go b/vendor/go.uber.org/fx/module.go index bb4f74484..d678c4dc6 100644 --- a/vendor/go.uber.org/fx/module.go +++ b/vendor/go.uber.org/fx/module.go @@ -45,17 +45,15 @@ type container interface { // place. For more information, see [Decorate], [Replace], or [Invoke]. func Module(name string, opts ...Option) Option { mo := moduleOption{ - name: name, - location: fxreflect.CallerStack(1, 2)[0], - options: opts, + name: name, + options: opts, } return mo } type moduleOption struct { - name string - location fxreflect.Frame - options []Option + name string + options []Option } func (o moduleOption) String() string { @@ -70,13 +68,9 @@ func (o moduleOption) apply(mod *module) { // module. // 2. Apply child Options on the new module. // 3. Append it to the parent module. - - // Create trace as parent's trace with this module's location pre-pended. - trace := append([]string{fmt.Sprintf("%v (%v)", o.location, o.name)}, mod.trace...) newModule := &module{ name: o.name, parent: mod, - trace: trace, app: mod.app, } for _, opt := range o.options { @@ -88,7 +82,6 @@ func (o moduleOption) apply(mod *module) { type module struct { parent *module name string - trace []string scope scope provides []provide invokes []invoke @@ -184,7 +177,6 @@ func (m *module) provide(p provide) { m.log.LogEvent(&fxevent.Provided{ ConstructorName: funcName, StackTrace: p.Stack.Strings(), - ModuleTrace: append([]string{p.Stack[0].String()}, m.trace...), ModuleName: m.name, OutputTypeNames: outputNames, Err: m.app.err, @@ -210,11 +202,10 @@ func (m *module) supply(p provide) { } m.log.LogEvent(&fxevent.Supplied{ - TypeName: typeName, - StackTrace: p.Stack.Strings(), - ModuleTrace: append([]string{p.Stack[0].String()}, m.trace...), - ModuleName: m.name, - Err: m.app.err, + TypeName: typeName, + StackTrace: p.Stack.Strings(), + ModuleName: m.name, + Err: m.app.err, }) } @@ -338,7 +329,6 @@ func (m *module) decorate(d decorator) (err error) { m.log.LogEvent(&fxevent.Decorated{ DecoratorName: funcName, StackTrace: d.Stack.Strings(), - ModuleTrace: append([]string{d.Stack[0].String()}, m.trace...), ModuleName: m.name, OutputTypeNames: outputNames, Err: err, @@ -364,7 +354,6 @@ func (m *module) replace(d decorator) error { m.log.LogEvent(&fxevent.Replaced{ ModuleName: m.name, StackTrace: d.Stack.Strings(), - ModuleTrace: append([]string{d.Stack[0].String()}, m.trace...), OutputTypeNames: []string{typeName}, Err: err, }) diff --git a/vendor/go.uber.org/fx/version.go b/vendor/go.uber.org/fx/version.go index 15934d2ce..943cd1a2c 100644 --- a/vendor/go.uber.org/fx/version.go +++ b/vendor/go.uber.org/fx/version.go @@ -21,4 +21,4 @@ package fx // Version is exported for runtime compatibility checks. -const Version = "1.20.1" +const Version = "1.20.0" diff --git a/vendor/go.uber.org/mock/AUTHORS b/vendor/go.uber.org/mock/AUTHORS deleted file mode 100644 index 660b8ccc8..000000000 --- a/vendor/go.uber.org/mock/AUTHORS +++ /dev/null @@ -1,12 +0,0 @@ -# This is the official list of GoMock authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. - -# Names should be added to this file as -# Name or Organization -# The email address is not required for organizations. - -# Please keep the list sorted. - -Alex Reece -Google Inc. diff --git a/vendor/go.uber.org/mock/CONTRIBUTORS b/vendor/go.uber.org/mock/CONTRIBUTORS deleted file mode 100644 index def849cab..000000000 --- a/vendor/go.uber.org/mock/CONTRIBUTORS +++ /dev/null @@ -1,37 +0,0 @@ -# This is the official list of people who can contribute (and typically -# have contributed) code to the gomock repository. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# The submission process automatically checks to make sure -# that people submitting code are listed in this file (by email address). -# -# Names should be added to this file only after verifying that -# the individual or the individual's organization has agreed to -# the appropriate Contributor License Agreement, found here: -# -# http://code.google.com/legal/individual-cla-v1.0.html -# http://code.google.com/legal/corporate-cla-v1.0.html -# -# The agreement for individuals can be filled out on the web. -# -# When adding J Random Contributor's name to this file, -# either J's name or J's organization's name should be -# added to the AUTHORS file, depending on whether the -# individual or corporate CLA was used. - -# Names should be added to this file like so: -# Name -# -# An entry with two email addresses specifies that the -# first address should be used in the submit logs and -# that the second address should be recognized as the -# same person when interacting with Rietveld. - -# Please keep the list sorted. - -Aaron Jacobs -Alex Reece -David Symonds -Ryan Barrett diff --git a/vendor/go.uber.org/mock/LICENSE b/vendor/go.uber.org/mock/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/go.uber.org/mock/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/go.uber.org/mock/mockgen/generic_go118.go b/vendor/go.uber.org/mock/mockgen/generic_go118.go deleted file mode 100644 index 635402dc5..000000000 --- a/vendor/go.uber.org/mock/mockgen/generic_go118.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2022 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build go1.18 -// +build go1.18 - -package main - -import ( - "fmt" - "go/ast" - "strings" - - "go.uber.org/mock/mockgen/model" -) - -func getTypeSpecTypeParams(ts *ast.TypeSpec) []*ast.Field { - if ts == nil || ts.TypeParams == nil { - return nil - } - return ts.TypeParams.List -} - -func (p *fileParser) parseGenericType(pkg string, typ ast.Expr, tps map[string]model.Type) (model.Type, error) { - switch v := typ.(type) { - case *ast.IndexExpr: - m, err := p.parseType(pkg, v.X, tps) - if err != nil { - return nil, err - } - nm, ok := m.(*model.NamedType) - if !ok { - return m, nil - } - t, err := p.parseType(pkg, v.Index, tps) - if err != nil { - return nil, err - } - nm.TypeParams = &model.TypeParametersType{TypeParameters: []model.Type{t}} - return m, nil - case *ast.IndexListExpr: - m, err := p.parseType(pkg, v.X, tps) - if err != nil { - return nil, err - } - nm, ok := m.(*model.NamedType) - if !ok { - return m, nil - } - var ts []model.Type - for _, expr := range v.Indices { - t, err := p.parseType(pkg, expr, tps) - if err != nil { - return nil, err - } - ts = append(ts, t) - } - nm.TypeParams = &model.TypeParametersType{TypeParameters: ts} - return m, nil - } - return nil, nil -} - -func getIdentTypeParams(decl any) string { - if decl == nil { - return "" - } - ts, ok := decl.(*ast.TypeSpec) - if !ok { - return "" - } - if ts.TypeParams == nil || len(ts.TypeParams.List) == 0 { - return "" - } - var sb strings.Builder - sb.WriteString("[") - for i, v := range ts.TypeParams.List { - if i != 0 { - sb.WriteString(", ") - } - sb.WriteString(v.Names[0].Name) - } - sb.WriteString("]") - return sb.String() -} - -func (p *fileParser) parseGenericMethod(field *ast.Field, it *namedInterface, iface *model.Interface, pkg string, tps map[string]model.Type) ([]*model.Method, error) { - var indices []ast.Expr - var typ ast.Expr - switch v := field.Type.(type) { - case *ast.IndexExpr: - indices = []ast.Expr{v.Index} - typ = v.X - case *ast.IndexListExpr: - indices = v.Indices - typ = v.X - default: - return nil, fmt.Errorf("don't know how to mock method of type %T", field.Type) - } - - nf := &ast.Field{ - Doc: field.Comment, - Names: field.Names, - Type: typ, - Tag: field.Tag, - Comment: field.Comment, - } - - it.embeddedInstTypeParams = indices - - return p.parseMethod(nf, it, iface, pkg, tps) -} diff --git a/vendor/go.uber.org/mock/mockgen/generic_notgo118.go b/vendor/go.uber.org/mock/mockgen/generic_notgo118.go deleted file mode 100644 index 8a779c8b2..000000000 --- a/vendor/go.uber.org/mock/mockgen/generic_notgo118.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2022 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//go:build !go1.18 -// +build !go1.18 - -package main - -import ( - "fmt" - "go/ast" - - "go.uber.org/mock/mockgen/model" -) - -func getTypeSpecTypeParams(ts *ast.TypeSpec) []*ast.Field { - return nil -} - -func (p *fileParser) parseGenericType(pkg string, typ ast.Expr, tps map[string]model.Type) (model.Type, error) { - return nil, nil -} - -func getIdentTypeParams(decl any) string { - return "" -} - -func (p *fileParser) parseGenericMethod(field *ast.Field, it *namedInterface, iface *model.Interface, pkg string, tps map[string]model.Type) ([]*model.Method, error) { - return nil, fmt.Errorf("don't know how to mock method of type %T", field.Type) -} diff --git a/vendor/go.uber.org/zap/.golangci.yml b/vendor/go.uber.org/zap/.golangci.yml deleted file mode 100644 index fbc6df790..000000000 --- a/vendor/go.uber.org/zap/.golangci.yml +++ /dev/null @@ -1,77 +0,0 @@ -output: - # Make output more digestible with quickfix in vim/emacs/etc. - sort-results: true - print-issued-lines: false - -linters: - # We'll track the golangci-lint default linters manually - # instead of letting them change without our control. - disable-all: true - enable: - # golangci-lint defaults: - - errcheck - - gosimple - - govet - - ineffassign - - staticcheck - - unused - - # Our own extras: - - gofmt - - nolintlint # lints nolint directives - - revive - -linters-settings: - govet: - # These govet checks are disabled by default, but they're useful. - enable: - - niliness - - reflectvaluecompare - - sortslice - - unusedwrite - - errcheck: - exclude-functions: - # These methods can not fail. - # They operate on an in-memory buffer. - - (*go.uber.org/zap/buffer.Buffer).Write - - (*go.uber.org/zap/buffer.Buffer).WriteByte - - (*go.uber.org/zap/buffer.Buffer).WriteString - - - (*go.uber.org/zap/zapio.Writer).Close - - (*go.uber.org/zap/zapio.Writer).Sync - - (*go.uber.org/zap/zapio.Writer).Write - # Write to zapio.Writer cannot fail, - # so io.WriteString on it cannot fail. - - io.WriteString(*go.uber.org/zap/zapio.Writer) - - # Writing a plain string to a fmt.State cannot fail. - - io.WriteString(fmt.State) - -issues: - # Print all issues reported by all linters. - max-issues-per-linter: 0 - max-same-issues: 0 - - # Don't ignore some of the issues that golangci-lint considers okay. - # This includes documenting all exported entities. - exclude-use-default: false - - exclude-rules: - # Don't warn on unused parameters. - # Parameter names are useful; replacing them with '_' is undesirable. - - linters: [revive] - text: 'unused-parameter: parameter \S+ seems to be unused, consider removing or renaming it as _' - - # staticcheck already has smarter checks for empty blocks. - # revive's empty-block linter has false positives. - # For example, as of writing this, the following is not allowed. - # for foo() { } - - linters: [revive] - text: 'empty-block: this block is empty, you can remove it' - - # Ignore logger.Sync() errcheck failures in example_test.go - # since those are intended to be uncomplicated examples. - - linters: [errcheck] - path: example_test.go - text: 'Error return value of `logger.Sync` is not checked' diff --git a/vendor/go.uber.org/zap/CHANGELOG.md b/vendor/go.uber.org/zap/CHANGELOG.md index 11b465976..0db1f9f15 100644 --- a/vendor/go.uber.org/zap/CHANGELOG.md +++ b/vendor/go.uber.org/zap/CHANGELOG.md @@ -1,39 +1,7 @@ # Changelog All notable changes to this project will be documented in this file. -This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## 1.26.0 (14 Sep 2023) -Enhancements: -* [#1319][]: Add `WithLazy` method to `Logger` which lazily evaluates the structured -context. -* [#1350][]: String encoding is much (~50%) faster now. - -Thanks to @jquirke, @cdvr1993 for their contributions to this release. - -[#1319]: https://github.com/uber-go/zap/pull/1319 -[#1350]: https://github.com/uber-go/zap/pull/1350 - -## 1.25.0 (1 Aug 2023) - -This release contains several improvements including performance, API additions, -and two new experimental packages whose APIs are unstable and may change in the -future. - -Enhancements: -* [#1246][]: Add `zap/exp/zapslog` package for integration with slog. -* [#1273][]: Add `Name` to `Logger` which returns the Logger's name if one is set. -* [#1281][]: Add `zap/exp/expfield` package which contains helper methods -`Str` and `Strs` for constructing String-like zap.Fields. -* [#1310][]: Reduce stack size on `Any`. - -Thanks to @knight42, @dzakaammar, @bcspragu, and @rexywork for their contributions -to this release. - -[#1246]: https://github.com/uber-go/zap/pull/1246 -[#1273]: https://github.com/uber-go/zap/pull/1273 -[#1281]: https://github.com/uber-go/zap/pull/1281 -[#1310]: https://github.com/uber-go/zap/pull/1310 +This project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## 1.24.0 (30 Nov 2022) @@ -59,6 +27,7 @@ Enhancements: [#1147]: https://github.com/uber-go/zap/pull/1147 [#1155]: https://github.com/uber-go/zap/pull/1155 + ## 1.22.0 (8 Aug 2022) Enhancements: @@ -207,16 +176,6 @@ Enhancements: Thanks to @ash2k, @FMLS, @jimmystewpot, @Oncilla, @tsoslow, @tylitianrui, @withshubh, and @wziww for their contributions to this release. -[#865]: https://github.com/uber-go/zap/pull/865 -[#867]: https://github.com/uber-go/zap/pull/867 -[#881]: https://github.com/uber-go/zap/pull/881 -[#903]: https://github.com/uber-go/zap/pull/903 -[#912]: https://github.com/uber-go/zap/pull/912 -[#913]: https://github.com/uber-go/zap/pull/913 -[#928]: https://github.com/uber-go/zap/pull/928 -[#931]: https://github.com/uber-go/zap/pull/931 -[#936]: https://github.com/uber-go/zap/pull/936 - ## 1.16.0 (1 Sep 2020) Bugfixes: @@ -238,17 +197,6 @@ Enhancements: Thanks to @SteelPhase, @tmshn, @lixingwang, @wyxloading, @moul, @segevfiner, @andy-retailnext and @jcorbin for their contributions to this release. -[#629]: https://github.com/uber-go/zap/pull/629 -[#697]: https://github.com/uber-go/zap/pull/697 -[#828]: https://github.com/uber-go/zap/pull/828 -[#835]: https://github.com/uber-go/zap/pull/835 -[#843]: https://github.com/uber-go/zap/pull/843 -[#844]: https://github.com/uber-go/zap/pull/844 -[#852]: https://github.com/uber-go/zap/pull/852 -[#854]: https://github.com/uber-go/zap/pull/854 -[#861]: https://github.com/uber-go/zap/pull/861 -[#862]: https://github.com/uber-go/zap/pull/862 - ## 1.15.0 (23 Apr 2020) Bugfixes: @@ -265,11 +213,6 @@ Enhancements: Thanks to @danielbprice for their contributions to this release. -[#804]: https://github.com/uber-go/zap/pull/804 -[#812]: https://github.com/uber-go/zap/pull/812 -[#806]: https://github.com/uber-go/zap/pull/806 -[#813]: https://github.com/uber-go/zap/pull/813 - ## 1.14.1 (14 Mar 2020) Bugfixes: @@ -282,10 +225,6 @@ Bugfixes: Thanks to @YashishDua for their contributions to this release. -[#791]: https://github.com/uber-go/zap/pull/791 -[#795]: https://github.com/uber-go/zap/pull/795 -[#799]: https://github.com/uber-go/zap/pull/799 - ## 1.14.0 (20 Feb 2020) Enhancements: @@ -296,11 +235,6 @@ Enhancements: Thanks to @caibirdme for their contributions to this release. -[#771]: https://github.com/uber-go/zap/pull/771 -[#773]: https://github.com/uber-go/zap/pull/773 -[#775]: https://github.com/uber-go/zap/pull/775 -[#786]: https://github.com/uber-go/zap/pull/786 - ## 1.13.0 (13 Nov 2019) Enhancements: @@ -309,15 +243,11 @@ Enhancements: Thanks to @jbizzle for their contributions to this release. -[#758]: https://github.com/uber-go/zap/pull/758 - ## 1.12.0 (29 Oct 2019) Enhancements: * [#751][]: Migrate to Go modules. -[#751]: https://github.com/uber-go/zap/pull/751 - ## 1.11.0 (21 Oct 2019) Enhancements: @@ -326,9 +256,6 @@ Enhancements: Thanks to @juicemia, @uhthomas for their contributions to this release. -[#725]: https://github.com/uber-go/zap/pull/725 -[#736]: https://github.com/uber-go/zap/pull/736 - ## 1.10.0 (29 Apr 2019) Bugfixes: @@ -346,20 +273,12 @@ Enhancements: Thanks to @iaroslav-ciupin, @lelenanam, @joa, @NWilson for their contributions to this release. -[#657]: https://github.com/uber-go/zap/pull/657 -[#706]: https://github.com/uber-go/zap/pull/706 -[#610]: https://github.com/uber-go/zap/pull/610 -[#675]: https://github.com/uber-go/zap/pull/675 -[#704]: https://github.com/uber-go/zap/pull/704 - ## v1.9.1 (06 Aug 2018) Bugfixes: * [#614][]: MapObjectEncoder should not ignore empty slices. -[#614]: https://github.com/uber-go/zap/pull/614 - ## v1.9.0 (19 Jul 2018) Enhancements: @@ -369,10 +288,6 @@ Enhancements: Thanks to @nfarah86, @AlekSi, @JeanMertz, @philippgille, @etsangsplk, and @dimroc for their contributions to this release. -[#602]: https://github.com/uber-go/zap/pull/602 -[#572]: https://github.com/uber-go/zap/pull/572 -[#606]: https://github.com/uber-go/zap/pull/606 - ## v1.8.0 (13 Apr 2018) Enhancements: @@ -386,18 +301,11 @@ Bugfixes: Thanks to @DiSiqueira and @djui for their contributions to this release. -[#508]: https://github.com/uber-go/zap/pull/508 -[#518]: https://github.com/uber-go/zap/pull/518 -[#577]: https://github.com/uber-go/zap/pull/577 -[#574]: https://github.com/uber-go/zap/pull/574 - ## v1.7.1 (25 Sep 2017) Bugfixes: * [#504][]: Store strings when using AddByteString with the map encoder. -[#504]: https://github.com/uber-go/zap/pull/504 - ## v1.7.0 (21 Sep 2017) Enhancements: @@ -405,8 +313,6 @@ Enhancements: * [#487][]: Add `NewStdLogAt`, which extends `NewStdLog` by allowing the user to specify the level of the logged messages. -[#487]: https://github.com/uber-go/zap/pull/487 - ## v1.6.0 (30 Aug 2017) Enhancements: @@ -415,9 +321,6 @@ Enhancements: * [#490][]: Add a `ContextMap` method to observer logs for simpler field validation in tests. -[#490]: https://github.com/uber-go/zap/pull/490 -[#491]: https://github.com/uber-go/zap/pull/491 - ## v1.5.0 (22 Jul 2017) Enhancements: @@ -431,11 +334,6 @@ Bugfixes: Thanks to @richard-tunein and @pavius for their contributions to this release. -[#477]: https://github.com/uber-go/zap/pull/477 -[#465]: https://github.com/uber-go/zap/pull/465 -[#460]: https://github.com/uber-go/zap/pull/460 -[#470]: https://github.com/uber-go/zap/pull/470 - ## v1.4.1 (08 Jun 2017) This release fixes two bugs. @@ -445,9 +343,6 @@ Bugfixes: * [#435][]: Support a variety of case conventions when unmarshaling levels. * [#444][]: Fix a panic in the observer. -[#435]: https://github.com/uber-go/zap/pull/435 -[#444]: https://github.com/uber-go/zap/pull/444 - ## v1.4.0 (12 May 2017) This release adds a few small features and is fully backward-compatible. @@ -460,10 +355,6 @@ Enhancements: * [#431][]: Make `zap.AtomicLevel` implement `fmt.Stringer`, which makes a variety of operations a bit simpler. -[#424]: https://github.com/uber-go/zap/pull/424 -[#425]: https://github.com/uber-go/zap/pull/425 -[#431]: https://github.com/uber-go/zap/pull/431 - ## v1.3.0 (25 Apr 2017) This release adds an enhancement to zap's testing helpers as well as the @@ -475,9 +366,6 @@ Enhancements: particularly useful when testing the `SugaredLogger`. * [#416][]: Make `AtomicLevel` implement `encoding.TextMarshaler`. -[#415]: https://github.com/uber-go/zap/pull/415 -[#416]: https://github.com/uber-go/zap/pull/416 - ## v1.2.0 (13 Apr 2017) This release adds a gRPC compatibility wrapper. It is fully backward-compatible. @@ -487,8 +375,6 @@ Enhancements: * [#402][]: Add a `zapgrpc` package that wraps zap's Logger and implements `grpclog.Logger`. -[#402]: https://github.com/uber-go/zap/pull/402 - ## v1.1.0 (31 Mar 2017) This release fixes two bugs and adds some enhancements to zap's testing helpers. @@ -506,10 +392,6 @@ Enhancements: Thanks to @moitias for contributing to this release. -[#385]: https://github.com/uber-go/zap/pull/385 -[#396]: https://github.com/uber-go/zap/pull/396 -[#386]: https://github.com/uber-go/zap/pull/386 - ## v1.0.0 (14 Mar 2017) This is zap's first stable release. All exported APIs are now final, and no @@ -555,20 +437,6 @@ Enhancements: Thanks to @suyash, @htrendev, @flisky, @Ulexus, and @skipor for their contributions to this release. -[#366]: https://github.com/uber-go/zap/pull/366 -[#364]: https://github.com/uber-go/zap/pull/364 -[#371]: https://github.com/uber-go/zap/pull/371 -[#362]: https://github.com/uber-go/zap/pull/362 -[#369]: https://github.com/uber-go/zap/pull/369 -[#347]: https://github.com/uber-go/zap/pull/347 -[#373]: https://github.com/uber-go/zap/pull/373 -[#348]: https://github.com/uber-go/zap/pull/348 -[#327]: https://github.com/uber-go/zap/pull/327 -[#376]: https://github.com/uber-go/zap/pull/376 -[#346]: https://github.com/uber-go/zap/pull/346 -[#365]: https://github.com/uber-go/zap/pull/365 -[#372]: https://github.com/uber-go/zap/pull/372 - ## v1.0.0-rc.3 (7 Mar 2017) This is the third release candidate for zap's stable release. There are no @@ -590,11 +458,6 @@ Enhancements: Thanks to @ansel1 and @suyash for their contributions to this release. -[#339]: https://github.com/uber-go/zap/pull/339 -[#307]: https://github.com/uber-go/zap/pull/307 -[#353]: https://github.com/uber-go/zap/pull/353 -[#311]: https://github.com/uber-go/zap/pull/311 - ## v1.0.0-rc.2 (21 Feb 2017) This is the second release candidate for zap's stable release. It includes two @@ -632,15 +495,6 @@ Enhancements: Thanks to @skipor and @chapsuk for their contributions to this release. -[#316]: https://github.com/uber-go/zap/pull/316 -[#309]: https://github.com/uber-go/zap/pull/309 -[#317]: https://github.com/uber-go/zap/pull/317 -[#321]: https://github.com/uber-go/zap/pull/321 -[#325]: https://github.com/uber-go/zap/pull/325 -[#333]: https://github.com/uber-go/zap/pull/333 -[#326]: https://github.com/uber-go/zap/pull/326 -[#300]: https://github.com/uber-go/zap/pull/300 - ## v1.0.0-rc.1 (14 Feb 2017) This is the first release candidate for zap's stable release. There are multiple @@ -669,3 +523,95 @@ backward compatibility concerns and all functionality is new. Early zap adopters should pin to the 0.1.x minor version until they're ready to upgrade to the upcoming stable release. + +[#316]: https://github.com/uber-go/zap/pull/316 +[#309]: https://github.com/uber-go/zap/pull/309 +[#317]: https://github.com/uber-go/zap/pull/317 +[#321]: https://github.com/uber-go/zap/pull/321 +[#325]: https://github.com/uber-go/zap/pull/325 +[#333]: https://github.com/uber-go/zap/pull/333 +[#326]: https://github.com/uber-go/zap/pull/326 +[#300]: https://github.com/uber-go/zap/pull/300 +[#339]: https://github.com/uber-go/zap/pull/339 +[#307]: https://github.com/uber-go/zap/pull/307 +[#353]: https://github.com/uber-go/zap/pull/353 +[#311]: https://github.com/uber-go/zap/pull/311 +[#366]: https://github.com/uber-go/zap/pull/366 +[#364]: https://github.com/uber-go/zap/pull/364 +[#371]: https://github.com/uber-go/zap/pull/371 +[#362]: https://github.com/uber-go/zap/pull/362 +[#369]: https://github.com/uber-go/zap/pull/369 +[#347]: https://github.com/uber-go/zap/pull/347 +[#373]: https://github.com/uber-go/zap/pull/373 +[#348]: https://github.com/uber-go/zap/pull/348 +[#327]: https://github.com/uber-go/zap/pull/327 +[#376]: https://github.com/uber-go/zap/pull/376 +[#346]: https://github.com/uber-go/zap/pull/346 +[#365]: https://github.com/uber-go/zap/pull/365 +[#372]: https://github.com/uber-go/zap/pull/372 +[#385]: https://github.com/uber-go/zap/pull/385 +[#396]: https://github.com/uber-go/zap/pull/396 +[#386]: https://github.com/uber-go/zap/pull/386 +[#402]: https://github.com/uber-go/zap/pull/402 +[#415]: https://github.com/uber-go/zap/pull/415 +[#416]: https://github.com/uber-go/zap/pull/416 +[#424]: https://github.com/uber-go/zap/pull/424 +[#425]: https://github.com/uber-go/zap/pull/425 +[#431]: https://github.com/uber-go/zap/pull/431 +[#435]: https://github.com/uber-go/zap/pull/435 +[#444]: https://github.com/uber-go/zap/pull/444 +[#477]: https://github.com/uber-go/zap/pull/477 +[#465]: https://github.com/uber-go/zap/pull/465 +[#460]: https://github.com/uber-go/zap/pull/460 +[#470]: https://github.com/uber-go/zap/pull/470 +[#487]: https://github.com/uber-go/zap/pull/487 +[#490]: https://github.com/uber-go/zap/pull/490 +[#491]: https://github.com/uber-go/zap/pull/491 +[#504]: https://github.com/uber-go/zap/pull/504 +[#508]: https://github.com/uber-go/zap/pull/508 +[#518]: https://github.com/uber-go/zap/pull/518 +[#577]: https://github.com/uber-go/zap/pull/577 +[#574]: https://github.com/uber-go/zap/pull/574 +[#602]: https://github.com/uber-go/zap/pull/602 +[#572]: https://github.com/uber-go/zap/pull/572 +[#606]: https://github.com/uber-go/zap/pull/606 +[#614]: https://github.com/uber-go/zap/pull/614 +[#657]: https://github.com/uber-go/zap/pull/657 +[#706]: https://github.com/uber-go/zap/pull/706 +[#610]: https://github.com/uber-go/zap/pull/610 +[#675]: https://github.com/uber-go/zap/pull/675 +[#704]: https://github.com/uber-go/zap/pull/704 +[#725]: https://github.com/uber-go/zap/pull/725 +[#736]: https://github.com/uber-go/zap/pull/736 +[#751]: https://github.com/uber-go/zap/pull/751 +[#758]: https://github.com/uber-go/zap/pull/758 +[#771]: https://github.com/uber-go/zap/pull/771 +[#773]: https://github.com/uber-go/zap/pull/773 +[#775]: https://github.com/uber-go/zap/pull/775 +[#786]: https://github.com/uber-go/zap/pull/786 +[#791]: https://github.com/uber-go/zap/pull/791 +[#795]: https://github.com/uber-go/zap/pull/795 +[#799]: https://github.com/uber-go/zap/pull/799 +[#804]: https://github.com/uber-go/zap/pull/804 +[#812]: https://github.com/uber-go/zap/pull/812 +[#806]: https://github.com/uber-go/zap/pull/806 +[#813]: https://github.com/uber-go/zap/pull/813 +[#629]: https://github.com/uber-go/zap/pull/629 +[#697]: https://github.com/uber-go/zap/pull/697 +[#828]: https://github.com/uber-go/zap/pull/828 +[#835]: https://github.com/uber-go/zap/pull/835 +[#843]: https://github.com/uber-go/zap/pull/843 +[#844]: https://github.com/uber-go/zap/pull/844 +[#852]: https://github.com/uber-go/zap/pull/852 +[#854]: https://github.com/uber-go/zap/pull/854 +[#861]: https://github.com/uber-go/zap/pull/861 +[#862]: https://github.com/uber-go/zap/pull/862 +[#865]: https://github.com/uber-go/zap/pull/865 +[#867]: https://github.com/uber-go/zap/pull/867 +[#881]: https://github.com/uber-go/zap/pull/881 +[#903]: https://github.com/uber-go/zap/pull/903 +[#912]: https://github.com/uber-go/zap/pull/912 +[#913]: https://github.com/uber-go/zap/pull/913 +[#928]: https://github.com/uber-go/zap/pull/928 +[#931]: https://github.com/uber-go/zap/pull/931 +[#936]: https://github.com/uber-go/zap/pull/936 diff --git a/vendor/go.uber.org/zap/Makefile b/vendor/go.uber.org/zap/Makefile index eb1cee53b..9b1bc3b0e 100644 --- a/vendor/go.uber.org/zap/Makefile +++ b/vendor/go.uber.org/zap/Makefile @@ -1,51 +1,50 @@ -# Directory containing the Makefile. -PROJECT_ROOT = $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) +export GOBIN ?= $(shell pwd)/bin -export GOBIN ?= $(PROJECT_ROOT)/bin -export PATH := $(GOBIN):$(PATH) - -GOVULNCHECK = $(GOBIN)/govulncheck +GOLINT = $(GOBIN)/golint +STATICCHECK = $(GOBIN)/staticcheck BENCH_FLAGS ?= -cpuprofile=cpu.pprof -memprofile=mem.pprof -benchmem # Directories containing independent Go modules. -MODULE_DIRS = . ./exp ./benchmarks ./zapgrpc/internal/test +# +# We track coverage only for the main module. +MODULE_DIRS = . ./benchmarks ./zapgrpc/internal/test -# Directories that we want to track coverage for. -COVER_DIRS = . ./exp +# Many Go tools take file globs or directories as arguments instead of packages. +GO_FILES := $(shell \ + find . '(' -path '*/.*' -o -path './vendor' ')' -prune \ + -o -name '*.go' -print | cut -b3-) .PHONY: all all: lint test .PHONY: lint -lint: golangci-lint tidy-lint license-lint +lint: $(GOLINT) $(STATICCHECK) + @rm -rf lint.log + @echo "Checking formatting..." + @gofmt -d -s $(GO_FILES) 2>&1 | tee lint.log + @echo "Checking vet..." + @$(foreach dir,$(MODULE_DIRS),(cd $(dir) && go vet ./... 2>&1) &&) true | tee -a lint.log + @echo "Checking lint..." + @$(foreach dir,$(MODULE_DIRS),(cd $(dir) && $(GOLINT) ./... 2>&1) &&) true | tee -a lint.log + @echo "Checking staticcheck..." + @$(foreach dir,$(MODULE_DIRS),(cd $(dir) && $(STATICCHECK) ./... 2>&1) &&) true | tee -a lint.log + @echo "Checking for unresolved FIXMEs..." + @git grep -i fixme | grep -v -e Makefile | tee -a lint.log + @echo "Checking for license headers..." + @./checklicense.sh | tee -a lint.log + @[ ! -s lint.log ] + @echo "Checking 'go mod tidy'..." + @make tidy + @if ! git diff --quiet; then \ + echo "'go mod tidy' resulted in changes or working tree is dirty:"; \ + git --no-pager diff; \ + fi -.PHONY: golangci-lint -golangci-lint: - @$(foreach mod,$(MODULE_DIRS), \ - (cd $(mod) && \ - echo "[lint] golangci-lint: $(mod)" && \ - golangci-lint run --path-prefix $(mod)) &&) true +$(GOLINT): + cd tools && go install golang.org/x/lint/golint -.PHONY: tidy -tidy: - @$(foreach dir,$(MODULE_DIRS), \ - (cd $(dir) && go mod tidy) &&) true - -.PHONY: tidy-lint -tidy-lint: - @$(foreach mod,$(MODULE_DIRS), \ - (cd $(mod) && \ - echo "[lint] tidy: $(mod)" && \ - go mod tidy && \ - git diff --exit-code -- go.mod go.sum) &&) true - - -.PHONY: license-lint -license-lint: - ./checklicense.sh - -$(GOVULNCHECK): - cd tools && go install golang.org/x/vuln/cmd/govulncheck +$(STATICCHECK): + cd tools && go install honnef.co/go/tools/cmd/staticcheck .PHONY: test test: @@ -53,10 +52,8 @@ test: .PHONY: cover cover: - @$(foreach dir,$(COVER_DIRS), ( \ - cd $(dir) && \ - go test -race -coverprofile=cover.out -coverpkg=./... ./... \ - && go tool cover -html=cover.out -o cover.html) &&) true + go test -race -coverprofile=cover.out -coverpkg=./... ./... + go tool cover -html=cover.out -o cover.html .PHONY: bench BENCH ?= . @@ -71,6 +68,6 @@ updatereadme: rm -f README.md cat .readme.tmpl | go run internal/readme/readme.go > README.md -.PHONY: vulncheck -vulncheck: $(GOVULNCHECK) - $(GOVULNCHECK) ./... +.PHONY: tidy +tidy: + @$(foreach dir,$(MODULE_DIRS),(cd $(dir) && go mod tidy) &&) true diff --git a/vendor/go.uber.org/zap/README.md b/vendor/go.uber.org/zap/README.md index 9de08927b..a553a428c 100644 --- a/vendor/go.uber.org/zap/README.md +++ b/vendor/go.uber.org/zap/README.md @@ -54,7 +54,7 @@ and make many small allocations. Put differently, using `encoding/json` and Zap takes a different approach. It includes a reflection-free, zero-allocation JSON encoder, and the base `Logger` strives to avoid serialization overhead and allocations wherever possible. By building the high-level `SugaredLogger` -on that foundation, zap lets users *choose* when they need to count every +on that foundation, zap lets users _choose_ when they need to count every allocation and when they'd prefer a more familiar, loosely typed API. As measured by its own [benchmarking suite][], not only is zap more performant @@ -64,43 +64,40 @@ id="anchor-versions">[1](#footnote-versions) Log a message and 10 fields: -| Package | Time | Time % to zap | Objects Allocated | -| :------ | :--: | :-----------: | :---------------: | -| :zap: zap | 1744 ns/op | +0% | 5 allocs/op -| :zap: zap (sugared) | 2483 ns/op | +42% | 10 allocs/op -| zerolog | 918 ns/op | -47% | 1 allocs/op -| go-kit | 5590 ns/op | +221% | 57 allocs/op -| slog | 5640 ns/op | +223% | 40 allocs/op -| apex/log | 21184 ns/op | +1115% | 63 allocs/op -| logrus | 24338 ns/op | +1296% | 79 allocs/op -| log15 | 26054 ns/op | +1394% | 74 allocs/op +| Package | Time | Time % to zap | Objects Allocated | +| :------------------ | :---------: | :-----------: | :---------------: | +| :zap: zap | 2900 ns/op | +0% | 5 allocs/op | +| :zap: zap (sugared) | 3475 ns/op | +20% | 10 allocs/op | +| zerolog | 10639 ns/op | +267% | 32 allocs/op | +| go-kit | 14434 ns/op | +398% | 59 allocs/op | +| logrus | 17104 ns/op | +490% | 81 allocs/op | +| apex/log | 32424 ns/op | +1018% | 66 allocs/op | +| log15 | 33579 ns/op | +1058% | 76 allocs/op | Log a message with a logger that already has 10 fields of context: -| Package | Time | Time % to zap | Objects Allocated | -| :------ | :--: | :-----------: | :---------------: | -| :zap: zap | 193 ns/op | +0% | 0 allocs/op -| :zap: zap (sugared) | 227 ns/op | +18% | 1 allocs/op -| zerolog | 81 ns/op | -58% | 0 allocs/op -| slog | 322 ns/op | +67% | 0 allocs/op -| go-kit | 5377 ns/op | +2686% | 56 allocs/op -| apex/log | 19518 ns/op | +10013% | 53 allocs/op -| log15 | 19812 ns/op | +10165% | 70 allocs/op -| logrus | 21997 ns/op | +11297% | 68 allocs/op +| Package | Time | Time % to zap | Objects Allocated | +| :------------------ | :---------: | :-----------: | :---------------: | +| :zap: zap | 373 ns/op | +0% | 0 allocs/op | +| :zap: zap (sugared) | 452 ns/op | +21% | 1 allocs/op | +| zerolog | 288 ns/op | -23% | 0 allocs/op | +| go-kit | 11785 ns/op | +3060% | 58 allocs/op | +| logrus | 19629 ns/op | +5162% | 70 allocs/op | +| log15 | 21866 ns/op | +5762% | 72 allocs/op | +| apex/log | 30890 ns/op | +8182% | 55 allocs/op | Log a static string, without any context or `printf`-style templating: -| Package | Time | Time % to zap | Objects Allocated | -| :------ | :--: | :-----------: | :---------------: | -| :zap: zap | 165 ns/op | +0% | 0 allocs/op -| :zap: zap (sugared) | 212 ns/op | +28% | 1 allocs/op -| zerolog | 95 ns/op | -42% | 0 allocs/op -| slog | 296 ns/op | +79% | 0 allocs/op -| go-kit | 415 ns/op | +152% | 9 allocs/op -| standard library | 422 ns/op | +156% | 2 allocs/op -| apex/log | 1601 ns/op | +870% | 5 allocs/op -| logrus | 3017 ns/op | +1728% | 23 allocs/op -| log15 | 3469 ns/op | +2002% | 20 allocs/op +| Package | Time | Time % to zap | Objects Allocated | +| :------------------ | :--------: | :-----------: | :---------------: | +| :zap: zap | 381 ns/op | +0% | 0 allocs/op | +| :zap: zap (sugared) | 410 ns/op | +8% | 1 allocs/op | +| zerolog | 369 ns/op | -3% | 0 allocs/op | +| standard library | 385 ns/op | +1% | 2 allocs/op | +| go-kit | 606 ns/op | +59% | 11 allocs/op | +| logrus | 1730 ns/op | +354% | 25 allocs/op | +| apex/log | 1998 ns/op | +424% | 7 allocs/op | +| log15 | 4546 ns/op | +1093% | 22 allocs/op | ## Development Status: Stable @@ -134,4 +131,3 @@ pinned in the [benchmarks/go.mod][] file. [↩](#anchor-versions) [cov]: https://codecov.io/gh/uber-go/zap [benchmarking suite]: https://github.com/uber-go/zap/tree/master/benchmarks [benchmarks/go.mod]: https://github.com/uber-go/zap/blob/master/benchmarks/go.mod - diff --git a/vendor/go.uber.org/zap/array.go b/vendor/go.uber.org/zap/array.go index abfccb566..5be3704a3 100644 --- a/vendor/go.uber.org/zap/array.go +++ b/vendor/go.uber.org/zap/array.go @@ -21,7 +21,6 @@ package zap import ( - "fmt" "time" "go.uber.org/zap/zapcore" @@ -95,137 +94,11 @@ func Int8s(key string, nums []int8) Field { return Array(key, int8s(nums)) } -// Objects constructs a field with the given key, holding a list of the -// provided objects that can be marshaled by Zap. -// -// Note that these objects must implement zapcore.ObjectMarshaler directly. -// That is, if you're trying to marshal a []Request, the MarshalLogObject -// method must be declared on the Request type, not its pointer (*Request). -// If it's on the pointer, use ObjectValues. -// -// Given an object that implements MarshalLogObject on the value receiver, you -// can log a slice of those objects with Objects like so: -// -// type Author struct{ ... } -// func (a Author) MarshalLogObject(enc zapcore.ObjectEncoder) error -// -// var authors []Author = ... -// logger.Info("loading article", zap.Objects("authors", authors)) -// -// Similarly, given a type that implements MarshalLogObject on its pointer -// receiver, you can log a slice of pointers to that object with Objects like -// so: -// -// type Request struct{ ... } -// func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) error -// -// var requests []*Request = ... -// logger.Info("sending requests", zap.Objects("requests", requests)) -// -// If instead, you have a slice of values of such an object, use the -// ObjectValues constructor. -// -// var requests []Request = ... -// logger.Info("sending requests", zap.ObjectValues("requests", requests)) -func Objects[T zapcore.ObjectMarshaler](key string, values []T) Field { - return Array(key, objects[T](values)) -} - -type objects[T zapcore.ObjectMarshaler] []T - -func (os objects[T]) MarshalLogArray(arr zapcore.ArrayEncoder) error { - for _, o := range os { - if err := arr.AppendObject(o); err != nil { - return err - } - } - return nil -} - -// ObjectMarshalerPtr is a constraint that specifies that the given type -// implements zapcore.ObjectMarshaler on a pointer receiver. -type ObjectMarshalerPtr[T any] interface { - *T - zapcore.ObjectMarshaler -} - -// ObjectValues constructs a field with the given key, holding a list of the -// provided objects, where pointers to these objects can be marshaled by Zap. -// -// Note that pointers to these objects must implement zapcore.ObjectMarshaler. -// That is, if you're trying to marshal a []Request, the MarshalLogObject -// method must be declared on the *Request type, not the value (Request). -// If it's on the value, use Objects. -// -// Given an object that implements MarshalLogObject on the pointer receiver, -// you can log a slice of those objects with ObjectValues like so: -// -// type Request struct{ ... } -// func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) error -// -// var requests []Request = ... -// logger.Info("sending requests", zap.ObjectValues("requests", requests)) -// -// If instead, you have a slice of pointers of such an object, use the Objects -// field constructor. -// -// var requests []*Request = ... -// logger.Info("sending requests", zap.Objects("requests", requests)) -func ObjectValues[T any, P ObjectMarshalerPtr[T]](key string, values []T) Field { - return Array(key, objectValues[T, P](values)) -} - -type objectValues[T any, P ObjectMarshalerPtr[T]] []T - -func (os objectValues[T, P]) MarshalLogArray(arr zapcore.ArrayEncoder) error { - for i := range os { - // It is necessary for us to explicitly reference the "P" type. - // We cannot simply pass "&os[i]" to AppendObject because its type - // is "*T", which the type system does not consider as - // implementing ObjectMarshaler. - // Only the type "P" satisfies ObjectMarshaler, which we have - // to convert "*T" to explicitly. - var p P = &os[i] - if err := arr.AppendObject(p); err != nil { - return err - } - } - return nil -} - // Strings constructs a field that carries a slice of strings. func Strings(key string, ss []string) Field { return Array(key, stringArray(ss)) } -// Stringers constructs a field with the given key, holding a list of the -// output provided by the value's String method -// -// Given an object that implements String on the value receiver, you -// can log a slice of those objects with Objects like so: -// -// type Request struct{ ... } -// func (a Request) String() string -// -// var requests []Request = ... -// logger.Info("sending requests", zap.Stringers("requests", requests)) -// -// Note that these objects must implement fmt.Stringer directly. -// That is, if you're trying to marshal a []Request, the String method -// must be declared on the Request type, not its pointer (*Request). -func Stringers[T fmt.Stringer](key string, values []T) Field { - return Array(key, stringers[T](values)) -} - -type stringers[T fmt.Stringer] []T - -func (os stringers[T]) MarshalLogArray(arr zapcore.ArrayEncoder) error { - for _, o := range os { - arr.AppendString(o.String()) - } - return nil -} - // Times constructs a field that carries a slice of time.Times. func Times(key string, ts []time.Time) Field { return Array(key, times(ts)) diff --git a/vendor/go.uber.org/zap/array_go118.go b/vendor/go.uber.org/zap/array_go118.go new file mode 100644 index 000000000..d0d2c49d6 --- /dev/null +++ b/vendor/go.uber.org/zap/array_go118.go @@ -0,0 +1,156 @@ +// Copyright (c) 2022 Uber Technologies, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +//go:build go1.18 +// +build go1.18 + +package zap + +import ( + "fmt" + + "go.uber.org/zap/zapcore" +) + +// Objects constructs a field with the given key, holding a list of the +// provided objects that can be marshaled by Zap. +// +// Note that these objects must implement zapcore.ObjectMarshaler directly. +// That is, if you're trying to marshal a []Request, the MarshalLogObject +// method must be declared on the Request type, not its pointer (*Request). +// If it's on the pointer, use ObjectValues. +// +// Given an object that implements MarshalLogObject on the value receiver, you +// can log a slice of those objects with Objects like so: +// +// type Author struct{ ... } +// func (a Author) MarshalLogObject(enc zapcore.ObjectEncoder) error +// +// var authors []Author = ... +// logger.Info("loading article", zap.Objects("authors", authors)) +// +// Similarly, given a type that implements MarshalLogObject on its pointer +// receiver, you can log a slice of pointers to that object with Objects like +// so: +// +// type Request struct{ ... } +// func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) error +// +// var requests []*Request = ... +// logger.Info("sending requests", zap.Objects("requests", requests)) +// +// If instead, you have a slice of values of such an object, use the +// ObjectValues constructor. +// +// var requests []Request = ... +// logger.Info("sending requests", zap.ObjectValues("requests", requests)) +func Objects[T zapcore.ObjectMarshaler](key string, values []T) Field { + return Array(key, objects[T](values)) +} + +type objects[T zapcore.ObjectMarshaler] []T + +func (os objects[T]) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for _, o := range os { + if err := arr.AppendObject(o); err != nil { + return err + } + } + return nil +} + +// ObjectMarshalerPtr is a constraint that specifies that the given type +// implements zapcore.ObjectMarshaler on a pointer receiver. +type ObjectMarshalerPtr[T any] interface { + *T + zapcore.ObjectMarshaler +} + +// ObjectValues constructs a field with the given key, holding a list of the +// provided objects, where pointers to these objects can be marshaled by Zap. +// +// Note that pointers to these objects must implement zapcore.ObjectMarshaler. +// That is, if you're trying to marshal a []Request, the MarshalLogObject +// method must be declared on the *Request type, not the value (Request). +// If it's on the value, use Objects. +// +// Given an object that implements MarshalLogObject on the pointer receiver, +// you can log a slice of those objects with ObjectValues like so: +// +// type Request struct{ ... } +// func (r *Request) MarshalLogObject(enc zapcore.ObjectEncoder) error +// +// var requests []Request = ... +// logger.Info("sending requests", zap.ObjectValues("requests", requests)) +// +// If instead, you have a slice of pointers of such an object, use the Objects +// field constructor. +// +// var requests []*Request = ... +// logger.Info("sending requests", zap.Objects("requests", requests)) +func ObjectValues[T any, P ObjectMarshalerPtr[T]](key string, values []T) Field { + return Array(key, objectValues[T, P](values)) +} + +type objectValues[T any, P ObjectMarshalerPtr[T]] []T + +func (os objectValues[T, P]) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for i := range os { + // It is necessary for us to explicitly reference the "P" type. + // We cannot simply pass "&os[i]" to AppendObject because its type + // is "*T", which the type system does not consider as + // implementing ObjectMarshaler. + // Only the type "P" satisfies ObjectMarshaler, which we have + // to convert "*T" to explicitly. + var p P = &os[i] + if err := arr.AppendObject(p); err != nil { + return err + } + } + return nil +} + +// Stringers constructs a field with the given key, holding a list of the +// output provided by the value's String method +// +// Given an object that implements String on the value receiver, you +// can log a slice of those objects with Objects like so: +// +// type Request struct{ ... } +// func (a Request) String() string +// +// var requests []Request = ... +// logger.Info("sending requests", zap.Stringers("requests", requests)) +// +// Note that these objects must implement fmt.Stringer directly. +// That is, if you're trying to marshal a []Request, the String method +// must be declared on the Request type, not its pointer (*Request). +func Stringers[T fmt.Stringer](key string, values []T) Field { + return Array(key, stringers[T](values)) +} + +type stringers[T fmt.Stringer] []T + +func (os stringers[T]) MarshalLogArray(arr zapcore.ArrayEncoder) error { + for _, o := range os { + arr.AppendString(o.String()) + } + return nil +} diff --git a/vendor/go.uber.org/zap/buffer/buffer.go b/vendor/go.uber.org/zap/buffer/buffer.go index 27fb5cd5d..9e929cd98 100644 --- a/vendor/go.uber.org/zap/buffer/buffer.go +++ b/vendor/go.uber.org/zap/buffer/buffer.go @@ -42,11 +42,6 @@ func (b *Buffer) AppendByte(v byte) { b.bs = append(b.bs, v) } -// AppendBytes writes a single byte to the Buffer. -func (b *Buffer) AppendBytes(v []byte) { - b.bs = append(b.bs, v...) -} - // AppendString writes a string to the Buffer. func (b *Buffer) AppendString(s string) { b.bs = append(b.bs, s...) diff --git a/vendor/go.uber.org/zap/buffer/pool.go b/vendor/go.uber.org/zap/buffer/pool.go index 846323360..8fb3e202c 100644 --- a/vendor/go.uber.org/zap/buffer/pool.go +++ b/vendor/go.uber.org/zap/buffer/pool.go @@ -20,29 +20,25 @@ package buffer -import ( - "go.uber.org/zap/internal/pool" -) +import "sync" // A Pool is a type-safe wrapper around a sync.Pool. type Pool struct { - p *pool.Pool[*Buffer] + p *sync.Pool } // NewPool constructs a new Pool. func NewPool() Pool { - return Pool{ - p: pool.New(func() *Buffer { - return &Buffer{ - bs: make([]byte, 0, _size), - } - }), - } + return Pool{p: &sync.Pool{ + New: func() interface{} { + return &Buffer{bs: make([]byte, 0, _size)} + }, + }} } // Get retrieves a Buffer from the pool, creating one if necessary. func (p Pool) Get() *Buffer { - buf := p.p.Get() + buf := p.p.Get().(*Buffer) buf.Reset() buf.pool = p return buf diff --git a/vendor/go.uber.org/zap/config.go b/vendor/go.uber.org/zap/config.go index e76e4e64f..ee6096766 100644 --- a/vendor/go.uber.org/zap/config.go +++ b/vendor/go.uber.org/zap/config.go @@ -95,32 +95,6 @@ type Config struct { // NewProductionEncoderConfig returns an opinionated EncoderConfig for // production environments. -// -// Messages encoded with this configuration will be JSON-formatted -// and will have the following keys by default: -// -// - "level": The logging level (e.g. "info", "error"). -// - "ts": The current time in number of seconds since the Unix epoch. -// - "msg": The message passed to the log statement. -// - "caller": If available, a short path to the file and line number -// where the log statement was issued. -// The logger configuration determines whether this field is captured. -// - "stacktrace": If available, a stack trace from the line -// where the log statement was issued. -// The logger configuration determines whether this field is captured. -// -// By default, the following formats are used for different types: -// -// - Time is formatted as floating-point number of seconds since the Unix -// epoch. -// - Duration is formatted as floating-point number of seconds. -// -// You may change these by setting the appropriate fields in the returned -// object. -// For example, use the following to change the time encoding format: -// -// cfg := zap.NewProductionEncoderConfig() -// cfg.EncodeTime = zapcore.ISO8601TimeEncoder func NewProductionEncoderConfig() zapcore.EncoderConfig { return zapcore.EncoderConfig{ TimeKey: "ts", @@ -138,22 +112,11 @@ func NewProductionEncoderConfig() zapcore.EncoderConfig { } } -// NewProductionConfig builds a reasonable default production logging -// configuration. -// Logging is enabled at InfoLevel and above, and uses a JSON encoder. -// Logs are written to standard error. -// Stacktraces are included on logs of ErrorLevel and above. -// DPanicLevel logs will not panic, but will write a stacktrace. +// NewProductionConfig is a reasonable production logging configuration. +// Logging is enabled at InfoLevel and above. // -// Sampling is enabled at 100:100 by default, -// meaning that after the first 100 log entries -// with the same level and message in the same second, -// it will log every 100th entry -// with the same level and message in the same second. -// You may disable this behavior by setting Sampling to nil. -// -// See [NewProductionEncoderConfig] for information -// on the default encoder configuration. +// It uses a JSON encoder, writes to standard error, and enables sampling. +// Stacktraces are automatically included on logs of ErrorLevel and above. func NewProductionConfig() Config { return Config{ Level: NewAtomicLevelAt(InfoLevel), @@ -171,32 +134,6 @@ func NewProductionConfig() Config { // NewDevelopmentEncoderConfig returns an opinionated EncoderConfig for // development environments. -// -// Messages encoded with this configuration will use Zap's console encoder -// intended to print human-readable output. -// It will print log messages with the following information: -// -// - The log level (e.g. "INFO", "ERROR"). -// - The time in ISO8601 format (e.g. "2017-01-01T12:00:00Z"). -// - The message passed to the log statement. -// - If available, a short path to the file and line number -// where the log statement was issued. -// The logger configuration determines whether this field is captured. -// - If available, a stacktrace from the line -// where the log statement was issued. -// The logger configuration determines whether this field is captured. -// -// By default, the following formats are used for different types: -// -// - Time is formatted in ISO8601 format (e.g. "2017-01-01T12:00:00Z"). -// - Duration is formatted as a string (e.g. "1.234s"). -// -// You may change these by setting the appropriate fields in the returned -// object. -// For example, use the following to change the time encoding format: -// -// cfg := zap.NewDevelopmentEncoderConfig() -// cfg.EncodeTime = zapcore.ISO8601TimeEncoder func NewDevelopmentEncoderConfig() zapcore.EncoderConfig { return zapcore.EncoderConfig{ // Keys can be anything except the empty string. @@ -215,15 +152,12 @@ func NewDevelopmentEncoderConfig() zapcore.EncoderConfig { } } -// NewDevelopmentConfig builds a reasonable default development logging -// configuration. -// Logging is enabled at DebugLevel and above, and uses a console encoder. -// Logs are written to standard error. -// Stacktraces are included on logs of WarnLevel and above. -// DPanicLevel logs will panic. +// NewDevelopmentConfig is a reasonable development logging configuration. +// Logging is enabled at DebugLevel and above. // -// See [NewDevelopmentEncoderConfig] for information -// on the default encoder configuration. +// It enables development mode (which makes DPanicLevel logs panic), uses a +// console encoder, writes to standard error, and disables sampling. +// Stacktraces are automatically included on logs of WarnLevel and above. func NewDevelopmentConfig() Config { return Config{ Level: NewAtomicLevelAt(DebugLevel), diff --git a/vendor/go.uber.org/zap/error.go b/vendor/go.uber.org/zap/error.go index 45f7b838d..65982a51e 100644 --- a/vendor/go.uber.org/zap/error.go +++ b/vendor/go.uber.org/zap/error.go @@ -21,13 +21,14 @@ package zap import ( - "go.uber.org/zap/internal/pool" + "sync" + "go.uber.org/zap/zapcore" ) -var _errArrayElemPool = pool.New(func() *errArrayElem { +var _errArrayElemPool = sync.Pool{New: func() interface{} { return &errArrayElem{} -}) +}} // Error is shorthand for the common idiom NamedError("error", err). func Error(err error) Field { @@ -59,14 +60,11 @@ func (errs errArray) MarshalLogArray(arr zapcore.ArrayEncoder) error { // potentially an "errorVerbose" attribute, we need to wrap it in a // type that implements LogObjectMarshaler. To prevent this from // allocating, pool the wrapper type. - elem := _errArrayElemPool.Get() + elem := _errArrayElemPool.Get().(*errArrayElem) elem.error = errs[i] - err := arr.AppendObject(elem) + arr.AppendObject(elem) elem.error = nil _errArrayElemPool.Put(elem) - if err != nil { - return err - } } return nil } diff --git a/vendor/go.uber.org/zap/field.go b/vendor/go.uber.org/zap/field.go index c8dd3358a..bbb745db5 100644 --- a/vendor/go.uber.org/zap/field.go +++ b/vendor/go.uber.org/zap/field.go @@ -25,7 +25,6 @@ import ( "math" "time" - "go.uber.org/zap/internal/stacktrace" "go.uber.org/zap/zapcore" ) @@ -375,7 +374,7 @@ func StackSkip(key string, skip int) Field { // from expanding the zapcore.Field union struct to include a byte slice. Since // taking a stacktrace is already so expensive (~10us), the extra allocation // is okay. - return String(key, stacktrace.Take(skip+1)) // skip StackSkip + return String(key, takeStacktrace(skip+1)) // skip StackSkip } // Duration constructs a field with the given key and value. The encoder @@ -411,63 +410,6 @@ func Inline(val zapcore.ObjectMarshaler) Field { } } -// Dict constructs a field containing the provided key-value pairs. -// It acts similar to [Object], but with the fields specified as arguments. -func Dict(key string, val ...Field) Field { - return dictField(key, val) -} - -// We need a function with the signature (string, T) for zap.Any. -func dictField(key string, val []Field) Field { - return Object(key, dictObject(val)) -} - -type dictObject []Field - -func (d dictObject) MarshalLogObject(enc zapcore.ObjectEncoder) error { - for _, f := range d { - f.AddTo(enc) - } - return nil -} - -// We discovered an issue where zap.Any can cause a performance degradation -// when used in new goroutines. -// -// This happens because the compiler assigns 4.8kb (one zap.Field per arm of -// switch statement) of stack space for zap.Any when it takes the form: -// -// switch v := v.(type) { -// case string: -// return String(key, v) -// case int: -// return Int(key, v) -// // ... -// default: -// return Reflect(key, v) -// } -// -// To avoid this, we use the type switch to assign a value to a single local variable -// and then call a function on it. -// The local variable is just a function reference so it doesn't allocate -// when converted to an interface{}. -// -// A fair bit of experimentation went into this. -// See also: -// -// - https://github.com/uber-go/zap/pull/1301 -// - https://github.com/uber-go/zap/pull/1303 -// - https://github.com/uber-go/zap/pull/1304 -// - https://github.com/uber-go/zap/pull/1305 -// - https://github.com/uber-go/zap/pull/1308 -type anyFieldC[T any] func(string, T) Field - -func (f anyFieldC[T]) Any(key string, val any) Field { - v, _ := val.(T) - // val is guaranteed to be a T, except when it's nil. - return f(key, v) -} - // Any takes a key and an arbitrary value and chooses the best way to represent // them as a field, falling back to a reflection-based approach only if // necessary. @@ -476,138 +418,132 @@ func (f anyFieldC[T]) Any(key string, val any) Field { // them. To minimize surprises, []byte values are treated as binary blobs, byte // values are treated as uint8, and runes are always treated as integers. func Any(key string, value interface{}) Field { - var c interface{ Any(string, any) Field } - - switch value.(type) { + switch val := value.(type) { case zapcore.ObjectMarshaler: - c = anyFieldC[zapcore.ObjectMarshaler](Object) + return Object(key, val) case zapcore.ArrayMarshaler: - c = anyFieldC[zapcore.ArrayMarshaler](Array) - case []Field: - c = anyFieldC[[]Field](dictField) + return Array(key, val) case bool: - c = anyFieldC[bool](Bool) + return Bool(key, val) case *bool: - c = anyFieldC[*bool](Boolp) + return Boolp(key, val) case []bool: - c = anyFieldC[[]bool](Bools) + return Bools(key, val) case complex128: - c = anyFieldC[complex128](Complex128) + return Complex128(key, val) case *complex128: - c = anyFieldC[*complex128](Complex128p) + return Complex128p(key, val) case []complex128: - c = anyFieldC[[]complex128](Complex128s) + return Complex128s(key, val) case complex64: - c = anyFieldC[complex64](Complex64) + return Complex64(key, val) case *complex64: - c = anyFieldC[*complex64](Complex64p) + return Complex64p(key, val) case []complex64: - c = anyFieldC[[]complex64](Complex64s) + return Complex64s(key, val) case float64: - c = anyFieldC[float64](Float64) + return Float64(key, val) case *float64: - c = anyFieldC[*float64](Float64p) + return Float64p(key, val) case []float64: - c = anyFieldC[[]float64](Float64s) + return Float64s(key, val) case float32: - c = anyFieldC[float32](Float32) + return Float32(key, val) case *float32: - c = anyFieldC[*float32](Float32p) + return Float32p(key, val) case []float32: - c = anyFieldC[[]float32](Float32s) + return Float32s(key, val) case int: - c = anyFieldC[int](Int) + return Int(key, val) case *int: - c = anyFieldC[*int](Intp) + return Intp(key, val) case []int: - c = anyFieldC[[]int](Ints) + return Ints(key, val) case int64: - c = anyFieldC[int64](Int64) + return Int64(key, val) case *int64: - c = anyFieldC[*int64](Int64p) + return Int64p(key, val) case []int64: - c = anyFieldC[[]int64](Int64s) + return Int64s(key, val) case int32: - c = anyFieldC[int32](Int32) + return Int32(key, val) case *int32: - c = anyFieldC[*int32](Int32p) + return Int32p(key, val) case []int32: - c = anyFieldC[[]int32](Int32s) + return Int32s(key, val) case int16: - c = anyFieldC[int16](Int16) + return Int16(key, val) case *int16: - c = anyFieldC[*int16](Int16p) + return Int16p(key, val) case []int16: - c = anyFieldC[[]int16](Int16s) + return Int16s(key, val) case int8: - c = anyFieldC[int8](Int8) + return Int8(key, val) case *int8: - c = anyFieldC[*int8](Int8p) + return Int8p(key, val) case []int8: - c = anyFieldC[[]int8](Int8s) + return Int8s(key, val) case string: - c = anyFieldC[string](String) + return String(key, val) case *string: - c = anyFieldC[*string](Stringp) + return Stringp(key, val) case []string: - c = anyFieldC[[]string](Strings) + return Strings(key, val) case uint: - c = anyFieldC[uint](Uint) + return Uint(key, val) case *uint: - c = anyFieldC[*uint](Uintp) + return Uintp(key, val) case []uint: - c = anyFieldC[[]uint](Uints) + return Uints(key, val) case uint64: - c = anyFieldC[uint64](Uint64) + return Uint64(key, val) case *uint64: - c = anyFieldC[*uint64](Uint64p) + return Uint64p(key, val) case []uint64: - c = anyFieldC[[]uint64](Uint64s) + return Uint64s(key, val) case uint32: - c = anyFieldC[uint32](Uint32) + return Uint32(key, val) case *uint32: - c = anyFieldC[*uint32](Uint32p) + return Uint32p(key, val) case []uint32: - c = anyFieldC[[]uint32](Uint32s) + return Uint32s(key, val) case uint16: - c = anyFieldC[uint16](Uint16) + return Uint16(key, val) case *uint16: - c = anyFieldC[*uint16](Uint16p) + return Uint16p(key, val) case []uint16: - c = anyFieldC[[]uint16](Uint16s) + return Uint16s(key, val) case uint8: - c = anyFieldC[uint8](Uint8) + return Uint8(key, val) case *uint8: - c = anyFieldC[*uint8](Uint8p) + return Uint8p(key, val) case []byte: - c = anyFieldC[[]byte](Binary) + return Binary(key, val) case uintptr: - c = anyFieldC[uintptr](Uintptr) + return Uintptr(key, val) case *uintptr: - c = anyFieldC[*uintptr](Uintptrp) + return Uintptrp(key, val) case []uintptr: - c = anyFieldC[[]uintptr](Uintptrs) + return Uintptrs(key, val) case time.Time: - c = anyFieldC[time.Time](Time) + return Time(key, val) case *time.Time: - c = anyFieldC[*time.Time](Timep) + return Timep(key, val) case []time.Time: - c = anyFieldC[[]time.Time](Times) + return Times(key, val) case time.Duration: - c = anyFieldC[time.Duration](Duration) + return Duration(key, val) case *time.Duration: - c = anyFieldC[*time.Duration](Durationp) + return Durationp(key, val) case []time.Duration: - c = anyFieldC[[]time.Duration](Durations) + return Durations(key, val) case error: - c = anyFieldC[error](NamedError) + return NamedError(key, val) case []error: - c = anyFieldC[[]error](Errors) + return Errors(key, val) case fmt.Stringer: - c = anyFieldC[fmt.Stringer](Stringer) + return Stringer(key, val) default: - c = anyFieldC[any](Reflect) + return Reflect(key, val) } - - return c.Any(key, value) } diff --git a/vendor/go.uber.org/zap/http_handler.go b/vendor/go.uber.org/zap/http_handler.go index 2be8f6515..632b6831a 100644 --- a/vendor/go.uber.org/zap/http_handler.go +++ b/vendor/go.uber.org/zap/http_handler.go @@ -69,13 +69,6 @@ import ( // // curl -X PUT localhost:8080/log/level -H "Content-Type: application/json" -d '{"level":"debug"}' func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if err := lvl.serveHTTP(w, r); err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, "internal error: %v", err) - } -} - -func (lvl AtomicLevel) serveHTTP(w http.ResponseWriter, r *http.Request) error { type errorResponse struct { Error string `json:"error"` } @@ -87,20 +80,19 @@ func (lvl AtomicLevel) serveHTTP(w http.ResponseWriter, r *http.Request) error { switch r.Method { case http.MethodGet: - return enc.Encode(payload{Level: lvl.Level()}) - + enc.Encode(payload{Level: lvl.Level()}) case http.MethodPut: requestedLvl, err := decodePutRequest(r.Header.Get("Content-Type"), r) if err != nil { w.WriteHeader(http.StatusBadRequest) - return enc.Encode(errorResponse{Error: err.Error()}) + enc.Encode(errorResponse{Error: err.Error()}) + return } lvl.SetLevel(requestedLvl) - return enc.Encode(payload{Level: lvl.Level()}) - + enc.Encode(payload{Level: lvl.Level()}) default: w.WriteHeader(http.StatusMethodNotAllowed) - return enc.Encode(errorResponse{ + enc.Encode(errorResponse{ Error: "Only GET and PUT are supported.", }) } @@ -137,4 +129,5 @@ func decodePutJSON(body io.Reader) (zapcore.Level, error) { return 0, errors.New("must specify logging level") } return *pld.Level, nil + } diff --git a/vendor/go.uber.org/zap/internal/level_enabler.go b/vendor/go.uber.org/zap/internal/level_enabler.go index 40bfed81e..5f3e3f1b9 100644 --- a/vendor/go.uber.org/zap/internal/level_enabler.go +++ b/vendor/go.uber.org/zap/internal/level_enabler.go @@ -18,8 +18,6 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -// Package internal and its subpackages hold types and functionality -// that are not part of Zap's public API. package internal import "go.uber.org/zap/zapcore" diff --git a/vendor/go.uber.org/zap/internal/pool/pool.go b/vendor/go.uber.org/zap/internal/pool/pool.go deleted file mode 100644 index 60e9d2c43..000000000 --- a/vendor/go.uber.org/zap/internal/pool/pool.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2023 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// Package pool provides internal pool utilities. -package pool - -import ( - "sync" -) - -// A Pool is a generic wrapper around [sync.Pool] to provide strongly-typed -// object pooling. -// -// Note that SA6002 (ref: https://staticcheck.io/docs/checks/#SA6002) will -// not be detected, so all internal pool use must take care to only store -// pointer types. -type Pool[T any] struct { - pool sync.Pool -} - -// New returns a new [Pool] for T, and will use fn to construct new Ts when -// the pool is empty. -func New[T any](fn func() T) *Pool[T] { - return &Pool[T]{ - pool: sync.Pool{ - New: func() any { - return fn() - }, - }, - } -} - -// Get gets a T from the pool, or creates a new one if the pool is empty. -func (p *Pool[T]) Get() T { - return p.pool.Get().(T) -} - -// Put returns x into the pool. -func (p *Pool[T]) Put(x T) { - p.pool.Put(x) -} diff --git a/vendor/go.uber.org/zap/level.go b/vendor/go.uber.org/zap/level.go index 155b208bd..db951e19a 100644 --- a/vendor/go.uber.org/zap/level.go +++ b/vendor/go.uber.org/zap/level.go @@ -21,8 +21,7 @@ package zap import ( - "sync/atomic" - + "go.uber.org/atomic" "go.uber.org/zap/internal" "go.uber.org/zap/zapcore" ) @@ -77,9 +76,9 @@ var _ internal.LeveledEnabler = AtomicLevel{} // NewAtomicLevel creates an AtomicLevel with InfoLevel and above logging // enabled. func NewAtomicLevel() AtomicLevel { - lvl := AtomicLevel{l: new(atomic.Int32)} - lvl.l.Store(int32(InfoLevel)) - return lvl + return AtomicLevel{ + l: atomic.NewInt32(int32(InfoLevel)), + } } // NewAtomicLevelAt is a convenience function that creates an AtomicLevel diff --git a/vendor/go.uber.org/zap/logger.go b/vendor/go.uber.org/zap/logger.go index 6205fe48a..cd44030d1 100644 --- a/vendor/go.uber.org/zap/logger.go +++ b/vendor/go.uber.org/zap/logger.go @@ -27,7 +27,6 @@ import ( "strings" "go.uber.org/zap/internal/bufferpool" - "go.uber.org/zap/internal/stacktrace" "go.uber.org/zap/zapcore" ) @@ -174,8 +173,7 @@ func (log *Logger) WithOptions(opts ...Option) *Logger { } // With creates a child logger and adds structured context to it. Fields added -// to the child don't affect the parent, and vice versa. Any fields that -// require evaluation (such as Objects) are evaluated upon invocation of With. +// to the child don't affect the parent, and vice versa. func (log *Logger) With(fields ...Field) *Logger { if len(fields) == 0 { return log @@ -185,28 +183,6 @@ func (log *Logger) With(fields ...Field) *Logger { return l } -// WithLazy creates a child logger and adds structured context to it lazily. -// -// The fields are evaluated only if the logger is further chained with [With] -// or is written to with any of the log level methods. -// Until that occurs, the logger may retain references to objects inside the fields, -// and logging will reflect the state of an object at the time of logging, -// not the time of WithLazy(). -// -// WithLazy provides a worthwhile performance optimization for contextual loggers -// when the likelihood of using the child logger is low, -// such as error paths and rarely taken branches. -// -// Similar to [With], fields added to the child don't affect the parent, and vice versa. -func (log *Logger) WithLazy(fields ...Field) *Logger { - if len(fields) == 0 { - return log - } - return log.WithOptions(WrapCore(func(core zapcore.Core) zapcore.Core { - return zapcore.NewLazyWith(core, fields) - })) -} - // Level reports the minimum enabled level for this logger. // // For NopLoggers, this is [zapcore.InvalidLevel]. @@ -223,8 +199,6 @@ func (log *Logger) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { // Log logs a message at the specified level. The message includes any fields // passed at the log site, as well as any fields accumulated on the logger. -// Any Fields that require evaluation (such as Objects) are evaluated upon -// invocation of Log. func (log *Logger) Log(lvl zapcore.Level, msg string, fields ...Field) { if ce := log.check(lvl, msg); ce != nil { ce.Write(fields...) @@ -307,15 +281,9 @@ func (log *Logger) Core() zapcore.Core { return log.core } -// Name returns the Logger's underlying name, -// or an empty string if the logger is unnamed. -func (log *Logger) Name() string { - return log.name -} - func (log *Logger) clone() *Logger { - clone := *log - return &clone + copy := *log + return © } func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { @@ -386,17 +354,17 @@ func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { // Adding the caller or stack trace requires capturing the callers of // this function. We'll share information between these two. - stackDepth := stacktrace.First + stackDepth := stacktraceFirst if addStack { - stackDepth = stacktrace.Full + stackDepth = stacktraceFull } - stack := stacktrace.Capture(log.callerSkip+callerSkipOffset, stackDepth) + stack := captureStacktrace(log.callerSkip+callerSkipOffset, stackDepth) defer stack.Free() if stack.Count() == 0 { if log.addCaller { fmt.Fprintf(log.errorOutput, "%v Logger.check error: failed to get caller\n", ent.Time.UTC()) - _ = log.errorOutput.Sync() + log.errorOutput.Sync() } return ce } @@ -417,7 +385,7 @@ func (log *Logger) check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { buffer := bufferpool.Get() defer buffer.Free() - stackfmt := stacktrace.NewFormatter(buffer) + stackfmt := newStackFormatter(buffer) // We've already extracted the first frame, so format that // separately and defer to stackfmt for the rest. diff --git a/vendor/go.uber.org/zap/sink.go b/vendor/go.uber.org/zap/sink.go index 499772a00..478c9a10f 100644 --- a/vendor/go.uber.org/zap/sink.go +++ b/vendor/go.uber.org/zap/sink.go @@ -66,8 +66,7 @@ func newSinkRegistry() *sinkRegistry { factories: make(map[string]func(*url.URL) (Sink, error)), openFile: os.OpenFile, } - // Infallible operation: the registry is empty, so we can't have a conflict. - _ = sr.RegisterSink(schemeFile, sr.newFileSinkFromURL) + sr.RegisterSink(schemeFile, sr.newFileSinkFromURL) return sr } @@ -155,7 +154,7 @@ func (sr *sinkRegistry) newFileSinkFromPath(path string) (Sink, error) { case "stderr": return nopCloserSink{os.Stderr}, nil } - return sr.openFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666) + return sr.openFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) } func normalizeScheme(s string) (string, error) { diff --git a/vendor/go.uber.org/zap/internal/stacktrace/stack.go b/vendor/go.uber.org/zap/stacktrace.go similarity index 73% rename from vendor/go.uber.org/zap/internal/stacktrace/stack.go rename to vendor/go.uber.org/zap/stacktrace.go index 82af7551f..817a3bde8 100644 --- a/vendor/go.uber.org/zap/internal/stacktrace/stack.go +++ b/vendor/go.uber.org/zap/stacktrace.go @@ -1,4 +1,4 @@ -// Copyright (c) 2023 Uber Technologies, Inc. +// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -18,26 +18,25 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -// Package stacktrace provides support for gathering stack traces -// efficiently. -package stacktrace +package zap import ( "runtime" + "sync" "go.uber.org/zap/buffer" "go.uber.org/zap/internal/bufferpool" - "go.uber.org/zap/internal/pool" ) -var _stackPool = pool.New(func() *Stack { - return &Stack{ - storage: make([]uintptr, 64), - } -}) +var _stacktracePool = sync.Pool{ + New: func() interface{} { + return &stacktrace{ + storage: make([]uintptr, 64), + } + }, +} -// Stack is a captured stack trace. -type Stack struct { +type stacktrace struct { pcs []uintptr // program counters; always a subslice of storage frames *runtime.Frames @@ -51,30 +50,30 @@ type Stack struct { storage []uintptr } -// Depth specifies how deep of a stack trace should be captured. -type Depth int +// stacktraceDepth specifies how deep of a stack trace should be captured. +type stacktraceDepth int const ( - // First captures only the first frame. - First Depth = iota + // stacktraceFirst captures only the first frame. + stacktraceFirst stacktraceDepth = iota - // Full captures the entire call stack, allocating more + // stacktraceFull captures the entire call stack, allocating more // storage for it if needed. - Full + stacktraceFull ) -// Capture captures a stack trace of the specified depth, skipping +// captureStacktrace captures a stack trace of the specified depth, skipping // the provided number of frames. skip=0 identifies the caller of -// Capture. +// captureStacktrace. // // The caller must call Free on the returned stacktrace after using it. -func Capture(skip int, depth Depth) *Stack { - stack := _stackPool.Get() +func captureStacktrace(skip int, depth stacktraceDepth) *stacktrace { + stack := _stacktracePool.Get().(*stacktrace) switch depth { - case First: + case stacktraceFirst: stack.pcs = stack.storage[:1] - case Full: + case stacktraceFull: stack.pcs = stack.storage } @@ -88,7 +87,7 @@ func Capture(skip int, depth Depth) *Stack { // runtime.Callers truncates the recorded stacktrace if there is no // room in the provided slice. For the full stack trace, keep expanding // storage until there are fewer frames than there is room. - if depth == Full { + if depth == stacktraceFull { pcs := stack.pcs for numFrames == len(pcs) { pcs = make([]uintptr, len(pcs)*2) @@ -110,54 +109,50 @@ func Capture(skip int, depth Depth) *Stack { // Free releases resources associated with this stacktrace // and returns it back to the pool. -func (st *Stack) Free() { +func (st *stacktrace) Free() { st.frames = nil st.pcs = nil - _stackPool.Put(st) + _stacktracePool.Put(st) } // Count reports the total number of frames in this stacktrace. // Count DOES NOT change as Next is called. -func (st *Stack) Count() int { +func (st *stacktrace) Count() int { return len(st.pcs) } // Next returns the next frame in the stack trace, // and a boolean indicating whether there are more after it. -func (st *Stack) Next() (_ runtime.Frame, more bool) { +func (st *stacktrace) Next() (_ runtime.Frame, more bool) { return st.frames.Next() } -// Take returns a string representation of the current stacktrace. -// -// skip is the number of frames to skip before recording the stack trace. -// skip=0 identifies the caller of Take. -func Take(skip int) string { - stack := Capture(skip+1, Full) +func takeStacktrace(skip int) string { + stack := captureStacktrace(skip+1, stacktraceFull) defer stack.Free() buffer := bufferpool.Get() defer buffer.Free() - stackfmt := NewFormatter(buffer) + stackfmt := newStackFormatter(buffer) stackfmt.FormatStack(stack) return buffer.String() } -// Formatter formats a stack trace into a readable string representation. -type Formatter struct { +// stackFormatter formats a stack trace into a readable string representation. +type stackFormatter struct { b *buffer.Buffer nonEmpty bool // whehther we've written at least one frame already } -// NewFormatter builds a new Formatter. -func NewFormatter(b *buffer.Buffer) Formatter { - return Formatter{b: b} +// newStackFormatter builds a new stackFormatter. +func newStackFormatter(b *buffer.Buffer) stackFormatter { + return stackFormatter{b: b} } // FormatStack formats all remaining frames in the provided stacktrace -- minus // the final runtime.main/runtime.goexit frame. -func (sf *Formatter) FormatStack(stack *Stack) { +func (sf *stackFormatter) FormatStack(stack *stacktrace) { // Note: On the last iteration, frames.Next() returns false, with a valid // frame, but we ignore this frame. The last frame is a runtime frame which // adds noise, since it's only either runtime.main or runtime.goexit. @@ -167,7 +162,7 @@ func (sf *Formatter) FormatStack(stack *Stack) { } // FormatFrame formats the given frame. -func (sf *Formatter) FormatFrame(frame runtime.Frame) { +func (sf *stackFormatter) FormatFrame(frame runtime.Frame) { if sf.nonEmpty { sf.b.AppendByte('\n') } diff --git a/vendor/go.uber.org/zap/sugar.go b/vendor/go.uber.org/zap/sugar.go index 00ac5fe3a..ac387b3e4 100644 --- a/vendor/go.uber.org/zap/sugar.go +++ b/vendor/go.uber.org/zap/sugar.go @@ -122,88 +122,74 @@ func (s *SugaredLogger) Level() zapcore.Level { return zapcore.LevelOf(s.base.core) } -// Debug logs the provided arguments at [DebugLevel]. -// Spaces are added between arguments when neither is a string. +// Debug uses fmt.Sprint to construct and log a message. func (s *SugaredLogger) Debug(args ...interface{}) { s.log(DebugLevel, "", args, nil) } -// Info logs the provided arguments at [InfoLevel]. -// Spaces are added between arguments when neither is a string. +// Info uses fmt.Sprint to construct and log a message. func (s *SugaredLogger) Info(args ...interface{}) { s.log(InfoLevel, "", args, nil) } -// Warn logs the provided arguments at [WarnLevel]. -// Spaces are added between arguments when neither is a string. +// Warn uses fmt.Sprint to construct and log a message. func (s *SugaredLogger) Warn(args ...interface{}) { s.log(WarnLevel, "", args, nil) } -// Error logs the provided arguments at [ErrorLevel]. -// Spaces are added between arguments when neither is a string. +// Error uses fmt.Sprint to construct and log a message. func (s *SugaredLogger) Error(args ...interface{}) { s.log(ErrorLevel, "", args, nil) } -// DPanic logs the provided arguments at [DPanicLevel]. -// In development, the logger then panics. (See [DPanicLevel] for details.) -// Spaces are added between arguments when neither is a string. +// DPanic uses fmt.Sprint to construct and log a message. In development, the +// logger then panics. (See DPanicLevel for details.) func (s *SugaredLogger) DPanic(args ...interface{}) { s.log(DPanicLevel, "", args, nil) } -// Panic constructs a message with the provided arguments and panics. -// Spaces are added between arguments when neither is a string. +// Panic uses fmt.Sprint to construct and log a message, then panics. func (s *SugaredLogger) Panic(args ...interface{}) { s.log(PanicLevel, "", args, nil) } -// Fatal constructs a message with the provided arguments and calls os.Exit. -// Spaces are added between arguments when neither is a string. +// Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit. func (s *SugaredLogger) Fatal(args ...interface{}) { s.log(FatalLevel, "", args, nil) } -// Debugf formats the message according to the format specifier -// and logs it at [DebugLevel]. +// Debugf uses fmt.Sprintf to log a templated message. func (s *SugaredLogger) Debugf(template string, args ...interface{}) { s.log(DebugLevel, template, args, nil) } -// Infof formats the message according to the format specifier -// and logs it at [InfoLevel]. +// Infof uses fmt.Sprintf to log a templated message. func (s *SugaredLogger) Infof(template string, args ...interface{}) { s.log(InfoLevel, template, args, nil) } -// Warnf formats the message according to the format specifier -// and logs it at [WarnLevel]. +// Warnf uses fmt.Sprintf to log a templated message. func (s *SugaredLogger) Warnf(template string, args ...interface{}) { s.log(WarnLevel, template, args, nil) } -// Errorf formats the message according to the format specifier -// and logs it at [ErrorLevel]. +// Errorf uses fmt.Sprintf to log a templated message. func (s *SugaredLogger) Errorf(template string, args ...interface{}) { s.log(ErrorLevel, template, args, nil) } -// DPanicf formats the message according to the format specifier -// and logs it at [DPanicLevel]. -// In development, the logger then panics. (See [DPanicLevel] for details.) +// DPanicf uses fmt.Sprintf to log a templated message. In development, the +// logger then panics. (See DPanicLevel for details.) func (s *SugaredLogger) DPanicf(template string, args ...interface{}) { s.log(DPanicLevel, template, args, nil) } -// Panicf formats the message according to the format specifier -// and panics. +// Panicf uses fmt.Sprintf to log a templated message, then panics. func (s *SugaredLogger) Panicf(template string, args ...interface{}) { s.log(PanicLevel, template, args, nil) } -// Fatalf formats the message according to the format specifier -// and calls os.Exit. +// Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit. func (s *SugaredLogger) Fatalf(template string, args ...interface{}) { s.log(FatalLevel, template, args, nil) } @@ -255,45 +241,38 @@ func (s *SugaredLogger) Fatalw(msg string, keysAndValues ...interface{}) { s.log(FatalLevel, msg, nil, keysAndValues) } -// Debugln logs a message at [DebugLevel]. -// Spaces are always added between arguments. +// Debugln uses fmt.Sprintln to construct and log a message. func (s *SugaredLogger) Debugln(args ...interface{}) { s.logln(DebugLevel, args, nil) } -// Infoln logs a message at [InfoLevel]. -// Spaces are always added between arguments. +// Infoln uses fmt.Sprintln to construct and log a message. func (s *SugaredLogger) Infoln(args ...interface{}) { s.logln(InfoLevel, args, nil) } -// Warnln logs a message at [WarnLevel]. -// Spaces are always added between arguments. +// Warnln uses fmt.Sprintln to construct and log a message. func (s *SugaredLogger) Warnln(args ...interface{}) { s.logln(WarnLevel, args, nil) } -// Errorln logs a message at [ErrorLevel]. -// Spaces are always added between arguments. +// Errorln uses fmt.Sprintln to construct and log a message. func (s *SugaredLogger) Errorln(args ...interface{}) { s.logln(ErrorLevel, args, nil) } -// DPanicln logs a message at [DPanicLevel]. -// In development, the logger then panics. (See [DPanicLevel] for details.) -// Spaces are always added between arguments. +// DPanicln uses fmt.Sprintln to construct and log a message. In development, the +// logger then panics. (See DPanicLevel for details.) func (s *SugaredLogger) DPanicln(args ...interface{}) { s.logln(DPanicLevel, args, nil) } -// Panicln logs a message at [PanicLevel] and panics. -// Spaces are always added between arguments. +// Panicln uses fmt.Sprintln to construct and log a message, then panics. func (s *SugaredLogger) Panicln(args ...interface{}) { s.logln(PanicLevel, args, nil) } -// Fatalln logs a message at [FatalLevel] and calls os.Exit. -// Spaces are always added between arguments. +// Fatalln uses fmt.Sprintln to construct and log a message, then calls os.Exit. func (s *SugaredLogger) Fatalln(args ...interface{}) { s.logln(FatalLevel, args, nil) } diff --git a/vendor/go.uber.org/zap/writer.go b/vendor/go.uber.org/zap/writer.go index 06768c679..f08728e1e 100644 --- a/vendor/go.uber.org/zap/writer.go +++ b/vendor/go.uber.org/zap/writer.go @@ -48,21 +48,21 @@ import ( // os.Stdout and os.Stderr. When specified without a scheme, relative file // paths also work. func Open(paths ...string) (zapcore.WriteSyncer, func(), error) { - writers, closeAll, err := open(paths) + writers, close, err := open(paths) if err != nil { return nil, nil, err } writer := CombineWriteSyncers(writers...) - return writer, closeAll, nil + return writer, close, nil } func open(paths []string) ([]zapcore.WriteSyncer, func(), error) { writers := make([]zapcore.WriteSyncer, 0, len(paths)) closers := make([]io.Closer, 0, len(paths)) - closeAll := func() { + close := func() { for _, c := range closers { - _ = c.Close() + c.Close() } } @@ -77,11 +77,11 @@ func open(paths []string) ([]zapcore.WriteSyncer, func(), error) { closers = append(closers, sink) } if openErr != nil { - closeAll() + close() return nil, nil, openErr } - return writers, closeAll, nil + return writers, close, nil } // CombineWriteSyncers is a utility that combines multiple WriteSyncers into a diff --git a/vendor/go.uber.org/zap/zapcore/console_encoder.go b/vendor/go.uber.org/zap/zapcore/console_encoder.go index 8ca0bfaf5..1aa5dc364 100644 --- a/vendor/go.uber.org/zap/zapcore/console_encoder.go +++ b/vendor/go.uber.org/zap/zapcore/console_encoder.go @@ -22,20 +22,20 @@ package zapcore import ( "fmt" + "sync" "go.uber.org/zap/buffer" "go.uber.org/zap/internal/bufferpool" - "go.uber.org/zap/internal/pool" ) -var _sliceEncoderPool = pool.New(func() *sliceArrayEncoder { - return &sliceArrayEncoder{ - elems: make([]interface{}, 0, 2), - } -}) +var _sliceEncoderPool = sync.Pool{ + New: func() interface{} { + return &sliceArrayEncoder{elems: make([]interface{}, 0, 2)} + }, +} func getSliceEncoder() *sliceArrayEncoder { - return _sliceEncoderPool.Get() + return _sliceEncoderPool.Get().(*sliceArrayEncoder) } func putSliceEncoder(e *sliceArrayEncoder) { diff --git a/vendor/go.uber.org/zap/zapcore/core.go b/vendor/go.uber.org/zap/zapcore/core.go index 776e93f6f..9dfd64051 100644 --- a/vendor/go.uber.org/zap/zapcore/core.go +++ b/vendor/go.uber.org/zap/zapcore/core.go @@ -102,9 +102,9 @@ func (c *ioCore) Write(ent Entry, fields []Field) error { return err } if ent.Level > ErrorLevel { - // Since we may be crashing the program, sync the output. - // Ignore Sync errors, pending a clean solution to issue #370. - _ = c.Sync() + // Since we may be crashing the program, sync the output. Ignore Sync + // errors, pending a clean solution to issue #370. + c.Sync() } return nil } diff --git a/vendor/go.uber.org/zap/zapcore/entry.go b/vendor/go.uber.org/zap/zapcore/entry.go index 459a5d7ce..9d326e95e 100644 --- a/vendor/go.uber.org/zap/zapcore/entry.go +++ b/vendor/go.uber.org/zap/zapcore/entry.go @@ -24,23 +24,25 @@ import ( "fmt" "runtime" "strings" + "sync" "time" "go.uber.org/multierr" "go.uber.org/zap/internal/bufferpool" "go.uber.org/zap/internal/exit" - "go.uber.org/zap/internal/pool" ) -var _cePool = pool.New(func() *CheckedEntry { - // Pre-allocate some space for cores. - return &CheckedEntry{ - cores: make([]Core, 4), - } -}) +var ( + _cePool = sync.Pool{New: func() interface{} { + // Pre-allocate some space for cores. + return &CheckedEntry{ + cores: make([]Core, 4), + } + }} +) func getCheckedEntry() *CheckedEntry { - ce := _cePool.Get() + ce := _cePool.Get().(*CheckedEntry) ce.reset() return ce } @@ -242,7 +244,7 @@ func (ce *CheckedEntry) Write(fields ...Field) { // CheckedEntry is being used after it was returned to the pool, // the message may be an amalgamation from multiple call sites. fmt.Fprintf(ce.ErrorOutput, "%v Unsafe CheckedEntry re-use near Entry %+v.\n", ce.Time, ce.Entry) - _ = ce.ErrorOutput.Sync() // ignore error + ce.ErrorOutput.Sync() } return } @@ -254,7 +256,7 @@ func (ce *CheckedEntry) Write(fields ...Field) { } if err != nil && ce.ErrorOutput != nil { fmt.Fprintf(ce.ErrorOutput, "%v write error: %v\n", ce.Time, err) - _ = ce.ErrorOutput.Sync() // ignore error + ce.ErrorOutput.Sync() } hook := ce.after diff --git a/vendor/go.uber.org/zap/zapcore/error.go b/vendor/go.uber.org/zap/zapcore/error.go index c40df1326..06359907a 100644 --- a/vendor/go.uber.org/zap/zapcore/error.go +++ b/vendor/go.uber.org/zap/zapcore/error.go @@ -23,8 +23,7 @@ package zapcore import ( "fmt" "reflect" - - "go.uber.org/zap/internal/pool" + "sync" ) // Encodes the given error into fields of an object. A field with the given @@ -98,18 +97,15 @@ func (errs errArray) MarshalLogArray(arr ArrayEncoder) error { } el := newErrArrayElem(errs[i]) - err := arr.AppendObject(el) + arr.AppendObject(el) el.Free() - if err != nil { - return err - } } return nil } -var _errArrayElemPool = pool.New(func() *errArrayElem { +var _errArrayElemPool = sync.Pool{New: func() interface{} { return &errArrayElem{} -}) +}} // Encodes any error into a {"error": ...} re-using the same errors logic. // @@ -117,7 +113,7 @@ var _errArrayElemPool = pool.New(func() *errArrayElem { type errArrayElem struct{ err error } func newErrArrayElem(err error) *errArrayElem { - e := _errArrayElemPool.Get() + e := _errArrayElemPool.Get().(*errArrayElem) e.err = err return e } diff --git a/vendor/go.uber.org/zap/zapcore/json_encoder.go b/vendor/go.uber.org/zap/zapcore/json_encoder.go index c8ab86979..3921c5cd3 100644 --- a/vendor/go.uber.org/zap/zapcore/json_encoder.go +++ b/vendor/go.uber.org/zap/zapcore/json_encoder.go @@ -23,20 +23,24 @@ package zapcore import ( "encoding/base64" "math" + "sync" "time" "unicode/utf8" "go.uber.org/zap/buffer" "go.uber.org/zap/internal/bufferpool" - "go.uber.org/zap/internal/pool" ) // For JSON-escaping; see jsonEncoder.safeAddString below. const _hex = "0123456789abcdef" -var _jsonPool = pool.New(func() *jsonEncoder { +var _jsonPool = sync.Pool{New: func() interface{} { return &jsonEncoder{} -}) +}} + +func getJSONEncoder() *jsonEncoder { + return _jsonPool.Get().(*jsonEncoder) +} func putJSONEncoder(enc *jsonEncoder) { if enc.reflectBuf != nil { @@ -350,7 +354,7 @@ func (enc *jsonEncoder) Clone() Encoder { } func (enc *jsonEncoder) clone() *jsonEncoder { - clone := _jsonPool.Get() + clone := getJSONEncoder() clone.EncoderConfig = enc.EncoderConfig clone.spaced = enc.spaced clone.openNamespaces = enc.openNamespaces @@ -486,98 +490,73 @@ func (enc *jsonEncoder) appendFloat(val float64, bitSize int) { // Unlike the standard library's encoder, it doesn't attempt to protect the // user from browser vulnerabilities or JSONP-related problems. func (enc *jsonEncoder) safeAddString(s string) { - safeAppendStringLike( - (*buffer.Buffer).AppendString, - utf8.DecodeRuneInString, - enc.buf, - s, - ) + for i := 0; i < len(s); { + if enc.tryAddRuneSelf(s[i]) { + i++ + continue + } + r, size := utf8.DecodeRuneInString(s[i:]) + if enc.tryAddRuneError(r, size) { + i++ + continue + } + enc.buf.AppendString(s[i : i+size]) + i += size + } } // safeAddByteString is no-alloc equivalent of safeAddString(string(s)) for s []byte. func (enc *jsonEncoder) safeAddByteString(s []byte) { - safeAppendStringLike( - (*buffer.Buffer).AppendBytes, - utf8.DecodeRune, - enc.buf, - s, - ) -} - -// safeAppendStringLike is a generic implementation of safeAddString and safeAddByteString. -// It appends a string or byte slice to the buffer, escaping all special characters. -func safeAppendStringLike[S []byte | string]( - // appendTo appends this string-like object to the buffer. - appendTo func(*buffer.Buffer, S), - // decodeRune decodes the next rune from the string-like object - // and returns its value and width in bytes. - decodeRune func(S) (rune, int), - buf *buffer.Buffer, - s S, -) { - // The encoding logic below works by skipping over characters - // that can be safely copied as-is, - // until a character is found that needs special handling. - // At that point, we copy everything we've seen so far, - // and then handle that special character. - // - // last is the index of the last byte that was copied to the buffer. - last := 0 for i := 0; i < len(s); { - if s[i] >= utf8.RuneSelf { - // Character >= RuneSelf may be part of a multi-byte rune. - // They need to be decoded before we can decide how to handle them. - r, size := decodeRune(s[i:]) - if r != utf8.RuneError || size != 1 { - // No special handling required. - // Skip over this rune and continue. - i += size - continue - } - - // Invalid UTF-8 sequence. - // Replace it with the Unicode replacement character. - appendTo(buf, s[last:i]) - buf.AppendString(`\ufffd`) - + if enc.tryAddRuneSelf(s[i]) { i++ - last = i - } else { - // Character < RuneSelf is a single-byte UTF-8 rune. - if s[i] >= 0x20 && s[i] != '\\' && s[i] != '"' { - // No escaping necessary. - // Skip over this character and continue. - i++ - continue - } - - // This character needs to be escaped. - appendTo(buf, s[last:i]) - switch s[i] { - case '\\', '"': - buf.AppendByte('\\') - buf.AppendByte(s[i]) - case '\n': - buf.AppendByte('\\') - buf.AppendByte('n') - case '\r': - buf.AppendByte('\\') - buf.AppendByte('r') - case '\t': - buf.AppendByte('\\') - buf.AppendByte('t') - default: - // Encode bytes < 0x20, except for the escape sequences above. - buf.AppendString(`\u00`) - buf.AppendByte(_hex[s[i]>>4]) - buf.AppendByte(_hex[s[i]&0xF]) - } - - i++ - last = i + continue } + r, size := utf8.DecodeRune(s[i:]) + if enc.tryAddRuneError(r, size) { + i++ + continue + } + enc.buf.Write(s[i : i+size]) + i += size } - - // add remaining - appendTo(buf, s[last:]) +} + +// tryAddRuneSelf appends b if it is valid UTF-8 character represented in a single byte. +func (enc *jsonEncoder) tryAddRuneSelf(b byte) bool { + if b >= utf8.RuneSelf { + return false + } + if 0x20 <= b && b != '\\' && b != '"' { + enc.buf.AppendByte(b) + return true + } + switch b { + case '\\', '"': + enc.buf.AppendByte('\\') + enc.buf.AppendByte(b) + case '\n': + enc.buf.AppendByte('\\') + enc.buf.AppendByte('n') + case '\r': + enc.buf.AppendByte('\\') + enc.buf.AppendByte('r') + case '\t': + enc.buf.AppendByte('\\') + enc.buf.AppendByte('t') + default: + // Encode bytes < 0x20, except for the escape sequences above. + enc.buf.AppendString(`\u00`) + enc.buf.AppendByte(_hex[b>>4]) + enc.buf.AppendByte(_hex[b&0xF]) + } + return true +} + +func (enc *jsonEncoder) tryAddRuneError(r rune, size int) bool { + if r == utf8.RuneError && size == 1 { + enc.buf.AppendString(`\ufffd`) + return true + } + return false } diff --git a/vendor/go.uber.org/zap/zapcore/lazy_with.go b/vendor/go.uber.org/zap/zapcore/lazy_with.go deleted file mode 100644 index 05288d6a8..000000000 --- a/vendor/go.uber.org/zap/zapcore/lazy_with.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2023 Uber Technologies, Inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -package zapcore - -import "sync" - -type lazyWithCore struct { - Core - sync.Once - fields []Field -} - -// NewLazyWith wraps a Core with a "lazy" Core that will only encode fields if -// the logger is written to (or is further chained in a lon-lazy manner). -func NewLazyWith(core Core, fields []Field) Core { - return &lazyWithCore{ - Core: core, - fields: fields, - } -} - -func (d *lazyWithCore) initOnce() { - d.Once.Do(func() { - d.Core = d.Core.With(d.fields) - }) -} - -func (d *lazyWithCore) With(fields []Field) Core { - d.initOnce() - return d.Core.With(fields) -} - -func (d *lazyWithCore) Check(e Entry, ce *CheckedEntry) *CheckedEntry { - d.initOnce() - return d.Core.Check(e, ce) -} diff --git a/vendor/go.uber.org/zap/zapcore/sampler.go b/vendor/go.uber.org/zap/zapcore/sampler.go index b7c093a4f..dc518055a 100644 --- a/vendor/go.uber.org/zap/zapcore/sampler.go +++ b/vendor/go.uber.org/zap/zapcore/sampler.go @@ -21,8 +21,9 @@ package zapcore import ( - "sync/atomic" "time" + + "go.uber.org/atomic" ) const ( @@ -65,16 +66,16 @@ func (c *counter) IncCheckReset(t time.Time, tick time.Duration) uint64 { tn := t.UnixNano() resetAfter := c.resetAt.Load() if resetAfter > tn { - return c.counter.Add(1) + return c.counter.Inc() } c.counter.Store(1) newResetAfter := tn + tick.Nanoseconds() - if !c.resetAt.CompareAndSwap(resetAfter, newResetAfter) { + if !c.resetAt.CAS(resetAfter, newResetAfter) { // We raced with another goroutine trying to reset, and it also reset // the counter to 1, so we need to reincrement the counter. - return c.counter.Add(1) + return c.counter.Inc() } return 1 diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_arm64.go b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.go index 5dfacbb98..94c71ac1a 100644 --- a/vendor/golang.org/x/crypto/chacha20/chacha_arm64.go +++ b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.go @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build gc && !purego -// +build gc,!purego +//go:build go1.11 && gc && !purego +// +build go1.11,gc,!purego package chacha20 diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_arm64.s b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.s index f1f66230d..63cae9e6f 100644 --- a/vendor/golang.org/x/crypto/chacha20/chacha_arm64.s +++ b/vendor/golang.org/x/crypto/chacha20/chacha_arm64.s @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build gc && !purego -// +build gc,!purego +//go:build go1.11 && gc && !purego +// +build go1.11,gc,!purego #include "textflag.h" diff --git a/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go b/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go index 02ff3d05e..025b49897 100644 --- a/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go +++ b/vendor/golang.org/x/crypto/chacha20/chacha_noasm.go @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build (!arm64 && !s390x && !ppc64le) || !gc || purego -// +build !arm64,!s390x,!ppc64le !gc purego +//go:build (!arm64 && !s390x && !ppc64le) || (arm64 && !go1.11) || !gc || purego +// +build !arm64,!s390x,!ppc64le arm64,!go1.11 !gc purego package chacha20 diff --git a/vendor/golang.org/x/crypto/cryptobyte/builder.go b/vendor/golang.org/x/crypto/cryptobyte/builder.go index cf254f5f1..c05ac7d16 100644 --- a/vendor/golang.org/x/crypto/cryptobyte/builder.go +++ b/vendor/golang.org/x/crypto/cryptobyte/builder.go @@ -95,11 +95,6 @@ func (b *Builder) AddUint32(v uint32) { b.add(byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) } -// AddUint48 appends a big-endian, 48-bit value to the byte string. -func (b *Builder) AddUint48(v uint64) { - b.add(byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) -} - // AddUint64 appends a big-endian, 64-bit value to the byte string. func (b *Builder) AddUint64(v uint64) { b.add(byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) diff --git a/vendor/golang.org/x/crypto/cryptobyte/string.go b/vendor/golang.org/x/crypto/cryptobyte/string.go index 10692a8a3..0531a3d6f 100644 --- a/vendor/golang.org/x/crypto/cryptobyte/string.go +++ b/vendor/golang.org/x/crypto/cryptobyte/string.go @@ -81,17 +81,6 @@ func (s *String) ReadUint32(out *uint32) bool { return true } -// ReadUint48 decodes a big-endian, 48-bit value into out and advances over it. -// It reports whether the read was successful. -func (s *String) ReadUint48(out *uint64) bool { - v := s.read(6) - if v == nil { - return false - } - *out = uint64(v[0])<<40 | uint64(v[1])<<32 | uint64(v[2])<<24 | uint64(v[3])<<16 | uint64(v[4])<<8 | uint64(v[5]) - return true -} - // ReadUint64 decodes a big-endian, 64-bit value into out and advances over it. // It reports whether the read was successful. func (s *String) ReadUint64(out *uint64) bool { diff --git a/vendor/golang.org/x/crypto/sha3/sha3.go b/vendor/golang.org/x/crypto/sha3/sha3.go index 4884d172a..fa182beb4 100644 --- a/vendor/golang.org/x/crypto/sha3/sha3.go +++ b/vendor/golang.org/x/crypto/sha3/sha3.go @@ -121,11 +121,11 @@ func (d *state) padAndPermute(dsbyte byte) { copyOut(d, d.buf) } -// Write absorbs more data into the hash's state. It panics if any -// output has already been read. +// Write absorbs more data into the hash's state. It produces an error +// if more data is written to the ShakeHash after writing func (d *state) Write(p []byte) (written int, err error) { if d.state != spongeAbsorbing { - panic("sha3: Write after Read") + panic("sha3: write to sponge after read") } if d.buf == nil { d.buf = d.storage.asBytes()[:0] @@ -182,16 +182,12 @@ func (d *state) Read(out []byte) (n int, err error) { } // Sum applies padding to the hash state and then squeezes out the desired -// number of output bytes. It panics if any output has already been read. +// number of output bytes. func (d *state) Sum(in []byte) []byte { - if d.state != spongeAbsorbing { - panic("sha3: Sum after Read") - } - // Make a copy of the original hash so that caller can keep writing // and summing. dup := d.clone() - hash := make([]byte, dup.outputLen, 64) // explicit cap to allow stack allocation + hash := make([]byte, dup.outputLen) dup.Read(hash) return append(in, hash...) } diff --git a/vendor/golang.org/x/crypto/sha3/sha3_s390x.go b/vendor/golang.org/x/crypto/sha3/sha3_s390x.go index ec26f147f..63a3edb4c 100644 --- a/vendor/golang.org/x/crypto/sha3/sha3_s390x.go +++ b/vendor/golang.org/x/crypto/sha3/sha3_s390x.go @@ -49,7 +49,7 @@ type asmState struct { buf []byte // care must be taken to ensure cap(buf) is a multiple of rate rate int // equivalent to block size storage [3072]byte // underlying storage for buf - outputLen int // output length for full security + outputLen int // output length if fixed, 0 if not function code // KIMD/KLMD function code state spongeDirection // whether the sponge is absorbing or squeezing } @@ -72,10 +72,8 @@ func newAsmState(function code) *asmState { s.outputLen = 64 case shake_128: s.rate = 168 - s.outputLen = 32 case shake_256: s.rate = 136 - s.outputLen = 64 default: panic("sha3: unrecognized function code") } @@ -110,7 +108,7 @@ func (s *asmState) resetBuf() { // It never returns an error. func (s *asmState) Write(b []byte) (int, error) { if s.state != spongeAbsorbing { - panic("sha3: Write after Read") + panic("sha3: write to sponge after read") } length := len(b) for len(b) > 0 { @@ -194,8 +192,8 @@ func (s *asmState) Read(out []byte) (n int, err error) { // Sum appends the current hash to b and returns the resulting slice. // It does not change the underlying hash state. func (s *asmState) Sum(b []byte) []byte { - if s.state != spongeAbsorbing { - panic("sha3: Sum after Read") + if s.outputLen == 0 { + panic("sha3: cannot call Sum on SHAKE functions") } // Copy the state to preserve the original. diff --git a/vendor/golang.org/x/crypto/sha3/shake.go b/vendor/golang.org/x/crypto/sha3/shake.go index bb6998402..d7be2954a 100644 --- a/vendor/golang.org/x/crypto/sha3/shake.go +++ b/vendor/golang.org/x/crypto/sha3/shake.go @@ -17,25 +17,26 @@ package sha3 import ( "encoding/binary" - "hash" "io" ) -// ShakeHash defines the interface to hash functions that support -// arbitrary-length output. When used as a plain [hash.Hash], it -// produces minimum-length outputs that provide full-strength generic -// security. +// ShakeHash defines the interface to hash functions that +// support arbitrary-length output. type ShakeHash interface { - hash.Hash + // Write absorbs more data into the hash's state. It panics if input is + // written to it after output has been read from it. + io.Writer // Read reads more output from the hash; reading affects the hash's // state. (ShakeHash.Read is thus very different from Hash.Sum) - // It never returns an error, but subsequent calls to Write or Sum - // will panic. + // It never returns an error. io.Reader // Clone returns a copy of the ShakeHash in its current state. Clone() ShakeHash + + // Reset resets the ShakeHash to its initial state. + Reset() } // cSHAKE specific context @@ -80,8 +81,8 @@ func leftEncode(value uint64) []byte { return b[i-1:] } -func newCShake(N, S []byte, rate, outputLen int, dsbyte byte) ShakeHash { - c := cshakeState{state: &state{rate: rate, outputLen: outputLen, dsbyte: dsbyte}} +func newCShake(N, S []byte, rate int, dsbyte byte) ShakeHash { + c := cshakeState{state: &state{rate: rate, dsbyte: dsbyte}} // leftEncode returns max 9 bytes c.initBlock = make([]byte, 0, 9*2+len(N)+len(S)) @@ -118,7 +119,7 @@ func NewShake128() ShakeHash { if h := newShake128Asm(); h != nil { return h } - return &state{rate: rate128, outputLen: 32, dsbyte: dsbyteShake} + return &state{rate: rate128, dsbyte: dsbyteShake} } // NewShake256 creates a new SHAKE256 variable-output-length ShakeHash. @@ -128,7 +129,7 @@ func NewShake256() ShakeHash { if h := newShake256Asm(); h != nil { return h } - return &state{rate: rate256, outputLen: 64, dsbyte: dsbyteShake} + return &state{rate: rate256, dsbyte: dsbyteShake} } // NewCShake128 creates a new instance of cSHAKE128 variable-output-length ShakeHash, @@ -141,7 +142,7 @@ func NewCShake128(N, S []byte) ShakeHash { if len(N) == 0 && len(S) == 0 { return NewShake128() } - return newCShake(N, S, rate128, 32, dsbyteCShake) + return newCShake(N, S, rate128, dsbyteCShake) } // NewCShake256 creates a new instance of cSHAKE256 variable-output-length ShakeHash, @@ -154,7 +155,7 @@ func NewCShake256(N, S []byte) ShakeHash { if len(N) == 0 && len(S) == 0 { return NewShake256() } - return newCShake(N, S, rate256, 64, dsbyteCShake) + return newCShake(N, S, rate256, dsbyteCShake) } // ShakeSum128 writes an arbitrary-length digest of data into hash. diff --git a/vendor/golang.org/x/exp/rand/exp.go b/vendor/golang.org/x/exp/rand/exp.go deleted file mode 100644 index 083867276..000000000 --- a/vendor/golang.org/x/exp/rand/exp.go +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rand - -import ( - "math" -) - -/* - * Exponential distribution - * - * See "The Ziggurat Method for Generating Random Variables" - * (Marsaglia & Tsang, 2000) - * http://www.jstatsoft.org/v05/i08/paper [pdf] - */ - -const ( - re = 7.69711747013104972 -) - -// ExpFloat64 returns an exponentially distributed float64 in the range -// (0, +math.MaxFloat64] with an exponential distribution whose rate parameter -// (lambda) is 1 and whose mean is 1/lambda (1). -// To produce a distribution with a different rate parameter, -// callers can adjust the output using: -// -// sample = ExpFloat64() / desiredRateParameter -func (r *Rand) ExpFloat64() float64 { - for { - j := r.Uint32() - i := j & 0xFF - x := float64(j) * float64(we[i]) - if j < ke[i] { - return x - } - if i == 0 { - return re - math.Log(r.Float64()) - } - if fe[i]+float32(r.Float64())*(fe[i-1]-fe[i]) < float32(math.Exp(-x)) { - return x - } - } -} - -var ke = [256]uint32{ - 0xe290a139, 0x0, 0x9beadebc, 0xc377ac71, 0xd4ddb990, - 0xde893fb8, 0xe4a8e87c, 0xe8dff16a, 0xebf2deab, 0xee49a6e8, - 0xf0204efd, 0xf19bdb8e, 0xf2d458bb, 0xf3da104b, 0xf4b86d78, - 0xf577ad8a, 0xf61de83d, 0xf6afb784, 0xf730a573, 0xf7a37651, - 0xf80a5bb6, 0xf867189d, 0xf8bb1b4f, 0xf9079062, 0xf94d70ca, - 0xf98d8c7d, 0xf9c8928a, 0xf9ff175b, 0xfa319996, 0xfa6085f8, - 0xfa8c3a62, 0xfab5084e, 0xfadb36c8, 0xfaff0410, 0xfb20a6ea, - 0xfb404fb4, 0xfb5e2951, 0xfb7a59e9, 0xfb95038c, 0xfbae44ba, - 0xfbc638d8, 0xfbdcf892, 0xfbf29a30, 0xfc0731df, 0xfc1ad1ed, - 0xfc2d8b02, 0xfc3f6c4d, 0xfc5083ac, 0xfc60ddd1, 0xfc708662, - 0xfc7f8810, 0xfc8decb4, 0xfc9bbd62, 0xfca9027c, 0xfcb5c3c3, - 0xfcc20864, 0xfccdd70a, 0xfcd935e3, 0xfce42ab0, 0xfceebace, - 0xfcf8eb3b, 0xfd02c0a0, 0xfd0c3f59, 0xfd156b7b, 0xfd1e48d6, - 0xfd26daff, 0xfd2f2552, 0xfd372af7, 0xfd3eeee5, 0xfd4673e7, - 0xfd4dbc9e, 0xfd54cb85, 0xfd5ba2f2, 0xfd62451b, 0xfd68b415, - 0xfd6ef1da, 0xfd750047, 0xfd7ae120, 0xfd809612, 0xfd8620b4, - 0xfd8b8285, 0xfd90bcf5, 0xfd95d15e, 0xfd9ac10b, 0xfd9f8d36, - 0xfda43708, 0xfda8bf9e, 0xfdad2806, 0xfdb17141, 0xfdb59c46, - 0xfdb9a9fd, 0xfdbd9b46, 0xfdc170f6, 0xfdc52bd8, 0xfdc8ccac, - 0xfdcc542d, 0xfdcfc30b, 0xfdd319ef, 0xfdd6597a, 0xfdd98245, - 0xfddc94e5, 0xfddf91e6, 0xfde279ce, 0xfde54d1f, 0xfde80c52, - 0xfdeab7de, 0xfded5034, 0xfdefd5be, 0xfdf248e3, 0xfdf4aa06, - 0xfdf6f984, 0xfdf937b6, 0xfdfb64f4, 0xfdfd818d, 0xfdff8dd0, - 0xfe018a08, 0xfe03767a, 0xfe05536c, 0xfe07211c, 0xfe08dfc9, - 0xfe0a8fab, 0xfe0c30fb, 0xfe0dc3ec, 0xfe0f48b1, 0xfe10bf76, - 0xfe122869, 0xfe1383b4, 0xfe14d17c, 0xfe1611e7, 0xfe174516, - 0xfe186b2a, 0xfe19843e, 0xfe1a9070, 0xfe1b8fd6, 0xfe1c8289, - 0xfe1d689b, 0xfe1e4220, 0xfe1f0f26, 0xfe1fcfbc, 0xfe2083ed, - 0xfe212bc3, 0xfe21c745, 0xfe225678, 0xfe22d95f, 0xfe234ffb, - 0xfe23ba4a, 0xfe241849, 0xfe2469f2, 0xfe24af3c, 0xfe24e81e, - 0xfe25148b, 0xfe253474, 0xfe2547c7, 0xfe254e70, 0xfe25485a, - 0xfe25356a, 0xfe251586, 0xfe24e88f, 0xfe24ae64, 0xfe2466e1, - 0xfe2411df, 0xfe23af34, 0xfe233eb4, 0xfe22c02c, 0xfe22336b, - 0xfe219838, 0xfe20ee58, 0xfe20358c, 0xfe1f6d92, 0xfe1e9621, - 0xfe1daef0, 0xfe1cb7ac, 0xfe1bb002, 0xfe1a9798, 0xfe196e0d, - 0xfe1832fd, 0xfe16e5fe, 0xfe15869d, 0xfe141464, 0xfe128ed3, - 0xfe10f565, 0xfe0f478c, 0xfe0d84b1, 0xfe0bac36, 0xfe09bd73, - 0xfe07b7b5, 0xfe059a40, 0xfe03644c, 0xfe011504, 0xfdfeab88, - 0xfdfc26e9, 0xfdf98629, 0xfdf6c83b, 0xfdf3ec01, 0xfdf0f04a, - 0xfdedd3d1, 0xfdea953d, 0xfde7331e, 0xfde3abe9, 0xfddffdfb, - 0xfddc2791, 0xfdd826cd, 0xfdd3f9a8, 0xfdcf9dfc, 0xfdcb1176, - 0xfdc65198, 0xfdc15bb3, 0xfdbc2ce2, 0xfdb6c206, 0xfdb117be, - 0xfdab2a63, 0xfda4f5fd, 0xfd9e7640, 0xfd97a67a, 0xfd908192, - 0xfd8901f2, 0xfd812182, 0xfd78d98e, 0xfd7022bb, 0xfd66f4ed, - 0xfd5d4732, 0xfd530f9c, 0xfd48432b, 0xfd3cd59a, 0xfd30b936, - 0xfd23dea4, 0xfd16349e, 0xfd07a7a3, 0xfcf8219b, 0xfce7895b, - 0xfcd5c220, 0xfcc2aadb, 0xfcae1d5e, 0xfc97ed4e, 0xfc7fe6d4, - 0xfc65ccf3, 0xfc495762, 0xfc2a2fc8, 0xfc07ee19, 0xfbe213c1, - 0xfbb8051a, 0xfb890078, 0xfb5411a5, 0xfb180005, 0xfad33482, - 0xfa839276, 0xfa263b32, 0xf9b72d1c, 0xf930a1a2, 0xf889f023, - 0xf7b577d2, 0xf69c650c, 0xf51530f0, 0xf2cb0e3c, 0xeeefb15d, - 0xe6da6ecf, -} -var we = [256]float32{ - 2.0249555e-09, 1.486674e-11, 2.4409617e-11, 3.1968806e-11, - 3.844677e-11, 4.4228204e-11, 4.9516443e-11, 5.443359e-11, - 5.905944e-11, 6.344942e-11, 6.7643814e-11, 7.1672945e-11, - 7.556032e-11, 7.932458e-11, 8.298079e-11, 8.654132e-11, - 9.0016515e-11, 9.3415074e-11, 9.674443e-11, 1.0001099e-10, - 1.03220314e-10, 1.06377254e-10, 1.09486115e-10, 1.1255068e-10, - 1.1557435e-10, 1.1856015e-10, 1.2151083e-10, 1.2442886e-10, - 1.2731648e-10, 1.3017575e-10, 1.3300853e-10, 1.3581657e-10, - 1.3860142e-10, 1.4136457e-10, 1.4410738e-10, 1.4683108e-10, - 1.4953687e-10, 1.5222583e-10, 1.54899e-10, 1.5755733e-10, - 1.6020171e-10, 1.6283301e-10, 1.6545203e-10, 1.6805951e-10, - 1.7065617e-10, 1.732427e-10, 1.7581973e-10, 1.7838787e-10, - 1.8094774e-10, 1.8349985e-10, 1.8604476e-10, 1.8858298e-10, - 1.9111498e-10, 1.9364126e-10, 1.9616223e-10, 1.9867835e-10, - 2.0119004e-10, 2.0369768e-10, 2.0620168e-10, 2.087024e-10, - 2.1120022e-10, 2.136955e-10, 2.1618855e-10, 2.1867974e-10, - 2.2116936e-10, 2.2365775e-10, 2.261452e-10, 2.2863202e-10, - 2.311185e-10, 2.3360494e-10, 2.360916e-10, 2.3857874e-10, - 2.4106667e-10, 2.4355562e-10, 2.4604588e-10, 2.485377e-10, - 2.5103128e-10, 2.5352695e-10, 2.560249e-10, 2.585254e-10, - 2.6102867e-10, 2.6353494e-10, 2.6604446e-10, 2.6855745e-10, - 2.7107416e-10, 2.7359479e-10, 2.761196e-10, 2.7864877e-10, - 2.8118255e-10, 2.8372119e-10, 2.8626485e-10, 2.888138e-10, - 2.9136826e-10, 2.939284e-10, 2.9649452e-10, 2.9906677e-10, - 3.016454e-10, 3.0423064e-10, 3.0682268e-10, 3.0942177e-10, - 3.1202813e-10, 3.1464195e-10, 3.1726352e-10, 3.19893e-10, - 3.2253064e-10, 3.251767e-10, 3.2783135e-10, 3.3049485e-10, - 3.3316744e-10, 3.3584938e-10, 3.3854083e-10, 3.4124212e-10, - 3.4395342e-10, 3.46675e-10, 3.4940711e-10, 3.5215003e-10, - 3.5490397e-10, 3.5766917e-10, 3.6044595e-10, 3.6323455e-10, - 3.660352e-10, 3.6884823e-10, 3.7167386e-10, 3.745124e-10, - 3.773641e-10, 3.802293e-10, 3.8310827e-10, 3.860013e-10, - 3.8890866e-10, 3.918307e-10, 3.9476775e-10, 3.9772008e-10, - 4.0068804e-10, 4.0367196e-10, 4.0667217e-10, 4.09689e-10, - 4.1272286e-10, 4.1577405e-10, 4.1884296e-10, 4.2192994e-10, - 4.250354e-10, 4.281597e-10, 4.313033e-10, 4.3446652e-10, - 4.3764986e-10, 4.408537e-10, 4.4407847e-10, 4.4732465e-10, - 4.5059267e-10, 4.5388301e-10, 4.571962e-10, 4.6053267e-10, - 4.6389292e-10, 4.6727755e-10, 4.70687e-10, 4.741219e-10, - 4.7758275e-10, 4.810702e-10, 4.845848e-10, 4.8812715e-10, - 4.9169796e-10, 4.9529775e-10, 4.989273e-10, 5.0258725e-10, - 5.0627835e-10, 5.100013e-10, 5.1375687e-10, 5.1754584e-10, - 5.21369e-10, 5.2522725e-10, 5.2912136e-10, 5.330522e-10, - 5.370208e-10, 5.4102806e-10, 5.45075e-10, 5.491625e-10, - 5.532918e-10, 5.5746385e-10, 5.616799e-10, 5.6594107e-10, - 5.7024857e-10, 5.746037e-10, 5.7900773e-10, 5.834621e-10, - 5.8796823e-10, 5.925276e-10, 5.971417e-10, 6.018122e-10, - 6.065408e-10, 6.113292e-10, 6.1617933e-10, 6.2109295e-10, - 6.260722e-10, 6.3111916e-10, 6.3623595e-10, 6.4142497e-10, - 6.4668854e-10, 6.5202926e-10, 6.5744976e-10, 6.6295286e-10, - 6.6854156e-10, 6.742188e-10, 6.79988e-10, 6.858526e-10, - 6.9181616e-10, 6.978826e-10, 7.04056e-10, 7.103407e-10, - 7.167412e-10, 7.2326256e-10, 7.2990985e-10, 7.366886e-10, - 7.4360473e-10, 7.5066453e-10, 7.5787476e-10, 7.6524265e-10, - 7.7277595e-10, 7.80483e-10, 7.883728e-10, 7.9645507e-10, - 8.047402e-10, 8.1323964e-10, 8.219657e-10, 8.309319e-10, - 8.401528e-10, 8.496445e-10, 8.594247e-10, 8.6951274e-10, - 8.799301e-10, 8.9070046e-10, 9.018503e-10, 9.134092e-10, - 9.254101e-10, 9.378904e-10, 9.508923e-10, 9.644638e-10, - 9.786603e-10, 9.935448e-10, 1.0091913e-09, 1.025686e-09, - 1.0431306e-09, 1.0616465e-09, 1.08138e-09, 1.1025096e-09, - 1.1252564e-09, 1.1498986e-09, 1.1767932e-09, 1.206409e-09, - 1.2393786e-09, 1.276585e-09, 1.3193139e-09, 1.3695435e-09, - 1.4305498e-09, 1.508365e-09, 1.6160854e-09, 1.7921248e-09, -} -var fe = [256]float32{ - 1, 0.9381437, 0.90046996, 0.87170434, 0.8477855, 0.8269933, - 0.8084217, 0.7915276, 0.77595687, 0.7614634, 0.7478686, - 0.7350381, 0.72286767, 0.71127474, 0.70019263, 0.6895665, - 0.67935055, 0.6695063, 0.66000086, 0.65080583, 0.6418967, - 0.63325197, 0.6248527, 0.6166822, 0.60872537, 0.60096896, - 0.5934009, 0.58601034, 0.5787874, 0.57172304, 0.5648092, - 0.5580383, 0.5514034, 0.5448982, 0.5385169, 0.53225386, - 0.5261042, 0.52006316, 0.5141264, 0.50828975, 0.5025495, - 0.496902, 0.49134386, 0.485872, 0.48048335, 0.4751752, - 0.46994483, 0.46478975, 0.45970762, 0.45469615, 0.44975325, - 0.44487688, 0.44006512, 0.43531612, 0.43062815, 0.42599955, - 0.42142874, 0.4169142, 0.41245446, 0.40804818, 0.403694, - 0.3993907, 0.39513698, 0.39093173, 0.38677382, 0.38266218, - 0.37859577, 0.37457356, 0.37059465, 0.3666581, 0.362763, - 0.35890847, 0.35509375, 0.351318, 0.3475805, 0.34388044, - 0.34021714, 0.3365899, 0.33299807, 0.32944095, 0.32591796, - 0.3224285, 0.3189719, 0.31554767, 0.31215525, 0.30879408, - 0.3054636, 0.3021634, 0.29889292, 0.2956517, 0.29243928, - 0.28925523, 0.28609908, 0.28297043, 0.27986884, 0.27679393, - 0.2737453, 0.2707226, 0.2677254, 0.26475343, 0.26180625, - 0.25888354, 0.25598502, 0.2531103, 0.25025907, 0.24743107, - 0.24462597, 0.24184346, 0.23908329, 0.23634516, 0.23362878, - 0.23093392, 0.2282603, 0.22560766, 0.22297576, 0.22036438, - 0.21777324, 0.21520215, 0.21265087, 0.21011916, 0.20760682, - 0.20511365, 0.20263945, 0.20018397, 0.19774707, 0.19532852, - 0.19292815, 0.19054577, 0.1881812, 0.18583426, 0.18350479, - 0.1811926, 0.17889754, 0.17661946, 0.17435817, 0.17211354, - 0.1698854, 0.16767362, 0.16547804, 0.16329853, 0.16113494, - 0.15898713, 0.15685499, 0.15473837, 0.15263714, 0.15055119, - 0.14848037, 0.14642459, 0.14438373, 0.14235765, 0.14034624, - 0.13834943, 0.13636707, 0.13439907, 0.13244532, 0.13050574, - 0.1285802, 0.12666863, 0.12477092, 0.12288698, 0.12101672, - 0.119160056, 0.1173169, 0.115487166, 0.11367077, 0.11186763, - 0.11007768, 0.10830083, 0.10653701, 0.10478614, 0.10304816, - 0.101323, 0.09961058, 0.09791085, 0.09622374, 0.09454919, - 0.09288713, 0.091237515, 0.08960028, 0.087975375, 0.08636274, - 0.08476233, 0.083174095, 0.081597984, 0.08003395, 0.07848195, - 0.076941945, 0.07541389, 0.07389775, 0.072393484, 0.07090106, - 0.069420435, 0.06795159, 0.066494495, 0.06504912, 0.063615434, - 0.062193416, 0.060783047, 0.059384305, 0.057997175, - 0.05662164, 0.05525769, 0.053905312, 0.052564494, 0.051235236, - 0.049917534, 0.048611384, 0.047316793, 0.046033762, 0.0447623, - 0.043502413, 0.042254124, 0.041017443, 0.039792392, - 0.038578995, 0.037377283, 0.036187284, 0.035009038, - 0.033842582, 0.032687962, 0.031545233, 0.030414443, 0.02929566, - 0.02818895, 0.027094385, 0.026012046, 0.024942026, 0.023884421, - 0.022839336, 0.021806888, 0.020787204, 0.019780423, 0.0187867, - 0.0178062, 0.016839107, 0.015885621, 0.014945968, 0.014020392, - 0.013109165, 0.012212592, 0.011331013, 0.01046481, 0.009614414, - 0.008780315, 0.007963077, 0.0071633533, 0.006381906, - 0.0056196423, 0.0048776558, 0.004157295, 0.0034602648, - 0.0027887989, 0.0021459677, 0.0015362998, 0.0009672693, - 0.00045413437, -} diff --git a/vendor/golang.org/x/exp/rand/normal.go b/vendor/golang.org/x/exp/rand/normal.go deleted file mode 100644 index b66da3a81..000000000 --- a/vendor/golang.org/x/exp/rand/normal.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rand - -import ( - "math" -) - -/* - * Normal distribution - * - * See "The Ziggurat Method for Generating Random Variables" - * (Marsaglia & Tsang, 2000) - * http://www.jstatsoft.org/v05/i08/paper [pdf] - */ - -const ( - rn = 3.442619855899 -) - -func absInt32(i int32) uint32 { - if i < 0 { - return uint32(-i) - } - return uint32(i) -} - -// NormFloat64 returns a normally distributed float64 in the range -// [-math.MaxFloat64, +math.MaxFloat64] with -// standard normal distribution (mean = 0, stddev = 1). -// To produce a different normal distribution, callers can -// adjust the output using: -// -// sample = NormFloat64() * desiredStdDev + desiredMean -func (r *Rand) NormFloat64() float64 { - for { - j := int32(r.Uint32()) // Possibly negative - i := j & 0x7F - x := float64(j) * float64(wn[i]) - if absInt32(j) < kn[i] { - // This case should be hit better than 99% of the time. - return x - } - - if i == 0 { - // This extra work is only required for the base strip. - for { - x = -math.Log(r.Float64()) * (1.0 / rn) - y := -math.Log(r.Float64()) - if y+y >= x*x { - break - } - } - if j > 0 { - return rn + x - } - return -rn - x - } - if fn[i]+float32(r.Float64())*(fn[i-1]-fn[i]) < float32(math.Exp(-.5*x*x)) { - return x - } - } -} - -var kn = [128]uint32{ - 0x76ad2212, 0x0, 0x600f1b53, 0x6ce447a6, 0x725b46a2, - 0x7560051d, 0x774921eb, 0x789a25bd, 0x799045c3, 0x7a4bce5d, - 0x7adf629f, 0x7b5682a6, 0x7bb8a8c6, 0x7c0ae722, 0x7c50cce7, - 0x7c8cec5b, 0x7cc12cd6, 0x7ceefed2, 0x7d177e0b, 0x7d3b8883, - 0x7d5bce6c, 0x7d78dd64, 0x7d932886, 0x7dab0e57, 0x7dc0dd30, - 0x7dd4d688, 0x7de73185, 0x7df81cea, 0x7e07c0a3, 0x7e163efa, - 0x7e23b587, 0x7e303dfd, 0x7e3beec2, 0x7e46db77, 0x7e51155d, - 0x7e5aabb3, 0x7e63abf7, 0x7e6c222c, 0x7e741906, 0x7e7b9a18, - 0x7e82adfa, 0x7e895c63, 0x7e8fac4b, 0x7e95a3fb, 0x7e9b4924, - 0x7ea0a0ef, 0x7ea5b00d, 0x7eaa7ac3, 0x7eaf04f3, 0x7eb3522a, - 0x7eb765a5, 0x7ebb4259, 0x7ebeeafd, 0x7ec2620a, 0x7ec5a9c4, - 0x7ec8c441, 0x7ecbb365, 0x7ece78ed, 0x7ed11671, 0x7ed38d62, - 0x7ed5df12, 0x7ed80cb4, 0x7eda175c, 0x7edc0005, 0x7eddc78e, - 0x7edf6ebf, 0x7ee0f647, 0x7ee25ebe, 0x7ee3a8a9, 0x7ee4d473, - 0x7ee5e276, 0x7ee6d2f5, 0x7ee7a620, 0x7ee85c10, 0x7ee8f4cd, - 0x7ee97047, 0x7ee9ce59, 0x7eea0eca, 0x7eea3147, 0x7eea3568, - 0x7eea1aab, 0x7ee9e071, 0x7ee98602, 0x7ee90a88, 0x7ee86d08, - 0x7ee7ac6a, 0x7ee6c769, 0x7ee5bc9c, 0x7ee48a67, 0x7ee32efc, - 0x7ee1a857, 0x7edff42f, 0x7ede0ffa, 0x7edbf8d9, 0x7ed9ab94, - 0x7ed7248d, 0x7ed45fae, 0x7ed1585c, 0x7ece095f, 0x7eca6ccb, - 0x7ec67be2, 0x7ec22eee, 0x7ebd7d1a, 0x7eb85c35, 0x7eb2c075, - 0x7eac9c20, 0x7ea5df27, 0x7e9e769f, 0x7e964c16, 0x7e8d44ba, - 0x7e834033, 0x7e781728, 0x7e6b9933, 0x7e5d8a1a, 0x7e4d9ded, - 0x7e3b737a, 0x7e268c2f, 0x7e0e3ff5, 0x7df1aa5d, 0x7dcf8c72, - 0x7da61a1e, 0x7d72a0fb, 0x7d30e097, 0x7cd9b4ab, 0x7c600f1a, - 0x7ba90bdc, 0x7a722176, 0x77d664e5, -} -var wn = [128]float32{ - 1.7290405e-09, 1.2680929e-10, 1.6897518e-10, 1.9862688e-10, - 2.2232431e-10, 2.4244937e-10, 2.601613e-10, 2.7611988e-10, - 2.9073963e-10, 3.042997e-10, 3.1699796e-10, 3.289802e-10, - 3.4035738e-10, 3.5121603e-10, 3.616251e-10, 3.7164058e-10, - 3.8130857e-10, 3.9066758e-10, 3.9975012e-10, 4.08584e-10, - 4.1719309e-10, 4.2559822e-10, 4.338176e-10, 4.418672e-10, - 4.497613e-10, 4.5751258e-10, 4.651324e-10, 4.7263105e-10, - 4.8001775e-10, 4.87301e-10, 4.944885e-10, 5.015873e-10, - 5.0860405e-10, 5.155446e-10, 5.2241467e-10, 5.2921934e-10, - 5.359635e-10, 5.426517e-10, 5.4928817e-10, 5.5587696e-10, - 5.624219e-10, 5.6892646e-10, 5.753941e-10, 5.818282e-10, - 5.882317e-10, 5.946077e-10, 6.00959e-10, 6.072884e-10, - 6.135985e-10, 6.19892e-10, 6.2617134e-10, 6.3243905e-10, - 6.386974e-10, 6.449488e-10, 6.511956e-10, 6.5744005e-10, - 6.6368433e-10, 6.699307e-10, 6.7618144e-10, 6.824387e-10, - 6.8870465e-10, 6.949815e-10, 7.012715e-10, 7.075768e-10, - 7.1389966e-10, 7.202424e-10, 7.266073e-10, 7.329966e-10, - 7.394128e-10, 7.4585826e-10, 7.5233547e-10, 7.58847e-10, - 7.653954e-10, 7.719835e-10, 7.7861395e-10, 7.852897e-10, - 7.920138e-10, 7.987892e-10, 8.0561924e-10, 8.125073e-10, - 8.194569e-10, 8.2647167e-10, 8.3355556e-10, 8.407127e-10, - 8.479473e-10, 8.55264e-10, 8.6266755e-10, 8.7016316e-10, - 8.777562e-10, 8.8545243e-10, 8.932582e-10, 9.0117996e-10, - 9.09225e-10, 9.174008e-10, 9.2571584e-10, 9.341788e-10, - 9.427997e-10, 9.515889e-10, 9.605579e-10, 9.697193e-10, - 9.790869e-10, 9.88676e-10, 9.985036e-10, 1.0085882e-09, - 1.0189509e-09, 1.0296151e-09, 1.0406069e-09, 1.0519566e-09, - 1.063698e-09, 1.0758702e-09, 1.0885183e-09, 1.1016947e-09, - 1.1154611e-09, 1.1298902e-09, 1.1450696e-09, 1.1611052e-09, - 1.1781276e-09, 1.1962995e-09, 1.2158287e-09, 1.2369856e-09, - 1.2601323e-09, 1.2857697e-09, 1.3146202e-09, 1.347784e-09, - 1.3870636e-09, 1.4357403e-09, 1.5008659e-09, 1.6030948e-09, -} -var fn = [128]float32{ - 1, 0.9635997, 0.9362827, 0.9130436, 0.89228165, 0.87324303, - 0.8555006, 0.8387836, 0.8229072, 0.8077383, 0.793177, - 0.7791461, 0.7655842, 0.7524416, 0.73967725, 0.7272569, - 0.7151515, 0.7033361, 0.69178915, 0.68049186, 0.6694277, - 0.658582, 0.6479418, 0.63749546, 0.6272325, 0.6171434, - 0.6072195, 0.5974532, 0.58783704, 0.5783647, 0.56903, - 0.5598274, 0.5507518, 0.54179835, 0.5329627, 0.52424055, - 0.5156282, 0.50712204, 0.49871865, 0.49041483, 0.48220766, - 0.4740943, 0.46607214, 0.4581387, 0.45029163, 0.44252872, - 0.43484783, 0.427247, 0.41972435, 0.41227803, 0.40490642, - 0.39760786, 0.3903808, 0.3832238, 0.37613547, 0.36911446, - 0.3621595, 0.35526937, 0.34844297, 0.34167916, 0.33497685, - 0.3283351, 0.3217529, 0.3152294, 0.30876362, 0.30235484, - 0.29600215, 0.28970486, 0.2834622, 0.2772735, 0.27113807, - 0.2650553, 0.25902456, 0.2530453, 0.24711695, 0.241239, - 0.23541094, 0.22963232, 0.2239027, 0.21822165, 0.21258877, - 0.20700371, 0.20146611, 0.19597565, 0.19053204, 0.18513499, - 0.17978427, 0.17447963, 0.1692209, 0.16400786, 0.15884037, - 0.15371831, 0.14864157, 0.14361008, 0.13862377, 0.13368265, - 0.12878671, 0.12393598, 0.119130544, 0.11437051, 0.10965602, - 0.104987256, 0.10036444, 0.095787846, 0.0912578, 0.08677467, - 0.0823389, 0.077950984, 0.073611505, 0.06932112, 0.06508058, - 0.06089077, 0.056752663, 0.0526674, 0.048636295, 0.044660863, - 0.040742867, 0.03688439, 0.033087887, 0.029356318, - 0.025693292, 0.022103304, 0.018592102, 0.015167298, - 0.011839478, 0.008624485, 0.005548995, 0.0026696292, -} diff --git a/vendor/golang.org/x/exp/rand/rand.go b/vendor/golang.org/x/exp/rand/rand.go deleted file mode 100644 index ee6161bc6..000000000 --- a/vendor/golang.org/x/exp/rand/rand.go +++ /dev/null @@ -1,372 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package rand implements pseudo-random number generators. -// -// Random numbers are generated by a Source. Top-level functions, such as -// Float64 and Int, use a default shared Source that produces a deterministic -// sequence of values each time a program is run. Use the Seed function to -// initialize the default Source if different behavior is required for each run. -// The default Source, a LockedSource, is safe for concurrent use by multiple -// goroutines, but Sources created by NewSource are not. However, Sources are small -// and it is reasonable to have a separate Source for each goroutine, seeded -// differently, to avoid locking. -// -// For random numbers suitable for security-sensitive work, see the crypto/rand -// package. -package rand - -import "sync" - -// A Source represents a source of uniformly-distributed -// pseudo-random int64 values in the range [0, 1<<64). -type Source interface { - Uint64() uint64 - Seed(seed uint64) -} - -// NewSource returns a new pseudo-random Source seeded with the given value. -func NewSource(seed uint64) Source { - var rng PCGSource - rng.Seed(seed) - return &rng -} - -// A Rand is a source of random numbers. -type Rand struct { - src Source - - // readVal contains remainder of 64-bit integer used for bytes - // generation during most recent Read call. - // It is saved so next Read call can start where the previous - // one finished. - readVal uint64 - // readPos indicates the number of low-order bytes of readVal - // that are still valid. - readPos int8 -} - -// New returns a new Rand that uses random values from src -// to generate other random values. -func New(src Source) *Rand { - return &Rand{src: src} -} - -// Seed uses the provided seed value to initialize the generator to a deterministic state. -// Seed should not be called concurrently with any other Rand method. -func (r *Rand) Seed(seed uint64) { - if lk, ok := r.src.(*LockedSource); ok { - lk.seedPos(seed, &r.readPos) - return - } - - r.src.Seed(seed) - r.readPos = 0 -} - -// Uint64 returns a pseudo-random 64-bit integer as a uint64. -func (r *Rand) Uint64() uint64 { return r.src.Uint64() } - -// Int63 returns a non-negative pseudo-random 63-bit integer as an int64. -func (r *Rand) Int63() int64 { return int64(r.src.Uint64() &^ (1 << 63)) } - -// Uint32 returns a pseudo-random 32-bit value as a uint32. -func (r *Rand) Uint32() uint32 { return uint32(r.Uint64() >> 32) } - -// Int31 returns a non-negative pseudo-random 31-bit integer as an int32. -func (r *Rand) Int31() int32 { return int32(r.Uint64() >> 33) } - -// Int returns a non-negative pseudo-random int. -func (r *Rand) Int() int { - u := uint(r.Uint64()) - return int(u << 1 >> 1) // clear sign bit. -} - -const maxUint64 = (1 << 64) - 1 - -// Uint64n returns, as a uint64, a pseudo-random number in [0,n). -// It is guaranteed more uniform than taking a Source value mod n -// for any n that is not a power of 2. -func (r *Rand) Uint64n(n uint64) uint64 { - if n&(n-1) == 0 { // n is power of two, can mask - if n == 0 { - panic("invalid argument to Uint64n") - } - return r.Uint64() & (n - 1) - } - // If n does not divide v, to avoid bias we must not use - // a v that is within maxUint64%n of the top of the range. - v := r.Uint64() - if v > maxUint64-n { // Fast check. - ceiling := maxUint64 - maxUint64%n - for v >= ceiling { - v = r.Uint64() - } - } - - return v % n -} - -// Int63n returns, as an int64, a non-negative pseudo-random number in [0,n). -// It panics if n <= 0. -func (r *Rand) Int63n(n int64) int64 { - if n <= 0 { - panic("invalid argument to Int63n") - } - return int64(r.Uint64n(uint64(n))) -} - -// Int31n returns, as an int32, a non-negative pseudo-random number in [0,n). -// It panics if n <= 0. -func (r *Rand) Int31n(n int32) int32 { - if n <= 0 { - panic("invalid argument to Int31n") - } - // TODO: Avoid some 64-bit ops to make it more efficient on 32-bit machines. - return int32(r.Uint64n(uint64(n))) -} - -// Intn returns, as an int, a non-negative pseudo-random number in [0,n). -// It panics if n <= 0. -func (r *Rand) Intn(n int) int { - if n <= 0 { - panic("invalid argument to Intn") - } - // TODO: Avoid some 64-bit ops to make it more efficient on 32-bit machines. - return int(r.Uint64n(uint64(n))) -} - -// Float64 returns, as a float64, a pseudo-random number in [0.0,1.0). -func (r *Rand) Float64() float64 { - // There is one bug in the value stream: r.Int63() may be so close - // to 1<<63 that the division rounds up to 1.0, and we've guaranteed - // that the result is always less than 1.0. - // - // We tried to fix this by mapping 1.0 back to 0.0, but since float64 - // values near 0 are much denser than near 1, mapping 1 to 0 caused - // a theoretically significant overshoot in the probability of returning 0. - // Instead of that, if we round up to 1, just try again. - // Getting 1 only happens 1/2⁵³ of the time, so most clients - // will not observe it anyway. -again: - f := float64(r.Uint64n(1<<53)) / (1 << 53) - if f == 1.0 { - goto again // resample; this branch is taken O(never) - } - return f -} - -// Float32 returns, as a float32, a pseudo-random number in [0.0,1.0). -func (r *Rand) Float32() float32 { - // We do not want to return 1.0. - // This only happens 1/2²⁴ of the time (plus the 1/2⁵³ of the time in Float64). -again: - f := float32(r.Float64()) - if f == 1 { - goto again // resample; this branch is taken O(very rarely) - } - return f -} - -// Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n). -func (r *Rand) Perm(n int) []int { - m := make([]int, n) - // In the following loop, the iteration when i=0 always swaps m[0] with m[0]. - // A change to remove this useless iteration is to assign 1 to i in the init - // statement. But Perm also effects r. Making this change will affect - // the final state of r. So this change can't be made for compatibility - // reasons for Go 1. - for i := 0; i < n; i++ { - j := r.Intn(i + 1) - m[i] = m[j] - m[j] = i - } - return m -} - -// Shuffle pseudo-randomizes the order of elements. -// n is the number of elements. Shuffle panics if n < 0. -// swap swaps the elements with indexes i and j. -func (r *Rand) Shuffle(n int, swap func(i, j int)) { - if n < 0 { - panic("invalid argument to Shuffle") - } - - // Fisher-Yates shuffle: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle - // Shuffle really ought not be called with n that doesn't fit in 32 bits. - // Not only will it take a very long time, but with 2³¹! possible permutations, - // there's no way that any PRNG can have a big enough internal state to - // generate even a minuscule percentage of the possible permutations. - // Nevertheless, the right API signature accepts an int n, so handle it as best we can. - i := n - 1 - for ; i > 1<<31-1-1; i-- { - j := int(r.Int63n(int64(i + 1))) - swap(i, j) - } - for ; i > 0; i-- { - j := int(r.Int31n(int32(i + 1))) - swap(i, j) - } -} - -// Read generates len(p) random bytes and writes them into p. It -// always returns len(p) and a nil error. -// Read should not be called concurrently with any other Rand method unless -// the underlying source is a LockedSource. -func (r *Rand) Read(p []byte) (n int, err error) { - if lk, ok := r.src.(*LockedSource); ok { - return lk.Read(p, &r.readVal, &r.readPos) - } - return read(p, r.src, &r.readVal, &r.readPos) -} - -func read(p []byte, src Source, readVal *uint64, readPos *int8) (n int, err error) { - pos := *readPos - val := *readVal - rng, _ := src.(*PCGSource) - for n = 0; n < len(p); n++ { - if pos == 0 { - if rng != nil { - val = rng.Uint64() - } else { - val = src.Uint64() - } - pos = 8 - } - p[n] = byte(val) - val >>= 8 - pos-- - } - *readPos = pos - *readVal = val - return -} - -/* - * Top-level convenience functions - */ - -var globalRand = New(&LockedSource{src: *NewSource(1).(*PCGSource)}) - -// Type assert that globalRand's source is a LockedSource whose src is a PCGSource. -var _ PCGSource = globalRand.src.(*LockedSource).src - -// Seed uses the provided seed value to initialize the default Source to a -// deterministic state. If Seed is not called, the generator behaves as -// if seeded by Seed(1). -// Seed, unlike the Rand.Seed method, is safe for concurrent use. -func Seed(seed uint64) { globalRand.Seed(seed) } - -// Int63 returns a non-negative pseudo-random 63-bit integer as an int64 -// from the default Source. -func Int63() int64 { return globalRand.Int63() } - -// Uint32 returns a pseudo-random 32-bit value as a uint32 -// from the default Source. -func Uint32() uint32 { return globalRand.Uint32() } - -// Uint64 returns a pseudo-random 64-bit value as a uint64 -// from the default Source. -func Uint64() uint64 { return globalRand.Uint64() } - -// Int31 returns a non-negative pseudo-random 31-bit integer as an int32 -// from the default Source. -func Int31() int32 { return globalRand.Int31() } - -// Int returns a non-negative pseudo-random int from the default Source. -func Int() int { return globalRand.Int() } - -// Int63n returns, as an int64, a non-negative pseudo-random number in [0,n) -// from the default Source. -// It panics if n <= 0. -func Int63n(n int64) int64 { return globalRand.Int63n(n) } - -// Int31n returns, as an int32, a non-negative pseudo-random number in [0,n) -// from the default Source. -// It panics if n <= 0. -func Int31n(n int32) int32 { return globalRand.Int31n(n) } - -// Intn returns, as an int, a non-negative pseudo-random number in [0,n) -// from the default Source. -// It panics if n <= 0. -func Intn(n int) int { return globalRand.Intn(n) } - -// Float64 returns, as a float64, a pseudo-random number in [0.0,1.0) -// from the default Source. -func Float64() float64 { return globalRand.Float64() } - -// Float32 returns, as a float32, a pseudo-random number in [0.0,1.0) -// from the default Source. -func Float32() float32 { return globalRand.Float32() } - -// Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n) -// from the default Source. -func Perm(n int) []int { return globalRand.Perm(n) } - -// Shuffle pseudo-randomizes the order of elements using the default Source. -// n is the number of elements. Shuffle panics if n < 0. -// swap swaps the elements with indexes i and j. -func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) } - -// Read generates len(p) random bytes from the default Source and -// writes them into p. It always returns len(p) and a nil error. -// Read, unlike the Rand.Read method, is safe for concurrent use. -func Read(p []byte) (n int, err error) { return globalRand.Read(p) } - -// NormFloat64 returns a normally distributed float64 in the range -// [-math.MaxFloat64, +math.MaxFloat64] with -// standard normal distribution (mean = 0, stddev = 1) -// from the default Source. -// To produce a different normal distribution, callers can -// adjust the output using: -// -// sample = NormFloat64() * desiredStdDev + desiredMean -func NormFloat64() float64 { return globalRand.NormFloat64() } - -// ExpFloat64 returns an exponentially distributed float64 in the range -// (0, +math.MaxFloat64] with an exponential distribution whose rate parameter -// (lambda) is 1 and whose mean is 1/lambda (1) from the default Source. -// To produce a distribution with a different rate parameter, -// callers can adjust the output using: -// -// sample = ExpFloat64() / desiredRateParameter -func ExpFloat64() float64 { return globalRand.ExpFloat64() } - -// LockedSource is an implementation of Source that is concurrency-safe. -// A Rand using a LockedSource is safe for concurrent use. -// -// The zero value of LockedSource is valid, but should be seeded before use. -type LockedSource struct { - lk sync.Mutex - src PCGSource -} - -func (s *LockedSource) Uint64() (n uint64) { - s.lk.Lock() - n = s.src.Uint64() - s.lk.Unlock() - return -} - -func (s *LockedSource) Seed(seed uint64) { - s.lk.Lock() - s.src.Seed(seed) - s.lk.Unlock() -} - -// seedPos implements Seed for a LockedSource without a race condiiton. -func (s *LockedSource) seedPos(seed uint64, readPos *int8) { - s.lk.Lock() - s.src.Seed(seed) - *readPos = 0 - s.lk.Unlock() -} - -// Read implements Read for a LockedSource. -func (s *LockedSource) Read(p []byte, readVal *uint64, readPos *int8) (n int, err error) { - s.lk.Lock() - n, err = read(p, &s.src, readVal, readPos) - s.lk.Unlock() - return -} diff --git a/vendor/golang.org/x/exp/rand/rng.go b/vendor/golang.org/x/exp/rand/rng.go deleted file mode 100644 index 9b79108c7..000000000 --- a/vendor/golang.org/x/exp/rand/rng.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2017 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rand - -import ( - "encoding/binary" - "io" - "math/bits" -) - -// PCGSource is an implementation of a 64-bit permuted congruential -// generator as defined in -// -// PCG: A Family of Simple Fast Space-Efficient Statistically Good -// Algorithms for Random Number Generation -// Melissa E. O’Neill, Harvey Mudd College -// http://www.pcg-random.org/pdf/toms-oneill-pcg-family-v1.02.pdf -// -// The generator here is the congruential generator PCG XSL RR 128/64 (LCG) -// as found in the software available at http://www.pcg-random.org/. -// It has period 2^128 with 128 bits of state, producing 64-bit values. -// Is state is represented by two uint64 words. -type PCGSource struct { - low uint64 - high uint64 -} - -const ( - maxUint32 = (1 << 32) - 1 - - multiplier = 47026247687942121848144207491837523525 - mulHigh = multiplier >> 64 - mulLow = multiplier & maxUint64 - - increment = 117397592171526113268558934119004209487 - incHigh = increment >> 64 - incLow = increment & maxUint64 - - // TODO: Use these? - initializer = 245720598905631564143578724636268694099 - initHigh = initializer >> 64 - initLow = initializer & maxUint64 -) - -// Seed uses the provided seed value to initialize the generator to a deterministic state. -func (pcg *PCGSource) Seed(seed uint64) { - pcg.low = seed - pcg.high = seed // TODO: What is right? -} - -// Uint64 returns a pseudo-random 64-bit unsigned integer as a uint64. -func (pcg *PCGSource) Uint64() uint64 { - pcg.multiply() - pcg.add() - // XOR high and low 64 bits together and rotate right by high 6 bits of state. - return bits.RotateLeft64(pcg.high^pcg.low, -int(pcg.high>>58)) -} - -func (pcg *PCGSource) add() { - var carry uint64 - pcg.low, carry = bits.Add64(pcg.low, incLow, 0) - pcg.high, _ = bits.Add64(pcg.high, incHigh, carry) -} - -func (pcg *PCGSource) multiply() { - hi, lo := bits.Mul64(pcg.low, mulLow) - hi += pcg.high * mulLow - hi += pcg.low * mulHigh - pcg.low = lo - pcg.high = hi -} - -// MarshalBinary returns the binary representation of the current state of the generator. -func (pcg *PCGSource) MarshalBinary() ([]byte, error) { - var buf [16]byte - binary.BigEndian.PutUint64(buf[:8], pcg.high) - binary.BigEndian.PutUint64(buf[8:], pcg.low) - return buf[:], nil -} - -// UnmarshalBinary sets the state of the generator to the state represented in data. -func (pcg *PCGSource) UnmarshalBinary(data []byte) error { - if len(data) < 16 { - return io.ErrUnexpectedEOF - } - pcg.low = binary.BigEndian.Uint64(data[8:]) - pcg.high = binary.BigEndian.Uint64(data[:8]) - return nil -} diff --git a/vendor/golang.org/x/exp/rand/zipf.go b/vendor/golang.org/x/exp/rand/zipf.go deleted file mode 100644 index f04c814eb..000000000 --- a/vendor/golang.org/x/exp/rand/zipf.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// W.Hormann, G.Derflinger: -// "Rejection-Inversion to Generate Variates -// from Monotone Discrete Distributions" -// http://eeyore.wu-wien.ac.at/papers/96-04-04.wh-der.ps.gz - -package rand - -import "math" - -// A Zipf generates Zipf distributed variates. -type Zipf struct { - r *Rand - imax float64 - v float64 - q float64 - s float64 - oneminusQ float64 - oneminusQinv float64 - hxm float64 - hx0minusHxm float64 -} - -func (z *Zipf) h(x float64) float64 { - return math.Exp(z.oneminusQ*math.Log(z.v+x)) * z.oneminusQinv -} - -func (z *Zipf) hinv(x float64) float64 { - return math.Exp(z.oneminusQinv*math.Log(z.oneminusQ*x)) - z.v -} - -// NewZipf returns a Zipf variate generator. -// The generator generates values k ∈ [0, imax] -// such that P(k) is proportional to (v + k) ** (-s). -// Requirements: s > 1 and v >= 1. -func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf { - z := new(Zipf) - if s <= 1.0 || v < 1 { - return nil - } - z.r = r - z.imax = float64(imax) - z.v = v - z.q = s - z.oneminusQ = 1.0 - z.q - z.oneminusQinv = 1.0 / z.oneminusQ - z.hxm = z.h(z.imax + 0.5) - z.hx0minusHxm = z.h(0.5) - math.Exp(math.Log(z.v)*(-z.q)) - z.hxm - z.s = 1 - z.hinv(z.h(1.5)-math.Exp(-z.q*math.Log(z.v+1.0))) - return z -} - -// Uint64 returns a value drawn from the Zipf distribution described -// by the Zipf object. -func (z *Zipf) Uint64() uint64 { - if z == nil { - panic("rand: nil Zipf") - } - k := 0.0 - - for { - r := z.r.Float64() // r on [0,1] - ur := z.hxm + r*z.hx0minusHxm - x := z.hinv(ur) - k = math.Floor(x + 0.5) - if k-x <= z.s { - break - } - if ur >= z.h(k+0.5)-math.Exp(-math.Log(k+z.v)*z.q) { - break - } - } - return uint64(k) -} diff --git a/vendor/golang.org/x/exp/slices/cmp.go b/vendor/golang.org/x/exp/slices/cmp.go deleted file mode 100644 index fbf1934a0..000000000 --- a/vendor/golang.org/x/exp/slices/cmp.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2023 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package slices - -import "golang.org/x/exp/constraints" - -// min is a version of the predeclared function from the Go 1.21 release. -func min[T constraints.Ordered](a, b T) T { - if a < b || isNaN(a) { - return a - } - return b -} - -// max is a version of the predeclared function from the Go 1.21 release. -func max[T constraints.Ordered](a, b T) T { - if a > b || isNaN(a) { - return a - } - return b -} - -// cmpLess is a copy of cmp.Less from the Go 1.21 release. -func cmpLess[T constraints.Ordered](x, y T) bool { - return (isNaN(x) && !isNaN(y)) || x < y -} - -// cmpCompare is a copy of cmp.Compare from the Go 1.21 release. -func cmpCompare[T constraints.Ordered](x, y T) int { - xNaN := isNaN(x) - yNaN := isNaN(y) - if xNaN && yNaN { - return 0 - } - if xNaN || x < y { - return -1 - } - if yNaN || x > y { - return +1 - } - return 0 -} diff --git a/vendor/golang.org/x/exp/slices/slices.go b/vendor/golang.org/x/exp/slices/slices.go index 5e8158bba..8a7cf20db 100644 --- a/vendor/golang.org/x/exp/slices/slices.go +++ b/vendor/golang.org/x/exp/slices/slices.go @@ -3,20 +3,23 @@ // license that can be found in the LICENSE file. // Package slices defines various functions useful with slices of any type. +// Unless otherwise specified, these functions all apply to the elements +// of a slice at index 0 <= i < len(s). +// +// Note that the less function in IsSortedFunc, SortFunc, SortStableFunc requires a +// strict weak ordering (https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings), +// or the sorting may fail to sort correctly. A common case is when sorting slices of +// floating-point numbers containing NaN values. package slices -import ( - "unsafe" - - "golang.org/x/exp/constraints" -) +import "golang.org/x/exp/constraints" // Equal reports whether two slices are equal: the same length and all // elements equal. If the lengths are different, Equal returns false. // Otherwise, the elements are compared in increasing index order, and the // comparison stops at the first unequal pair. // Floating point NaNs are not considered equal. -func Equal[S ~[]E, E comparable](s1, s2 S) bool { +func Equal[E comparable](s1, s2 []E) bool { if len(s1) != len(s2) { return false } @@ -28,12 +31,12 @@ func Equal[S ~[]E, E comparable](s1, s2 S) bool { return true } -// EqualFunc reports whether two slices are equal using an equality +// EqualFunc reports whether two slices are equal using a comparison // function on each pair of elements. If the lengths are different, // EqualFunc returns false. Otherwise, the elements are compared in // increasing index order, and the comparison stops at the first index // for which eq returns false. -func EqualFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, eq func(E1, E2) bool) bool { +func EqualFunc[E1, E2 any](s1 []E1, s2 []E2, eq func(E1, E2) bool) bool { if len(s1) != len(s2) { return false } @@ -46,37 +49,45 @@ func EqualFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, eq func(E1, E2) boo return true } -// Compare compares the elements of s1 and s2, using [cmp.Compare] on each pair -// of elements. The elements are compared sequentially, starting at index 0, +// Compare compares the elements of s1 and s2. +// The elements are compared sequentially, starting at index 0, // until one element is not equal to the other. // The result of comparing the first non-matching elements is returned. // If both slices are equal until one of them ends, the shorter slice is // considered less than the longer one. // The result is 0 if s1 == s2, -1 if s1 < s2, and +1 if s1 > s2. -func Compare[S ~[]E, E constraints.Ordered](s1, s2 S) int { +// Comparisons involving floating point NaNs are ignored. +func Compare[E constraints.Ordered](s1, s2 []E) int { + s2len := len(s2) for i, v1 := range s1 { - if i >= len(s2) { + if i >= s2len { return +1 } v2 := s2[i] - if c := cmpCompare(v1, v2); c != 0 { - return c + switch { + case v1 < v2: + return -1 + case v1 > v2: + return +1 } } - if len(s1) < len(s2) { + if len(s1) < s2len { return -1 } return 0 } -// CompareFunc is like [Compare] but uses a custom comparison function on each -// pair of elements. +// CompareFunc is like Compare but uses a comparison function +// on each pair of elements. The elements are compared in increasing +// index order, and the comparisons stop after the first time cmp +// returns non-zero. // The result is the first non-zero result of cmp; if cmp always // returns 0 the result is 0 if len(s1) == len(s2), -1 if len(s1) < len(s2), // and +1 if len(s1) > len(s2). -func CompareFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, cmp func(E1, E2) int) int { +func CompareFunc[E1, E2 any](s1 []E1, s2 []E2, cmp func(E1, E2) int) int { + s2len := len(s2) for i, v1 := range s1 { - if i >= len(s2) { + if i >= s2len { return +1 } v2 := s2[i] @@ -84,7 +95,7 @@ func CompareFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, cmp func(E1, E2) return c } } - if len(s1) < len(s2) { + if len(s1) < s2len { return -1 } return 0 @@ -92,7 +103,7 @@ func CompareFunc[S1 ~[]E1, S2 ~[]E2, E1, E2 any](s1 S1, s2 S2, cmp func(E1, E2) // Index returns the index of the first occurrence of v in s, // or -1 if not present. -func Index[S ~[]E, E comparable](s S, v E) int { +func Index[E comparable](s []E, v E) int { for i := range s { if v == s[i] { return i @@ -103,7 +114,7 @@ func Index[S ~[]E, E comparable](s S, v E) int { // IndexFunc returns the first index i satisfying f(s[i]), // or -1 if none do. -func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int { +func IndexFunc[E any](s []E, f func(E) bool) int { for i := range s { if f(s[i]) { return i @@ -113,104 +124,39 @@ func IndexFunc[S ~[]E, E any](s S, f func(E) bool) int { } // Contains reports whether v is present in s. -func Contains[S ~[]E, E comparable](s S, v E) bool { +func Contains[E comparable](s []E, v E) bool { return Index(s, v) >= 0 } // ContainsFunc reports whether at least one // element e of s satisfies f(e). -func ContainsFunc[S ~[]E, E any](s S, f func(E) bool) bool { +func ContainsFunc[E any](s []E, f func(E) bool) bool { return IndexFunc(s, f) >= 0 } // Insert inserts the values v... into s at index i, // returning the modified slice. -// The elements at s[i:] are shifted up to make room. -// In the returned slice r, r[i] == v[0], -// and r[i+len(v)] == value originally at r[i]. +// In the returned slice r, r[i] == v[0]. // Insert panics if i is out of range. // This function is O(len(s) + len(v)). func Insert[S ~[]E, E any](s S, i int, v ...E) S { - m := len(v) - if m == 0 { - return s - } - n := len(s) - if i == n { - return append(s, v...) - } - if n+m > cap(s) { - // Use append rather than make so that we bump the size of - // the slice up to the next storage class. - // This is what Grow does but we don't call Grow because - // that might copy the values twice. - s2 := append(s[:i], make(S, n+m-i)...) + tot := len(s) + len(v) + if tot <= cap(s) { + s2 := s[:tot] + copy(s2[i+len(v):], s[i:]) copy(s2[i:], v) - copy(s2[i+m:], s[i:]) return s2 } - s = s[:n+m] - - // before: - // s: aaaaaaaabbbbccccccccdddd - // ^ ^ ^ ^ - // i i+m n n+m - // after: - // s: aaaaaaaavvvvbbbbcccccccc - // ^ ^ ^ ^ - // i i+m n n+m - // - // a are the values that don't move in s. - // v are the values copied in from v. - // b and c are the values from s that are shifted up in index. - // d are the values that get overwritten, never to be seen again. - - if !overlaps(v, s[i+m:]) { - // Easy case - v does not overlap either the c or d regions. - // (It might be in some of a or b, or elsewhere entirely.) - // The data we copy up doesn't write to v at all, so just do it. - - copy(s[i+m:], s[i:]) - - // Now we have - // s: aaaaaaaabbbbbbbbcccccccc - // ^ ^ ^ ^ - // i i+m n n+m - // Note the b values are duplicated. - - copy(s[i:], v) - - // Now we have - // s: aaaaaaaavvvvbbbbcccccccc - // ^ ^ ^ ^ - // i i+m n n+m - // That's the result we want. - return s - } - - // The hard case - v overlaps c or d. We can't just shift up - // the data because we'd move or clobber the values we're trying - // to insert. - // So instead, write v on top of d, then rotate. - copy(s[n:], v) - - // Now we have - // s: aaaaaaaabbbbccccccccvvvv - // ^ ^ ^ ^ - // i i+m n n+m - - rotateRight(s[i:], m) - - // Now we have - // s: aaaaaaaavvvvbbbbcccccccc - // ^ ^ ^ ^ - // i i+m n n+m - // That's the result we want. - return s + s2 := make(S, tot) + copy(s2, s[:i]) + copy(s2[i:], v) + copy(s2[i+len(v):], s[i:]) + return s2 } // Delete removes the elements s[i:j] from s, returning the modified slice. // Delete panics if s[i:j] is not a valid slice of s. +// Delete modifies the contents of the slice s; it does not create a new slice. // Delete is O(len(s)-j), so if many items must be deleted, it is better to // make a single call deleting them all together than to delete one at a time. // Delete might not modify the elements s[len(s)-(j-i):len(s)]. If those @@ -229,106 +175,39 @@ func Delete[S ~[]E, E any](s S, i, j int) S { // zeroing those elements so that objects they reference can be garbage // collected. func DeleteFunc[S ~[]E, E any](s S, del func(E) bool) S { - i := IndexFunc(s, del) - if i == -1 { - return s - } // Don't start copying elements until we find one to delete. - for j := i + 1; j < len(s); j++ { - if v := s[j]; !del(v) { - s[i] = v - i++ + for i, v := range s { + if del(v) { + j := i + for i++; i < len(s); i++ { + v = s[i] + if !del(v) { + s[j] = v + j++ + } + } + return s[:j] } } - return s[:i] + return s } // Replace replaces the elements s[i:j] by the given v, and returns the // modified slice. Replace panics if s[i:j] is not a valid slice of s. func Replace[S ~[]E, E any](s S, i, j int, v ...E) S { _ = s[i:j] // verify that i:j is a valid subslice - - if i == j { - return Insert(s, i, v...) - } - if j == len(s) { - return append(s[:i], v...) - } - tot := len(s[:i]) + len(v) + len(s[j:]) - if tot > cap(s) { - // Too big to fit, allocate and copy over. - s2 := append(s[:i], make(S, tot-i)...) // See Insert - copy(s2[i:], v) + if tot <= cap(s) { + s2 := s[:tot] copy(s2[i+len(v):], s[j:]) + copy(s2[i:], v) return s2 } - - r := s[:tot] - - if i+len(v) <= j { - // Easy, as v fits in the deleted portion. - copy(r[i:], v) - if i+len(v) != j { - copy(r[i+len(v):], s[j:]) - } - return r - } - - // We are expanding (v is bigger than j-i). - // The situation is something like this: - // (example has i=4,j=8,len(s)=16,len(v)=6) - // s: aaaaxxxxbbbbbbbbyy - // ^ ^ ^ ^ - // i j len(s) tot - // a: prefix of s - // x: deleted range - // b: more of s - // y: area to expand into - - if !overlaps(r[i+len(v):], v) { - // Easy, as v is not clobbered by the first copy. - copy(r[i+len(v):], s[j:]) - copy(r[i:], v) - return r - } - - // This is a situation where we don't have a single place to which - // we can copy v. Parts of it need to go to two different places. - // We want to copy the prefix of v into y and the suffix into x, then - // rotate |y| spots to the right. - // - // v[2:] v[:2] - // | | - // s: aaaavvvvbbbbbbbbvv - // ^ ^ ^ ^ - // i j len(s) tot - // - // If either of those two destinations don't alias v, then we're good. - y := len(v) - (j - i) // length of y portion - - if !overlaps(r[i:j], v) { - copy(r[i:j], v[y:]) - copy(r[len(s):], v[:y]) - rotateRight(r[i:], y) - return r - } - if !overlaps(r[len(s):], v) { - copy(r[len(s):], v[:y]) - copy(r[i:j], v[y:]) - rotateRight(r[i:], y) - return r - } - - // Now we know that v overlaps both x and y. - // That means that the entirety of b is *inside* v. - // So we don't need to preserve b at all; instead we - // can copy v first, then copy the b part of v out of - // v to the right destination. - k := startIdx(v, s[j:]) - copy(r[i:], v) - copy(r[i+len(v):], r[i+k:]) - return r + s2 := make(S, tot) + copy(s2, s[:i]) + copy(s2[i:], v) + copy(s2[i+len(v):], s[j:]) + return s2 } // Clone returns a copy of the slice. @@ -343,8 +222,7 @@ func Clone[S ~[]E, E any](s S) S { // Compact replaces consecutive runs of equal elements with a single copy. // This is like the uniq command found on Unix. -// Compact modifies the contents of the slice s and returns the modified slice, -// which may have a smaller length. +// Compact modifies the contents of the slice s; it does not create a new slice. // When Compact discards m elements in total, it might not modify the elements // s[len(s)-m:len(s)]. If those elements contain pointers you might consider // zeroing those elements so that objects they reference can be garbage collected. @@ -364,8 +242,7 @@ func Compact[S ~[]E, E comparable](s S) S { return s[:i] } -// CompactFunc is like [Compact] but uses an equality function to compare elements. -// For runs of elements that compare equal, CompactFunc keeps the first one. +// CompactFunc is like Compact but uses a comparison function. func CompactFunc[S ~[]E, E any](s S, eq func(E, E) bool) S { if len(s) < 2 { return s @@ -403,97 +280,3 @@ func Grow[S ~[]E, E any](s S, n int) S { func Clip[S ~[]E, E any](s S) S { return s[:len(s):len(s)] } - -// Rotation algorithm explanation: -// -// rotate left by 2 -// start with -// 0123456789 -// split up like this -// 01 234567 89 -// swap first 2 and last 2 -// 89 234567 01 -// join first parts -// 89234567 01 -// recursively rotate first left part by 2 -// 23456789 01 -// join at the end -// 2345678901 -// -// rotate left by 8 -// start with -// 0123456789 -// split up like this -// 01 234567 89 -// swap first 2 and last 2 -// 89 234567 01 -// join last parts -// 89 23456701 -// recursively rotate second part left by 6 -// 89 01234567 -// join at the end -// 8901234567 - -// TODO: There are other rotate algorithms. -// This algorithm has the desirable property that it moves each element exactly twice. -// The triple-reverse algorithm is simpler and more cache friendly, but takes more writes. -// The follow-cycles algorithm can be 1-write but it is not very cache friendly. - -// rotateLeft rotates b left by n spaces. -// s_final[i] = s_orig[i+r], wrapping around. -func rotateLeft[E any](s []E, r int) { - for r != 0 && r != len(s) { - if r*2 <= len(s) { - swap(s[:r], s[len(s)-r:]) - s = s[:len(s)-r] - } else { - swap(s[:len(s)-r], s[r:]) - s, r = s[len(s)-r:], r*2-len(s) - } - } -} -func rotateRight[E any](s []E, r int) { - rotateLeft(s, len(s)-r) -} - -// swap swaps the contents of x and y. x and y must be equal length and disjoint. -func swap[E any](x, y []E) { - for i := 0; i < len(x); i++ { - x[i], y[i] = y[i], x[i] - } -} - -// overlaps reports whether the memory ranges a[0:len(a)] and b[0:len(b)] overlap. -func overlaps[E any](a, b []E) bool { - if len(a) == 0 || len(b) == 0 { - return false - } - elemSize := unsafe.Sizeof(a[0]) - if elemSize == 0 { - return false - } - // TODO: use a runtime/unsafe facility once one becomes available. See issue 12445. - // Also see crypto/internal/alias/alias.go:AnyOverlap - return uintptr(unsafe.Pointer(&a[0])) <= uintptr(unsafe.Pointer(&b[len(b)-1]))+(elemSize-1) && - uintptr(unsafe.Pointer(&b[0])) <= uintptr(unsafe.Pointer(&a[len(a)-1]))+(elemSize-1) -} - -// startIdx returns the index in haystack where the needle starts. -// prerequisite: the needle must be aliased entirely inside the haystack. -func startIdx[E any](haystack, needle []E) int { - p := &needle[0] - for i := range haystack { - if p == &haystack[i] { - return i - } - } - // TODO: what if the overlap is by a non-integral number of Es? - panic("needle not found") -} - -// Reverse reverses the elements of the slice in place. -func Reverse[S ~[]E, E any](s S) { - for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { - s[i], s[j] = s[j], s[i] - } -} diff --git a/vendor/golang.org/x/exp/slices/sort.go b/vendor/golang.org/x/exp/slices/sort.go index b67897f76..231b6448a 100644 --- a/vendor/golang.org/x/exp/slices/sort.go +++ b/vendor/golang.org/x/exp/slices/sort.go @@ -2,8 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:generate go run $GOROOT/src/sort/gen_sort_variants.go -exp - package slices import ( @@ -13,116 +11,57 @@ import ( ) // Sort sorts a slice of any ordered type in ascending order. -// When sorting floating-point numbers, NaNs are ordered before other values. -func Sort[S ~[]E, E constraints.Ordered](x S) { +// Sort may fail to sort correctly when sorting slices of floating-point +// numbers containing Not-a-number (NaN) values. +// Use slices.SortFunc(x, func(a, b float64) bool {return a < b || (math.IsNaN(a) && !math.IsNaN(b))}) +// instead if the input may contain NaNs. +func Sort[E constraints.Ordered](x []E) { n := len(x) pdqsortOrdered(x, 0, n, bits.Len(uint(n))) } -// SortFunc sorts the slice x in ascending order as determined by the cmp -// function. This sort is not guaranteed to be stable. -// cmp(a, b) should return a negative number when a < b, a positive number when -// a > b and zero when a == b. +// SortFunc sorts the slice x in ascending order as determined by the less function. +// This sort is not guaranteed to be stable. // -// SortFunc requires that cmp is a strict weak ordering. +// SortFunc requires that less is a strict weak ordering. // See https://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings. -func SortFunc[S ~[]E, E any](x S, cmp func(a, b E) int) { +func SortFunc[E any](x []E, less func(a, b E) bool) { n := len(x) - pdqsortCmpFunc(x, 0, n, bits.Len(uint(n)), cmp) + pdqsortLessFunc(x, 0, n, bits.Len(uint(n)), less) } // SortStableFunc sorts the slice x while keeping the original order of equal -// elements, using cmp to compare elements in the same way as [SortFunc]. -func SortStableFunc[S ~[]E, E any](x S, cmp func(a, b E) int) { - stableCmpFunc(x, len(x), cmp) +// elements, using less to compare elements. +func SortStableFunc[E any](x []E, less func(a, b E) bool) { + stableLessFunc(x, len(x), less) } // IsSorted reports whether x is sorted in ascending order. -func IsSorted[S ~[]E, E constraints.Ordered](x S) bool { +func IsSorted[E constraints.Ordered](x []E) bool { for i := len(x) - 1; i > 0; i-- { - if cmpLess(x[i], x[i-1]) { + if x[i] < x[i-1] { return false } } return true } -// IsSortedFunc reports whether x is sorted in ascending order, with cmp as the -// comparison function as defined by [SortFunc]. -func IsSortedFunc[S ~[]E, E any](x S, cmp func(a, b E) int) bool { +// IsSortedFunc reports whether x is sorted in ascending order, with less as the +// comparison function. +func IsSortedFunc[E any](x []E, less func(a, b E) bool) bool { for i := len(x) - 1; i > 0; i-- { - if cmp(x[i], x[i-1]) < 0 { + if less(x[i], x[i-1]) { return false } } return true } -// Min returns the minimal value in x. It panics if x is empty. -// For floating-point numbers, Min propagates NaNs (any NaN value in x -// forces the output to be NaN). -func Min[S ~[]E, E constraints.Ordered](x S) E { - if len(x) < 1 { - panic("slices.Min: empty list") - } - m := x[0] - for i := 1; i < len(x); i++ { - m = min(m, x[i]) - } - return m -} - -// MinFunc returns the minimal value in x, using cmp to compare elements. -// It panics if x is empty. If there is more than one minimal element -// according to the cmp function, MinFunc returns the first one. -func MinFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E { - if len(x) < 1 { - panic("slices.MinFunc: empty list") - } - m := x[0] - for i := 1; i < len(x); i++ { - if cmp(x[i], m) < 0 { - m = x[i] - } - } - return m -} - -// Max returns the maximal value in x. It panics if x is empty. -// For floating-point E, Max propagates NaNs (any NaN value in x -// forces the output to be NaN). -func Max[S ~[]E, E constraints.Ordered](x S) E { - if len(x) < 1 { - panic("slices.Max: empty list") - } - m := x[0] - for i := 1; i < len(x); i++ { - m = max(m, x[i]) - } - return m -} - -// MaxFunc returns the maximal value in x, using cmp to compare elements. -// It panics if x is empty. If there is more than one maximal element -// according to the cmp function, MaxFunc returns the first one. -func MaxFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E { - if len(x) < 1 { - panic("slices.MaxFunc: empty list") - } - m := x[0] - for i := 1; i < len(x); i++ { - if cmp(x[i], m) > 0 { - m = x[i] - } - } - return m -} - // BinarySearch searches for target in a sorted slice and returns the position // where target is found, or the position where target would appear in the // sort order; it also returns a bool saying whether the target is really found // in the slice. The slice must be sorted in increasing order. -func BinarySearch[S ~[]E, E constraints.Ordered](x S, target E) (int, bool) { +func BinarySearch[E constraints.Ordered](x []E, target E) (int, bool) { // Inlining is faster than calling BinarySearchFunc with a lambda. n := len(x) // Define x[-1] < target and x[n] >= target. @@ -131,24 +70,24 @@ func BinarySearch[S ~[]E, E constraints.Ordered](x S, target E) (int, bool) { for i < j { h := int(uint(i+j) >> 1) // avoid overflow when computing h // i ≤ h < j - if cmpLess(x[h], target) { + if x[h] < target { i = h + 1 // preserves x[i-1] < target } else { j = h // preserves x[j] >= target } } // i == j, x[i-1] < target, and x[j] (= x[i]) >= target => answer is i. - return i, i < n && (x[i] == target || (isNaN(x[i]) && isNaN(target))) + return i, i < n && x[i] == target } -// BinarySearchFunc works like [BinarySearch], but uses a custom comparison +// BinarySearchFunc works like BinarySearch, but uses a custom comparison // function. The slice must be sorted in increasing order, where "increasing" // is defined by cmp. cmp should return 0 if the slice element matches // the target, a negative number if the slice element precedes the target, // or a positive number if the slice element follows the target. // cmp must implement the same ordering as the slice, such that if // cmp(a, t) < 0 and cmp(b, t) >= 0, then a must precede b in the slice. -func BinarySearchFunc[S ~[]E, E, T any](x S, target T, cmp func(E, T) int) (int, bool) { +func BinarySearchFunc[E, T any](x []E, target T, cmp func(E, T) int) (int, bool) { n := len(x) // Define cmp(x[-1], target) < 0 and cmp(x[n], target) >= 0 . // Invariant: cmp(x[i - 1], target) < 0, cmp(x[j], target) >= 0. @@ -187,9 +126,3 @@ func (r *xorshift) Next() uint64 { func nextPowerOfTwo(length int) uint { return 1 << bits.Len(uint(length)) } - -// isNaN reports whether x is a NaN without requiring the math package. -// This will always return false if T is not floating-point. -func isNaN[T constraints.Ordered](x T) bool { - return x != x -} diff --git a/vendor/golang.org/x/exp/slices/zsortanyfunc.go b/vendor/golang.org/x/exp/slices/zsortfunc.go similarity index 64% rename from vendor/golang.org/x/exp/slices/zsortanyfunc.go rename to vendor/golang.org/x/exp/slices/zsortfunc.go index 06f2c7a24..2a632476c 100644 --- a/vendor/golang.org/x/exp/slices/zsortanyfunc.go +++ b/vendor/golang.org/x/exp/slices/zsortfunc.go @@ -6,28 +6,28 @@ package slices -// insertionSortCmpFunc sorts data[a:b] using insertion sort. -func insertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) { +// insertionSortLessFunc sorts data[a:b] using insertion sort. +func insertionSortLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { for i := a + 1; i < b; i++ { - for j := i; j > a && (cmp(data[j], data[j-1]) < 0); j-- { + for j := i; j > a && less(data[j], data[j-1]); j-- { data[j], data[j-1] = data[j-1], data[j] } } } -// siftDownCmpFunc implements the heap property on data[lo:hi]. +// siftDownLessFunc implements the heap property on data[lo:hi]. // first is an offset into the array where the root of the heap lies. -func siftDownCmpFunc[E any](data []E, lo, hi, first int, cmp func(a, b E) int) { +func siftDownLessFunc[E any](data []E, lo, hi, first int, less func(a, b E) bool) { root := lo for { child := 2*root + 1 if child >= hi { break } - if child+1 < hi && (cmp(data[first+child], data[first+child+1]) < 0) { + if child+1 < hi && less(data[first+child], data[first+child+1]) { child++ } - if !(cmp(data[first+root], data[first+child]) < 0) { + if !less(data[first+root], data[first+child]) { return } data[first+root], data[first+child] = data[first+child], data[first+root] @@ -35,30 +35,30 @@ func siftDownCmpFunc[E any](data []E, lo, hi, first int, cmp func(a, b E) int) { } } -func heapSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) { +func heapSortLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { first := a lo := 0 hi := b - a // Build heap with greatest element at top. for i := (hi - 1) / 2; i >= 0; i-- { - siftDownCmpFunc(data, i, hi, first, cmp) + siftDownLessFunc(data, i, hi, first, less) } // Pop elements, largest first, into end of data. for i := hi - 1; i >= 0; i-- { data[first], data[first+i] = data[first+i], data[first] - siftDownCmpFunc(data, lo, i, first, cmp) + siftDownLessFunc(data, lo, i, first, less) } } -// pdqsortCmpFunc sorts data[a:b]. +// pdqsortLessFunc sorts data[a:b]. // The algorithm based on pattern-defeating quicksort(pdqsort), but without the optimizations from BlockQuicksort. // pdqsort paper: https://arxiv.org/pdf/2106.05123.pdf // C++ implementation: https://github.com/orlp/pdqsort // Rust implementation: https://docs.rs/pdqsort/latest/pdqsort/ // limit is the number of allowed bad (very unbalanced) pivots before falling back to heapsort. -func pdqsortCmpFunc[E any](data []E, a, b, limit int, cmp func(a, b E) int) { +func pdqsortLessFunc[E any](data []E, a, b, limit int, less func(a, b E) bool) { const maxInsertion = 12 var ( @@ -70,25 +70,25 @@ func pdqsortCmpFunc[E any](data []E, a, b, limit int, cmp func(a, b E) int) { length := b - a if length <= maxInsertion { - insertionSortCmpFunc(data, a, b, cmp) + insertionSortLessFunc(data, a, b, less) return } // Fall back to heapsort if too many bad choices were made. if limit == 0 { - heapSortCmpFunc(data, a, b, cmp) + heapSortLessFunc(data, a, b, less) return } // If the last partitioning was imbalanced, we need to breaking patterns. if !wasBalanced { - breakPatternsCmpFunc(data, a, b, cmp) + breakPatternsLessFunc(data, a, b, less) limit-- } - pivot, hint := choosePivotCmpFunc(data, a, b, cmp) + pivot, hint := choosePivotLessFunc(data, a, b, less) if hint == decreasingHint { - reverseRangeCmpFunc(data, a, b, cmp) + reverseRangeLessFunc(data, a, b, less) // The chosen pivot was pivot-a elements after the start of the array. // After reversing it is pivot-a elements before the end of the array. // The idea came from Rust's implementation. @@ -98,48 +98,48 @@ func pdqsortCmpFunc[E any](data []E, a, b, limit int, cmp func(a, b E) int) { // The slice is likely already sorted. if wasBalanced && wasPartitioned && hint == increasingHint { - if partialInsertionSortCmpFunc(data, a, b, cmp) { + if partialInsertionSortLessFunc(data, a, b, less) { return } } // Probably the slice contains many duplicate elements, partition the slice into // elements equal to and elements greater than the pivot. - if a > 0 && !(cmp(data[a-1], data[pivot]) < 0) { - mid := partitionEqualCmpFunc(data, a, b, pivot, cmp) + if a > 0 && !less(data[a-1], data[pivot]) { + mid := partitionEqualLessFunc(data, a, b, pivot, less) a = mid continue } - mid, alreadyPartitioned := partitionCmpFunc(data, a, b, pivot, cmp) + mid, alreadyPartitioned := partitionLessFunc(data, a, b, pivot, less) wasPartitioned = alreadyPartitioned leftLen, rightLen := mid-a, b-mid balanceThreshold := length / 8 if leftLen < rightLen { wasBalanced = leftLen >= balanceThreshold - pdqsortCmpFunc(data, a, mid, limit, cmp) + pdqsortLessFunc(data, a, mid, limit, less) a = mid + 1 } else { wasBalanced = rightLen >= balanceThreshold - pdqsortCmpFunc(data, mid+1, b, limit, cmp) + pdqsortLessFunc(data, mid+1, b, limit, less) b = mid } } } -// partitionCmpFunc does one quicksort partition. +// partitionLessFunc does one quicksort partition. // Let p = data[pivot] // Moves elements in data[a:b] around, so that data[i]

=p for inewpivot. // On return, data[newpivot] = p -func partitionCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int, alreadyPartitioned bool) { +func partitionLessFunc[E any](data []E, a, b, pivot int, less func(a, b E) bool) (newpivot int, alreadyPartitioned bool) { data[a], data[pivot] = data[pivot], data[a] i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned - for i <= j && (cmp(data[i], data[a]) < 0) { + for i <= j && less(data[i], data[a]) { i++ } - for i <= j && !(cmp(data[j], data[a]) < 0) { + for i <= j && !less(data[j], data[a]) { j-- } if i > j { @@ -151,10 +151,10 @@ func partitionCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (n j-- for { - for i <= j && (cmp(data[i], data[a]) < 0) { + for i <= j && less(data[i], data[a]) { i++ } - for i <= j && !(cmp(data[j], data[a]) < 0) { + for i <= j && !less(data[j], data[a]) { j-- } if i > j { @@ -168,17 +168,17 @@ func partitionCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (n return j, false } -// partitionEqualCmpFunc partitions data[a:b] into elements equal to data[pivot] followed by elements greater than data[pivot]. +// partitionEqualLessFunc partitions data[a:b] into elements equal to data[pivot] followed by elements greater than data[pivot]. // It assumed that data[a:b] does not contain elements smaller than the data[pivot]. -func partitionEqualCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) int) (newpivot int) { +func partitionEqualLessFunc[E any](data []E, a, b, pivot int, less func(a, b E) bool) (newpivot int) { data[a], data[pivot] = data[pivot], data[a] i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned for { - for i <= j && !(cmp(data[a], data[i]) < 0) { + for i <= j && !less(data[a], data[i]) { i++ } - for i <= j && (cmp(data[a], data[j]) < 0) { + for i <= j && less(data[a], data[j]) { j-- } if i > j { @@ -191,15 +191,15 @@ func partitionEqualCmpFunc[E any](data []E, a, b, pivot int, cmp func(a, b E) in return i } -// partialInsertionSortCmpFunc partially sorts a slice, returns true if the slice is sorted at the end. -func partialInsertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) bool { +// partialInsertionSortLessFunc partially sorts a slice, returns true if the slice is sorted at the end. +func partialInsertionSortLessFunc[E any](data []E, a, b int, less func(a, b E) bool) bool { const ( maxSteps = 5 // maximum number of adjacent out-of-order pairs that will get shifted shortestShifting = 50 // don't shift any elements on short arrays ) i := a + 1 for j := 0; j < maxSteps; j++ { - for i < b && !(cmp(data[i], data[i-1]) < 0) { + for i < b && !less(data[i], data[i-1]) { i++ } @@ -216,7 +216,7 @@ func partialInsertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int // Shift the smaller one to the left. if i-a >= 2 { for j := i - 1; j >= 1; j-- { - if !(cmp(data[j], data[j-1]) < 0) { + if !less(data[j], data[j-1]) { break } data[j], data[j-1] = data[j-1], data[j] @@ -225,7 +225,7 @@ func partialInsertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int // Shift the greater one to the right. if b-i >= 2 { for j := i + 1; j < b; j++ { - if !(cmp(data[j], data[j-1]) < 0) { + if !less(data[j], data[j-1]) { break } data[j], data[j-1] = data[j-1], data[j] @@ -235,9 +235,9 @@ func partialInsertionSortCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int return false } -// breakPatternsCmpFunc scatters some elements around in an attempt to break some patterns +// breakPatternsLessFunc scatters some elements around in an attempt to break some patterns // that might cause imbalanced partitions in quicksort. -func breakPatternsCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) { +func breakPatternsLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { length := b - a if length >= 8 { random := xorshift(length) @@ -253,12 +253,12 @@ func breakPatternsCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) { } } -// choosePivotCmpFunc chooses a pivot in data[a:b]. +// choosePivotLessFunc chooses a pivot in data[a:b]. // // [0,8): chooses a static pivot. // [8,shortestNinther): uses the simple median-of-three method. // [shortestNinther,∞): uses the Tukey ninther method. -func choosePivotCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) (pivot int, hint sortedHint) { +func choosePivotLessFunc[E any](data []E, a, b int, less func(a, b E) bool) (pivot int, hint sortedHint) { const ( shortestNinther = 50 maxSwaps = 4 * 3 @@ -276,12 +276,12 @@ func choosePivotCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) (pivot if l >= 8 { if l >= shortestNinther { // Tukey ninther method, the idea came from Rust's implementation. - i = medianAdjacentCmpFunc(data, i, &swaps, cmp) - j = medianAdjacentCmpFunc(data, j, &swaps, cmp) - k = medianAdjacentCmpFunc(data, k, &swaps, cmp) + i = medianAdjacentLessFunc(data, i, &swaps, less) + j = medianAdjacentLessFunc(data, j, &swaps, less) + k = medianAdjacentLessFunc(data, k, &swaps, less) } // Find the median among i, j, k and stores it into j. - j = medianCmpFunc(data, i, j, k, &swaps, cmp) + j = medianLessFunc(data, i, j, k, &swaps, less) } switch swaps { @@ -294,29 +294,29 @@ func choosePivotCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) (pivot } } -// order2CmpFunc returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a. -func order2CmpFunc[E any](data []E, a, b int, swaps *int, cmp func(a, b E) int) (int, int) { - if cmp(data[b], data[a]) < 0 { +// order2LessFunc returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a. +func order2LessFunc[E any](data []E, a, b int, swaps *int, less func(a, b E) bool) (int, int) { + if less(data[b], data[a]) { *swaps++ return b, a } return a, b } -// medianCmpFunc returns x where data[x] is the median of data[a],data[b],data[c], where x is a, b, or c. -func medianCmpFunc[E any](data []E, a, b, c int, swaps *int, cmp func(a, b E) int) int { - a, b = order2CmpFunc(data, a, b, swaps, cmp) - b, c = order2CmpFunc(data, b, c, swaps, cmp) - a, b = order2CmpFunc(data, a, b, swaps, cmp) +// medianLessFunc returns x where data[x] is the median of data[a],data[b],data[c], where x is a, b, or c. +func medianLessFunc[E any](data []E, a, b, c int, swaps *int, less func(a, b E) bool) int { + a, b = order2LessFunc(data, a, b, swaps, less) + b, c = order2LessFunc(data, b, c, swaps, less) + a, b = order2LessFunc(data, a, b, swaps, less) return b } -// medianAdjacentCmpFunc finds the median of data[a - 1], data[a], data[a + 1] and stores the index into a. -func medianAdjacentCmpFunc[E any](data []E, a int, swaps *int, cmp func(a, b E) int) int { - return medianCmpFunc(data, a-1, a, a+1, swaps, cmp) +// medianAdjacentLessFunc finds the median of data[a - 1], data[a], data[a + 1] and stores the index into a. +func medianAdjacentLessFunc[E any](data []E, a int, swaps *int, less func(a, b E) bool) int { + return medianLessFunc(data, a-1, a, a+1, swaps, less) } -func reverseRangeCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) { +func reverseRangeLessFunc[E any](data []E, a, b int, less func(a, b E) bool) { i := a j := b - 1 for i < j { @@ -326,37 +326,37 @@ func reverseRangeCmpFunc[E any](data []E, a, b int, cmp func(a, b E) int) { } } -func swapRangeCmpFunc[E any](data []E, a, b, n int, cmp func(a, b E) int) { +func swapRangeLessFunc[E any](data []E, a, b, n int, less func(a, b E) bool) { for i := 0; i < n; i++ { data[a+i], data[b+i] = data[b+i], data[a+i] } } -func stableCmpFunc[E any](data []E, n int, cmp func(a, b E) int) { +func stableLessFunc[E any](data []E, n int, less func(a, b E) bool) { blockSize := 20 // must be > 0 a, b := 0, blockSize for b <= n { - insertionSortCmpFunc(data, a, b, cmp) + insertionSortLessFunc(data, a, b, less) a = b b += blockSize } - insertionSortCmpFunc(data, a, n, cmp) + insertionSortLessFunc(data, a, n, less) for blockSize < n { a, b = 0, 2*blockSize for b <= n { - symMergeCmpFunc(data, a, a+blockSize, b, cmp) + symMergeLessFunc(data, a, a+blockSize, b, less) a = b b += 2 * blockSize } if m := a + blockSize; m < n { - symMergeCmpFunc(data, a, m, n, cmp) + symMergeLessFunc(data, a, m, n, less) } blockSize *= 2 } } -// symMergeCmpFunc merges the two sorted subsequences data[a:m] and data[m:b] using +// symMergeLessFunc merges the two sorted subsequences data[a:m] and data[m:b] using // the SymMerge algorithm from Pok-Son Kim and Arne Kutzner, "Stable Minimum // Storage Merging by Symmetric Comparisons", in Susanne Albers and Tomasz // Radzik, editors, Algorithms - ESA 2004, volume 3221 of Lecture Notes in @@ -375,7 +375,7 @@ func stableCmpFunc[E any](data []E, n int, cmp func(a, b E) int) { // symMerge assumes non-degenerate arguments: a < m && m < b. // Having the caller check this condition eliminates many leaf recursion calls, // which improves performance. -func symMergeCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) { +func symMergeLessFunc[E any](data []E, a, m, b int, less func(a, b E) bool) { // Avoid unnecessary recursions of symMerge // by direct insertion of data[a] into data[m:b] // if data[a:m] only contains one element. @@ -387,7 +387,7 @@ func symMergeCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) { j := b for i < j { h := int(uint(i+j) >> 1) - if cmp(data[h], data[a]) < 0 { + if less(data[h], data[a]) { i = h + 1 } else { j = h @@ -411,7 +411,7 @@ func symMergeCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) { j := m for i < j { h := int(uint(i+j) >> 1) - if !(cmp(data[m], data[h]) < 0) { + if !less(data[m], data[h]) { i = h + 1 } else { j = h @@ -438,7 +438,7 @@ func symMergeCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) { for start < r { c := int(uint(start+r) >> 1) - if !(cmp(data[p-c], data[c]) < 0) { + if !less(data[p-c], data[c]) { start = c + 1 } else { r = c @@ -447,33 +447,33 @@ func symMergeCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) { end := n - start if start < m && m < end { - rotateCmpFunc(data, start, m, end, cmp) + rotateLessFunc(data, start, m, end, less) } if a < start && start < mid { - symMergeCmpFunc(data, a, start, mid, cmp) + symMergeLessFunc(data, a, start, mid, less) } if mid < end && end < b { - symMergeCmpFunc(data, mid, end, b, cmp) + symMergeLessFunc(data, mid, end, b, less) } } -// rotateCmpFunc rotates two consecutive blocks u = data[a:m] and v = data[m:b] in data: +// rotateLessFunc rotates two consecutive blocks u = data[a:m] and v = data[m:b] in data: // Data of the form 'x u v y' is changed to 'x v u y'. // rotate performs at most b-a many calls to data.Swap, // and it assumes non-degenerate arguments: a < m && m < b. -func rotateCmpFunc[E any](data []E, a, m, b int, cmp func(a, b E) int) { +func rotateLessFunc[E any](data []E, a, m, b int, less func(a, b E) bool) { i := m - a j := b - m for i != j { if i > j { - swapRangeCmpFunc(data, m-i, m, j, cmp) + swapRangeLessFunc(data, m-i, m, j, less) i -= j } else { - swapRangeCmpFunc(data, m-i, m+j-i, i, cmp) + swapRangeLessFunc(data, m-i, m+j-i, i, less) j -= i } } // i == j - swapRangeCmpFunc(data, m-i, m, i, cmp) + swapRangeLessFunc(data, m-i, m, i, less) } diff --git a/vendor/golang.org/x/exp/slices/zsortordered.go b/vendor/golang.org/x/exp/slices/zsortordered.go index 99b47c398..efaa1c8b7 100644 --- a/vendor/golang.org/x/exp/slices/zsortordered.go +++ b/vendor/golang.org/x/exp/slices/zsortordered.go @@ -11,7 +11,7 @@ import "golang.org/x/exp/constraints" // insertionSortOrdered sorts data[a:b] using insertion sort. func insertionSortOrdered[E constraints.Ordered](data []E, a, b int) { for i := a + 1; i < b; i++ { - for j := i; j > a && cmpLess(data[j], data[j-1]); j-- { + for j := i; j > a && (data[j] < data[j-1]); j-- { data[j], data[j-1] = data[j-1], data[j] } } @@ -26,10 +26,10 @@ func siftDownOrdered[E constraints.Ordered](data []E, lo, hi, first int) { if child >= hi { break } - if child+1 < hi && cmpLess(data[first+child], data[first+child+1]) { + if child+1 < hi && (data[first+child] < data[first+child+1]) { child++ } - if !cmpLess(data[first+root], data[first+child]) { + if !(data[first+root] < data[first+child]) { return } data[first+root], data[first+child] = data[first+child], data[first+root] @@ -107,7 +107,7 @@ func pdqsortOrdered[E constraints.Ordered](data []E, a, b, limit int) { // Probably the slice contains many duplicate elements, partition the slice into // elements equal to and elements greater than the pivot. - if a > 0 && !cmpLess(data[a-1], data[pivot]) { + if a > 0 && !(data[a-1] < data[pivot]) { mid := partitionEqualOrdered(data, a, b, pivot) a = mid continue @@ -138,10 +138,10 @@ func partitionOrdered[E constraints.Ordered](data []E, a, b, pivot int) (newpivo data[a], data[pivot] = data[pivot], data[a] i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned - for i <= j && cmpLess(data[i], data[a]) { + for i <= j && (data[i] < data[a]) { i++ } - for i <= j && !cmpLess(data[j], data[a]) { + for i <= j && !(data[j] < data[a]) { j-- } if i > j { @@ -153,10 +153,10 @@ func partitionOrdered[E constraints.Ordered](data []E, a, b, pivot int) (newpivo j-- for { - for i <= j && cmpLess(data[i], data[a]) { + for i <= j && (data[i] < data[a]) { i++ } - for i <= j && !cmpLess(data[j], data[a]) { + for i <= j && !(data[j] < data[a]) { j-- } if i > j { @@ -177,10 +177,10 @@ func partitionEqualOrdered[E constraints.Ordered](data []E, a, b, pivot int) (ne i, j := a+1, b-1 // i and j are inclusive of the elements remaining to be partitioned for { - for i <= j && !cmpLess(data[a], data[i]) { + for i <= j && !(data[a] < data[i]) { i++ } - for i <= j && cmpLess(data[a], data[j]) { + for i <= j && (data[a] < data[j]) { j-- } if i > j { @@ -201,7 +201,7 @@ func partialInsertionSortOrdered[E constraints.Ordered](data []E, a, b int) bool ) i := a + 1 for j := 0; j < maxSteps; j++ { - for i < b && !cmpLess(data[i], data[i-1]) { + for i < b && !(data[i] < data[i-1]) { i++ } @@ -218,7 +218,7 @@ func partialInsertionSortOrdered[E constraints.Ordered](data []E, a, b int) bool // Shift the smaller one to the left. if i-a >= 2 { for j := i - 1; j >= 1; j-- { - if !cmpLess(data[j], data[j-1]) { + if !(data[j] < data[j-1]) { break } data[j], data[j-1] = data[j-1], data[j] @@ -227,7 +227,7 @@ func partialInsertionSortOrdered[E constraints.Ordered](data []E, a, b int) bool // Shift the greater one to the right. if b-i >= 2 { for j := i + 1; j < b; j++ { - if !cmpLess(data[j], data[j-1]) { + if !(data[j] < data[j-1]) { break } data[j], data[j-1] = data[j-1], data[j] @@ -298,7 +298,7 @@ func choosePivotOrdered[E constraints.Ordered](data []E, a, b int) (pivot int, h // order2Ordered returns x,y where data[x] <= data[y], where x,y=a,b or x,y=b,a. func order2Ordered[E constraints.Ordered](data []E, a, b int, swaps *int) (int, int) { - if cmpLess(data[b], data[a]) { + if data[b] < data[a] { *swaps++ return b, a } @@ -389,7 +389,7 @@ func symMergeOrdered[E constraints.Ordered](data []E, a, m, b int) { j := b for i < j { h := int(uint(i+j) >> 1) - if cmpLess(data[h], data[a]) { + if data[h] < data[a] { i = h + 1 } else { j = h @@ -413,7 +413,7 @@ func symMergeOrdered[E constraints.Ordered](data []E, a, m, b int) { j := m for i < j { h := int(uint(i+j) >> 1) - if !cmpLess(data[m], data[h]) { + if !(data[m] < data[h]) { i = h + 1 } else { j = h @@ -440,7 +440,7 @@ func symMergeOrdered[E constraints.Ordered](data []E, a, m, b int) { for start < r { c := int(uint(start+r) >> 1) - if !cmpLess(data[p-c], data[c]) { + if !(data[p-c] < data[c]) { start = c + 1 } else { r = c diff --git a/vendor/golang.org/x/mod/modfile/rule.go b/vendor/golang.org/x/mod/modfile/rule.go index e0869fa38..930b6c59b 100644 --- a/vendor/golang.org/x/mod/modfile/rule.go +++ b/vendor/golang.org/x/mod/modfile/rule.go @@ -367,7 +367,7 @@ func (f *File) add(errs *ErrorList, block *LineBlock, line *Line, verb string, a } } if !fixed { - errorf("invalid go version '%s': must match format 1.23.0", args[0]) + errorf("invalid go version '%s': must match format 1.23", args[0]) return } } @@ -384,7 +384,7 @@ func (f *File) add(errs *ErrorList, block *LineBlock, line *Line, verb string, a errorf("toolchain directive expects exactly one argument") return } else if strict && !ToolchainRE.MatchString(args[0]) { - errorf("invalid toolchain version '%s': must match format go1.23.0 or local", args[0]) + errorf("invalid toolchain version '%s': must match format go1.23 or local", args[0]) return } f.Toolchain = &Toolchain{Syntax: line} diff --git a/vendor/golang.org/x/net/dns/dnsmessage/message.go b/vendor/golang.org/x/net/dns/dnsmessage/message.go index b6b4f9c19..37da3de4d 100644 --- a/vendor/golang.org/x/net/dns/dnsmessage/message.go +++ b/vendor/golang.org/x/net/dns/dnsmessage/message.go @@ -361,8 +361,6 @@ func (m *Header) GoString() string { "Truncated: " + printBool(m.Truncated) + ", " + "RecursionDesired: " + printBool(m.RecursionDesired) + ", " + "RecursionAvailable: " + printBool(m.RecursionAvailable) + ", " + - "AuthenticData: " + printBool(m.AuthenticData) + ", " + - "CheckingDisabled: " + printBool(m.CheckingDisabled) + ", " + "RCode: " + m.RCode.GoString() + "}" } @@ -492,7 +490,7 @@ func (r *Resource) GoString() string { // A ResourceBody is a DNS resource record minus the header. type ResourceBody interface { // pack packs a Resource except for its header. - pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) + pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) // realType returns the actual type of the Resource. This is used to // fill in the header Type field. @@ -503,7 +501,7 @@ type ResourceBody interface { } // pack appends the wire format of the Resource to msg. -func (r *Resource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *Resource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { if r.Body == nil { return msg, errNilResouceBody } @@ -542,13 +540,11 @@ type Parser struct { msg []byte header header - section section - off int - index int - resHeaderValid bool - resHeaderOffset int - resHeaderType Type - resHeaderLength uint16 + section section + off int + index int + resHeaderValid bool + resHeader ResourceHeader } // Start parses the header and enables the parsing of Questions. @@ -599,9 +595,8 @@ func (p *Parser) resource(sec section) (Resource, error) { func (p *Parser) resourceHeader(sec section) (ResourceHeader, error) { if p.resHeaderValid { - p.off = p.resHeaderOffset + return p.resHeader, nil } - if err := p.checkAdvance(sec); err != nil { return ResourceHeader{}, err } @@ -611,16 +606,14 @@ func (p *Parser) resourceHeader(sec section) (ResourceHeader, error) { return ResourceHeader{}, err } p.resHeaderValid = true - p.resHeaderOffset = p.off - p.resHeaderType = hdr.Type - p.resHeaderLength = hdr.Length + p.resHeader = hdr p.off = off return hdr, nil } func (p *Parser) skipResource(sec section) error { - if p.resHeaderValid && p.section == sec { - newOff := p.off + int(p.resHeaderLength) + if p.resHeaderValid { + newOff := p.off + int(p.resHeader.Length) if newOff > len(p.msg) { return errResourceLen } @@ -871,14 +864,14 @@ func (p *Parser) SkipAllAdditionals() error { // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) CNAMEResource() (CNAMEResource, error) { - if !p.resHeaderValid || p.resHeaderType != TypeCNAME { + if !p.resHeaderValid || p.resHeader.Type != TypeCNAME { return CNAMEResource{}, ErrNotStarted } r, err := unpackCNAMEResource(p.msg, p.off) if err != nil { return CNAMEResource{}, err } - p.off += int(p.resHeaderLength) + p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil @@ -889,14 +882,14 @@ func (p *Parser) CNAMEResource() (CNAMEResource, error) { // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) MXResource() (MXResource, error) { - if !p.resHeaderValid || p.resHeaderType != TypeMX { + if !p.resHeaderValid || p.resHeader.Type != TypeMX { return MXResource{}, ErrNotStarted } r, err := unpackMXResource(p.msg, p.off) if err != nil { return MXResource{}, err } - p.off += int(p.resHeaderLength) + p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil @@ -907,14 +900,14 @@ func (p *Parser) MXResource() (MXResource, error) { // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) NSResource() (NSResource, error) { - if !p.resHeaderValid || p.resHeaderType != TypeNS { + if !p.resHeaderValid || p.resHeader.Type != TypeNS { return NSResource{}, ErrNotStarted } r, err := unpackNSResource(p.msg, p.off) if err != nil { return NSResource{}, err } - p.off += int(p.resHeaderLength) + p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil @@ -925,14 +918,14 @@ func (p *Parser) NSResource() (NSResource, error) { // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) PTRResource() (PTRResource, error) { - if !p.resHeaderValid || p.resHeaderType != TypePTR { + if !p.resHeaderValid || p.resHeader.Type != TypePTR { return PTRResource{}, ErrNotStarted } r, err := unpackPTRResource(p.msg, p.off) if err != nil { return PTRResource{}, err } - p.off += int(p.resHeaderLength) + p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil @@ -943,14 +936,14 @@ func (p *Parser) PTRResource() (PTRResource, error) { // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) SOAResource() (SOAResource, error) { - if !p.resHeaderValid || p.resHeaderType != TypeSOA { + if !p.resHeaderValid || p.resHeader.Type != TypeSOA { return SOAResource{}, ErrNotStarted } r, err := unpackSOAResource(p.msg, p.off) if err != nil { return SOAResource{}, err } - p.off += int(p.resHeaderLength) + p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil @@ -961,14 +954,14 @@ func (p *Parser) SOAResource() (SOAResource, error) { // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) TXTResource() (TXTResource, error) { - if !p.resHeaderValid || p.resHeaderType != TypeTXT { + if !p.resHeaderValid || p.resHeader.Type != TypeTXT { return TXTResource{}, ErrNotStarted } - r, err := unpackTXTResource(p.msg, p.off, p.resHeaderLength) + r, err := unpackTXTResource(p.msg, p.off, p.resHeader.Length) if err != nil { return TXTResource{}, err } - p.off += int(p.resHeaderLength) + p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil @@ -979,14 +972,14 @@ func (p *Parser) TXTResource() (TXTResource, error) { // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) SRVResource() (SRVResource, error) { - if !p.resHeaderValid || p.resHeaderType != TypeSRV { + if !p.resHeaderValid || p.resHeader.Type != TypeSRV { return SRVResource{}, ErrNotStarted } r, err := unpackSRVResource(p.msg, p.off) if err != nil { return SRVResource{}, err } - p.off += int(p.resHeaderLength) + p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil @@ -997,14 +990,14 @@ func (p *Parser) SRVResource() (SRVResource, error) { // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) AResource() (AResource, error) { - if !p.resHeaderValid || p.resHeaderType != TypeA { + if !p.resHeaderValid || p.resHeader.Type != TypeA { return AResource{}, ErrNotStarted } r, err := unpackAResource(p.msg, p.off) if err != nil { return AResource{}, err } - p.off += int(p.resHeaderLength) + p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil @@ -1015,14 +1008,14 @@ func (p *Parser) AResource() (AResource, error) { // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) AAAAResource() (AAAAResource, error) { - if !p.resHeaderValid || p.resHeaderType != TypeAAAA { + if !p.resHeaderValid || p.resHeader.Type != TypeAAAA { return AAAAResource{}, ErrNotStarted } r, err := unpackAAAAResource(p.msg, p.off) if err != nil { return AAAAResource{}, err } - p.off += int(p.resHeaderLength) + p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil @@ -1033,14 +1026,14 @@ func (p *Parser) AAAAResource() (AAAAResource, error) { // One of the XXXHeader methods must have been called before calling this // method. func (p *Parser) OPTResource() (OPTResource, error) { - if !p.resHeaderValid || p.resHeaderType != TypeOPT { + if !p.resHeaderValid || p.resHeader.Type != TypeOPT { return OPTResource{}, ErrNotStarted } - r, err := unpackOPTResource(p.msg, p.off, p.resHeaderLength) + r, err := unpackOPTResource(p.msg, p.off, p.resHeader.Length) if err != nil { return OPTResource{}, err } - p.off += int(p.resHeaderLength) + p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil @@ -1054,11 +1047,11 @@ func (p *Parser) UnknownResource() (UnknownResource, error) { if !p.resHeaderValid { return UnknownResource{}, ErrNotStarted } - r, err := unpackUnknownResource(p.resHeaderType, p.msg, p.off, p.resHeaderLength) + r, err := unpackUnknownResource(p.resHeader.Type, p.msg, p.off, p.resHeader.Length) if err != nil { return UnknownResource{}, err } - p.off += int(p.resHeaderLength) + p.off += int(p.resHeader.Length) p.resHeaderValid = false p.index++ return r, nil @@ -1129,7 +1122,7 @@ func (m *Message) AppendPack(b []byte) ([]byte, error) { // DNS messages can be a maximum of 512 bytes long. Without compression, // many DNS response messages are over this limit, so enabling // compression will help ensure compliance. - compression := map[string]uint16{} + compression := map[string]int{} for i := range m.Questions { var err error @@ -1220,7 +1213,7 @@ type Builder struct { // compression is a mapping from name suffixes to their starting index // in msg. - compression map[string]uint16 + compression map[string]int } // NewBuilder creates a new builder with compression disabled. @@ -1257,7 +1250,7 @@ func NewBuilder(buf []byte, h Header) Builder { // // Compression should be enabled before any sections are added for best results. func (b *Builder) EnableCompression() { - b.compression = map[string]uint16{} + b.compression = map[string]int{} } func (b *Builder) startCheck(s section) error { @@ -1673,7 +1666,7 @@ func (h *ResourceHeader) GoString() string { // pack appends the wire format of the ResourceHeader to oldMsg. // // lenOff is the offset in msg where the Length field was packed. -func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]uint16, compressionOff int) (msg []byte, lenOff int, err error) { +func (h *ResourceHeader) pack(oldMsg []byte, compression map[string]int, compressionOff int) (msg []byte, lenOff int, err error) { msg = oldMsg if msg, err = h.Name.pack(msg, compression, compressionOff); err != nil { return oldMsg, 0, &nestedError{"Name", err} @@ -1901,7 +1894,7 @@ func unpackBytes(msg []byte, off int, field []byte) (int, error) { const nonEncodedNameMax = 254 -// A Name is a non-encoded and non-escaped domain name. It is used instead of strings to avoid +// A Name is a non-encoded domain name. It is used instead of strings to avoid // allocations. type Name struct { Data [255]byte @@ -1928,8 +1921,6 @@ func MustNewName(name string) Name { } // String implements fmt.Stringer.String. -// -// Note: characters inside the labels are not escaped in any way. func (n Name) String() string { return string(n.Data[:n.Length]) } @@ -1946,7 +1937,7 @@ func (n *Name) GoString() string { // // The compression map will be updated with new domain suffixes. If compression // is nil, compression will not be used. -func (n *Name) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (n *Name) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { oldMsg := msg if n.Length > nonEncodedNameMax { @@ -1963,8 +1954,6 @@ func (n *Name) pack(msg []byte, compression map[string]uint16, compressionOff in return append(msg, 0), nil } - var nameAsStr string - // Emit sequence of counted strings, chopping at dots. for i, begin := 0, 0; i < int(n.Length); i++ { // Check for the end of the segment. @@ -1995,22 +1984,16 @@ func (n *Name) pack(msg []byte, compression map[string]uint16, compressionOff in // segment. A pointer is two bytes with the two most significant // bits set to 1 to indicate that it is a pointer. if (i == 0 || n.Data[i-1] == '.') && compression != nil { - if ptr, ok := compression[string(n.Data[i:n.Length])]; ok { + if ptr, ok := compression[string(n.Data[i:])]; ok { // Hit. Emit a pointer instead of the rest of // the domain. return append(msg, byte(ptr>>8|0xC0), byte(ptr)), nil } // Miss. Add the suffix to the compression table if the - // offset can be stored in the available 14 bits. - newPtr := len(msg) - compressionOff - if newPtr <= int(^uint16(0)>>2) { - if nameAsStr == "" { - // allocate n.Data on the heap once, to avoid allocating it - // multiple times (for next labels). - nameAsStr = string(n.Data[:n.Length]) - } - compression[nameAsStr[i:]] = uint16(newPtr) + // offset can be stored in the available 14 bytes. + if len(msg) <= int(^uint16(0)>>2) { + compression[string(n.Data[i:])] = len(msg) - compressionOff } } } @@ -2150,7 +2133,7 @@ type Question struct { } // pack appends the wire format of the Question to msg. -func (q *Question) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (q *Question) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { msg, err := q.Name.pack(msg, compression, compressionOff) if err != nil { return msg, &nestedError{"Name", err} @@ -2246,7 +2229,7 @@ func (r *CNAMEResource) realType() Type { } // pack appends the wire format of the CNAMEResource to msg. -func (r *CNAMEResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *CNAMEResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { return r.CNAME.pack(msg, compression, compressionOff) } @@ -2274,7 +2257,7 @@ func (r *MXResource) realType() Type { } // pack appends the wire format of the MXResource to msg. -func (r *MXResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *MXResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { oldMsg := msg msg = packUint16(msg, r.Pref) msg, err := r.MX.pack(msg, compression, compressionOff) @@ -2313,7 +2296,7 @@ func (r *NSResource) realType() Type { } // pack appends the wire format of the NSResource to msg. -func (r *NSResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *NSResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { return r.NS.pack(msg, compression, compressionOff) } @@ -2340,7 +2323,7 @@ func (r *PTRResource) realType() Type { } // pack appends the wire format of the PTRResource to msg. -func (r *PTRResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *PTRResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { return r.PTR.pack(msg, compression, compressionOff) } @@ -2377,7 +2360,7 @@ func (r *SOAResource) realType() Type { } // pack appends the wire format of the SOAResource to msg. -func (r *SOAResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *SOAResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { oldMsg := msg msg, err := r.NS.pack(msg, compression, compressionOff) if err != nil { @@ -2449,7 +2432,7 @@ func (r *TXTResource) realType() Type { } // pack appends the wire format of the TXTResource to msg. -func (r *TXTResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *TXTResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { oldMsg := msg for _, s := range r.TXT { var err error @@ -2505,7 +2488,7 @@ func (r *SRVResource) realType() Type { } // pack appends the wire format of the SRVResource to msg. -func (r *SRVResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *SRVResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { oldMsg := msg msg = packUint16(msg, r.Priority) msg = packUint16(msg, r.Weight) @@ -2556,7 +2539,7 @@ func (r *AResource) realType() Type { } // pack appends the wire format of the AResource to msg. -func (r *AResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *AResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { return packBytes(msg, r.A[:]), nil } @@ -2590,7 +2573,7 @@ func (r *AAAAResource) GoString() string { } // pack appends the wire format of the AAAAResource to msg. -func (r *AAAAResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *AAAAResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { return packBytes(msg, r.AAAA[:]), nil } @@ -2630,7 +2613,7 @@ func (r *OPTResource) realType() Type { return TypeOPT } -func (r *OPTResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *OPTResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { for _, opt := range r.Options { msg = packUint16(msg, opt.Code) l := uint16(len(opt.Data)) @@ -2688,7 +2671,7 @@ func (r *UnknownResource) realType() Type { } // pack appends the wire format of the UnknownResource to msg. -func (r *UnknownResource) pack(msg []byte, compression map[string]uint16, compressionOff int) ([]byte, error) { +func (r *UnknownResource) pack(msg []byte, compression map[string]int, compressionOff int) ([]byte, error) { return packBytes(msg, r.Data[:]), nil } diff --git a/vendor/golang.org/x/net/publicsuffix/data/children b/vendor/golang.org/x/net/publicsuffix/data/children index 08261bffd196fd6942b4cebb5ff06e0ffe53808d..1038c561ade4683e91b37e8298fc5ead7c306779 100644 GIT binary patch literal 2876 zcmWO8`CAib0svrUzRb+`nSk6zK|{VtNTRiJd7yyG8JU16mRliLD^_b=t;%||>na8l zP!yF%fdB@t+Ui#Avu#}!)CeZrS5%ZMplz*Iv9&5~*B{>h;dOCwadCeq;GIS9q`Z^& z4zVS!huE^`0kP%QL!#hTKe0dV5pkd}k|?!C6Nl&oqRgryj?$?_d0`G=rZt2)emhZX z-9en7jfADpL|Ci`i8}faai*}0IAc9YoTX2R&&HotpS7M5e;NNJao+kBaiQ><_=2^8 zxJch1F2>u5ONGtEC2I%qt+kW*&U&Bt!TN}}690_2YJE;zx4sqEGeBIQz$5DSQiP46 z346kOMDyNYqMeyTbTF|*XM&RGx}8MyGpQt*u$=@DVW1RXU~nZTDBVa8s31KJv7}dH zBIym6lHSS`(z|gP>8ng7eGQqUP?<$eHK@s{jhpc_xP=T*Zp8tHe~|%=yGSwoHz`r> z)<_JcSPBnfsj`ez7!GR`jVH+&@Dv%`cn*ia+c-qoh(iobI27K&p-MXrH8hiA?+&y|}@M@D2V1e1j9<8#Y&blbeWd+C1_t-LV zFPDvbjVnn9e-(BZ^RUCF!FO$1e2@DG-!tapd$u+BKKC)cZ(N7__@9t{+^1xpZ3BK_ z+^BiTZN?961>`V)8y?}C@Ca9iM~sK@DE|l^HJ0O1+cErze;hwDR^UgrD*Tvl#*evb z^0Bc7|IF3mpN(JPpKV{`C;ao|6Yc_jV*C$&V*3XF!oP@r;V$8){LA<$_h0g<@jLPv z|9kS8?F#uTca40(uP4WhjpT3q7V>v~7x}x*LB6)#C*N?7@EhZgCI~j&0$~Cx8>VVw!|d%~wxAQtHFbe- z!9%dvKG>A@uAl4OuxMFt@*X#=tTqgl#u|G&m!hma509ElUken0(Qe4A9O41^* zym>KL(aeFg;#82@KJFwSYKQPHo9H~8wqhMdMH`rIA02L+E*-E#6u$9T1*vgX6*vgj8Y?a#< zwkmlmTUAoPR<-;SnBBGkbMki9T(X0$F4@V}xb0$VN_Mj~Ero1t@?N&Kq=>C;*#|7i zMsTvE6r3(O#&d6}m3X+vNIX(vB_0RjBpz+?JkPcSo_8C^Qyoait;Ej8= z@c!=nmEv{&O$k=uMdO=r+-qkyl^6me1$6X8Kq1|gj8iuh`!2qi@qvt zD`oL5pw9FhpuXujMSXw7MqTasiE8$JOSPqkQ9bF4sRu_hsnJQBsh=j5Q_m-z);~|b zNsS%7MUC~gP`~%KQhyx1PmT8uQGfQ1QGchuqUqj0X(q#uM#8D|1fhf$2<3r-j3C<0 z5ll}ME}$otN6_w$DB80;hV~LB(q0Y~?JZnNPjaNtLSZgFIU|qubLeURjP$^7w=>?-ckWN6n~%?+Tm9zH?b#7@ zXLcOjdpwDD_^k?bWakAsj;rarej55OKV9Ho*?$E7b^JBslKn>JQb8~-eI!HV02%2| z$$&qUfeL|)m*d9pDm-MoK2I5)<0Yf}Cd-%{KN(XoRR;a1$zVk!2=9l1)T!@NY+X-;H1`;(b2(Nd->H-+gk zFOzlkFK4<%sZ4k73Z~oq0n^=|ChN&fXL`(;OizCn(<{oB_2%X<3z;Ev5i^{-j~O->Ll;qr{M`oRE(3&|2mo>-j|YhX z3QnwM$KsKCQt%ZKoA40!@ zPoRImdMK*?6sq!e!VGaR%uwgSj6pTb5^G_WdNo{GlMmJ6&2qJRH`I#vKz)q~>IaX& zj|Pvz{2DX-c<>}#J9r+h6JLbu)R*7}@nyJS@Fv`(zAfKW(++pmbjWuOzJZ^M-@-4% zT<`gC~Y|LJQsx>of=8Da~Pc23Nu}8Vfv&>)<(j8lJ}&;Q65|@XF9N z_&+=buWDYxtF^D;b^Hci*Sf%ZmVoucJlMc8u;B!R4Z{=Q4VDjYX$7!}^?^-V3AAaY zuw{5AY#&}A?_d*PhgJzYhL=ExmV=HHYUmi&z`Lv#KG5pmL+xj9h%JCaS_2%>7Qr{{ zVK}aRj7au5;yIy$(s?N;i;seG`Xbsn2|=A7nqm5d_}q!P)U)ktAE zfu`$Dq8XAiXom9~de3qm&D4E^f+Uwwkn=hUw%kA=Ix7m5G@($Z9fj#y(QHXOn(gdD zb1c1RuI?V1CwYM8IR{X2h9V^|P^9xEiqgG83nj17LgzSI zWceE{){`h&N}=cxh+^vaC|2)=V(UCmoZb_~kNBVjsUK2G{ZXPc043_>XsKR-mexh0 zl#wX3LK=h8q$wy(pMlawGEurT8)fQqP?lbgvPbgKO8t7YYUDGd)^9_ax;;oI-G_Ag Z1B%rnr6^x|0)0GUL2F0Oqfew4{}2BS2s{7) literal 2976 zcmWO8`9qWS9{_Nl=dkqI0;nk~GuU>uM@qcI1JG0(VzeBB> z_6N0UM-8>A@-p>RrAY0X)8av$LqKtrG2viXZot8+JnGl50;&X;1(bx9 zQ%BN&qmERar^@gJsx0ghbv&$+IuT~4D#F^SiYg~{Cd@^h3%eh1F8yi1xvFQ>dHkHJ zPJcmJt9_}U-)3UpLH7T2?FgI zK8yCum`(SGIrM;xx%2?5iuTHwPs^+t+85Rm-|#frKVu#7w{E2aU>h9}zMT%t*r5ru z=8&N9JtQb&Fa3dapJp%|q(2NlM2A2L2?@87kc=7aMum5g(HTy9wDkr(25you8MnyTj63vL>jN?_;~_oH`iP7Ve@st+ zr}RX4LC>_lrUmJTL@E7b25I61 z(kv)Rvu-wN;pUJQVJ>OaMUz%hMXm_*$rW8ZY2y}>HbG6=#01hVXi2*+iF9zu><~6d&y01AGs;)CpX1Ba*Hbu z9UymvL*$Nln7+&XLf_T>O701zn)_TCxvwjy{}E4+$6_^k!qt%{LOppRHjt-66M3p@ zAy36t@=Ulwp6S}jGqHm_=dRMvg}=y4u9LhJZjqO|+vKHqhknJ~C9i~g;#MTEfneQRU9Dt;5gqJD< zQEyui&nZ9Txy&KFo7+$%vkm8c-PR)C%rxX{`-b;(ThIF`zvcZhHy}UTMkIIJ#LJa> zB+oP;xy^`zZMkT$n+1K8c?b=2JBEfS&uWKdoad2nc3q#N4q;f~Th`l9bVywFaML1<@oAlmC8N5;sx$e6tZ{hGa$ zFY!3WmqeEHCE366CABB`Qje2-X=DXontci#jXcdC&Ay0^*8YLYJpSa%A}{gBA}jf0 zwKe?lNRdCDZRg89YWecWdcHin0iEz@L=};3=yar0Lb7iMlKNeNd|zE4KPxkk-<>51 z+?_3v@6M4V)*B@&8}>-j8mc85XS*bs4gX4V=7dW2^_w9%&=@N@mh+S3Y`@Er%6@-K z#3)b6gQg*pmr-XJ_PyH-*F1>voI8y1@|?}cJk?C#k6$GPHs>S-dG1LHn)@R&#B(nb z(p=7r`B7v(^Sr~%><`SWmS9G^cM7wle|FN6=ptrS%K>Ihv>3EzZws@re=D=K?ry4Ps35K4*$sw=fk0a)T=NIf5!$yMs;*a3!6Z*OPQ=-*x7~ycO@D^)@N#<(zb5=4Qt}I;Y7nuoNUO!OWTcjS==x3Wrh;@vi4G( z5_bgeZ7-AW^NEq~Q^jJvDo(C9CSZMs1{+jbxzQ&{p6jz%o@-2z?^i9y`;9B*`#V<2 z^HrrvygYVMXTD-_UIDwfvyfdP zvnZCt7qLt74k(t&irJ;{huEcghZW26erA_-ma-|bBWz0iQ8p#7Op(%gj7^mtXH(*woGwiskVq+2whs*yWw4*%h)giWTu^*%f)`6kp2DE53~Xon0ln$gY-I*|jno zyEgtWc3oa4`%U}}_M5!h?E3gS?E1X>tUmsMLZ6?YF!*W|hJ}d=Lw*u#^i5_Db}d#M z$}dnH>MB$m_O&PuFDz0V&Og8&?kZ+~%|FPNb{%7n_?}_Qe9y9FU6?1ydxU|)!##)=?9RTav(%)3=T2XK#1cqjBtoB($o|@ z%G3p;)!i`0|2j-i-+~FIe_^8IB}{g_g(+qhrZ_!ds<{t@nft*Erw`0DD0OK)my7PzS69t#dOZ27C|60lQ&| zSq~}B;^5SP4XjDo3O$83^qHT!#;vQ zuZe|xk^rXev|zJlTd=usN3gj&9SXa@gCdO%P89wCCp8^VK{}zL+X1HvU2s}+1J01! zaHjhnoGp9^=QNMtJb4;?Uh@JjkbmJq_iOmQ@GV^AX}IW;z#kSC{?zt{OT0T=a`lBu z%X?6z9RSt5H&nX@fz{#%HCh5TJ_u~C;b6CfLap{wsN+XNoogJ_YbQbjKN%WaQ=!o^ z9h$T=p_z|>X4foeu|z?ub{<^elYnJuk&~5~WWeYg9TcO*v16;fgdiYGZ!S99}T0Pv=8sM&_1n#*?rM)c2 zrF0Q3rF(iyQ6eWrMeb6j$3u#H21+6EeW|o3K*}X5r0zXKq6WiqNQGm^Q7L12~wY;r2hjALVp1O diff --git a/vendor/golang.org/x/net/publicsuffix/data/nodes b/vendor/golang.org/x/net/publicsuffix/data/nodes index 1dae6ede8f292889cb4252aa473312fea1bac46a..34751cd5b9d1b14c3a0977e4fa4b04db058b241d 100644 GIT binary patch literal 48280 zcmaH!2Xs``*2m9GGBc?V0-=T?iYSVxfMUZtbEnr#dJh5?RIDhrr;tup#4a`z6&1yT zVja>GniRXJ*q+b+?A`CTPk2UM?|qB4_Bv&k|K4Yxa?iaJlqxv8RVnAhWTmPq>`ImF zN)ke;Jk+67WgWf#E9&VT(xg;@k)o1}309S~=N5-jWrG7s#s9Tf$P%SoyXurOzi3d& z&dgd$%Mr_KpsoB-+7jo`R#MffZ0^%UpSwZXT8e4&-eoFP(_>e5BdtZL;zFNNZg+>W zC+5183OeXD9`FJ(+N@M~JE+WfvT_(F&|9z}@18xvrhIXFN((+_ea?XCXxs@vUeMvff|nREqPdT1qMS z;lD4aQWBrFf_@KT@vrEpXirtCiE&_Y9)w#3Uc`ch4Pd#wUZriGhz(;LF1T)Yt8^n5 z7{%vM+IvZxQogf$REA--!jgj1CHHly{>Euk12<4D8il^1QBB0}Hygy+Np(U8FfK)D zX&IQkA)m@NhNIMc*;Lt^Z*wVCz06btjp?=U9ow!3Cd$y~DM3|W8<<@^=yOl%MwSWOzy zs5uBgmG9KiTVyKho`_ZD7^i|D_#S~UP9-FjO<1eC9tHkYR70cGQ@ZG>dF@I6n- zcm=!0D{kU)l!MZb@Hvwh0OvR_&z52%2?QHz64m3k%a&$dNJtuS#Y*&*IW~g}?Hfpwj zCH9m}s>pixg3r4bmhk3eHFj6Ho`AXOaHqRrE)jjBlE8Njs@y?H{ALWfZZH{??_eo@ zqE#K3nBYtNdSSb6tW&`AhIs79|UzS~V9y zRdfC75F_AHha?U`!e5D@!tDSr{?J3#UE0W^HJ@tv%oKH~aY(zG;iAND=Gy2boDTul^^#8=zxgJdDSVr%?~`VAy6cy2oH>cA=>$+w z0+8lefHW_{xOvT1$UQOu>xJcWa>H$<3G|v z&h+%JRcE%uq~nqX$enHKY}eCNi_dANn$b!~uB2p~0U-Yz07YB9jODWs;}ZO>sc_@l zg>~v2!vIV8&3eNAJ-y*K(H9=jNMhcbg2ZC@%AO(yl|43A$D=4kciYLFH}TCs!L82k zn&4FzxK^6naywF5;zTY8)m{xamVLYE+qpgkDdti3eyVN}6Gf3jG zT9Vyycxh;umR|={|c^IwLrYwS#iX+1JoEIVzMeC3? z4mZ_BovUiq#pbu|bc9;fd?Tj?%{L)de6mf=-;A|OTDLAzmpXH;>N4XPdV^QtrLzt# z!HMWAm0T;`&hQj367mmvW9i+>nm7>V_>yOrToQ)vB)Wmv*Qt5~(ga&h1kF zFzj^r9_>+A#>!jORb{!2czLFu%(kJvygy@JFdpBWx#U4!7Qrr&kts_~Rad<^0pJlG zgZt`mbzrhu;9{he>&{M$cOx766lQm318q+d7te0mJg;=B1)GaNP%x_=eZ!^WYxulJ zBI})kQtvSiRU67=O1eK!rg~N?mALX|O!s1^L&MGVfwkZ%~qeaHE*TSTdR9Zvh^ zn5r%@A2H87VR@BQ@gJBZ1oi%Z0kZf8KOM5(2cE;4^KO&jIRf=X(*Yhl)sF1KI;>p? zNY793MP|U~`N@Xt*pYp*y9Q7)E(f!BT)nDy52#i3Z3F65gOP5f zBONWqKx~9h0fuu4HhfRFsD{K?dfij%Rb$V>TGeC>K|$H^053ZpYi2)eRBgAbro3uVe?951p^l!%fHT1dybcCk3k?`Sy_i_f$ zcQH094l~u##1vfclSs-~)uNV#c7Uq#8Q~j@AK~Hfx%V!jG?KW4CD>tqH>9!wa;}j2 zF14)nuw=E|dmf6H6fxNzo;dbPqCw5k<}<@i=`J@`uQ z^T7NJV#UKyP*n(U=ZT`~HB((}>k?M9c+h{DzRD&P1t2>N-lq%+c*?87eYQ|{4x+9U}A_eYA zChW(d%9GiFA5Tj4h9tGdC~m<)c@Bv9Y>>((a_wG$ab_!%{e1LA&aZ=9RHxP?R!}Wi zfoyRA1{PcY6<`!+RLx8(Gwb@ni73>_g)0`;1cQ>B%aQu)|`y(@}r^au8gz z0?b=m)#mMFyR|i1t6Gc$T#U^3C@or!4RfxEjWKqRx*)O39mIZKn`+tIU{$ToVK5hY zz#O}hj`BfX)!Na9jj|g+5P6|awHYO~s_oUc&=PsWP3~4NQti=>TGier0V`hEt~#PU zF4bvxQB^VpEoDPxl{%=MF!>k&qtmWBTb@CmnMH=>kH#Z!Im9?W2^X>&X&Z`|zd~$S zI#gHU?poDt?y!P6mo{%j1JEvQqH5xT=SQj)vJ-n6D8*TeyAyk0E?x;f@B5lWh)^Xd zP-tT!y01;f>2F~!lEt!cS3SLwlde;2swX@iiEzxLdRh;lBd^A*ws_>R!2LDGi|(kS zR0WH>$^$vYiwzH@{OjFnOY8Bi`0+~zs=jE)nS>3})5ZW~AQsA4s@9EqIqI1!}Cgt zdNFahRqZsc#E|=pI<@P?ATCtMEQ^1(2rUseyp%N-wjlq^(kt1_v|KRsTMW`}ZZmx5`wnIm1@<+74M{BCptpp@?6{bGXsvrT>Kx)@or z)Ks4)4xr?E9c%tCP4!tK$;wjj2__33N1|%Ahm^k)%+9Nbf%Enb^||qCt@=DM*o8^i zor9}a5|`!ln#Y>t+FD)mC~M0NE$VmUKJ-;S06ybBY?Q1>QonCL8(H(@B#ScMYN2BQ zy;XORNa1OX*!Y#$*YxWU!W1vxiyzLH>n#?evKB07wOcHSwHR`5MxSAAhrDW9tch2> zV3C^>W1X8U-fp)fRbAd_NlM6iUsZro{|7#ht^{-53t}i?T2fy;tr z){@b=fvW#5Jc`SfAC6)?e6x+wzd)08OJ?3IJJop*&%R``WQy04`Qq6~__C02|D=f^ zD0V}3qagpA21~!vsa8wBgx6~6pYV#RS@cF`gLI1r zh|9L^T*+n_pFv#WGg%qpXC(bL5(c5#_#kx$CyIU;v9om-h=cOK8lv;gXF#UEco)~_E-idT(lKl)Jd?1 z!xzd$B9t3o8Z7gmsss0ptR%}2=XywDY%K`J+bu(5-_jeEqlWixH0S^9whT?YPH*)Y z$(CW8FKMBa(*U45lP$Tf*{zn`#CnZmoj8@<%y!0I%hD;S}KQuD%H#;n&Hec3c8C`yMn`MkqWwne+9D;1PgWf8h zk5tr8$y@2itz(mk>8%|YnrO2e&=pKU%Vc2q=e0wwuVZ9bhaiag?yj?p^=xuk#wN0B zLC{WM{oN}*%gQ2#CtmbBU|2X4NFs{2PgFIns*1+2-W%BLxogN%MH0BUuk z<*RynZ4S#pi5z-e6;{hQV;^vheI`rz3G}+<2Cd}zcFVX{Ih^Dl2sHC$6a?l|ihkZ; zIoLImj=+n_mV*-+lxoJ|pmUlXYe`+O%m+cib*PHG=dp};zbjMYsWzNmipkKVR;;zu zS;i+?a3L@QrNJILoB=D=2AGyZjKi#!LlPD=mp=7a_5pFcn|z zr{nNcWcPMj4vlZIu_Ic+QZ~B-@&K9xRW{3^i3plYex{nY5`6LM4$B0;JlVv%>KX2H znjp*UmI<3*hRV;onEsNS@RK$n~!)cN489IS&lM|76xjz$8uE5beH95V?eEC zvVSh3SS|FvU`_^TJw7Wul;k@s%~({7TX`36l3(2C8P&S*rZ0 zwU(+xKNLh|t;=_|(>ugu`Yp3ll>=^IQ5~g1+VV@K?VMz+_4A_OQA+ujVJ&}Q&{7=< zqs4obhw3ehAvdEc{{iWJuo1EzX6ItNrMhLbmGM;_tQPGyMm3vo27Iu@-hn0djswlr z4MeTQ2j*L;nzwQTUL_lS)u?t$jj@o9s*jo=9q<`uo291Z&RUG;(B^%+-ZH}*bEEXF zEtvca^pVFpr39A9MoO+*TUiP|1lcME?E{MEsDR?&x^1ihFGo4jn0_qEo*$H`-R4IHNvBD3e z<8z`>_$$>SM=@kL){4rJEvlBbO|TSg>xO)f(qbfO96Ds7iimq=^@OW7bWmpRc=wghWsD>EQ# z5G#9x{j%(FOqM;H2T8;r9jGeXvJ|qNu$S%H1=&Ze%0B7``S%tf!t$*!|0r$0T+Ilo zYazBcBo*26jOCC47%CrH067x%`(~4nLb@In|gBUo6KCIXD?r zi`__k*lIZ~+EZ&eEwPri(1<3>>8?9nD3CMtaGp(-lgnUzm)84as2_t2Iqr{e5M5)D z37KG3Dy^Fc=@$xe@%DFS<44*G?-@*re#+2BrV|qPX&@~=6X5x)K~+-yBJ0(lfw=Gx z9f5~@0D1*4J+(dLWMwx~=(bccC!c`n_k#t$(BbkD67y_e#9ksU`V~&>7e=AR!yvnE z>m*F0GAY^W;ad@e+<{o{tBN70cRzw5Pd2^&30^>|HgOu?ToFL#zebzB?e>Hi54q#+ zy{Fc<(*>t3Cc4Wzuq%tX@dc{fho+&=AeHrfVsII7-B+SYUt$I1NL+O@EEOG;0vDjq zWhHc#Pi(<+d2laGrZ@gz0KU_E(6W>cL*A#9#jaybJdCAOKS;Ra@D-g5i|KEI<(WFL zbf7AhpiQ5Az4EB#m!qUU@CBMts*hmNT_7!dnb7GyIl2%9o)qF|j3MQFS9D2%KaIXT z|LTF)gRB#zHyLyaNJjLvxi(VO%%iPI`*TD0{z;$QGxTLsU;1c1*N+6pD(~(zi{)^M zuGp|lZJ<;@iW-kW@*W}e47t)XhEOs&CtB+tfJMC$R4V(|b|FL~2^}~iw^lkXRVTSQ$z10kOa7Sz^9KNTK7^{k#jt37{U!BsmZXF4)nrPO>nNSo zt}+rbIqlgQanZ;v3Lazt;jFBle z^nkjnlPC?6anqUe93bO*rIF`1*C><3bO_4`I>c^P@E+oe8wa|O zXsp{GKW(i~R;NH8vyx}sq=T`c-ujQVzWLTC))z?~KmB;)lEZOM1IhZwf}GR#&Pp{n zdV;?qGZwf zpS=Z}Fkba*GI72gyZXb9sJv&7Z9u&ibB|_rSL_V3RXzzm^HV=1d1%$Xd1k<@*B9qp zR5{OQiuWa^_XU`HmzyPwzFu?krghRLv8sLykK(r?rn9Ny+(s6Kw<5GTQXoYvmhqoq zDZ3vmMk|3ZatN6FFa|zQ(*tHnJww(%{rFJW1GE05D%h38F8&@-^RY6hs+kbO#wZkA zL`=gc0n+%amA$7QM1Mcz+$SZ;tN2DdsyG?GYIhO}TI=YLS86&q#lxu17=>G<$5Sdf zCzFHHD_x)pgFat2pbB{nShK!Wjo7SLr01n~G$D3BNry)knZhj~^%Uc!?+B`{G0XB~X!O7%`iMVpNn$hD?-3+VN$U+=GU z_}rlKonk^3K+0NatCYKI=MqTKiFJhOxF$7H&qniUdP^Rs%{UoiPLt|RNcBNPqs)^8 z=FbAySU_9;#5y&yU1H#zM29h$Hs@gC5AZO@`oEbQp5M z9(e`XXgBC}Mil3EDr-XT>`$8@7=nb;Y(-Yz2kV5|GfnkSZlc!I{wv`Orh#2jr>gCC$tm$v^WW zdP5JP%5^;?{xxEe#dW0eEF{Vvrpj#!TI4px$f3hu)=FExiOGLKf<09AmfD-FZFO|a zg5+PB1XFu$j!E~SBTsayXB72h*L7g(&n6Nr6jvS?`@-8 z8yYQA9RN|XsjCxcQ!<&9z)%8135*nh(YuWa3?(p91%?tBDf^^NU?d3)B`}o0Py!=a zU?_p11cpUm=uJr-CLIDp2@EAL{^x3@%$EPBH(4!0fh>o5Ym+tS0If;e8v#YC3UZoYkE^EJoZ1b+L}9AOkM`j=LnZvm+O}_ z^0uXSfj3%&Mb0Hod4XbBTObl4Pk*WIgM_}XRR>mi+??{Rr9i059xMrqP?_EjW^B#M($PERaG$S6xBPEj&5&Y9|O2v!z@JvR%d7LZnY+f z>fu(1Yy?UIAxFR7ji6vWb_+h`*?I3g#CrF58MnT3tPIqlZ!PmF>yppyIG6?*adNks z;45xY6ZU@QCmK8&9Tqt@NQiA+>hL=bXJPCoN0N;3eom1CL(017#>Hx4io8YcKfhZ| zyvEl>b|(4M5&lX@$JqGTc?h^4Q8blU_&in<+2SVYC}I| zWCkw>sXj?3AC;tz7NvjZ6PC$;>(F9qSqsbtAazpfgp-)|&Yr%B(>oVrWiY0=Abc-6 zb+c@I?x#?oN8c;Zy{_*ddcqpzv}qX5nY6iYwNjP6BK}0JI(C=ZN>!E--h@E1VbO03xJ;)s zf-1MVAl*n+-{I-2tBT`^o+kt9n7u`dm38@34t1S!wqVhjz;q90Fr1Nmvu0AP~HoZ(JWK4@3b`XC9)|;PI%g_ ztg~SmnT=R)i1oIJTh<17G?HEIxT_C^CG$p-L7#&3Oi}X4BgA^k4xo*^kXM(tzS2f% z56Lj3qlcV)z^YCdIh1u{G~b1*)KvgaT_wv1pEasM9Rt(}?YOG?JxMk913!Mq1OA{~ zR)O5awW?&vmrMvX4ns+4T%QaYF0=6SQp+-WE%$pNZ#O|cCD_SV0VAiIxn;?7kmHviJ6J}4@JIbo|HcYr2g4^TYw6Y* zxIgsr6jhe}cm@l=-D#@q^;41P|6>mxWl~DLy%~H#rley{7Y-`?$T^-;(il2)dMCZs zUs+dv5@Atzf%o0RUP}k_SY#~^QnK9R2bBZ2a@Ge?HJvuw*UZMW6KEUS%xDb?plZ~q zOJP}#AN}PHASr;2n@bGz(emfLtwYE1Mv9NcABpJtpKSAEZ-CJyP20fb0R>6!%cj&(osh9oJyNPun;`OBk$Sw8B0fl=kZK__h0Jz9 z&TfLp7fe}}G=}z2oX%atxFtVGTkdwUZs@oHbc|?Z**uR?$f#aSaAY6sKbokiv6Awa z!ZJucMe4T%l6DITtYp1%$PI4B#6^(f8J-M-fzK#PQ5Abe@t&#w(Os(2x1p1^rIN+V z$>Q9-sj6~wvZ!)v!l0z(Z>M)p7?9VaW#mJWK6~g$k(>O~19w6`Xa?W&C>?PmNt4z< z9;A0M$m#FoKz@ZUBfST*SW4^2oQ#d2?>}z`38LW39FjqT45TA-Jq~8Rv<(DlQOH2V z`i)!)xv~(_%-wLmmB{vcAclf(Ff{Z!@b%k?f_}e%s{i@)X0-!yz(-`*pyeUR@5`9` z(~uZ?1geH^L-VlDu3>e&7KsrT5Q7nqqblPCv}Ame2l+P=8Q;;7nM5@+)ep%)bLIpv z=dMkGJPk`$8kmRvt6No7edbqH+b$#anTuHFl4}=X@*mw)A7vO7ADyX`FBxCEL0j^* zX{tKjYG=7_&E&)HcjKxi?^70!?5|N^9g@bFf4_|j@LSXI=%0w$7A;XThDA_nU5)yo zD`DyXF0t>Aan=_fSOjENza|F$5hRjcM>gwH&}UtVTUiU?lLOz37Z>Ad*6k^fwM@T} zlbcy6t|IJ76VSo|P@NK)zeJs~dqoj0d`U-6S1QAE9O?(2f)>licrPIb*q` z1sBdE*tTn4#Kv0M?3E0>zO6{Vf`QLC4;YRkftK622+ftGZT1{OGGcfa3)wRPB;KX! z7=x>h>LrkQFgxzWuHz|K9D87KybSu3abd)MB0?FPJ0V}BF)}_)_0Q^YEG5Kz}0W2lk+T*xF?>S}WA- zx4N3~P0nj+{b13Tah6YTHM@}DTz^bhomzEd4=aB(s7~!Z)sNHX3W66Uew%#Q-GRRJ zWHAo<)3RSBm9yWJs%&@JUoKat-ElNSoAZbmn%<(UwJS|^Vo`ICIw{b#NKG$$E2>W3 zd+v7S3_jLRxr*-UQRYjv%ay0-$f)wZG;eF~L4?ytYVSeBU$t|o3M9VkQNhiYpbEWp zctAy}uSr$WSK7K&-i#x`r_YHaQ<;q;&mDmAyNFfJLNYsN5^Xv2NUo7Df^<{~NJm|b z3q#s6h=T!N<`!NB^xs5vU>zNUJ|=28JzI&|3A7D+<0hOA4kN@#uOWNrD#&rXdm1H2 zgHd}}P}G7|DjwU^t@3YsW|1l^s83ZzFKt<*iW7AKb>g0GMr)W{xTK!8T%GjS>U61| z92iEH{K2A~F$(E0x}~G<4E$FX=U-L1q-tta|4YIxO5IxNUsZWT*85*z_(a0@|HAN# zY~cU38x$>l4u<|(4NEorUrbqm4T;4Zuz z+yxc^X}x^`n~3FoZnqY_!c0*kWZC?Tbytfij&I5)YiIW3DXdMOLy~W)hh=CZ_~d-m zU)~gEtwE`!nI%ZcO|<1r?CKl!%rD>@9V8@LmDZf%LcNktsx0yrz*-MccO?;s-=x~e z9*`mrQ#muNOxT}Ug0d#EXsHWfk%wTV56ALQz5n`2p1}3nFK3aIjzz5ZnO&BD{XD22 z_Vz#2w9+fj_WD6gAN>1R^h*n0j(dM^Uq_#WN-^n`=cA-)c&Tp}inz{Perv1IW zpF_*FO`oiOP1$=VXta_W?$pdab`~Q|GiTW5{wIYE zznK~!@7@P&@RNUOoh)-tr!gM#y2~mDX6wEcn7rA?$P_Z5a%8tIYNC{}nvRs+3`O?W zZR*_m<=fSHW^S0aYiS#tLRvTu3@{C(G<=3gTuKt!zGv$lWMISgElP*~TdYlmFY9G` zt&_lFlRZ@5@#v$F?K`T22hou>wg;BU!aSJV=>N8t(#a7BXBsukw;jIU*y;Lpder%O zx6&q8LuxR;*H!%$&Sd1V@{drkSk|D=aSkMdjnukw7cAN3NMxT*?+`a%EDVWqaJ4=p z@e`uoj!5aeL=FR`lT}ZR!5fpnTt-G%jAS8bk(aE>{v{8_ix0%^pm}Umw(l9sl`~l= zZp&*{7wq^MllmpAzUI^V^zo?QbxT-UxEp~m3i3kLdfnPils?2g*TNs%>cS;oEMf$I z>0pw4!}1{SH2;)Cc6pB1AxV-O>jCn?-=FeX61Xohd*3ujmgt%C*Xyi5@kN)xqMzus zguYe#-%59jzG+F^B#`YFFZr^874tz8%yS4+pO{mw;QCDJYlmX_(zEYgUL)=Oz(TH1 zWC~qkd`rpNATf|R(Rfd*Ebz~*I60)A@z^e>zOY7 z4@Dvib=y0aEU|Cr8k4&|2 z@5yOMd}f7D1|`V>p9VhU{TLmxcIthrcjecMs$8D+z2WV<75c9clEu7lRQr-kK2gva zt8(rELBVDg8J#&*Elk~N`65{d*0~e(;a37&kG;mE8}Qob{rXbQCGT^thg8`(qYqov z!IB~F_gxcICG{s(`y9OAl9!Gyd1B5#j7J{#8BP1W>>Zw`F+T8&M(*o;OnbjvTgQ#o z-V{}N{~~I+4dRD>_b!tpcM=2eC%5#(`RlSCm(5FGE?Z+Ju|FA!KiqH3l^@Fu;j-($ zYti}qN80KT>#f82I>z-Lr6+dZ-E}Xt(f{d9+Q7K!UFh#1|6tKOaY}wbMj^!L%l7`a zsjGja@(1Sqn& z!YfnxNKt=5r|(%SP9h_!ekLcYKZLLPQ>r!hBQ|3oRW*Uw_l3Q84f~tZhrq1Au^FgH zV8;{WpZz_Y);HE^cXyGUqd=APhL^J>)#(E7|aq`y*|sVHGYRU<%{?#*)=M6(W{MDb-MAl1bq5e z_If;Aikl*=PO3+lZAm#gBk zp?1dOkpCFh-?tan!Q#0JyRvI2?;_$-IR^y#gW^AqTURG!fht}O^YG(gc6e=Q)<-`E z;2PItdV2?c3|iv3Xwl!?{c#;_UG~1Y-%CB|dY5n(yp>wBZY#PEXnHHs=div+(!oiV z4;|FJG&Cc2trpYC(8s67*3uidGGzLT07=KZmr+`f2dc8)>Che-b6u3=)urA8YHr0D zz3ys5zGIr{mA5kbU56pp%!atHt@Vz1K`m)3-;_It(A&F49N2;ueVsqB6$zO=6GQ5rj`oHX1^O3rf10%;L8?c~_cXoyf(HqmFY;-fzTMZ~t@rwt?1I^0g~-Q2 zYN5%RJ&SJ}bDmkX-z|-Pz@v-kJ)H3v_TZBJ2P#LpgHjQLocnL)WzxMpjLaO4bhZbV z((&&g2hs_|K!0;G;89Xa-{K@qLyP|K#IUzu=&58Btl++B`8Pb?jGW%cRBPR;t`B|A ztkr=XvMt0~{PYra{jOm?bwmEJpt|Ah6Y2rv$L^>`Y>b*pW?KunaTxptb|u6&23{sY zshf!IfE|>q&mxg)Fh=RmHc_nyc-ppfbz@>Rv$p@y@C}k*S>=>M(ppFmNB34Vy9tR* z`J)jAFn^%r#T2+-e)`Z0uL z!0aw{bCTgvH#hW0>41Fzvc&PtZVRbfLNytPh3LrKhevXhROxb^m1C`Aec6q^+QF!j z@AYnZeWuto9O|~%8b4U%sWR;v#v|j*9(CI*0ot->ap~0|%YHl= z^m2Xow^CnqgK@~^9H?_`px(c3F;ocd;?UI6+&*Z$M;Dp&G-TfUwZ zePX%$2yD)LLYy;&;Ea?t%ykfvtddi`kw)tILIFzh{efrI7T(E~Gv*Pw^EJ|IVNMWi z@4vXA@?6is#y5*^dOf#Xi^-?xbv{M>s*Vf8vLl_2%67yySXs2bqBnmOvWC3SieAzI z^Vgj8iw&5oJ|}916+UBX3(PGkl;o3#!bwOJUBZ#BXzJDIOSsYeNfCBuW73dqv9y@X zu9VkAm5%_j{B!(}zrv#og@WpH?UXL2sw1TTYL4-I3s~fSyz+Mu`#lbpXF=+Gmgg;J zE7tTM!g2l#i%agG<&WMd*OBNeOrUSZm=yq@$hDkn9c_9wb1fm8^k1~`K0(QIZzdgw z5m;j)&iMN8fDBv?IZNPHG9@cd$->nI#2{YBjH-5Ht+WJE)tV|UxR4!+UElZ&$OOV^ z$jjoGoW6`sO2#2V{#Zaw3uEcNSTIY(J*iEQ@jg(=dg@#av!{S8)_*dka5t`c7f0xj z)1mJz7MW-W%ri2RP&x<&W-EgdzuAREvB>r?w4R-!^wV0zisH!S9fwUn;3qPbrTl1-RA13PJ(i9TbKVA z8q0{U>FFT|0F`ipESS{vJtR1Q0l&3 zG#?0aVt#5(PfvWf+ zWJ&22$QoI+1?1OafxE02{{a$T!Jx!f;79xhsXhTQEG-y65s+q!h#gK<|AN;0xFqYF zL@iiMc18oBGA?FwSUl|zY5bokmR?K*p=&4=gX9G zONB2L9%U*dMW?dv17%wo`UfTFpcZ&ICqu25oT|{&^5TQHzuy z5xJb+${XR!zk#;+;%o+QH_Xuwt|j#{cR{AEfLu*GjEGQ#Q~`5bxPfxadb z^oJ$6l~J&ro5HmE7|o6|VM(6DoE}my!}A!iA2G+S*1r9-2hAs8Xh3%uiN|5Kufv-C z5j$dONH}&ZR`&+pZ&3Gkf8VL@3+66T_jUY$KHGV0MJj5;%cDimkqUsp_F!pEqOe$27G*Dh~*18mh9Qg6~1M zTEAsLntIrqSFaxKxv^b661u`W72?O>FI>X zaX)i;z1rYCx=wA_n$)Ns^>egWS+~G4^bE+5c>#{jN3^O(ce^{(WBKz^)MKrwjXYrt z^r^=^yhV9DF}g)Pv3WNkwx)OBbSkA3!>u-kXSb=1-S;-BC-vXANP54X(6RSCxn*So z#wTLPvc4G`FQCu*nUDexfDZA3;3gaA@exEQYYR#TTuR3Pkg5S!BawTgiI<1^3FqtL z)(WqB%6)2^dTMWJliK8-2LcB{RQ7xAYE#c)jp}K4qfI@%#q_CXO0Gvib{F~v%Ae~> zI;W0D_zzOhcPp-rtVA~Hy9V{lYtuT_v%&iosb_bLY=>oJmwGOCo=-j3Gao=1Z_}m@ zwBdr>Y4tk*^!<)R>CkKG&A!yGo-aQXLn#}n+IhTDIX{EcbsDRgTMT*nZ(%V%0a@Qx zO5sUMSRFH|7G$MEhAe^{C2dorP527pK}azpSWw9tR&dJ}$o*-oC2#hyjlIlTT=cGx z52zLggp|NiT)qS{i&E(=luGYh3|Sw7Y)FGVCe@9U$}gg~Tz+U=k+mH%2$l-@)o;ah zQhFJ_iq}#h@>p6S&&1V9^j3eq1@cV~>yZ2aw&ov8*vm4vsONjqo7D@!if;A77G5SM z^zR@?9z-;XUnES1t(9f?Ei%lRLJ+;**$KqObOa-`g=Brn-%d5;V9ZM#os=HNWb|PS zc_#TF6N#yBC#7JBQvSj1sCpIk?&c=cPiw=O_fZv_H(zFMaGO?-DCdt{-U2k2|ub%gsoJQdEG) z_S)e4kf8{tQLXk#TRlp>uftMeN3%IUjp}?ahMuM){%=Y(x1%q3o`c?Z+JW1FmVjK4 zgiU(OFSoOOJV~&F*;osnOIvXfHljti8k_5%e3*8&!p; zN_DOe&7U@7{2{air@$95Iw&2FaX0g_Hw8*xS`4!lmKdL!smKYiRA*z-lS8%0Y^3e= zWMKTjgblpgN$6M|RkQ))#d8|4cCa0#d%6L1F$e;WdvWGgX^YTS6d)~%+@wWiJE#Kp z&=J}Jmgp?1)%T#U`WE=g{{gDV0#!vJEoz25 z)CgI>h=4^pKp*#^S+djE*hRGgeFb)yi(hO9%V#Ladx9xhTniTSV>g=RU|k?Hs-mKY zNKQt=Jdmnvf&95!#C+{Q(=)|;6q)FYR3hcp#@J+a-N4D!B7X`JO>i0qQhAYsorjfd1E7DyU|zvF8X5YQ}E~#s@_Bg zN>2ozaUp!+C-9^EIgEQo(&qdX2R%b5xi=@HYKMnXA(1Tls0l+dc+MRt2);r{0uOqz zn-7b#jgUmg6R`X}^t$B>$&wWSuei!V=?dENWFhlhZW7(6(Hz)qr@D=j^CFa1cvEp& z-ou8r1qsuQsIU0J2fl5{>c5F9M-mluH$%$3*vM(zAGNTkH=oE6L?*u^ndfMO1k{r5fa}RQc;+32aP8>;@iI%yG2o zWDWe7ferb?7r|$-8$1rp5f6r385j?&L?W<~j_AkObyk8UREo*q+02Tfn=xc;qt|(e zn`*pgzccP>Fjw5%Ot9aEC3=#mf5uLj?uI$Y)}{*QHX`Ar!}kID%H`QFuoe=Ux`Ws+ zp;Ue^AWP*mTs0OF+C`YEWCR17ZD=`^-snD5g^r-A*QRJ8>I>Y!a80Kpcr9Au$D+P? zlpT<7kwZok#D7u%@*?_z_crd2ee6;sH0H>vF3E^3^uE?fV*UVgNREyEq zP1fR)!U*bbLX{!uUHqM!7~BoWz??4Jk{KWUm{Kqs5_l56NIUof8zJGB92n|IWz1(n z+!5T0H((<;!A_iCZyO&;<5g5+5loNFPm>1Zjo5{=3w$hx0wK%LW>n4(N6!&ikAl4!1?`ADo$^r z^d<^ineAw9MtxMyj`3+-$R3YuaV;!`mte>_HWkd*!xEei+`^|Q`Dgjb*lzUI+=iI@ z7?f5`LL#(*-U<)#^T<&=(gvSSW|OvGC7CO`%qR0EG;L;qP^pZuwtuw^O4 zLEh`m|ok@^7P+yzp5D@9C>bZxRyY|k^BmBZJch~OAbNuVv;^(+1~wq;GMdr1 zbrBM>pPTck7UeNoC6Btw>pUv#aSNXb2H8=*S`7~%B{MWx&Wd*$#Hy#dVL7OMKd;u?UK zko?URvl+3-(iE9i?S!NgYtb)+&qbSgRUCw0!ldA*c29~to zp`glJMZ#4{U~4uZk$*7?j3>OL&$lRb{|XlORL}lk=bdgxeGeq`5gooIKD2xab7>d_ z#Rp?IuK*WfE}o~OU)gYLCrYd3q~Q4#W|!RaN9QM_FQo^~Ly#yQD*DcBhFOj{RR_Qv z-qaRWuFd?Cre!Y=+#$E(G=SJT^(q-9V~fAY(cXF zLp5^7${5Qi7NUvrPw_%SJz^r@Co2n zUQ1i>Edo~lvklMPkn&$>3oLF0^RILmr%?4wq*PJS0bE)CjPu(ehXBYt5<~g(F;wzU zJs}QIEsbHLbSh%{jO2a>F=Gn~^x;lFOoht=0NN{>+mfuTTCo0N+omjWntAfNQ7pQ z7J18M>P~D#Hf(3e-lt@~jSHcjXpXcZTNJdR^q~k)!Wm=Mi*F~?*@TPFyjhJ<^xTHZa(U( z$h#2Zq%HtSW}Cm%Ltc>TBuqMgh3EkdIWSp$2dZ5CQDx3=NBuQ+lHn2Tnr9}1^y^02 zUP6KY9&A+KMs-HAozar#WdE%w&^uj8CctB7`7u5M=HQ5B$QDyA+>|1~z1Wark6ykC zPeeAfh8V>DEhBRvr<=Tk&>Rr;(H~)s%cDX8H?BM*LWUz zAWKWhOYj+sh`9S1FTJ~bsFK@?q8n`}m;+1oS9T(P4*2rVL5u$zY?R3F>4NV!Q~kCL zlkY9b2@CE=?Uy7kn8>@HN4WGHsgA3KfIeej1Pw_#{ z=mtv|kMtg@2Tvcj3T}frD%l=B0OQdO5V`2)&s_jA_yL)19Ezbl*?P-YqN?b(c1SE0 z%r7uq0`q`tj6@=ujYq}2=Hg9jCw|OEvvDY66nYY9=27@jGQmN$!=auiy0VG;=K)yL zpVb;q!B^nHMtB42L+4;Tn;xdA2R6h8V zcLXYshpLL38j*Oyhf?`SJ0woWFG~i&F0pYK>Z|8@Q1BgqoCjgDSRW?z%5{q$eVM2) zzYmkapqFY7F#Nl*Rv`DvHO)jQaBmaj0c^N`K|&8yNbVU*CtxTz6wM(?QC|lv{*!4d z{RJ(B{je6RLpF9ZRp0aQ#bqbaS688bBH_QG0ezpOfWD@Ssc{Ew)$?d8`34E&0P*PT zZpb~{tw$XgFU^CL-Ik7B*`3W)V3@6t&{`G+=fPMDy@g%9kw(u&m41t2?sO9?AHC6; zSPS3nWq5X@IeHvv<~$g?p*Z@&_aj>|98!D$NIgx>_>qZ8x10ox3q17753u!(Txf1P z=oc>{R!)=#S9YM~>aCF5xN8X|*hoV=QJ|0Zdg;?gwUP};lnlYR??WWaNe&cTgl1Ew zY3VH53d~IOB~jJec2t4DOo-UQ^p?MlT|H1WMk;OVFs?7?{Cn{-w35u$Cw+6BovQ4d z{uzk5U)h4v?*sUjfr9d9#X)(-@tgrEigcm$e0oE*Ot8YosphY5q$JNIt`8{{nc}Zp zy%=YE8Px_@yptPHa4H>^OmIq$C*|ycGn&yXXxj zFcjQ@$>3Ykt8XSwh#_`5w=??nfZltmq8=Rlz8M6AyHS5TC37MY?w&3>21d=2daYGP+wI_hkrHB#2!OJkEL-eeBsfU%$M)TqI)}Fk;8HH zq-L^M{$QeK78BNU1$^c^01DMZsxC%L{=-NVji)2fhWgN*_z`nD{(P`5co9RfWw;eu zj7NbLh((@3Ouq;!ksGe;zuK^?;c7ILbmiLFq;wW^vV-+$skI3`GhItp~INhO2-B5=&K@aBe&3DK8RRpLlf5SplZl03wTqA z^G7z2HU&ZOA)ZIRh3H%2s&C<&kpxSHTm0CEf*Hd*QCf+$ScMO}*Egf@JmC6o6p(tf z!nBo5b2GsTlfnE6eBtLHk?*llVPd!DtHs#3n6|tp9B4idKL4YTSZyPKR@4h2H%flR z1>-~jh2Cg`$T_y?cVHMcO8Wgwi99L<#E?~20XeB1@4{F`wi95 zHdyo#F|rUt#baqR=Gw6A_kEqy0l{EZ)v zF2`DEHxj{lpfa9-#9y}4A+Ja(d)iU;0l?$$!x!I;m)ehl-6?>SQ&r>|AE>sYG;lH= z>EnLMI5q-#_ul)SDf+c|o{Ca^jMo7R$a8#fTmUVVXmM8JrLhs>k~qiC23qvYMyg|2 zfg^H#67AQH#9g$N$c2GB7v|8n*yw#@cNba;laLM0?_k`Lfm>k1ZtvTh1k4`U#%7G9 zE&g6A9kM=0SKx=XTd>wcNzx~@5LEi0S^l~gEiPF6n;|8e>cR2=h9VDu&q!`Y%Nm&V z)1qD(3gy#heWe$Y*Rs{Cv8x|d^~VK;%*dT-oBwMZ@{ z^x-Ld1rqvYSW%d^@FfE1^bXpdZzgo<5OWDB@i8y=5pdT<|e_n72}mFZIFBE2tG-2g;GR)p*SO17e5$7HL}|q^5@M%9bTOF zL-b3oV7b7Ug-O4-75cy8&O1t~Dr@xjR(Dl(qG=jvkSG`t6N8E(>a85QsybJ7ZgfUW z7{=^i0y>e=0dp9Y?=y`f>gbFZrfHfE&<1ow5FK^U5i^L2+4tMKu#2gu^VVDIt?&J_ z*E#p>boSZzoOAa*VMQ45Bv#YNj;sM+n_PM&3x<-LizHmMcaKviOj!hzJb5X(UP`_% z(-vm2M4ojclL7nehmZwaHrdEwWD1ad4yoO7srBRO`coDsOD!cWwNO2+3d%rF7PL%Q>DqX$uO%OB{;x4z*}WpD zg346aVa}#c@B=-sFLsNQl-RH4)*c$_6M9IdCf1tpCwYgcu>s2+G#!m2FRh5Im~2shtaw{HWuWOY$;mGUW~_;^aw7tj6N zGuhxG+uOVQ9Nb*HT*+inWKUH6|f6+!B@sxx~CK$Zqji>Ldp98Z>X8nLb((5G2B*f?no&ob(f zVqld+k!JgJy9i3!jx^mBm0J0zswG`uprv*9yiNKheVO!KFk}OSDx~$$7gqNfsyTJf zkGV68C2p^yt}xwn^A+7JFxwwH%O+bRa|l^I_%_$Tv$YDkPp6-j$ zzC;CC>(Ea+54BZVdw7ngG;Kq23MJJ`rMz7`qg0z`NE|)=4HbV$QK+VBXCw2cCR6*R z1Zmdsgom|$eZhTbx2#RAnH_M3q)&<~r>eh?zwA#{RiVmTv1DWmO=dj^=fHNFwqjj? zHy}<6dYWk?Jxbp@n*#6b1p@fGtC>kl>&@U+?tJhha_o`0isx=-zLw0^n_hsT{xu3B zJ$%R4zYIlGcBSan_~43d!|&m(vU46I#IQkUW{dX9hTus(*i zGuogyRP>YCVbukUZx!;bRyLyxF2mth`v{=o3EZdTbezGe$);fK0#aw8T3J7?;u%fd ztU2iH?GMp4pM%J{A4TNvVBaA8^h$2e&0g%X4&<2 zp>D%(22qbOlqO^L-aQ|(x&qzk;qn7X(h!Y-8~;Ou@0LGB%FyK(P=v-@BKx%Xs&yal@iw>(ewI|S*C z&{Yz<@$|yp(~Dg^yM(hR3`pQF-qVogy$Pnl1d2EIppf?k6!OY+rpgN93?bP2Lg*aW z=ENEottWdqt>wz6W&AZzSZBf|a06D0#t@i@=Qo^v4WRTQtx1<&ilR`tCo9*8Ui zuZRX{EaGgXngXFX)Q-sNZulJpD{sCZ85=jCUmwr(YT}X{Y^C=T*G}xCMn6K~&&&c0 zMq2U);%Pmkru715kP7O5ji;!BtHg)g02&0UK~CNdETIxlE!n`5JitR#Kk#%rK)V0n z0W@RyNLcAjzdnyIqh0w;v z7xQj)p`WGSA5*AS^sY8%zDZni5{&mo2eh(TT`vr+ z_)RZLQNZ^?_L$avLG&39*^n)IU9Zh-e3%vpLoo>O`} z`~5201_KsCRzI9=JoR&A-^o^(Hca!O&<;}Wj20Ye6|HY=r9s`Yv^^-lT&l0hCcBwb z`61{WSWC*<1G3(U>5&mT}M4m;q z>Rd|WB?t;htL4|zv7QYIY(C&q>dZnH=axDgU+bNacqe~VAd#Au9=CYH$ z35u9K$m@48`su|l)>F{NuZApe(*kOA2f}sZS=ITFg-bV}Y14XW^FVR!hcwqU0QaTn z+;lC^+z>QOg-;{;%}nT0Tb=@j>For01RYst?I&@HRG?7EE|M; z>v&Uq>u6P<%oHlykx|+H68=1!ROD^g``dD0dKFo{tgv<%s=0G|C|!rIS#R^2)=LC3 zaT4sKp8>4A7`8fY5TG8zTAi4rY#4Y685RS#kxi_CU+r$H;F(1&gEe?lq#{6ez8wvQ zg=x3jK-OykYnJ8VDtCma`5G))e3)c6QW}4v9q@8Dc(=Bq#)?d;^$vnc?}tH9E@^6P zNBhKIeN^xS*z2`>B{w$X=r>}V#t>@g20HI|sG+yvg__W+em5wd5k1(d8rqs_Xyb>Y znp^(3N8W@?udCDlQPv-k7T%0%!T2%?UR!`6V)#|##vtlu!>_oo4XqlnefYO1*_04X zKSAfFeh2!!AnGn56&-`1^6D%=trIX?vU4ddpOXu}^=RO_6ycs8)CkCVRo+HKdV6Tb zutd~dv$9cg6{%1iT-+aEt11b_dcSJNJ71@ztMYh%tA@OT+8~ zpZsJ9jiEGl1+2WYn(>2!5UEq*)KMNft=;DXRi^eOFJg%FDZ4~=^t&hZb@y|u^fOW! zq^9R-p9RU2Oa>;~$}bHiIoTFn($r85^oon*%zWU}GVP;Kw}4xRxzSl-0Lkxw5jL_D z=3)EeyWlJ#R=KHouZ)3Ny`Dm$FI{rqqC{fcRc_;r4)%Wi!*f4|aE|NV3-oJIPyf-A zrHwPNxUC02826{e#+#kXXw~eG`;E75dj`+Rnnu=fKXP+iw8!ATd5IUa|pnVG`W*cueXYv}1$iM{*+2o!3 zDactna@ef&!SlvH^Cm51)77jfT5&|1ZRri5=sD5)mFk#4J@nX#)Pc`K9&JIc7eRJ; zyY+DAs z=yQA7P^RZF?_3P+aczK@fQJJZM`r8B95*$;i>!GJD7o_eJL*;Jl0TJac@xPd4;Ze> z0$Gj_Hl!K#+_${`T##p?!I(EOY>@|kdSWBNNzhzVNDd>`aq?qK5cH`Z; z+n~*?q?Q?1Ib#kfc&IR9(UVJYmImfGCeqC`1eqZ zJOvxr)@B?3DxHOw*e7A8;b)>+!N-&iDPhZ}9xS{6kzq_C$H|(PcN+g%zc|-;FBIN@ zZ~RDs;{>=EhhmcaPH6QslKkN)o+sPB^h{aj1=$#O6wjP@sLc75rPkXzY{abNv&_mxf=K%?@EZ90>AM8)xU82WL6U%otzY53-zrXv*3YU49{_Y$ngw6O<1c z1kbi?9iH)K6~hU-UGbREWzR z#OxC0GxRDJy){ZBXeKf~PWDLBeK{^d7h@=?WUptq$Z8x;`#Z0MS zRG=cQSJv=JvZEd7@RAWejooPHI}pH8ty0mqk!z&pQp=&wVqHUGEskAuUxQBTrWx`3 zuGdLv+loMeZ`4>*u zxSr;5oeaOo8@RH!tr^-XvUM4x!k1x^fCXOS0{FRq?SsKQbn&>`7=+uPjjqNn@h=?= za=(>=+3P`;-|p25(B4z*gY0t{R4gP_sXrLEI#I2X*Tr)TBIAcHKympZ@a3U><5hHw zQ8_53Y8y>0Og9Bbi47{z&x#}5YJ@>@;PXJ?mG42%C^%PsNvUTX>Uze(+1-en zxo>STc6J0inN|6Ej9tYiw^LdGO6}$Ap{)z=ZL*Mjnuq=_6vd*8g}=DYrYmsE@#gLm zpMz`@GNMQNF!2omY*5n&mjlr+$R=f@+Q1sFS3DR(J}$~005lwoAlECTyt0O`Y!2DT z-vNzJ@XR+J?S13hU~owmW;)vsa`s@dUk5PBE(dZSLz+8|Bl%=vT|0C>Rtr$zzY4j2 z`3DsK9F*Wis9XC~JAP1(R{k4l6#s27^~*cx-@4w|_1v%Up+F~Ucus(Q;A}hK6qp7Y z{D2n8-U3xCT!M%9ckLXwFgsHU*4cz4v_%FwP@lG_TxeDa^ zJf79xolU9CJH7IQF}TzV-f!0fZl_W7I*`~ItyuR)K)eC1>L+)j)h-{xE5Hj>^f24( z!A0w4hf#c$gUQ{86ja>{Mbm9Jd7kSh7K~w*-yduS~`ek#j?U z%Mck^A*^nof{}aufcw@XXjeC>$9Pt=9yR>4z>Du6K-~+;)=h3UKCfCyY0LxDXmKwU z97{n-26&AxQsBRqY*RgkXxd3>BtW*zPHFH8o&{cN$M&bRP!I)_Ue-qGD9Fmfw0^}& zP*g1JgUdY>MBl{uqwfmXu@LZK9&#TACH7|lPjms+gaA)306e<^uvW5NJ?L@)$kyw~ z4TL}r&h18_TtLm4aIS6TS>m%rRBJrQ{)=G{m<|Z-4B$hDW4b^Wsj@YGxO@wjguH&P zHIVrq%oO0j8t3GKcQ_)0E5UQ0nhou!Zl1Z@AzRH`5sy(z*9o9l6046Lj?NJY?KV9^ z*8e%F@>OWi_&5y83|h;-8M%SwWJC9L!_Px1x*FA@_ff&(qagGCD+-q)2V7PI8aIIA z+O{5Z(uEsddBH-zqQ}(Pbx8)o>%T^|+D{P_ls~dAS>sjtvfcQ+qqc;`YiI*B1p%j_ zU&)o-#uvUTY@{B8y?z$x0XK;+o<~WUDa4}Pa5+B*yJYp@G#{c>br9nOFQXtjH4DSK z0U_DHP<0ih9&r`x=m>S2hBSYx=-da2zdC4q(XnM7S^2#Z7k8|mv4HHCXli}bZhYw$ zv%9xp?D{7ut-N9hmA*8HpdW(9mmS0CT3mCRjXin~R(YV?*wax2zp?`{n0F-#S?`FT z`R!QkUD2b2LMAb*cSorN}g^vzP4gitMcJ43~?;9Rdc99)yu-= zMbwSI1YW2b4eEQ~5?stP_fj1w9k?VcC~9XQBkF3!E(w5-Il2+}zz&5( zw&S~`pOk2Y^|lXlRzg<#UN5OqvMvdHxaUJwlkLO?V|i93qf6~t7&MNj1*3oU<6N&o z7P*dR(Pv;9-R_l_iGo-!6qNytUG~>L-j8>vk?T1WFDVj`pcg1P70xARN_JZoVCQ-? zcsd7)VIkui%cL^prD))K64SZF!`v4F%BLXG6Gxh_A%w_#ppD+c06B9q$R!^l(mxhf z{;{BxhlFf81+^cMbzP07o|Vm%R(4Y$Tepg91h2E*_-1niR&k~VM*L1EH6PLk%0y6n z2L+99%R-{0gi1;u4#H&;Dfj3Fc*Mg#GxZ{ zu<=X=Yil`uY}r%rs~;4mzJEdk?_|tS$u96G^Q+l^476j6s02mjW(`0j`9$QbK=~&G4(diJrCcE}{5i9^ffrv{i4w zs_KIXU>CGipOcC=5$lUzL^gg8Oyd$6i$B;8=#bLq@&K=pN(@GBV(fCj1Obzu155!g zQA0x|Zh=AKc0$yNw}t?A45bBa=v?i9LAA`+s`H?zE_?w{1cT}c=vO@##j6)d_6~$s z-}^k^L8MjxO&Dxi3fNi-c!N+~wVdQ${Vp=9cP;_!7FK%%}JgjC8a%--pMm5a>+R&x8meSg5;ZobY z2+%Ii7RLZLNQ%7_Kh)mAu}ZZM!L;@X;%2oHFs*%$1DomwEdh)e44AMCP$j8q$m$wF zuDcvF)!mDrI@!8a_Yh51w|X()X~Fv&4OO>M7`!2++Xeg!&UGJ1>Bn%X&&dM}=2`vF zT)=+N)=z|U{Xt6slW@ZN<6Z{1_0Zbwk#o*1u71~Qrsp`huo0>C+&02fffri)?FbeW(m zMT4g6p9kCkS<|buOw*f4YuZ5rxNqRKS76Cnob=Q%x+ULdyogPU5VQ}n6lk{iXx_`f z5rBP4pQTg_D&@m2A&RF;Qz_+~%BE6!2&K}do@pv2NK?vLRnt%I)OUO;lA4Nq8V6%U z+ud|Q&O7PD^0)WW(;P-vqeDKg^-|p8ADVfV{QRe<(cgQn6W1|DT}-y@86TyoZ+7|e zckf3Bko+mItbgwp7=tN*soZ8t2U;@DbQxW;RIgt#}%ww9C&^LmD~fbl!!bPvZi{LkQvIPXWHtTj$jy?BIPXO??F7D^sNjr7(s`*QS4 z#u$$PMQ$xKbjgi#B4nv+C5D`YQ)h8GkKyQffz+N5LCWs|BNpM=BU+ci<)R2cW04QQ zCGWd7RFmI!gN7CZMq!OX;{;3;a1csrXj1PY(a@xxL7cxCopXQHjn$SyHtaS)foz1< zTd|XI#|J6RsAhOd#U1l!wu2%u#sUU#BUffiMH%1~`k~F~S@=^Faf%q{Xpr~0g=!=< zmpcHA!l9ztA-QID)e=}4^0%+B2#+Y7Dyd^zIbF!DM&5%rG zDa?`RJmezUt!S<^UU?X4+mMm=S0?=k`T_PSHGX!TmP9mDeOPK`VRDt34-L|~Qcp9& zRa)4&jy`b*AR<+@rey#mAeoA@CZnNqJq%voQ!W3Ulo|(-^}e4$c4#lN(kr~oullK0 zV1n{G-al+*aAlS%oA9&@l( zrs^a3`A4F2UIbmrDxYx><{CcS6zEaHGwr5je(oq&KHE`cmi%H>~v@Dxz2 z5Uj#C0wTxeFb>KBi})WXXc|Oz(BmjH=*1q?_%9!`py}A&V@InoQ{n8J4q5CDCj;p? zm|Cmt)VUuDn;j#@olw|j`mxJ5>yh@I&`M;-w+*ZLu7;w{3#&}=KV21(5Mwu92u0$n zR`|&_-@sU6_d)Z$nYKJxDgM53;wiNfq&I$WBt06V--HhrNDs zyXEIgnf#k5yF~CVqaeDZg}PnYiyvfBs&^SwJSG$);F8Egm+a#xb;);B>au}x1q=8w z@<|R=5Ou?+plL|Hn4{$mL@uyn=NM*+#lQ<)(+~SEBWOAqO@m+b!1)~181Wsc8V6iz z#%{#y6Djp)Bh8!LiXU7A=f-c)$~}yfF2Ib*7@)`I*Ni|~`9ahpaWAQ1`S6QexE_jA z5m_l;ZIvT==Gj7{G_3bidI_LhzJSV~f-F=6@QO1Oe$mA<(aL(0XYNUG8F>}74P8Ef zyav^m_fh%?J(A}_Y;TRF)6&D8>sNqWUWCrk4v=HrQt56eN*>Pu zyyWp_DB|E*PB)$?>)TzEVOqA7XEnD9`wJj*wUBj97d$zgSI^`PB|>DI;F9<=OkJ;m z=bIxGPO`z%0G3Iq_i2Fp5ojxZok78k6ojoVgvY%I+K+7c9uF3}jMC`iWGn2=07o~a z7k2LL3TzuGuxVdh;YQlP#49!bGtagoQhMsN9?p^;F4d8RYGIZ7%aiOyTjwLKO61O7 zM?L-@RlGipYo^KXzm=VOff*f5$X|N8Uqk$`g?Z-4{pya@Sp~6#| zR`i2x9SRsbhVCY<=U3$9|D*Bi=yQg9LB4%H?5Ci(s!{trGLpK8HS~~HUE`lxr$1c& zx~T?f>km?cgEIX&;fj)GA^ioWKj2do+KuSoHGC_!(!X=6pQ5C?@O^&P=`bdtzogki z*ucEC3)^p`@$|K7xLE8m8|NSVV=GhLv#_(aDooA&8vo2olAM62TtH?S%FnollzAuY zmFd_7?~x%MG47T&+~;OI){wST{cI~e=BTQ#10YL76_)Up=@e&d6d8sLe0C2`sPmWH zFDcExE{kV18O){L>o!Ntmv!MqLjZ>Kwt5B3;1f`{;Kljo=mIy|7p$bA#;_3F$dDr&ZVlbiptY1b&%>OBExCY&y>NcElN5pJ=n3PF9jzSl; zsajGUB%~vb&bdv zS#M$SUAMOi^3S?5N+Ty7^CKL|l8qtSsu{AU!LkdoV=Z7Dz_)829rsX7?AtY;XL1{b zl_jMzc^dVDw7HL_urlY;OG)6eG{KNx`Z)!b!LzEZl5&`P2UjbDRNY(5ODx-3fEdSe zy37gDn~>pse?3`gX=alhlQN`QdZ}EpZUc5M zI*A5NHkr6oQl$L;Hbw)~l3JScY!;;ht(q~-qsZm~rJWS)KOAJ;k}zyqC$z&d01in> z$E|O&-taa)=-+GIylY4edlC21(s4y>f4PNU0lE=}`@pf4GZTyFZKq$;i;>KuXb-Kz z_)P&^&jxbFtqw#?%fX8~Y0JXwW?cCWgs0Uqy@E2)OhZZTX%LI+O-O;05T52pdXvCD zuJ<*Uo~$U~z0~WP1`VQ(hVDnT(nk$(%rx5MwiX?Lq$xZr`j965kY@?~Rm#qzwxNbL zN?EiW7pTBs+Qa31L(L0XvHg&ZP>jD2YiQq8@a_ie661{@F8?s>xu6XHJv~Fg>7=yh zvdzPOj&CW=`J^4INq=RZSOT~P4>RSzf%aFKkAhcpS2y3L(rM+LLEVPQJZ$)(sB8QP zUalPQHE1gu*=|s> zTAd{M7px_3nUL4Y*n;V- z{b8WPiONtfNe(~*Z)0-k6@N(%+oIn-!{^xfaFH4Xq+7S->nZ8k1CF%MbS71|v@gDC zFwhGYleDLh)h;qzhD|Hqq#3Q<830jy?3_iUM5MkII#V6<9@$^CqBwVrX46`fUGy~)hulk5-RCD#Os!L$XHl@1-LC6=kCNSo)VNNtabWzuXw7FWIC;L5b zqhEd?r`*xCimbjB8M3v^JArY~6N4;r7Jd-vaxz5a0vdKjNL2vhi_tzL2dukVgjNDQ z(a*g!z!tJGxjrE(^K3m&UvG)g^;eNIdf+@$x&ny>c^`pGSi(T1UTUchQZrgpJc}=F zVE~t|H0d-F0V*4e8akm$$cm4KI{_{S1=bEI8iN=oSiAuln>*n=5ry=|kg^|yX$dH? zdr2AjEuSDz6!0pZ2)UE4O(|SwRAra#FDS|B3C|9f=vKz+N7Tjyx3`z z@}#=56H}4t`poI-428B#T(7jnoS`n2*G%=tmvY6$_|y3FGyXgNTdKufpyP7#ApP9^wcD|VBFE?x*($^J9R(snKcTo>CHK+GDg64@a z*>DZQiA?xJpm%K^HsPp|UQi=W4>ZfA6vhGBL3Hgxqe2C9`P zZj%j6wi~F?(B5KFpG3`*Ivj5EWR|3vCwCm=Hczp}begAhoIKC8bn!5sGN#p0;Wk~| z)MUCkk93=E%d&|Np*Xj+neNRp<8eRcF+J9|*pH~Q>FKy=9u+L4;m4G=nO@h6ou;>= zu+#KeSvJ$xQSLVV7RO-uJLCgl)a6uPPe^1Bj2XZk%|O?I^UR>-hhOfNjb^aJVKYM= zhuh3B)-}T&r*&ecRlR00Hw~G^9kp&V!sS6`r1x!`8KvhkqaC@OW{h{$jIBM!ZI)OW zoo30}(~zcHLqjjDGfO?6xy{nGhtD(1+?Lxc>v+*-mNTZ9;X zW=-f^K^-=Z_xx_E@SnA> z-x}JB;(p#k=kYoeiM1^}lW{P`H2SKrlDW6%?+gAZl( zD8*h4w$BtyW+*z#)f)Yq;)uM0Q8y)bpINThK>v8^Rl@ocNon=S1=Ze=`FKi@{*g$| zX=HektZmWuHu^+AKxuU{_LJ2psAXtNF{m#mlwBd`q*mO_2$t9&DOs6RAzwC?TL4v? z7&Yn+%@ROXZw%IZf>Rd*>jX`20Dn-{-8we*i&noaj< zJTamnK<5XMEz)_^c+Aro8~3_EaytEtb8pBoMVtK9GgfG4WB>;IK>uEAXiZx`>8AsY robrQ|owa>aoRhN_X(Mf!48lrA?l?kCzkiF4Q8iUAs#=ol_WAz{i*386 literal 46610 zcmaf*b)1#e_W$?kNoIy-2m?_O6)Zwjp7Wf}IcLsvASMv;X%`~Cg1UVHCVpS5;A`+3e$DplxF$`ke~RpAr%S2WEosVT%r}*7N30Q%5BeZw8-;9A%2-sZly|o-Wj9haN+o7c4W@j` z-ufohs(Wn85j+Z0{XXB$VuUk1=XP8Qbe-L~3gT;Gb z8m6wI~KO$n+ege9N{d z6^I~Gb+1FI)NNf##n+%~)I!Qz14<#tsr!tHj%$xJD7h5YX$HOgM*r_tzZxN+265WEQ>?*T$B65Kzy(%kwJB(nkMP;>S zV&3;6NsL?-R5`8FFlszSM82JNrRF+y343LKP%7U5Dx=0L#D~ix8`aR($!Pem^{8RS zv6%O+v#DXN`&nuGtzHc`3`(&XXcX^{Mj+xsUE>>&K{WTX0!I-so}%A#2|W!;f(RU=x5 z;U~=1qvtU1{!-+=$AD??5Yox`TLn@x3oK?n z=*`L9WOrdLr4+d`H+877?Xxgt&gvz$Ye=H`0r@k(_d|XlYo6Vk)cCeJRyD!=)ucMI zOHJq)*{gQ*{2>}MaanMZV1CA`cI%klu68$0u2FkBQL3D-XxIsa^e@y{l< z*$ZLg zThxlbN2Em7gOdHyAlEjjeOu?&t3%p;K`j(;sYBgsO?7D7L+xrt>!Nm0mDj6T{XM7^ zXJDoLHoO^&deq@Y2N4xqEY*%)wa7CEq@G|S?Cdk+?Jbby(1op9@MpEml6?1o;&apQ|2{ zQ47h!kuS@o&TL&`rIZ_1XQfi6I;-;yt6J>cSfdtqePjO`!%SGjEIdMd;k(%fN;f&b?RdG_e2!?#7|-` zXV#Wo3#0lTA%9@h^dsy(#Z*ho4y#(y<~3>i!=^4VexT%;ib&{{2HKuOE_M#ystYKU zj0(c-153%64n+EhvM`7b-@Z=54^s-b4Ysx=<2QFZP@{DzkxY?}BDkHS=PK5&!s=^lT31V^uQ;kUC{SzCu9TzoWK z<50V*H!L;Go_QYC5Pr5>HMFu=s@RiFs?k`7T;S#m)nxqUQO(Ai-PqfLT0tv5%C?cA zvYEtI@LmSwIf5=}@-iXb2&v}RWk2#svJF`*!)B*y32%TK-Vng(bV$KAGz#7Yb8%)9 z!ZKKWr@K^3`>7!C?MGXr0ukQ>LLLRZ@7aJ_5k9$@((`qY_vsnmmjLp8E7flsA^)m{ z{Nhq8T1T16+U;m3{KJ3|eFm<74s!m4l&X6mCwkOM^H8ER?-#jqK^i>OPBzX8Qk7lJ zUsn&@v1mj#fHdiAq3W$wD_cKC&GQW+ftP?0%;@oxv#Qm`9#o6(2TSq& z4&=VWNBJM!YIUmv%SAu<$W=F{{5Jry`e#JU3K+$|bx8>|PX;hj(`@Q;<4jD2pA2CB zI~cz2NJQA(Nv@u-Vdb+Xb$Ndm)o7QXZ|MNgD-bi@p{_`LZIVu=&=sxyl!}f@V`)y& zmsPm{uYLtog=M&`DhsG9ecP$JeeLSXu2*Z+RYr9U+y~L{#$hCGs-q;r-m8c_TZf;EBNSM1tyS|14bkXVJBhB-}_bmi>N8=8pgm zTn*Rv1HBrJW4@Br;_9AlSdPhd>~3pU*LXgl8a~X4-wy>9<4;xekd5ekA+>;vUM2=^ zlG5EEjXn`n*R(!Yr>^zS$EfEtOnFYjTXX}}!c%=z%?@>Kdp4mKulB0zjOjJ%y0!)F z_&vi9$ScLl+Xx$Bf+=4PTw_fw<7K-|U2h!Pu5M@zfU5KXiQ`ZkNDpLz23 ziJYtv#vCub@KL9bjp}B@jyKP>B76&LyV=yMZr&sl+puHVeOm|4&m|(?=gn{#led@) zX)~XQF<6H+kk}=e>Xz1g{Kl)B)ZOhxR&|e|@D}!Vse4*8FdrD-gS}U=SN2tty4P^g zW=ykV1z9yM@{vDcN>np z+q%>X-Dg|Xi>+^Bs)T8vN?9Q;h+l=BAO(L=zg7*$Df-25Dd%Fha{=B*%Ky%ZBV~@p*L^ z{n?Juxtpa#?|VySj4yyuxCJ%$-r{JHm)Nf9Q7`wOgRtjEhkC`mFCyii`PC~O-w}~J z2WUZgaPsX1!?#yG_BP|(xVT=uYIr&rJ|ztpt?Z(EGO=t7$EY`eMx-!Hy}CKCM(s2V zNb4}58N;w=4D+hj+_F){yiNFcu@lP&`_*f08%*`OQCFj0Zt-0&rjr) zI5K{=sW-w!VS3f=fP9D}Pa0fLS_r?F6P9sYFV(d&+Lt-07NXJFjlI<4LG`9Fr$)Wm znul}mYaQzCg5SVgcrZT7S7V@XCRmID3>e3F)Z2X#7^c~)-tl~o0pEdEtlWl1#l}9W zbp%r&_0Ee9Q@!i{5{<}GM9SyzJk#2VOF!%ByKRYf^`4P1)qCB4 zpyvMrknRVu5^6*^qK_$yI>09f|I|97jLYdi{sVFawjjg-!+TL3!Y?qm3J$Reaj5r= zB7Bron(F*Q!2B zO*7R;t+Q&>$C2kv^>J&U27GU$W;FTLCjrSuC8sY{HI%H98PZ-Ox#fhDt|eLp*-M_gv>!Kbuag`nmNsJ-(Z$`U{fw2w10ap> z*+uSGv|BRWo7&;NLNIO~wN&J6k0rD9+#2%o&kjqLN49A9>2S-xPNQq1_=xMH_)x4A z4`q?5I*?v4N7PxejXZ>71zncxwvCwbthN#KS9Fx==&%fFcYq)whedO39az3;u;c`9 za9VP@?xd}}B>=HwD)JE;$q5J>C)g|_Ua;3%Mj9j9EhAe$BIwYtbW;2ZVHJ#=ad}F&vbJ|xEu-825JoP+c;u|?`2oM) zS=jR$`1Kl@mNAKuMCmo1n3{->@M^zh%(mT{DE(Fo<4WLquk57yI^5`40ZV?o%wfsj zT3urq>ps?M8D~BNme>lf5JqA$1<2s;otAN}$5<`ngEGs4c_1y_6OqL6^;9RhEaSIb zi_zjTyJdn=1jw?(n5zl7J}I~ak;I)2%Y^obIQQb$>&>L?NlJ;QH$gTaXGYlR5`Dy$ z*v3Fgyoqq)&5f4bTKzSa-91xG%kG^wc3AdErei*tUTfK-+iSJ#Sv0Ag>L{F>MMR$1 ziMR5L8VK-)ddr@zV-a?H>Zm@0c|VVH%DlH5xw-U~_Z=HizKP4gtqg|phtLhQ`h;Mr z{1Goxl(5lP;Sfyf7T%OqnczU!+bste6ET%6!CQHgmpDFe zK)9|6dk<4h%t9?Z%3(P$xCd>;yAx{p2z-?1YXY?Lr5%<7yY6qdOf@nvHCKgz_PPV| zW+%x$qMq)lMJ{q40fug_w@foGw-ejkUfRyUTjVJ(WJj-MTI(1LL{CFF+181-A6=G% zj8ou-=9!j*T1Ue*J|Ift18KX+2HXSdEeE^hTv8y9!=@~Z@h)5j_JPrUo|W)7c3KWG zEQnMeN|fG3ewL+vGG6*S5mhY5QEZOGa>(XmSpbTUu><#R%$pZr-u+XDT$V5Jv0gnx=NZ3Y&vPf^D*PPwQU+;C88}L0)0TRp z(Q;VNOiU#cL|*bOr1U#<&0idr>BjDWH14P;gv-F^KFe>J-uEb3b4M^5>~2J@vB5IK zeU}xDSBazK^DfJbZ4*t)OwW(#dPg)^W^M}hSY~;WR6`5NRpK%y_Uh_zKAn=!fK+;! z#QuA_0RAXd<5)s9jgsDPha1Bv#r|Ql9NuOSbo_d+Wp?Vf46t0%f$)`t zn!LhK>6A{(?Dj>X7BekJ7$;FOAHtr0DR4_>3FezI5H!#T?v1y&>@Mc91Z|jImLpno z(J1L|!17h7nTNFt>9!ncPPJN&Y###G`*N4%DEG%!%TcXM+AVWlt98)b(=iYj*<~>T z7uKRXl3)^}#K#?Q{rA-)Qs>3g$$%_8#A`8H(-|EpIUyGw11e*BFWLAMuJ6;3kV0ns z30Nt5(_=APhgh+<7^Ee`K~=T@wd5j)#bbU9qa@#E@wEP7TD5qynUF)oJ0SY$%2V@%759ru`)`EB2sFmf=ON-;pCtVC2vE{d>kLa z72V9E4{`24t^-CJZAnRSa%UY@Zh;Z}jZ*S60!)6r(Q-=rg}_MUW1x_WC{>t4Fok37 zkZ}kXjz_rs0H@_tqZg#rcOzF2CW(oa-E@zf^b1x7aQ-T4=BqH={Z!rkabkPYPidON za%$TW7*!D=Mi&gH*K(RiKfC;^2lFHCmeab<2ar!LNBvCz4^MGH4g^N@WYh|0)-prQ zm6UjJQogMS`$vPN`giOVUQlaU;Bk4hg51~wc^~1jNifRhMIpxtIT?+zMQn>@i=}kIHpr5#kQ%8j7m-yYr|fbLq-D3| zK^}-h9*qc*(s~hodKF|tE~I@Jq1?0^uAfJfHcT)XP$gfx_&)NdX z17!KAOvv6aD$;>lksXEP3K<6Q3OB+P-ZV(0S;(c36E;~ERxHY()Q|^}vV=S-xvyi=B^J9Zi;OzB(YHG+i(03e z#32uqad~P>9)_^-nay(M)(orVEceDb=FFxZ%UK<>YhZMAC^amB%fPLavV4BP_Om^cF6j4tHldBN+2Tlj1X zr5;QfMRZEC1mFb=FrW{(#w(cDCq{j^3tdE2AGhMQAWdaBF(8|8>^iF6FLCbM+P`Zt z*F#{i_Xj&(ce3W{Ha!INh!|}1Md^=$Q8FA<17kym)Sx|mi7;q%aQJ8|)iS&-_tlXc zd9t>J$gZ}RaRZSLATSwqzKJqeT|yiXFWaJZmE6f#?c`w8a)d`MCqr2soyxj2Lil5@ zAh9EC%Mn>ePdh%u(b!{1M5Z0$H2Prt)C8l8l#HB#sWBI0U|6(HSsM43L*>nFMysSm zzsAyeDf^O8_3Y6%l>^r-HGX}IgzJt$ zw7r}g8xcN|F=VMFXxlNOJH1|I>#6Hl<5Ai2+HOdAk90MpWnoCEjPsd785d{oN^$0M z_}~-_`srCX8r80HQui=ybMM7o;q78i7JxA$?aEqPXp(Gu&92g_>D@$Wt7S}bX3f?8 z>uIl3c@p$cjZdzCRYZK~D9u-G_^?}d^|||OlN=0{HhGA1--#*r`5vm1sfyp+7Z#Ij z4b5>7a@w1`bIoi2)6{=8;GIqC{wr6*Ra`46rxm|SUO*|i!?Vb%3VXLy$573(T7gR@ zmDU&>=mTNN)wAwUeVH`am&Tr0G3B9uU@rA(RMXoa|DMyoQ5hoV{*`5Y7N0?eDaNr(%*h0KOnZEL$R!ldJhJ8)%O!>v;mhzGYBvx`>MARKt?ti^5S7& zFvLIUrcG|`-PtyTO&{K5y)t4w%G$ObVN+ixIBD~4f#|ztJxa=JG3t+DzHEOOresYo zpq}5U8va^F&d-#R`7pTPr0p^Gz z;b+Z|()<3uAN_X0eZNOds_%5Ez5Ue;Lgzob@g~Q- ztaEsP(ddWIYgE=Nifh&0`ukILb+c0G=h(p~W5bwK2l;c0F-+R@qGfFcsUDrlVubaH zR^CAlWYQ{$7~F8nW`a4@#pOWTyxRZi1u;5!B$iENvUi)~oT(0}l)D1wMI<(NTsQU1~SgEyG9)1PumHiDO%DEkAIp;Y* zDu;6WjUDQsW&cSIk%Rxn&}wR&iP4C4*Pzw|PICH}{?$WjV5Qc*e<2YWvmw^2GSp#u z;&?Y=U|`=GWwMrJ*6bRI@=c8LS3ul)jE{p6{?^36yOfMfD{9*y#`tztvkxc@e};$A z*svOA#W5yoS3x}2!O$lPd6m3tUN%vRd4wT16Ui)7%}562IYrhI_tthw@=nA&50S(~ z+Kk*9$RCtSdTG;_h5C-H;=&dVG5gSFWI)Qe_&sdr!e%wSXjYgY?Tu=B>scm)P>u!z z9RNd(4zFVQlTYyG${p>n$v!nxXTvVfACirkm%hv$kMGOQUD+5sBMqP1%sBm_dskSw zyU}^hyJ~mE_UGfZwdNEUvX{-u+3BUH<)brw_8C}s&)Ep$yiD3g!f^3&?fB8_5{$J9)GY6ih}_p8_8c^V&cr$${hf<-}G%TYeMC&O9CSV~-Kc%QArW4H3C+0CU(<0PH%*q6M$SSrDalTazUDVAeTyYwN!5vvR0}O_duSI>T`{dR%vUOYOj>! z@+@tOkQasQ=z+Z42zf)uyF&iqVpUcFh)qbYRP%ZuyGv;wDaq%u=`$K3vjULWQZ-03D?s43fkH8P7wiXv?~k7n`aANyd3=I9aPe?yq8;CQ7@>b9(YqrvFr(nft0iWwoEW1ttnrjg~ z?ds&dJw2WAl0I3;%MpB>RLu5d!QS|n!&GZ1W!%XC$@p>;e)F-Hbrd0F$$fj)&IF_6 zHZW%&j)4(%ILe>aLUnEyPj{)%>-L z#C*B?&-wws)@i+jaHtr460UO9P`b5G&6g9v{LVFWRQ8dqog)t+iPjuQ_Vr!J@%@_0 zc3^7EzYuYJL^kXTTGUB_KEJXy_Qljmo5yZfC%Y4N@U8We=a(`taAHiI{NhUD$hit# z>jTTxDYhZ#x}q%WV{az0IhW-@uAwbw9l_+R2Vc&!bgk<~G%VIlM7}rK$elv?xq?cc zs&bDCs8hDNV^n2L%q?cDsUOjGI(Gf1AD7vWNUB-uTPVKL?l0$jFN5cHi6a*&U1-b6&QS0ou54+b#x zeFk!Bg*q)E&)8#kW~tK}yhCs~sRKr(lU&J;ohNHkUYvb!^(pk$_!BYe&x3?&B?Yv(s@5~RlUs^w{Xr? zmRZ{&m5dzA1NvVj&3%ze-g&8)n$;2I zyu~|W=b7}IMP4S3u3ByZhjw=7(45ezft2v@JN7RhMFunTkx;kFBh`2?>)FOjN z?EfI_5n<1NfZ-JwK7rwTK^*;`R{SCy5aECp{tu3VA`%jj(0>yNi%3L7BL9DvQ4x-b zaP0pt92emN5&m1k66G)wJO4LBCp#%>g`!sY-!P{{q)0@H{{JwFMYu$SOaA}Dr6OD= z!hgeDUJj#tCya{1|1tzL`bv?j6uGMZQ?6R%szq+Dmis?@`e+e8T7>_GO1qr56YeqP z|C?)FD!1LX@_J^)ba}lpk~^~65j@Ra7LKqK?Cnw3>o(WYHjQbJo>9j`Xc}hDpcN?PKb0%x2ay^VBeA zp32JOX=3ymcFD2wa546Cyx9+;lrA4|<$p;j?FBog9-@?)Mai`qE3VZ{`|Q0Mgn&Rm zTCZ>SAeR^5IYrhDwZ;mOOIfX^AFp${d*B9$Wi#z@Nd5whx|aH>R-x3Fn^2(Ik%q^a~7 zZW}Ih-V_9K%_r9cyB-y|cGz|M!Se^7PoZI+YNh0ms=P+fFRK1_kEE|t2k(*e1JPeZ z7UCmf1)6?_{R`vIn`zcJR=q~?$s z^5RQVXKz28tw_l$mw_ip31-;W?dqJ4%;oA_k9==tDey7EB%O+1<((@(`cuwh$<_E4 z58VI#M)5E2d-Q{ylIu3xoR~VVb3U1LuIg6jTlVu|Z!`yC`$@D}Z`=sEp$YOSRom5! z({XZC8-5uP4NbAnIM0NUwi_KPk1f{b3n^tD03+u>#^lhoo$CC$ljG`w;HwO3*W(Ph z{B4Mgdxz4<6P@VhQq6him`S@KXb?kv2i*XYo^eWM`w1uR(~(WY;~^hq#l zD#B?`)0T4V&MoGB3TA^F)@1r40c}Ke2(Q@&3cQEQi%%Sx%F>XzN`- z(=WaCZRp_pZf#zl6LU^uSPW5_+@LXMAiYG%Yi;YLN4Qv8?qUAcoY<)@zI;6)j4vT2 zmg8|GFO~l?t{h*2MW@O6UM+njuO$C6#^pYCaIoqZGK1WIzXbe?Tx=(5`U+$~L*GTp zfYaAcdM*qa^_^uycyEZzfTfo|;b6s_P1Vs#!UnyWa&bB6Qs2`UUA5dn{rUPr8`a;x z=(#G>s>U}1wY+JhQ(plmF7v3`)<3Z%r^3~MJonoE$CTVvc?%%M8TNr()eUMyudCgq zp=a{nUmL%I6+LU6&!nmPK{X9r=lRczBQ2-Tf9k)!pZ=S9eJiAIw)G|8sCSmD#*IJ9 zXukoZGQ0;~7F&Ah>CrrSHMPpu`BuikK=>n$=my_+#Fldl4AsS?D}SDnU|t@)aiv<` zEnh!bG8tTaeu#*l5ut&Pe4B}FmGxBbWdpl`UTEdYaWDj(PTf8KDMNa#`%AC>xr)jc zBznXu%YjV4)Lo2ceT!Z33Yfk5{sEBm3@Hvg$e@l-wFJ z8ji-8G4+r?uTKg#$lA1uNvAKr-8U0k#R|^Ap&)Z+uzM08;C$Fm7%=~6A-3bmZelHd z^&;(=Le^Z30^`<>U4voFWbeNXR+%_D{K0{qbfKZIz8Nl)y-8~*`le`eP@oemv%Gw|o&|Jy{=yR*X#NiPtf+Ormo zf1kSkKS;!%m-{1~%_0!$B4?@y!sA)NUrKh3k387zS{w+=a>BUl&oE`>lX8(*x zuP^!okiQ50?~B%mZ-_%r$-f~D+(i;?*V+hmnCGuy*_L$gx_T~p2=pZtto$XXGAr~= zbeS{4oY{?GG4O$-TufIiAz@V|2v_|~wc3J4_0!1B9Ys~muh|v;VB~)b+E%rkaVnoc zjoh69?0TAABcr90eNgWChssZhb7beV$j4Aa&SbC-y&gI1+UCE;X8Q)=;6CKa_>}I} zi--I}$-tZR!M+^)v`OE4>$#w_tC!Nj9t{1#?9uD9p0$D7$d&$ag8OJ3mCN0=POSf9 zT?NvF^itj@#@oI;(V;=Pa^-kzqhWwhoE(odb;Q}Ld@T&E$g;I*}U{tq|au9 z`O|80qonNL(p$MlZA1>;o3ySTj)TJbb*nMN3WARzdUhxG#d1o1^-%8}&69m7jwc*TU6f(im!DMa}|-jXdkH zye|P<&(MLHCkJ73Azfz3Z*z@2(IAPt@;4Wx1G{b~Tz*UigZ+2l^GE$oME{szAU3&} zai0Y-_Ax_WqEm9OU`FYamh(JNWp1Et6E#DyKg8+^-0j)i8plv*L*F@(aoOSq;9`@2A0*Kwd#&gJNHOSIdoXB{*16{ z@~}7VQx2}VFZ8NAYOZmpwf2qVIgh`}P__d}XKrDpTKmTD+(Fg!(oxy(lPft-Dw}+U zlXWr(a^(eW!w&Gtr<3bSu7i*=*iFDuthG~q5frmmnCC8mss&Z4QukS3mKAex? z0k!_MTFmovsdcSfx7}$R=2Ulf^3%M#Dg!Qrmw-xNdj736SRE@rtLH2}&}Dzw#Rtdp zz=kUa8$EmUgwS6@4o+CTPz-)`ucx1$Wsbvup{JEr8~AzqpZk{jka4ACU2{H9S6I&R zGE=(ffa-Z@!RQh5QNW_!+k z5w1KD7_z(?r!f~oNzpxttm&^*^dCEwR?(OGkDV$PceAM0GI5Ms5H4E>7DG;bMsp45 zdxMk=ycvcQxsSF=iCbdd%fKyJ!@;ZaA||Y_m98kAwvml*1L!N30la)W;ipE5DTRTm z8!_PaQPLT5Hwxo6NR_)0;U`cle}dafbG1VVv(dbTQ<^Dn9?dO?nC~)>+;cFX|7IxV zZvgJs0805UBl4MIPZqr38G`vHGU@+$}gq4p?N;`=>@Fuwm zyn89+Lk3OYQx@95S7amb&moW>gz+;70>AAbLsmvp(6y4`a~g>VFZE!`hRfo+7)_=7 z`>8tGN$1G~I50K(apYOu#4^&0NOJvZ$kSxkx{S#fSWozc|A|)oYTMQZf{q5+Gq;Hqz#xEik2y zl6*^NB%Aq^>Czx2Zs?W%VZSM_Jxw`c$5MbaC-%TSu7eQvb<+FuVvysQ2Eox(^%p|k z?iwj!ApA=KM=U}GKWBRLpb&+2I5I{3rx5L(Ok%*Igoy; ziNh0gR0Sa<|-Wb!OBnL3o^+IJ-5AovlZJ#-?ain~Bxb}!Yk*QmxP zlF4LoH&)JU2jm*Cn5)RRF`TOLmW_^o$_b2*KpOM{Bfgfw;5`jeGO>XW4nZS%1EVf^ zOBM*^bA;sk#Npm%LcX;^?v&E&kkkhwnFb!_bkPDS-FOA$_CkE@pj7-WIjvkpimQ$v z4LP+GaxQPvs;=fYXH~ZddEgaD*C@!260$aio~hmwd)52B0GUcPeO`^auYGNux?g`m zrytD+4kB`nu%2E+O5~bKpEm}N8v6Y5w>u+!Oi}NnHt_h6s!JS)u+qOJHH(I{2|C&KpA zdpYlpV+f?lryH63cBzLpABdWj6R67c3z-f#F9TuA0@SQqnXo#n>~)P8*gFW>+6`%h z;RsN5K8l>>3QB1UJIPBB#?TH#^zFWS7_Mu)Q$1YrxDUA~R$SAg=$6~iJrd_mk6j3H zIM4OM-Lg?V-1m}CJrerVr5@>--=`i8tb*YPhMCjPf=|tCz`X2lqZ=_`$ksNVQ|_Z( zQdRR2$!H;%jJ8Yw$xn4Hn?0a9A4ggH_|#*Oy+i7;{wauLok&~WqHgtg^p!64_$$-F zm$u!h)*Jg0k+sF4*1yKjeN_H!AQ->6Sv?V1>r_v4oe@$`7H1=(E^ARwZdsa!c>{ZC zXCpV});jf6pzGUFzvATpFt(7j>y;>FK@x||Z&1%h`O*Ee?RUdX>p(c`^g22;Bb`u}cc|xL zw|A@O-q@>2ZIFLoQ6ts`)Q0ZY>(ujxg$%i(eX7-)=z-Bj{xah@8uzpvQ+Ich`)}>4 zwf|PTYAZjzQMGM3*~PO}6a=z)wd;Q#vAlra(GLd+bt>kEmSe^8Il*Mf$FH_KC^_Ch zEmI!#bH65Qx!+M*`=sg4(4 zXK9%*!LPakao`TU11q-Q8Oru+ovLf&hz8YdPN-Min_7BQPvlsPX6#Rf(idVXZvpu1 zX;{v3!N|UZ>}EbvM|RJ|l>K&x>Urtj9@QIsJEVHIPWOT8>?YM$Fs4!UZJG#h`}tkC z{I(u)hM=#aWR>f-{AS`E`4ZKfeTX;jQ@`36kO$fHy}H%L?q~7q_(uS_0ByF}_*KV( zYHk*bmZv41)odeH{9_}KN(N@=h~=y$Us5fUPv#2WMx*eTO_1MVqZR>6+KOs3SjhHS1)0H?P%Q7Gii=YQ=Bd1}VPQ1>p&o4_zBUzXPtZ1EZds{A>iW{}#HvY%G%-sOn?h z&@Og^$7qZEf=J|h)J%qt@;*<3 zTyk;)2)@R7Y>SAzhlcw>xJHO56Tf1r$PPaDu?Tx_O=k?rc49t`T4)Z{a4x#hBVCxf z1V?_^<3nHcG7d7)C}{Fw>iaMn>rsnb4+-aE-p{|DD)V8~Qe|*`|AbN80V6raPj+Rc z37>#pb3+%xS74=(d9Dh6?*^5;?sCh&i-j$M;CQOxhs4LxO^A$y=#KZ?if-gPA!CCi zVj(Vr`52A8=qIc_sHQwr{lCJET`5*r|5R{zH^CeTqr8)n9s;Gmw!oN8wV;W3Jr5vU z_&RO=*NHb#3nRv2sfzDr^$ES$NUpx3ExrWju~ffA0Xm; z2zIwe@JEqzkwB6;wie#v?7%Sdb z1Hj)RB}osZ$la(JZt@a0=#Rv?-2`(MjOY|Ekq_@d_#;2MpNU)XU*ah86l$?Wb=Z>?v;1aE8M1Cf zr$b8Dpb?a#S~L@4HV{$KWOSo%QZ-gkG6E!9AMTPpm%GyKf?(*X3 zbDn41Dcba44L!>N(%6A;XiXDomoLeyR$#PPR$I>oG(z(b~DzRSZ&=Q z2aKmtGxx_)d^b8k2VFno_a{ zd&ar=Ejmgf!+g{M+2{k(x;b|j_n*$kx6T`(f+RzmKTM7)oIiUS()u@y$e zWaPZEBUaxL+%^9EYw#A5za&mx2zvKD$ocnY(pBu;#4>X3CM@4CmKzWW^*HH;7h#01 z#;ETCG$NB?ke^XAzdJjH&qe8?K61L!OR1%c-oLsYIekKToNDNibmH(K z7xrN}u?%R*dkE0|C@vFnMHsjr;D-EW-tPic=?SnMq6;Q;1EU*P{P&FopI3WcUXkVXehS zG>&kh1!&Ru3P=g&OQ+LjoYjHwexOP|gb!ac8s_;J4c`x-k^>;-R{=1`7#4azFE8+d z`S?ySe-1Rgs>HT~)O&#FJ_m`&YF2R|e)aJq8DX7tKR`9mA4ctzJ`&rBfyn;248Pk; z+e?_&Cv*33Cor5K2;GDEVz~?{?*VCQCUVhm190Uqrq}k$S$=?@3!p%052ltmATkGo zhhZSL1p`I%)3AIWy87RKOY}i=1b*G?5s8n3Q8I~=k^sC{#3+Qe*;h?j+vyiMHGZg4jZYi%)YA(W1?8cZwAcgUfdja{j_JtXRER znN3w6Sju1SLF9IpD)*scU@;=T76;t@dlBx%TTm`4JbR;2EyJSpaQY)@QVPpsQ0497 zqrM5uzxs%1Bf9Ygl+0-il|UYGAQ!8}ig5thh)ae_PHG|T z<#65d9ej8gA;dnwO3{HqIb@*`>H|<&KBROqM!gS$#W>3cLz11$Y5=4YA5jxVX;%-> z4nf#B00TuA_A;m)0la<7lW=?!_S|=)Tety+u>oPDfE%0m;yRqmAPhM%>Z`zBq!$r= z#Bq<3(wi_U`iLziyJ_1@`(KGMwU)@2gJodb`7MfNIlKoCqs`b4wZyqWI*L1^fekmF zi@kycIP$LO##>by2HF5rl9f)|=CFhcDt)3&4in(7Ix%$_Bs#GH-F+b?*%&%z+Zs?}-R`gPO zpZQj0Qk|PaM+HB?=)mKMtV5CUXc%YPAT>m3lp&{cRdG!Qj^v~j>c>DdeG{lo#IGUW z`@{~gQ`#Swp@vRMQz6NDQYyt|>@Y~xbA(?Y2hGAa0i+)W;;sTf_T#sp1mT!mOed@0 zMjpm*WFq*go&{gQACRi&X!Cx9H}5x?GA2_kz8aCr1(fvq7ke5x_c%lfd(yzNF+hN` z>KHyV@LMV;(8T=>xZDE`&xersQz2Z+;cnoWvy*E4IX~v*5vAf6C;40IW1OB&sXC4+ zy^Wds05?3Iwpbx;#_qLL55h`f_a@XP^kC%xpoNd38hM@<0OdEgAa@Ro$Zp+~WaPw` z0+=o^AaHI~cm5c4@gh%Lr)j9V~{Zw`$5y`*G+;eOGG%Ti{1M1DpV znUA;7I{X%1=@)MRH(Pk5iAFSvmB^1_ za@vI>J-qcZi7^!f?)%fx^`(LIqyVWq4z)I;R7S-l-% z&a1<+k5X7xbmLe`CF>z`cW*#Mo|B^y5a^xG9MwnGhT}JIBIW}plI(~aY>H*CO^!#S zR4xGrmapR-aDO5PzCSYP^9NYNf)Dv|z6uiG;Us9eiIE#zPB#!w2@HLZE0RN7lutoa zWDW@Qwpe~T!2O#Wh<801_k4(OB%j#yZH3zpS6^9#uR%8%0blZML;?pjqt>5=503yp z7)I$gPEcJ88JMf`1mxcY7JW!4ewvamiLQAUDJhu(alhsTxI7S*JV8XI0l1}d=JLpK zHF+=2gSR6W{sczsY%IIwWkkVHxKWw9#iz7@^vfV)NcK>D*$_w&TZ}gnD)}I4#RoRP z-Iq46oF{{8R=|~qM}46du5;{KR6PN(6l8VcqYy{Yk*wYcW=$dupx%376nqSc7 znGmA$cE_IHLv`or<5tBagyT!n7`u}DxC2vuxeE%*&K031*`a8jeUzUZr?1q>}^78ezoIFb>8*G!tlrz2v@ncK}642h{UjV<=hj(9QcC zdn4lL4pnI6^`blUND$;j05trce(vutgrPqaHsm)Ku{+Qx$m#+{e-mUCSc<+yPOq4u zuTU$pFlbUaQF`!492F$c2(L{eLpDmWLtP+Ez$kS3$e#?P5;=^S=V3Ikg0{d4>;=YP zUat&g<1y;n-ART{YrxU_eUNK05RxaQR4&{?c@l}rm&;YtXseV9m&p1cmR(>8f6zcC zuOv_fG2tgjh-FL$% zKDiewU*R%x1UV@91ebAnDPYPG!hKp3)hU2X)Wh{Pp;1)t2Sy17N}~uTucTAtt%nNT z1o2#shVD?$2c1N8a~;sq(T%*@4WNSpr0#w@rmmuDRAV44-58alvwsS5#dBR4sKHd! zjU(Sx4lKWpQGHL7nnzpF*R(}$LBpsZ?Gc%8(LIKMbe}YYzX_7gxe*vgiAWPjy(_>H z-IH-;PQiR=8wT`-8$YoNwUcR!RDv||2Yv&?F%X&2jiU>&9QTXbewd2f?ZnDj*} z1kg*QKGJy}=|iNf8B^b5G;&S=k%*7HQyBO=>-T$TcF8r9MeKC0wE zuRAI=11piM;p&ULz!*E#j~Gq*i6HW^pLpBQ@cr6=#uqRmN8+Q>gMsn|WJ5m-`BQKc zzXx$N3U1^CLP%C(v~U8tr6cGCk4;2mX$if6TO=!icU4VDwm)Irqa@)+@C~Zoosl z#-%ul)HWd}J5#6*m!WPfhhK3(-hdnaC)LO(L?U|%_bxxBWpqWPYa3SNHNwCi^_Gu_ z-V4GgC5ie;GbGiD&7vm9nb0yA;WFTst57()dI;a8t1 z+)p5)?}Fk#!A;6Tbu2B744sH`{}c6Cc@F0VS(HL{Ou5&0VNWj8t7^JIFsTQSvMNWT zPUK`b>b`WJN-2DAFMWAGfZ}pWtEdHr`OhHL4IAmG$LKsyfrGXU=tky4+>09s^#d

kM-i?FIu zi!BC$zP>B?7~t{G!56u;iD2sRQ6`tI;X-=Q{VH;W)36uLM$P=P4`CT_{+kgo3(znQ zsv}JoBck7kxnJqR)GytT6)R}lmr~Uff(g#XK=|4q&Se}#_VDk@y}1OrkOeDoxy}zB zj!2{hRLOG?so0Om6StzP?=4F2#Z-9|uJ-^mQa=2KmUyx3r!BM;K%o^_34MWD!AwZ$ zbQcEfV2-S4A^WBbe96%b1*1%KH(C zJ&u)v>VERqjTOJbo_;XVGbOMRzxqfQ{FmrH0G9CQ6Bzq2o8s#FPzJ*IM++F`7F@%HEuZKpmZE^g$@!Hz60}-r&mI@a4{WC=VF!^Aq5^STTZPxxE<#&r4V`_+#?MI6eoYrR(7OFT|8y zseKnw3dk0nYT@y#;2cEsnKd+}n_+Q0R*D<}jON*}x6}z1xz8@$w~4T3z=+DNLC{UL zY%GAhFQ67HP6z#5KpI~FEjiLfY;s!Had;m?&O87{?0gKA7Gtz9(FF`SuayQi0fQI% z1MjHf{m2=O7}bve1NYvt?Syke7&yf%1k2tq-U7!XS1wl6Z;&JgH8BQg<@xqE=Ba1)mGMM^=i3!_1zEc+6<QN<{SVi5w4CA5yFKcha^75wo7KQkMwQ%j<-IFHr%b_?dKE{(?)rDi`fWPwVTz z@Z$eh+<8aWRUM7~oZHo9$-NM;1DN(`rnhtZy^^l3bk&;!#>Di11EGZ`S=kmFmZls(*z!j2&!{uHnJb5Z|p3>4|Hn-4?s$eS2V$vZ14_l^OS?S#|#=a4Vm zn{vzhV54#g^wh$lV=#fzN1)fx8KI1R9|>pi6c-=X^cp~$P*B=*-G_rDs3*LJ<`RDv zKb|b^Ldp%~NXjpTet z)9DypDl3ukeelsRT>TN0()ZD+?374P63OPTbv+mMl2^7i>5&fI-l}K1bPJDeB-PMd z=`CMjbda&ZjCd04Ls~eKB^?D+ zb^>N@0{mCsB!?XFf1y-n{4?sUI6#r6Oc4?(YR}TNpgj)$*p$oKj2GLUi;#oU7l!Xh z*tMBVpLnp5)!=rEkdbPf1dj}1*%2iXio3vhH#$Lb2ba5ZK!jBE8&??9ayWdy$@ zRnL;8Ll_oAKNDQlWo`XE{`CxTf;z2zAof*I?OEu|)Uv z!Cjl>rikf4Q$LCF}jpTLdF{_PZox9f`H@zQ0u>1#D)yb7qg%22UZfPDblKGLhY%0Sk*5E+|kZ4}!}**2ukNOh$;@NGwHnJrXW zqn#sN6{2VJ?AGBbOWVtj+l=QEvK0)Wh~0VLwRze7EnVm7eZIR}o^3DcbCe;ysNQzc zw)0hFyV&sZ7M@J)Di_$|l=HLSKEbZ@o(6ezcq24tKLw?uI&R^q=H7TZo$H_2N*(Hqv2AZa_+nRWefc;d!2fsK)x!KzheA2~ZgMzh zMbW8jZE_ytB~_v^8FJ&m*h^4^`JImn7#RbM79gWE?=#?KzuRVfCdWlTPrNGRUy_CIz+;Sea6?eD|LSgDP#8`Z_7Yo8vj5& zraD2}$2xvImP+@M|HA33-%Uq!*zHf%^V@FN?sd~=>#wBVlwQ%6AEYe4ryYfftM|;J z?dQ!KKoPWn;g}{wui0rWq!CA!4Kc7@PL-7}1|>YE)7aT_MX&K~OBV^L8%jX=jH=KR zwEi=(;+Cb9(Rd{}QlIe}lu7qczK4H0*_IOebqJ?_0134oz6GObGWIPXc(#}SvhN4! zA^Ol--GLB@k0+rj&<~K=#@Lro4qnYud0w1vmy=rZH1zzFIsw%*9RDv!Xn409hGYN~ zIWGqHhvF21_hTw8=kTp!EL0j#YzIYVfD+3mAvJnPcL@P`P z_&0k1N01QPNw!Flm(*u)s^P2Ps^P?bBr^Hda2>2Q+ztr!LA3f;9c24x5WFvtqvj(x zsQHK@>nliYTHlSH%PA;$eLFe!4MAQ^Ad1&`m-vF$^2IU0{}yl;0+uf!Z~4+V;66~wAC%We zAR6$Y&e+coCVDqSW8d2l>for>9?PQk#=tc7(5d8_+qT)pZzk*7llBeiF;OQaiRGe%rUkQrrRZE1R z9J-IZfv3VyIcor2jf|48lBZDBJUG3d*Vr;pN@OB0cs2>8ecd3JqrXJF9m;w5gR+?& z)YjpGH(O9%hF--1{?5FLfvHDb6d@|n) zC_qig$;g)c>40eli*Q=WCdlhwhn}uZJPXm(Phq3>)CfeQXuRabRj~FRg$JLB!QWyM zs>DPin|z@B77c~RQd;mDQY{JY95Ub_yc3>7`wa1PQI~1<%6$p`eL!wJISVQ>>0Uk) zb_2aJ(-Dn9uX+IGlpKK^f$M0~wfpj|((N-HJudRb&Y5F6^@@wytr64N6Kq8r*RF=1 zEXV|IrJyR=_7TeSz}ox{Qa|IV`6*Zn&75Pp0&A(6z-0rd?#xcp_4*+&StqyBHAv+J zk3{Hr0+i^zF?4Vw6;N^OD!?5+z@2cVf7^lM(O>*4w2=xROzVEi0~o>ReA-Kz*^&6K-hh1DpVrY72!`%T*ZFRm?b4&ya+( z3gO@gUTaRFjG8dyYvS^BIY<0!=0U1v0HQT(;jd;rRB9yjea**ZfX@K6C%*s)vm>B3 zE}()OwY9l`j&8tx^7YkQ_K|x+Euj>WnWkJ~l8+Bh5qGAVS z)Mpg{a#3CVKI;K;r$zmt0*=fBoCJY-OI|~gBZk82%Mqr&3U=!o1T>SaVFHvJjzaAX z$ISzroDc9*WJ6q1E7zFW4YdRXXgDwLgNl>kv}<2C^@|I+vs5_LAl$*|mwWbTO*rsb<0L+tYHwgHxQ2CvtKDYt!XCd&I zsp&<;Z~8S1eDRdH5c$j9^jt|T1s{~U^I9w$5K$s3Fy8>E_G;`j_zB|mxK!iP+iM=6yCCRBuy>cI}9vSTAsY_@pK+dGQ5z6*zz0b?SU)_`kFYC)ac%T zJyP$6iY8ROfnsa_mb+)Fji;3DSNlmLAZcFvn?BhE>621c*6i6@dzRDw{nuIDQHv2e z`&l0|6Mx3JB|JjwOzYSNa z)1M7tq)g8N2t9jFK_`uMI?%1aj0@-*+ouu^2#HF`;F3|^W z3o$40LKc6On_KzmUyyAUHh$bcjHgqWljh@D&1csmU=#LN{CiBm`C^AzxWNdUBT^s1 z+N7f(uVL@T-JQ+6%IuBgIFNeNB@KH*Qg4Z|FNo0z$x(;EmAMgT&eWt?q~XcDlcA?m zj*jy-nnlJ1KX3ybB$?4I8=dtOa}kO0G21+|TDTuW}f8dIg6@($<+u4U{*2ODUXQ z6G3&SkauMH8lGOp>FeE@>1oIogfZrIz|a$@Q>P)lMbJx6InJQ)q9>3oKM9r5pHZP^ z5TKKazyf$-)V*LsTQc z>7q~Z*Ey87REi9HNnoz2F(#K91PESI>X0YyAVu@B}$QprbK%OMZmtJJ#9MQ_tn*d!%bM!e7Mi#@2N93Cc(1^H(1lrPD zXB>HaOHUt19ei6Vz{NMmFC?49zcRdl^qQOm!7?ODl_|z${uSVoz*B|tjkUPZI6O7%M=+4A~3y zM3ym&d(Ly1Bg-XPqcOS79LcLb0q$v~qBfxHz&KLV3rjya ztWy?p$3I8~c;`@;`H%86=^=P7{Gc7q9(SXS00yUVi8EH>bW+jwNH%%f`>2<)U)32| zGOcN6v)6=mebAim!cLFr2SoxC*?GflaGEaiaS{TLwE^bx&3}%(%G6|r%hkzDy{9!& zK&mm?3EqiqP`-ioVYMQv_1S8=a+#4I zVXb*H2`wq|T33-?a&e zG=6N2{EP;&0f`j@;LQm#E|Do#oeij&2?x3wX}ySVQj@a2flBZlD5tKXjLNsjTUFwr zpcBa!nCC?=^23(4wZ9C)>GLQowKq}*x5I|URSUJwfrBilRK5aAYT*#S4`+#Dp9Qbt zf==4?*es|#5Bb8oB7D2g1p)tRp58*#icbV@I|+%4DJ_`fTglU;YUtgn+hM5ULZ}2j zMg&KQ)Y_NBh(Ep!4sL+d#K{oQz{_Pfkx+5~$nkOg(3?r#{EBvRoJMumiuu$OQorRV z0+O$FQN|JQT=N)2NA-}c=GD32-5}=pDBr3|eK3Aa2lep*^nwdYFzOd6LpL0x?>qhw z#_P7Ysmr|}UwR`?M#~WY8uH87ytW&n`2!3(Zh}!{w@4?Q2q8s4&TFT}Sd;<+@&U}6i%sTV0c zvDA%}%P6gU8QGF8i0>Z)FV@ipa*}L;Eq&m_Hab5@f`rj4Squk_N9${VZ`G|r zuZ^dNSHi}&K3Ee|)_8M)UA$T`Nj1r9Y0S9qVBEieY~fvyvg#ekmLNy?d0yj>y7;E+ z$y-P$dCN({fdX!vgNC}mOWZEtU0y5RAt53`Ga@^KARin;!23u@t#JW1pvk~4s04O- zhFylYlvKBmY`W;JjzWEyy%ayO1Lde&&+vrS63Vb0p5K6!y)LB9KnHgfPf&PO3gohm zK3eU;;Ay~iOTOtaPe)|Y*?s0u%D$mK^seN{N2L12@o3j!9fjIQPUF?~#TlIXXOJ4a zst?&7&&4x@v7t<4>0wni`@W9Q9V>^~D9>#l9v!MSG=7+F<+8V9d7ecWC7Q8|!R|>^ z@_$vhqGW0)Pb8A@hMhy*jrMe-4umyb&r>xiitXy{<-N3nlF7of_c=;*AdNkJf4t1A z_)l%4jH9u&f(NL5hePx%>vRw`_g&XVbIvdU%SE=dFn{Q!C-LyAM2(MWZ-(TZDC^T% zGa$;qVpxRYM4!3eOXXfZ$uPioF16s54#=^YZw~2GoNv>db+D7$2pjobpyVA(g0W-3 z++VlzN7T4Ngl$m?c&<>=mq(C(#tOYcI`Yd!Zz!1Mq}f2NM0G&Ru-+sLpHS=yzo@7#!_YGb*lksf24$NEtDf~|Dg#;j?u;UJ(~9R2oVg`S-DweImAg92 zFP37#zto}448GSYItI>39;%rkBZF(P+ zGw$Qg;nXa)yE|@s9A0F;fy=OUhp??ZnY@85g@@l}L^H?g`L>3_{9J21x!i2i-O zjITyCu=QZkdCuW7GVH)M8ohueLlL@lP0cYK;QzLj!{XcKXvzPFO~rvDbKJNJE74mB z3NNOPir$8yj9x?amytJZ?Yk!og6n8oT2S)1EU5TVldbHDhd^0bt5}ML!iQo=>gL?b z!JF{QF5JzrWE&@oKI)*19tI*s2bW@h=b~bdc%(_Qu=XM+PwKv$vbyBGp44I&1k`D{ z4f(S!L(k)$Awiv%@4G>=<$D-GiRa3_8v%_A_~!ZpMNarIil;dv4v?9}{010O=QdW> zaGmeN#t)7RHJwG_>b@qu)y~sgrXtjbnVpn2{%yV$odV_w-fN z??f+!uf`*dJp|hr@k;@_om){hRMgh&ickNxh>Hx#I3isYKXx*j#;zs#ZH#no%) zpx^Y@SN}c@4+&~HdWVN@Zqe>ZjA4&#=|0re$~XD@RHJc-9J+%}`xGrBZ7RF%KutjN zDyQ~t5xWnyrc;n|6%*gCzglUreoRHb*|KH)BU+0^8{NSlRMNz&`pMw_5KaD?YP2pA z6#2dO-HuAMNNpNAtYz07DF05AzNIUNa~R!D^Ax?_x=_ya`}U>=<&Mbo{nO(X&{65k ziJ4FBr=zU@w2i)d6v!yY^lKS=+{v(ela8{h7fd7`Acu;InoR$SfMb|(4vt{yE?2Z3Q3_`427bvke6 z+kXxwFRQ+KytwFenuc=V-{~?#DrNO&pr{E%WpPqji~b3o?P^r=#@9|dDw)&Li&dtN z#6=e9C~~*istwtfim3NdD*x(WgQ~o{J{k;JLZ!2Xvr(nMTu_`Fz!KX);$6K zV!rGJ`PG#??GzL-INi@x_Iv0BCxsC~rj=sfh2U9cl#)BTpeNRDy^hbZ9Aryg3SMKF zYE-rRXYj4!oK8qdC*08APmaq4$jq2Eo^PeMqoLRobQLi9mJ|n-4u5?uMEzgzt>PgH zG79LJE0@7brToMNt{@>*45{Fq6xp;zs`feL4Ibx%zb66u7ZZ}B0qQr>o!4$VO}iT@ zQvHjvtA{5P8J}oIdIWhy9EM!Mb~Dy1qte{vypDS9X8i8U#k9+PSP7Z%ChGNe#JumIetn{*tV=2kN3S?RV=Z#18`ewJ;na+V76I1nT0K0@ z@peY(l%5EivCwZ3UoYlzz6tk51|Ypp@G2J;aaa&umZQ4dYf-EY?uu`rk8-f@0MI62 z4mEpxDR~FiU!h9cC%_IhdtAQvzn0b)ds6>ydd(e!9#AZrx1uJQXm@{cb={ zsY6T@Qrt>nCM_8cg;RZIvS%JSn8h|LtTsD0sn)QUuH|u+14zqzs_+|s%%xtup0%l{688DlyNv&qnilYK%bGS>m+Jqv) z`v%SC-kVy@mSDWsY*|s+YfiTg0`!dOHGgKwKl_ONP-4zSo#xMas$0!di5qX8+S3*= zPxEgel?i9_v=#3=%o<_L?(#j_);3Cla}N`idi4&6x!GHfQ!6&}*I%c&ODpW7W?C z=Fj8jv>I5VfPPe`_r(4Ge|6sH#IDBo{okWu*W84k0--tlFi;;tp=CgV=c=`HhEQv&2D;#E!TF1kE2Ts zAB%&k$)yF974n)e=^?@|)2TPL)6XQFc;%W)u>0s$m~v%noKzXGq_y#+n}TFtU%70G zQytVE>|rqR!XR^k%XzAmAE)UKUQ-uRPb z*~1d3Cx@;H*T|-yvUQy#OhYzXFM9b`&Ba3$xdPUzQh|wyq@tm6-#O zpTReK#At2jTf#xPl_!f>OJFGU4+w;_06LVcyfzE*?-3LUc2ao~ua#C8Ovd?^kS%G} z8J!Tll5g>qbd@35iItl99A2d_7b;EN6n;A8R$fgf966oT%HPKrmYq%EdK00p?5XPX z1fy!m`0)>~E)(fEQU7-2)iL*+LHgCNp{#jzsGHWVD7J7!2ZhV1O2uj%MTMqht+J{O zCTpLQr%U0bYB^$6Uj?X{(#4qTOa<_ql3|`+Gicu{n7&Q$DZ2c?F?oR53n6eA+aPNH z2>JTjwGg;;4TX<{tKteqD8)A+bg}FoA1P&w?iMf)%46gl^Oz|D{ulIgIo&P$7|l;t zF&@1M*>oB8N6iXhe%vJ8Qe|q-(TA}dtJrDIR=c+q5u6jn7n`Dp-FbEWO@HUC>>#O+ zw+*W)eXL5RFw>_3bXHe}_G len(sa.raw.Type)-1 { + if len(sa.Type) > 13 { return nil, 0, EINVAL } - if len(sa.Name) > len(sa.raw.Name)-1 { + if len(sa.Name) > 63 { return nil, 0, EINVAL } @@ -704,8 +704,17 @@ func (sa *SockaddrALG) sockaddr() (unsafe.Pointer, _Socklen, error) { sa.raw.Feat = sa.Feature sa.raw.Mask = sa.Mask - copy(sa.raw.Type[:], sa.Type) - copy(sa.raw.Name[:], sa.Name) + typ, err := ByteSliceFromString(sa.Type) + if err != nil { + return nil, 0, err + } + name, err := ByteSliceFromString(sa.Name) + if err != nil { + return nil, 0, err + } + + copy(sa.raw.Type[:], typ) + copy(sa.raw.Name[:], name) return unsafe.Pointer(&sa.raw), SizeofSockaddrALG, nil } @@ -1979,6 +1988,8 @@ func Signalfd(fd int, sigmask *Sigset_t, flags int) (newfd int, err error) { //sys Unshare(flags int) (err error) //sys write(fd int, p []byte) (n int, err error) //sys exitThread(code int) (err error) = SYS_EXIT +//sys readlen(fd int, p *byte, np int) (n int, err error) = SYS_READ +//sys writelen(fd int, p *byte, np int) (n int, err error) = SYS_WRITE //sys readv(fd int, iovs []Iovec) (n int, err error) = SYS_READV //sys writev(fd int, iovs []Iovec) (n int, err error) = SYS_WRITEV //sys preadv(fd int, iovs []Iovec, offs_l uintptr, offs_h uintptr) (n int, err error) = SYS_PREADV @@ -2460,25 +2471,98 @@ func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask * return pselect6(nfd, r, w, e, mutableTimeout, kernelMask) } -//sys schedSetattr(pid int, attr *SchedAttr, flags uint) (err error) -//sys schedGetattr(pid int, attr *SchedAttr, size uint, flags uint) (err error) - -// SchedSetAttr is a wrapper for sched_setattr(2) syscall. -// https://man7.org/linux/man-pages/man2/sched_setattr.2.html -func SchedSetAttr(pid int, attr *SchedAttr, flags uint) error { - if attr == nil { - return EINVAL - } - attr.Size = SizeofSchedAttr - return schedSetattr(pid, attr, flags) -} - -// SchedGetAttr is a wrapper for sched_getattr(2) syscall. -// https://man7.org/linux/man-pages/man2/sched_getattr.2.html -func SchedGetAttr(pid int, flags uint) (*SchedAttr, error) { - attr := &SchedAttr{} - if err := schedGetattr(pid, attr, SizeofSchedAttr, flags); err != nil { - return nil, err - } - return attr, nil -} +/* + * Unimplemented + */ +// AfsSyscall +// ArchPrctl +// Brk +// ClockNanosleep +// ClockSettime +// Clone +// EpollCtlOld +// EpollPwait +// EpollWaitOld +// Execve +// Fork +// Futex +// GetKernelSyms +// GetMempolicy +// GetRobustList +// GetThreadArea +// Getpmsg +// IoCancel +// IoDestroy +// IoGetevents +// IoSetup +// IoSubmit +// IoprioGet +// IoprioSet +// KexecLoad +// LookupDcookie +// Mbind +// MigratePages +// Mincore +// ModifyLdt +// Mount +// MovePages +// MqGetsetattr +// MqNotify +// MqOpen +// MqTimedreceive +// MqTimedsend +// MqUnlink +// Msgctl +// Msgget +// Msgrcv +// Msgsnd +// Nfsservctl +// Personality +// Pselect6 +// Ptrace +// Putpmsg +// Quotactl +// Readahead +// Readv +// RemapFilePages +// RestartSyscall +// RtSigaction +// RtSigpending +// RtSigqueueinfo +// RtSigreturn +// RtSigsuspend +// RtSigtimedwait +// SchedGetPriorityMax +// SchedGetPriorityMin +// SchedGetparam +// SchedGetscheduler +// SchedRrGetInterval +// SchedSetparam +// SchedYield +// Security +// Semctl +// Semget +// Semop +// Semtimedop +// SetMempolicy +// SetRobustList +// SetThreadArea +// SetTidAddress +// Sigaltstack +// Swapoff +// Swapon +// Sysfs +// TimerCreate +// TimerDelete +// TimerGetoverrun +// TimerGettime +// TimerSettime +// Tkill (obsolete) +// Tuxcall +// Umount2 +// Uselib +// Utimensat +// Vfork +// Vhangup +// Vserver +// _Sysctl diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd.go b/vendor/golang.org/x/sys/unix/syscall_netbsd.go index 88162099a..ddd1ac853 100644 --- a/vendor/golang.org/x/sys/unix/syscall_netbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_netbsd.go @@ -356,6 +356,8 @@ func Statvfs(path string, buf *Statvfs_t) (err error) { //sys write(fd int, p []byte) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) +//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ +//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) const ( @@ -369,3 +371,262 @@ const ( func mremap(oldaddr uintptr, oldlength uintptr, newlength uintptr, flags int, newaddr uintptr) (uintptr, error) { return mremapNetBSD(oldaddr, oldlength, newaddr, newlength, flags) } + +/* + * Unimplemented + */ +// ____semctl13 +// __clone +// __fhopen40 +// __fhstat40 +// __fhstatvfs140 +// __fstat30 +// __getcwd +// __getfh30 +// __getlogin +// __lstat30 +// __mount50 +// __msgctl13 +// __msync13 +// __ntp_gettime30 +// __posix_chown +// __posix_fchown +// __posix_lchown +// __posix_rename +// __setlogin +// __shmctl13 +// __sigaction_sigtramp +// __sigaltstack14 +// __sigpending14 +// __sigprocmask14 +// __sigsuspend14 +// __sigtimedwait +// __stat30 +// __syscall +// __vfork14 +// _ksem_close +// _ksem_destroy +// _ksem_getvalue +// _ksem_init +// _ksem_open +// _ksem_post +// _ksem_trywait +// _ksem_unlink +// _ksem_wait +// _lwp_continue +// _lwp_create +// _lwp_ctl +// _lwp_detach +// _lwp_exit +// _lwp_getname +// _lwp_getprivate +// _lwp_kill +// _lwp_park +// _lwp_self +// _lwp_setname +// _lwp_setprivate +// _lwp_suspend +// _lwp_unpark +// _lwp_unpark_all +// _lwp_wait +// _lwp_wakeup +// _pset_bind +// _sched_getaffinity +// _sched_getparam +// _sched_setaffinity +// _sched_setparam +// acct +// aio_cancel +// aio_error +// aio_fsync +// aio_read +// aio_return +// aio_suspend +// aio_write +// break +// clock_getres +// clock_gettime +// clock_settime +// compat_09_ogetdomainname +// compat_09_osetdomainname +// compat_09_ouname +// compat_10_omsgsys +// compat_10_osemsys +// compat_10_oshmsys +// compat_12_fstat12 +// compat_12_getdirentries +// compat_12_lstat12 +// compat_12_msync +// compat_12_oreboot +// compat_12_oswapon +// compat_12_stat12 +// compat_13_sigaction13 +// compat_13_sigaltstack13 +// compat_13_sigpending13 +// compat_13_sigprocmask13 +// compat_13_sigreturn13 +// compat_13_sigsuspend13 +// compat_14___semctl +// compat_14_msgctl +// compat_14_shmctl +// compat_16___sigaction14 +// compat_16___sigreturn14 +// compat_20_fhstatfs +// compat_20_fstatfs +// compat_20_getfsstat +// compat_20_statfs +// compat_30___fhstat30 +// compat_30___fstat13 +// compat_30___lstat13 +// compat_30___stat13 +// compat_30_fhopen +// compat_30_fhstat +// compat_30_fhstatvfs1 +// compat_30_getdents +// compat_30_getfh +// compat_30_ntp_gettime +// compat_30_socket +// compat_40_mount +// compat_43_fstat43 +// compat_43_lstat43 +// compat_43_oaccept +// compat_43_ocreat +// compat_43_oftruncate +// compat_43_ogetdirentries +// compat_43_ogetdtablesize +// compat_43_ogethostid +// compat_43_ogethostname +// compat_43_ogetkerninfo +// compat_43_ogetpagesize +// compat_43_ogetpeername +// compat_43_ogetrlimit +// compat_43_ogetsockname +// compat_43_okillpg +// compat_43_olseek +// compat_43_ommap +// compat_43_oquota +// compat_43_orecv +// compat_43_orecvfrom +// compat_43_orecvmsg +// compat_43_osend +// compat_43_osendmsg +// compat_43_osethostid +// compat_43_osethostname +// compat_43_osigblock +// compat_43_osigsetmask +// compat_43_osigstack +// compat_43_osigvec +// compat_43_otruncate +// compat_43_owait +// compat_43_stat43 +// execve +// extattr_delete_fd +// extattr_delete_file +// extattr_delete_link +// extattr_get_fd +// extattr_get_file +// extattr_get_link +// extattr_list_fd +// extattr_list_file +// extattr_list_link +// extattr_set_fd +// extattr_set_file +// extattr_set_link +// extattrctl +// fchroot +// fdatasync +// fgetxattr +// fktrace +// flistxattr +// fork +// fremovexattr +// fsetxattr +// fstatvfs1 +// fsync_range +// getcontext +// getitimer +// getvfsstat +// getxattr +// ktrace +// lchflags +// lchmod +// lfs_bmapv +// lfs_markv +// lfs_segclean +// lfs_segwait +// lgetxattr +// lio_listio +// listxattr +// llistxattr +// lremovexattr +// lseek +// lsetxattr +// lutimes +// madvise +// mincore +// minherit +// modctl +// mq_close +// mq_getattr +// mq_notify +// mq_open +// mq_receive +// mq_send +// mq_setattr +// mq_timedreceive +// mq_timedsend +// mq_unlink +// msgget +// msgrcv +// msgsnd +// nfssvc +// ntp_adjtime +// pmc_control +// pmc_get_info +// pollts +// preadv +// profil +// pselect +// pset_assign +// pset_create +// pset_destroy +// ptrace +// pwritev +// quotactl +// rasctl +// readv +// reboot +// removexattr +// sa_enable +// sa_preempt +// sa_register +// sa_setconcurrency +// sa_stacks +// sa_yield +// sbrk +// sched_yield +// semconfig +// semget +// semop +// setcontext +// setitimer +// setxattr +// shmat +// shmdt +// shmget +// sstk +// statvfs1 +// swapctl +// sysarch +// syscall +// timer_create +// timer_delete +// timer_getoverrun +// timer_gettime +// timer_settime +// undelete +// utrace +// uuidgen +// vadvise +// vfork +// writev diff --git a/vendor/golang.org/x/sys/unix/syscall_openbsd.go b/vendor/golang.org/x/sys/unix/syscall_openbsd.go index 6f34479b5..c5f166a11 100644 --- a/vendor/golang.org/x/sys/unix/syscall_openbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_openbsd.go @@ -326,4 +326,78 @@ func Uname(uname *Utsname) error { //sys write(fd int, p []byte) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) +//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ +//sys writelen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_WRITE //sys utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) + +/* + * Unimplemented + */ +// __getcwd +// __semctl +// __syscall +// __sysctl +// adjfreq +// break +// clock_getres +// clock_gettime +// clock_settime +// closefrom +// execve +// fhopen +// fhstat +// fhstatfs +// fork +// futimens +// getfh +// getgid +// getitimer +// getlogin +// getthrid +// ktrace +// lfs_bmapv +// lfs_markv +// lfs_segclean +// lfs_segwait +// mincore +// minherit +// mount +// mquery +// msgctl +// msgget +// msgrcv +// msgsnd +// nfssvc +// nnpfspioctl +// preadv +// profil +// pwritev +// quotactl +// readv +// reboot +// renameat +// rfork +// sched_yield +// semget +// semop +// setgroups +// setitimer +// setsockopt +// shmat +// shmctl +// shmdt +// shmget +// sigaction +// sigaltstack +// sigpending +// sigprocmask +// sigreturn +// sigsuspend +// sysarch +// syscall +// threxit +// thrsigdivert +// thrsleep +// thrwakeup +// vfork +// writev diff --git a/vendor/golang.org/x/sys/unix/syscall_solaris.go b/vendor/golang.org/x/sys/unix/syscall_solaris.go index b99cfa134..72d23575f 100644 --- a/vendor/golang.org/x/sys/unix/syscall_solaris.go +++ b/vendor/golang.org/x/sys/unix/syscall_solaris.go @@ -698,6 +698,24 @@ func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err e //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) = libsocket.setsockopt //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) = libsocket.recvfrom +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procread)), 3, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = e1 + } + return +} + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwrite)), 3, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf), 0, 0, 0) + n = int(r0) + if e1 != 0 { + err = e1 + } + return +} + // Event Ports type fileObjCookie struct { diff --git a/vendor/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go index f6eda2705..8bb30e7ce 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix.go @@ -549,9 +549,6 @@ func SetNonblock(fd int, nonblocking bool) (err error) { if err != nil { return err } - if (flag&O_NONBLOCK != 0) == nonblocking { - return nil - } if nonblocking { flag |= O_NONBLOCK } else { diff --git a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go index 4596d041c..44e72edb4 100644 --- a/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_zos_s390x.go @@ -192,6 +192,7 @@ func (cmsg *Cmsghdr) SetLen(length int) { //sys fcntl(fd int, cmd int, arg int) (val int, err error) //sys read(fd int, p []byte) (n int, err error) +//sys readlen(fd int, buf *byte, nbuf int) (n int, err error) = SYS_READ //sys write(fd int, p []byte) (n int, err error) //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) = SYS___ACCEPT_A diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux.go b/vendor/golang.org/x/sys/unix/zerrors_linux.go index f9c7f479b..3784f402e 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux.go @@ -2421,15 +2421,6 @@ const ( PR_PAC_GET_ENABLED_KEYS = 0x3d PR_PAC_RESET_KEYS = 0x36 PR_PAC_SET_ENABLED_KEYS = 0x3c - PR_RISCV_V_GET_CONTROL = 0x46 - PR_RISCV_V_SET_CONTROL = 0x45 - PR_RISCV_V_VSTATE_CTRL_CUR_MASK = 0x3 - PR_RISCV_V_VSTATE_CTRL_DEFAULT = 0x0 - PR_RISCV_V_VSTATE_CTRL_INHERIT = 0x10 - PR_RISCV_V_VSTATE_CTRL_MASK = 0x1f - PR_RISCV_V_VSTATE_CTRL_NEXT_MASK = 0xc - PR_RISCV_V_VSTATE_CTRL_OFF = 0x1 - PR_RISCV_V_VSTATE_CTRL_ON = 0x2 PR_SCHED_CORE = 0x3e PR_SCHED_CORE_CREATE = 0x1 PR_SCHED_CORE_GET = 0x0 @@ -2830,23 +2821,6 @@ const ( RWF_SUPPORTED = 0x1f RWF_SYNC = 0x4 RWF_WRITE_LIFE_NOT_SET = 0x0 - SCHED_BATCH = 0x3 - SCHED_DEADLINE = 0x6 - SCHED_FIFO = 0x1 - SCHED_FLAG_ALL = 0x7f - SCHED_FLAG_DL_OVERRUN = 0x4 - SCHED_FLAG_KEEP_ALL = 0x18 - SCHED_FLAG_KEEP_PARAMS = 0x10 - SCHED_FLAG_KEEP_POLICY = 0x8 - SCHED_FLAG_RECLAIM = 0x2 - SCHED_FLAG_RESET_ON_FORK = 0x1 - SCHED_FLAG_UTIL_CLAMP = 0x60 - SCHED_FLAG_UTIL_CLAMP_MAX = 0x40 - SCHED_FLAG_UTIL_CLAMP_MIN = 0x20 - SCHED_IDLE = 0x5 - SCHED_NORMAL = 0x0 - SCHED_RESET_ON_FORK = 0x40000000 - SCHED_RR = 0x2 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index 30aee00a5..cfb143001 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -326,12 +326,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1f SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x26 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index 8ebfa5127..df64f2d59 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -327,12 +327,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1f SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x26 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index 271a21cdc..3025cd5b2 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -333,12 +333,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1f SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x26 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index 910c330a3..09e1ffbef 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -323,12 +323,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1f SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x26 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go index a640798c9..a45723540 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_loong64.go @@ -118,8 +118,6 @@ const ( IUCLC = 0x200 IXOFF = 0x1000 IXON = 0x400 - LASX_CTX_MAGIC = 0x41535801 - LSX_CTX_MAGIC = 0x53580001 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 @@ -319,12 +317,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1f SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x26 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index 0d5925d34..fee7dfb81 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -326,12 +326,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1e SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x1028 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index d72a00e0b..a5b2373ae 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -326,12 +326,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1e SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x1028 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index 02ba129f8..5dde82c98 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -326,12 +326,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1e SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x1028 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index 8daa6dd96..2e80ea6b3 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -326,12 +326,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0x100 SO_PASSCRED = 0x11 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x12 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1e SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x1028 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go index 63c8fa2f7..a65dcd7cb 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc.go @@ -381,12 +381,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0xa SO_PASSCRED = 0x14 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x15 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1f SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x26 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index 930799ec1..cbd34e3d8 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -385,12 +385,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0xa SO_PASSCRED = 0x14 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x15 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1f SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x26 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index 8605a7dd7..e4afa7a31 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -385,12 +385,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0xa SO_PASSCRED = 0x14 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x15 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1f SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x26 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go index 95a016f1c..44f45a039 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_riscv64.go @@ -314,12 +314,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1f SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x26 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index 1ae0108f5..74733e260 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -389,12 +389,10 @@ const ( SO_NOFCS = 0x2b SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 - SO_PASSPIDFD = 0x4c SO_PASSSEC = 0x22 SO_PEEK_OFF = 0x2a SO_PEERCRED = 0x11 SO_PEERGROUPS = 0x3b - SO_PEERPIDFD = 0x4d SO_PEERSEC = 0x1f SO_PREFER_BUSY_POLL = 0x45 SO_PROTOCOL = 0x26 diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go index 1bb7c6333..f5f3934b1 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_sparc64.go @@ -428,12 +428,10 @@ const ( SO_NOFCS = 0x27 SO_OOBINLINE = 0x100 SO_PASSCRED = 0x2 - SO_PASSPIDFD = 0x55 SO_PASSSEC = 0x1f SO_PEEK_OFF = 0x26 SO_PEERCRED = 0x40 SO_PEERGROUPS = 0x3d - SO_PEERPIDFD = 0x56 SO_PEERSEC = 0x1e SO_PREFER_BUSY_POLL = 0x48 SO_PROTOCOL = 0x1028 diff --git a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go index d1d1d2331..9a257219d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc.go @@ -817,6 +817,28 @@ func write(fd int, p []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, p *byte, np int) (n int, err error) { + r0, er := C.read(C.int(fd), C.uintptr_t(uintptr(unsafe.Pointer(p))), C.size_t(np)) + n = int(r0) + if r0 == -1 && er != nil { + err = er + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, p *byte, np int) (n int, err error) { + r0, er := C.write(C.int(fd), C.uintptr_t(uintptr(unsafe.Pointer(p))), C.size_t(np)) + n = int(r0) + if r0 == -1 && er != nil { + err = er + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Dup2(oldfd int, newfd int) (err error) { r0, er := C.dup2(C.int(oldfd), C.int(newfd)) if r0 == -1 && er != nil { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go index f99a18adc..6de80c20c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_aix_ppc64.go @@ -762,6 +762,28 @@ func write(fd int, p []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, p *byte, np int) (n int, err error) { + r0, e1 := callread(fd, uintptr(unsafe.Pointer(p)), np) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, p *byte, np int) (n int, err error) { + r0, e1 := callwrite(fd, uintptr(unsafe.Pointer(p)), np) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Dup2(oldfd int, newfd int) (err error) { _, e1 := calldup2(oldfd, newfd) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go index 1cad561e9..4037ccf7a 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go @@ -725,12 +725,6 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { return } -var libc_ioctl_trampoline_addr uintptr - -//go:cgo_import_dynamic libc_ioctl ioctl "/usr/lib/libSystem.B.dylib" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -739,6 +733,10 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { return } +var libc_ioctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ioctl ioctl "/usr/lib/libSystem.B.dylib" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { @@ -2412,6 +2410,28 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := syscall_syscall(libc_fstat64_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { @@ -2501,6 +2521,14 @@ func ptrace1(request int, pid int, addr uintptr, data uintptr) (err error) { return } +func ptrace1Ptr(request int, pid int, addr uintptr, data unsafe.Pointer) (err error) { + _, _, e1 := syscall_syscall6(libc_ptrace_trampoline_addr, uintptr(request), uintptr(pid), addr, uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + var libc_ptrace_trampoline_addr uintptr //go:cgo_import_dynamic libc_ptrace ptrace "/usr/lib/libSystem.B.dylib" diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s index 8b8bb2840..4baaed0bc 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.s @@ -5,586 +5,703 @@ TEXT libc_fdopendir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fdopendir(SB) + GLOBL ·libc_fdopendir_trampoline_addr(SB), RODATA, $8 DATA ·libc_fdopendir_trampoline_addr(SB)/8, $libc_fdopendir_trampoline<>(SB) TEXT libc_getgroups_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getgroups(SB) + GLOBL ·libc_getgroups_trampoline_addr(SB), RODATA, $8 DATA ·libc_getgroups_trampoline_addr(SB)/8, $libc_getgroups_trampoline<>(SB) TEXT libc_setgroups_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setgroups(SB) + GLOBL ·libc_setgroups_trampoline_addr(SB), RODATA, $8 DATA ·libc_setgroups_trampoline_addr(SB)/8, $libc_setgroups_trampoline<>(SB) TEXT libc_wait4_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_wait4(SB) + GLOBL ·libc_wait4_trampoline_addr(SB), RODATA, $8 DATA ·libc_wait4_trampoline_addr(SB)/8, $libc_wait4_trampoline<>(SB) TEXT libc_accept_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_accept(SB) + GLOBL ·libc_accept_trampoline_addr(SB), RODATA, $8 DATA ·libc_accept_trampoline_addr(SB)/8, $libc_accept_trampoline<>(SB) TEXT libc_bind_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_bind(SB) + GLOBL ·libc_bind_trampoline_addr(SB), RODATA, $8 DATA ·libc_bind_trampoline_addr(SB)/8, $libc_bind_trampoline<>(SB) TEXT libc_connect_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_connect(SB) + GLOBL ·libc_connect_trampoline_addr(SB), RODATA, $8 DATA ·libc_connect_trampoline_addr(SB)/8, $libc_connect_trampoline<>(SB) TEXT libc_socket_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_socket(SB) + GLOBL ·libc_socket_trampoline_addr(SB), RODATA, $8 DATA ·libc_socket_trampoline_addr(SB)/8, $libc_socket_trampoline<>(SB) TEXT libc_getsockopt_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getsockopt(SB) + GLOBL ·libc_getsockopt_trampoline_addr(SB), RODATA, $8 DATA ·libc_getsockopt_trampoline_addr(SB)/8, $libc_getsockopt_trampoline<>(SB) TEXT libc_setsockopt_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setsockopt(SB) + GLOBL ·libc_setsockopt_trampoline_addr(SB), RODATA, $8 DATA ·libc_setsockopt_trampoline_addr(SB)/8, $libc_setsockopt_trampoline<>(SB) TEXT libc_getpeername_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getpeername(SB) + GLOBL ·libc_getpeername_trampoline_addr(SB), RODATA, $8 DATA ·libc_getpeername_trampoline_addr(SB)/8, $libc_getpeername_trampoline<>(SB) TEXT libc_getsockname_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getsockname(SB) + GLOBL ·libc_getsockname_trampoline_addr(SB), RODATA, $8 DATA ·libc_getsockname_trampoline_addr(SB)/8, $libc_getsockname_trampoline<>(SB) TEXT libc_shutdown_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_shutdown(SB) + GLOBL ·libc_shutdown_trampoline_addr(SB), RODATA, $8 DATA ·libc_shutdown_trampoline_addr(SB)/8, $libc_shutdown_trampoline<>(SB) TEXT libc_socketpair_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_socketpair(SB) + GLOBL ·libc_socketpair_trampoline_addr(SB), RODATA, $8 DATA ·libc_socketpair_trampoline_addr(SB)/8, $libc_socketpair_trampoline<>(SB) TEXT libc_recvfrom_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_recvfrom(SB) + GLOBL ·libc_recvfrom_trampoline_addr(SB), RODATA, $8 DATA ·libc_recvfrom_trampoline_addr(SB)/8, $libc_recvfrom_trampoline<>(SB) TEXT libc_sendto_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sendto(SB) + GLOBL ·libc_sendto_trampoline_addr(SB), RODATA, $8 DATA ·libc_sendto_trampoline_addr(SB)/8, $libc_sendto_trampoline<>(SB) TEXT libc_recvmsg_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_recvmsg(SB) + GLOBL ·libc_recvmsg_trampoline_addr(SB), RODATA, $8 DATA ·libc_recvmsg_trampoline_addr(SB)/8, $libc_recvmsg_trampoline<>(SB) TEXT libc_sendmsg_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sendmsg(SB) + GLOBL ·libc_sendmsg_trampoline_addr(SB), RODATA, $8 DATA ·libc_sendmsg_trampoline_addr(SB)/8, $libc_sendmsg_trampoline<>(SB) TEXT libc_kevent_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_kevent(SB) + GLOBL ·libc_kevent_trampoline_addr(SB), RODATA, $8 DATA ·libc_kevent_trampoline_addr(SB)/8, $libc_kevent_trampoline<>(SB) TEXT libc_utimes_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_utimes(SB) + GLOBL ·libc_utimes_trampoline_addr(SB), RODATA, $8 DATA ·libc_utimes_trampoline_addr(SB)/8, $libc_utimes_trampoline<>(SB) TEXT libc_futimes_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_futimes(SB) + GLOBL ·libc_futimes_trampoline_addr(SB), RODATA, $8 DATA ·libc_futimes_trampoline_addr(SB)/8, $libc_futimes_trampoline<>(SB) TEXT libc_poll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_poll(SB) + GLOBL ·libc_poll_trampoline_addr(SB), RODATA, $8 DATA ·libc_poll_trampoline_addr(SB)/8, $libc_poll_trampoline<>(SB) TEXT libc_madvise_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_madvise(SB) + GLOBL ·libc_madvise_trampoline_addr(SB), RODATA, $8 DATA ·libc_madvise_trampoline_addr(SB)/8, $libc_madvise_trampoline<>(SB) TEXT libc_mlock_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mlock(SB) + GLOBL ·libc_mlock_trampoline_addr(SB), RODATA, $8 DATA ·libc_mlock_trampoline_addr(SB)/8, $libc_mlock_trampoline<>(SB) TEXT libc_mlockall_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mlockall(SB) + GLOBL ·libc_mlockall_trampoline_addr(SB), RODATA, $8 DATA ·libc_mlockall_trampoline_addr(SB)/8, $libc_mlockall_trampoline<>(SB) TEXT libc_mprotect_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mprotect(SB) + GLOBL ·libc_mprotect_trampoline_addr(SB), RODATA, $8 DATA ·libc_mprotect_trampoline_addr(SB)/8, $libc_mprotect_trampoline<>(SB) TEXT libc_msync_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_msync(SB) + GLOBL ·libc_msync_trampoline_addr(SB), RODATA, $8 DATA ·libc_msync_trampoline_addr(SB)/8, $libc_msync_trampoline<>(SB) TEXT libc_munlock_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_munlock(SB) + GLOBL ·libc_munlock_trampoline_addr(SB), RODATA, $8 DATA ·libc_munlock_trampoline_addr(SB)/8, $libc_munlock_trampoline<>(SB) TEXT libc_munlockall_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_munlockall(SB) + GLOBL ·libc_munlockall_trampoline_addr(SB), RODATA, $8 DATA ·libc_munlockall_trampoline_addr(SB)/8, $libc_munlockall_trampoline<>(SB) TEXT libc_closedir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_closedir(SB) + GLOBL ·libc_closedir_trampoline_addr(SB), RODATA, $8 DATA ·libc_closedir_trampoline_addr(SB)/8, $libc_closedir_trampoline<>(SB) TEXT libc_readdir_r_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_readdir_r(SB) + GLOBL ·libc_readdir_r_trampoline_addr(SB), RODATA, $8 DATA ·libc_readdir_r_trampoline_addr(SB)/8, $libc_readdir_r_trampoline<>(SB) TEXT libc_pipe_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_pipe(SB) + GLOBL ·libc_pipe_trampoline_addr(SB), RODATA, $8 DATA ·libc_pipe_trampoline_addr(SB)/8, $libc_pipe_trampoline<>(SB) TEXT libc_getxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getxattr(SB) + GLOBL ·libc_getxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_getxattr_trampoline_addr(SB)/8, $libc_getxattr_trampoline<>(SB) TEXT libc_fgetxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fgetxattr(SB) + GLOBL ·libc_fgetxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_fgetxattr_trampoline_addr(SB)/8, $libc_fgetxattr_trampoline<>(SB) TEXT libc_setxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setxattr(SB) + GLOBL ·libc_setxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_setxattr_trampoline_addr(SB)/8, $libc_setxattr_trampoline<>(SB) TEXT libc_fsetxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fsetxattr(SB) + GLOBL ·libc_fsetxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_fsetxattr_trampoline_addr(SB)/8, $libc_fsetxattr_trampoline<>(SB) TEXT libc_removexattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_removexattr(SB) + GLOBL ·libc_removexattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_removexattr_trampoline_addr(SB)/8, $libc_removexattr_trampoline<>(SB) TEXT libc_fremovexattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fremovexattr(SB) + GLOBL ·libc_fremovexattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_fremovexattr_trampoline_addr(SB)/8, $libc_fremovexattr_trampoline<>(SB) TEXT libc_listxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_listxattr(SB) + GLOBL ·libc_listxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_listxattr_trampoline_addr(SB)/8, $libc_listxattr_trampoline<>(SB) TEXT libc_flistxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_flistxattr(SB) + GLOBL ·libc_flistxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_flistxattr_trampoline_addr(SB)/8, $libc_flistxattr_trampoline<>(SB) TEXT libc_utimensat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_utimensat(SB) + GLOBL ·libc_utimensat_trampoline_addr(SB), RODATA, $8 DATA ·libc_utimensat_trampoline_addr(SB)/8, $libc_utimensat_trampoline<>(SB) TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fcntl(SB) + GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) TEXT libc_kill_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_kill(SB) + GLOBL ·libc_kill_trampoline_addr(SB), RODATA, $8 DATA ·libc_kill_trampoline_addr(SB)/8, $libc_kill_trampoline<>(SB) TEXT libc_ioctl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ioctl(SB) + GLOBL ·libc_ioctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_ioctl_trampoline_addr(SB)/8, $libc_ioctl_trampoline<>(SB) TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sysctl(SB) + GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) TEXT libc_sendfile_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sendfile(SB) + GLOBL ·libc_sendfile_trampoline_addr(SB), RODATA, $8 DATA ·libc_sendfile_trampoline_addr(SB)/8, $libc_sendfile_trampoline<>(SB) TEXT libc_shmat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_shmat(SB) + GLOBL ·libc_shmat_trampoline_addr(SB), RODATA, $8 DATA ·libc_shmat_trampoline_addr(SB)/8, $libc_shmat_trampoline<>(SB) TEXT libc_shmctl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_shmctl(SB) + GLOBL ·libc_shmctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_shmctl_trampoline_addr(SB)/8, $libc_shmctl_trampoline<>(SB) TEXT libc_shmdt_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_shmdt(SB) + GLOBL ·libc_shmdt_trampoline_addr(SB), RODATA, $8 DATA ·libc_shmdt_trampoline_addr(SB)/8, $libc_shmdt_trampoline<>(SB) TEXT libc_shmget_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_shmget(SB) + GLOBL ·libc_shmget_trampoline_addr(SB), RODATA, $8 DATA ·libc_shmget_trampoline_addr(SB)/8, $libc_shmget_trampoline<>(SB) TEXT libc_access_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_access(SB) + GLOBL ·libc_access_trampoline_addr(SB), RODATA, $8 DATA ·libc_access_trampoline_addr(SB)/8, $libc_access_trampoline<>(SB) TEXT libc_adjtime_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_adjtime(SB) + GLOBL ·libc_adjtime_trampoline_addr(SB), RODATA, $8 DATA ·libc_adjtime_trampoline_addr(SB)/8, $libc_adjtime_trampoline<>(SB) TEXT libc_chdir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_chdir(SB) + GLOBL ·libc_chdir_trampoline_addr(SB), RODATA, $8 DATA ·libc_chdir_trampoline_addr(SB)/8, $libc_chdir_trampoline<>(SB) TEXT libc_chflags_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_chflags(SB) + GLOBL ·libc_chflags_trampoline_addr(SB), RODATA, $8 DATA ·libc_chflags_trampoline_addr(SB)/8, $libc_chflags_trampoline<>(SB) TEXT libc_chmod_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_chmod(SB) + GLOBL ·libc_chmod_trampoline_addr(SB), RODATA, $8 DATA ·libc_chmod_trampoline_addr(SB)/8, $libc_chmod_trampoline<>(SB) TEXT libc_chown_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_chown(SB) + GLOBL ·libc_chown_trampoline_addr(SB), RODATA, $8 DATA ·libc_chown_trampoline_addr(SB)/8, $libc_chown_trampoline<>(SB) TEXT libc_chroot_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_chroot(SB) + GLOBL ·libc_chroot_trampoline_addr(SB), RODATA, $8 DATA ·libc_chroot_trampoline_addr(SB)/8, $libc_chroot_trampoline<>(SB) TEXT libc_clock_gettime_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_clock_gettime(SB) + GLOBL ·libc_clock_gettime_trampoline_addr(SB), RODATA, $8 DATA ·libc_clock_gettime_trampoline_addr(SB)/8, $libc_clock_gettime_trampoline<>(SB) TEXT libc_close_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_close(SB) + GLOBL ·libc_close_trampoline_addr(SB), RODATA, $8 DATA ·libc_close_trampoline_addr(SB)/8, $libc_close_trampoline<>(SB) TEXT libc_clonefile_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_clonefile(SB) + GLOBL ·libc_clonefile_trampoline_addr(SB), RODATA, $8 DATA ·libc_clonefile_trampoline_addr(SB)/8, $libc_clonefile_trampoline<>(SB) TEXT libc_clonefileat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_clonefileat(SB) + GLOBL ·libc_clonefileat_trampoline_addr(SB), RODATA, $8 DATA ·libc_clonefileat_trampoline_addr(SB)/8, $libc_clonefileat_trampoline<>(SB) TEXT libc_dup_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_dup(SB) + GLOBL ·libc_dup_trampoline_addr(SB), RODATA, $8 DATA ·libc_dup_trampoline_addr(SB)/8, $libc_dup_trampoline<>(SB) TEXT libc_dup2_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_dup2(SB) + GLOBL ·libc_dup2_trampoline_addr(SB), RODATA, $8 DATA ·libc_dup2_trampoline_addr(SB)/8, $libc_dup2_trampoline<>(SB) TEXT libc_exchangedata_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_exchangedata(SB) + GLOBL ·libc_exchangedata_trampoline_addr(SB), RODATA, $8 DATA ·libc_exchangedata_trampoline_addr(SB)/8, $libc_exchangedata_trampoline<>(SB) TEXT libc_exit_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_exit(SB) + GLOBL ·libc_exit_trampoline_addr(SB), RODATA, $8 DATA ·libc_exit_trampoline_addr(SB)/8, $libc_exit_trampoline<>(SB) TEXT libc_faccessat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_faccessat(SB) + GLOBL ·libc_faccessat_trampoline_addr(SB), RODATA, $8 DATA ·libc_faccessat_trampoline_addr(SB)/8, $libc_faccessat_trampoline<>(SB) TEXT libc_fchdir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchdir(SB) + GLOBL ·libc_fchdir_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchdir_trampoline_addr(SB)/8, $libc_fchdir_trampoline<>(SB) TEXT libc_fchflags_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchflags(SB) + GLOBL ·libc_fchflags_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchflags_trampoline_addr(SB)/8, $libc_fchflags_trampoline<>(SB) TEXT libc_fchmod_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchmod(SB) + GLOBL ·libc_fchmod_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchmod_trampoline_addr(SB)/8, $libc_fchmod_trampoline<>(SB) TEXT libc_fchmodat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchmodat(SB) + GLOBL ·libc_fchmodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchmodat_trampoline_addr(SB)/8, $libc_fchmodat_trampoline<>(SB) TEXT libc_fchown_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchown(SB) + GLOBL ·libc_fchown_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchown_trampoline_addr(SB)/8, $libc_fchown_trampoline<>(SB) TEXT libc_fchownat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchownat(SB) + GLOBL ·libc_fchownat_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchownat_trampoline_addr(SB)/8, $libc_fchownat_trampoline<>(SB) TEXT libc_fclonefileat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fclonefileat(SB) + GLOBL ·libc_fclonefileat_trampoline_addr(SB), RODATA, $8 DATA ·libc_fclonefileat_trampoline_addr(SB)/8, $libc_fclonefileat_trampoline<>(SB) TEXT libc_flock_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_flock(SB) + GLOBL ·libc_flock_trampoline_addr(SB), RODATA, $8 DATA ·libc_flock_trampoline_addr(SB)/8, $libc_flock_trampoline<>(SB) TEXT libc_fpathconf_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fpathconf(SB) + GLOBL ·libc_fpathconf_trampoline_addr(SB), RODATA, $8 DATA ·libc_fpathconf_trampoline_addr(SB)/8, $libc_fpathconf_trampoline<>(SB) TEXT libc_fsync_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fsync(SB) + GLOBL ·libc_fsync_trampoline_addr(SB), RODATA, $8 DATA ·libc_fsync_trampoline_addr(SB)/8, $libc_fsync_trampoline<>(SB) TEXT libc_ftruncate_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ftruncate(SB) + GLOBL ·libc_ftruncate_trampoline_addr(SB), RODATA, $8 DATA ·libc_ftruncate_trampoline_addr(SB)/8, $libc_ftruncate_trampoline<>(SB) TEXT libc_getcwd_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getcwd(SB) + GLOBL ·libc_getcwd_trampoline_addr(SB), RODATA, $8 DATA ·libc_getcwd_trampoline_addr(SB)/8, $libc_getcwd_trampoline<>(SB) TEXT libc_getdtablesize_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getdtablesize(SB) + GLOBL ·libc_getdtablesize_trampoline_addr(SB), RODATA, $8 DATA ·libc_getdtablesize_trampoline_addr(SB)/8, $libc_getdtablesize_trampoline<>(SB) TEXT libc_getegid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getegid(SB) + GLOBL ·libc_getegid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getegid_trampoline_addr(SB)/8, $libc_getegid_trampoline<>(SB) TEXT libc_geteuid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_geteuid(SB) + GLOBL ·libc_geteuid_trampoline_addr(SB), RODATA, $8 DATA ·libc_geteuid_trampoline_addr(SB)/8, $libc_geteuid_trampoline<>(SB) TEXT libc_getgid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getgid(SB) + GLOBL ·libc_getgid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getgid_trampoline_addr(SB)/8, $libc_getgid_trampoline<>(SB) TEXT libc_getpgid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getpgid(SB) + GLOBL ·libc_getpgid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getpgid_trampoline_addr(SB)/8, $libc_getpgid_trampoline<>(SB) TEXT libc_getpgrp_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getpgrp(SB) + GLOBL ·libc_getpgrp_trampoline_addr(SB), RODATA, $8 DATA ·libc_getpgrp_trampoline_addr(SB)/8, $libc_getpgrp_trampoline<>(SB) TEXT libc_getpid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getpid(SB) + GLOBL ·libc_getpid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getpid_trampoline_addr(SB)/8, $libc_getpid_trampoline<>(SB) TEXT libc_getppid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getppid(SB) + GLOBL ·libc_getppid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getppid_trampoline_addr(SB)/8, $libc_getppid_trampoline<>(SB) TEXT libc_getpriority_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getpriority(SB) + GLOBL ·libc_getpriority_trampoline_addr(SB), RODATA, $8 DATA ·libc_getpriority_trampoline_addr(SB)/8, $libc_getpriority_trampoline<>(SB) TEXT libc_getrlimit_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getrlimit(SB) + GLOBL ·libc_getrlimit_trampoline_addr(SB), RODATA, $8 DATA ·libc_getrlimit_trampoline_addr(SB)/8, $libc_getrlimit_trampoline<>(SB) TEXT libc_getrusage_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getrusage(SB) + GLOBL ·libc_getrusage_trampoline_addr(SB), RODATA, $8 DATA ·libc_getrusage_trampoline_addr(SB)/8, $libc_getrusage_trampoline<>(SB) TEXT libc_getsid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getsid(SB) + GLOBL ·libc_getsid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getsid_trampoline_addr(SB)/8, $libc_getsid_trampoline<>(SB) TEXT libc_gettimeofday_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_gettimeofday(SB) + GLOBL ·libc_gettimeofday_trampoline_addr(SB), RODATA, $8 DATA ·libc_gettimeofday_trampoline_addr(SB)/8, $libc_gettimeofday_trampoline<>(SB) TEXT libc_getuid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getuid(SB) + GLOBL ·libc_getuid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getuid_trampoline_addr(SB)/8, $libc_getuid_trampoline<>(SB) TEXT libc_issetugid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_issetugid(SB) + GLOBL ·libc_issetugid_trampoline_addr(SB), RODATA, $8 DATA ·libc_issetugid_trampoline_addr(SB)/8, $libc_issetugid_trampoline<>(SB) TEXT libc_kqueue_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_kqueue(SB) + GLOBL ·libc_kqueue_trampoline_addr(SB), RODATA, $8 DATA ·libc_kqueue_trampoline_addr(SB)/8, $libc_kqueue_trampoline<>(SB) TEXT libc_lchown_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_lchown(SB) + GLOBL ·libc_lchown_trampoline_addr(SB), RODATA, $8 DATA ·libc_lchown_trampoline_addr(SB)/8, $libc_lchown_trampoline<>(SB) TEXT libc_link_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_link(SB) + GLOBL ·libc_link_trampoline_addr(SB), RODATA, $8 DATA ·libc_link_trampoline_addr(SB)/8, $libc_link_trampoline<>(SB) TEXT libc_linkat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_linkat(SB) + GLOBL ·libc_linkat_trampoline_addr(SB), RODATA, $8 DATA ·libc_linkat_trampoline_addr(SB)/8, $libc_linkat_trampoline<>(SB) TEXT libc_listen_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_listen(SB) + GLOBL ·libc_listen_trampoline_addr(SB), RODATA, $8 DATA ·libc_listen_trampoline_addr(SB)/8, $libc_listen_trampoline<>(SB) TEXT libc_mkdir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mkdir(SB) + GLOBL ·libc_mkdir_trampoline_addr(SB), RODATA, $8 DATA ·libc_mkdir_trampoline_addr(SB)/8, $libc_mkdir_trampoline<>(SB) TEXT libc_mkdirat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mkdirat(SB) + GLOBL ·libc_mkdirat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mkdirat_trampoline_addr(SB)/8, $libc_mkdirat_trampoline<>(SB) TEXT libc_mkfifo_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mkfifo(SB) + GLOBL ·libc_mkfifo_trampoline_addr(SB), RODATA, $8 DATA ·libc_mkfifo_trampoline_addr(SB)/8, $libc_mkfifo_trampoline<>(SB) TEXT libc_mknod_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mknod(SB) + GLOBL ·libc_mknod_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknod_trampoline_addr(SB)/8, $libc_mknod_trampoline<>(SB) TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mount(SB) + GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) TEXT libc_open_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_open(SB) + GLOBL ·libc_open_trampoline_addr(SB), RODATA, $8 DATA ·libc_open_trampoline_addr(SB)/8, $libc_open_trampoline<>(SB) TEXT libc_openat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_openat(SB) + GLOBL ·libc_openat_trampoline_addr(SB), RODATA, $8 DATA ·libc_openat_trampoline_addr(SB)/8, $libc_openat_trampoline<>(SB) TEXT libc_pathconf_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_pathconf(SB) + GLOBL ·libc_pathconf_trampoline_addr(SB), RODATA, $8 DATA ·libc_pathconf_trampoline_addr(SB)/8, $libc_pathconf_trampoline<>(SB) TEXT libc_pread_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_pread(SB) + GLOBL ·libc_pread_trampoline_addr(SB), RODATA, $8 DATA ·libc_pread_trampoline_addr(SB)/8, $libc_pread_trampoline<>(SB) TEXT libc_pwrite_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_pwrite(SB) + GLOBL ·libc_pwrite_trampoline_addr(SB), RODATA, $8 DATA ·libc_pwrite_trampoline_addr(SB)/8, $libc_pwrite_trampoline<>(SB) TEXT libc_read_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_read(SB) + GLOBL ·libc_read_trampoline_addr(SB), RODATA, $8 DATA ·libc_read_trampoline_addr(SB)/8, $libc_read_trampoline<>(SB) TEXT libc_readlink_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_readlink(SB) + GLOBL ·libc_readlink_trampoline_addr(SB), RODATA, $8 DATA ·libc_readlink_trampoline_addr(SB)/8, $libc_readlink_trampoline<>(SB) TEXT libc_readlinkat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_readlinkat(SB) + GLOBL ·libc_readlinkat_trampoline_addr(SB), RODATA, $8 DATA ·libc_readlinkat_trampoline_addr(SB)/8, $libc_readlinkat_trampoline<>(SB) TEXT libc_rename_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_rename(SB) + GLOBL ·libc_rename_trampoline_addr(SB), RODATA, $8 DATA ·libc_rename_trampoline_addr(SB)/8, $libc_rename_trampoline<>(SB) TEXT libc_renameat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_renameat(SB) + GLOBL ·libc_renameat_trampoline_addr(SB), RODATA, $8 DATA ·libc_renameat_trampoline_addr(SB)/8, $libc_renameat_trampoline<>(SB) TEXT libc_revoke_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_revoke(SB) + GLOBL ·libc_revoke_trampoline_addr(SB), RODATA, $8 DATA ·libc_revoke_trampoline_addr(SB)/8, $libc_revoke_trampoline<>(SB) TEXT libc_rmdir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_rmdir(SB) + GLOBL ·libc_rmdir_trampoline_addr(SB), RODATA, $8 DATA ·libc_rmdir_trampoline_addr(SB)/8, $libc_rmdir_trampoline<>(SB) TEXT libc_lseek_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_lseek(SB) + GLOBL ·libc_lseek_trampoline_addr(SB), RODATA, $8 DATA ·libc_lseek_trampoline_addr(SB)/8, $libc_lseek_trampoline<>(SB) TEXT libc_select_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_select(SB) + GLOBL ·libc_select_trampoline_addr(SB), RODATA, $8 DATA ·libc_select_trampoline_addr(SB)/8, $libc_select_trampoline<>(SB) @@ -595,160 +712,192 @@ DATA ·libc_setattrlist_trampoline_addr(SB)/8, $libc_setattrlist_trampoline<>(SB TEXT libc_setegid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setegid(SB) + GLOBL ·libc_setegid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setegid_trampoline_addr(SB)/8, $libc_setegid_trampoline<>(SB) TEXT libc_seteuid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_seteuid(SB) + GLOBL ·libc_seteuid_trampoline_addr(SB), RODATA, $8 DATA ·libc_seteuid_trampoline_addr(SB)/8, $libc_seteuid_trampoline<>(SB) TEXT libc_setgid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setgid(SB) + GLOBL ·libc_setgid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setgid_trampoline_addr(SB)/8, $libc_setgid_trampoline<>(SB) TEXT libc_setlogin_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setlogin(SB) + GLOBL ·libc_setlogin_trampoline_addr(SB), RODATA, $8 DATA ·libc_setlogin_trampoline_addr(SB)/8, $libc_setlogin_trampoline<>(SB) TEXT libc_setpgid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setpgid(SB) + GLOBL ·libc_setpgid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setpgid_trampoline_addr(SB)/8, $libc_setpgid_trampoline<>(SB) TEXT libc_setpriority_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setpriority(SB) + GLOBL ·libc_setpriority_trampoline_addr(SB), RODATA, $8 DATA ·libc_setpriority_trampoline_addr(SB)/8, $libc_setpriority_trampoline<>(SB) TEXT libc_setprivexec_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setprivexec(SB) + GLOBL ·libc_setprivexec_trampoline_addr(SB), RODATA, $8 DATA ·libc_setprivexec_trampoline_addr(SB)/8, $libc_setprivexec_trampoline<>(SB) TEXT libc_setregid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setregid(SB) + GLOBL ·libc_setregid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setregid_trampoline_addr(SB)/8, $libc_setregid_trampoline<>(SB) TEXT libc_setreuid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setreuid(SB) + GLOBL ·libc_setreuid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setreuid_trampoline_addr(SB)/8, $libc_setreuid_trampoline<>(SB) TEXT libc_setsid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setsid(SB) + GLOBL ·libc_setsid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setsid_trampoline_addr(SB)/8, $libc_setsid_trampoline<>(SB) TEXT libc_settimeofday_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_settimeofday(SB) + GLOBL ·libc_settimeofday_trampoline_addr(SB), RODATA, $8 DATA ·libc_settimeofday_trampoline_addr(SB)/8, $libc_settimeofday_trampoline<>(SB) TEXT libc_setuid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setuid(SB) + GLOBL ·libc_setuid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setuid_trampoline_addr(SB)/8, $libc_setuid_trampoline<>(SB) TEXT libc_symlink_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_symlink(SB) + GLOBL ·libc_symlink_trampoline_addr(SB), RODATA, $8 DATA ·libc_symlink_trampoline_addr(SB)/8, $libc_symlink_trampoline<>(SB) TEXT libc_symlinkat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_symlinkat(SB) + GLOBL ·libc_symlinkat_trampoline_addr(SB), RODATA, $8 DATA ·libc_symlinkat_trampoline_addr(SB)/8, $libc_symlinkat_trampoline<>(SB) TEXT libc_sync_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sync(SB) + GLOBL ·libc_sync_trampoline_addr(SB), RODATA, $8 DATA ·libc_sync_trampoline_addr(SB)/8, $libc_sync_trampoline<>(SB) TEXT libc_truncate_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_truncate(SB) + GLOBL ·libc_truncate_trampoline_addr(SB), RODATA, $8 DATA ·libc_truncate_trampoline_addr(SB)/8, $libc_truncate_trampoline<>(SB) TEXT libc_umask_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_umask(SB) + GLOBL ·libc_umask_trampoline_addr(SB), RODATA, $8 DATA ·libc_umask_trampoline_addr(SB)/8, $libc_umask_trampoline<>(SB) TEXT libc_undelete_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_undelete(SB) + GLOBL ·libc_undelete_trampoline_addr(SB), RODATA, $8 DATA ·libc_undelete_trampoline_addr(SB)/8, $libc_undelete_trampoline<>(SB) TEXT libc_unlink_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_unlink(SB) + GLOBL ·libc_unlink_trampoline_addr(SB), RODATA, $8 DATA ·libc_unlink_trampoline_addr(SB)/8, $libc_unlink_trampoline<>(SB) TEXT libc_unlinkat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_unlinkat(SB) + GLOBL ·libc_unlinkat_trampoline_addr(SB), RODATA, $8 DATA ·libc_unlinkat_trampoline_addr(SB)/8, $libc_unlinkat_trampoline<>(SB) TEXT libc_unmount_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_unmount(SB) + GLOBL ·libc_unmount_trampoline_addr(SB), RODATA, $8 DATA ·libc_unmount_trampoline_addr(SB)/8, $libc_unmount_trampoline<>(SB) TEXT libc_write_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_write(SB) + GLOBL ·libc_write_trampoline_addr(SB), RODATA, $8 DATA ·libc_write_trampoline_addr(SB)/8, $libc_write_trampoline<>(SB) TEXT libc_mmap_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mmap(SB) + GLOBL ·libc_mmap_trampoline_addr(SB), RODATA, $8 DATA ·libc_mmap_trampoline_addr(SB)/8, $libc_mmap_trampoline<>(SB) TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_munmap(SB) + GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB) TEXT libc_fstat64_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fstat64(SB) + GLOBL ·libc_fstat64_trampoline_addr(SB), RODATA, $8 DATA ·libc_fstat64_trampoline_addr(SB)/8, $libc_fstat64_trampoline<>(SB) TEXT libc_fstatat64_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fstatat64(SB) + GLOBL ·libc_fstatat64_trampoline_addr(SB), RODATA, $8 DATA ·libc_fstatat64_trampoline_addr(SB)/8, $libc_fstatat64_trampoline<>(SB) TEXT libc_fstatfs64_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fstatfs64(SB) + GLOBL ·libc_fstatfs64_trampoline_addr(SB), RODATA, $8 DATA ·libc_fstatfs64_trampoline_addr(SB)/8, $libc_fstatfs64_trampoline<>(SB) TEXT libc_getfsstat64_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getfsstat64(SB) + GLOBL ·libc_getfsstat64_trampoline_addr(SB), RODATA, $8 DATA ·libc_getfsstat64_trampoline_addr(SB)/8, $libc_getfsstat64_trampoline<>(SB) TEXT libc_lstat64_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_lstat64(SB) + GLOBL ·libc_lstat64_trampoline_addr(SB), RODATA, $8 DATA ·libc_lstat64_trampoline_addr(SB)/8, $libc_lstat64_trampoline<>(SB) TEXT libc_ptrace_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ptrace(SB) + GLOBL ·libc_ptrace_trampoline_addr(SB), RODATA, $8 DATA ·libc_ptrace_trampoline_addr(SB)/8, $libc_ptrace_trampoline<>(SB) TEXT libc_stat64_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_stat64(SB) + GLOBL ·libc_stat64_trampoline_addr(SB), RODATA, $8 DATA ·libc_stat64_trampoline_addr(SB)/8, $libc_stat64_trampoline<>(SB) TEXT libc_statfs64_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_statfs64(SB) + GLOBL ·libc_statfs64_trampoline_addr(SB), RODATA, $8 DATA ·libc_statfs64_trampoline_addr(SB)/8, $libc_statfs64_trampoline<>(SB) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go index b18edbd0e..51d6f3fb2 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go @@ -725,12 +725,6 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { return } -var libc_ioctl_trampoline_addr uintptr - -//go:cgo_import_dynamic libc_ioctl ioctl "/usr/lib/libSystem.B.dylib" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -739,6 +733,10 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { return } +var libc_ioctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ioctl ioctl "/usr/lib/libSystem.B.dylib" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { @@ -2412,6 +2410,28 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := syscall_syscall(libc_fstat_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { @@ -2501,6 +2521,14 @@ func ptrace1(request int, pid int, addr uintptr, data uintptr) (err error) { return } +func ptrace1Ptr(request int, pid int, addr uintptr, data unsafe.Pointer) (err error) { + _, _, e1 := syscall_syscall6(libc_ptrace_trampoline_addr, uintptr(request), uintptr(pid), addr, uintptr(data), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + var libc_ptrace_trampoline_addr uintptr //go:cgo_import_dynamic libc_ptrace ptrace "/usr/lib/libSystem.B.dylib" diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s index 08362c1ab..c3b82c037 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.s @@ -5,586 +5,703 @@ TEXT libc_fdopendir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fdopendir(SB) + GLOBL ·libc_fdopendir_trampoline_addr(SB), RODATA, $8 DATA ·libc_fdopendir_trampoline_addr(SB)/8, $libc_fdopendir_trampoline<>(SB) TEXT libc_getgroups_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getgroups(SB) + GLOBL ·libc_getgroups_trampoline_addr(SB), RODATA, $8 DATA ·libc_getgroups_trampoline_addr(SB)/8, $libc_getgroups_trampoline<>(SB) TEXT libc_setgroups_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setgroups(SB) + GLOBL ·libc_setgroups_trampoline_addr(SB), RODATA, $8 DATA ·libc_setgroups_trampoline_addr(SB)/8, $libc_setgroups_trampoline<>(SB) TEXT libc_wait4_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_wait4(SB) + GLOBL ·libc_wait4_trampoline_addr(SB), RODATA, $8 DATA ·libc_wait4_trampoline_addr(SB)/8, $libc_wait4_trampoline<>(SB) TEXT libc_accept_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_accept(SB) + GLOBL ·libc_accept_trampoline_addr(SB), RODATA, $8 DATA ·libc_accept_trampoline_addr(SB)/8, $libc_accept_trampoline<>(SB) TEXT libc_bind_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_bind(SB) + GLOBL ·libc_bind_trampoline_addr(SB), RODATA, $8 DATA ·libc_bind_trampoline_addr(SB)/8, $libc_bind_trampoline<>(SB) TEXT libc_connect_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_connect(SB) + GLOBL ·libc_connect_trampoline_addr(SB), RODATA, $8 DATA ·libc_connect_trampoline_addr(SB)/8, $libc_connect_trampoline<>(SB) TEXT libc_socket_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_socket(SB) + GLOBL ·libc_socket_trampoline_addr(SB), RODATA, $8 DATA ·libc_socket_trampoline_addr(SB)/8, $libc_socket_trampoline<>(SB) TEXT libc_getsockopt_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getsockopt(SB) + GLOBL ·libc_getsockopt_trampoline_addr(SB), RODATA, $8 DATA ·libc_getsockopt_trampoline_addr(SB)/8, $libc_getsockopt_trampoline<>(SB) TEXT libc_setsockopt_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setsockopt(SB) + GLOBL ·libc_setsockopt_trampoline_addr(SB), RODATA, $8 DATA ·libc_setsockopt_trampoline_addr(SB)/8, $libc_setsockopt_trampoline<>(SB) TEXT libc_getpeername_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getpeername(SB) + GLOBL ·libc_getpeername_trampoline_addr(SB), RODATA, $8 DATA ·libc_getpeername_trampoline_addr(SB)/8, $libc_getpeername_trampoline<>(SB) TEXT libc_getsockname_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getsockname(SB) + GLOBL ·libc_getsockname_trampoline_addr(SB), RODATA, $8 DATA ·libc_getsockname_trampoline_addr(SB)/8, $libc_getsockname_trampoline<>(SB) TEXT libc_shutdown_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_shutdown(SB) + GLOBL ·libc_shutdown_trampoline_addr(SB), RODATA, $8 DATA ·libc_shutdown_trampoline_addr(SB)/8, $libc_shutdown_trampoline<>(SB) TEXT libc_socketpair_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_socketpair(SB) + GLOBL ·libc_socketpair_trampoline_addr(SB), RODATA, $8 DATA ·libc_socketpair_trampoline_addr(SB)/8, $libc_socketpair_trampoline<>(SB) TEXT libc_recvfrom_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_recvfrom(SB) + GLOBL ·libc_recvfrom_trampoline_addr(SB), RODATA, $8 DATA ·libc_recvfrom_trampoline_addr(SB)/8, $libc_recvfrom_trampoline<>(SB) TEXT libc_sendto_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sendto(SB) + GLOBL ·libc_sendto_trampoline_addr(SB), RODATA, $8 DATA ·libc_sendto_trampoline_addr(SB)/8, $libc_sendto_trampoline<>(SB) TEXT libc_recvmsg_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_recvmsg(SB) + GLOBL ·libc_recvmsg_trampoline_addr(SB), RODATA, $8 DATA ·libc_recvmsg_trampoline_addr(SB)/8, $libc_recvmsg_trampoline<>(SB) TEXT libc_sendmsg_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sendmsg(SB) + GLOBL ·libc_sendmsg_trampoline_addr(SB), RODATA, $8 DATA ·libc_sendmsg_trampoline_addr(SB)/8, $libc_sendmsg_trampoline<>(SB) TEXT libc_kevent_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_kevent(SB) + GLOBL ·libc_kevent_trampoline_addr(SB), RODATA, $8 DATA ·libc_kevent_trampoline_addr(SB)/8, $libc_kevent_trampoline<>(SB) TEXT libc_utimes_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_utimes(SB) + GLOBL ·libc_utimes_trampoline_addr(SB), RODATA, $8 DATA ·libc_utimes_trampoline_addr(SB)/8, $libc_utimes_trampoline<>(SB) TEXT libc_futimes_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_futimes(SB) + GLOBL ·libc_futimes_trampoline_addr(SB), RODATA, $8 DATA ·libc_futimes_trampoline_addr(SB)/8, $libc_futimes_trampoline<>(SB) TEXT libc_poll_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_poll(SB) + GLOBL ·libc_poll_trampoline_addr(SB), RODATA, $8 DATA ·libc_poll_trampoline_addr(SB)/8, $libc_poll_trampoline<>(SB) TEXT libc_madvise_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_madvise(SB) + GLOBL ·libc_madvise_trampoline_addr(SB), RODATA, $8 DATA ·libc_madvise_trampoline_addr(SB)/8, $libc_madvise_trampoline<>(SB) TEXT libc_mlock_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mlock(SB) + GLOBL ·libc_mlock_trampoline_addr(SB), RODATA, $8 DATA ·libc_mlock_trampoline_addr(SB)/8, $libc_mlock_trampoline<>(SB) TEXT libc_mlockall_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mlockall(SB) + GLOBL ·libc_mlockall_trampoline_addr(SB), RODATA, $8 DATA ·libc_mlockall_trampoline_addr(SB)/8, $libc_mlockall_trampoline<>(SB) TEXT libc_mprotect_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mprotect(SB) + GLOBL ·libc_mprotect_trampoline_addr(SB), RODATA, $8 DATA ·libc_mprotect_trampoline_addr(SB)/8, $libc_mprotect_trampoline<>(SB) TEXT libc_msync_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_msync(SB) + GLOBL ·libc_msync_trampoline_addr(SB), RODATA, $8 DATA ·libc_msync_trampoline_addr(SB)/8, $libc_msync_trampoline<>(SB) TEXT libc_munlock_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_munlock(SB) + GLOBL ·libc_munlock_trampoline_addr(SB), RODATA, $8 DATA ·libc_munlock_trampoline_addr(SB)/8, $libc_munlock_trampoline<>(SB) TEXT libc_munlockall_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_munlockall(SB) + GLOBL ·libc_munlockall_trampoline_addr(SB), RODATA, $8 DATA ·libc_munlockall_trampoline_addr(SB)/8, $libc_munlockall_trampoline<>(SB) TEXT libc_closedir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_closedir(SB) + GLOBL ·libc_closedir_trampoline_addr(SB), RODATA, $8 DATA ·libc_closedir_trampoline_addr(SB)/8, $libc_closedir_trampoline<>(SB) TEXT libc_readdir_r_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_readdir_r(SB) + GLOBL ·libc_readdir_r_trampoline_addr(SB), RODATA, $8 DATA ·libc_readdir_r_trampoline_addr(SB)/8, $libc_readdir_r_trampoline<>(SB) TEXT libc_pipe_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_pipe(SB) + GLOBL ·libc_pipe_trampoline_addr(SB), RODATA, $8 DATA ·libc_pipe_trampoline_addr(SB)/8, $libc_pipe_trampoline<>(SB) TEXT libc_getxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getxattr(SB) + GLOBL ·libc_getxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_getxattr_trampoline_addr(SB)/8, $libc_getxattr_trampoline<>(SB) TEXT libc_fgetxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fgetxattr(SB) + GLOBL ·libc_fgetxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_fgetxattr_trampoline_addr(SB)/8, $libc_fgetxattr_trampoline<>(SB) TEXT libc_setxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setxattr(SB) + GLOBL ·libc_setxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_setxattr_trampoline_addr(SB)/8, $libc_setxattr_trampoline<>(SB) TEXT libc_fsetxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fsetxattr(SB) + GLOBL ·libc_fsetxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_fsetxattr_trampoline_addr(SB)/8, $libc_fsetxattr_trampoline<>(SB) TEXT libc_removexattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_removexattr(SB) + GLOBL ·libc_removexattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_removexattr_trampoline_addr(SB)/8, $libc_removexattr_trampoline<>(SB) TEXT libc_fremovexattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fremovexattr(SB) + GLOBL ·libc_fremovexattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_fremovexattr_trampoline_addr(SB)/8, $libc_fremovexattr_trampoline<>(SB) TEXT libc_listxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_listxattr(SB) + GLOBL ·libc_listxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_listxattr_trampoline_addr(SB)/8, $libc_listxattr_trampoline<>(SB) TEXT libc_flistxattr_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_flistxattr(SB) + GLOBL ·libc_flistxattr_trampoline_addr(SB), RODATA, $8 DATA ·libc_flistxattr_trampoline_addr(SB)/8, $libc_flistxattr_trampoline<>(SB) TEXT libc_utimensat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_utimensat(SB) + GLOBL ·libc_utimensat_trampoline_addr(SB), RODATA, $8 DATA ·libc_utimensat_trampoline_addr(SB)/8, $libc_utimensat_trampoline<>(SB) TEXT libc_fcntl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fcntl(SB) + GLOBL ·libc_fcntl_trampoline_addr(SB), RODATA, $8 DATA ·libc_fcntl_trampoline_addr(SB)/8, $libc_fcntl_trampoline<>(SB) TEXT libc_kill_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_kill(SB) + GLOBL ·libc_kill_trampoline_addr(SB), RODATA, $8 DATA ·libc_kill_trampoline_addr(SB)/8, $libc_kill_trampoline<>(SB) TEXT libc_ioctl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ioctl(SB) + GLOBL ·libc_ioctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_ioctl_trampoline_addr(SB)/8, $libc_ioctl_trampoline<>(SB) TEXT libc_sysctl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sysctl(SB) + GLOBL ·libc_sysctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_sysctl_trampoline_addr(SB)/8, $libc_sysctl_trampoline<>(SB) TEXT libc_sendfile_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sendfile(SB) + GLOBL ·libc_sendfile_trampoline_addr(SB), RODATA, $8 DATA ·libc_sendfile_trampoline_addr(SB)/8, $libc_sendfile_trampoline<>(SB) TEXT libc_shmat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_shmat(SB) + GLOBL ·libc_shmat_trampoline_addr(SB), RODATA, $8 DATA ·libc_shmat_trampoline_addr(SB)/8, $libc_shmat_trampoline<>(SB) TEXT libc_shmctl_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_shmctl(SB) + GLOBL ·libc_shmctl_trampoline_addr(SB), RODATA, $8 DATA ·libc_shmctl_trampoline_addr(SB)/8, $libc_shmctl_trampoline<>(SB) TEXT libc_shmdt_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_shmdt(SB) + GLOBL ·libc_shmdt_trampoline_addr(SB), RODATA, $8 DATA ·libc_shmdt_trampoline_addr(SB)/8, $libc_shmdt_trampoline<>(SB) TEXT libc_shmget_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_shmget(SB) + GLOBL ·libc_shmget_trampoline_addr(SB), RODATA, $8 DATA ·libc_shmget_trampoline_addr(SB)/8, $libc_shmget_trampoline<>(SB) TEXT libc_access_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_access(SB) + GLOBL ·libc_access_trampoline_addr(SB), RODATA, $8 DATA ·libc_access_trampoline_addr(SB)/8, $libc_access_trampoline<>(SB) TEXT libc_adjtime_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_adjtime(SB) + GLOBL ·libc_adjtime_trampoline_addr(SB), RODATA, $8 DATA ·libc_adjtime_trampoline_addr(SB)/8, $libc_adjtime_trampoline<>(SB) TEXT libc_chdir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_chdir(SB) + GLOBL ·libc_chdir_trampoline_addr(SB), RODATA, $8 DATA ·libc_chdir_trampoline_addr(SB)/8, $libc_chdir_trampoline<>(SB) TEXT libc_chflags_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_chflags(SB) + GLOBL ·libc_chflags_trampoline_addr(SB), RODATA, $8 DATA ·libc_chflags_trampoline_addr(SB)/8, $libc_chflags_trampoline<>(SB) TEXT libc_chmod_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_chmod(SB) + GLOBL ·libc_chmod_trampoline_addr(SB), RODATA, $8 DATA ·libc_chmod_trampoline_addr(SB)/8, $libc_chmod_trampoline<>(SB) TEXT libc_chown_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_chown(SB) + GLOBL ·libc_chown_trampoline_addr(SB), RODATA, $8 DATA ·libc_chown_trampoline_addr(SB)/8, $libc_chown_trampoline<>(SB) TEXT libc_chroot_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_chroot(SB) + GLOBL ·libc_chroot_trampoline_addr(SB), RODATA, $8 DATA ·libc_chroot_trampoline_addr(SB)/8, $libc_chroot_trampoline<>(SB) TEXT libc_clock_gettime_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_clock_gettime(SB) + GLOBL ·libc_clock_gettime_trampoline_addr(SB), RODATA, $8 DATA ·libc_clock_gettime_trampoline_addr(SB)/8, $libc_clock_gettime_trampoline<>(SB) TEXT libc_close_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_close(SB) + GLOBL ·libc_close_trampoline_addr(SB), RODATA, $8 DATA ·libc_close_trampoline_addr(SB)/8, $libc_close_trampoline<>(SB) TEXT libc_clonefile_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_clonefile(SB) + GLOBL ·libc_clonefile_trampoline_addr(SB), RODATA, $8 DATA ·libc_clonefile_trampoline_addr(SB)/8, $libc_clonefile_trampoline<>(SB) TEXT libc_clonefileat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_clonefileat(SB) + GLOBL ·libc_clonefileat_trampoline_addr(SB), RODATA, $8 DATA ·libc_clonefileat_trampoline_addr(SB)/8, $libc_clonefileat_trampoline<>(SB) TEXT libc_dup_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_dup(SB) + GLOBL ·libc_dup_trampoline_addr(SB), RODATA, $8 DATA ·libc_dup_trampoline_addr(SB)/8, $libc_dup_trampoline<>(SB) TEXT libc_dup2_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_dup2(SB) + GLOBL ·libc_dup2_trampoline_addr(SB), RODATA, $8 DATA ·libc_dup2_trampoline_addr(SB)/8, $libc_dup2_trampoline<>(SB) TEXT libc_exchangedata_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_exchangedata(SB) + GLOBL ·libc_exchangedata_trampoline_addr(SB), RODATA, $8 DATA ·libc_exchangedata_trampoline_addr(SB)/8, $libc_exchangedata_trampoline<>(SB) TEXT libc_exit_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_exit(SB) + GLOBL ·libc_exit_trampoline_addr(SB), RODATA, $8 DATA ·libc_exit_trampoline_addr(SB)/8, $libc_exit_trampoline<>(SB) TEXT libc_faccessat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_faccessat(SB) + GLOBL ·libc_faccessat_trampoline_addr(SB), RODATA, $8 DATA ·libc_faccessat_trampoline_addr(SB)/8, $libc_faccessat_trampoline<>(SB) TEXT libc_fchdir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchdir(SB) + GLOBL ·libc_fchdir_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchdir_trampoline_addr(SB)/8, $libc_fchdir_trampoline<>(SB) TEXT libc_fchflags_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchflags(SB) + GLOBL ·libc_fchflags_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchflags_trampoline_addr(SB)/8, $libc_fchflags_trampoline<>(SB) TEXT libc_fchmod_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchmod(SB) + GLOBL ·libc_fchmod_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchmod_trampoline_addr(SB)/8, $libc_fchmod_trampoline<>(SB) TEXT libc_fchmodat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchmodat(SB) + GLOBL ·libc_fchmodat_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchmodat_trampoline_addr(SB)/8, $libc_fchmodat_trampoline<>(SB) TEXT libc_fchown_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchown(SB) + GLOBL ·libc_fchown_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchown_trampoline_addr(SB)/8, $libc_fchown_trampoline<>(SB) TEXT libc_fchownat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fchownat(SB) + GLOBL ·libc_fchownat_trampoline_addr(SB), RODATA, $8 DATA ·libc_fchownat_trampoline_addr(SB)/8, $libc_fchownat_trampoline<>(SB) TEXT libc_fclonefileat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fclonefileat(SB) + GLOBL ·libc_fclonefileat_trampoline_addr(SB), RODATA, $8 DATA ·libc_fclonefileat_trampoline_addr(SB)/8, $libc_fclonefileat_trampoline<>(SB) TEXT libc_flock_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_flock(SB) + GLOBL ·libc_flock_trampoline_addr(SB), RODATA, $8 DATA ·libc_flock_trampoline_addr(SB)/8, $libc_flock_trampoline<>(SB) TEXT libc_fpathconf_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fpathconf(SB) + GLOBL ·libc_fpathconf_trampoline_addr(SB), RODATA, $8 DATA ·libc_fpathconf_trampoline_addr(SB)/8, $libc_fpathconf_trampoline<>(SB) TEXT libc_fsync_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fsync(SB) + GLOBL ·libc_fsync_trampoline_addr(SB), RODATA, $8 DATA ·libc_fsync_trampoline_addr(SB)/8, $libc_fsync_trampoline<>(SB) TEXT libc_ftruncate_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ftruncate(SB) + GLOBL ·libc_ftruncate_trampoline_addr(SB), RODATA, $8 DATA ·libc_ftruncate_trampoline_addr(SB)/8, $libc_ftruncate_trampoline<>(SB) TEXT libc_getcwd_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getcwd(SB) + GLOBL ·libc_getcwd_trampoline_addr(SB), RODATA, $8 DATA ·libc_getcwd_trampoline_addr(SB)/8, $libc_getcwd_trampoline<>(SB) TEXT libc_getdtablesize_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getdtablesize(SB) + GLOBL ·libc_getdtablesize_trampoline_addr(SB), RODATA, $8 DATA ·libc_getdtablesize_trampoline_addr(SB)/8, $libc_getdtablesize_trampoline<>(SB) TEXT libc_getegid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getegid(SB) + GLOBL ·libc_getegid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getegid_trampoline_addr(SB)/8, $libc_getegid_trampoline<>(SB) TEXT libc_geteuid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_geteuid(SB) + GLOBL ·libc_geteuid_trampoline_addr(SB), RODATA, $8 DATA ·libc_geteuid_trampoline_addr(SB)/8, $libc_geteuid_trampoline<>(SB) TEXT libc_getgid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getgid(SB) + GLOBL ·libc_getgid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getgid_trampoline_addr(SB)/8, $libc_getgid_trampoline<>(SB) TEXT libc_getpgid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getpgid(SB) + GLOBL ·libc_getpgid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getpgid_trampoline_addr(SB)/8, $libc_getpgid_trampoline<>(SB) TEXT libc_getpgrp_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getpgrp(SB) + GLOBL ·libc_getpgrp_trampoline_addr(SB), RODATA, $8 DATA ·libc_getpgrp_trampoline_addr(SB)/8, $libc_getpgrp_trampoline<>(SB) TEXT libc_getpid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getpid(SB) + GLOBL ·libc_getpid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getpid_trampoline_addr(SB)/8, $libc_getpid_trampoline<>(SB) TEXT libc_getppid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getppid(SB) + GLOBL ·libc_getppid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getppid_trampoline_addr(SB)/8, $libc_getppid_trampoline<>(SB) TEXT libc_getpriority_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getpriority(SB) + GLOBL ·libc_getpriority_trampoline_addr(SB), RODATA, $8 DATA ·libc_getpriority_trampoline_addr(SB)/8, $libc_getpriority_trampoline<>(SB) TEXT libc_getrlimit_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getrlimit(SB) + GLOBL ·libc_getrlimit_trampoline_addr(SB), RODATA, $8 DATA ·libc_getrlimit_trampoline_addr(SB)/8, $libc_getrlimit_trampoline<>(SB) TEXT libc_getrusage_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getrusage(SB) + GLOBL ·libc_getrusage_trampoline_addr(SB), RODATA, $8 DATA ·libc_getrusage_trampoline_addr(SB)/8, $libc_getrusage_trampoline<>(SB) TEXT libc_getsid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getsid(SB) + GLOBL ·libc_getsid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getsid_trampoline_addr(SB)/8, $libc_getsid_trampoline<>(SB) TEXT libc_gettimeofday_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_gettimeofday(SB) + GLOBL ·libc_gettimeofday_trampoline_addr(SB), RODATA, $8 DATA ·libc_gettimeofday_trampoline_addr(SB)/8, $libc_gettimeofday_trampoline<>(SB) TEXT libc_getuid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getuid(SB) + GLOBL ·libc_getuid_trampoline_addr(SB), RODATA, $8 DATA ·libc_getuid_trampoline_addr(SB)/8, $libc_getuid_trampoline<>(SB) TEXT libc_issetugid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_issetugid(SB) + GLOBL ·libc_issetugid_trampoline_addr(SB), RODATA, $8 DATA ·libc_issetugid_trampoline_addr(SB)/8, $libc_issetugid_trampoline<>(SB) TEXT libc_kqueue_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_kqueue(SB) + GLOBL ·libc_kqueue_trampoline_addr(SB), RODATA, $8 DATA ·libc_kqueue_trampoline_addr(SB)/8, $libc_kqueue_trampoline<>(SB) TEXT libc_lchown_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_lchown(SB) + GLOBL ·libc_lchown_trampoline_addr(SB), RODATA, $8 DATA ·libc_lchown_trampoline_addr(SB)/8, $libc_lchown_trampoline<>(SB) TEXT libc_link_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_link(SB) + GLOBL ·libc_link_trampoline_addr(SB), RODATA, $8 DATA ·libc_link_trampoline_addr(SB)/8, $libc_link_trampoline<>(SB) TEXT libc_linkat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_linkat(SB) + GLOBL ·libc_linkat_trampoline_addr(SB), RODATA, $8 DATA ·libc_linkat_trampoline_addr(SB)/8, $libc_linkat_trampoline<>(SB) TEXT libc_listen_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_listen(SB) + GLOBL ·libc_listen_trampoline_addr(SB), RODATA, $8 DATA ·libc_listen_trampoline_addr(SB)/8, $libc_listen_trampoline<>(SB) TEXT libc_mkdir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mkdir(SB) + GLOBL ·libc_mkdir_trampoline_addr(SB), RODATA, $8 DATA ·libc_mkdir_trampoline_addr(SB)/8, $libc_mkdir_trampoline<>(SB) TEXT libc_mkdirat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mkdirat(SB) + GLOBL ·libc_mkdirat_trampoline_addr(SB), RODATA, $8 DATA ·libc_mkdirat_trampoline_addr(SB)/8, $libc_mkdirat_trampoline<>(SB) TEXT libc_mkfifo_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mkfifo(SB) + GLOBL ·libc_mkfifo_trampoline_addr(SB), RODATA, $8 DATA ·libc_mkfifo_trampoline_addr(SB)/8, $libc_mkfifo_trampoline<>(SB) TEXT libc_mknod_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mknod(SB) + GLOBL ·libc_mknod_trampoline_addr(SB), RODATA, $8 DATA ·libc_mknod_trampoline_addr(SB)/8, $libc_mknod_trampoline<>(SB) TEXT libc_mount_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mount(SB) + GLOBL ·libc_mount_trampoline_addr(SB), RODATA, $8 DATA ·libc_mount_trampoline_addr(SB)/8, $libc_mount_trampoline<>(SB) TEXT libc_open_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_open(SB) + GLOBL ·libc_open_trampoline_addr(SB), RODATA, $8 DATA ·libc_open_trampoline_addr(SB)/8, $libc_open_trampoline<>(SB) TEXT libc_openat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_openat(SB) + GLOBL ·libc_openat_trampoline_addr(SB), RODATA, $8 DATA ·libc_openat_trampoline_addr(SB)/8, $libc_openat_trampoline<>(SB) TEXT libc_pathconf_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_pathconf(SB) + GLOBL ·libc_pathconf_trampoline_addr(SB), RODATA, $8 DATA ·libc_pathconf_trampoline_addr(SB)/8, $libc_pathconf_trampoline<>(SB) TEXT libc_pread_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_pread(SB) + GLOBL ·libc_pread_trampoline_addr(SB), RODATA, $8 DATA ·libc_pread_trampoline_addr(SB)/8, $libc_pread_trampoline<>(SB) TEXT libc_pwrite_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_pwrite(SB) + GLOBL ·libc_pwrite_trampoline_addr(SB), RODATA, $8 DATA ·libc_pwrite_trampoline_addr(SB)/8, $libc_pwrite_trampoline<>(SB) TEXT libc_read_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_read(SB) + GLOBL ·libc_read_trampoline_addr(SB), RODATA, $8 DATA ·libc_read_trampoline_addr(SB)/8, $libc_read_trampoline<>(SB) TEXT libc_readlink_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_readlink(SB) + GLOBL ·libc_readlink_trampoline_addr(SB), RODATA, $8 DATA ·libc_readlink_trampoline_addr(SB)/8, $libc_readlink_trampoline<>(SB) TEXT libc_readlinkat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_readlinkat(SB) + GLOBL ·libc_readlinkat_trampoline_addr(SB), RODATA, $8 DATA ·libc_readlinkat_trampoline_addr(SB)/8, $libc_readlinkat_trampoline<>(SB) TEXT libc_rename_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_rename(SB) + GLOBL ·libc_rename_trampoline_addr(SB), RODATA, $8 DATA ·libc_rename_trampoline_addr(SB)/8, $libc_rename_trampoline<>(SB) TEXT libc_renameat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_renameat(SB) + GLOBL ·libc_renameat_trampoline_addr(SB), RODATA, $8 DATA ·libc_renameat_trampoline_addr(SB)/8, $libc_renameat_trampoline<>(SB) TEXT libc_revoke_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_revoke(SB) + GLOBL ·libc_revoke_trampoline_addr(SB), RODATA, $8 DATA ·libc_revoke_trampoline_addr(SB)/8, $libc_revoke_trampoline<>(SB) TEXT libc_rmdir_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_rmdir(SB) + GLOBL ·libc_rmdir_trampoline_addr(SB), RODATA, $8 DATA ·libc_rmdir_trampoline_addr(SB)/8, $libc_rmdir_trampoline<>(SB) TEXT libc_lseek_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_lseek(SB) + GLOBL ·libc_lseek_trampoline_addr(SB), RODATA, $8 DATA ·libc_lseek_trampoline_addr(SB)/8, $libc_lseek_trampoline<>(SB) TEXT libc_select_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_select(SB) + GLOBL ·libc_select_trampoline_addr(SB), RODATA, $8 DATA ·libc_select_trampoline_addr(SB)/8, $libc_select_trampoline<>(SB) @@ -595,160 +712,192 @@ DATA ·libc_setattrlist_trampoline_addr(SB)/8, $libc_setattrlist_trampoline<>(SB TEXT libc_setegid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setegid(SB) + GLOBL ·libc_setegid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setegid_trampoline_addr(SB)/8, $libc_setegid_trampoline<>(SB) TEXT libc_seteuid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_seteuid(SB) + GLOBL ·libc_seteuid_trampoline_addr(SB), RODATA, $8 DATA ·libc_seteuid_trampoline_addr(SB)/8, $libc_seteuid_trampoline<>(SB) TEXT libc_setgid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setgid(SB) + GLOBL ·libc_setgid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setgid_trampoline_addr(SB)/8, $libc_setgid_trampoline<>(SB) TEXT libc_setlogin_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setlogin(SB) + GLOBL ·libc_setlogin_trampoline_addr(SB), RODATA, $8 DATA ·libc_setlogin_trampoline_addr(SB)/8, $libc_setlogin_trampoline<>(SB) TEXT libc_setpgid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setpgid(SB) + GLOBL ·libc_setpgid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setpgid_trampoline_addr(SB)/8, $libc_setpgid_trampoline<>(SB) TEXT libc_setpriority_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setpriority(SB) + GLOBL ·libc_setpriority_trampoline_addr(SB), RODATA, $8 DATA ·libc_setpriority_trampoline_addr(SB)/8, $libc_setpriority_trampoline<>(SB) TEXT libc_setprivexec_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setprivexec(SB) + GLOBL ·libc_setprivexec_trampoline_addr(SB), RODATA, $8 DATA ·libc_setprivexec_trampoline_addr(SB)/8, $libc_setprivexec_trampoline<>(SB) TEXT libc_setregid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setregid(SB) + GLOBL ·libc_setregid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setregid_trampoline_addr(SB)/8, $libc_setregid_trampoline<>(SB) TEXT libc_setreuid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setreuid(SB) + GLOBL ·libc_setreuid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setreuid_trampoline_addr(SB)/8, $libc_setreuid_trampoline<>(SB) TEXT libc_setsid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setsid(SB) + GLOBL ·libc_setsid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setsid_trampoline_addr(SB)/8, $libc_setsid_trampoline<>(SB) TEXT libc_settimeofday_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_settimeofday(SB) + GLOBL ·libc_settimeofday_trampoline_addr(SB), RODATA, $8 DATA ·libc_settimeofday_trampoline_addr(SB)/8, $libc_settimeofday_trampoline<>(SB) TEXT libc_setuid_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_setuid(SB) + GLOBL ·libc_setuid_trampoline_addr(SB), RODATA, $8 DATA ·libc_setuid_trampoline_addr(SB)/8, $libc_setuid_trampoline<>(SB) TEXT libc_symlink_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_symlink(SB) + GLOBL ·libc_symlink_trampoline_addr(SB), RODATA, $8 DATA ·libc_symlink_trampoline_addr(SB)/8, $libc_symlink_trampoline<>(SB) TEXT libc_symlinkat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_symlinkat(SB) + GLOBL ·libc_symlinkat_trampoline_addr(SB), RODATA, $8 DATA ·libc_symlinkat_trampoline_addr(SB)/8, $libc_symlinkat_trampoline<>(SB) TEXT libc_sync_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_sync(SB) + GLOBL ·libc_sync_trampoline_addr(SB), RODATA, $8 DATA ·libc_sync_trampoline_addr(SB)/8, $libc_sync_trampoline<>(SB) TEXT libc_truncate_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_truncate(SB) + GLOBL ·libc_truncate_trampoline_addr(SB), RODATA, $8 DATA ·libc_truncate_trampoline_addr(SB)/8, $libc_truncate_trampoline<>(SB) TEXT libc_umask_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_umask(SB) + GLOBL ·libc_umask_trampoline_addr(SB), RODATA, $8 DATA ·libc_umask_trampoline_addr(SB)/8, $libc_umask_trampoline<>(SB) TEXT libc_undelete_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_undelete(SB) + GLOBL ·libc_undelete_trampoline_addr(SB), RODATA, $8 DATA ·libc_undelete_trampoline_addr(SB)/8, $libc_undelete_trampoline<>(SB) TEXT libc_unlink_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_unlink(SB) + GLOBL ·libc_unlink_trampoline_addr(SB), RODATA, $8 DATA ·libc_unlink_trampoline_addr(SB)/8, $libc_unlink_trampoline<>(SB) TEXT libc_unlinkat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_unlinkat(SB) + GLOBL ·libc_unlinkat_trampoline_addr(SB), RODATA, $8 DATA ·libc_unlinkat_trampoline_addr(SB)/8, $libc_unlinkat_trampoline<>(SB) TEXT libc_unmount_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_unmount(SB) + GLOBL ·libc_unmount_trampoline_addr(SB), RODATA, $8 DATA ·libc_unmount_trampoline_addr(SB)/8, $libc_unmount_trampoline<>(SB) TEXT libc_write_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_write(SB) + GLOBL ·libc_write_trampoline_addr(SB), RODATA, $8 DATA ·libc_write_trampoline_addr(SB)/8, $libc_write_trampoline<>(SB) TEXT libc_mmap_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_mmap(SB) + GLOBL ·libc_mmap_trampoline_addr(SB), RODATA, $8 DATA ·libc_mmap_trampoline_addr(SB)/8, $libc_mmap_trampoline<>(SB) TEXT libc_munmap_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_munmap(SB) + GLOBL ·libc_munmap_trampoline_addr(SB), RODATA, $8 DATA ·libc_munmap_trampoline_addr(SB)/8, $libc_munmap_trampoline<>(SB) TEXT libc_fstat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fstat(SB) + GLOBL ·libc_fstat_trampoline_addr(SB), RODATA, $8 DATA ·libc_fstat_trampoline_addr(SB)/8, $libc_fstat_trampoline<>(SB) TEXT libc_fstatat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fstatat(SB) + GLOBL ·libc_fstatat_trampoline_addr(SB), RODATA, $8 DATA ·libc_fstatat_trampoline_addr(SB)/8, $libc_fstatat_trampoline<>(SB) TEXT libc_fstatfs_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_fstatfs(SB) + GLOBL ·libc_fstatfs_trampoline_addr(SB), RODATA, $8 DATA ·libc_fstatfs_trampoline_addr(SB)/8, $libc_fstatfs_trampoline<>(SB) TEXT libc_getfsstat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_getfsstat(SB) + GLOBL ·libc_getfsstat_trampoline_addr(SB), RODATA, $8 DATA ·libc_getfsstat_trampoline_addr(SB)/8, $libc_getfsstat_trampoline<>(SB) TEXT libc_lstat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_lstat(SB) + GLOBL ·libc_lstat_trampoline_addr(SB), RODATA, $8 DATA ·libc_lstat_trampoline_addr(SB)/8, $libc_lstat_trampoline<>(SB) TEXT libc_ptrace_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_ptrace(SB) + GLOBL ·libc_ptrace_trampoline_addr(SB), RODATA, $8 DATA ·libc_ptrace_trampoline_addr(SB)/8, $libc_ptrace_trampoline<>(SB) TEXT libc_stat_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_stat(SB) + GLOBL ·libc_stat_trampoline_addr(SB), RODATA, $8 DATA ·libc_stat_trampoline_addr(SB)/8, $libc_stat_trampoline<>(SB) TEXT libc_statfs_trampoline<>(SB),NOSPLIT,$0-0 JMP libc_statfs(SB) + GLOBL ·libc_statfs_trampoline_addr(SB), RODATA, $8 DATA ·libc_statfs_trampoline_addr(SB)/8, $libc_statfs_trampoline<>(SB) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go index 0c67df64a..0eabac7ad 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go @@ -1642,6 +1642,28 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) nfd = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go index e6e05d145..ee313eb00 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go @@ -1862,6 +1862,28 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) nfd = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go index 7508accac..4c986e448 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go @@ -1862,6 +1862,28 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) nfd = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go index 7b56aead4..555216944 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go @@ -1862,6 +1862,28 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) nfd = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go index cc623dcaa..67a226fbf 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm64.go @@ -1862,6 +1862,28 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) nfd = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go index 581849197..f0b9ddaaa 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_riscv64.go @@ -1862,6 +1862,28 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func accept4(fd int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (nfd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) nfd = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go index 6be25cd19..b57c7050d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_illumos_amd64.go @@ -40,7 +40,7 @@ func readv(fd int, iovs []Iovec) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procreadv)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -55,7 +55,7 @@ func preadv(fd int, iovs []Iovec, off int64) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpreadv)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), uintptr(off), 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -70,7 +70,7 @@ func writev(fd int, iovs []Iovec) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwritev)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -85,7 +85,7 @@ func pwritev(fd int, iovs []Iovec, off int64) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpwritev)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(iovs)), uintptr(off), 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -96,7 +96,7 @@ func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procaccept4)), 4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux.go b/vendor/golang.org/x/sys/unix/zsyscall_linux.go index 1ff3aec74..a07321bed 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux.go @@ -1734,6 +1734,28 @@ func exitThread(code int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, p *byte, np int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, p *byte, np int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func readv(fd int, iovs []Iovec) (n int, err error) { var _p0 unsafe.Pointer if len(iovs) > 0 { @@ -2175,23 +2197,3 @@ func getresgid(rgid *_C_int, egid *_C_int, sgid *_C_int) { RawSyscallNoError(SYS_GETRESGID, uintptr(unsafe.Pointer(rgid)), uintptr(unsafe.Pointer(egid)), uintptr(unsafe.Pointer(sgid))) return } - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func schedSetattr(pid int, attr *SchedAttr, flags uint) (err error) { - _, _, e1 := Syscall(SYS_SCHED_SETATTR, uintptr(pid), uintptr(unsafe.Pointer(attr)), uintptr(flags)) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - -func schedGetattr(pid int, attr *SchedAttr, size uint, flags uint) (err error) { - _, _, e1 := Syscall6(SYS_SCHED_GETATTR, uintptr(pid), uintptr(unsafe.Pointer(attr)), uintptr(size), uintptr(flags), 0, 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go index 2df3c5bac..35f499b32 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go @@ -1824,6 +1824,28 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go index a60556bab..3cda65b0d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go @@ -1824,6 +1824,28 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go index 9f788917a..1e1fea902 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go @@ -1824,6 +1824,28 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go index 82a4cb2dc..3b77da110 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm64.go @@ -1824,6 +1824,28 @@ func munmap(addr uintptr, length uintptr) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go index 66b3b6456..9ab9abf72 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go @@ -549,12 +549,6 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { return } -var libc_ioctl_trampoline_addr uintptr - -//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -563,6 +557,10 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { return } +var libc_ioctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { @@ -2213,6 +2211,28 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go index c5c4cc112..915761eab 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go @@ -2213,6 +2213,28 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go index 93bfbb328..8e87fdf15 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go @@ -549,12 +549,6 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { return } -var libc_ioctl_trampoline_addr uintptr - -//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -563,6 +557,10 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { return } +var libc_ioctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { @@ -2213,6 +2211,28 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go index a107b8fda..12a7a2160 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm64.go @@ -549,12 +549,6 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { return } -var libc_ioctl_trampoline_addr uintptr - -//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -563,6 +557,10 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { return } +var libc_ioctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { @@ -2213,6 +2211,28 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go index c427de509..b19e8aa03 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_mips64.go @@ -549,12 +549,6 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { return } -var libc_ioctl_trampoline_addr uintptr - -//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -563,6 +557,10 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { return } +var libc_ioctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { @@ -2213,6 +2211,28 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go index 60c1a99ae..fb99594c9 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_ppc64.go @@ -549,12 +549,6 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { return } -var libc_ioctl_trampoline_addr uintptr - -//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -563,6 +557,10 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { return } +var libc_ioctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { @@ -2213,6 +2211,28 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go index 52eba360f..32cbbbc52 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_riscv64.go @@ -549,12 +549,6 @@ func ioctl(fd int, req uint, arg uintptr) (err error) { return } -var libc_ioctl_trampoline_addr uintptr - -//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { _, _, e1 := syscall_syscall(libc_ioctl_trampoline_addr, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -563,6 +557,10 @@ func ioctlPtr(fd int, req uint, arg unsafe.Pointer) (err error) { return } +var libc_ioctl_trampoline_addr uintptr + +//go:cgo_import_dynamic libc_ioctl ioctl "libc.so" + // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) { @@ -2213,6 +2211,28 @@ var libc_munmap_trampoline_addr uintptr // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_read_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func writelen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(libc_write_trampoline_addr, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go index b40189464..609d1c598 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go @@ -436,7 +436,7 @@ func pipe(p *[2]_C_int) (n int, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procpipe)), 1, uintptr(unsafe.Pointer(p)), 0, 0, 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -446,7 +446,7 @@ func pipe(p *[2]_C_int) (n int, err error) { func pipe2(p *[2]_C_int, flags int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procpipe2)), 2, uintptr(unsafe.Pointer(p)), uintptr(flags), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -456,7 +456,7 @@ func pipe2(p *[2]_C_int, flags int) (err error) { func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgetsockname)), 3, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -471,7 +471,7 @@ func Getcwd(buf []byte) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetcwd)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0, 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -482,7 +482,7 @@ func getgroups(ngid int, gid *_Gid_t) (n int, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procgetgroups)), 2, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0, 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -492,7 +492,7 @@ func getgroups(ngid int, gid *_Gid_t) (n int, err error) { func setgroups(ngid int, gid *_Gid_t) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procsetgroups)), 2, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -503,7 +503,7 @@ func wait4(pid int32, statusp *_C_int, options int, rusage *Rusage) (wpid int32, r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwait4)), 4, uintptr(pid), uintptr(unsafe.Pointer(statusp)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int32(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -518,7 +518,7 @@ func gethostname(buf []byte) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgethostname)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), 0, 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -533,7 +533,7 @@ func utimes(path string, times *[2]Timeval) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procutimes)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -548,7 +548,7 @@ func utimensat(fd int, path string, times *[2]Timespec, flag int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procutimensat)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flag), 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -559,7 +559,7 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0) val = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -569,7 +569,7 @@ func fcntl(fd int, cmd int, arg int) (val int, err error) { func futimesat(fildes int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfutimesat)), 3, uintptr(fildes), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times)), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -580,7 +580,7 @@ func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procaccept)), 3, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) fd = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -591,7 +591,7 @@ func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_recvmsg)), 3, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -602,7 +602,7 @@ func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_sendmsg)), 3, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags), 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -612,7 +612,7 @@ func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { func acct(path *byte) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procacct)), 1, uintptr(unsafe.Pointer(path)), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -647,7 +647,7 @@ func ioctlRet(fd int, req int, arg uintptr) (ret int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procioctl)), 3, uintptr(fd), uintptr(req), uintptr(arg), 0, 0, 0) ret = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -658,7 +658,7 @@ func ioctlPtrRet(fd int, req int, arg unsafe.Pointer) (ret int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procioctl)), 3, uintptr(fd), uintptr(req), uintptr(arg), 0, 0, 0) ret = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -669,7 +669,7 @@ func poll(fds *PollFd, nfds int, timeout int) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpoll)), 3, uintptr(unsafe.Pointer(fds)), uintptr(nfds), uintptr(timeout), 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -684,7 +684,7 @@ func Access(path string, mode uint32) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procAccess)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -694,7 +694,7 @@ func Access(path string, mode uint32) (err error) { func Adjtime(delta *Timeval, olddelta *Timeval) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procAdjtime)), 2, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -709,7 +709,7 @@ func Chdir(path string) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChdir)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -724,7 +724,7 @@ func Chmod(path string, mode uint32) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChmod)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -739,7 +739,7 @@ func Chown(path string, uid int, gid int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChown)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -754,7 +754,7 @@ func Chroot(path string) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procChroot)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -764,7 +764,7 @@ func Chroot(path string) (err error) { func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procClockGettime)), 2, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -774,7 +774,7 @@ func ClockGettime(clockid int32, time *Timespec) (err error) { func Close(fd int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procClose)), 1, uintptr(fd), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -790,7 +790,7 @@ func Creat(path string, mode uint32) (fd int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procCreat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) fd = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -801,7 +801,7 @@ func Dup(fd int) (nfd int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procDup)), 1, uintptr(fd), 0, 0, 0, 0, 0) nfd = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -811,7 +811,7 @@ func Dup(fd int) (nfd int, err error) { func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procDup2)), 2, uintptr(oldfd), uintptr(newfd), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -833,7 +833,7 @@ func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFaccessat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -843,7 +843,7 @@ func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { func Fchdir(fd int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchdir)), 1, uintptr(fd), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -853,7 +853,7 @@ func Fchdir(fd int) (err error) { func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchmod)), 2, uintptr(fd), uintptr(mode), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -868,7 +868,7 @@ func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchmodat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -878,7 +878,7 @@ func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchown)), 3, uintptr(fd), uintptr(uid), uintptr(gid), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -893,7 +893,7 @@ func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFchownat)), 5, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -903,7 +903,7 @@ func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { func Fdatasync(fd int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFdatasync)), 1, uintptr(fd), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -913,7 +913,7 @@ func Fdatasync(fd int) (err error) { func Flock(fd int, how int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFlock)), 2, uintptr(fd), uintptr(how), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -924,7 +924,7 @@ func Fpathconf(fd int, name int) (val int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFpathconf)), 2, uintptr(fd), uintptr(name), 0, 0, 0, 0) val = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -934,7 +934,7 @@ func Fpathconf(fd int, name int) (val int, err error) { func Fstat(fd int, stat *Stat_t) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstat)), 2, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -949,7 +949,7 @@ func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstatat)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -959,7 +959,7 @@ func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { func Fstatvfs(fd int, vfsstat *Statvfs_t) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstatvfs)), 2, uintptr(fd), uintptr(unsafe.Pointer(vfsstat)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -974,7 +974,7 @@ func Getdents(fd int, buf []byte, basep *uintptr) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetdents)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1001,7 +1001,7 @@ func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpgid)), 1, uintptr(pid), 0, 0, 0, 0, 0) pgid = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1012,7 +1012,7 @@ func Getpgrp() (pgid int, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetpgrp)), 0, 0, 0, 0, 0, 0, 0) pgid = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1047,7 +1047,7 @@ func Getpriority(which int, who int) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procGetpriority)), 2, uintptr(which), uintptr(who), 0, 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1057,7 +1057,7 @@ func Getpriority(which int, who int) (n int, err error) { func Getrlimit(which int, lim *Rlimit) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetrlimit)), 2, uintptr(which), uintptr(unsafe.Pointer(lim)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1067,7 +1067,7 @@ func Getrlimit(which int, lim *Rlimit) (err error) { func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetrusage)), 2, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1078,7 +1078,7 @@ func Getsid(pid int) (sid int, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGetsid)), 1, uintptr(pid), 0, 0, 0, 0, 0) sid = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1088,7 +1088,7 @@ func Getsid(pid int) (sid int, err error) { func Gettimeofday(tv *Timeval) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procGettimeofday)), 1, uintptr(unsafe.Pointer(tv)), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1106,7 +1106,7 @@ func Getuid() (uid int) { func Kill(pid int, signum syscall.Signal) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procKill)), 2, uintptr(pid), uintptr(signum), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1121,7 +1121,7 @@ func Lchown(path string, uid int, gid int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLchown)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1141,7 +1141,7 @@ func Link(path string, link string) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLink)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1151,7 +1151,7 @@ func Link(path string, link string) (err error) { func Listen(s int, backlog int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_llisten)), 2, uintptr(s), uintptr(backlog), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1166,7 +1166,7 @@ func Lstat(path string, stat *Stat_t) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procLstat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1180,7 +1180,7 @@ func Madvise(b []byte, advice int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMadvise)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(advice), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1195,7 +1195,7 @@ func Mkdir(path string, mode uint32) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkdir)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1210,7 +1210,7 @@ func Mkdirat(dirfd int, path string, mode uint32) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkdirat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1225,7 +1225,7 @@ func Mkfifo(path string, mode uint32) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkfifo)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1240,7 +1240,7 @@ func Mkfifoat(dirfd int, path string, mode uint32) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMkfifoat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1255,7 +1255,7 @@ func Mknod(path string, mode uint32, dev int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMknod)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1270,7 +1270,7 @@ func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMknodat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1284,7 +1284,7 @@ func Mlock(b []byte) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMlock)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1294,7 +1294,7 @@ func Mlock(b []byte) (err error) { func Mlockall(flags int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMlockall)), 1, uintptr(flags), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1308,7 +1308,7 @@ func Mprotect(b []byte, prot int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMprotect)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(prot), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1322,7 +1322,7 @@ func Msync(b []byte, flags int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMsync)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(flags), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1336,7 +1336,7 @@ func Munlock(b []byte) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMunlock)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1346,7 +1346,7 @@ func Munlock(b []byte) (err error) { func Munlockall() (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procMunlockall)), 0, 0, 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1356,7 +1356,7 @@ func Munlockall() (err error) { func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procNanosleep)), 2, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1372,7 +1372,7 @@ func Open(path string, mode int, perm uint32) (fd int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procOpen)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm), 0, 0, 0) fd = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1388,7 +1388,7 @@ func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procOpenat)), 4, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) fd = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1404,7 +1404,7 @@ func Pathconf(path string, name int) (val int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPathconf)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0, 0, 0, 0) val = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1414,7 +1414,7 @@ func Pathconf(path string, name int) (val int, err error) { func Pause() (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procPause)), 0, 0, 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1429,7 +1429,7 @@ func pread(fd int, p []byte, offset int64) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpread)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1444,7 +1444,7 @@ func pwrite(fd int, p []byte, offset int64) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procpwrite)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(offset), 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1459,7 +1459,7 @@ func read(fd int, p []byte) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procread)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1479,7 +1479,7 @@ func Readlink(path string, buf []byte) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procReadlink)), 3, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(len(buf)), 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1499,7 +1499,7 @@ func Rename(from string, to string) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRename)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1519,7 +1519,7 @@ func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err e } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRenameat)), 4, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1534,7 +1534,7 @@ func Rmdir(path string) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procRmdir)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1545,7 +1545,7 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proclseek)), 3, uintptr(fd), uintptr(offset), uintptr(whence), 0, 0, 0) newoffset = int64(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1556,7 +1556,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSelect)), 5, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1566,7 +1566,7 @@ func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err func Setegid(egid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetegid)), 1, uintptr(egid), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1576,7 +1576,7 @@ func Setegid(egid int) (err error) { func Seteuid(euid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSeteuid)), 1, uintptr(euid), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1586,7 +1586,7 @@ func Seteuid(euid int) (err error) { func Setgid(gid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetgid)), 1, uintptr(gid), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1600,7 +1600,7 @@ func Sethostname(p []byte) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSethostname)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1610,7 +1610,7 @@ func Sethostname(p []byte) (err error) { func Setpgid(pid int, pgid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetpgid)), 2, uintptr(pid), uintptr(pgid), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1620,7 +1620,7 @@ func Setpgid(pid int, pgid int) (err error) { func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSetpriority)), 3, uintptr(which), uintptr(who), uintptr(prio), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1630,7 +1630,7 @@ func Setpriority(which int, who int, prio int) (err error) { func Setregid(rgid int, egid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetregid)), 2, uintptr(rgid), uintptr(egid), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1640,7 +1640,7 @@ func Setregid(rgid int, egid int) (err error) { func Setreuid(ruid int, euid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetreuid)), 2, uintptr(ruid), uintptr(euid), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1651,7 +1651,7 @@ func Setsid() (pid int, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetsid)), 0, 0, 0, 0, 0, 0, 0) pid = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1661,7 +1661,7 @@ func Setsid() (pid int, err error) { func Setuid(uid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetuid)), 1, uintptr(uid), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1671,7 +1671,7 @@ func Setuid(uid int) (err error) { func Shutdown(s int, how int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procshutdown)), 2, uintptr(s), uintptr(how), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1686,7 +1686,7 @@ func Stat(path string, stat *Stat_t) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procStat)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1701,7 +1701,7 @@ func Statvfs(path string, vfsstat *Statvfs_t) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procStatvfs)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(vfsstat)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1721,7 +1721,7 @@ func Symlink(path string, link string) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSymlink)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1731,7 +1731,7 @@ func Symlink(path string, link string) (err error) { func Sync() (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSync)), 0, 0, 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1742,7 +1742,7 @@ func Sysconf(which int) (n int64, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSysconf)), 1, uintptr(which), 0, 0, 0, 0, 0) n = int64(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1753,7 +1753,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procTimes)), 1, uintptr(unsafe.Pointer(tms)), 0, 0, 0, 0, 0) ticks = uintptr(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1768,7 +1768,7 @@ func Truncate(path string, length int64) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procTruncate)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1778,7 +1778,7 @@ func Truncate(path string, length int64) (err error) { func Fsync(fd int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFsync)), 1, uintptr(fd), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1788,7 +1788,7 @@ func Fsync(fd int) (err error) { func Ftruncate(fd int, length int64) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFtruncate)), 2, uintptr(fd), uintptr(length), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1806,7 +1806,7 @@ func Umask(mask int) (oldmask int) { func Uname(buf *Utsname) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procUname)), 1, uintptr(unsafe.Pointer(buf)), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1821,7 +1821,7 @@ func Unmount(target string, flags int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procumount)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1836,7 +1836,7 @@ func Unlink(path string) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlink)), 1, uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1851,7 +1851,7 @@ func Unlinkat(dirfd int, path string, flags int) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlinkat)), 3, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1861,7 +1861,7 @@ func Unlinkat(dirfd int, path string, flags int) (err error) { func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUstat)), 2, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1876,7 +1876,7 @@ func Utime(path string, buf *Utimbuf) (err error) { } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUtime)), 2, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1886,7 +1886,7 @@ func Utime(path string, buf *Utimbuf) (err error) { func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_bind)), 3, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1896,7 +1896,7 @@ func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_connect)), 3, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1907,7 +1907,7 @@ func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) ( r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procmmap)), 6, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos)) ret = uintptr(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1917,7 +1917,7 @@ func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) ( func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procmunmap)), 2, uintptr(addr), uintptr(length), 0, 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1928,7 +1928,7 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsendfile)), 4, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1942,7 +1942,7 @@ func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) ( } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_sendto)), 6, uintptr(s), uintptr(unsafe.Pointer(_p0)), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1953,7 +1953,7 @@ func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_socket)), 3, uintptr(domain), uintptr(typ), uintptr(proto), 0, 0, 0) fd = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1963,7 +1963,7 @@ func socket(domain int, typ int, proto int) (fd int, err error) { func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&proc__xnet_socketpair)), 4, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1978,7 +1978,7 @@ func write(fd int, p []byte) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procwrite)), 3, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1988,7 +1988,7 @@ func write(fd int, p []byte) (n int, err error) { func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proc__xnet_getsockopt)), 5, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -1998,7 +1998,7 @@ func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procgetpeername)), 3, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), 0, 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -2008,7 +2008,7 @@ func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsetsockopt)), 5, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -2023,7 +2023,7 @@ func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Sockl r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procrecvfrom)), 6, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -2034,7 +2034,7 @@ func port_create() (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_create)), 0, 0, 0, 0, 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -2045,7 +2045,7 @@ func port_associate(port int, source int, object uintptr, events int, user *byte r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_associate)), 5, uintptr(port), uintptr(source), uintptr(object), uintptr(events), uintptr(unsafe.Pointer(user)), 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -2056,7 +2056,7 @@ func port_dissociate(port int, source int, object uintptr) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_dissociate)), 3, uintptr(port), uintptr(source), uintptr(object), 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -2067,7 +2067,7 @@ func port_get(port int, pe *portEvent, timeout *Timespec) (n int, err error) { r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_get)), 3, uintptr(port), uintptr(unsafe.Pointer(pe)), uintptr(unsafe.Pointer(timeout)), 0, 0, 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -2078,7 +2078,7 @@ func port_getn(port int, pe *portEvent, max uint32, nget *uint32, timeout *Times r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procport_getn)), 5, uintptr(port), uintptr(unsafe.Pointer(pe)), uintptr(max), uintptr(unsafe.Pointer(nget)), uintptr(unsafe.Pointer(timeout)), 0) n = int(r0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -2088,7 +2088,7 @@ func port_getn(port int, pe *portEvent, max uint32, nget *uint32, timeout *Times func putmsg(fd int, clptr *strbuf, dataptr *strbuf, flags int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procputmsg)), 4, uintptr(fd), uintptr(unsafe.Pointer(clptr)), uintptr(unsafe.Pointer(dataptr)), uintptr(flags), 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } @@ -2098,7 +2098,7 @@ func putmsg(fd int, clptr *strbuf, dataptr *strbuf, flags int) (err error) { func getmsg(fd int, clptr *strbuf, dataptr *strbuf, flags *int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procgetmsg)), 4, uintptr(fd), uintptr(unsafe.Pointer(clptr)), uintptr(unsafe.Pointer(dataptr)), uintptr(unsafe.Pointer(flags)), 0, 0) if e1 != 0 { - err = errnoErr(e1) + err = e1 } return } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go b/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go index 1d8fe1d4b..c31681743 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_zos_s390x.go @@ -40,6 +40,17 @@ func read(fd int, p []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func readlen(fd int, buf *byte, nbuf int) (n int, err error) { + r0, _, e1 := syscall_syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf)) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go index 9862853d3..c9c4ad031 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_386.go @@ -447,5 +447,4 @@ const ( SYS_PROCESS_MRELEASE = 448 SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 - SYS_CACHESTAT = 451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go index 8901f0f4e..12ff3417c 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go @@ -369,5 +369,4 @@ const ( SYS_PROCESS_MRELEASE = 448 SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 - SYS_CACHESTAT = 451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go index 6902c37ee..c3fb5e77a 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go @@ -411,5 +411,4 @@ const ( SYS_PROCESS_MRELEASE = 448 SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 - SYS_CACHESTAT = 451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go index a6d3dff81..358c847a4 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go @@ -314,5 +314,4 @@ const ( SYS_PROCESS_MRELEASE = 448 SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 - SYS_CACHESTAT = 451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go index b18f3f710..81c4849b1 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_loong64.go @@ -308,5 +308,4 @@ const ( SYS_PROCESS_MRELEASE = 448 SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 - SYS_CACHESTAT = 451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go index 0302e5e3d..202a57e90 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips.go @@ -431,5 +431,4 @@ const ( SYS_PROCESS_MRELEASE = 4448 SYS_FUTEX_WAITV = 4449 SYS_SET_MEMPOLICY_HOME_NODE = 4450 - SYS_CACHESTAT = 4451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go index 6693ba4a0..1fbceb52d 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64.go @@ -361,5 +361,4 @@ const ( SYS_PROCESS_MRELEASE = 5448 SYS_FUTEX_WAITV = 5449 SYS_SET_MEMPOLICY_HOME_NODE = 5450 - SYS_CACHESTAT = 5451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go index fd93f4987..b4ffb7a20 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mips64le.go @@ -361,5 +361,4 @@ const ( SYS_PROCESS_MRELEASE = 5448 SYS_FUTEX_WAITV = 5449 SYS_SET_MEMPOLICY_HOME_NODE = 5450 - SYS_CACHESTAT = 5451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go index 760ddcadc..867985f9b 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_mipsle.go @@ -431,5 +431,4 @@ const ( SYS_PROCESS_MRELEASE = 4448 SYS_FUTEX_WAITV = 4449 SYS_SET_MEMPOLICY_HOME_NODE = 4450 - SYS_CACHESTAT = 4451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go index cff2b2555..a8cce69ed 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc.go @@ -438,5 +438,4 @@ const ( SYS_PROCESS_MRELEASE = 448 SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 - SYS_CACHESTAT = 451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go index a4b2405d0..d44c5b39d 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go @@ -410,5 +410,4 @@ const ( SYS_PROCESS_MRELEASE = 448 SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 - SYS_CACHESTAT = 451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go index aca54b4e3..4214dd9c0 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go @@ -410,5 +410,4 @@ const ( SYS_PROCESS_MRELEASE = 448 SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 - SYS_CACHESTAT = 451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go index 9d1738d64..ef285c567 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_riscv64.go @@ -315,5 +315,4 @@ const ( SYS_PROCESS_MRELEASE = 448 SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 - SYS_CACHESTAT = 451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go index 022878dc8..e6ed7d637 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go @@ -376,5 +376,4 @@ const ( SYS_PROCESS_MRELEASE = 448 SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 - SYS_CACHESTAT = 451 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go index 4100a761c..92f628ef4 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_sparc64.go @@ -389,5 +389,4 @@ const ( SYS_PROCESS_MRELEASE = 448 SYS_FUTEX_WAITV = 449 SYS_SET_MEMPOLICY_HOME_NODE = 450 - SYS_CACHESTAT = 451 ) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux.go b/vendor/golang.org/x/sys/unix/ztypes_linux.go index 18aa70b42..26ef52aaf 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux.go @@ -1977,7 +1977,7 @@ const ( NFT_MSG_GETFLOWTABLE = 0x17 NFT_MSG_DELFLOWTABLE = 0x18 NFT_MSG_GETRULE_RESET = 0x19 - NFT_MSG_MAX = 0x22 + NFT_MSG_MAX = 0x21 NFTA_LIST_UNSPEC = 0x0 NFTA_LIST_ELEM = 0x1 NFTA_HOOK_UNSPEC = 0x0 @@ -4499,7 +4499,7 @@ const ( NL80211_ATTR_MAC_HINT = 0xc8 NL80211_ATTR_MAC_MASK = 0xd7 NL80211_ATTR_MAX_AP_ASSOC_STA = 0xca - NL80211_ATTR_MAX = 0x146 + NL80211_ATTR_MAX = 0x145 NL80211_ATTR_MAX_CRIT_PROT_DURATION = 0xb4 NL80211_ATTR_MAX_CSA_COUNTERS = 0xce NL80211_ATTR_MAX_MATCH_SETS = 0x85 @@ -4869,7 +4869,7 @@ const ( NL80211_CMD_LEAVE_IBSS = 0x2c NL80211_CMD_LEAVE_MESH = 0x45 NL80211_CMD_LEAVE_OCB = 0x6d - NL80211_CMD_MAX = 0x9a + NL80211_CMD_MAX = 0x99 NL80211_CMD_MICHAEL_MIC_FAILURE = 0x29 NL80211_CMD_MODIFY_LINK_STA = 0x97 NL80211_CMD_NAN_MATCH = 0x78 @@ -5503,7 +5503,7 @@ const ( NL80211_RATE_INFO_HE_RU_ALLOC_52 = 0x1 NL80211_RATE_INFO_HE_RU_ALLOC_996 = 0x5 NL80211_RATE_INFO_HE_RU_ALLOC = 0x11 - NL80211_RATE_INFO_MAX = 0x1d + NL80211_RATE_INFO_MAX = 0x16 NL80211_RATE_INFO_MCS = 0x2 NL80211_RATE_INFO_SHORT_GI = 0x4 NL80211_RATE_INFO_VHT_MCS = 0x6 @@ -5868,18 +5868,3 @@ const ( VIRTIO_NET_HDR_GSO_UDP_L4 = 0x5 VIRTIO_NET_HDR_GSO_ECN = 0x80 ) - -type SchedAttr struct { - Size uint32 - Policy uint32 - Flags uint64 - Nice int32 - Priority uint32 - Runtime uint64 - Deadline uint64 - Period uint64 - Util_min uint32 - Util_max uint32 -} - -const SizeofSchedAttr = 0x38 diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go index 1b4c97c32..83c69c119 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_riscv64.go @@ -733,10 +733,6 @@ const ( RISCV_HWPROBE_KEY_IMA_EXT_0 = 0x4 RISCV_HWPROBE_IMA_FD = 0x1 RISCV_HWPROBE_IMA_C = 0x2 - RISCV_HWPROBE_IMA_V = 0x4 - RISCV_HWPROBE_EXT_ZBA = 0x8 - RISCV_HWPROBE_EXT_ZBB = 0x10 - RISCV_HWPROBE_EXT_ZBS = 0x20 RISCV_HWPROBE_KEY_CPUPERF_0 = 0x5 RISCV_HWPROBE_MISALIGNED_UNKNOWN = 0x0 RISCV_HWPROBE_MISALIGNED_EMULATED = 0x1 diff --git a/vendor/golang.org/x/sys/windows/exec_windows.go b/vendor/golang.org/x/sys/windows/exec_windows.go index 9cabbb694..a52e0331d 100644 --- a/vendor/golang.org/x/sys/windows/exec_windows.go +++ b/vendor/golang.org/x/sys/windows/exec_windows.go @@ -22,7 +22,7 @@ import ( // but only if there is space or tab inside s. func EscapeArg(s string) string { if len(s) == 0 { - return `""` + return "\"\"" } n := len(s) hasSpace := false @@ -35,7 +35,7 @@ func EscapeArg(s string) string { } } if hasSpace { - n += 2 // Reserve space for quotes. + n += 2 } if n == len(s) { return s @@ -82,68 +82,20 @@ func EscapeArg(s string) string { // in CreateProcess's CommandLine argument, CreateService/ChangeServiceConfig's BinaryPathName argument, // or any program that uses CommandLineToArgv. func ComposeCommandLine(args []string) string { - if len(args) == 0 { - return "" - } - - // Per https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw: - // “This function accepts command lines that contain a program name; the - // program name can be enclosed in quotation marks or not.” - // - // Unfortunately, it provides no means of escaping interior quotation marks - // within that program name, and we have no way to report them here. - prog := args[0] - mustQuote := len(prog) == 0 - for i := 0; i < len(prog); i++ { - c := prog[i] - if c <= ' ' || (c == '"' && i == 0) { - // Force quotes for not only the ASCII space and tab as described in the - // MSDN article, but also ASCII control characters. - // The documentation for CommandLineToArgvW doesn't say what happens when - // the first argument is not a valid program name, but it empirically - // seems to drop unquoted control characters. - mustQuote = true - break + var commandLine string + for i := range args { + if i > 0 { + commandLine += " " } + commandLine += EscapeArg(args[i]) } - var commandLine []byte - if mustQuote { - commandLine = make([]byte, 0, len(prog)+2) - commandLine = append(commandLine, '"') - for i := 0; i < len(prog); i++ { - c := prog[i] - if c == '"' { - // This quote would interfere with our surrounding quotes. - // We have no way to report an error, so just strip out - // the offending character instead. - continue - } - commandLine = append(commandLine, c) - } - commandLine = append(commandLine, '"') - } else { - if len(args) == 1 { - // args[0] is a valid command line representing itself. - // No need to allocate a new slice or string for it. - return prog - } - commandLine = []byte(prog) - } - - for _, arg := range args[1:] { - commandLine = append(commandLine, ' ') - // TODO(bcmills): since we're already appending to a slice, it would be nice - // to avoid the intermediate allocations of EscapeArg. - // Perhaps we can factor out an appendEscapedArg function. - commandLine = append(commandLine, EscapeArg(arg)...) - } - return string(commandLine) + return commandLine } // DecomposeCommandLine breaks apart its argument command line into unescaped parts using CommandLineToArgv, // as gathered from GetCommandLine, QUERY_SERVICE_CONFIG's BinaryPathName argument, or elsewhere that // command lines are passed around. -// DecomposeCommandLine returns an error if commandLine contains NUL. +// DecomposeCommandLine returns error if commandLine contains NUL. func DecomposeCommandLine(commandLine string) ([]string, error) { if len(commandLine) == 0 { return []string{}, nil @@ -153,35 +105,18 @@ func DecomposeCommandLine(commandLine string) ([]string, error) { return nil, errorspkg.New("string with NUL passed to DecomposeCommandLine") } var argc int32 - argv, err := commandLineToArgv(&utf16CommandLine[0], &argc) + argv, err := CommandLineToArgv(&utf16CommandLine[0], &argc) if err != nil { return nil, err } defer LocalFree(Handle(unsafe.Pointer(argv))) - var args []string - for _, p := range unsafe.Slice(argv, argc) { - args = append(args, UTF16PtrToString(p)) + for _, v := range (*argv)[:argc] { + args = append(args, UTF16ToString((*v)[:])) } return args, nil } -// CommandLineToArgv parses a Unicode command line string and sets -// argc to the number of parsed arguments. -// -// The returned memory should be freed using a single call to LocalFree. -// -// Note that although the return type of CommandLineToArgv indicates 8192 -// entries of up to 8192 characters each, the actual count of parsed arguments -// may exceed 8192, and the documentation for CommandLineToArgvW does not mention -// any bound on the lengths of the individual argument strings. -// (See https://go.dev/issue/63236.) -func CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) { - argp, err := commandLineToArgv(cmd, argc) - argv = (*[8192]*[8192]uint16)(unsafe.Pointer(argp)) - return argv, err -} - func CloseOnExec(fd Handle) { SetHandleInformation(Handle(fd), HANDLE_FLAG_INHERIT, 0) } diff --git a/vendor/golang.org/x/sys/windows/security_windows.go b/vendor/golang.org/x/sys/windows/security_windows.go index 26be94a8a..d414ef13b 100644 --- a/vendor/golang.org/x/sys/windows/security_windows.go +++ b/vendor/golang.org/x/sys/windows/security_windows.go @@ -7,6 +7,8 @@ package windows import ( "syscall" "unsafe" + + "golang.org/x/sys/internal/unsafeheader" ) const ( @@ -1339,14 +1341,21 @@ func (selfRelativeSD *SECURITY_DESCRIPTOR) copySelfRelativeSecurityDescriptor() sdLen = min } - src := unsafe.Slice((*byte)(unsafe.Pointer(selfRelativeSD)), sdLen) - // SECURITY_DESCRIPTOR has pointers in it, which means checkptr expects for it to - // be aligned properly. When we're copying a Windows-allocated struct to a - // Go-allocated one, make sure that the Go allocation is aligned to the - // pointer size. + var src []byte + h := (*unsafeheader.Slice)(unsafe.Pointer(&src)) + h.Data = unsafe.Pointer(selfRelativeSD) + h.Len = sdLen + h.Cap = sdLen + const psize = int(unsafe.Sizeof(uintptr(0))) + + var dst []byte + h = (*unsafeheader.Slice)(unsafe.Pointer(&dst)) alloc := make([]uintptr, (sdLen+psize-1)/psize) - dst := unsafe.Slice((*byte)(unsafe.Pointer(&alloc[0])), sdLen) + h.Data = (*unsafeheader.Slice)(unsafe.Pointer(&alloc)).Data + h.Len = sdLen + h.Cap = sdLen + copy(dst, src) return (*SECURITY_DESCRIPTOR)(unsafe.Pointer(&dst[0])) } diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index 35cfc57ca..373d16388 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -15,6 +15,8 @@ import ( "time" "unicode/utf16" "unsafe" + + "golang.org/x/sys/internal/unsafeheader" ) type Handle uintptr @@ -214,7 +216,7 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys shGetKnownFolderPath(id *KNOWNFOLDERID, flags uint32, token Token, path **uint16) (ret error) = shell32.SHGetKnownFolderPath //sys TerminateProcess(handle Handle, exitcode uint32) (err error) //sys GetExitCodeProcess(handle Handle, exitcode *uint32) (err error) -//sys getStartupInfo(startupInfo *StartupInfo) = GetStartupInfoW +//sys GetStartupInfo(startupInfo *StartupInfo) (err error) = GetStartupInfoW //sys GetProcessTimes(handle Handle, creationTime *Filetime, exitTime *Filetime, kernelTime *Filetime, userTime *Filetime) (err error) //sys DuplicateHandle(hSourceProcessHandle Handle, hSourceHandle Handle, hTargetProcessHandle Handle, lpTargetHandle *Handle, dwDesiredAccess uint32, bInheritHandle bool, dwOptions uint32) (err error) //sys WaitForSingleObject(handle Handle, waitMilliseconds uint32) (event uint32, err error) [failretval==0xffffffff] @@ -238,7 +240,7 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys SetFileAttributes(name *uint16, attrs uint32) (err error) = kernel32.SetFileAttributesW //sys GetFileAttributesEx(name *uint16, level uint32, info *byte) (err error) = kernel32.GetFileAttributesExW //sys GetCommandLine() (cmd *uint16) = kernel32.GetCommandLineW -//sys commandLineToArgv(cmd *uint16, argc *int32) (argv **uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW +//sys CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) [failretval==nil] = shell32.CommandLineToArgvW //sys LocalFree(hmem Handle) (handle Handle, err error) [failretval!=0] //sys LocalAlloc(flags uint32, length uint32) (ptr uintptr, err error) //sys SetHandleInformation(handle Handle, mask uint32, flags uint32) (err error) @@ -297,15 +299,12 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys RegNotifyChangeKeyValue(key Handle, watchSubtree bool, notifyFilter uint32, event Handle, asynchronous bool) (regerrno error) = advapi32.RegNotifyChangeKeyValue //sys GetCurrentProcessId() (pid uint32) = kernel32.GetCurrentProcessId //sys ProcessIdToSessionId(pid uint32, sessionid *uint32) (err error) = kernel32.ProcessIdToSessionId -//sys ClosePseudoConsole(console Handle) = kernel32.ClosePseudoConsole -//sys createPseudoConsole(size uint32, in Handle, out Handle, flags uint32, pconsole *Handle) (hr error) = kernel32.CreatePseudoConsole //sys GetConsoleMode(console Handle, mode *uint32) (err error) = kernel32.GetConsoleMode //sys SetConsoleMode(console Handle, mode uint32) (err error) = kernel32.SetConsoleMode //sys GetConsoleScreenBufferInfo(console Handle, info *ConsoleScreenBufferInfo) (err error) = kernel32.GetConsoleScreenBufferInfo //sys setConsoleCursorPosition(console Handle, position uint32) (err error) = kernel32.SetConsoleCursorPosition //sys WriteConsole(console Handle, buf *uint16, towrite uint32, written *uint32, reserved *byte) (err error) = kernel32.WriteConsoleW //sys ReadConsole(console Handle, buf *uint16, toread uint32, read *uint32, inputControl *byte) (err error) = kernel32.ReadConsoleW -//sys resizePseudoConsole(pconsole Handle, size uint32) (hr error) = kernel32.ResizePseudoConsole //sys CreateToolhelp32Snapshot(flags uint32, processId uint32) (handle Handle, err error) [failretval==InvalidHandle] = kernel32.CreateToolhelp32Snapshot //sys Module32First(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32FirstW //sys Module32Next(snapshot Handle, moduleEntry *ModuleEntry32) (err error) = kernel32.Module32NextW @@ -438,10 +437,6 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys DwmGetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) = dwmapi.DwmGetWindowAttribute //sys DwmSetWindowAttribute(hwnd HWND, attribute uint32, value unsafe.Pointer, size uint32) (ret error) = dwmapi.DwmSetWindowAttribute -// Windows Multimedia API -//sys TimeBeginPeriod (period uint32) (err error) [failretval != 0] = winmm.timeBeginPeriod -//sys TimeEndPeriod (period uint32) (err error) [failretval != 0] = winmm.timeEndPeriod - // syscall interface implementation for other packages // GetCurrentProcess returns the handle for the current process. @@ -1629,11 +1624,6 @@ func SetConsoleCursorPosition(console Handle, position Coord) error { return setConsoleCursorPosition(console, *((*uint32)(unsafe.Pointer(&position)))) } -func GetStartupInfo(startupInfo *StartupInfo) error { - getStartupInfo(startupInfo) - return nil -} - func (s NTStatus) Errno() syscall.Errno { return rtlNtStatusToDosErrorNoTeb(s) } @@ -1668,8 +1658,12 @@ func NewNTUnicodeString(s string) (*NTUnicodeString, error) { // Slice returns a uint16 slice that aliases the data in the NTUnicodeString. func (s *NTUnicodeString) Slice() []uint16 { - slice := unsafe.Slice(s.Buffer, s.MaximumLength) - return slice[:s.Length] + var slice []uint16 + hdr := (*unsafeheader.Slice)(unsafe.Pointer(&slice)) + hdr.Data = unsafe.Pointer(s.Buffer) + hdr.Len = int(s.Length) + hdr.Cap = int(s.MaximumLength) + return slice } func (s *NTUnicodeString) String() string { @@ -1692,8 +1686,12 @@ func NewNTString(s string) (*NTString, error) { // Slice returns a byte slice that aliases the data in the NTString. func (s *NTString) Slice() []byte { - slice := unsafe.Slice(s.Buffer, s.MaximumLength) - return slice[:s.Length] + var slice []byte + hdr := (*unsafeheader.Slice)(unsafe.Pointer(&slice)) + hdr.Data = unsafe.Pointer(s.Buffer) + hdr.Len = int(s.Length) + hdr.Cap = int(s.MaximumLength) + return slice } func (s *NTString) String() string { @@ -1745,7 +1743,10 @@ func LoadResourceData(module, resInfo Handle) (data []byte, err error) { if err != nil { return } - data = unsafe.Slice((*byte)(unsafe.Pointer(ptr)), size) + h := (*unsafeheader.Slice)(unsafe.Pointer(&data)) + h.Data = unsafe.Pointer(ptr) + h.Len = int(size) + h.Cap = int(size) return } @@ -1816,17 +1817,3 @@ type PSAPI_WORKING_SET_EX_INFORMATION struct { // A PSAPI_WORKING_SET_EX_BLOCK union that indicates the attributes of the page at VirtualAddress. VirtualAttributes PSAPI_WORKING_SET_EX_BLOCK } - -// CreatePseudoConsole creates a windows pseudo console. -func CreatePseudoConsole(size Coord, in Handle, out Handle, flags uint32, pconsole *Handle) error { - // We need this wrapper to manually cast Coord to uint32. The autogenerated wrappers only - // accept arguments that can be casted to uintptr, and Coord can't. - return createPseudoConsole(*((*uint32)(unsafe.Pointer(&size))), in, out, flags, pconsole) -} - -// ResizePseudoConsole resizes the internal buffers of the pseudo console to the width and height specified in `size`. -func ResizePseudoConsole(pconsole Handle, size Coord) error { - // We need this wrapper to manually cast Coord to uint32. The autogenerated wrappers only - // accept arguments that can be casted to uintptr, and Coord can't. - return resizePseudoConsole(pconsole, *((*uint32)(unsafe.Pointer(&size)))) -} diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index b88dc7c85..88e62a638 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -247,7 +247,6 @@ const ( PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY = 0x00020007 PROC_THREAD_ATTRIBUTE_UMS_THREAD = 0x00030006 PROC_THREAD_ATTRIBUTE_PROTECTION_LEVEL = 0x0002000b - PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE = 0x00020016 ) const ( @@ -2140,12 +2139,6 @@ const ( ENABLE_LVB_GRID_WORLDWIDE = 0x10 ) -// Pseudo console related constants used for the flags parameter to -// CreatePseudoConsole. See: https://learn.microsoft.com/en-us/windows/console/createpseudoconsole -const ( - PSEUDOCONSOLE_INHERIT_CURSOR = 0x1 -) - type Coord struct { X int16 Y int16 diff --git a/vendor/golang.org/x/sys/windows/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/zsyscall_windows.go index 8b1688de4..566dd3e31 100644 --- a/vendor/golang.org/x/sys/windows/zsyscall_windows.go +++ b/vendor/golang.org/x/sys/windows/zsyscall_windows.go @@ -55,7 +55,6 @@ var ( moduser32 = NewLazySystemDLL("user32.dll") moduserenv = NewLazySystemDLL("userenv.dll") modversion = NewLazySystemDLL("version.dll") - modwinmm = NewLazySystemDLL("winmm.dll") modwintrust = NewLazySystemDLL("wintrust.dll") modws2_32 = NewLazySystemDLL("ws2_32.dll") modwtsapi32 = NewLazySystemDLL("wtsapi32.dll") @@ -188,7 +187,6 @@ var ( procCancelIo = modkernel32.NewProc("CancelIo") procCancelIoEx = modkernel32.NewProc("CancelIoEx") procCloseHandle = modkernel32.NewProc("CloseHandle") - procClosePseudoConsole = modkernel32.NewProc("ClosePseudoConsole") procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") procCreateDirectoryW = modkernel32.NewProc("CreateDirectoryW") procCreateEventExW = modkernel32.NewProc("CreateEventExW") @@ -203,7 +201,6 @@ var ( procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") procCreatePipe = modkernel32.NewProc("CreatePipe") procCreateProcessW = modkernel32.NewProc("CreateProcessW") - procCreatePseudoConsole = modkernel32.NewProc("CreatePseudoConsole") procCreateSymbolicLinkW = modkernel32.NewProc("CreateSymbolicLinkW") procCreateToolhelp32Snapshot = modkernel32.NewProc("CreateToolhelp32Snapshot") procDefineDosDeviceW = modkernel32.NewProc("DefineDosDeviceW") @@ -330,7 +327,6 @@ var ( procReleaseMutex = modkernel32.NewProc("ReleaseMutex") procRemoveDirectoryW = modkernel32.NewProc("RemoveDirectoryW") procResetEvent = modkernel32.NewProc("ResetEvent") - procResizePseudoConsole = modkernel32.NewProc("ResizePseudoConsole") procResumeThread = modkernel32.NewProc("ResumeThread") procSetCommTimeouts = modkernel32.NewProc("SetCommTimeouts") procSetConsoleCursorPosition = modkernel32.NewProc("SetConsoleCursorPosition") @@ -472,8 +468,6 @@ var ( procGetFileVersionInfoSizeW = modversion.NewProc("GetFileVersionInfoSizeW") procGetFileVersionInfoW = modversion.NewProc("GetFileVersionInfoW") procVerQueryValueW = modversion.NewProc("VerQueryValueW") - proctimeBeginPeriod = modwinmm.NewProc("timeBeginPeriod") - proctimeEndPeriod = modwinmm.NewProc("timeEndPeriod") procWinVerifyTrustEx = modwintrust.NewProc("WinVerifyTrustEx") procFreeAddrInfoW = modws2_32.NewProc("FreeAddrInfoW") procGetAddrInfoW = modws2_32.NewProc("GetAddrInfoW") @@ -1636,11 +1630,6 @@ func CloseHandle(handle Handle) (err error) { return } -func ClosePseudoConsole(console Handle) { - syscall.Syscall(procClosePseudoConsole.Addr(), 1, uintptr(console), 0, 0) - return -} - func ConnectNamedPipe(pipe Handle, overlapped *Overlapped) (err error) { r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(overlapped)), 0) if r1 == 0 { @@ -1770,14 +1759,6 @@ func CreateProcess(appName *uint16, commandLine *uint16, procSecurity *SecurityA return } -func createPseudoConsole(size uint32, in Handle, out Handle, flags uint32, pconsole *Handle) (hr error) { - r0, _, _ := syscall.Syscall6(procCreatePseudoConsole.Addr(), 5, uintptr(size), uintptr(in), uintptr(out), uintptr(flags), uintptr(unsafe.Pointer(pconsole)), 0) - if r0 != 0 { - hr = syscall.Errno(r0) - } - return -} - func CreateSymbolicLink(symlinkfilename *uint16, targetfilename *uint16, flags uint32) (err error) { r1, _, e1 := syscall.Syscall(procCreateSymbolicLinkW.Addr(), 3, uintptr(unsafe.Pointer(symlinkfilename)), uintptr(unsafe.Pointer(targetfilename)), uintptr(flags)) if r1&0xff == 0 { @@ -2386,8 +2367,11 @@ func GetShortPathName(longpath *uint16, shortpath *uint16, buflen uint32) (n uin return } -func getStartupInfo(startupInfo *StartupInfo) { - syscall.Syscall(procGetStartupInfoW.Addr(), 1, uintptr(unsafe.Pointer(startupInfo)), 0, 0) +func GetStartupInfo(startupInfo *StartupInfo) (err error) { + r1, _, e1 := syscall.Syscall(procGetStartupInfoW.Addr(), 1, uintptr(unsafe.Pointer(startupInfo)), 0, 0) + if r1 == 0 { + err = errnoErr(e1) + } return } @@ -2878,14 +2862,6 @@ func ResetEvent(event Handle) (err error) { return } -func resizePseudoConsole(pconsole Handle, size uint32) (hr error) { - r0, _, _ := syscall.Syscall(procResizePseudoConsole.Addr(), 2, uintptr(pconsole), uintptr(size), 0) - if r0 != 0 { - hr = syscall.Errno(r0) - } - return -} - func ResumeThread(thread Handle) (ret uint32, err error) { r0, _, e1 := syscall.Syscall(procResumeThread.Addr(), 1, uintptr(thread), 0, 0) ret = uint32(r0) @@ -3844,9 +3820,9 @@ func setupUninstallOEMInf(infFileName *uint16, flags SUOI, reserved uintptr) (er return } -func commandLineToArgv(cmd *uint16, argc *int32) (argv **uint16, err error) { +func CommandLineToArgv(cmd *uint16, argc *int32) (argv *[8192]*[8192]uint16, err error) { r0, _, e1 := syscall.Syscall(procCommandLineToArgvW.Addr(), 2, uintptr(unsafe.Pointer(cmd)), uintptr(unsafe.Pointer(argc)), 0) - argv = (**uint16)(unsafe.Pointer(r0)) + argv = (*[8192]*[8192]uint16)(unsafe.Pointer(r0)) if argv == nil { err = errnoErr(e1) } @@ -4041,22 +4017,6 @@ func _VerQueryValue(block unsafe.Pointer, subBlock *uint16, pointerToBufferPoint return } -func TimeBeginPeriod(period uint32) (err error) { - r1, _, e1 := syscall.Syscall(proctimeBeginPeriod.Addr(), 1, uintptr(period), 0, 0) - if r1 != 0 { - err = errnoErr(e1) - } - return -} - -func TimeEndPeriod(period uint32) (err error) { - r1, _, e1 := syscall.Syscall(proctimeEndPeriod.Addr(), 1, uintptr(period), 0, 0) - if r1 != 0 { - err = errnoErr(e1) - } - return -} - func WinVerifyTrustEx(hwnd HWND, actionId *GUID, data *WinTrustData) (ret error) { r0, _, _ := syscall.Syscall(procWinVerifyTrustEx.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(actionId)), uintptr(unsafe.Pointer(data))) if r0 != 0 { diff --git a/vendor/golang.org/x/text/unicode/norm/trie.go b/vendor/golang.org/x/text/unicode/norm/trie.go index e4250ae22..423386bf4 100644 --- a/vendor/golang.org/x/text/unicode/norm/trie.go +++ b/vendor/golang.org/x/text/unicode/norm/trie.go @@ -29,7 +29,7 @@ var ( nfkcData = newNfkcTrie(0) ) -// lookup determines the type of block n and looks up the value for b. +// lookupValue determines the type of block n and looks up the value for b. // For n < t.cutoff, the block is a simple lookup table. Otherwise, the block // is a list of ranges with an accompanying value. Given a matching range r, // the value for b is by r.value + (b - r.lo) * stride. diff --git a/vendor/golang.org/x/tools/cmd/goimports/goimports.go b/vendor/golang.org/x/tools/cmd/goimports/goimports.go index 3b6bd7250..b354c9e82 100644 --- a/vendor/golang.org/x/tools/cmd/goimports/goimports.go +++ b/vendor/golang.org/x/tools/cmd/goimports/goimports.go @@ -13,6 +13,7 @@ import ( "go/scanner" exec "golang.org/x/sys/execabs" "io" + "io/ioutil" "log" "os" "path/filepath" @@ -105,7 +106,7 @@ func processFile(filename string, in io.Reader, out io.Writer, argType argumentT in = f } - src, err := io.ReadAll(in) + src, err := ioutil.ReadAll(in) if err != nil { return err } @@ -158,7 +159,7 @@ func processFile(filename string, in io.Reader, out io.Writer, argType argumentT if fi, err := os.Stat(filename); err == nil { perms = fi.Mode() & os.ModePerm } - err = os.WriteFile(filename, res, perms) + err = ioutil.WriteFile(filename, res, perms) if err != nil { return err } @@ -295,7 +296,7 @@ func gofmtMain() { } func writeTempFile(dir, prefix string, data []byte) (string, error) { - file, err := os.CreateTemp(dir, prefix) + file, err := ioutil.TempFile(dir, prefix) if err != nil { return "", err } diff --git a/vendor/golang.org/x/tools/go/packages/doc.go b/vendor/golang.org/x/tools/go/packages/doc.go index a7a8f73e3..da4ab89fe 100644 --- a/vendor/golang.org/x/tools/go/packages/doc.go +++ b/vendor/golang.org/x/tools/go/packages/doc.go @@ -35,7 +35,7 @@ The Package struct provides basic information about the package, including - Imports, a map from source import strings to the Packages they name; - Types, the type information for the package's exported symbols; - Syntax, the parsed syntax trees for the package's source code; and - - TypesInfo, the result of a complete type-check of the package syntax trees. + - TypeInfo, the result of a complete type-check of the package syntax trees. (See the documentation for type Package for the complete list of fields and more detailed descriptions.) diff --git a/vendor/golang.org/x/tools/go/packages/golist.go b/vendor/golang.org/x/tools/go/packages/golist.go index 1f1eade0a..b5de9cf9f 100644 --- a/vendor/golang.org/x/tools/go/packages/golist.go +++ b/vendor/golang.org/x/tools/go/packages/golist.go @@ -9,6 +9,7 @@ import ( "context" "encoding/json" "fmt" + "io/ioutil" "log" "os" "path" @@ -1108,7 +1109,7 @@ func (state *golistState) writeOverlays() (filename string, cleanup func(), err if len(state.cfg.Overlay) == 0 { return "", func() {}, nil } - dir, err := os.MkdirTemp("", "gopackages-*") + dir, err := ioutil.TempDir("", "gopackages-*") if err != nil { return "", nil, err } @@ -1127,7 +1128,7 @@ func (state *golistState) writeOverlays() (filename string, cleanup func(), err // Create a unique filename for the overlaid files, to avoid // creating nested directories. noSeparator := strings.Join(strings.Split(filepath.ToSlash(k), "/"), "") - f, err := os.CreateTemp(dir, fmt.Sprintf("*-%s", noSeparator)) + f, err := ioutil.TempFile(dir, fmt.Sprintf("*-%s", noSeparator)) if err != nil { return "", func() {}, err } @@ -1145,7 +1146,7 @@ func (state *golistState) writeOverlays() (filename string, cleanup func(), err } // Write out the overlay file that contains the filepath mappings. filename = filepath.Join(dir, "overlay.json") - if err := os.WriteFile(filename, b, 0665); err != nil { + if err := ioutil.WriteFile(filename, b, 0665); err != nil { return "", func() {}, err } return filename, cleanup, nil diff --git a/vendor/golang.org/x/tools/go/packages/packages.go b/vendor/golang.org/x/tools/go/packages/packages.go index ece0e7c60..124a6fe14 100644 --- a/vendor/golang.org/x/tools/go/packages/packages.go +++ b/vendor/golang.org/x/tools/go/packages/packages.go @@ -16,6 +16,7 @@ import ( "go/token" "go/types" "io" + "io/ioutil" "log" "os" "path/filepath" @@ -1126,7 +1127,7 @@ func (ld *loader) parseFile(filename string) (*ast.File, error) { var err error if src == nil { ioLimit <- true // wait - src, err = os.ReadFile(filename) + src, err = ioutil.ReadFile(filename) <-ioLimit // signal } if err != nil { diff --git a/vendor/golang.org/x/tools/imports/forward.go b/vendor/golang.org/x/tools/imports/forward.go index cb6db8893..d2547c743 100644 --- a/vendor/golang.org/x/tools/imports/forward.go +++ b/vendor/golang.org/x/tools/imports/forward.go @@ -7,8 +7,8 @@ package imports // import "golang.org/x/tools/imports" import ( + "io/ioutil" "log" - "os" "golang.org/x/tools/internal/gocommand" intimp "golang.org/x/tools/internal/imports" @@ -44,7 +44,7 @@ var LocalPrefix string func Process(filename string, src []byte, opt *Options) ([]byte, error) { var err error if src == nil { - src, err = os.ReadFile(filename) + src, err = ioutil.ReadFile(filename) if err != nil { return nil, err } diff --git a/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_portable.go b/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_portable.go index 27e860243..085d31160 100644 --- a/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_portable.go +++ b/vendor/golang.org/x/tools/internal/fastwalk/fastwalk_portable.go @@ -8,6 +8,7 @@ package fastwalk import ( + "io/ioutil" "os" ) @@ -16,20 +17,16 @@ import ( // If fn returns a non-nil error, readDir returns with that error // immediately. func readDir(dirName string, fn func(dirName, entName string, typ os.FileMode) error) error { - fis, err := os.ReadDir(dirName) + fis, err := ioutil.ReadDir(dirName) if err != nil { return err } skipFiles := false for _, fi := range fis { - info, err := fi.Info() - if err != nil { - return err - } - if info.Mode().IsRegular() && skipFiles { + if fi.Mode().IsRegular() && skipFiles { continue } - if err := fn(dirName, fi.Name(), info.Mode()&os.ModeType); err != nil { + if err := fn(dirName, fi.Name(), fi.Mode()&os.ModeType); err != nil { if err == ErrSkipFiles { skipFiles = true continue diff --git a/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go index 2d078ccb1..b1223713b 100644 --- a/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go +++ b/vendor/golang.org/x/tools/internal/gcimporter/gcimporter.go @@ -29,6 +29,7 @@ import ( "go/token" "go/types" "io" + "io/ioutil" "os" "os/exec" "path/filepath" @@ -220,7 +221,7 @@ func Import(packages map[string]*types.Package, path, srcDir string, lookup func switch hdr { case "$$B\n": var data []byte - data, err = io.ReadAll(buf) + data, err = ioutil.ReadAll(buf) if err != nil { break } diff --git a/vendor/golang.org/x/tools/internal/imports/fix.go b/vendor/golang.org/x/tools/internal/imports/fix.go index 01e8ba5fa..d4f1b4e8a 100644 --- a/vendor/golang.org/x/tools/internal/imports/fix.go +++ b/vendor/golang.org/x/tools/internal/imports/fix.go @@ -13,7 +13,6 @@ import ( "go/build" "go/parser" "go/token" - "io/fs" "io/ioutil" "os" "path" @@ -108,7 +107,7 @@ func parseOtherFiles(fset *token.FileSet, srcDir, filename string) []*ast.File { considerTests := strings.HasSuffix(filename, "_test.go") fileBase := filepath.Base(filename) - packageFileInfos, err := os.ReadDir(srcDir) + packageFileInfos, err := ioutil.ReadDir(srcDir) if err != nil { return nil } @@ -1470,11 +1469,11 @@ func VendorlessPath(ipath string) string { func loadExportsFromFiles(ctx context.Context, env *ProcessEnv, dir string, includeTest bool) (string, []string, error) { // Look for non-test, buildable .go files which could provide exports. - all, err := os.ReadDir(dir) + all, err := ioutil.ReadDir(dir) if err != nil { return "", nil, err } - var files []fs.DirEntry + var files []os.FileInfo for _, fi := range all { name := fi.Name() if !strings.HasSuffix(name, ".go") || (!includeTest && strings.HasSuffix(name, "_test.go")) { diff --git a/vendor/golang.org/x/tools/internal/imports/mod.go b/vendor/golang.org/x/tools/internal/imports/mod.go index 5f4d435d3..977d2389d 100644 --- a/vendor/golang.org/x/tools/internal/imports/mod.go +++ b/vendor/golang.org/x/tools/internal/imports/mod.go @@ -9,6 +9,7 @@ import ( "context" "encoding/json" "fmt" + "io/ioutil" "os" "path" "path/filepath" @@ -264,7 +265,7 @@ func (r *ModuleResolver) findPackage(importPath string) (*gocommand.ModuleJSON, } // Not cached. Read the filesystem. - pkgFiles, err := os.ReadDir(pkgDir) + pkgFiles, err := ioutil.ReadDir(pkgDir) if err != nil { continue } @@ -369,7 +370,7 @@ func (r *ModuleResolver) dirIsNestedModule(dir string, mod *gocommand.ModuleJSON func (r *ModuleResolver) modInfo(dir string) (modDir string, modName string) { readModName := func(modFile string) string { - modBytes, err := os.ReadFile(modFile) + modBytes, err := ioutil.ReadFile(modFile) if err != nil { return "" } diff --git a/vendor/golang.org/x/xerrors/LICENSE b/vendor/golang.org/x/xerrors/LICENSE new file mode 100644 index 000000000..e4a47e17f --- /dev/null +++ b/vendor/golang.org/x/xerrors/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2019 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/xerrors/PATENTS b/vendor/golang.org/x/xerrors/PATENTS new file mode 100644 index 000000000..733099041 --- /dev/null +++ b/vendor/golang.org/x/xerrors/PATENTS @@ -0,0 +1,22 @@ +Additional IP Rights Grant (Patents) + +"This implementation" means the copyrightable works distributed by +Google as part of the Go project. + +Google hereby grants to You a perpetual, worldwide, non-exclusive, +no-charge, royalty-free, irrevocable (except as stated in this section) +patent license to make, have made, use, offer to sell, sell, import, +transfer and otherwise run, modify and propagate the contents of this +implementation of Go, where such license applies only to those patent +claims, both currently owned or controlled by Google and acquired in +the future, licensable by Google that are necessarily infringed by this +implementation of Go. This grant does not include claims that would be +infringed only as a consequence of further modification of this +implementation. If you or your agent or exclusive licensee institute or +order or agree to the institution of patent litigation against any +entity (including a cross-claim or counterclaim in a lawsuit) alleging +that this implementation of Go or any code incorporated within this +implementation of Go constitutes direct or contributory patent +infringement, or inducement of patent infringement, then any patent +rights granted to you under this License for this implementation of Go +shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/xerrors/README b/vendor/golang.org/x/xerrors/README new file mode 100644 index 000000000..aac7867a5 --- /dev/null +++ b/vendor/golang.org/x/xerrors/README @@ -0,0 +1,2 @@ +This repository holds the transition packages for the new Go 1.13 error values. +See golang.org/design/29934-error-values. diff --git a/vendor/golang.org/x/xerrors/adaptor.go b/vendor/golang.org/x/xerrors/adaptor.go new file mode 100644 index 000000000..4317f2483 --- /dev/null +++ b/vendor/golang.org/x/xerrors/adaptor.go @@ -0,0 +1,193 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package xerrors + +import ( + "bytes" + "fmt" + "io" + "reflect" + "strconv" +) + +// FormatError calls the FormatError method of f with an errors.Printer +// configured according to s and verb, and writes the result to s. +func FormatError(f Formatter, s fmt.State, verb rune) { + // Assuming this function is only called from the Format method, and given + // that FormatError takes precedence over Format, it cannot be called from + // any package that supports errors.Formatter. It is therefore safe to + // disregard that State may be a specific printer implementation and use one + // of our choice instead. + + // limitations: does not support printing error as Go struct. + + var ( + sep = " " // separator before next error + p = &state{State: s} + direct = true + ) + + var err error = f + + switch verb { + // Note that this switch must match the preference order + // for ordinary string printing (%#v before %+v, and so on). + + case 'v': + if s.Flag('#') { + if stringer, ok := err.(fmt.GoStringer); ok { + io.WriteString(&p.buf, stringer.GoString()) + goto exit + } + // proceed as if it were %v + } else if s.Flag('+') { + p.printDetail = true + sep = "\n - " + } + case 's': + case 'q', 'x', 'X': + // Use an intermediate buffer in the rare cases that precision, + // truncation, or one of the alternative verbs (q, x, and X) are + // specified. + direct = false + + default: + p.buf.WriteString("%!") + p.buf.WriteRune(verb) + p.buf.WriteByte('(') + switch { + case err != nil: + p.buf.WriteString(reflect.TypeOf(f).String()) + default: + p.buf.WriteString("") + } + p.buf.WriteByte(')') + io.Copy(s, &p.buf) + return + } + +loop: + for { + switch v := err.(type) { + case Formatter: + err = v.FormatError((*printer)(p)) + case fmt.Formatter: + v.Format(p, 'v') + break loop + default: + io.WriteString(&p.buf, v.Error()) + break loop + } + if err == nil { + break + } + if p.needColon || !p.printDetail { + p.buf.WriteByte(':') + p.needColon = false + } + p.buf.WriteString(sep) + p.inDetail = false + p.needNewline = false + } + +exit: + width, okW := s.Width() + prec, okP := s.Precision() + + if !direct || (okW && width > 0) || okP { + // Construct format string from State s. + format := []byte{'%'} + if s.Flag('-') { + format = append(format, '-') + } + if s.Flag('+') { + format = append(format, '+') + } + if s.Flag(' ') { + format = append(format, ' ') + } + if okW { + format = strconv.AppendInt(format, int64(width), 10) + } + if okP { + format = append(format, '.') + format = strconv.AppendInt(format, int64(prec), 10) + } + format = append(format, string(verb)...) + fmt.Fprintf(s, string(format), p.buf.String()) + } else { + io.Copy(s, &p.buf) + } +} + +var detailSep = []byte("\n ") + +// state tracks error printing state. It implements fmt.State. +type state struct { + fmt.State + buf bytes.Buffer + + printDetail bool + inDetail bool + needColon bool + needNewline bool +} + +func (s *state) Write(b []byte) (n int, err error) { + if s.printDetail { + if len(b) == 0 { + return 0, nil + } + if s.inDetail && s.needColon { + s.needNewline = true + if b[0] == '\n' { + b = b[1:] + } + } + k := 0 + for i, c := range b { + if s.needNewline { + if s.inDetail && s.needColon { + s.buf.WriteByte(':') + s.needColon = false + } + s.buf.Write(detailSep) + s.needNewline = false + } + if c == '\n' { + s.buf.Write(b[k:i]) + k = i + 1 + s.needNewline = true + } + } + s.buf.Write(b[k:]) + if !s.inDetail { + s.needColon = true + } + } else if !s.inDetail { + s.buf.Write(b) + } + return len(b), nil +} + +// printer wraps a state to implement an xerrors.Printer. +type printer state + +func (s *printer) Print(args ...interface{}) { + if !s.inDetail || s.printDetail { + fmt.Fprint((*state)(s), args...) + } +} + +func (s *printer) Printf(format string, args ...interface{}) { + if !s.inDetail || s.printDetail { + fmt.Fprintf((*state)(s), format, args...) + } +} + +func (s *printer) Detail() bool { + s.inDetail = true + return s.printDetail +} diff --git a/vendor/golang.org/x/xerrors/codereview.cfg b/vendor/golang.org/x/xerrors/codereview.cfg new file mode 100644 index 000000000..3f8b14b64 --- /dev/null +++ b/vendor/golang.org/x/xerrors/codereview.cfg @@ -0,0 +1 @@ +issuerepo: golang/go diff --git a/vendor/golang.org/x/xerrors/doc.go b/vendor/golang.org/x/xerrors/doc.go new file mode 100644 index 000000000..2ef99f5a8 --- /dev/null +++ b/vendor/golang.org/x/xerrors/doc.go @@ -0,0 +1,23 @@ +// Copyright 2019 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package xerrors implements functions to manipulate errors. +// +// This package is based on the Go 2 proposal for error values: +// +// https://golang.org/design/29934-error-values +// +// These functions were incorporated into the standard library's errors package +// in Go 1.13: +// - Is +// - As +// - Unwrap +// +// Also, Errorf's %w verb was incorporated into fmt.Errorf. +// +// Use this package to get equivalent behavior in all supported Go versions. +// +// No other features of this package were included in Go 1.13, and at present +// there are no plans to include any of them. +package xerrors // import "golang.org/x/xerrors" diff --git a/vendor/golang.org/x/xerrors/errors.go b/vendor/golang.org/x/xerrors/errors.go new file mode 100644 index 000000000..e88d3772d --- /dev/null +++ b/vendor/golang.org/x/xerrors/errors.go @@ -0,0 +1,33 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package xerrors + +import "fmt" + +// errorString is a trivial implementation of error. +type errorString struct { + s string + frame Frame +} + +// New returns an error that formats as the given text. +// +// The returned error contains a Frame set to the caller's location and +// implements Formatter to show this information when printed with details. +func New(text string) error { + return &errorString{text, Caller(1)} +} + +func (e *errorString) Error() string { + return e.s +} + +func (e *errorString) Format(s fmt.State, v rune) { FormatError(e, s, v) } + +func (e *errorString) FormatError(p Printer) (next error) { + p.Print(e.s) + e.frame.Format(p) + return nil +} diff --git a/vendor/golang.org/x/xerrors/fmt.go b/vendor/golang.org/x/xerrors/fmt.go new file mode 100644 index 000000000..27a5d70bd --- /dev/null +++ b/vendor/golang.org/x/xerrors/fmt.go @@ -0,0 +1,190 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package xerrors + +import ( + "fmt" + "strings" + "unicode" + "unicode/utf8" + + "golang.org/x/xerrors/internal" +) + +const percentBangString = "%!" + +// Errorf formats according to a format specifier and returns the string as a +// value that satisfies error. +// +// The returned error includes the file and line number of the caller when +// formatted with additional detail enabled. If the last argument is an error +// the returned error's Format method will return it if the format string ends +// with ": %s", ": %v", or ": %w". If the last argument is an error and the +// format string ends with ": %w", the returned error implements an Unwrap +// method returning it. +// +// If the format specifier includes a %w verb with an error operand in a +// position other than at the end, the returned error will still implement an +// Unwrap method returning the operand, but the error's Format method will not +// return the wrapped error. +// +// It is invalid to include more than one %w verb or to supply it with an +// operand that does not implement the error interface. The %w verb is otherwise +// a synonym for %v. +// +// Note that as of Go 1.13, the fmt.Errorf function will do error formatting, +// but it will not capture a stack backtrace. +func Errorf(format string, a ...interface{}) error { + format = formatPlusW(format) + // Support a ": %[wsv]" suffix, which works well with xerrors.Formatter. + wrap := strings.HasSuffix(format, ": %w") + idx, format2, ok := parsePercentW(format) + percentWElsewhere := !wrap && idx >= 0 + if !percentWElsewhere && (wrap || strings.HasSuffix(format, ": %s") || strings.HasSuffix(format, ": %v")) { + err := errorAt(a, len(a)-1) + if err == nil { + return &noWrapError{fmt.Sprintf(format, a...), nil, Caller(1)} + } + // TODO: this is not entirely correct. The error value could be + // printed elsewhere in format if it mixes numbered with unnumbered + // substitutions. With relatively small changes to doPrintf we can + // have it optionally ignore extra arguments and pass the argument + // list in its entirety. + msg := fmt.Sprintf(format[:len(format)-len(": %s")], a[:len(a)-1]...) + frame := Frame{} + if internal.EnableTrace { + frame = Caller(1) + } + if wrap { + return &wrapError{msg, err, frame} + } + return &noWrapError{msg, err, frame} + } + // Support %w anywhere. + // TODO: don't repeat the wrapped error's message when %w occurs in the middle. + msg := fmt.Sprintf(format2, a...) + if idx < 0 { + return &noWrapError{msg, nil, Caller(1)} + } + err := errorAt(a, idx) + if !ok || err == nil { + // Too many %ws or argument of %w is not an error. Approximate the Go + // 1.13 fmt.Errorf message. + return &noWrapError{fmt.Sprintf("%sw(%s)", percentBangString, msg), nil, Caller(1)} + } + frame := Frame{} + if internal.EnableTrace { + frame = Caller(1) + } + return &wrapError{msg, err, frame} +} + +func errorAt(args []interface{}, i int) error { + if i < 0 || i >= len(args) { + return nil + } + err, ok := args[i].(error) + if !ok { + return nil + } + return err +} + +// formatPlusW is used to avoid the vet check that will barf at %w. +func formatPlusW(s string) string { + return s +} + +// Return the index of the only %w in format, or -1 if none. +// Also return a rewritten format string with %w replaced by %v, and +// false if there is more than one %w. +// TODO: handle "%[N]w". +func parsePercentW(format string) (idx int, newFormat string, ok bool) { + // Loosely copied from golang.org/x/tools/go/analysis/passes/printf/printf.go. + idx = -1 + ok = true + n := 0 + sz := 0 + var isW bool + for i := 0; i < len(format); i += sz { + if format[i] != '%' { + sz = 1 + continue + } + // "%%" is not a format directive. + if i+1 < len(format) && format[i+1] == '%' { + sz = 2 + continue + } + sz, isW = parsePrintfVerb(format[i:]) + if isW { + if idx >= 0 { + ok = false + } else { + idx = n + } + // "Replace" the last character, the 'w', with a 'v'. + p := i + sz - 1 + format = format[:p] + "v" + format[p+1:] + } + n++ + } + return idx, format, ok +} + +// Parse the printf verb starting with a % at s[0]. +// Return how many bytes it occupies and whether the verb is 'w'. +func parsePrintfVerb(s string) (int, bool) { + // Assume only that the directive is a sequence of non-letters followed by a single letter. + sz := 0 + var r rune + for i := 1; i < len(s); i += sz { + r, sz = utf8.DecodeRuneInString(s[i:]) + if unicode.IsLetter(r) { + return i + sz, r == 'w' + } + } + return len(s), false +} + +type noWrapError struct { + msg string + err error + frame Frame +} + +func (e *noWrapError) Error() string { + return fmt.Sprint(e) +} + +func (e *noWrapError) Format(s fmt.State, v rune) { FormatError(e, s, v) } + +func (e *noWrapError) FormatError(p Printer) (next error) { + p.Print(e.msg) + e.frame.Format(p) + return e.err +} + +type wrapError struct { + msg string + err error + frame Frame +} + +func (e *wrapError) Error() string { + return fmt.Sprint(e) +} + +func (e *wrapError) Format(s fmt.State, v rune) { FormatError(e, s, v) } + +func (e *wrapError) FormatError(p Printer) (next error) { + p.Print(e.msg) + e.frame.Format(p) + return e.err +} + +func (e *wrapError) Unwrap() error { + return e.err +} diff --git a/vendor/golang.org/x/xerrors/format.go b/vendor/golang.org/x/xerrors/format.go new file mode 100644 index 000000000..1bc9c26b9 --- /dev/null +++ b/vendor/golang.org/x/xerrors/format.go @@ -0,0 +1,34 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package xerrors + +// A Formatter formats error messages. +type Formatter interface { + error + + // FormatError prints the receiver's first error and returns the next error in + // the error chain, if any. + FormatError(p Printer) (next error) +} + +// A Printer formats error messages. +// +// The most common implementation of Printer is the one provided by package fmt +// during Printf (as of Go 1.13). Localization packages such as golang.org/x/text/message +// typically provide their own implementations. +type Printer interface { + // Print appends args to the message output. + Print(args ...interface{}) + + // Printf writes a formatted string. + Printf(format string, args ...interface{}) + + // Detail reports whether error detail is requested. + // After the first call to Detail, all text written to the Printer + // is formatted as additional detail, or ignored when + // detail has not been requested. + // If Detail returns false, the caller can avoid printing the detail at all. + Detail() bool +} diff --git a/vendor/golang.org/x/xerrors/frame.go b/vendor/golang.org/x/xerrors/frame.go new file mode 100644 index 000000000..0de628ec5 --- /dev/null +++ b/vendor/golang.org/x/xerrors/frame.go @@ -0,0 +1,56 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package xerrors + +import ( + "runtime" +) + +// A Frame contains part of a call stack. +type Frame struct { + // Make room for three PCs: the one we were asked for, what it called, + // and possibly a PC for skipPleaseUseCallersFrames. See: + // https://go.googlesource.com/go/+/032678e0fb/src/runtime/extern.go#169 + frames [3]uintptr +} + +// Caller returns a Frame that describes a frame on the caller's stack. +// The argument skip is the number of frames to skip over. +// Caller(0) returns the frame for the caller of Caller. +func Caller(skip int) Frame { + var s Frame + runtime.Callers(skip+1, s.frames[:]) + return s +} + +// location reports the file, line, and function of a frame. +// +// The returned function may be "" even if file and line are not. +func (f Frame) location() (function, file string, line int) { + frames := runtime.CallersFrames(f.frames[:]) + if _, ok := frames.Next(); !ok { + return "", "", 0 + } + fr, ok := frames.Next() + if !ok { + return "", "", 0 + } + return fr.Function, fr.File, fr.Line +} + +// Format prints the stack as error detail. +// It should be called from an error's Format implementation +// after printing any other error detail. +func (f Frame) Format(p Printer) { + if p.Detail() { + function, file, line := f.location() + if function != "" { + p.Printf("%s\n ", function) + } + if file != "" { + p.Printf("%s:%d\n", file, line) + } + } +} diff --git a/vendor/golang.org/x/xerrors/internal/internal.go b/vendor/golang.org/x/xerrors/internal/internal.go new file mode 100644 index 000000000..89f4eca5d --- /dev/null +++ b/vendor/golang.org/x/xerrors/internal/internal.go @@ -0,0 +1,8 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package internal + +// EnableTrace indicates whether stack information should be recorded in errors. +var EnableTrace = true diff --git a/vendor/golang.org/x/xerrors/wrap.go b/vendor/golang.org/x/xerrors/wrap.go new file mode 100644 index 000000000..9842758ca --- /dev/null +++ b/vendor/golang.org/x/xerrors/wrap.go @@ -0,0 +1,112 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package xerrors + +import ( + "reflect" +) + +// A Wrapper provides context around another error. +type Wrapper interface { + // Unwrap returns the next error in the error chain. + // If there is no next error, Unwrap returns nil. + Unwrap() error +} + +// Opaque returns an error with the same error formatting as err +// but that does not match err and cannot be unwrapped. +func Opaque(err error) error { + return noWrapper{err} +} + +type noWrapper struct { + error +} + +func (e noWrapper) FormatError(p Printer) (next error) { + if f, ok := e.error.(Formatter); ok { + return f.FormatError(p) + } + p.Print(e.error) + return nil +} + +// Unwrap returns the result of calling the Unwrap method on err, if err implements +// Unwrap. Otherwise, Unwrap returns nil. +// +// Deprecated: As of Go 1.13, use errors.Unwrap instead. +func Unwrap(err error) error { + u, ok := err.(Wrapper) + if !ok { + return nil + } + return u.Unwrap() +} + +// Is reports whether any error in err's chain matches target. +// +// An error is considered to match a target if it is equal to that target or if +// it implements a method Is(error) bool such that Is(target) returns true. +// +// Deprecated: As of Go 1.13, use errors.Is instead. +func Is(err, target error) bool { + if target == nil { + return err == target + } + + isComparable := reflect.TypeOf(target).Comparable() + for { + if isComparable && err == target { + return true + } + if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) { + return true + } + // TODO: consider supporing target.Is(err). This would allow + // user-definable predicates, but also may allow for coping with sloppy + // APIs, thereby making it easier to get away with them. + if err = Unwrap(err); err == nil { + return false + } + } +} + +// As finds the first error in err's chain that matches the type to which target +// points, and if so, sets the target to its value and returns true. An error +// matches a type if it is assignable to the target type, or if it has a method +// As(interface{}) bool such that As(target) returns true. As will panic if target +// is not a non-nil pointer to a type which implements error or is of interface type. +// +// The As method should set the target to its value and return true if err +// matches the type to which target points. +// +// Deprecated: As of Go 1.13, use errors.As instead. +func As(err error, target interface{}) bool { + if target == nil { + panic("errors: target cannot be nil") + } + val := reflect.ValueOf(target) + typ := val.Type() + if typ.Kind() != reflect.Ptr || val.IsNil() { + panic("errors: target must be a non-nil pointer") + } + if e := typ.Elem(); e.Kind() != reflect.Interface && !e.Implements(errorType) { + panic("errors: *target must be interface or implement error") + } + targetType := typ.Elem() + for err != nil { + if reflect.TypeOf(err).AssignableTo(targetType) { + val.Elem().Set(reflect.ValueOf(err)) + return true + } + if x, ok := err.(interface{ As(interface{}) bool }); ok && x.As(target) { + return true + } + err = Unwrap(err) + } + return false +} + +var errorType = reflect.TypeOf((*error)(nil)).Elem() diff --git a/vendor/modules.txt b/vendor/modules.txt index 59c9d8633..1e26b8aa0 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -349,6 +349,8 @@ github.com/golang/groupcache/singleflight # github.com/golang/mock v1.6.0 ## explicit; go 1.11 github.com/golang/mock/gomock +github.com/golang/mock/mockgen +github.com/golang/mock/mockgen/model # github.com/golang/protobuf v1.5.3 ## explicit; go 1.9 github.com/golang/protobuf/proto @@ -365,7 +367,7 @@ github.com/google/btree # github.com/google/gopacket v1.1.19 ## explicit; go 1.12 github.com/google/gopacket/routing -# github.com/google/pprof v0.0.0-20231023181126-ff6d637d2a7b +# github.com/google/pprof v0.0.0-20230705174524-200ffdc848b8 ## explicit; go 1.19 github.com/google/pprof/profile # github.com/google/uuid v1.3.0 @@ -397,10 +399,9 @@ github.com/hashicorp/go-version ## explicit; go 1.12 github.com/hashicorp/golang-lru github.com/hashicorp/golang-lru/simplelru -# github.com/hashicorp/golang-lru/v2 v2.0.5 +# github.com/hashicorp/golang-lru/v2 v2.0.2 ## explicit; go 1.18 github.com/hashicorp/golang-lru/v2 -github.com/hashicorp/golang-lru/v2/internal github.com/hashicorp/golang-lru/v2/simplelru # github.com/holiman/bloomfilter/v2 v2.0.3 ## explicit; go 1.15 @@ -411,7 +412,7 @@ github.com/holiman/uint256 # github.com/huandu/xstrings v1.3.2 ## explicit; go 1.12 github.com/huandu/xstrings -# github.com/huin/goupnp v1.3.0 +# github.com/huin/goupnp v1.2.0 ## explicit; go 1.14 github.com/huin/goupnp github.com/huin/goupnp/dcps/internetgateway1 @@ -451,7 +452,7 @@ github.com/keighl/metabolize # github.com/kilic/bls12-381 v0.0.0-20200607163746-32e1441c8a9f ## explicit; go 1.12 github.com/kilic/bls12-381 -# github.com/klauspost/compress v1.17.2 +# github.com/klauspost/compress v1.16.7 ## explicit; go 1.18 github.com/klauspost/compress github.com/klauspost/compress/fse @@ -495,8 +496,8 @@ github.com/libp2p/go-cidranger/net # github.com/libp2p/go-flow-metrics v0.1.0 ## explicit; go 1.17 github.com/libp2p/go-flow-metrics -# github.com/libp2p/go-libp2p v0.32.2 -## explicit; go 1.20 +# github.com/libp2p/go-libp2p v0.29.2 +## explicit; go 1.19 github.com/libp2p/go-libp2p github.com/libp2p/go-libp2p/config github.com/libp2p/go-libp2p/core/canonicallog @@ -522,7 +523,6 @@ github.com/libp2p/go-libp2p/core/sec github.com/libp2p/go-libp2p/core/sec/insecure github.com/libp2p/go-libp2p/core/sec/insecure/pb github.com/libp2p/go-libp2p/core/transport -github.com/libp2p/go-libp2p/internal/sha256 github.com/libp2p/go-libp2p/p2p/discovery/backoff github.com/libp2p/go-libp2p/p2p/host/autonat github.com/libp2p/go-libp2p/p2p/host/autonat/pb @@ -537,6 +537,7 @@ github.com/libp2p/go-libp2p/p2p/host/relaysvc github.com/libp2p/go-libp2p/p2p/host/resource-manager github.com/libp2p/go-libp2p/p2p/host/routed github.com/libp2p/go-libp2p/p2p/metricshelper +github.com/libp2p/go-libp2p/p2p/muxer/mplex github.com/libp2p/go-libp2p/p2p/muxer/yamux github.com/libp2p/go-libp2p/p2p/net/connmgr github.com/libp2p/go-libp2p/p2p/net/nat @@ -565,11 +566,8 @@ github.com/libp2p/go-libp2p/p2p/transport/webtransport # github.com/libp2p/go-libp2p-asn-util v0.3.0 ## explicit; go 1.19 github.com/libp2p/go-libp2p-asn-util -# github.com/libp2p/go-libp2p-mplex v0.9.0 -## explicit; go 1.20 -github.com/libp2p/go-libp2p-mplex -# github.com/libp2p/go-libp2p-pubsub v0.10.0 -## explicit; go 1.20 +# github.com/libp2p/go-libp2p-pubsub v0.9.3 +## explicit; go 1.19 github.com/libp2p/go-libp2p-pubsub github.com/libp2p/go-libp2p-pubsub/pb github.com/libp2p/go-libp2p-pubsub/timecache @@ -587,8 +585,8 @@ github.com/libp2p/go-nat # github.com/libp2p/go-netroute v0.2.1 ## explicit; go 1.18 github.com/libp2p/go-netroute -# github.com/libp2p/go-reuseport v0.4.0 -## explicit; go 1.20 +# github.com/libp2p/go-reuseport v0.3.0 +## explicit; go 1.19 github.com/libp2p/go-reuseport # github.com/libp2p/go-yamux/v4 v4.0.1 ## explicit; go 1.18 @@ -611,7 +609,7 @@ github.com/mat/besticon/ico # github.com/mattn/go-colorable v0.1.8 ## explicit; go 1.13 github.com/mattn/go-colorable -# github.com/mattn/go-isatty v0.0.20 +# github.com/mattn/go-isatty v0.0.19 ## explicit; go 1.15 github.com/mattn/go-isatty # github.com/mattn/go-runewidth v0.0.13 @@ -623,7 +621,7 @@ github.com/matttproud/golang_protobuf_extensions/pbutil # github.com/meirf/gopart v0.0.0-20180520194036-37e9492a85a8 ## explicit github.com/meirf/gopart -# github.com/miekg/dns v1.1.56 +# github.com/miekg/dns v1.1.55 ## explicit; go 1.19 github.com/miekg/dns # github.com/mikioh/tcpinfo v0.0.0-20190314235526-30a79bb1804b @@ -653,8 +651,8 @@ github.com/multiformats/go-base32 # github.com/multiformats/go-base36 v0.2.0 ## explicit; go 1.18 github.com/multiformats/go-base36 -# github.com/multiformats/go-multiaddr v0.12.0 -## explicit; go 1.20 +# github.com/multiformats/go-multiaddr v0.10.1 +## explicit; go 1.19 github.com/multiformats/go-multiaddr github.com/multiformats/go-multiaddr/net # github.com/multiformats/go-multiaddr-dns v0.3.1 @@ -680,8 +678,8 @@ github.com/multiformats/go-multihash/register/miniosha256 github.com/multiformats/go-multihash/register/murmur3 github.com/multiformats/go-multihash/register/sha256 github.com/multiformats/go-multihash/register/sha3 -# github.com/multiformats/go-multistream v0.5.0 -## explicit; go 1.20 +# github.com/multiformats/go-multistream v0.4.1 +## explicit; go 1.19 github.com/multiformats/go-multistream # github.com/multiformats/go-varint v0.0.7 ## explicit; go 1.18 @@ -701,7 +699,7 @@ github.com/olekukonko/tablewriter # github.com/oliamb/cutter v0.2.2 ## explicit github.com/oliamb/cutter -# github.com/onsi/ginkgo/v2 v2.13.0 +# github.com/onsi/ginkgo/v2 v2.11.0 ## explicit; go 1.18 github.com/onsi/ginkgo/v2/config github.com/onsi/ginkgo/v2/formatter @@ -719,7 +717,7 @@ github.com/onsi/ginkgo/v2/internal/interrupt_handler github.com/onsi/ginkgo/v2/internal/parallel_support github.com/onsi/ginkgo/v2/reporters github.com/onsi/ginkgo/v2/types -# github.com/opencontainers/runtime-spec v1.1.0 +# github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417 ## explicit github.com/opencontainers/runtime-spec/specs-go # github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 @@ -728,14 +726,13 @@ github.com/pbnjay/memory # github.com/pborman/uuid v1.2.0 ## explicit github.com/pborman/uuid -# github.com/pion/datachannel v1.5.5 +# github.com/pion/datachannel v1.5.2 ## explicit; go 1.13 github.com/pion/datachannel -# github.com/pion/dtls/v2 v2.2.7 +# github.com/pion/dtls/v2 v2.1.2 ## explicit; go 1.13 github.com/pion/dtls/v2 github.com/pion/dtls/v2/internal/ciphersuite -github.com/pion/dtls/v2/internal/ciphersuite/types github.com/pion/dtls/v2/internal/closer github.com/pion/dtls/v2/internal/util github.com/pion/dtls/v2/pkg/crypto/ccm @@ -752,61 +749,52 @@ github.com/pion/dtls/v2/pkg/protocol/alert github.com/pion/dtls/v2/pkg/protocol/extension github.com/pion/dtls/v2/pkg/protocol/handshake github.com/pion/dtls/v2/pkg/protocol/recordlayer -# github.com/pion/ice/v2 v2.3.6 +# github.com/pion/ice/v2 v2.1.20 ## explicit; go 1.13 github.com/pion/ice/v2 -github.com/pion/ice/v2/internal/atomic -github.com/pion/ice/v2/internal/fakenet -github.com/pion/ice/v2/internal/stun -# github.com/pion/interceptor v0.1.17 +# github.com/pion/interceptor v0.1.7 ## explicit; go 1.15 github.com/pion/interceptor -github.com/pion/interceptor/internal/ntp github.com/pion/interceptor/pkg/nack github.com/pion/interceptor/pkg/report github.com/pion/interceptor/pkg/twcc # github.com/pion/logging v0.2.2 ## explicit; go 1.12 github.com/pion/logging -# github.com/pion/mdns v0.0.7 +# github.com/pion/mdns v0.0.5 ## explicit; go 1.12 github.com/pion/mdns # github.com/pion/randutil v0.1.0 ## explicit; go 1.14 github.com/pion/randutil -# github.com/pion/rtcp v1.2.10 +# github.com/pion/rtcp v1.2.9 ## explicit; go 1.13 github.com/pion/rtcp -# github.com/pion/rtp v1.7.13 +# github.com/pion/rtp v1.7.4 ## explicit; go 1.13 github.com/pion/rtp github.com/pion/rtp/codecs -github.com/pion/rtp/pkg/obu -# github.com/pion/sctp v1.8.7 +# github.com/pion/sctp v1.8.2 ## explicit; go 1.13 github.com/pion/sctp -# github.com/pion/sdp/v3 v3.0.6 +# github.com/pion/sdp/v3 v3.0.4 ## explicit; go 1.13 github.com/pion/sdp/v3 -# github.com/pion/srtp/v2 v2.0.15 +# github.com/pion/srtp/v2 v2.0.5 ## explicit; go 1.14 github.com/pion/srtp/v2 -# github.com/pion/stun v0.6.0 +# github.com/pion/stun v0.3.5 ## explicit; go 1.12 github.com/pion/stun github.com/pion/stun/internal/hmac -# github.com/pion/transport/v2 v2.2.1 +# github.com/pion/transport v0.13.0 ## explicit; go 1.12 -github.com/pion/transport/v2 -github.com/pion/transport/v2/connctx -github.com/pion/transport/v2/deadline -github.com/pion/transport/v2/packetio -github.com/pion/transport/v2/replaydetector -github.com/pion/transport/v2/stdnet -github.com/pion/transport/v2/udp -github.com/pion/transport/v2/utils/xor -github.com/pion/transport/v2/vnet -# github.com/pion/turn/v2 v2.1.0 +github.com/pion/transport/connctx +github.com/pion/transport/deadline +github.com/pion/transport/packetio +github.com/pion/transport/replaydetector +github.com/pion/transport/vnet +# github.com/pion/turn/v2 v2.0.6 ## explicit; go 1.13 github.com/pion/turn/v2 github.com/pion/turn/v2/internal/allocation @@ -814,7 +802,10 @@ github.com/pion/turn/v2/internal/client github.com/pion/turn/v2/internal/ipnet github.com/pion/turn/v2/internal/proto github.com/pion/turn/v2/internal/server -# github.com/pion/webrtc/v3 v3.2.9 +# github.com/pion/udp v0.1.1 +## explicit; go 1.14 +github.com/pion/udp +# github.com/pion/webrtc/v3 v3.1.24-0.20220208053747-94262c1b2b38 ## explicit; go 1.13 github.com/pion/webrtc/v3 github.com/pion/webrtc/v3/internal/fmtp @@ -852,11 +843,14 @@ github.com/prometheus/tsdb/fileutil # github.com/quic-go/qpack v0.4.0 ## explicit; go 1.18 github.com/quic-go/qpack -# github.com/quic-go/qtls-go1-20 v0.3.4 +# github.com/quic-go/qtls-go1-19 v0.3.3 +## explicit; go 1.19 +github.com/quic-go/qtls-go1-19 +# github.com/quic-go/qtls-go1-20 v0.2.3 ## explicit; go 1.20 github.com/quic-go/qtls-go1-20 -# github.com/quic-go/quic-go v0.39.4 -## explicit; go 1.20 +# github.com/quic-go/quic-go v0.36.4 +## explicit; go 1.19 github.com/quic-go/quic-go github.com/quic-go/quic-go/http3 github.com/quic-go/quic-go/internal/ackhandler @@ -874,8 +868,8 @@ github.com/quic-go/quic-go/internal/wire github.com/quic-go/quic-go/logging github.com/quic-go/quic-go/qlog github.com/quic-go/quic-go/quicvarint -# github.com/quic-go/webtransport-go v0.6.0 -## explicit; go 1.20 +# github.com/quic-go/webtransport-go v0.5.3 +## explicit; go 1.18 github.com/quic-go/webtransport-go # github.com/raulk/go-watchdog v1.3.0 ## explicit; go 1.15 @@ -942,7 +936,7 @@ github.com/status-im/migrate/v4/database/postgres github.com/status-im/migrate/v4/database/sqlcipher github.com/status-im/migrate/v4/internal/url github.com/status-im/migrate/v4/source/go_bindata -# github.com/status-im/rendezvous v1.3.8-0.20240110194857-cc5be22bf83e +# github.com/status-im/rendezvous v1.3.7 ## explicit; go 1.18 github.com/status-im/rendezvous github.com/status-im/rendezvous/protocol @@ -1021,13 +1015,13 @@ github.com/vacp2p/mvds/transport github.com/waku-org/go-discover/discover github.com/waku-org/go-discover/discover/v4wire github.com/waku-org/go-discover/discover/v5wire -# github.com/waku-org/go-libp2p-rendezvous v0.0.0-20240110193335-a67d1cc760a0 +# github.com/waku-org/go-libp2p-rendezvous v0.0.0-20230628220917-7b4e5ae4c0e7 ## explicit; go 1.19 github.com/waku-org/go-libp2p-rendezvous github.com/waku-org/go-libp2p-rendezvous/db github.com/waku-org/go-libp2p-rendezvous/pb -# github.com/waku-org/go-waku v0.8.1-0.20240112174027-faf046e059a5 -## explicit; go 1.20 +# github.com/waku-org/go-waku v0.8.1-0.20240104144340-585648c4eefe +## explicit; go 1.19 github.com/waku-org/go-waku/logging github.com/waku-org/go-waku/waku/persistence github.com/waku-org/go-waku/waku/v2/discv5 @@ -1150,29 +1144,25 @@ go.etcd.io/bbolt # go.uber.org/atomic v1.11.0 ## explicit; go 1.18 go.uber.org/atomic -# go.uber.org/dig v1.17.1 -## explicit; go 1.20 +# go.uber.org/dig v1.17.0 +## explicit; go 1.18 go.uber.org/dig go.uber.org/dig/internal/digerror go.uber.org/dig/internal/digreflect go.uber.org/dig/internal/dot go.uber.org/dig/internal/graph -# go.uber.org/fx v1.20.1 -## explicit; go 1.20 +# go.uber.org/fx v1.20.0 +## explicit; go 1.19 go.uber.org/fx go.uber.org/fx/fxevent go.uber.org/fx/internal/fxclock go.uber.org/fx/internal/fxlog go.uber.org/fx/internal/fxreflect go.uber.org/fx/internal/lifecycle -# go.uber.org/mock v0.3.0 -## explicit; go 1.20 -go.uber.org/mock/mockgen -go.uber.org/mock/mockgen/model # go.uber.org/multierr v1.11.0 ## explicit; go 1.19 go.uber.org/multierr -# go.uber.org/zap v1.26.0 +# go.uber.org/zap v1.24.0 ## explicit; go 1.19 go.uber.org/zap go.uber.org/zap/buffer @@ -1180,10 +1170,8 @@ go.uber.org/zap/internal go.uber.org/zap/internal/bufferpool go.uber.org/zap/internal/color go.uber.org/zap/internal/exit -go.uber.org/zap/internal/pool -go.uber.org/zap/internal/stacktrace go.uber.org/zap/zapcore -# golang.org/x/crypto v0.14.0 +# golang.org/x/crypto v0.12.0 ## explicit; go 1.17 golang.org/x/crypto/blake2b golang.org/x/crypto/blake2s @@ -1202,11 +1190,10 @@ golang.org/x/crypto/salsa20/salsa golang.org/x/crypto/scrypt golang.org/x/crypto/sha3 golang.org/x/crypto/ssh/terminal -# golang.org/x/exp v0.0.0-20231006140011-7918f672742d +# golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 ## explicit; go 1.20 golang.org/x/exp/constraints golang.org/x/exp/maps -golang.org/x/exp/rand golang.org/x/exp/slices # golang.org/x/image v0.0.0-20210220032944-ac19c3e999fb ## explicit; go 1.12 @@ -1223,13 +1210,13 @@ golang.org/x/image/vector golang.org/x/image/vp8 golang.org/x/image/vp8l golang.org/x/image/webp -# golang.org/x/mod v0.13.0 -## explicit; go 1.18 +# golang.org/x/mod v0.12.0 +## explicit; go 1.17 golang.org/x/mod/internal/lazyregexp golang.org/x/mod/modfile golang.org/x/mod/module golang.org/x/mod/semver -# golang.org/x/net v0.17.0 +# golang.org/x/net v0.14.0 ## explicit; go 1.17 golang.org/x/net/bpf golang.org/x/net/dns/dnsmessage @@ -1247,21 +1234,22 @@ golang.org/x/net/ipv6 golang.org/x/net/proxy golang.org/x/net/publicsuffix golang.org/x/net/route -# golang.org/x/sync v0.4.0 +# golang.org/x/sync v0.3.0 ## explicit; go 1.17 golang.org/x/sync/errgroup golang.org/x/sync/singleflight -# golang.org/x/sys v0.13.0 +# golang.org/x/sys v0.11.0 ## explicit; go 1.17 golang.org/x/sys/cpu golang.org/x/sys/execabs +golang.org/x/sys/internal/unsafeheader golang.org/x/sys/plan9 golang.org/x/sys/unix golang.org/x/sys/windows -# golang.org/x/term v0.13.0 +# golang.org/x/term v0.11.0 ## explicit; go 1.17 golang.org/x/term -# golang.org/x/text v0.13.0 +# golang.org/x/text v0.12.0 ## explicit; go 1.17 golang.org/x/text/cases golang.org/x/text/encoding @@ -1288,7 +1276,7 @@ golang.org/x/text/unicode/norm # golang.org/x/time v0.0.0-20220922220347-f3bd1da661af ## explicit golang.org/x/time/rate -# golang.org/x/tools v0.14.0 +# golang.org/x/tools v0.12.1-0.20230818130535-1517d1a3ba60 ## explicit; go 1.18 golang.org/x/tools/cmd/goimports golang.org/x/tools/go/ast/astutil @@ -1313,6 +1301,10 @@ golang.org/x/tools/internal/pkgbits golang.org/x/tools/internal/tokeninternal golang.org/x/tools/internal/typeparams golang.org/x/tools/internal/typesinternal +# golang.org/x/xerrors v0.0.0-20220609144429-65e65417b02f +## explicit; go 1.17 +golang.org/x/xerrors +golang.org/x/xerrors/internal # google.golang.org/protobuf v1.31.0 ## explicit; go 1.11 google.golang.org/protobuf/cmd/protoc-gen-go diff --git a/wakuv2/waku.go b/wakuv2/waku.go index 6a93bd271..fe0718ad3 100644 --- a/wakuv2/waku.go +++ b/wakuv2/waku.go @@ -1815,11 +1815,11 @@ func FormatPeerStats(wakuNode *node.WakuNode, peers node.PeerStats) map[string]t peerInfo := wakuNode.Host().Peerstore().PeerInfo(k) wakuV2Peer := types.WakuV2Peer{} wakuV2Peer.Protocols = v - hostInfo, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/p2p/%s", k.String())) + hostInfo, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/p2p/%s", k.Pretty())) for _, addr := range peerInfo.Addrs { wakuV2Peer.Addresses = append(wakuV2Peer.Addresses, addr.Encapsulate(hostInfo).String()) } - p[k.String()] = wakuV2Peer + p[k.Pretty()] = wakuV2Peer } return p }