diff --git a/go.mod b/go.mod index 716532523..511015217 100644 --- a/go.mod +++ b/go.mod @@ -37,7 +37,7 @@ 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.35.0 + github.com/libp2p/go-libp2p v0.35.2 github.com/libp2p/go-libp2p-pubsub v0.11.0 github.com/lucasb-eyer/go-colorful v1.0.3 github.com/mat/besticon v0.0.0-20210314201728-1579f269edb7 @@ -96,7 +96,7 @@ require ( github.com/schollz/peerdiscovery v1.7.0 github.com/siphiuel/lc-proxy-wrapper v0.0.0-20230516150924-246507cee8c7 github.com/urfave/cli/v2 v2.27.2 - github.com/waku-org/go-waku v0.8.1-0.20240705124012-8df5a0337a1e + github.com/waku-org/go-waku v0.8.1-0.20240711160252-9412af28dd81 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 @@ -171,7 +171,7 @@ require ( github.com/google/gopacket v1.1.19 // indirect github.com/google/pprof v0.0.0-20240207164012-fb44976bdcd5 // indirect github.com/gorilla/securecookie v1.1.1 // indirect - github.com/gorilla/websocket v1.5.1 // indirect + github.com/gorilla/websocket v1.5.3 // 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 @@ -222,7 +222,7 @@ require ( github.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect github.com/pion/datachannel v1.5.6 // indirect github.com/pion/dtls/v2 v2.2.11 // indirect - github.com/pion/ice/v2 v2.3.24 // indirect + github.com/pion/ice/v2 v2.3.25 // indirect github.com/pion/interceptor v0.1.29 // indirect github.com/pion/logging v0.2.2 // indirect github.com/pion/mdns v0.0.12 // indirect @@ -277,7 +277,7 @@ require ( 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.21.1 // indirect + go.uber.org/fx v1.22.1 // indirect go.uber.org/mock v0.4.0 // indirect golang.org/x/mod v0.17.0 // indirect golang.org/x/sync v0.7.0 // indirect diff --git a/go.sum b/go.sum index 3e185b46d..023138815 100644 --- a/go.sum +++ b/go.sum @@ -1076,8 +1076,8 @@ github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/z github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY= -github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gosuri/uilive v0.0.0-20170323041506-ac356e6e42cd/go.mod h1:qkLSc0A5EXSP6B04TrN4oQoxqFI7A8XvoXSlJi8cwk8= github.com/gosuri/uilive v0.0.3/go.mod h1:qkLSc0A5EXSP6B04TrN4oQoxqFI7A8XvoXSlJi8cwk8= github.com/gosuri/uiprogress v0.0.0-20170224063937-d0567a9d84a1/go.mod h1:C1RTYn4Sc7iEyf6j8ft5dyoZ4212h8G1ol9QQluh5+0= @@ -1360,8 +1360,8 @@ github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6 github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= 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.35.0 h1:1xS1Bkr9X7GtdvV6ntLnDV9xB1kNjHK1lZ0eaO6gnhc= -github.com/libp2p/go-libp2p v0.35.0/go.mod h1:snyJQix4ET6Tj+LeI0VPjjxTtdWpeOhYt5lEY0KirkQ= +github.com/libp2p/go-libp2p v0.35.2 h1:287oHbuplkrLdAF+syB0n/qDgd50AUBtEODqS0e0HDs= +github.com/libp2p/go-libp2p v0.35.2/go.mod h1:RKCDNt30IkFipGL0tl8wQW/3zVWEGFUZo8g2gAKxwjU= github.com/libp2p/go-libp2p-asn-util v0.4.1 h1:xqL7++IKD9TBFMgnLPZR6/6iYhawHKHl950SO9L6n94= github.com/libp2p/go-libp2p-asn-util v0.4.1/go.mod h1:d/NI6XZ9qxw67b4e+NgpQexCIiFYJjErASrYW4PFDN8= github.com/libp2p/go-libp2p-testing v0.12.0 h1:EPvBb4kKMWO29qP4mZGyhVzUyR25dvfUIK5WDu6iPUA= @@ -1713,8 +1713,8 @@ github.com/pion/ice/v2 v2.1.7/go.mod h1:kV4EODVD5ux2z8XncbLHIOtcXKtYXVgLVCeVqnpo 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/go.mod h1:hEAldRzBhTtAfvlU1V/2/nLCMvveQWFKPNCop+63/Iw= -github.com/pion/ice/v2 v2.3.24 h1:RYgzhH/u5lH0XO+ABatVKCtRd+4U1GEaCXSMjNr13tI= -github.com/pion/ice/v2 v2.3.24/go.mod h1:KXJJcZK7E8WzrBEYnV4UtqEZsGeWfHxsNqhVcVvgjxw= +github.com/pion/ice/v2 v2.3.25 h1:M5rJA07dqhi3nobJIg+uPtcVjFECTrhcR3n0ns8kDZs= +github.com/pion/ice/v2 v2.3.25/go.mod h1:KXJJcZK7E8WzrBEYnV4UtqEZsGeWfHxsNqhVcVvgjxw= 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= @@ -2143,8 +2143,8 @@ github.com/waku-org/go-libp2p-pubsub v0.0.0-20240703191659-2cbb09eac9b5 h1:9u16E github.com/waku-org/go-libp2p-pubsub v0.0.0-20240703191659-2cbb09eac9b5/go.mod h1:QEb+hEV9WL9wCiUAnpY29FZR6W3zK8qYlaml8R4q6gQ= 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.20240705124012-8df5a0337a1e h1:aqZA60QlYiMBcgqHEx6ksof4A6+KspMIqoXu/ACXmKU= -github.com/waku-org/go-waku v0.8.1-0.20240705124012-8df5a0337a1e/go.mod h1:nLQmeqztw19wmJI9rpXY6Lx81yYE/qOAd1qZsrAK2A8= +github.com/waku-org/go-waku v0.8.1-0.20240711160252-9412af28dd81 h1:0YV8dN8qdNV7MwcMB2s9ky826Tv5KAK3Untabf4RIAU= +github.com/waku-org/go-waku v0.8.1-0.20240711160252-9412af28dd81/go.mod h1:ugDTCvcP6oJ9mTtINeo4EIsnC3oQCU3RsctNKu4MsRw= 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= @@ -2268,8 +2268,8 @@ 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.21.1 h1:RqBh3cYdzZS0uqwVeEjOX2p73dddLpym315myy/Bpb0= -go.uber.org/fx v1.21.1/go.mod h1:HT2M7d7RHo+ebKGh9NRcrsrHHfpZ60nW3QRubMRfv48= +go.uber.org/fx v1.22.1 h1:nvvln7mwyT5s1q201YE29V/BFrGor6vMiDNpU/78Mys= +go.uber.org/fx v1.22.1/go.mod h1:HT2M7d7RHo+ebKGh9NRcrsrHHfpZ60nW3QRubMRfv48= 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= diff --git a/vendor/github.com/gorilla/websocket/.editorconfig b/vendor/github.com/gorilla/websocket/.editorconfig deleted file mode 100644 index 2940ec92a..000000000 --- a/vendor/github.com/gorilla/websocket/.editorconfig +++ /dev/null @@ -1,20 +0,0 @@ -; https://editorconfig.org/ - -root = true - -[*] -insert_final_newline = true -charset = utf-8 -trim_trailing_whitespace = true -indent_style = space -indent_size = 2 - -[{Makefile,go.mod,go.sum,*.go,.gitmodules}] -indent_style = tab -indent_size = 4 - -[*.md] -indent_size = 4 -trim_trailing_whitespace = false - -eclint_indent_style = unset diff --git a/vendor/github.com/gorilla/websocket/.gitignore b/vendor/github.com/gorilla/websocket/.gitignore index 84039fec6..cd3fcd1ef 100644 --- a/vendor/github.com/gorilla/websocket/.gitignore +++ b/vendor/github.com/gorilla/websocket/.gitignore @@ -1 +1,25 @@ -coverage.coverprofile +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe + +.idea/ +*.iml diff --git a/vendor/github.com/gorilla/websocket/.golangci.yml b/vendor/github.com/gorilla/websocket/.golangci.yml deleted file mode 100644 index 34882139e..000000000 --- a/vendor/github.com/gorilla/websocket/.golangci.yml +++ /dev/null @@ -1,3 +0,0 @@ -run: - skip-dirs: - - examples/*.go diff --git a/vendor/github.com/gorilla/websocket/AUTHORS b/vendor/github.com/gorilla/websocket/AUTHORS new file mode 100644 index 000000000..1931f4006 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/AUTHORS @@ -0,0 +1,9 @@ +# This is the official list of Gorilla WebSocket authors for copyright +# purposes. +# +# Please keep the list sorted. + +Gary Burd +Google LLC (https://opensource.google.com/) +Joachim Bauch + diff --git a/vendor/github.com/gorilla/websocket/LICENSE b/vendor/github.com/gorilla/websocket/LICENSE index bb9d80bc9..9171c9722 100644 --- a/vendor/github.com/gorilla/websocket/LICENSE +++ b/vendor/github.com/gorilla/websocket/LICENSE @@ -1,27 +1,22 @@ -Copyright (c) 2023 The Gorilla Authors. All rights reserved. +Copyright (c) 2013 The Gorilla WebSocket 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: +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. + Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. -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 + 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. + +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 HOLDER 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/gorilla/websocket/Makefile b/vendor/github.com/gorilla/websocket/Makefile deleted file mode 100644 index 603a63f50..000000000 --- a/vendor/github.com/gorilla/websocket/Makefile +++ /dev/null @@ -1,34 +0,0 @@ -GO_LINT=$(shell which golangci-lint 2> /dev/null || echo '') -GO_LINT_URI=github.com/golangci/golangci-lint/cmd/golangci-lint@latest - -GO_SEC=$(shell which gosec 2> /dev/null || echo '') -GO_SEC_URI=github.com/securego/gosec/v2/cmd/gosec@latest - -GO_VULNCHECK=$(shell which govulncheck 2> /dev/null || echo '') -GO_VULNCHECK_URI=golang.org/x/vuln/cmd/govulncheck@latest - -.PHONY: golangci-lint -golangci-lint: - $(if $(GO_LINT), ,go install $(GO_LINT_URI)) - @echo "##### Running golangci-lint" - golangci-lint run -v - -.PHONY: gosec -gosec: - $(if $(GO_SEC), ,go install $(GO_SEC_URI)) - @echo "##### Running gosec" - gosec -exclude-dir examples ./... - -.PHONY: govulncheck -govulncheck: - $(if $(GO_VULNCHECK), ,go install $(GO_VULNCHECK_URI)) - @echo "##### Running govulncheck" - govulncheck ./... - -.PHONY: verify -verify: golangci-lint gosec govulncheck - -.PHONY: test -test: - @echo "##### Running tests" - go test -race -cover -coverprofile=coverage.coverprofile -covermode=atomic -v ./... diff --git a/vendor/github.com/gorilla/websocket/README.md b/vendor/github.com/gorilla/websocket/README.md index 1fd5e9c4e..d33ed7fdd 100644 --- a/vendor/github.com/gorilla/websocket/README.md +++ b/vendor/github.com/gorilla/websocket/README.md @@ -1,13 +1,10 @@ -# gorilla/websocket +# Gorilla WebSocket -![testing](https://github.com/gorilla/websocket/actions/workflows/test.yml/badge.svg) -[![codecov](https://codecov.io/github/gorilla/websocket/branch/main/graph/badge.svg)](https://codecov.io/github/gorilla/websocket) -[![godoc](https://godoc.org/github.com/gorilla/websocket?status.svg)](https://godoc.org/github.com/gorilla/websocket) -[![sourcegraph](https://sourcegraph.com/github.com/gorilla/websocket/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/websocket?badge) +[![GoDoc](https://godoc.org/github.com/gorilla/websocket?status.svg)](https://godoc.org/github.com/gorilla/websocket) +[![CircleCI](https://circleci.com/gh/gorilla/websocket.svg?style=svg)](https://circleci.com/gh/gorilla/websocket) -Gorilla WebSocket is a [Go](http://golang.org/) implementation of the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. - -![Gorilla Logo](https://github.com/gorilla/.github/assets/53367916/d92caabf-98e0-473e-bfbf-ab554ba435e5) +Gorilla WebSocket is a [Go](http://golang.org/) implementation of the +[WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. ### Documentation @@ -17,7 +14,6 @@ Gorilla WebSocket is a [Go](http://golang.org/) implementation of the [WebSocket * [Command example](https://github.com/gorilla/websocket/tree/master/examples/command) * [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo) * [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch) -* [Write buffer pool example](https://github.com/gorilla/websocket/tree/master/examples/bufferpool) ### Status @@ -34,3 +30,4 @@ package API is stable. The Gorilla WebSocket package passes the server tests in the [Autobahn Test Suite](https://github.com/crossbario/autobahn-testsuite) using the application in the [examples/autobahn subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn). + diff --git a/vendor/github.com/gorilla/websocket/client.go b/vendor/github.com/gorilla/websocket/client.go index 815b0ca5c..04fdafee1 100644 --- a/vendor/github.com/gorilla/websocket/client.go +++ b/vendor/github.com/gorilla/websocket/client.go @@ -11,16 +11,13 @@ import ( "errors" "fmt" "io" - "log" - + "io/ioutil" "net" "net/http" "net/http/httptrace" "net/url" "strings" "time" - - "golang.org/x/net/proxy" ) // ErrBadHandshake is returned when the server response to opening handshake is @@ -228,7 +225,6 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h k == "Connection" || k == "Sec-Websocket-Key" || k == "Sec-Websocket-Version" || - //#nosec G101 (CWE-798): Potential HTTP request smuggling via parameter pollution k == "Sec-Websocket-Extensions" || (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0): return nil, nil, errors.New("websocket: duplicate header not allowed: " + k) @@ -294,9 +290,7 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h } err = c.SetDeadline(deadline) if err != nil { - if err := c.Close(); err != nil { - log.Printf("websocket: failed to close network connection: %v", err) - } + c.Close() return nil, err } return c, nil @@ -310,7 +304,7 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h return nil, nil, err } if proxyURL != nil { - dialer, err := proxy.FromURL(proxyURL, netDialerFunc(netDial)) + dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial)) if err != nil { return nil, nil, err } @@ -336,9 +330,7 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h defer func() { if netConn != nil { - if err := netConn.Close(); err != nil { - log.Printf("websocket: failed to close network connection: %v", err) - } + netConn.Close() } }() @@ -408,7 +400,7 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h // debugging. buf := make([]byte, 1024) n, _ := io.ReadFull(resp.Body, buf) - resp.Body = io.NopCloser(bytes.NewReader(buf[:n])) + resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n])) return nil, resp, ErrBadHandshake } @@ -426,19 +418,17 @@ func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader h break } - resp.Body = io.NopCloser(bytes.NewReader([]byte{})) + resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol") - if err := netConn.SetDeadline(time.Time{}); err != nil { - return nil, nil, err - } + netConn.SetDeadline(time.Time{}) netConn = nil // to avoid close in defer. return conn, resp, nil } func cloneTLSConfig(cfg *tls.Config) *tls.Config { if cfg == nil { - return &tls.Config{MinVersion: tls.VersionTLS12} + return &tls.Config{} } return cfg.Clone() } diff --git a/vendor/github.com/gorilla/websocket/compression.go b/vendor/github.com/gorilla/websocket/compression.go index 9fed0ef52..813ffb1e8 100644 --- a/vendor/github.com/gorilla/websocket/compression.go +++ b/vendor/github.com/gorilla/websocket/compression.go @@ -8,7 +8,6 @@ import ( "compress/flate" "errors" "io" - "log" "strings" "sync" ) @@ -34,9 +33,7 @@ func decompressNoContextTakeover(r io.Reader) io.ReadCloser { "\x01\x00\x00\xff\xff" fr, _ := flateReaderPool.Get().(io.ReadCloser) - if err := fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil); err != nil { - panic(err) - } + fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil) return &flateReadWrapper{fr} } @@ -135,9 +132,7 @@ func (r *flateReadWrapper) Read(p []byte) (int, error) { // Preemptively place the reader back in the pool. This helps with // scenarios where the application does not call NextReader() soon after // this final read. - if err := r.Close(); err != nil { - log.Printf("websocket: flateReadWrapper.Close() returned error: %v", err) - } + r.Close() } return n, err } diff --git a/vendor/github.com/gorilla/websocket/conn.go b/vendor/github.com/gorilla/websocket/conn.go index 221e6cf79..5161ef81f 100644 --- a/vendor/github.com/gorilla/websocket/conn.go +++ b/vendor/github.com/gorilla/websocket/conn.go @@ -6,11 +6,11 @@ package websocket import ( "bufio" - "crypto/rand" "encoding/binary" "errors" "io" - "log" + "io/ioutil" + "math/rand" "net" "strconv" "strings" @@ -181,20 +181,13 @@ var ( errInvalidControlFrame = errors.New("websocket: invalid control frame") ) -// maskRand is an io.Reader for generating mask bytes. The reader is initialized -// to crypto/rand Reader. Tests swap the reader to a math/rand reader for -// reproducible results. -var maskRand = rand.Reader - -// newMaskKey returns a new 32 bit value for masking client frames. func newMaskKey() [4]byte { - var k [4]byte - _, _ = io.ReadFull(maskRand, k[:]) - return k + n := rand.Uint32() + return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)} } func hideTempErr(err error) error { - if e, ok := err.(net.Error); ok { + if e, ok := err.(net.Error); ok && e.Temporary() { err = &netError{msg: e.Error(), timeout: e.Timeout()} } return err @@ -379,9 +372,7 @@ func (c *Conn) read(n int) ([]byte, error) { if err == io.EOF { err = errUnexpectedEOF } - if _, err := c.br.Discard(len(p)); err != nil { - return p, err - } + c.br.Discard(len(p)) return p, err } @@ -396,9 +387,7 @@ func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error return err } - if err := c.conn.SetWriteDeadline(deadline); err != nil { - return c.writeFatal(err) - } + c.conn.SetWriteDeadline(deadline) if len(buf1) == 0 { _, err = c.conn.Write(buf0) } else { @@ -408,7 +397,7 @@ func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error return c.writeFatal(err) } if frameType == CloseMessage { - _ = c.writeFatal(ErrCloseSent) + c.writeFatal(ErrCloseSent) } return nil } @@ -449,7 +438,7 @@ func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) er d := 1000 * time.Hour if !deadline.IsZero() { - d = time.Until(deadline) + d = deadline.Sub(time.Now()) if d < 0 { return errWriteTimeout } @@ -471,15 +460,13 @@ func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) er return err } - if err := c.conn.SetWriteDeadline(deadline); err != nil { - return c.writeFatal(err) - } + c.conn.SetWriteDeadline(deadline) _, err = c.conn.Write(buf) if err != nil { return c.writeFatal(err) } if messageType == CloseMessage { - _ = c.writeFatal(ErrCloseSent) + c.writeFatal(ErrCloseSent) } return err } @@ -490,9 +477,7 @@ func (c *Conn) beginMessage(mw *messageWriter, messageType int) error { // probably better to return an error in this situation, but we cannot // change this without breaking existing applications. if c.writer != nil { - if err := c.writer.Close(); err != nil { - log.Printf("websocket: discarding writer close error: %v", err) - } + c.writer.Close() c.writer = nil } @@ -645,7 +630,7 @@ func (w *messageWriter) flushFrame(final bool, extra []byte) error { } if final { - _ = w.endMessage(errWriteClosed) + w.endMessage(errWriteClosed) return nil } @@ -810,7 +795,7 @@ func (c *Conn) advanceFrame() (int, error) { // 1. Skip remainder of previous frame. if c.readRemaining > 0 { - if _, err := io.CopyN(io.Discard, c.br, c.readRemaining); err != nil { + if _, err := io.CopyN(ioutil.Discard, c.br, c.readRemaining); err != nil { return noFrame, err } } @@ -832,9 +817,7 @@ func (c *Conn) advanceFrame() (int, error) { rsv2 := p[0]&rsv2Bit != 0 rsv3 := p[0]&rsv3Bit != 0 mask := p[1]&maskBit != 0 - if err := c.setReadRemaining(int64(p[1] & 0x7f)); err != nil { - return noFrame, err - } + c.setReadRemaining(int64(p[1] & 0x7f)) c.readDecompress = false if rsv1 { @@ -939,9 +922,7 @@ func (c *Conn) advanceFrame() (int, error) { } if c.readLimit > 0 && c.readLength > c.readLimit { - if err := c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)); err != nil { - return noFrame, err - } + c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)) return noFrame, ErrReadLimit } @@ -953,9 +934,7 @@ func (c *Conn) advanceFrame() (int, error) { var payload []byte if c.readRemaining > 0 { payload, err = c.read(int(c.readRemaining)) - if err := c.setReadRemaining(0); err != nil { - return noFrame, err - } + c.setReadRemaining(0) if err != nil { return noFrame, err } @@ -1002,9 +981,7 @@ func (c *Conn) handleProtocolError(message string) error { if len(data) > maxControlFramePayloadSize { data = data[:maxControlFramePayloadSize] } - if err := c.WriteControl(CloseMessage, data, time.Now().Add(writeWait)); err != nil { - return err - } + c.WriteControl(CloseMessage, data, time.Now().Add(writeWait)) return errors.New("websocket: " + message) } @@ -1021,9 +998,7 @@ func (c *Conn) handleProtocolError(message string) error { func (c *Conn) NextReader() (messageType int, r io.Reader, err error) { // Close previous reader, only relevant for decompression. if c.reader != nil { - if err := c.reader.Close(); err != nil { - log.Printf("websocket: discarding reader close error: %v", err) - } + c.reader.Close() c.reader = nil } @@ -1079,9 +1054,7 @@ func (r *messageReader) Read(b []byte) (int, error) { } rem := c.readRemaining rem -= int64(n) - if err := c.setReadRemaining(rem); err != nil { - return 0, err - } + c.setReadRemaining(rem) if c.readRemaining > 0 && c.readErr == io.EOF { c.readErr = errUnexpectedEOF } @@ -1121,7 +1094,7 @@ func (c *Conn) ReadMessage() (messageType int, p []byte, err error) { if err != nil { return messageType, nil, err } - p, err = io.ReadAll(r) + p, err = ioutil.ReadAll(r) return messageType, p, err } @@ -1163,9 +1136,7 @@ func (c *Conn) SetCloseHandler(h func(code int, text string) error) { if h == nil { h = func(code int, text string) error { message := FormatCloseMessage(code, "") - if err := c.WriteControl(CloseMessage, message, time.Now().Add(writeWait)); err != nil { - return err - } + c.WriteControl(CloseMessage, message, time.Now().Add(writeWait)) return nil } } @@ -1190,7 +1161,7 @@ func (c *Conn) SetPingHandler(h func(appData string) error) { err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait)) if err == ErrCloseSent { return nil - } else if _, ok := err.(net.Error); ok { + } else if e, ok := err.(net.Error); ok && e.Temporary() { return nil } return err diff --git a/vendor/github.com/gorilla/websocket/mask.go b/vendor/github.com/gorilla/websocket/mask.go index 67d0968be..d0742bf2a 100644 --- a/vendor/github.com/gorilla/websocket/mask.go +++ b/vendor/github.com/gorilla/websocket/mask.go @@ -9,7 +9,6 @@ package websocket import "unsafe" -// #nosec G103 -- (CWE-242) Has been audited const wordSize = int(unsafe.Sizeof(uintptr(0))) func maskBytes(key [4]byte, pos int, b []byte) int { @@ -23,7 +22,6 @@ func maskBytes(key [4]byte, pos int, b []byte) int { } // Mask one byte at a time to word boundary. - //#nosec G103 -- (CWE-242) Has been audited if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 { n = wordSize - n for i := range b[:n] { @@ -38,13 +36,11 @@ func maskBytes(key [4]byte, pos int, b []byte) int { for i := range k { k[i] = key[(pos+i)&3] } - //#nosec G103 -- (CWE-242) Has been audited kw := *(*uintptr)(unsafe.Pointer(&k)) // Mask one word at a time. n := (len(b) / wordSize) * wordSize for i := 0; i < n; i += wordSize { - //#nosec G103 -- (CWE-242) Has been audited *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw } diff --git a/vendor/github.com/gorilla/websocket/proxy.go b/vendor/github.com/gorilla/websocket/proxy.go index 80f55d1ea..e0f466b72 100644 --- a/vendor/github.com/gorilla/websocket/proxy.go +++ b/vendor/github.com/gorilla/websocket/proxy.go @@ -8,13 +8,10 @@ import ( "bufio" "encoding/base64" "errors" - "log" "net" "net/http" "net/url" "strings" - - "golang.org/x/net/proxy" ) type netDialerFunc func(network, addr string) (net.Conn, error) @@ -24,7 +21,7 @@ func (fn netDialerFunc) Dial(network, addr string) (net.Conn, error) { } func init() { - proxy.RegisterDialerType("http", func(proxyURL *url.URL, forwardDialer proxy.Dialer) (proxy.Dialer, error) { + proxy_RegisterDialerType("http", func(proxyURL *url.URL, forwardDialer proxy_Dialer) (proxy_Dialer, error) { return &httpProxyDialer{proxyURL: proxyURL, forwardDial: forwardDialer.Dial}, nil }) } @@ -58,9 +55,7 @@ func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) } if err := connectReq.Write(conn); err != nil { - if err := conn.Close(); err != nil { - log.Printf("httpProxyDialer: failed to close connection: %v", err) - } + conn.Close() return nil, err } @@ -69,16 +64,12 @@ func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) br := bufio.NewReader(conn) resp, err := http.ReadResponse(br, connectReq) if err != nil { - if err := conn.Close(); err != nil { - log.Printf("httpProxyDialer: failed to close connection: %v", err) - } + conn.Close() return nil, err } if resp.StatusCode != 200 { - if err := conn.Close(); err != nil { - log.Printf("httpProxyDialer: failed to close connection: %v", err) - } + conn.Close() f := strings.SplitN(resp.Status, " ", 2) return nil, errors.New(f[1]) } diff --git a/vendor/github.com/gorilla/websocket/server.go b/vendor/github.com/gorilla/websocket/server.go index 1e720e1da..bb3359743 100644 --- a/vendor/github.com/gorilla/websocket/server.go +++ b/vendor/github.com/gorilla/websocket/server.go @@ -8,7 +8,6 @@ import ( "bufio" "errors" "io" - "log" "net/http" "net/url" "strings" @@ -184,9 +183,7 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade } if brw.Reader.Buffered() > 0 { - if err := netConn.Close(); err != nil { - log.Printf("websocket: failed to close network connection: %v", err) - } + netConn.Close() return nil, errors.New("websocket: client sent data before handshake is complete") } @@ -251,34 +248,17 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade p = append(p, "\r\n"...) // Clear deadlines set by HTTP server. - if err := netConn.SetDeadline(time.Time{}); err != nil { - if err := netConn.Close(); err != nil { - log.Printf("websocket: failed to close network connection: %v", err) - } - return nil, err - } + netConn.SetDeadline(time.Time{}) if u.HandshakeTimeout > 0 { - if err := netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)); err != nil { - if err := netConn.Close(); err != nil { - log.Printf("websocket: failed to close network connection: %v", err) - } - return nil, err - } + netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)) } if _, err = netConn.Write(p); err != nil { - if err := netConn.Close(); err != nil { - log.Printf("websocket: failed to close network connection: %v", err) - } + netConn.Close() return nil, err } if u.HandshakeTimeout > 0 { - if err := netConn.SetWriteDeadline(time.Time{}); err != nil { - if err := netConn.Close(); err != nil { - log.Printf("websocket: failed to close network connection: %v", err) - } - return nil, err - } + netConn.SetWriteDeadline(time.Time{}) } return c, nil @@ -376,12 +356,8 @@ func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte { // bufio.Writer's underlying writer. var wh writeHook bw.Reset(&wh) - if err := bw.WriteByte(0); err != nil { - panic(err) - } - if err := bw.Flush(); err != nil { - log.Printf("websocket: bufioWriterBuffer: Flush: %v", err) - } + bw.WriteByte(0) + bw.Flush() bw.Reset(originalWriter) diff --git a/vendor/github.com/gorilla/websocket/tls_handshake.go b/vendor/github.com/gorilla/websocket/tls_handshake.go index 7f3864534..a62b68ccb 100644 --- a/vendor/github.com/gorilla/websocket/tls_handshake.go +++ b/vendor/github.com/gorilla/websocket/tls_handshake.go @@ -1,3 +1,6 @@ +//go:build go1.17 +// +build go1.17 + package websocket import ( diff --git a/vendor/github.com/gorilla/websocket/tls_handshake_116.go b/vendor/github.com/gorilla/websocket/tls_handshake_116.go new file mode 100644 index 000000000..e1b2b44f6 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/tls_handshake_116.go @@ -0,0 +1,21 @@ +//go:build !go1.17 +// +build !go1.17 + +package websocket + +import ( + "context" + "crypto/tls" +) + +func doHandshake(ctx context.Context, tlsConn *tls.Conn, cfg *tls.Config) error { + if err := tlsConn.Handshake(); err != nil { + return err + } + if !cfg.InsecureSkipVerify { + if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil { + return err + } + } + return nil +} diff --git a/vendor/github.com/gorilla/websocket/util.go b/vendor/github.com/gorilla/websocket/util.go index 9b1a629bf..31a5dee64 100644 --- a/vendor/github.com/gorilla/websocket/util.go +++ b/vendor/github.com/gorilla/websocket/util.go @@ -6,7 +6,7 @@ package websocket import ( "crypto/rand" - "crypto/sha1" //#nosec G505 -- (CWE-327) https://datatracker.ietf.org/doc/html/rfc6455#page-54 + "crypto/sha1" "encoding/base64" "io" "net/http" @@ -17,7 +17,7 @@ import ( var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") func computeAcceptKey(challengeKey string) string { - h := sha1.New() //#nosec G401 -- (CWE-326) https://datatracker.ietf.org/doc/html/rfc6455#page-54 + h := sha1.New() h.Write([]byte(challengeKey)) h.Write(keyGUID) return base64.StdEncoding.EncodeToString(h.Sum(nil)) diff --git a/vendor/github.com/gorilla/websocket/x_net_proxy.go b/vendor/github.com/gorilla/websocket/x_net_proxy.go new file mode 100644 index 000000000..2e668f6b8 --- /dev/null +++ b/vendor/github.com/gorilla/websocket/x_net_proxy.go @@ -0,0 +1,473 @@ +// Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT. +//go:generate bundle -o x_net_proxy.go golang.org/x/net/proxy + +// Package proxy provides support for a variety of protocols to proxy network +// data. +// + +package websocket + +import ( + "errors" + "io" + "net" + "net/url" + "os" + "strconv" + "strings" + "sync" +) + +type proxy_direct struct{} + +// Direct is a direct proxy: one that makes network connections directly. +var proxy_Direct = proxy_direct{} + +func (proxy_direct) Dial(network, addr string) (net.Conn, error) { + return net.Dial(network, addr) +} + +// A PerHost directs connections to a default Dialer unless the host name +// requested matches one of a number of exceptions. +type proxy_PerHost struct { + def, bypass proxy_Dialer + + bypassNetworks []*net.IPNet + bypassIPs []net.IP + bypassZones []string + bypassHosts []string +} + +// NewPerHost returns a PerHost Dialer that directs connections to either +// defaultDialer or bypass, depending on whether the connection matches one of +// the configured rules. +func proxy_NewPerHost(defaultDialer, bypass proxy_Dialer) *proxy_PerHost { + return &proxy_PerHost{ + def: defaultDialer, + bypass: bypass, + } +} + +// Dial connects to the address addr on the given network through either +// defaultDialer or bypass. +func (p *proxy_PerHost) Dial(network, addr string) (c net.Conn, err error) { + host, _, err := net.SplitHostPort(addr) + if err != nil { + return nil, err + } + + return p.dialerForRequest(host).Dial(network, addr) +} + +func (p *proxy_PerHost) dialerForRequest(host string) proxy_Dialer { + if ip := net.ParseIP(host); ip != nil { + for _, net := range p.bypassNetworks { + if net.Contains(ip) { + return p.bypass + } + } + for _, bypassIP := range p.bypassIPs { + if bypassIP.Equal(ip) { + return p.bypass + } + } + return p.def + } + + for _, zone := range p.bypassZones { + if strings.HasSuffix(host, zone) { + return p.bypass + } + if host == zone[1:] { + // For a zone ".example.com", we match "example.com" + // too. + return p.bypass + } + } + for _, bypassHost := range p.bypassHosts { + if bypassHost == host { + return p.bypass + } + } + return p.def +} + +// AddFromString parses a string that contains comma-separated values +// specifying hosts that should use the bypass proxy. Each value is either an +// IP address, a CIDR range, a zone (*.example.com) or a host name +// (localhost). A best effort is made to parse the string and errors are +// ignored. +func (p *proxy_PerHost) AddFromString(s string) { + hosts := strings.Split(s, ",") + for _, host := range hosts { + host = strings.TrimSpace(host) + if len(host) == 0 { + continue + } + if strings.Contains(host, "/") { + // We assume that it's a CIDR address like 127.0.0.0/8 + if _, net, err := net.ParseCIDR(host); err == nil { + p.AddNetwork(net) + } + continue + } + if ip := net.ParseIP(host); ip != nil { + p.AddIP(ip) + continue + } + if strings.HasPrefix(host, "*.") { + p.AddZone(host[1:]) + continue + } + p.AddHost(host) + } +} + +// AddIP specifies an IP address that will use the bypass proxy. Note that +// this will only take effect if a literal IP address is dialed. A connection +// to a named host will never match an IP. +func (p *proxy_PerHost) AddIP(ip net.IP) { + p.bypassIPs = append(p.bypassIPs, ip) +} + +// AddNetwork specifies an IP range that will use the bypass proxy. Note that +// this will only take effect if a literal IP address is dialed. A connection +// to a named host will never match. +func (p *proxy_PerHost) AddNetwork(net *net.IPNet) { + p.bypassNetworks = append(p.bypassNetworks, net) +} + +// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of +// "example.com" matches "example.com" and all of its subdomains. +func (p *proxy_PerHost) AddZone(zone string) { + if strings.HasSuffix(zone, ".") { + zone = zone[:len(zone)-1] + } + if !strings.HasPrefix(zone, ".") { + zone = "." + zone + } + p.bypassZones = append(p.bypassZones, zone) +} + +// AddHost specifies a host name that will use the bypass proxy. +func (p *proxy_PerHost) AddHost(host string) { + if strings.HasSuffix(host, ".") { + host = host[:len(host)-1] + } + p.bypassHosts = append(p.bypassHosts, host) +} + +// A Dialer is a means to establish a connection. +type proxy_Dialer interface { + // Dial connects to the given address via the proxy. + Dial(network, addr string) (c net.Conn, err error) +} + +// Auth contains authentication parameters that specific Dialers may require. +type proxy_Auth struct { + User, Password string +} + +// FromEnvironment returns the dialer specified by the proxy related variables in +// the environment. +func proxy_FromEnvironment() proxy_Dialer { + allProxy := proxy_allProxyEnv.Get() + if len(allProxy) == 0 { + return proxy_Direct + } + + proxyURL, err := url.Parse(allProxy) + if err != nil { + return proxy_Direct + } + proxy, err := proxy_FromURL(proxyURL, proxy_Direct) + if err != nil { + return proxy_Direct + } + + noProxy := proxy_noProxyEnv.Get() + if len(noProxy) == 0 { + return proxy + } + + perHost := proxy_NewPerHost(proxy, proxy_Direct) + perHost.AddFromString(noProxy) + return perHost +} + +// proxySchemes is a map from URL schemes to a function that creates a Dialer +// from a URL with such a scheme. +var proxy_proxySchemes map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error) + +// RegisterDialerType takes a URL scheme and a function to generate Dialers from +// a URL with that scheme and a forwarding Dialer. Registered schemes are used +// by FromURL. +func proxy_RegisterDialerType(scheme string, f func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) { + if proxy_proxySchemes == nil { + proxy_proxySchemes = make(map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) + } + proxy_proxySchemes[scheme] = f +} + +// FromURL returns a Dialer given a URL specification and an underlying +// Dialer for it to make network requests. +func proxy_FromURL(u *url.URL, forward proxy_Dialer) (proxy_Dialer, error) { + var auth *proxy_Auth + if u.User != nil { + auth = new(proxy_Auth) + auth.User = u.User.Username() + if p, ok := u.User.Password(); ok { + auth.Password = p + } + } + + switch u.Scheme { + case "socks5": + return proxy_SOCKS5("tcp", u.Host, auth, forward) + } + + // If the scheme doesn't match any of the built-in schemes, see if it + // was registered by another package. + if proxy_proxySchemes != nil { + if f, ok := proxy_proxySchemes[u.Scheme]; ok { + return f(u, forward) + } + } + + return nil, errors.New("proxy: unknown scheme: " + u.Scheme) +} + +var ( + proxy_allProxyEnv = &proxy_envOnce{ + names: []string{"ALL_PROXY", "all_proxy"}, + } + proxy_noProxyEnv = &proxy_envOnce{ + names: []string{"NO_PROXY", "no_proxy"}, + } +) + +// envOnce looks up an environment variable (optionally by multiple +// names) once. It mitigates expensive lookups on some platforms +// (e.g. Windows). +// (Borrowed from net/http/transport.go) +type proxy_envOnce struct { + names []string + once sync.Once + val string +} + +func (e *proxy_envOnce) Get() string { + e.once.Do(e.init) + return e.val +} + +func (e *proxy_envOnce) init() { + for _, n := range e.names { + e.val = os.Getenv(n) + if e.val != "" { + return + } + } +} + +// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address +// with an optional username and password. See RFC 1928 and RFC 1929. +func proxy_SOCKS5(network, addr string, auth *proxy_Auth, forward proxy_Dialer) (proxy_Dialer, error) { + s := &proxy_socks5{ + network: network, + addr: addr, + forward: forward, + } + if auth != nil { + s.user = auth.User + s.password = auth.Password + } + + return s, nil +} + +type proxy_socks5 struct { + user, password string + network, addr string + forward proxy_Dialer +} + +const proxy_socks5Version = 5 + +const ( + proxy_socks5AuthNone = 0 + proxy_socks5AuthPassword = 2 +) + +const proxy_socks5Connect = 1 + +const ( + proxy_socks5IP4 = 1 + proxy_socks5Domain = 3 + proxy_socks5IP6 = 4 +) + +var proxy_socks5Errors = []string{ + "", + "general failure", + "connection forbidden", + "network unreachable", + "host unreachable", + "connection refused", + "TTL expired", + "command not supported", + "address type not supported", +} + +// Dial connects to the address addr on the given network via the SOCKS5 proxy. +func (s *proxy_socks5) Dial(network, addr string) (net.Conn, error) { + switch network { + case "tcp", "tcp6", "tcp4": + default: + return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network) + } + + conn, err := s.forward.Dial(s.network, s.addr) + if err != nil { + return nil, err + } + if err := s.connect(conn, addr); err != nil { + conn.Close() + return nil, err + } + return conn, nil +} + +// connect takes an existing connection to a socks5 proxy server, +// and commands the server to extend that connection to target, +// which must be a canonical address with a host and port. +func (s *proxy_socks5) connect(conn net.Conn, target string) error { + host, portStr, err := net.SplitHostPort(target) + if err != nil { + return err + } + + port, err := strconv.Atoi(portStr) + if err != nil { + return errors.New("proxy: failed to parse port number: " + portStr) + } + if port < 1 || port > 0xffff { + return errors.New("proxy: port number out of range: " + portStr) + } + + // the size here is just an estimate + buf := make([]byte, 0, 6+len(host)) + + buf = append(buf, proxy_socks5Version) + if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 { + buf = append(buf, 2 /* num auth methods */, proxy_socks5AuthNone, proxy_socks5AuthPassword) + } else { + buf = append(buf, 1 /* num auth methods */, proxy_socks5AuthNone) + } + + if _, err := conn.Write(buf); err != nil { + return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if _, err := io.ReadFull(conn, buf[:2]); err != nil { + return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + if buf[0] != 5 { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0]))) + } + if buf[1] == 0xff { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication") + } + + // See RFC 1929 + if buf[1] == proxy_socks5AuthPassword { + buf = buf[:0] + buf = append(buf, 1 /* password protocol version */) + buf = append(buf, uint8(len(s.user))) + buf = append(buf, s.user...) + buf = append(buf, uint8(len(s.password))) + buf = append(buf, s.password...) + + if _, err := conn.Write(buf); err != nil { + return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if _, err := io.ReadFull(conn, buf[:2]); err != nil { + return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if buf[1] != 0 { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password") + } + } + + buf = buf[:0] + buf = append(buf, proxy_socks5Version, proxy_socks5Connect, 0 /* reserved */) + + if ip := net.ParseIP(host); ip != nil { + if ip4 := ip.To4(); ip4 != nil { + buf = append(buf, proxy_socks5IP4) + ip = ip4 + } else { + buf = append(buf, proxy_socks5IP6) + } + buf = append(buf, ip...) + } else { + if len(host) > 255 { + return errors.New("proxy: destination host name too long: " + host) + } + buf = append(buf, proxy_socks5Domain) + buf = append(buf, byte(len(host))) + buf = append(buf, host...) + } + buf = append(buf, byte(port>>8), byte(port)) + + if _, err := conn.Write(buf); err != nil { + return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + if _, err := io.ReadFull(conn, buf[:4]); err != nil { + return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + failure := "unknown error" + if int(buf[1]) < len(proxy_socks5Errors) { + failure = proxy_socks5Errors[buf[1]] + } + + if len(failure) > 0 { + return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure) + } + + bytesToDiscard := 0 + switch buf[3] { + case proxy_socks5IP4: + bytesToDiscard = net.IPv4len + case proxy_socks5IP6: + bytesToDiscard = net.IPv6len + case proxy_socks5Domain: + _, err := io.ReadFull(conn, buf[:1]) + if err != nil { + return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + bytesToDiscard = int(buf[0]) + default: + return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr) + } + + if cap(buf) < bytesToDiscard { + buf = make([]byte, bytesToDiscard) + } else { + buf = buf[:bytesToDiscard] + } + if _, err := io.ReadFull(conn, buf); err != nil { + return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + // Also need to discard the port number + if _, err := io.ReadFull(conn, buf[:2]); err != nil { + return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error()) + } + + return nil +} diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/host/peerstore/pstoremem/protobook.go b/vendor/github.com/libp2p/go-libp2p/p2p/host/peerstore/pstoremem/protobook.go index 51c4b0282..b28ffe11b 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/host/peerstore/pstoremem/protobook.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/host/peerstore/pstoremem/protobook.go @@ -26,9 +26,6 @@ type memoryProtoBook struct { segments protoSegments maxProtos int - - lk sync.RWMutex - interned map[protocol.ID]protocol.ID } var _ pstore.ProtoBook = (*memoryProtoBook)(nil) @@ -44,7 +41,6 @@ func WithMaxProtocols(num int) ProtoBookOption { func NewProtoBook(opts ...ProtoBookOption) (*memoryProtoBook, error) { pb := &memoryProtoBook{ - interned: make(map[protocol.ID]protocol.ID, 256), segments: func() (ret protoSegments) { for i := range ret { ret[i] = &protoSegment{ @@ -53,7 +49,7 @@ func NewProtoBook(opts ...ProtoBookOption) (*memoryProtoBook, error) { } return ret }(), - maxProtos: 1024, + maxProtos: 128, } for _, opt := range opts { @@ -64,30 +60,6 @@ func NewProtoBook(opts ...ProtoBookOption) (*memoryProtoBook, error) { return pb, nil } -func (pb *memoryProtoBook) internProtocol(proto protocol.ID) protocol.ID { - // check if it is interned with the read lock - pb.lk.RLock() - interned, ok := pb.interned[proto] - pb.lk.RUnlock() - - if ok { - return interned - } - - // intern with the write lock - pb.lk.Lock() - defer pb.lk.Unlock() - - // check again in case it got interned in between locks - interned, ok = pb.interned[proto] - if ok { - return interned - } - - pb.interned[proto] = proto - return proto -} - func (pb *memoryProtoBook) SetProtocols(p peer.ID, protos ...protocol.ID) error { if len(protos) > pb.maxProtos { return errTooManyProtocols @@ -95,7 +67,7 @@ func (pb *memoryProtoBook) SetProtocols(p peer.ID, protos ...protocol.ID) error newprotos := make(map[protocol.ID]struct{}, len(protos)) for _, proto := range protos { - newprotos[pb.internProtocol(proto)] = struct{}{} + newprotos[proto] = struct{}{} } s := pb.segments.get(p) @@ -121,7 +93,7 @@ func (pb *memoryProtoBook) AddProtocols(p peer.ID, protos ...protocol.ID) error } for _, proto := range protos { - protomap[pb.internProtocol(proto)] = struct{}{} + protomap[proto] = struct{}{} } return nil } @@ -151,7 +123,10 @@ func (pb *memoryProtoBook) RemoveProtocols(p peer.ID, protos ...protocol.ID) err } for _, proto := range protos { - delete(protomap, pb.internProtocol(proto)) + delete(protomap, proto) + } + if len(protomap) == 0 { + delete(s.protocols, p) } return nil } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/host/pstoremanager/pstoremanager.go b/vendor/github.com/libp2p/go-libp2p/p2p/host/pstoremanager/pstoremanager.go index 93cc2a98d..f4a20f8ac 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/host/pstoremanager/pstoremanager.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/host/pstoremanager/pstoremanager.go @@ -121,10 +121,12 @@ func (m *PeerstoreManager) background(ctx context.Context, sub event.Subscriptio // Check that the peer is actually not connected at this point. // This avoids a race condition where the Connected notification // is processed after this time has fired. - if m.network.Connectedness(p) != network.Connected { + switch m.network.Connectedness(p) { + case network.Connected, network.Limited: + default: m.pstore.RemovePeer(p) - delete(disconnected, p) } + delete(disconnected, p) } } case <-ctx.Done(): diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/client/reservation.go b/vendor/github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/client/reservation.go index dbb924193..462c01d23 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/client/reservation.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/client/reservation.go @@ -93,10 +93,7 @@ func Reserve(ctx context.Context, h host.Host, ai peer.AddrInfo) (*Reservation, } if msg.GetType() != pbv2.HopMessage_STATUS { - return nil, ReservationError{ - Status: pbv2.Status_MALFORMED_MESSAGE, - Reason: fmt.Sprintf("unexpected relay response: not a status message (%d)", msg.GetType()), - err: err} + return nil, ReservationError{Status: pbv2.Status_MALFORMED_MESSAGE, Reason: fmt.Sprintf("unexpected relay response: not a status message (%d)", msg.GetType())} } if status := msg.GetStatus(); status != pbv2.Status_OK { @@ -130,7 +127,7 @@ func Reserve(ctx context.Context, h host.Host, ai peer.AddrInfo) (*Reservation, voucherBytes := rsvp.GetVoucher() if voucherBytes != nil { - _, rec, err := record.ConsumeEnvelope(voucherBytes, proto.RecordDomain) + env, rec, err := record.ConsumeEnvelope(voucherBytes, proto.RecordDomain) if err != nil { return nil, ReservationError{ Status: pbv2.Status_MALFORMED_MESSAGE, @@ -146,6 +143,27 @@ func Reserve(ctx context.Context, h host.Host, ai peer.AddrInfo) (*Reservation, Reason: fmt.Sprintf("unexpected voucher record type: %+T", rec), } } + signerPeerID, err := peer.IDFromPublicKey(env.PublicKey) + if err != nil { + return nil, ReservationError{ + Status: pbv2.Status_MALFORMED_MESSAGE, + Reason: fmt.Sprintf("invalid voucher signing public key: %s", err), + err: err, + } + } + if signerPeerID != voucher.Relay { + return nil, ReservationError{ + Status: pbv2.Status_MALFORMED_MESSAGE, + Reason: fmt.Sprintf("invalid voucher relay id: expected %s, got %s", signerPeerID, voucher.Relay), + } + } + if h.ID() != voucher.Peer { + return nil, ReservationError{ + Status: pbv2.Status_MALFORMED_MESSAGE, + Reason: fmt.Sprintf("invalid voucher peer id: expected %s, got %s", h.ID(), voucher.Peer), + } + + } result.Voucher = voucher } 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 a91cc4f92..e91fdee76 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 @@ -831,7 +831,7 @@ func (ids *idService) consumeMessage(mes *pb.Identify, c network.Conn, isPush bo ids.Host.Peerstore().UpdateAddrs(p, peerstore.TempAddrTTL, 0) ids.addrMu.Unlock() - log.Debugf("%s received listen addrs for %s: %s", c.LocalPeer(), c.RemotePeer(), lmaddrs) + log.Debugf("%s received listen addrs for %s: %s", c.LocalPeer(), c.RemotePeer(), addrs) // get protocol versions pv := mes.GetProtocolVersion() @@ -1064,18 +1064,23 @@ func (nn *netNotifiee) Disconnected(_ network.Network, c network.Conn) { func (nn *netNotifiee) Listen(n network.Network, a ma.Multiaddr) {} func (nn *netNotifiee) ListenClose(n network.Network, a ma.Multiaddr) {} -// filterAddrs filters the address slice based on the remove multiaddr: -// * if it's a localhost address, no filtering is applied -// * if it's a local network address, all localhost addresses are filtered out -// * if it's a public address, all localhost and local network addresses are filtered out +// filterAddrs filters the address slice based on the remote multiaddr: +// - if it's a localhost address, no filtering is applied +// - if it's a private network address, all localhost addresses are filtered out +// - if it's a public address, all non-public addresses are filtered out +// - if none of the above, (e.g. discard prefix), no filtering is applied. +// We can't do anything meaningful here so we do nothing. func filterAddrs(addrs []ma.Multiaddr, remote ma.Multiaddr) []ma.Multiaddr { - if manet.IsIPLoopback(remote) { + switch { + case manet.IsIPLoopback(remote): + return addrs + case manet.IsPrivateAddr(remote): + return ma.FilterAddrs(addrs, func(a ma.Multiaddr) bool { return !manet.IsIPLoopback(a) }) + case manet.IsPublicAddr(remote): + return ma.FilterAddrs(addrs, manet.IsPublicAddr) + default: return addrs } - if manet.IsPrivateAddr(remote) { - return ma.FilterAddrs(addrs, func(a ma.Multiaddr) bool { return !manet.IsIPLoopback(a) }) - } - return ma.FilterAddrs(addrs, manet.IsPublicAddr) } func trimHostAddrList(addrs []ma.Multiaddr, maxSize int) []ma.Multiaddr { 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 4437c4b01..fc1c100c8 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 @@ -452,6 +452,12 @@ func (o *ObservedAddrManager) removeConn(conn connMultiaddrs) { o.mu.Lock() defer o.mu.Unlock() + observedTWAddr, ok := o.connObservedTWAddrs[conn] + if !ok { + return + } + delete(o.connObservedTWAddrs, conn) + // normalize before obtaining the thinWaist so that we are always dealing // with the normalized form of the address localTW, err := thinWaistForm(o.normalize(conn.LocalMultiaddr())) @@ -467,11 +473,6 @@ func (o *ObservedAddrManager) removeConn(conn connMultiaddrs) { delete(o.localAddrs, string(localTW.Addr.Bytes())) } - observedTWAddr, ok := o.connObservedTWAddrs[conn] - if !ok { - return - } - delete(o.connObservedTWAddrs, conn) observer, err := getObserver(conn.RemoteMultiaddr()) if err != nil { return 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..0c6974135 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 @@ -51,8 +51,10 @@ func (l *listener) Accept() (tpt.CapableConn, error) { if err != nil { return nil, err } - c, err := l.setupConn(qconn) + c, err := l.wrapConn(qconn) if err != nil { + log.Debugf("failed to setup connection: %s", err) + qconn.CloseWithError(1, "") continue } l.transport.addConn(qconn, c) @@ -79,7 +81,10 @@ func (l *listener) Accept() (tpt.CapableConn, error) { } } -func (l *listener) setupConn(qconn quic.Connection) (*conn, error) { +// wrapConn wraps a QUIC connection into a libp2p [tpt.CapableConn]. +// If wrapping fails. The caller is responsible for cleaning up the +// connection. +func (l *listener) wrapConn(qconn quic.Connection) (*conn, error) { remoteMultiaddr, err := quicreuse.ToQuicMultiaddr(qconn.RemoteAddr(), qconn.ConnectionState().Version) if err != nil { return nil, err @@ -90,18 +95,16 @@ func (l *listener) setupConn(qconn quic.Connection) (*conn, error) { log.Debugw("resource manager blocked incoming connection", "addr", qconn.RemoteAddr(), "error", err) return nil, err } - c, err := l.setupConnWithScope(qconn, connScope, remoteMultiaddr) + c, err := l.wrapConnWithScope(qconn, connScope, remoteMultiaddr) if err != nil { connScope.Done() - qconn.CloseWithError(1, "") return nil, err } return c, nil } -func (l *listener) setupConnWithScope(qconn quic.Connection, connScope network.ConnManagementScope, remoteMultiaddr ma.Multiaddr) (*conn, error) { - +func (l *listener) wrapConnWithScope(qconn quic.Connection, connScope network.ConnManagementScope, remoteMultiaddr ma.Multiaddr) (*conn, error) { // The tls.Config used to establish this connection already verified the certificate chain. // Since we don't have any way of knowing which tls.Config was used though, // we have to re-determine the peer's identity here. diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webrtc/listener.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webrtc/listener.go index 1834fc812..3f465b34f 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webrtc/listener.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webrtc/listener.go @@ -330,7 +330,7 @@ func addOnConnectionStateChangeCallback(pc *webrtc.PeerConnection) <-chan error errC := make(chan error, 1) var once sync.Once pc.OnConnectionStateChange(func(state webrtc.PeerConnectionState) { - switch state { + switch pc.ConnectionState() { case webrtc.PeerConnectionStateConnected: once.Do(func() { close(errC) }) case webrtc.PeerConnectionStateFailed: diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webrtc/transport.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webrtc/transport.go index b04753eca..68a2988c7 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webrtc/transport.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webrtc/transport.go @@ -415,15 +415,17 @@ func genUfrag() string { uFragAlphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" uFragPrefix = "libp2p+webrtc+v1/" uFragIdLength = 32 - uFragIdOffset = len(uFragPrefix) - uFragLength = uFragIdOffset + uFragIdLength + uFragLength = len(uFragPrefix) + uFragIdLength ) seed := [8]byte{} rand.Read(seed[:]) r := mrand.New(mrand.NewSource(binary.BigEndian.Uint64(seed[:]))) b := make([]byte, uFragLength) - for i := uFragIdOffset; i < uFragLength; i++ { + for i := 0; i < len(uFragPrefix); i++ { + b[i] = uFragPrefix[i] + } + for i := len(uFragPrefix); i < uFragLength; i++ { b[i] = uFragAlphabet[r.Intn(len(uFragAlphabet))] } return string(b) diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/conn.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/conn.go index 0e83b1d16..052512471 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/conn.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/conn.go @@ -7,6 +7,7 @@ import ( tpt "github.com/libp2p/go-libp2p/core/transport" ma "github.com/multiformats/go-multiaddr" + "github.com/quic-go/quic-go" "github.com/quic-go/webtransport-go" ) @@ -31,16 +32,18 @@ type conn struct { session *webtransport.Session scope network.ConnManagementScope + qconn quic.Connection } var _ tpt.CapableConn = &conn{} -func newConn(tr *transport, sess *webtransport.Session, sconn *connSecurityMultiaddrs, scope network.ConnManagementScope) *conn { +func newConn(tr *transport, sess *webtransport.Session, sconn *connSecurityMultiaddrs, scope network.ConnManagementScope, qconn quic.Connection) *conn { return &conn{ connSecurityMultiaddrs: sconn, transport: tr, session: sess, scope: scope, + qconn: qconn, } } @@ -70,7 +73,9 @@ func (c *conn) allowWindowIncrease(size uint64) bool { func (c *conn) Close() error { c.scope.Done() c.transport.removeConn(c.session) - return c.session.CloseWithError(0, "") + err := c.session.CloseWithError(0, "") + _ = c.qconn.CloseWithError(1, "") + return err } func (c *conn) IsClosed() bool { return c.session.Context().Err() != nil } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/listener.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/listener.go index 2a7c3546f..ff611fe92 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/listener.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/listener.go @@ -15,12 +15,61 @@ import ( "github.com/libp2p/go-libp2p/p2p/transport/quicreuse" ma "github.com/multiformats/go-multiaddr" + "github.com/quic-go/quic-go" + "github.com/quic-go/quic-go/http3" "github.com/quic-go/webtransport-go" ) const queueLen = 16 const handshakeTimeout = 10 * time.Second +type connKey struct{} + +// negotiatingConn is a wrapper around a quic.Connection that lets us wrap it in +// our own context for the duration of the upgrade process. Upgrading a quic +// connection to an h3 connection to a webtransport session. +type negotiatingConn struct { + quic.Connection + ctx context.Context + cancel context.CancelFunc + // stopClose is a function that stops the connection from being closed when + // the context is done. Returns true if the connection close function was + // not called. + stopClose func() bool + err error +} + +func (c *negotiatingConn) Unwrap() (quic.Connection, error) { + defer c.cancel() + if c.stopClose != nil { + // unwrap the first time + if !c.stopClose() { + c.err = errTimeout + } + c.stopClose = nil + } + if c.err != nil { + return nil, c.err + } + return c.Connection, nil +} + +func wrapConn(ctx context.Context, c quic.Connection, handshakeTimeout time.Duration) *negotiatingConn { + ctx, cancel := context.WithTimeout(ctx, handshakeTimeout) + stopClose := context.AfterFunc(ctx, func() { + log.Debugf("failed to handshake on conn: %s", c.RemoteAddr()) + c.CloseWithError(1, "") + }) + return &negotiatingConn{ + Connection: c, + ctx: ctx, + cancel: cancel, + stopClose: stopClose, + } +} + +var errTimeout = errors.New("timeout") + type listener struct { transport *transport isStaticTLSConf bool @@ -56,6 +105,11 @@ func newListener(reuseListener quicreuse.Listener, t *transport, isStaticTLSConf addr: reuseListener.Addr(), multiaddr: localMultiaddr, server: webtransport.Server{ + H3: http3.Server{ + ConnContext: func(ctx context.Context, c quic.Connection) context.Context { + return context.WithValue(ctx, connKey{}, c) + }, + }, CheckOrigin: func(r *http.Request) bool { return true }, }, } @@ -71,7 +125,8 @@ func newListener(reuseListener quicreuse.Listener, t *transport, isStaticTLSConf log.Debugw("serving failed", "addr", ln.Addr(), "error", err) return } - go ln.server.ServeQUICConn(conn) + wrapped := wrapConn(ln.ctx, conn, t.handshakeTimeout) + go ln.server.ServeQUICConn(wrapped) } }() return ln, nil @@ -137,13 +192,32 @@ func (l *listener) httpHandlerWithConnScope(w http.ResponseWriter, r *http.Reque return err } - conn := newConn(l.transport, sess, sconn, connScope) + connVal := r.Context().Value(connKey{}) + if connVal == nil { + log.Errorf("missing conn from context") + sess.CloseWithError(1, "") + return errors.New("invalid context") + } + nconn, ok := connVal.(*negotiatingConn) + if !ok { + log.Errorf("unexpected connection in context. invalid conn type: %T", nconn) + sess.CloseWithError(1, "") + return errors.New("invalid context") + } + qconn, err := nconn.Unwrap() + if err != nil { + log.Debugf("handshake timed out: %s", r.RemoteAddr) + sess.CloseWithError(1, "") + return err + } + + conn := newConn(l.transport, sess, sconn, connScope, qconn) l.transport.addConn(sess, conn) select { case l.queue <- conn: default: log.Debugw("accept queue full, dropping incoming connection", "peer", sconn.RemotePeer(), "addr", r.RemoteAddr, "error", err) - sess.CloseWithError(1, "") + conn.Close() return errors.New("accept queue full") } diff --git a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/transport.go b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/transport.go index 97172703f..ef8551d60 100644 --- a/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/transport.go +++ b/vendor/github.com/libp2p/go-libp2p/p2p/transport/webtransport/transport.go @@ -60,6 +60,13 @@ func WithTLSClientConfig(c *tls.Config) Option { } } +func WithHandshakeTimeout(d time.Duration) Option { + return func(t *transport) error { + t.handshakeTimeout = d + return nil + } +} + type transport struct { privKey ic.PrivKey pid peer.ID @@ -78,8 +85,9 @@ type transport struct { noise *noise.Transport - connMx sync.Mutex - conns map[quic.ConnectionTracingID]*conn // using quic-go's ConnectionTracingKey as map key + connMx sync.Mutex + conns map[quic.ConnectionTracingID]*conn // using quic-go's ConnectionTracingKey as map key + handshakeTimeout time.Duration } var _ tpt.Transport = &transport{} @@ -99,13 +107,14 @@ func New(key ic.PrivKey, psk pnet.PSK, connManager *quicreuse.ConnManager, gater return nil, err } t := &transport{ - pid: id, - privKey: key, - rcmgr: rcmgr, - gater: gater, - clock: clock.New(), - connManager: connManager, - conns: map[quic.ConnectionTracingID]*conn{}, + pid: id, + privKey: key, + rcmgr: rcmgr, + gater: gater, + clock: clock.New(), + connManager: connManager, + conns: map[quic.ConnectionTracingID]*conn{}, + handshakeTimeout: handshakeTimeout, } for _, opt := range opts { if err := opt(t); err != nil { @@ -159,7 +168,7 @@ func (t *transport) dialWithScope(ctx context.Context, raddr ma.Multiaddr, p pee } maddr, _ := ma.SplitFunc(raddr, func(c ma.Component) bool { return c.Protocol().Code == ma.P_WEBTRANSPORT }) - sess, err := t.dial(ctx, maddr, url, sni, certHashes) + sess, qconn, err := t.dial(ctx, maddr, url, sni, certHashes) if err != nil { return nil, err } @@ -172,12 +181,12 @@ func (t *transport) dialWithScope(ctx context.Context, raddr ma.Multiaddr, p pee sess.CloseWithError(errorCodeConnectionGating, "") return nil, fmt.Errorf("secured connection gated") } - conn := newConn(t, sess, sconn, scope) + conn := newConn(t, sess, sconn, scope, qconn) t.addConn(sess, conn) return conn, nil } -func (t *transport) dial(ctx context.Context, addr ma.Multiaddr, url, sni string, certHashes []multihash.DecodedMultihash) (*webtransport.Session, error) { +func (t *transport) dial(ctx context.Context, addr ma.Multiaddr, url, sni string, certHashes []multihash.DecodedMultihash) (*webtransport.Session, quic.Connection, error) { var tlsConf *tls.Config if t.tlsClientConf != nil { tlsConf = t.tlsClientConf.Clone() @@ -200,7 +209,7 @@ func (t *transport) dial(ctx context.Context, addr ma.Multiaddr, url, sni string } conn, err := t.connManager.DialQUIC(ctx, addr, tlsConf, t.allowWindowIncrease) if err != nil { - return nil, err + return nil, nil, err } dialer := webtransport.Dialer{ DialAddr: func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error) { @@ -210,12 +219,14 @@ func (t *transport) dial(ctx context.Context, addr ma.Multiaddr, url, sni string } rsp, sess, err := dialer.Dial(ctx, url, nil) if err != nil { - return nil, err + conn.CloseWithError(1, "") + return nil, nil, err } if rsp.StatusCode < 200 || rsp.StatusCode > 299 { - return nil, fmt.Errorf("invalid response status code: %d", rsp.StatusCode) + conn.CloseWithError(1, "") + return nil, nil, fmt.Errorf("invalid response status code: %d", rsp.StatusCode) } - return sess, err + return sess, conn, err } func (t *transport) upgrade(ctx context.Context, sess *webtransport.Session, p peer.ID, certHashes []multihash.DecodedMultihash) (*connSecurityMultiaddrs, error) { diff --git a/vendor/github.com/libp2p/go-libp2p/version.json b/vendor/github.com/libp2p/go-libp2p/version.json index fb0aea4f0..808595258 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.35.0" + "version": "v0.35.2" } diff --git a/vendor/github.com/pion/ice/v2/agent.go b/vendor/github.com/pion/ice/v2/agent.go index 5befb4a4c..344200c21 100644 --- a/vendor/github.com/pion/ice/v2/agent.go +++ b/vendor/github.com/pion/ice/v2/agent.go @@ -133,9 +133,9 @@ type Agent struct { gatherCandidateCancel func() gatherCandidateDone chan struct{} - chanCandidate chan Candidate - chanCandidatePair chan *CandidatePair - chanState chan ConnectionState + connectionStateNotifier *handlerNotifier + candidateNotifier *handlerNotifier + selectedCandidatePairNotifier *handlerNotifier loggerFactory logging.LoggerFactory log logging.LeveledLogger @@ -232,9 +232,6 @@ func (a *Agent) taskLoop() { after() - close(a.chanState) - close(a.chanCandidate) - close(a.chanCandidatePair) close(a.taskLoopDone) }() @@ -282,33 +279,30 @@ func NewAgent(config *AgentConfig) (*Agent, error) { //nolint:gocognit startedCtx, startedFn := context.WithCancel(context.Background()) a := &Agent{ - chanTask: make(chan task), - chanState: make(chan ConnectionState), - chanCandidate: make(chan Candidate), - chanCandidatePair: make(chan *CandidatePair), - tieBreaker: globalMathRandomGenerator.Uint64(), - lite: config.Lite, - gatheringState: GatheringStateNew, - connectionState: ConnectionStateNew, - localCandidates: make(map[NetworkType][]Candidate), - remoteCandidates: make(map[NetworkType][]Candidate), - urls: config.Urls, - networkTypes: config.NetworkTypes, - onConnected: make(chan struct{}), - buf: packetio.NewBuffer(), - done: make(chan struct{}), - taskLoopDone: make(chan struct{}), - startedCh: startedCtx.Done(), - startedFn: startedFn, - 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, + chanTask: make(chan task), + tieBreaker: globalMathRandomGenerator.Uint64(), + lite: config.Lite, + gatheringState: GatheringStateNew, + connectionState: ConnectionStateNew, + localCandidates: make(map[NetworkType][]Candidate), + remoteCandidates: make(map[NetworkType][]Candidate), + urls: config.Urls, + networkTypes: config.NetworkTypes, + onConnected: make(chan struct{}), + buf: packetio.NewBuffer(), + done: make(chan struct{}), + taskLoopDone: make(chan struct{}), + startedCh: startedCtx.Done(), + startedFn: startedFn, + 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, @@ -329,6 +323,9 @@ func NewAgent(config *AgentConfig) (*Agent, error) { //nolint:gocognit userBindingRequestHandler: config.BindingRequestHandler, } + a.connectionStateNotifier = &handlerNotifier{connectionStateFunc: a.onConnectionStateChange} + a.candidateNotifier = &handlerNotifier{candidateFunc: a.onCandidate} + a.selectedCandidatePairNotifier = &handlerNotifier{candidatePairFunc: a.onSelectedCandidatePairChange} if a.net == nil { a.net, err = stdnet.NewNet() @@ -372,13 +369,6 @@ func NewAgent(config *AgentConfig) (*Agent, error) { //nolint:gocognit 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() - // Restart is also used to initialize the agent for the first time if err := a.Restart(config.LocalUfrag, config.LocalPwd); err != nil { a.closeMulticastConn() @@ -516,12 +506,7 @@ func (a *Agent) updateConnectionState(newState ConnectionState) { a.log.Infof("Setting new connection state: %s", newState) a.connectionState = newState - - // Call handler after finishing current task since we may be holding the agent lock - // and the handler may also require it - a.afterRun(func(ctx context.Context) { - a.chanState <- newState - }) + a.connectionStateNotifier.EnqueueConnectionState(newState) } } @@ -540,12 +525,7 @@ func (a *Agent) setSelectedPair(p *CandidatePair) { a.updateConnectionState(ConnectionStateConnected) // Notify when the selected pair changes - a.afterRun(func(ctx context.Context) { - select { - case a.chanCandidatePair <- p: - case <-ctx.Done(): - } - }) + a.selectedCandidatePairNotifier.EnqueueSelectedCandidatePair(p) // Signal connected a.onConnectedOnce.Do(func() { close(a.onConnected) }) @@ -781,7 +761,7 @@ func (a *Agent) addRemotePassiveTCPCandidate(remoteCandidate Candidate) { localCandidate.start(a, conn, a.startedCh) a.localCandidates[localCandidate.NetworkType()] = append(a.localCandidates[localCandidate.NetworkType()], localCandidate) - a.chanCandidate <- localCandidate + a.candidateNotifier.EnqueueCandidate(localCandidate) a.addPair(localCandidate, remoteCandidate) } @@ -851,7 +831,7 @@ func (a *Agent) addCandidate(ctx context.Context, c Candidate, candidateConn net a.requestConnectivityCheck() - a.chanCandidate <- c + a.candidateNotifier.EnqueueCandidate(c) }) } @@ -1287,7 +1267,7 @@ func (a *Agent) setGatheringState(newState GatheringState) error { done := make(chan struct{}) if err := a.run(a.context(), func(ctx context.Context, agent *Agent) { if a.gatheringState != newState && newState == GatheringStateComplete { - a.chanCandidate <- nil + a.candidateNotifier.EnqueueCandidate(nil) } a.gatheringState = newState diff --git a/vendor/github.com/pion/ice/v2/agent_handlers.go b/vendor/github.com/pion/ice/v2/agent_handlers.go index c5a5ec03b..bb0c8d303 100644 --- a/vendor/github.com/pion/ice/v2/agent_handlers.go +++ b/vendor/github.com/pion/ice/v2/agent_handlers.go @@ -3,6 +3,8 @@ package ice +import "sync" + // OnConnectionStateChange sets a handler that is fired when the connection state changes func (a *Agent) OnConnectionStateChange(f func(ConnectionState)) error { a.onConnectionStateChangeHdlr.Store(f) @@ -41,20 +43,94 @@ func (a *Agent) onConnectionStateChange(s ConnectionState) { } } -func (a *Agent) candidatePairRoutine() { - for p := range a.chanCandidatePair { - a.onSelectedCandidatePairChange(p) +type handlerNotifier struct { + sync.Mutex + running bool + + connectionStates []ConnectionState + connectionStateFunc func(ConnectionState) + + candidates []Candidate + candidateFunc func(Candidate) + + selectedCandidatePairs []*CandidatePair + candidatePairFunc func(*CandidatePair) +} + +func (h *handlerNotifier) EnqueueConnectionState(s ConnectionState) { + h.Lock() + defer h.Unlock() + + notify := func() { + for { + h.Lock() + if len(h.connectionStates) == 0 { + h.running = false + h.Unlock() + return + } + notification := h.connectionStates[0] + h.connectionStates = h.connectionStates[1:] + h.Unlock() + h.connectionStateFunc(notification) + } + } + + h.connectionStates = append(h.connectionStates, s) + if !h.running { + h.running = true + go notify() } } -func (a *Agent) connectionStateRoutine() { - for s := range a.chanState { - go a.onConnectionStateChange(s) +func (h *handlerNotifier) EnqueueCandidate(c Candidate) { + h.Lock() + defer h.Unlock() + + notify := func() { + for { + h.Lock() + if len(h.candidates) == 0 { + h.running = false + h.Unlock() + return + } + notification := h.candidates[0] + h.candidates = h.candidates[1:] + h.Unlock() + h.candidateFunc(notification) + } + } + + h.candidates = append(h.candidates, c) + if !h.running { + h.running = true + go notify() } } -func (a *Agent) candidateRoutine() { - for c := range a.chanCandidate { - a.onCandidate(c) +func (h *handlerNotifier) EnqueueSelectedCandidatePair(p *CandidatePair) { + h.Lock() + defer h.Unlock() + + notify := func() { + for { + h.Lock() + if len(h.selectedCandidatePairs) == 0 { + h.running = false + h.Unlock() + return + } + notification := h.selectedCandidatePairs[0] + h.selectedCandidatePairs = h.selectedCandidatePairs[1:] + h.Unlock() + h.candidatePairFunc(notification) + } + } + + h.selectedCandidatePairs = append(h.selectedCandidatePairs, p) + if !h.running { + h.running = true + go notify() } } diff --git a/vendor/github.com/pion/ice/v2/candidate_base.go b/vendor/github.com/pion/ice/v2/candidate_base.go index 7f97be82f..631994062 100644 --- a/vendor/github.com/pion/ice/v2/candidate_base.go +++ b/vendor/github.com/pion/ice/v2/candidate_base.go @@ -31,8 +31,8 @@ type candidateBase struct { resolvedAddr net.Addr - lastSent atomic.Int64 - lastReceived atomic.Int64 + lastSent atomic.Value + lastReceived atomic.Value conn net.PacketConn currAgent *Agent @@ -400,27 +400,27 @@ func (c *candidateBase) String() string { // LastReceived returns a time.Time indicating the last time // this candidate was received func (c *candidateBase) LastReceived() time.Time { - if lastReceived := c.lastReceived.Load(); lastReceived != 0 { - return time.Unix(0, lastReceived) + if lastReceived, ok := c.lastReceived.Load().(time.Time); ok { + return lastReceived } return time.Time{} } func (c *candidateBase) setLastReceived(t time.Time) { - c.lastReceived.Store(t.UnixNano()) + c.lastReceived.Store(t) } // LastSent returns a time.Time indicating the last time // this candidate was sent func (c *candidateBase) LastSent() time.Time { - if lastSent := c.lastSent.Load(); lastSent != 0 { - return time.Unix(0, lastSent) + if lastSent, ok := c.lastSent.Load().(time.Time); ok { + return lastSent } return time.Time{} } func (c *candidateBase) setLastSent(t time.Time) { - c.lastSent.Store(t.UnixNano()) + c.lastSent.Store(t) } func (c *candidateBase) seen(outbound bool) { diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/node/keepalive.go b/vendor/github.com/waku-org/go-waku/waku/v2/node/keepalive.go index 5e3815f9c..2cb03317e 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/node/keepalive.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/node/keepalive.go @@ -174,23 +174,3 @@ func (w *WakuNode) tryPing(ctx context.Context, peerID peer.ID, logger *zap.Logg } return true } - -func (w *WakuNode) getRelayPeers() []peer.ID { - relayPeers := make(map[peer.ID]struct{}) - for _, t := range w.Relay().Topics() { - for _, p := range w.Relay().PubSub().ListPeers(t) { - relayPeers[p] = struct{}{} - } - } - return maps.Keys(relayPeers) -} - -func (w *WakuNode) getFullMeshPeers() []peer.ID { - meshPeers := make(map[peer.ID]struct{}) - for _, t := range w.Relay().Topics() { - for _, p := range w.Relay().PubSub().MeshPeers(t) { - meshPeers[p] = struct{}{} - } - } - return maps.Keys(meshPeers) -} diff --git a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/metadata/waku_metadata.go b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/metadata/waku_metadata.go index 875902034..6129d6c01 100644 --- a/vendor/github.com/waku-org/go-waku/waku/v2/protocol/metadata/waku_metadata.go +++ b/vendor/github.com/waku-org/go-waku/waku/v2/protocol/metadata/waku_metadata.go @@ -18,6 +18,7 @@ import ( "github.com/waku-org/go-waku/waku/v2/protocol" "github.com/waku-org/go-waku/waku/v2/protocol/enr" "github.com/waku-org/go-waku/waku/v2/protocol/metadata/pb" + "github.com/waku-org/go-waku/waku/v2/protocol/relay" "go.uber.org/zap" ) @@ -59,11 +60,6 @@ func (wakuM *WakuMetadata) SetHost(h host.Host) { // Start inits the metadata protocol func (wakuM *WakuMetadata) Start(ctx context.Context) error { - if wakuM.clusterID == 0 { - wakuM.log.Warn("no clusterID is specified. Protocol will not be initialized") - return nil - } - ctx, cancel := context.WithCancel(ctx) wakuM.ctx = ctx @@ -83,6 +79,7 @@ func (wakuM *WakuMetadata) RelayShard() (*protocol.RelayShards, error) { } func (wakuM *WakuMetadata) ClusterAndShards() (*uint32, []uint32, error) { + shard, err := wakuM.RelayShard() if err != nil { return nil, nil, err @@ -100,7 +97,7 @@ func (wakuM *WakuMetadata) ClusterAndShards() (*uint32, []uint32, error) { return &u32ClusterID, shards, nil } -func (wakuM *WakuMetadata) Request(ctx context.Context, peerID peer.ID) (*protocol.RelayShards, error) { +func (wakuM *WakuMetadata) Request(ctx context.Context, peerID peer.ID) (*pb.WakuMetadataResponse, error) { logger := wakuM.log.With(logging.HostID("peer", peerID)) stream, err := wakuM.h.NewStream(ctx, peerID, MetadataID_v1) @@ -149,31 +146,7 @@ func (wakuM *WakuMetadata) Request(ctx context.Context, peerID peer.ID) (*protoc stream.Close() logger.Debug("received metadata response") - - if response.ClusterId == nil { - return nil, errors.New("node did not provide a waku clusterid") - } - - rClusterID := uint16(*response.ClusterId) - var rShardIDs []uint16 - if len(response.Shards) != 0 { - for _, i := range response.Shards { - rShardIDs = append(rShardIDs, uint16(i)) - } - } else { - // TODO: remove with nwaku 0.28 deployment - for _, i := range response.ShardsDeprecated { // nolint: staticcheck - rShardIDs = append(rShardIDs, uint16(i)) - } - } - logger.Debug("getting remote cluster and shards") - - rs, err := protocol.NewRelayShards(rClusterID, rShardIDs...) - if err != nil { - return nil, err - } - - return &rs, nil + return response, nil } func (wakuM *WakuMetadata) onRequest(ctx context.Context) func(network.Stream) { @@ -259,14 +232,49 @@ func (wakuM *WakuMetadata) Connected(n network.Network, cc network.Conn) { } peerID := cc.RemotePeer() - shard, err := wakuM.Request(wakuM.ctx, peerID) + response, err := wakuM.Request(wakuM.ctx, peerID) + if err != nil { + wakuM.disconnectPeer(peerID, err) + return + } + if response.ClusterId == nil { + wakuM.disconnectPeer(peerID, errors.New("node did not provide a waku clusterid")) + return + } + rClusterID := uint16(*response.ClusterId) + var rs protocol.RelayShards + + if _, err = wakuM.h.Peerstore().SupportsProtocols(peerID, relay.WakuRelayID_v200); err == nil { + wakuM.log.Debug("light peer only checking clusterID") + if rClusterID != wakuM.clusterID { + wakuM.disconnectPeer(peerID, errors.New("different clusterID reported")) + } + return + } + + wakuM.log.Debug("relay peer checking cluster and shards") + + var rShardIDs []uint16 + if len(response.Shards) != 0 { + for _, i := range response.Shards { + rShardIDs = append(rShardIDs, uint16(i)) + } + } else { + // TODO: remove with nwaku 0.28 deployment + for _, i := range response.ShardsDeprecated { // nolint: staticcheck + rShardIDs = append(rShardIDs, uint16(i)) + } + } + wakuM.log.Debug("getting remote cluster and shards") + //if peer supports relay, then check for both clusterID and shards. + rs, err = protocol.NewRelayShards(rClusterID, rShardIDs...) if err != nil { wakuM.disconnectPeer(peerID, err) return } - if shard.ClusterID != wakuM.clusterID { + if rs.ClusterID != wakuM.clusterID { wakuM.disconnectPeer(peerID, errors.New("different clusterID reported")) return } @@ -274,7 +282,7 @@ func (wakuM *WakuMetadata) Connected(n network.Network, cc network.Conn) { // Store shards so they're used to verify if a relay peer supports the same shards we do wakuM.peerShardsMutex.Lock() defer wakuM.peerShardsMutex.Unlock() - wakuM.peerShards[peerID] = shard.ShardIDs + wakuM.peerShards[peerID] = rs.ShardIDs }() } diff --git a/vendor/go.uber.org/fx/CHANGELOG.md b/vendor/go.uber.org/fx/CHANGELOG.md index 015695a88..08642a59a 100644 --- a/vendor/go.uber.org/fx/CHANGELOG.md +++ b/vendor/go.uber.org/fx/CHANGELOG.md @@ -10,6 +10,28 @@ 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.22.1](https://github.com/uber-go/fx/compare/v1.22.0...v1.22.1) - 2024-06-25 + +### Fixed +- Fx apps will only listen to signals when `.Run()`, `.Wait()`, or `.Done()` + are called, fixing a regression introduced in v1.19.0. + +## [1.22.0](https://github.com/uber-go/fx/compare/v1.21.1...v1.22.0) - 2024-05-30 + +### Added +- Add `fx.Self` which can be passed to the `fx.As` annotation to signify + that a type should be provided as itself. +- Add `fxtest.EnforceTimeout` that can be passed to `fxtest.NewLifecycle` + to force `Start` and `Stop` to return context errors when hook context expires. + +### Changed +- `fx.Private` can now be used with `fx.Supply`. + +### Fixed +- Fx apps will no longer listen to OS signals when they are stopped, + solving blocking issues in programs that depended on OS signals + after an Fx app stops. + ## [1.21.1](https://github.com/uber-go/fx/compare/v1.21.0...v1.21.1) - 2024-04-24 ### Changed diff --git a/vendor/go.uber.org/fx/annotated.go b/vendor/go.uber.org/fx/annotated.go index 4e0238661..0e72860e3 100644 --- a/vendor/go.uber.org/fx/annotated.go +++ b/vendor/go.uber.org/fx/annotated.go @@ -1097,7 +1097,19 @@ func OnStop(onStop interface{}) Annotation { type asAnnotation struct { targets []interface{} - types []reflect.Type + types []asType +} + +type asType struct { + self bool + typ reflect.Type // May be nil if self is true. +} + +func (a asType) String() string { + if a.self { + return "self" + } + return a.typ.String() } func isOut(t reflect.Type) bool { @@ -1119,7 +1131,7 @@ var _ Annotation = (*asAnnotation)(nil) // bytes.NewBuffer (bytes.Buffer) should be provided as io.Writer type: // // fx.Provide( -// fx.Annotate(bytes.NewBuffer(...), fx.As(new(io.Writer))) +// fx.Annotate(bytes.NewBuffer, fx.As(new(io.Writer))) // ) // // In other words, the code above is equivalent to: @@ -1152,20 +1164,58 @@ var _ Annotation = (*asAnnotation)(nil) // return w, r // } // +// As entirely replaces the default return types of a function. In order +// to maintain the original return types when using As, see [Self]. +// // As annotation cannot be used in a function that returns an [Out] struct as a return type. func As(interfaces ...interface{}) Annotation { return &asAnnotation{targets: interfaces} } +// Self returns a special value that can be passed to [As] to indicate +// that a type should be provided as its original type, in addition to whatever other +// types it gets provided as via other [As] annotations. +// +// For example, +// +// fx.Provide( +// fx.Annotate( +// bytes.NewBuffer, +// fx.As(new(io.Writer)), +// fx.As(fx.Self()), +// ) +// ) +// +// Is equivalent to, +// +// fx.Provide( +// bytes.NewBuffer, +// func(b *bytes.Buffer) io.Writer { +// return b +// }, +// ) +// +// in that it provides the same *bytes.Buffer instance +// as both a *bytes.Buffer and an io.Writer. +func Self() any { + return &self{} +} + +type self struct{} + func (at *asAnnotation) apply(ann *annotated) error { - at.types = make([]reflect.Type, len(at.targets)) + at.types = make([]asType, len(at.targets)) for i, typ := range at.targets { + if _, ok := typ.(*self); ok { + at.types[i] = asType{self: true} + continue + } t := reflect.TypeOf(typ) if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Interface { return fmt.Errorf("fx.As: argument must be a pointer to an interface: got %v", t) } t = t.Elem() - at.types[i] = t + at.types[i] = asType{typ: t} } ann.As = append(ann.As, at.types) @@ -1209,12 +1259,16 @@ func (at *asAnnotation) results(ann *annotated) ( Type: t, Tag: f.Tag, } - if i < len(at.types) { - if !t.Implements(at.types[i]) { - return nil, nil, fmt.Errorf("invalid fx.As: %v does not implement %v", t, at.types[i]) - } - field.Type = at.types[i] + + if i >= len(at.types) || at.types[i].self { + fields = append(fields, field) + continue } + + if !t.Implements(at.types[i].typ) { + return nil, nil, fmt.Errorf("invalid fx.As: %v does not implement %v", t, at.types[i]) + } + field.Type = at.types[i].typ fields = append(fields, field) } resType := reflect.StructOf(fields) @@ -1475,7 +1529,7 @@ type annotated struct { Annotations []Annotation ParamTags []string ResultTags []string - As [][]reflect.Type + As [][]asType From []reflect.Type FuncPtr uintptr Hooks []*lifecycleHookAnnotation diff --git a/vendor/go.uber.org/fx/app.go b/vendor/go.uber.org/fx/app.go index 8189f9d71..ef3d35a0d 100644 --- a/vendor/go.uber.org/fx/app.go +++ b/vendor/go.uber.org/fx/app.go @@ -704,7 +704,6 @@ func (app *App) start(ctx context.Context) error { if err := app.lifecycle.Start(ctx); err != nil { return err } - app.receivers.Start(ctx) return nil }) } @@ -742,6 +741,7 @@ func (app *App) Stop(ctx context.Context) (err error) { // Alternatively, a signal can be broadcast to all done channels manually by // using the Shutdown functionality (see the [Shutdowner] documentation for details). func (app *App) Done() <-chan os.Signal { + app.receivers.Start() // No-op if running return app.receivers.Done() } @@ -752,6 +752,7 @@ func (app *App) Done() <-chan os.Signal { // in the [ShutdownSignal] struct. // Otherwise, the signal that was received will be set. func (app *App) Wait() <-chan ShutdownSignal { + app.receivers.Start() // No-op if running return app.receivers.Wait() } diff --git a/vendor/go.uber.org/fx/provide.go b/vendor/go.uber.org/fx/provide.go index 999262c36..72db3f83b 100644 --- a/vendor/go.uber.org/fx/provide.go +++ b/vendor/go.uber.org/fx/provide.go @@ -96,7 +96,7 @@ func (o provideOption) apply(mod *module) { type privateOption struct{} -// Private is an option that can be passed as an argument to [Provide] to +// Private is an option that can be passed as an argument to [Provide] or [Supply] to // restrict access to the constructors being provided. Specifically, // corresponding constructors can only be used within the current module // or modules the current module contains. Other modules that contain this diff --git a/vendor/go.uber.org/fx/signal.go b/vendor/go.uber.org/fx/signal.go index 71d2204a0..595a847bc 100644 --- a/vendor/go.uber.org/fx/signal.go +++ b/vendor/go.uber.org/fx/signal.go @@ -46,8 +46,9 @@ func (sig ShutdownSignal) String() string { func newSignalReceivers() signalReceivers { return signalReceivers{ - notify: signal.Notify, - signals: make(chan os.Signal, 1), + notify: signal.Notify, + stopNotify: signal.Stop, + signals: make(chan os.Signal, 1), } } @@ -64,7 +65,8 @@ type signalReceivers struct { finished chan struct{} // this stub allows us to unit test signal relay functionality - notify func(c chan<- os.Signal, sig ...os.Signal) + notify func(c chan<- os.Signal, sig ...os.Signal) + stopNotify func(c chan<- os.Signal) // last will contain a pointer to the last ShutdownSignal received, or // nil if none, if a new channel is created by Wait or Done, this last @@ -100,7 +102,7 @@ func (recv *signalReceivers) running() bool { return recv.shutdown != nil && recv.finished != nil } -func (recv *signalReceivers) Start(ctx context.Context) { +func (recv *signalReceivers) Start() { recv.m.Lock() defer recv.m.Unlock() @@ -118,6 +120,7 @@ func (recv *signalReceivers) Start(ctx context.Context) { func (recv *signalReceivers) Stop(ctx context.Context) error { recv.m.Lock() defer recv.m.Unlock() + recv.stopNotify(recv.signals) // if the relayer is not running; return nil error if !recv.running() { diff --git a/vendor/go.uber.org/fx/supply.go b/vendor/go.uber.org/fx/supply.go index f3997289e..23d1a6ef0 100644 --- a/vendor/go.uber.org/fx/supply.go +++ b/vendor/go.uber.org/fx/supply.go @@ -56,6 +56,8 @@ import ( // // Supply panics if a value (or annotation target) is an untyped nil or an error. // +// [Private] can be used to restrict access to supplied values. +// // # Supply Caveats // // As mentioned above, Supply uses the most specific type of the provided @@ -78,29 +80,36 @@ import ( // fx.Annotate(handler, fx.As(new(http.Handler))), // ) func Supply(values ...interface{}) Option { - constructors := make([]interface{}, len(values)) // one function per value - types := make([]reflect.Type, len(values)) - for i, value := range values { + constructors := make([]interface{}, 0, len(values)) + types := make([]reflect.Type, 0, len(values)) + var private bool + for _, value := range values { + var ( + typ reflect.Type + ctor any + ) switch value := value.(type) { + case privateOption: + private = true + continue case annotated: - var typ reflect.Type value.Target, typ = newSupplyConstructor(value.Target) - constructors[i] = value - types[i] = typ + ctor = value case Annotated: - var typ reflect.Type value.Target, typ = newSupplyConstructor(value.Target) - constructors[i] = value - types[i] = typ + ctor = value default: - constructors[i], types[i] = newSupplyConstructor(value) + ctor, typ = newSupplyConstructor(value) } + constructors = append(constructors, ctor) + types = append(types, typ) } return supplyOption{ Targets: constructors, Types: types, Stack: fxreflect.CallerStack(1, 0), + Private: private, } } @@ -108,6 +117,7 @@ type supplyOption struct { Targets []interface{} Types []reflect.Type // type of value produced by constructor[i] Stack fxreflect.Stack + Private bool } func (o supplyOption) apply(m *module) { @@ -117,6 +127,7 @@ func (o supplyOption) apply(m *module) { Stack: o.Stack, IsSupply: true, SupplyType: o.Types[i], + Private: o.Private, }) } } diff --git a/vendor/go.uber.org/fx/version.go b/vendor/go.uber.org/fx/version.go index 153c0a78f..9ca711601 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.21.1" +const Version = "1.22.1" diff --git a/vendor/modules.txt b/vendor/modules.txt index 3184c15c0..f27ee62cd 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -380,8 +380,8 @@ github.com/gorilla/securecookie # github.com/gorilla/sessions v1.2.1 ## explicit github.com/gorilla/sessions -# github.com/gorilla/websocket v1.5.1 -## explicit; go 1.20 +# github.com/gorilla/websocket v1.5.3 +## explicit; go 1.12 github.com/gorilla/websocket # github.com/hashicorp/errwrap v1.1.0 ## explicit @@ -497,7 +497,7 @@ github.com/libp2p/go-buffer-pool # 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.35.0 +# github.com/libp2p/go-libp2p v0.35.2 ## explicit; go 1.21 github.com/libp2p/go-libp2p github.com/libp2p/go-libp2p/config @@ -746,7 +746,7 @@ 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.24 +# github.com/pion/ice/v2 v2.3.25 ## explicit; go 1.13 github.com/pion/ice/v2 github.com/pion/ice/v2/internal/atomic @@ -1018,7 +1018,7 @@ github.com/waku-org/go-discover/discover/v5wire 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.20240705124012-8df5a0337a1e +# github.com/waku-org/go-waku v0.8.1-0.20240711160252-9412af28dd81 ## explicit; go 1.21 github.com/waku-org/go-waku/logging github.com/waku-org/go-waku/tests @@ -1152,7 +1152,7 @@ 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.21.1 +# go.uber.org/fx v1.22.1 ## explicit; go 1.20 go.uber.org/fx go.uber.org/fx/fxevent