mirror of
https://github.com/cloudflare/cloudflared
synced 2026-06-08 13:33:07 +00:00
Compare commits
72 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e9a2c85671 | |||
| b0f0741a9b | |||
| db4564e5b9 | |||
| 3d345d3748 | |||
| b1995b4dd1 | |||
| b457cca1e5 | |||
| a0b6ba9b8d | |||
| de00396669 | |||
| 013bdbd10c | |||
| b639b6627a | |||
| e454994e3e | |||
| 8a53c1aa1d | |||
| f5f3e6a453 | |||
| 30c529e730 | |||
| bf3d70d1d2 | |||
| a65f8bce7f | |||
| 2ffff0687b | |||
| e380333520 | |||
| 11cbff4ff7 | |||
| 3e0ff3a771 | |||
| 7a19798682 | |||
| 4b75943d59 | |||
| fc20a22685 | |||
| faa86ffeca | |||
| f7a14d9200 | |||
| 902e5beb4f | |||
| 7ca5f7569a | |||
| 4ac68711cd | |||
| 075ac1acf1 | |||
| cfef0e737f | |||
| 8ec0f7746b | |||
| 2b3707e2b9 | |||
| 7e760f9fcc | |||
| efb99d90d7 | |||
| e131125558 | |||
| af6bf5c4e5 | |||
| e3390fcb15 | |||
| fc5749328d | |||
| 59f5b0df83 | |||
| f6bd4aa039 | |||
| d2bc15e224 | |||
| bad2e8e812 | |||
| 20ed7557f9 | |||
| 8e9e1d973e | |||
| a97673e8b9 | |||
| e123bbe1c5 | |||
| 906eb2d840 | |||
| e09c62a796 | |||
| bd88093de0 | |||
| 0538953a39 | |||
| 88235356d5 | |||
| 99f39225f1 | |||
| 278df5478a | |||
| d3fd581b7b | |||
| 68d370af19 | |||
| 679a89c7df | |||
| a768132d37 | |||
| 9de4e88ca6 | |||
| 91eba53035 | |||
| 065d8355c5 | |||
| 4016334efc | |||
| d4d9a43dd7 | |||
| 046a30e3c7 | |||
| 7a9207a6e1 | |||
| b9cba7f2ae | |||
| 7f1c890a82 | |||
| f48a7cd3dd | |||
| d96c39196d | |||
| 032ba7b5e4 | |||
| e63ec34503 | |||
| 2a177e0fc4 | |||
| 1733fe8c65 |
+4
-1
@@ -1,6 +1,6 @@
|
||||
images:
|
||||
- name: cloudflared
|
||||
dockerfile: Dockerfile
|
||||
dockerfile: Dockerfile.$ARCH
|
||||
context: .
|
||||
versions:
|
||||
- latest
|
||||
@@ -8,3 +8,6 @@ images:
|
||||
- name: docker.io/cloudflare
|
||||
user: env:DOCKER_USER
|
||||
password: env:DOCKER_PASSWORD
|
||||
architectures:
|
||||
- amd64
|
||||
- arm64
|
||||
|
||||
@@ -3,7 +3,6 @@ name: "\U0001F41B Bug report"
|
||||
about: Create a report to help us improve cloudflared
|
||||
title: "\U0001F41B"
|
||||
labels: 'Priority: Normal, Type: Bug'
|
||||
assignees: abelinkinbio
|
||||
|
||||
---
|
||||
|
||||
@@ -16,6 +15,10 @@ Steps to reproduce the behavior:
|
||||
2. Run '....'
|
||||
3. See error
|
||||
|
||||
If it's an issue with Cloudflare Tunnel:
|
||||
4. Tunnel ID :
|
||||
5. cloudflared config:
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ name: "\U0001F4DD Documentation"
|
||||
about: Request new or updated documentation for cloudflared
|
||||
title: "\U0001F4DD"
|
||||
labels: 'Priority: Normal, Type: Documentation'
|
||||
assignees: abelinkinbio, ranbel
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ name: "\U0001F4A1 Feature request"
|
||||
about: Suggest a feature or enhancement for cloudflared
|
||||
title: "\U0001F4A1"
|
||||
labels: 'Priority: Normal, Type: Feature Request'
|
||||
assignees: abelinkinbio, sssilver
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ jobs:
|
||||
check:
|
||||
strategy:
|
||||
matrix:
|
||||
go-version: [1.17.x]
|
||||
go-version: [1.19.x]
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
VERSION=$(git describe --tags --always --match "[0-9][0-9][0-9][0-9].*.*")
|
||||
echo $VERSION
|
||||
|
||||
export TARGET_OS=windows
|
||||
# This controls the directory the built artifacts go into
|
||||
export ARTIFACT_DIR=built_artifacts/
|
||||
mkdir -p $ARTIFACT_DIR
|
||||
windowsArchs=("amd64" "386")
|
||||
for arch in ${windowsArchs[@]}; do
|
||||
export TARGET_ARCH=$arch
|
||||
# Copy exe into final directory
|
||||
cp ./artifacts/cloudflared-windows-$arch.exe $ARTIFACT_DIR/cloudflared-windows-$arch.exe
|
||||
cp ./artifacts/cloudflared-windows-$arch.exe ./cloudflared.exe
|
||||
make cloudflared-msi
|
||||
# Copy msi into final directory
|
||||
mv cloudflared-$VERSION-$arch.msi $ARTIFACT_DIR/cloudflared-windows-$arch.msi
|
||||
done
|
||||
@@ -1,3 +1,12 @@
|
||||
## 2022.9.0
|
||||
### New Features
|
||||
- cloudflared now rejects ingress rules with invalid http status codes for http_status.
|
||||
|
||||
## 2022.8.1
|
||||
### New Features
|
||||
- cloudflared now remembers if it connected to a certain protocol successfully. If it did, it does not fall back to a lower
|
||||
protocol on connection failures.
|
||||
|
||||
## 2022.7.1
|
||||
### New Features
|
||||
- It is now possible to connect cloudflared tunnel to Cloudflare Global Network with IPv6. See `cloudflared tunnel --help` and look for `edge-ip-version` for more information. For now, the default behavior is to still connect with IPv4 only.
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
# use a builder image for building cloudflare
|
||||
ARG TARGET_GOOS
|
||||
ARG TARGET_GOARCH
|
||||
FROM golang:1.17.1 as builder
|
||||
FROM golang:1.19 as builder
|
||||
ENV GO111MODULE=on \
|
||||
CGO_ENABLED=0 \
|
||||
TARGET_GOOS=${TARGET_GOOS} \
|
||||
@@ -18,7 +18,7 @@ COPY . .
|
||||
RUN make cloudflared
|
||||
|
||||
# use a distroless base image with glibc
|
||||
FROM gcr.io/distroless/base-debian10:nonroot
|
||||
FROM gcr.io/distroless/base-debian11:nonroot
|
||||
|
||||
# copy our compiled binary
|
||||
COPY --from=builder --chown=nonroot /go/src/github.com/cloudflare/cloudflared/cloudflared /usr/local/bin/
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# use a builder image for building cloudflare
|
||||
FROM golang:1.19 as builder
|
||||
ENV GO111MODULE=on \
|
||||
CGO_ENABLED=0
|
||||
|
||||
LABEL org.opencontainers.image.source="https://github.com/cloudflare/cloudflared"
|
||||
|
||||
WORKDIR /go/src/github.com/cloudflare/cloudflared/
|
||||
|
||||
# copy our sources into the builder image
|
||||
COPY . .
|
||||
|
||||
# compile cloudflared
|
||||
RUN GOOS=linux GOARCH=amd64 make cloudflared
|
||||
|
||||
# use a distroless base image with glibc
|
||||
FROM gcr.io/distroless/base-debian11:nonroot
|
||||
|
||||
# copy our compiled binary
|
||||
COPY --from=builder --chown=nonroot /go/src/github.com/cloudflare/cloudflared/cloudflared /usr/local/bin/
|
||||
|
||||
# run as non-privileged user
|
||||
USER nonroot
|
||||
|
||||
# command / entrypoint of container
|
||||
ENTRYPOINT ["cloudflared", "--no-autoupdate"]
|
||||
CMD ["version"]
|
||||
@@ -0,0 +1,27 @@
|
||||
# use a builder image for building cloudflare
|
||||
FROM golang:1.19 as builder
|
||||
ENV GO111MODULE=on \
|
||||
CGO_ENABLED=0
|
||||
|
||||
LABEL org.opencontainers.image.source="https://github.com/cloudflare/cloudflared"
|
||||
|
||||
WORKDIR /go/src/github.com/cloudflare/cloudflared/
|
||||
|
||||
# copy our sources into the builder image
|
||||
COPY . .
|
||||
|
||||
# compile cloudflared
|
||||
RUN GOOS=linux GOARCH=arm64 make cloudflared
|
||||
|
||||
# use a distroless base image with glibc
|
||||
FROM gcr.io/distroless/base-debian11:nonroot-arm64
|
||||
|
||||
# copy our compiled binary
|
||||
COPY --from=builder --chown=nonroot /go/src/github.com/cloudflare/cloudflared/cloudflared /usr/local/bin/
|
||||
|
||||
# run as non-privileged user
|
||||
USER nonroot
|
||||
|
||||
# command / entrypoint of container
|
||||
ENTRYPOINT ["cloudflared", "--no-autoupdate"]
|
||||
CMD ["version"]
|
||||
@@ -198,7 +198,7 @@ cloudflared-pkg: cloudflared cloudflared.1
|
||||
$(call build_package,osxpkg)
|
||||
|
||||
.PHONY: cloudflared-msi
|
||||
cloudflared-msi: cloudflared
|
||||
cloudflared-msi:
|
||||
wixl --define Version=$(VERSION) --define Path=$(EXECUTABLE_PATH) --output cloudflared-$(VERSION)-$(TARGET_ARCH).msi cloudflared.wxs
|
||||
|
||||
.PHONY: cloudflared-darwin-amd64.tgz
|
||||
@@ -288,10 +288,17 @@ github-mac-upload:
|
||||
python3 github_release.py --path artifacts/cloudflared-darwin-amd64.tgz --release-version $(VERSION) --name cloudflared-darwin-amd64.tgz
|
||||
python3 github_release.py --path artifacts/cloudflared-amd64.pkg --release-version $(VERSION) --name cloudflared-amd64.pkg
|
||||
|
||||
.PHONY: github-windows-upload
|
||||
github-windows-upload:
|
||||
python3 github_release.py --path built_artifacts/cloudflared-windows-amd64.exe --release-version $(VERSION) --name cloudflared-windows-amd64.exe
|
||||
python3 github_release.py --path built_artifacts/cloudflared-windows-amd64.msi --release-version $(VERSION) --name cloudflared-windows-amd64.msi
|
||||
python3 github_release.py --path built_artifacts/cloudflared-windows-386.exe --release-version $(VERSION) --name cloudflared-windows-386.exe
|
||||
python3 github_release.py --path built_artifacts/cloudflared-windows-386.msi --release-version $(VERSION) --name cloudflared-windows-386.msi
|
||||
|
||||
.PHONY: tunnelrpc-deps
|
||||
tunnelrpc-deps:
|
||||
which capnp # https://capnproto.org/install.html
|
||||
which capnpc-go # go get zombiezen.com/go/capnproto2/capnpc-go
|
||||
which capnpc-go # go install zombiezen.com/go/capnproto2/capnpc-go@latest
|
||||
capnp compile -ogo tunnelrpc/tunnelrpc.capnp
|
||||
|
||||
.PHONY: quic-deps
|
||||
@@ -302,7 +309,7 @@ quic-deps:
|
||||
|
||||
.PHONY: vet
|
||||
vet:
|
||||
go vet -mod=vendor ./...
|
||||
go vet -v -mod=vendor ./...
|
||||
|
||||
.PHONY: goimports
|
||||
goimports:
|
||||
|
||||
@@ -1,3 +1,82 @@
|
||||
2022.9.1
|
||||
- 2022-09-20 TUN-6777: Fix race condition in TestFunnelIdleTimeout
|
||||
- 2022-09-20 TUN-6595: Enable datagramv2 and icmp proxy by default
|
||||
- 2022-09-20 TUN-6773: Add access based configuration to ingress.OriginRequestConfig
|
||||
- 2022-09-19 TUN-6778: Cleanup logs about ICMP
|
||||
- 2022-09-19 TUN-6779: cloudflared should also use the root CAs from system pool to validate edge certificate
|
||||
- 2022-09-19 TUN-6780: Add support for certReload to also include support for client certificates
|
||||
- 2022-09-16 TUN-6767: Build ICMP proxy for Windows only when CGO is enabled
|
||||
- 2022-09-15 TUN-6590: Use Windows Teamcity agent to build binary
|
||||
- 2022-09-13 TUN-6592: Decrement TTL and return ICMP time exceed if it's 0
|
||||
- 2022-09-09 TUN-6749: Fix icmp_generic build
|
||||
- 2022-09-09 TUN-6744: On posix platforms, assign unique echo ID per (src, dst, echo ID)
|
||||
- 2022-09-08 TUN-6743: Support ICMPv6 echo on Windows
|
||||
- 2022-09-08 TUN-6689: Utilize new RegisterUDPSession to begin tracing
|
||||
- 2022-09-07 TUN-6688: Update RegisterUdpSession capnproto to include trace context
|
||||
- 2022-09-06 TUN-6740: Detect no UDP packets allowed and fallback from QUIC in that case
|
||||
- 2022-09-06 TUN-6654: Support ICMPv6 on Linux and Darwin
|
||||
- 2022-09-02 TUN-6696: Refactor flow into funnel and close idle funnels
|
||||
- 2022-09-02 TUN-6718: Bump go and go-boring 1.18.6
|
||||
- 2022-08-29 TUN-6531: Implement ICMP proxy for Windows using IcmpSendEcho
|
||||
- 2022-08-24 RTG-1339 Support post-quantum hybrid key exchange
|
||||
|
||||
2022.9.0
|
||||
- 2022-09-05 TUN-6737: Fix datagramV2Type should be declared in its own block so it starts at 0
|
||||
- 2022-09-01 TUN-6725: Fix testProxySSEAllData
|
||||
- 2022-09-01 TUN-6726: Fix maxDatagramPayloadSize for Windows QUIC datagrams
|
||||
- 2022-09-01 TUN-6729: Fix flaky TestClosePreviousProxies
|
||||
- 2022-09-01 TUN-6728: Verify http status code ingress rule
|
||||
- 2022-08-25 TUN-6695: Implement ICMP proxy for linux
|
||||
|
||||
2022.8.4
|
||||
- 2022-08-31 TUN-6717: Update Github action to run with Go 1.19
|
||||
- 2022-08-31 TUN-6720: Remove forcibly closing connection during reconnect signal
|
||||
- 2022-08-29 Release 2022.8.3
|
||||
|
||||
2022.8.3
|
||||
- 2022-08-26 TUN-6708: Fix replace flow logic
|
||||
- 2022-08-25 TUN-6705: Tunnel should retry connections forever
|
||||
- 2022-08-25 TUN-6704: Honor protocol flag when edge discovery is unreachable
|
||||
- 2022-08-25 TUN-6699: Add metric for packet too big dropped
|
||||
- 2022-08-24 TUN-6691: Properly error check for net.ErrClosed
|
||||
- 2022-08-22 TUN-6679: Allow client side of quic request to close body
|
||||
- 2022-08-22 TUN-6586: Change ICMP proxy to only build for Darwin and use echo ID to track flows
|
||||
- 2022-08-18 TUN-6530: Implement ICMPv4 proxy
|
||||
- 2022-08-17 TUN-6666: Define packet package
|
||||
- 2022-08-17 TUN-6667: DatagramMuxerV2 provides a method to receive RawPacket
|
||||
- 2022-08-16 TUN-6657: Ask for Tunnel ID and Configuration on Bug Report
|
||||
- 2022-08-16 TUN-6676: Add suport for trailers in http2 connections
|
||||
- 2022-08-11 TUN-6575: Consume cf-trace-id from incoming http2 TCP requests
|
||||
|
||||
2022.8.2
|
||||
- 2022-08-16 TUN-6656: Docker for arm64 should not be deployed in an amd64 container
|
||||
|
||||
2022.8.1
|
||||
- 2022-08-15 TUN-6617: Updated CHANGES.md for protocol stickiness
|
||||
- 2022-08-12 EDGEPLAT-3918: bump go and go-boring to 1.18.5
|
||||
- 2022-08-12 TUN-6652: Publish dockerfile for both amd64 and arm64
|
||||
- 2022-08-11 TUN-6617: Dont fallback to http2 if QUIC conn was successful.
|
||||
- 2022-08-11 TUN-6617: Dont fallback to http2 if QUIC conn was successful.
|
||||
- 2022-08-11 Revert "TUN-6617: Dont fallback to http2 if QUIC conn was successful."
|
||||
- 2022-08-11 TUN-6617: Dont fallback to http2 if QUIC conn was successful.
|
||||
- 2022-08-01 TUN-6584: Define QUIC datagram v2 format to support proxying IP packets
|
||||
|
||||
2022.8.0
|
||||
- 2022-08-10 TUN-6637: Upgrade quic-go
|
||||
- 2022-08-10 TUN-6646: Add support to SafeStreamCloser to close only write side of stream
|
||||
- 2022-08-09 TUN-6642: Fix unexpected close of quic stream triggered by upstream origin close
|
||||
- 2022-08-09 TUN-6639: Validate cyclic ingress configuration
|
||||
- 2022-08-08 TUN-6637: Upgrade go version and quic-go
|
||||
- 2022-08-08 TUN-6639: Validate cyclic ingress configuration
|
||||
- 2022-08-04 EDGEPLAT-3918: build cloudflared for Bookworm
|
||||
- 2022-08-02 Revert "TUN-6576: Consume cf-trace-id from incoming TCP requests to create root span"
|
||||
- 2022-07-27 TUN-6601: Update gopkg.in/yaml.v3 references in modules
|
||||
- 2022-07-26 TUN-6576: Consume cf-trace-id from incoming TCP requests to create root span
|
||||
- 2022-07-26 TUN-6576: Consume cf-trace-id from incoming TCP requests to create root span
|
||||
- 2022-07-25 TUN-6598: Remove auto assignees on github issues
|
||||
- 2022-07-20 TUN-6583: Remove legacy --ui flag
|
||||
- 2022-07-20 cURL supports stdin and uses os pipes directly without copying
|
||||
- 2022-07-07 TUN-6517: Use QUIC stream context while proxying HTTP requests and TCP connections
|
||||
2022.7.1
|
||||
- 2022-07-06 TUN-6503: Fix transport fallback from QUIC in face of dial error "no network activity"
|
||||
|
||||
|
||||
@@ -7,15 +7,6 @@ export CGO_ENABLED=0
|
||||
# This controls the directory the built artifacts go into
|
||||
export ARTIFACT_DIR=built_artifacts/
|
||||
mkdir -p $ARTIFACT_DIR
|
||||
windowsArchs=("amd64" "386")
|
||||
export TARGET_OS=windows
|
||||
for arch in ${windowsArchs[@]}; do
|
||||
export TARGET_ARCH=$arch
|
||||
make cloudflared-msi
|
||||
mv ./cloudflared.exe $ARTIFACT_DIR/cloudflared-windows-$arch.exe
|
||||
mv cloudflared-$VERSION-$arch.msi $ARTIFACT_DIR/cloudflared-windows-$arch.msi
|
||||
done
|
||||
|
||||
|
||||
linuxArchs=("386" "amd64" "arm" "armhf" "arm64")
|
||||
export TARGET_OS=linux
|
||||
|
||||
+32
-16
@@ -1,8 +1,8 @@
|
||||
pinned_go: &pinned_go go=1.17.10-1
|
||||
pinned_go_fips: &pinned_go_fips go-boring=1.17.9-1
|
||||
pinned_go: &pinned_go go=1.18.6-1
|
||||
pinned_go_fips: &pinned_go_fips go-boring=1.18.6-1
|
||||
|
||||
build_dir: &build_dir /cfsetup_build
|
||||
default-flavor: buster
|
||||
default-flavor: bullseye
|
||||
stretch: &stretch
|
||||
build:
|
||||
build_dir: *build_dir
|
||||
@@ -133,7 +133,7 @@ stretch: &stretch
|
||||
- make publish-deb
|
||||
github-release-macos-amd64:
|
||||
build_dir: *build_dir
|
||||
builddeps:
|
||||
builddeps: &build_pygithub
|
||||
- *pinned_go
|
||||
- build-essential
|
||||
- python3-dev
|
||||
@@ -145,6 +145,27 @@ stretch: &stretch
|
||||
- pip3 install pygithub==1.55
|
||||
post-cache:
|
||||
- make github-mac-upload
|
||||
github-release-windows:
|
||||
build_dir: *build_dir
|
||||
builddeps:
|
||||
- *pinned_go
|
||||
- build-essential
|
||||
- python3-dev
|
||||
- libffi-dev
|
||||
- python3-setuptools
|
||||
- python3-pip
|
||||
- wget
|
||||
# libmsi and libgcab are libraries the wixl binary depends on.
|
||||
- libmsi-dev
|
||||
- libgcab-dev
|
||||
pre-cache:
|
||||
- wget https://github.com/sudarshan-reddy/msitools/releases/download/v0.101b/wixl -P /usr/local/bin
|
||||
- chmod a+x /usr/local/bin/wixl
|
||||
- pip3 install pynacl==1.4.0
|
||||
- pip3 install pygithub==1.55
|
||||
post-cache:
|
||||
- .teamcity/package-windows.sh
|
||||
- make github-windows-upload
|
||||
test:
|
||||
build_dir: *build_dir
|
||||
builddeps:
|
||||
@@ -152,7 +173,7 @@ stretch: &stretch
|
||||
- build-essential
|
||||
- gotest-to-teamcity
|
||||
pre-cache: &test_pre_cache
|
||||
- go get golang.org/x/tools/cmd/goimports
|
||||
- go install golang.org/x/tools/cmd/goimports@latest
|
||||
post-cache:
|
||||
- export GOOS=linux
|
||||
- export GOARCH=amd64
|
||||
@@ -204,13 +225,7 @@ stretch: &stretch
|
||||
- .teamcity/update-homebrew-core.sh
|
||||
github-message-release:
|
||||
build_dir: *build_dir
|
||||
builddeps:
|
||||
- *pinned_go
|
||||
- build-essential
|
||||
- python3-dev
|
||||
- libffi-dev
|
||||
- python3-setuptools
|
||||
- python3-pip
|
||||
builddeps: *build_pygithub
|
||||
pre-cache: *install_pygithub
|
||||
post-cache:
|
||||
- make github-message
|
||||
@@ -221,13 +236,13 @@ stretch: &stretch
|
||||
- build-essential
|
||||
- python3
|
||||
- genisoimage
|
||||
- jetez
|
||||
pre-cache:
|
||||
- ln -s /usr/bin/genisoimage /usr/bin/mkisofs
|
||||
post-cache:
|
||||
- export CGO_ENABLED=0
|
||||
- export GOOS=freebsd
|
||||
- export GOARCH=amd64
|
||||
- make cloudflared-junos
|
||||
- make cloudflared
|
||||
publish-junos:
|
||||
build_dir: *build_dir
|
||||
builddeps:
|
||||
@@ -246,6 +261,7 @@ stretch: &stretch
|
||||
|
||||
buster: *stretch
|
||||
bullseye: *stretch
|
||||
bookworm: *stretch
|
||||
centos-7:
|
||||
publish-rpm:
|
||||
build_dir: *build_dir
|
||||
@@ -254,8 +270,8 @@ centos-7:
|
||||
pre-cache:
|
||||
- yum install -y fakeroot
|
||||
- yum upgrade -y binutils-2.27-44.base.el7.x86_64
|
||||
- wget https://go.dev/dl/go1.17.10.linux-amd64.tar.gz -P /tmp/
|
||||
- tar -C /usr/local -xzf /tmp/go1.17.10.linux-amd64.tar.gz
|
||||
- wget https://go.dev/dl/go1.18.6.linux-amd64.tar.gz -P /tmp/
|
||||
- tar -C /usr/local -xzf /tmp/go1.18.6.linux-amd64.tar.gz
|
||||
post-cache:
|
||||
- export PATH=$PATH:/usr/local/go/bin
|
||||
- export GOOS=linux
|
||||
|
||||
@@ -296,6 +296,7 @@ func curl(c *cli.Context) error {
|
||||
// run kicks off a shell task and pipe the results to the respective std pipes
|
||||
func run(cmd string, args ...string) error {
|
||||
c := exec.Command(cmd, args...)
|
||||
c.Stdin = os.Stdin
|
||||
stderr, err := c.StderrPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -25,7 +25,6 @@ import (
|
||||
"github.com/cloudflare/cloudflared/cfapi"
|
||||
"github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil"
|
||||
"github.com/cloudflare/cloudflared/cmd/cloudflared/proxydns"
|
||||
"github.com/cloudflare/cloudflared/cmd/cloudflared/ui"
|
||||
"github.com/cloudflare/cloudflared/cmd/cloudflared/updater"
|
||||
"github.com/cloudflare/cloudflared/config"
|
||||
"github.com/cloudflare/cloudflared/connection"
|
||||
@@ -218,7 +217,7 @@ func runAdhocNamedTunnel(sc *subcommandContext, name, credentialsOutputPath stri
|
||||
|
||||
// runClassicTunnel creates a "classic" non-named tunnel
|
||||
func runClassicTunnel(sc *subcommandContext) error {
|
||||
return StartServer(sc.c, buildInfo, nil, sc.log, sc.isUIEnabled)
|
||||
return StartServer(sc.c, buildInfo, nil, sc.log)
|
||||
}
|
||||
|
||||
func routeFromFlag(c *cli.Context) (route cfapi.HostnameRoute, ok bool) {
|
||||
@@ -236,7 +235,6 @@ func StartServer(
|
||||
info *cliutil.BuildInfo,
|
||||
namedTunnel *connection.NamedTunnelProperties,
|
||||
log *zerolog.Logger,
|
||||
isUIEnabled bool,
|
||||
) error {
|
||||
_ = raven.SetDSN(sentryDSN)
|
||||
var wg sync.WaitGroup
|
||||
@@ -331,9 +329,9 @@ func StartServer(
|
||||
return fmt.Errorf(errText)
|
||||
}
|
||||
|
||||
logTransport := logger.CreateTransportLoggerFromContext(c, isUIEnabled)
|
||||
logTransport := logger.CreateTransportLoggerFromContext(c, logger.EnableTerminalLog)
|
||||
|
||||
observer := connection.NewObserver(log, logTransport, isUIEnabled)
|
||||
observer := connection.NewObserver(log, logTransport)
|
||||
|
||||
// Send Quick Tunnel URL to UI if applicable
|
||||
var quickTunnelURL string
|
||||
@@ -377,7 +375,7 @@ func StartServer(
|
||||
errC <- metrics.ServeMetrics(metricsListener, ctx.Done(), readinessServer, quickTunnelURL, orchestrator, log)
|
||||
}()
|
||||
|
||||
reconnectCh := make(chan supervisor.ReconnectSignal, 1)
|
||||
reconnectCh := make(chan supervisor.ReconnectSignal, c.Int("ha-connections"))
|
||||
if c.IsSet("stdin-control") {
|
||||
log.Info().Msg("Enabling control through stdin")
|
||||
go stdinControl(reconnectCh, log)
|
||||
@@ -392,18 +390,6 @@ func StartServer(
|
||||
errC <- supervisor.StartTunnelDaemon(ctx, tunnelConfig, orchestrator, connectedSignal, reconnectCh, graceShutdownC)
|
||||
}()
|
||||
|
||||
if isUIEnabled {
|
||||
tunnelUI := ui.NewUIModel(
|
||||
info.Version(),
|
||||
hostname,
|
||||
metricsListener.Addr().String(),
|
||||
orchestratorConfig.Ingress,
|
||||
tunnelConfig.HAConnections,
|
||||
)
|
||||
app := tunnelUI.Launch(ctx, log, logTransport)
|
||||
observer.RegisterSink(app)
|
||||
}
|
||||
|
||||
gracePeriod, err := gracePeriod(c)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -663,9 +649,9 @@ func tunnelFlags(shouldHide bool) []cli.Flag {
|
||||
}),
|
||||
altsrc.NewBoolFlag(&cli.BoolFlag{
|
||||
Name: uiFlag,
|
||||
Usage: "Launch tunnel UI. Tunnel logs are scrollable via 'j', 'k', or arrow keys.",
|
||||
Usage: "(depreciated) Launch tunnel UI. Tunnel logs are scrollable via 'j', 'k', or arrow keys.",
|
||||
Value: false,
|
||||
Hidden: shouldHide,
|
||||
Hidden: true,
|
||||
}),
|
||||
altsrc.NewStringFlag(&cli.StringFlag{
|
||||
Name: "quick-service",
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
mathRand "math/rand"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -43,7 +44,7 @@ var (
|
||||
LogFieldHostname = "hostname"
|
||||
|
||||
secretFlags = [2]*altsrc.StringFlag{credentialsContentsFlag, tunnelTokenFlag}
|
||||
defaultFeatures = []string{supervisor.FeatureAllowRemoteConfig, supervisor.FeatureSerializedHeaders}
|
||||
defaultFeatures = []string{supervisor.FeatureAllowRemoteConfig, supervisor.FeatureSerializedHeaders, supervisor.FeatureDatagramV2}
|
||||
|
||||
configFlags = []string{"autoupdate-freq", "no-autoupdate", "retries", "protocol", "loglevel", "transport-loglevel", "origincert", "metrics", "metrics-update-freq", "edge-ip-version"}
|
||||
)
|
||||
@@ -220,6 +221,19 @@ func prepareTunnelConfig(
|
||||
)
|
||||
|
||||
transportProtocol := c.String("protocol")
|
||||
|
||||
needPQ := c.Bool("post-quantum")
|
||||
if needPQ {
|
||||
if FipsEnabled {
|
||||
return nil, nil, fmt.Errorf("post-quantum not supported in FIPS mode")
|
||||
}
|
||||
// Error if the user tries to force a non-quic transport protocol
|
||||
if transportProtocol != connection.AutoSelectFlag && transportProtocol != connection.QUIC.String() {
|
||||
return nil, nil, fmt.Errorf("post-quantum is only supported with the quic transport")
|
||||
}
|
||||
transportProtocol = connection.QUIC.String()
|
||||
}
|
||||
|
||||
protocolFetcher := edgediscovery.ProtocolPercentage
|
||||
|
||||
cfg := config.GetConfiguration()
|
||||
@@ -230,6 +244,9 @@ func prepareTunnelConfig(
|
||||
}
|
||||
log.Info().Msgf("Generated Connector ID: %s", clientUUID)
|
||||
features := append(c.StringSlice("features"), defaultFeatures...)
|
||||
if needPQ {
|
||||
features = append(features, supervisor.FeaturePostQuantum)
|
||||
}
|
||||
if c.IsSet(TunnelTokenFlag) {
|
||||
if transportProtocol == connection.AutoSelectFlag {
|
||||
protocolFetcher = func() (edgediscovery.ProtocolPercents, error) {
|
||||
@@ -291,7 +308,7 @@ func prepareTunnelConfig(
|
||||
}
|
||||
|
||||
warpRoutingEnabled := isWarpRoutingEnabled(cfg.WarpRouting, isNamedTunnel)
|
||||
protocolSelector, err := connection.NewProtocolSelector(transportProtocol, warpRoutingEnabled, namedTunnel, protocolFetcher, supervisor.ResolveTTL, log)
|
||||
protocolSelector, err := connection.NewProtocolSelector(transportProtocol, warpRoutingEnabled, namedTunnel, protocolFetcher, supervisor.ResolveTTL, log, c.Bool("post-quantum"))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
@@ -330,6 +347,15 @@ func prepareTunnelConfig(
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var pqKexIdx int
|
||||
if needPQ {
|
||||
pqKexIdx = mathRand.Intn(len(supervisor.PQKexes))
|
||||
log.Info().Msgf(
|
||||
"Using experimental hybrid post-quantum key agreement %s",
|
||||
supervisor.PQKexNames[supervisor.PQKexes[pqKexIdx]],
|
||||
)
|
||||
}
|
||||
|
||||
tunnelConfig := &supervisor.TunnelConfig{
|
||||
GracePeriod: gracePeriod,
|
||||
ReplaceExisting: c.Bool("force"),
|
||||
@@ -355,6 +381,8 @@ func prepareTunnelConfig(
|
||||
MuxerConfig: muxerConfig,
|
||||
ProtocolSelector: protocolSelector,
|
||||
EdgeTLSConfigs: edgeTLSConfigs,
|
||||
NeedPQ: needPQ,
|
||||
PQKexIdx: pqKexIdx,
|
||||
}
|
||||
orchestratorConfig := &orchestration.Config{
|
||||
Ingress: &ingressRules,
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
package tunnel
|
||||
|
||||
var FipsEnabled bool
|
||||
@@ -78,7 +78,6 @@ func RunQuickTunnel(sc *subcommandContext) error {
|
||||
buildInfo,
|
||||
&connection.NamedTunnelProperties{Credentials: credentials, QuickTunnelUrl: data.Result.Hostname},
|
||||
sc.log,
|
||||
sc.isUIEnabled,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -31,10 +31,9 @@ func (e errInvalidJSONCredential) Error() string {
|
||||
// subcommandContext carries structs shared between subcommands, to reduce number of arguments needed to
|
||||
// pass between subcommands, and make sure they are only initialized once
|
||||
type subcommandContext struct {
|
||||
c *cli.Context
|
||||
log *zerolog.Logger
|
||||
isUIEnabled bool
|
||||
fs fileSystem
|
||||
c *cli.Context
|
||||
log *zerolog.Logger
|
||||
fs fileSystem
|
||||
|
||||
// These fields should be accessed using their respective Getter
|
||||
tunnelstoreClient cfapi.Client
|
||||
@@ -42,16 +41,10 @@ type subcommandContext struct {
|
||||
}
|
||||
|
||||
func newSubcommandContext(c *cli.Context) (*subcommandContext, error) {
|
||||
isUIEnabled := c.IsSet(uiFlag) && c.String("name") != ""
|
||||
|
||||
// If UI is enabled, terminal log output should be disabled -- log should be written into a UI log window instead
|
||||
log := logger.CreateLoggerFromContext(c, isUIEnabled)
|
||||
|
||||
return &subcommandContext{
|
||||
c: c,
|
||||
log: log,
|
||||
isUIEnabled: isUIEnabled,
|
||||
fs: realFileSystem{},
|
||||
c: c,
|
||||
log: logger.CreateLoggerFromContext(c, logger.EnableTerminalLog),
|
||||
fs: realFileSystem{},
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -312,7 +305,6 @@ func (sc *subcommandContext) runWithCredentials(credentials connection.Credentia
|
||||
buildInfo,
|
||||
&connection.NamedTunnelProperties{Credentials: credentials},
|
||||
sc.log,
|
||||
sc.isUIEnabled,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -35,7 +35,6 @@ func Test_subcommandContext_findCredentials(t *testing.T) {
|
||||
type fields struct {
|
||||
c *cli.Context
|
||||
log *zerolog.Logger
|
||||
isUIEnabled bool
|
||||
fs fileSystem
|
||||
tunnelstoreClient cfapi.Client
|
||||
userCredential *userCredential
|
||||
@@ -168,7 +167,6 @@ func Test_subcommandContext_findCredentials(t *testing.T) {
|
||||
sc := &subcommandContext{
|
||||
c: tt.fields.c,
|
||||
log: tt.fields.log,
|
||||
isUIEnabled: tt.fields.isUIEnabled,
|
||||
fs: tt.fields.fs,
|
||||
tunnelstoreClient: tt.fields.tunnelstoreClient,
|
||||
userCredential: tt.fields.userCredential,
|
||||
@@ -307,7 +305,6 @@ func Test_subcommandContext_Delete(t *testing.T) {
|
||||
sc := &subcommandContext{
|
||||
c: tt.fields.c,
|
||||
log: tt.fields.log,
|
||||
isUIEnabled: tt.fields.isUIEnabled,
|
||||
fs: tt.fields.fs,
|
||||
tunnelstoreClient: tt.fields.tunnelstoreClient,
|
||||
userCredential: tt.fields.userCredential,
|
||||
|
||||
@@ -140,6 +140,13 @@ var (
|
||||
EnvVars: []string{"TUNNEL_TRANSPORT_PROTOCOL"},
|
||||
Hidden: true,
|
||||
})
|
||||
postQuantumFlag = altsrc.NewBoolFlag(&cli.BoolFlag{
|
||||
Name: "post-quantum",
|
||||
Usage: "When given creates an experimental post-quantum secure tunnel",
|
||||
Aliases: []string{"pq"},
|
||||
EnvVars: []string{"TUNNEL_POST_QUANTUM"},
|
||||
Hidden: FipsEnabled,
|
||||
})
|
||||
sortInfoByFlag = &cli.StringFlag{
|
||||
Name: "sort-by",
|
||||
Value: "createdAt",
|
||||
@@ -602,6 +609,7 @@ func buildRunCommand() *cli.Command {
|
||||
forceFlag,
|
||||
credentialsFileFlag,
|
||||
credentialsContentsFlag,
|
||||
postQuantumFlag,
|
||||
selectProtocolFlag,
|
||||
featuresFlag,
|
||||
tunnelTokenFlag,
|
||||
|
||||
@@ -1,223 +0,0 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/gdamore/tcell"
|
||||
"github.com/rivo/tview"
|
||||
"github.com/rs/zerolog"
|
||||
|
||||
"github.com/cloudflare/cloudflared/connection"
|
||||
"github.com/cloudflare/cloudflared/ingress"
|
||||
)
|
||||
|
||||
type connState struct {
|
||||
location string
|
||||
}
|
||||
|
||||
type uiModel struct {
|
||||
version string
|
||||
edgeURL string
|
||||
metricsURL string
|
||||
localServices []string
|
||||
connections []connState
|
||||
}
|
||||
|
||||
type palette struct {
|
||||
url string
|
||||
connected string
|
||||
defaultText string
|
||||
disconnected string
|
||||
reconnecting string
|
||||
unregistered string
|
||||
}
|
||||
|
||||
func NewUIModel(version, hostname, metricsURL string, ing *ingress.Ingress, haConnections int) *uiModel {
|
||||
localServices := make([]string, len(ing.Rules))
|
||||
for i, rule := range ing.Rules {
|
||||
localServices[i] = rule.Service.String()
|
||||
}
|
||||
return &uiModel{
|
||||
version: version,
|
||||
edgeURL: hostname,
|
||||
metricsURL: metricsURL,
|
||||
localServices: localServices,
|
||||
connections: make([]connState, haConnections),
|
||||
}
|
||||
}
|
||||
|
||||
func (data *uiModel) Launch(
|
||||
ctx context.Context,
|
||||
log, transportLog *zerolog.Logger,
|
||||
) connection.EventSink {
|
||||
// Configure the logger to stream logs into the textview
|
||||
|
||||
// Add TextView as a group to write output to
|
||||
logTextView := NewDynamicColorTextView()
|
||||
// TODO: Format log for UI
|
||||
//log.Add(logTextView, logger.NewUIFormatter(time.RFC3339), logLevels...)
|
||||
//transportLog.Add(logTextView, logger.NewUIFormatter(time.RFC3339), logLevels...)
|
||||
|
||||
// Construct the UI
|
||||
palette := palette{
|
||||
url: "lightblue",
|
||||
connected: "lime",
|
||||
defaultText: "white",
|
||||
disconnected: "red",
|
||||
reconnecting: "orange",
|
||||
unregistered: "orange",
|
||||
}
|
||||
|
||||
app := tview.NewApplication()
|
||||
|
||||
grid := tview.NewGrid().SetGap(1, 0)
|
||||
frame := tview.NewFrame(grid)
|
||||
header := fmt.Sprintf("cloudflared [::b]%s", data.version)
|
||||
|
||||
frame.AddText(header, true, tview.AlignLeft, tcell.ColorWhite)
|
||||
|
||||
// Create table to store connection info and status
|
||||
connTable := tview.NewTable()
|
||||
// SetColumns takes a value for each column, representing the size of the column
|
||||
// Numbers <= 0 represent proportional widths and positive numbers represent absolute widths
|
||||
grid.SetColumns(20, 0)
|
||||
|
||||
// SetRows takes a value for each row, representing the size of the row
|
||||
grid.SetRows(1, 1, len(data.connections), 1, 0)
|
||||
|
||||
// AddItem takes a primitive tview type, row, column, rowSpan, columnSpan, minGridHeight, minGridWidth, and focus
|
||||
grid.AddItem(tview.NewTextView().SetText("Tunnel:"), 0, 0, 1, 1, 0, 0, false)
|
||||
grid.AddItem(tview.NewTextView().SetText("Status:"), 1, 0, 1, 1, 0, 0, false)
|
||||
grid.AddItem(tview.NewTextView().SetText("Connections:"), 2, 0, 1, 1, 0, 0, false)
|
||||
|
||||
grid.AddItem(tview.NewTextView().SetText("Metrics:"), 3, 0, 1, 1, 0, 0, false)
|
||||
|
||||
tunnelHostText := tview.NewTextView().SetText(data.edgeURL)
|
||||
|
||||
grid.AddItem(tunnelHostText, 0, 1, 1, 1, 0, 0, false)
|
||||
status := fmt.Sprintf("[%s]\u2022[%s] Proxying to [%s::b]%s", palette.connected, palette.defaultText, palette.url, strings.Join(data.localServices, ", "))
|
||||
grid.AddItem(NewDynamicColorTextView().SetText(status), 1, 1, 1, 1, 0, 0, false)
|
||||
|
||||
grid.AddItem(connTable, 2, 1, 1, 1, 0, 0, false)
|
||||
|
||||
grid.AddItem(NewDynamicColorTextView().SetText(fmt.Sprintf("Metrics at [%s::b]http://%s/metrics", palette.url, data.metricsURL)), 3, 1, 1, 1, 0, 0, false)
|
||||
|
||||
// Add TextView to stream logs
|
||||
// Logs are displayed in a new grid so a border can be set around them
|
||||
logGrid := tview.NewGrid().SetBorders(true).AddItem(logTextView.SetChangedFunc(handleNewText(app, logTextView)), 0, 0, 5, 2, 0, 0, false)
|
||||
// LogFrame holds the Logs header as well as the grid with the textView for streamed logs
|
||||
logFrame := tview.NewFrame(logGrid).AddText("[::b]Logs:[::-]", true, tview.AlignLeft, tcell.ColorWhite).SetBorders(0, 0, 0, 0, 0, 0)
|
||||
// Footer for log frame
|
||||
logFrame.AddText("[::d]Use Ctrl+C to exit[::-]", false, tview.AlignRight, tcell.ColorWhite)
|
||||
grid.AddItem(logFrame, 4, 0, 5, 2, 0, 0, false)
|
||||
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
app.Stop()
|
||||
return
|
||||
}()
|
||||
|
||||
go func() {
|
||||
if err := app.SetRoot(frame, true).Run(); err != nil {
|
||||
log.Error().Msgf("Error launching UI: %s", err)
|
||||
}
|
||||
}()
|
||||
|
||||
return connection.EventSinkFunc(func(event connection.Event) {
|
||||
switch event.EventType {
|
||||
case connection.Connected:
|
||||
data.setConnTableCell(event, connTable, palette)
|
||||
case connection.Disconnected, connection.Reconnecting, connection.Unregistering:
|
||||
data.changeConnStatus(event, connTable, log, palette)
|
||||
case connection.SetURL:
|
||||
tunnelHostText.SetText(event.URL)
|
||||
data.edgeURL = event.URL
|
||||
case connection.RegisteringTunnel:
|
||||
if data.edgeURL == "" {
|
||||
tunnelHostText.SetText(fmt.Sprintf("Registering tunnel connection %d...", event.Index))
|
||||
}
|
||||
}
|
||||
app.Draw()
|
||||
})
|
||||
}
|
||||
|
||||
func NewDynamicColorTextView() *tview.TextView {
|
||||
return tview.NewTextView().SetDynamicColors(true)
|
||||
}
|
||||
|
||||
// Re-draws application when new logs are streamed to UI
|
||||
func handleNewText(app *tview.Application, logTextView *tview.TextView) func() {
|
||||
return func() {
|
||||
app.Draw()
|
||||
// SetFocus to enable scrolling in textview
|
||||
app.SetFocus(logTextView)
|
||||
}
|
||||
}
|
||||
|
||||
func (data *uiModel) changeConnStatus(event connection.Event, table *tview.Table, log *zerolog.Logger, palette palette) {
|
||||
index := int(event.Index)
|
||||
// Get connection location and state
|
||||
connState := data.getConnState(index)
|
||||
// Check if connection is already displayed in UI
|
||||
if connState == nil {
|
||||
log.Info().Msg("Connection is not in the UI table")
|
||||
return
|
||||
}
|
||||
|
||||
locationState := event.Location
|
||||
|
||||
if event.EventType == connection.Reconnecting {
|
||||
locationState = "Reconnecting..."
|
||||
}
|
||||
|
||||
connectionNum := index + 1
|
||||
// Get table cell
|
||||
cell := table.GetCell(index, 0)
|
||||
// Change dot color in front of text as well as location state
|
||||
text := newCellText(palette, connectionNum, locationState, event.EventType)
|
||||
cell.SetText(text)
|
||||
}
|
||||
|
||||
// Return connection location and row in UI table
|
||||
func (data *uiModel) getConnState(connID int) *connState {
|
||||
if connID < len(data.connections) {
|
||||
return &data.connections[connID]
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (data *uiModel) setConnTableCell(event connection.Event, table *tview.Table, palette palette) {
|
||||
index := int(event.Index)
|
||||
connectionNum := index + 1
|
||||
|
||||
// Update slice to keep track of connection location and state in UI table
|
||||
data.connections[index].location = event.Location
|
||||
|
||||
// Update text in table cell to show disconnected state
|
||||
text := newCellText(palette, connectionNum, event.Location, event.EventType)
|
||||
cell := tview.NewTableCell(text)
|
||||
table.SetCell(index, 0, cell)
|
||||
}
|
||||
|
||||
func newCellText(palette palette, connectionNum int, location string, connectedStatus connection.Status) string {
|
||||
// HA connection indicator formatted as: "• #<CONNECTION_INDEX>: <COLO>",
|
||||
// where the left middle dot's color depends on the status of the connection
|
||||
const connFmtString = "[%s]\u2022[%s] #%d: %s"
|
||||
|
||||
var dotColor string
|
||||
switch connectedStatus {
|
||||
case connection.Connected:
|
||||
dotColor = palette.connected
|
||||
case connection.Disconnected:
|
||||
dotColor = palette.disconnected
|
||||
case connection.Reconnecting:
|
||||
dotColor = palette.reconnecting
|
||||
case connection.Unregistering:
|
||||
dotColor = palette.unregistered
|
||||
}
|
||||
|
||||
return fmt.Sprintf(connFmtString, dotColor, palette.defaultText, connectionNum, location)
|
||||
}
|
||||
@@ -47,17 +47,12 @@ class TestReconnect:
|
||||
cloudflared.stdin.flush()
|
||||
|
||||
def assert_reconnect(self, config, cloudflared, repeat):
|
||||
wait_tunnel_ready(tunnel_url=config.get_url(), require_min_connections=self.default_ha_conns)
|
||||
wait_tunnel_ready(tunnel_url=config.get_url(),
|
||||
require_min_connections=self.default_ha_conns)
|
||||
for _ in range(repeat):
|
||||
for i in range(self.default_ha_conns):
|
||||
for _ in range(self.default_ha_conns):
|
||||
self.send_reconnect(cloudflared, self.default_reconnect_secs)
|
||||
expect_connections = self.default_ha_conns-i-1
|
||||
if expect_connections > 0:
|
||||
# Don't check if tunnel returns 200 here because there is a race condition between wait_tunnel_ready
|
||||
# retrying to get 200 response and reconnecting
|
||||
wait_tunnel_ready(require_min_connections=expect_connections)
|
||||
else:
|
||||
check_tunnel_not_connected()
|
||||
|
||||
check_tunnel_not_connected()
|
||||
sleep(self.default_reconnect_secs * 2)
|
||||
wait_tunnel_ready(tunnel_url=config.get_url(), require_min_connections=self.default_ha_conns)
|
||||
wait_tunnel_ready(tunnel_url=config.get_url(),
|
||||
require_min_connections=self.default_ha_conns)
|
||||
|
||||
+10
-5
@@ -15,6 +15,7 @@ from constants import METRICS_PORT, MAX_RETRIES, BACKOFF_SECS
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def select_platform(plat):
|
||||
return pytest.mark.skipif(
|
||||
platform.system() != plat, reason=f"Only runs on {plat}")
|
||||
@@ -61,13 +62,15 @@ def cloudflared_cmd(config, config_path, cfd_args, cfd_pre_args, root):
|
||||
def run_cloudflared_background(cmd, allow_input, capture_output):
|
||||
output = subprocess.PIPE if capture_output else subprocess.DEVNULL
|
||||
stdin = subprocess.PIPE if allow_input else None
|
||||
cfd = None
|
||||
try:
|
||||
cfd = subprocess.Popen(cmd, stdin=stdin, stdout=output, stderr=output)
|
||||
yield cfd
|
||||
finally:
|
||||
cfd.terminate()
|
||||
if capture_output:
|
||||
LOGGER.info(f"cloudflared log: {cfd.stderr.read()}")
|
||||
if cfd:
|
||||
cfd.terminate()
|
||||
if capture_output:
|
||||
LOGGER.info(f"cloudflared log: {cfd.stderr.read()}")
|
||||
|
||||
|
||||
def wait_tunnel_ready(tunnel_url=None, require_min_connections=1, cfd_logs=None):
|
||||
@@ -106,13 +109,15 @@ def _log_cloudflared_logs(cfd_logs):
|
||||
LOGGER.warning(line)
|
||||
|
||||
|
||||
@retry(stop_max_attempt_number=MAX_RETRIES * BACKOFF_SECS, wait_fixed=1000)
|
||||
@retry(stop_max_attempt_number=MAX_RETRIES, wait_fixed=BACKOFF_SECS * 1000)
|
||||
def check_tunnel_not_connected():
|
||||
url = f'http://localhost:{METRICS_PORT}/ready'
|
||||
|
||||
try:
|
||||
resp = requests.get(url, timeout=1)
|
||||
resp = requests.get(url, timeout=BACKOFF_SECS)
|
||||
assert resp.status_code == 503, f"Expect {url} returns 503, got {resp.status_code}"
|
||||
assert resp.json()[
|
||||
"readyConnections"] == 0, "Expected all connections to be terminated (pending reconnect)"
|
||||
# cloudflared might already terminate
|
||||
except requests.exceptions.ConnectionError as e:
|
||||
LOGGER.warning(f"Failed to connect to {url}, error: {e}")
|
||||
|
||||
@@ -229,6 +229,19 @@ type OriginRequestConfig struct {
|
||||
IPRules []IngressIPRule `yaml:"ipRules" json:"ipRules,omitempty"`
|
||||
// Attempt to connect to origin with HTTP/2
|
||||
Http2Origin *bool `yaml:"http2Origin" json:"http2Origin,omitempty"`
|
||||
// Access holds all access related configs
|
||||
Access *AccessConfig `yaml:"access" json:"access,omitempty"`
|
||||
}
|
||||
|
||||
type AccessConfig struct {
|
||||
// Enabled when set to true will fail every request that does not arrive through an access authenticated endpoint.
|
||||
Enabled bool
|
||||
|
||||
// TeamName is the organization team name to get the public key certificates for.
|
||||
TeamName string `yaml:"teamName" json:"teamName,omitempty"`
|
||||
|
||||
// AudTag is the AudTag to verify access JWT against.
|
||||
AudTag []string `yaml:"audTag" json:"audTag,omitempty"`
|
||||
}
|
||||
|
||||
type IngressIPRule struct {
|
||||
|
||||
+33
-11
@@ -24,9 +24,16 @@ const (
|
||||
LogFieldConnIndex = "connIndex"
|
||||
MaxGracePeriod = time.Minute * 3
|
||||
MaxConcurrentStreams = math.MaxUint32
|
||||
|
||||
contentTypeHeader = "content-type"
|
||||
sseContentType = "text/event-stream"
|
||||
grpcContentType = "application/grpc"
|
||||
)
|
||||
|
||||
var switchingProtocolText = fmt.Sprintf("%d %s", http.StatusSwitchingProtocols, http.StatusText(http.StatusSwitchingProtocols))
|
||||
var (
|
||||
switchingProtocolText = fmt.Sprintf("%d %s", http.StatusSwitchingProtocols, http.StatusText(http.StatusSwitchingProtocols))
|
||||
flushableContentTypes = []string{sseContentType, grpcContentType}
|
||||
)
|
||||
|
||||
type Orchestrator interface {
|
||||
UpdateConfig(version int32, config []byte) *pogs.UpdateConfigurationResponse
|
||||
@@ -123,23 +130,24 @@ func (t Type) String() string {
|
||||
|
||||
// OriginProxy is how data flows from cloudflared to the origin services running behind it.
|
||||
type OriginProxy interface {
|
||||
ProxyHTTP(w ResponseWriter, tr *tracing.TracedRequest, isWebsocket bool) error
|
||||
ProxyHTTP(w ResponseWriter, tr *tracing.TracedHTTPRequest, isWebsocket bool) error
|
||||
ProxyTCP(ctx context.Context, rwa ReadWriteAcker, req *TCPRequest) error
|
||||
}
|
||||
|
||||
// TCPRequest defines the input format needed to perform a TCP proxy.
|
||||
type TCPRequest struct {
|
||||
Dest string
|
||||
CFRay string
|
||||
LBProbe bool
|
||||
FlowID string
|
||||
Dest string
|
||||
CFRay string
|
||||
LBProbe bool
|
||||
FlowID string
|
||||
CfTraceID string
|
||||
}
|
||||
|
||||
// ReadWriteAcker is a readwriter with the ability to Acknowledge to the downstream (edge) that the origin has
|
||||
// accepted the connection.
|
||||
type ReadWriteAcker interface {
|
||||
io.ReadWriter
|
||||
AckConnection() error
|
||||
AckConnection(tracePropagation string) error
|
||||
}
|
||||
|
||||
// HTTPResponseReadWriteAcker is an HTTP implementation of ReadWriteAcker.
|
||||
@@ -168,22 +176,28 @@ func (h *HTTPResponseReadWriteAcker) Write(p []byte) (int, error) {
|
||||
|
||||
// AckConnection acks an HTTP connection by sending a switch protocols status code that enables the caller to
|
||||
// upgrade to streams.
|
||||
func (h *HTTPResponseReadWriteAcker) AckConnection() error {
|
||||
func (h *HTTPResponseReadWriteAcker) AckConnection(tracePropagation string) error {
|
||||
resp := &http.Response{
|
||||
Status: switchingProtocolText,
|
||||
StatusCode: http.StatusSwitchingProtocols,
|
||||
ContentLength: -1,
|
||||
Header: http.Header{},
|
||||
}
|
||||
|
||||
if secWebsocketKey := h.req.Header.Get("Sec-WebSocket-Key"); secWebsocketKey != "" {
|
||||
resp.Header = websocket.NewResponseHeader(h.req)
|
||||
}
|
||||
|
||||
if tracePropagation != "" {
|
||||
resp.Header.Add(tracing.CanonicalCloudflaredTracingHeader, tracePropagation)
|
||||
}
|
||||
|
||||
return h.w.WriteRespHeaders(resp.StatusCode, resp.Header)
|
||||
}
|
||||
|
||||
type ResponseWriter interface {
|
||||
WriteRespHeaders(status int, header http.Header) error
|
||||
AddTrailer(trailerName, trailerValue string)
|
||||
io.Writer
|
||||
}
|
||||
|
||||
@@ -192,10 +206,18 @@ type ConnectedFuse interface {
|
||||
IsConnected() bool
|
||||
}
|
||||
|
||||
func IsServerSentEvent(headers http.Header) bool {
|
||||
if contentType := headers.Get("content-type"); contentType != "" {
|
||||
return strings.HasPrefix(strings.ToLower(contentType), "text/event-stream")
|
||||
// Helper method to let the caller know what content-types should require a flush on every
|
||||
// write to a ResponseWriter.
|
||||
func shouldFlush(headers http.Header) bool {
|
||||
if contentType := headers.Get(contentTypeHeader); contentType != "" {
|
||||
contentType = strings.ToLower(contentType)
|
||||
for _, c := range flushableContentTypes {
|
||||
if strings.HasPrefix(contentType, c) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@@ -6,11 +6,9 @@ import (
|
||||
"io"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/cloudflare/cloudflared/tracing"
|
||||
tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
|
||||
@@ -30,6 +28,8 @@ var (
|
||||
testLargeResp = make([]byte, largeFileSize)
|
||||
)
|
||||
|
||||
var _ ReadWriteAcker = (*HTTPResponseReadWriteAcker)(nil)
|
||||
|
||||
type testRequest struct {
|
||||
name string
|
||||
endpoint string
|
||||
@@ -60,7 +60,7 @@ type mockOriginProxy struct{}
|
||||
|
||||
func (moc *mockOriginProxy) ProxyHTTP(
|
||||
w ResponseWriter,
|
||||
tr *tracing.TracedRequest,
|
||||
tr *tracing.TracedHTTPRequest,
|
||||
isWebsocket bool,
|
||||
) error {
|
||||
req := tr.Request
|
||||
@@ -195,40 +195,3 @@ func (mcf mockConnectedFuse) Connected() {}
|
||||
func (mcf mockConnectedFuse) IsConnected() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func TestIsEventStream(t *testing.T) {
|
||||
tests := []struct {
|
||||
headers http.Header
|
||||
isEventStream bool
|
||||
}{
|
||||
{
|
||||
headers: newHeader("Content-Type", "text/event-stream"),
|
||||
isEventStream: true,
|
||||
},
|
||||
{
|
||||
headers: newHeader("content-type", "text/event-stream"),
|
||||
isEventStream: true,
|
||||
},
|
||||
{
|
||||
headers: newHeader("Content-Type", "text/event-stream; charset=utf-8"),
|
||||
isEventStream: true,
|
||||
},
|
||||
{
|
||||
headers: newHeader("Content-Type", "application/json"),
|
||||
isEventStream: false,
|
||||
},
|
||||
{
|
||||
headers: http.Header{},
|
||||
isEventStream: false,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
assert.Equal(t, test.isEventStream, IsServerSentEvent(test.headers))
|
||||
}
|
||||
}
|
||||
|
||||
func newHeader(key, value string) http.Header {
|
||||
header := http.Header{}
|
||||
header.Add(key, value)
|
||||
return header
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package connection
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
@@ -21,6 +22,7 @@ type controlStream struct {
|
||||
namedTunnelProperties *NamedTunnelProperties
|
||||
connIndex uint8
|
||||
edgeAddress net.IP
|
||||
protocol Protocol
|
||||
|
||||
newRPCClientFunc RPCClientFunc
|
||||
|
||||
@@ -51,6 +53,7 @@ func NewControlStream(
|
||||
newRPCClientFunc RPCClientFunc,
|
||||
gracefulShutdownC <-chan struct{},
|
||||
gracePeriod time.Duration,
|
||||
protocol Protocol,
|
||||
) ControlStreamHandler {
|
||||
if newRPCClientFunc == nil {
|
||||
newRPCClientFunc = newRegistrationRPCClient
|
||||
@@ -64,6 +67,7 @@ func NewControlStream(
|
||||
edgeAddress: edgeAddress,
|
||||
gracefulShutdownC: gracefulShutdownC,
|
||||
gracePeriod: gracePeriod,
|
||||
protocol: protocol,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,6 +84,9 @@ func (c *controlStream) ServeControlStream(
|
||||
rpcClient.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
c.observer.logServerInfo(c.connIndex, registrationDetails.Location, c.edgeAddress, fmt.Sprintf("Connection %s registered", registrationDetails.UUID))
|
||||
c.observer.sendConnectedEvent(c.connIndex, c.protocol, registrationDetails.Location)
|
||||
c.connectedFuse.Connected()
|
||||
|
||||
// if conn index is 0 and tunnel is not remotely managed, then send local ingress rules configuration
|
||||
|
||||
@@ -27,6 +27,10 @@ func (e *EdgeQuicDialError) Error() string {
|
||||
return "failed to dial to edge with quic: " + e.Cause.Error()
|
||||
}
|
||||
|
||||
func (e *EdgeQuicDialError) Unwrap() error {
|
||||
return e.Cause
|
||||
}
|
||||
|
||||
// RegisterTunnel error from server
|
||||
type ServerRegisterTunnelError struct {
|
||||
Cause error
|
||||
|
||||
@@ -5,6 +5,7 @@ type Event struct {
|
||||
Index uint8
|
||||
EventType Status
|
||||
Location string
|
||||
Protocol Protocol
|
||||
URL string
|
||||
}
|
||||
|
||||
|
||||
+7
-1
@@ -69,6 +69,7 @@ func NewH2muxConnection(
|
||||
connIndex uint8,
|
||||
observer *Observer,
|
||||
gracefulShutdownC <-chan struct{},
|
||||
log *zerolog.Logger,
|
||||
) (*h2muxConnection, error, bool) {
|
||||
h := &h2muxConnection{
|
||||
orchestrator: orchestrator,
|
||||
@@ -79,6 +80,7 @@ func NewH2muxConnection(
|
||||
observer: observer,
|
||||
gracefulShutdownC: gracefulShutdownC,
|
||||
newRPCClientFunc: newRegistrationRPCClient,
|
||||
log: log,
|
||||
}
|
||||
|
||||
// Establish a muxed connection with the edge
|
||||
@@ -234,7 +236,7 @@ func (h *h2muxConnection) ServeStream(stream *h2mux.MuxedStream) error {
|
||||
return err
|
||||
}
|
||||
|
||||
err = originProxy.ProxyHTTP(respWriter, tracing.NewTracedRequest(req), sourceConnectionType == TypeWebsocket)
|
||||
err = originProxy.ProxyHTTP(respWriter, tracing.NewTracedHTTPRequest(req, h.log), sourceConnectionType == TypeWebsocket)
|
||||
if err != nil {
|
||||
respWriter.WriteErrorResponse()
|
||||
}
|
||||
@@ -257,6 +259,10 @@ type h2muxRespWriter struct {
|
||||
*h2mux.MuxedStream
|
||||
}
|
||||
|
||||
func (rp *h2muxRespWriter) AddTrailer(trailerName, trailerValue string) {
|
||||
// do nothing. we don't support trailers over h2mux
|
||||
}
|
||||
|
||||
func (rp *h2muxRespWriter) WriteRespHeaders(status int, header http.Header) error {
|
||||
headers := H1ResponseToH2ResponseHeaders(status, header)
|
||||
headers = append(headers, h2mux.Header{Name: ResponseMetaHeader, Value: responseMetaHeaderOrigin})
|
||||
|
||||
@@ -47,8 +47,8 @@ func newH2MuxConnection(t require.TestingT) (*h2muxConnection, *h2mux.Muxer) {
|
||||
edgeMuxChan <- edgeMux
|
||||
}()
|
||||
var connIndex = uint8(0)
|
||||
testObserver := NewObserver(&log, &log, false)
|
||||
h2muxConn, err, _ := NewH2muxConnection(testOrchestrator, testGracePeriod, testMuxerConfig, originConn, connIndex, testObserver, nil)
|
||||
testObserver := NewObserver(&log, &log)
|
||||
h2muxConn, err, _ := NewH2muxConnection(testOrchestrator, testGracePeriod, testMuxerConfig, originConn, connIndex, testObserver, nil, &log)
|
||||
require.NoError(t, err)
|
||||
return h2muxConn, <-edgeMuxChan
|
||||
}
|
||||
|
||||
+26
-12
@@ -132,7 +132,7 @@ func (c *HTTP2Connection) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
case TypeWebsocket, TypeHTTP:
|
||||
stripWebsocketUpgradeHeader(r)
|
||||
// Check for tracing on request
|
||||
tr := tracing.NewTracedRequest(r)
|
||||
tr := tracing.NewTracedHTTPRequest(r, c.log)
|
||||
if err := originProxy.ProxyHTTP(respWriter, tr, connType == TypeWebsocket); err != nil {
|
||||
err := fmt.Errorf("Failed to proxy HTTP: %w", err)
|
||||
c.log.Error().Err(err)
|
||||
@@ -149,9 +149,10 @@ func (c *HTTP2Connection) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
rws := NewHTTPResponseReadWriterAcker(respWriter, r)
|
||||
if err := originProxy.ProxyTCP(r.Context(), rws, &TCPRequest{
|
||||
Dest: host,
|
||||
CFRay: FindCfRayHeader(r),
|
||||
LBProbe: IsLBProbeRequest(r),
|
||||
Dest: host,
|
||||
CFRay: FindCfRayHeader(r),
|
||||
LBProbe: IsLBProbeRequest(r),
|
||||
CfTraceID: r.Header.Get(tracing.TracerContextName),
|
||||
}); err != nil {
|
||||
respWriter.WriteErrorResponse()
|
||||
}
|
||||
@@ -190,11 +191,12 @@ func (c *HTTP2Connection) close() {
|
||||
}
|
||||
|
||||
type http2RespWriter struct {
|
||||
r io.Reader
|
||||
w http.ResponseWriter
|
||||
flusher http.Flusher
|
||||
shouldFlush bool
|
||||
log *zerolog.Logger
|
||||
r io.Reader
|
||||
w http.ResponseWriter
|
||||
flusher http.Flusher
|
||||
shouldFlush bool
|
||||
statusWritten bool
|
||||
log *zerolog.Logger
|
||||
}
|
||||
|
||||
func NewHTTP2RespWriter(r *http.Request, w http.ResponseWriter, connType Type, log *zerolog.Logger) (*http2RespWriter, error) {
|
||||
@@ -218,11 +220,20 @@ func NewHTTP2RespWriter(r *http.Request, w http.ResponseWriter, connType Type, l
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (rp *http2RespWriter) AddTrailer(trailerName, trailerValue string) {
|
||||
if !rp.statusWritten {
|
||||
rp.log.Warn().Msg("Tried to add Trailer to response before status written. Ignoring...")
|
||||
return
|
||||
}
|
||||
|
||||
rp.w.Header().Add(http2.TrailerPrefix+trailerName, trailerValue)
|
||||
}
|
||||
|
||||
func (rp *http2RespWriter) WriteRespHeaders(status int, header http.Header) error {
|
||||
dest := rp.w.Header()
|
||||
userHeaders := make(http.Header, len(header))
|
||||
for name, values := range header {
|
||||
// Since these are http2 headers, they're required to be lowercase
|
||||
// lowercase headers for simplicity check
|
||||
h2name := strings.ToLower(name)
|
||||
|
||||
if h2name == "content-length" {
|
||||
@@ -233,7 +244,7 @@ func (rp *http2RespWriter) WriteRespHeaders(status int, header http.Header) erro
|
||||
|
||||
if h2name == tracing.IntCloudflaredTracingHeader {
|
||||
// Add cf-int-cloudflared-tracing header outside of serialized userHeaders
|
||||
rp.w.Header()[tracing.CanonicalCloudflaredTracingHeader] = values
|
||||
dest[tracing.CanonicalCloudflaredTracingHeader] = values
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -246,18 +257,21 @@ func (rp *http2RespWriter) WriteRespHeaders(status int, header http.Header) erro
|
||||
|
||||
// Perform user header serialization and set them in the single header
|
||||
dest.Set(CanonicalResponseUserHeaders, SerializeHeaders(userHeaders))
|
||||
|
||||
rp.setResponseMetaHeader(responseMetaHeaderOrigin)
|
||||
// HTTP2 removes support for 101 Switching Protocols https://tools.ietf.org/html/rfc7540#section-8.1.1
|
||||
if status == http.StatusSwitchingProtocols {
|
||||
status = http.StatusOK
|
||||
}
|
||||
rp.w.WriteHeader(status)
|
||||
if IsServerSentEvent(header) {
|
||||
if shouldFlush(header) {
|
||||
rp.shouldFlush = true
|
||||
}
|
||||
if rp.shouldFlush {
|
||||
rp.flusher.Flush()
|
||||
}
|
||||
|
||||
rp.statusWritten = true
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ func newTestHTTP2Connection() (*HTTP2Connection, net.Conn) {
|
||||
edgeConn, cfdConn := net.Pipe()
|
||||
var connIndex = uint8(0)
|
||||
log := zerolog.Nop()
|
||||
obs := NewObserver(&log, &log, false)
|
||||
obs := NewObserver(&log, &log)
|
||||
controlStream := NewControlStream(
|
||||
obs,
|
||||
mockConnectedFuse{},
|
||||
@@ -43,6 +43,7 @@ func newTestHTTP2Connection() (*HTTP2Connection, net.Conn) {
|
||||
nil,
|
||||
nil,
|
||||
1*time.Second,
|
||||
HTTP2,
|
||||
)
|
||||
return NewHTTP2Connection(
|
||||
cfdConn,
|
||||
@@ -356,7 +357,7 @@ func TestServeControlStream(t *testing.T) {
|
||||
unregistered: make(chan struct{}),
|
||||
}
|
||||
|
||||
obs := NewObserver(&log, &log, false)
|
||||
obs := NewObserver(&log, &log)
|
||||
controlStream := NewControlStream(
|
||||
obs,
|
||||
mockConnectedFuse{},
|
||||
@@ -366,6 +367,7 @@ func TestServeControlStream(t *testing.T) {
|
||||
rpcClientFactory.newMockRPCClient,
|
||||
nil,
|
||||
1*time.Second,
|
||||
HTTP2,
|
||||
)
|
||||
http2Conn.controlStreamHandler = controlStream
|
||||
|
||||
@@ -407,7 +409,7 @@ func TestFailRegistration(t *testing.T) {
|
||||
unregistered: make(chan struct{}),
|
||||
}
|
||||
|
||||
obs := NewObserver(&log, &log, false)
|
||||
obs := NewObserver(&log, &log)
|
||||
controlStream := NewControlStream(
|
||||
obs,
|
||||
mockConnectedFuse{},
|
||||
@@ -417,6 +419,7 @@ func TestFailRegistration(t *testing.T) {
|
||||
rpcClientFactory.newMockRPCClient,
|
||||
nil,
|
||||
1*time.Second,
|
||||
HTTP2,
|
||||
)
|
||||
http2Conn.controlStreamHandler = controlStream
|
||||
|
||||
@@ -453,7 +456,7 @@ func TestGracefulShutdownHTTP2(t *testing.T) {
|
||||
events := &eventCollectorSink{}
|
||||
|
||||
shutdownC := make(chan struct{})
|
||||
obs := NewObserver(&log, &log, false)
|
||||
obs := NewObserver(&log, &log)
|
||||
obs.RegisterSink(events)
|
||||
controlStream := NewControlStream(
|
||||
obs,
|
||||
@@ -464,6 +467,7 @@ func TestGracefulShutdownHTTP2(t *testing.T) {
|
||||
rpcClientFactory.newMockRPCClient,
|
||||
shutdownC,
|
||||
1*time.Second,
|
||||
HTTP2,
|
||||
)
|
||||
|
||||
http2Conn.controlStreamHandler = controlStream
|
||||
|
||||
@@ -18,7 +18,6 @@ type Observer struct {
|
||||
logTransport *zerolog.Logger
|
||||
metrics *tunnelMetrics
|
||||
tunnelEventChan chan Event
|
||||
uiEnabled bool
|
||||
addSinkChan chan EventSink
|
||||
}
|
||||
|
||||
@@ -26,12 +25,11 @@ type EventSink interface {
|
||||
OnTunnelEvent(event Event)
|
||||
}
|
||||
|
||||
func NewObserver(log, logTransport *zerolog.Logger, uiEnabled bool) *Observer {
|
||||
func NewObserver(log, logTransport *zerolog.Logger) *Observer {
|
||||
o := &Observer{
|
||||
log: log,
|
||||
logTransport: logTransport,
|
||||
metrics: newTunnelMetrics(),
|
||||
uiEnabled: uiEnabled,
|
||||
tunnelEventChan: make(chan Event, observerChannelBufferSize),
|
||||
addSinkChan: make(chan EventSink, observerChannelBufferSize),
|
||||
}
|
||||
@@ -57,8 +55,8 @@ func (o *Observer) sendRegisteringEvent(connIndex uint8) {
|
||||
o.sendEvent(Event{Index: connIndex, EventType: RegisteringTunnel})
|
||||
}
|
||||
|
||||
func (o *Observer) sendConnectedEvent(connIndex uint8, location string) {
|
||||
o.sendEvent(Event{Index: connIndex, EventType: Connected, Location: location})
|
||||
func (o *Observer) sendConnectedEvent(connIndex uint8, protocol Protocol, location string) {
|
||||
o.sendEvent(Event{Index: connIndex, EventType: Connected, Protocol: protocol, Location: location})
|
||||
}
|
||||
|
||||
func (o *Observer) SendURL(url string) {
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
func TestSendUrl(t *testing.T) {
|
||||
observer := NewObserver(&log, &log, false)
|
||||
observer := NewObserver(&log, &log)
|
||||
|
||||
observer.SendURL("my-url.com")
|
||||
assert.Equal(t, 1.0, getCounterValue(t, observer.metrics.userHostnamesCounts, "https://my-url.com"))
|
||||
@@ -63,7 +63,7 @@ func TestRegisterServerLocation(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestObserverEventsDontBlock(t *testing.T) {
|
||||
observer := NewObserver(&log, &log, false)
|
||||
observer := NewObserver(&log, &log)
|
||||
var mu sync.Mutex
|
||||
observer.RegisterSink(EventSinkFunc(func(_ Event) {
|
||||
// callback will block if lock is already held
|
||||
|
||||
+23
-6
@@ -1,6 +1,7 @@
|
||||
package connection
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"sync"
|
||||
@@ -130,6 +131,7 @@ type autoProtocolSelector struct {
|
||||
refreshAfter time.Time
|
||||
ttl time.Duration
|
||||
log *zerolog.Logger
|
||||
needPQ bool
|
||||
}
|
||||
|
||||
func newAutoProtocolSelector(
|
||||
@@ -139,6 +141,7 @@ func newAutoProtocolSelector(
|
||||
fetchFunc PercentageFetcher,
|
||||
ttl time.Duration,
|
||||
log *zerolog.Logger,
|
||||
needPQ bool,
|
||||
) *autoProtocolSelector {
|
||||
return &autoProtocolSelector{
|
||||
current: current,
|
||||
@@ -148,6 +151,7 @@ func newAutoProtocolSelector(
|
||||
refreshAfter: time.Now().Add(ttl),
|
||||
ttl: ttl,
|
||||
log: log,
|
||||
needPQ: needPQ,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,6 +191,9 @@ func getProtocol(protocolPool []Protocol, fetchFunc PercentageFetcher, switchThr
|
||||
func (s *autoProtocolSelector) Fallback() (Protocol, bool) {
|
||||
s.lock.RLock()
|
||||
defer s.lock.RUnlock()
|
||||
if s.needPQ {
|
||||
return 0, false
|
||||
}
|
||||
return s.current.fallback()
|
||||
}
|
||||
|
||||
@@ -199,9 +206,14 @@ func NewProtocolSelector(
|
||||
fetchFunc PercentageFetcher,
|
||||
ttl time.Duration,
|
||||
log *zerolog.Logger,
|
||||
needPQ bool,
|
||||
) (ProtocolSelector, error) {
|
||||
// Classic tunnel is only supported with h2mux
|
||||
if namedTunnel == nil {
|
||||
if needPQ {
|
||||
return nil, errors.New("Classic tunnel does not support post-quantum")
|
||||
}
|
||||
|
||||
return &staticProtocolSelector{
|
||||
current: H2mux,
|
||||
}, nil
|
||||
@@ -209,8 +221,11 @@ func NewProtocolSelector(
|
||||
|
||||
threshold := switchThreshold(namedTunnel.Credentials.AccountTag)
|
||||
fetchedProtocol, err := getProtocol([]Protocol{QUIC, HTTP2}, fetchFunc, threshold)
|
||||
if err != nil {
|
||||
log.Err(err).Msg("Unable to lookup protocol. Defaulting to `http2`. If this fails, you can set `--protocol h2mux` in your cloudflared command.")
|
||||
if err != nil && protocolFlag == "auto" {
|
||||
log.Err(err).Msg("Unable to lookup protocol. Defaulting to `http2`. If this fails, you can attempt `--protocol quic` instead.")
|
||||
if needPQ {
|
||||
return nil, errors.New("http2 does not support post-quantum")
|
||||
}
|
||||
return &staticProtocolSelector{
|
||||
current: HTTP2,
|
||||
}, nil
|
||||
@@ -221,10 +236,10 @@ func NewProtocolSelector(
|
||||
protocolFlag = HTTP2.String()
|
||||
fetchedProtocol = HTTP2Warp
|
||||
}
|
||||
return selectWarpRoutingProtocols(protocolFlag, fetchFunc, ttl, log, threshold, fetchedProtocol)
|
||||
return selectWarpRoutingProtocols(protocolFlag, fetchFunc, ttl, log, threshold, fetchedProtocol, needPQ)
|
||||
}
|
||||
|
||||
return selectNamedTunnelProtocols(protocolFlag, fetchFunc, ttl, log, threshold, fetchedProtocol)
|
||||
return selectNamedTunnelProtocols(protocolFlag, fetchFunc, ttl, log, threshold, fetchedProtocol, needPQ)
|
||||
}
|
||||
|
||||
func selectNamedTunnelProtocols(
|
||||
@@ -234,6 +249,7 @@ func selectNamedTunnelProtocols(
|
||||
log *zerolog.Logger,
|
||||
threshold int32,
|
||||
protocol Protocol,
|
||||
needPQ bool,
|
||||
) (ProtocolSelector, error) {
|
||||
// If the user picks a protocol, then we stick to it no matter what.
|
||||
switch protocolFlag {
|
||||
@@ -248,7 +264,7 @@ func selectNamedTunnelProtocols(
|
||||
// If the user does not pick (hopefully the majority) then we use the one derived from the TXT DNS record and
|
||||
// fallback on failures.
|
||||
if protocolFlag == AutoSelectFlag {
|
||||
return newAutoProtocolSelector(protocol, []Protocol{QUIC, HTTP2, H2mux}, threshold, fetchFunc, ttl, log), nil
|
||||
return newAutoProtocolSelector(protocol, []Protocol{QUIC, HTTP2, H2mux}, threshold, fetchFunc, ttl, log, needPQ), nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("Unknown protocol %s, %s", protocolFlag, AvailableProtocolFlagMessage)
|
||||
@@ -261,6 +277,7 @@ func selectWarpRoutingProtocols(
|
||||
log *zerolog.Logger,
|
||||
threshold int32,
|
||||
protocol Protocol,
|
||||
needPQ bool,
|
||||
) (ProtocolSelector, error) {
|
||||
// If the user picks a protocol, then we stick to it no matter what.
|
||||
switch protocolFlag {
|
||||
@@ -273,7 +290,7 @@ func selectWarpRoutingProtocols(
|
||||
// If the user does not pick (hopefully the majority) then we use the one derived from the TXT DNS record and
|
||||
// fallback on failures.
|
||||
if protocolFlag == AutoSelectFlag {
|
||||
return newAutoProtocolSelector(protocol, []Protocol{QUICWarp, HTTP2Warp}, threshold, fetchFunc, ttl, log), nil
|
||||
return newAutoProtocolSelector(protocol, []Protocol{QUICWarp, HTTP2Warp}, threshold, fetchFunc, ttl, log, needPQ), nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("Unknown protocol %s, %s", protocolFlag, AvailableProtocolFlagMessage)
|
||||
|
||||
@@ -219,7 +219,7 @@ func TestNewProtocolSelector(t *testing.T) {
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
selector, err := NewProtocolSelector(test.protocol, test.warpRoutingEnabled, test.namedTunnelConfig, test.fetchFunc, testNoTTL, &log)
|
||||
selector, err := NewProtocolSelector(test.protocol, test.warpRoutingEnabled, test.namedTunnelConfig, test.fetchFunc, testNoTTL, &log, false)
|
||||
if test.wantErr {
|
||||
assert.Error(t, err, fmt.Sprintf("test %s failed", test.name))
|
||||
} else {
|
||||
@@ -237,7 +237,7 @@ func TestNewProtocolSelector(t *testing.T) {
|
||||
|
||||
func TestAutoProtocolSelectorRefresh(t *testing.T) {
|
||||
fetcher := dynamicMockFetcher{}
|
||||
selector, err := NewProtocolSelector(AutoSelectFlag, noWarpRoutingEnabled, testNamedTunnelProperties, fetcher.fetch(), testNoTTL, &log)
|
||||
selector, err := NewProtocolSelector(AutoSelectFlag, noWarpRoutingEnabled, testNamedTunnelProperties, fetcher.fetch(), testNoTTL, &log, false)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, H2mux, selector.Current())
|
||||
|
||||
@@ -267,7 +267,7 @@ func TestAutoProtocolSelectorRefresh(t *testing.T) {
|
||||
func TestHTTP2ProtocolSelectorRefresh(t *testing.T) {
|
||||
fetcher := dynamicMockFetcher{}
|
||||
// Since the user chooses http2 on purpose, we always stick to it.
|
||||
selector, err := NewProtocolSelector("http2", noWarpRoutingEnabled, testNamedTunnelProperties, fetcher.fetch(), testNoTTL, &log)
|
||||
selector, err := NewProtocolSelector("http2", noWarpRoutingEnabled, testNamedTunnelProperties, fetcher.fetch(), testNoTTL, &log, false)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, HTTP2, selector.Current())
|
||||
|
||||
@@ -297,7 +297,7 @@ func TestHTTP2ProtocolSelectorRefresh(t *testing.T) {
|
||||
func TestProtocolSelectorRefreshTTL(t *testing.T) {
|
||||
fetcher := dynamicMockFetcher{}
|
||||
fetcher.protocolPercents = edgediscovery.ProtocolPercents{edgediscovery.ProtocolPercent{Protocol: "quic", Percentage: 100}}
|
||||
selector, err := NewProtocolSelector(AutoSelectFlag, noWarpRoutingEnabled, testNamedTunnelProperties, fetcher.fetch(), time.Hour, &log)
|
||||
selector, err := NewProtocolSelector(AutoSelectFlag, noWarpRoutingEnabled, testNamedTunnelProperties, fetcher.fetch(), time.Hour, &log, false)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, QUIC, selector.Current())
|
||||
|
||||
|
||||
+148
-28
@@ -7,18 +7,23 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/lucas-clemente/quic-go"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/cloudflare/cloudflared/datagramsession"
|
||||
"github.com/cloudflare/cloudflared/ingress"
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
quicpogs "github.com/cloudflare/cloudflared/quic"
|
||||
"github.com/cloudflare/cloudflared/tracing"
|
||||
tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
|
||||
@@ -33,14 +38,20 @@ const (
|
||||
HTTPHostKey = "HttpHost"
|
||||
|
||||
QUICMetadataFlowID = "FlowID"
|
||||
// emperically this capacity has been working well
|
||||
demuxChanCapacity = 16
|
||||
)
|
||||
|
||||
// QUICConnection represents the type that facilitates Proxying via QUIC streams.
|
||||
type QUICConnection struct {
|
||||
session quic.Connection
|
||||
logger *zerolog.Logger
|
||||
orchestrator Orchestrator
|
||||
sessionManager datagramsession.Manager
|
||||
session quic.Connection
|
||||
logger *zerolog.Logger
|
||||
orchestrator Orchestrator
|
||||
// sessionManager tracks active sessions. It receives datagrams from quic connection via datagramMuxer
|
||||
sessionManager datagramsession.Manager
|
||||
// datagramMuxer mux/demux datagrams from quic connection
|
||||
datagramMuxer quicpogs.BaseDatagramMuxer
|
||||
packetRouter *packet.Router
|
||||
controlStreamHandler ControlStreamHandler
|
||||
connOptions *tunnelpogs.ConnectionOptions
|
||||
}
|
||||
@@ -54,24 +65,34 @@ func NewQUICConnection(
|
||||
connOptions *tunnelpogs.ConnectionOptions,
|
||||
controlStreamHandler ControlStreamHandler,
|
||||
logger *zerolog.Logger,
|
||||
icmpRouter packet.ICMPRouter,
|
||||
) (*QUICConnection, error) {
|
||||
session, err := quic.DialAddr(edgeAddr.String(), tlsConfig, quicConfig)
|
||||
if err != nil {
|
||||
return nil, &EdgeQuicDialError{Cause: err}
|
||||
}
|
||||
|
||||
datagramMuxer, err := quicpogs.NewDatagramMuxer(session, logger)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
sessionDemuxChan := make(chan *packet.Session, demuxChanCapacity)
|
||||
var (
|
||||
datagramMuxer quicpogs.BaseDatagramMuxer
|
||||
pr *packet.Router
|
||||
)
|
||||
if icmpRouter != nil {
|
||||
datagramMuxerV2 := quicpogs.NewDatagramMuxerV2(session, logger, sessionDemuxChan)
|
||||
pr = packet.NewRouter(datagramMuxerV2, &returnPipe{muxer: datagramMuxerV2}, icmpRouter, logger)
|
||||
datagramMuxer = datagramMuxerV2
|
||||
} else {
|
||||
datagramMuxer = quicpogs.NewDatagramMuxer(session, logger, sessionDemuxChan)
|
||||
}
|
||||
|
||||
sessionManager := datagramsession.NewManager(datagramMuxer, logger)
|
||||
sessionManager := datagramsession.NewManager(logger, datagramMuxer.SendToSession, sessionDemuxChan)
|
||||
|
||||
return &QUICConnection{
|
||||
session: session,
|
||||
orchestrator: orchestrator,
|
||||
logger: logger,
|
||||
sessionManager: sessionManager,
|
||||
datagramMuxer: datagramMuxer,
|
||||
packetRouter: pr,
|
||||
controlStreamHandler: controlStreamHandler,
|
||||
connOptions: connOptions,
|
||||
}, nil
|
||||
@@ -108,6 +129,17 @@ func (q *QUICConnection) Serve(ctx context.Context) error {
|
||||
return q.sessionManager.Serve(ctx)
|
||||
})
|
||||
|
||||
errGroup.Go(func() error {
|
||||
defer cancel()
|
||||
return q.datagramMuxer.ServeReceive(ctx)
|
||||
})
|
||||
if q.packetRouter != nil {
|
||||
errGroup.Go(func() error {
|
||||
defer cancel()
|
||||
return q.packetRouter.Serve(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
return errGroup.Wait()
|
||||
}
|
||||
|
||||
@@ -143,15 +175,21 @@ func (q *QUICConnection) acceptStream(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func (q *QUICConnection) runStream(quicStream quic.Stream) {
|
||||
ctx := quicStream.Context()
|
||||
stream := quicpogs.NewSafeStreamCloser(quicStream)
|
||||
defer stream.Close()
|
||||
|
||||
if err := q.handleStream(stream); err != nil {
|
||||
// we are going to fuse readers/writers from stream <- cloudflared -> origin, and we want to guarantee that
|
||||
// code executed in the code path of handleStream don't trigger an earlier close to the downstream write stream.
|
||||
// So, we wrap the stream with a no-op write closer and only this method can actually close write side of the stream.
|
||||
// A call to close will simulate a close to the read-side, which will fail subsequent reads.
|
||||
noCloseStream := &nopCloserReadWriter{ReadWriteCloser: stream}
|
||||
if err := q.handleStream(ctx, noCloseStream); err != nil {
|
||||
q.logger.Err(err).Msg("Failed to handle QUIC stream")
|
||||
}
|
||||
}
|
||||
|
||||
func (q *QUICConnection) handleStream(stream io.ReadWriteCloser) error {
|
||||
func (q *QUICConnection) handleStream(ctx context.Context, stream io.ReadWriteCloser) error {
|
||||
signature, err := quicpogs.DetermineProtocol(stream)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -162,7 +200,7 @@ func (q *QUICConnection) handleStream(stream io.ReadWriteCloser) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return q.handleDataStream(reqServerStream)
|
||||
return q.handleDataStream(ctx, reqServerStream)
|
||||
case quicpogs.RPCStreamProtocolSignature:
|
||||
rpcStream, err := quicpogs.NewRPCServerStream(stream, signature)
|
||||
if err != nil {
|
||||
@@ -174,13 +212,13 @@ func (q *QUICConnection) handleStream(stream io.ReadWriteCloser) error {
|
||||
}
|
||||
}
|
||||
|
||||
func (q *QUICConnection) handleDataStream(stream *quicpogs.RequestServerStream) error {
|
||||
func (q *QUICConnection) handleDataStream(ctx context.Context, stream *quicpogs.RequestServerStream) error {
|
||||
request, err := stream.ReadConnectRequestData()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := q.dispatchRequest(stream, err, request); err != nil {
|
||||
if err := q.dispatchRequest(ctx, stream, err, request); err != nil {
|
||||
_ = stream.WriteConnectResponseData(err)
|
||||
q.logger.Err(err).Str("type", request.Type.String()).Str("dest", request.Dest).Msg("Request failed")
|
||||
}
|
||||
@@ -188,7 +226,7 @@ func (q *QUICConnection) handleDataStream(stream *quicpogs.RequestServerStream)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (q *QUICConnection) dispatchRequest(stream *quicpogs.RequestServerStream, err error, request *quicpogs.ConnectRequest) error {
|
||||
func (q *QUICConnection) dispatchRequest(ctx context.Context, stream *quicpogs.RequestServerStream, err error, request *quicpogs.ConnectRequest) error {
|
||||
originProxy, err := q.orchestrator.GetOriginProxy()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -196,7 +234,7 @@ func (q *QUICConnection) dispatchRequest(stream *quicpogs.RequestServerStream, e
|
||||
|
||||
switch request.Type {
|
||||
case quicpogs.ConnectionTypeHTTP, quicpogs.ConnectionTypeWebsocket:
|
||||
tracedReq, err := buildHTTPRequest(request, stream)
|
||||
tracedReq, err := buildHTTPRequest(ctx, request, stream, q.logger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -206,9 +244,10 @@ func (q *QUICConnection) dispatchRequest(stream *quicpogs.RequestServerStream, e
|
||||
case quicpogs.ConnectionTypeTCP:
|
||||
rwa := &streamReadWriteAcker{stream}
|
||||
metadata := request.MetadataMap()
|
||||
return originProxy.ProxyTCP(context.Background(), rwa, &TCPRequest{
|
||||
Dest: request.Dest,
|
||||
FlowID: metadata[QUICMetadataFlowID],
|
||||
return originProxy.ProxyTCP(ctx, rwa, &TCPRequest{
|
||||
Dest: request.Dest,
|
||||
FlowID: metadata[QUICMetadataFlowID],
|
||||
CfTraceID: metadata[tracing.TracerContextName],
|
||||
})
|
||||
}
|
||||
return nil
|
||||
@@ -219,24 +258,42 @@ func (q *QUICConnection) handleRPCStream(rpcStream *quicpogs.RPCServerStream) er
|
||||
}
|
||||
|
||||
// RegisterUdpSession is the RPC method invoked by edge to register and run a session
|
||||
func (q *QUICConnection) RegisterUdpSession(ctx context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeAfterIdleHint time.Duration) error {
|
||||
func (q *QUICConnection) RegisterUdpSession(ctx context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeAfterIdleHint time.Duration, traceContext string) (*tunnelpogs.RegisterUdpSessionResponse, error) {
|
||||
traceCtx := tracing.NewTracedContext(ctx, traceContext, q.logger)
|
||||
ctx, registerSpan := traceCtx.Tracer().Start(traceCtx, "register-session", trace.WithAttributes(
|
||||
attribute.String("session-id", sessionID.String()),
|
||||
attribute.String("dst", fmt.Sprintf("%s:%d", dstIP, dstPort)),
|
||||
))
|
||||
// Each session is a series of datagram from an eyeball to a dstIP:dstPort.
|
||||
// (src port, dst IP, dst port) uniquely identifies a session, so it needs a dedicated connected socket.
|
||||
originProxy, err := ingress.DialUDP(dstIP, dstPort)
|
||||
if err != nil {
|
||||
q.logger.Err(err).Msgf("Failed to create udp proxy to %s:%d", dstIP, dstPort)
|
||||
return err
|
||||
tracing.EndWithErrorStatus(registerSpan, err)
|
||||
return nil, err
|
||||
}
|
||||
registerSpan.SetAttributes(
|
||||
attribute.Bool("socket-bind-success", true),
|
||||
attribute.String("src", originProxy.LocalAddr().String()),
|
||||
)
|
||||
|
||||
session, err := q.sessionManager.RegisterSession(ctx, sessionID, originProxy)
|
||||
if err != nil {
|
||||
q.logger.Err(err).Str("sessionID", sessionID.String()).Msgf("Failed to register udp session")
|
||||
return err
|
||||
tracing.EndWithErrorStatus(registerSpan, err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
go q.serveUDPSession(session, closeAfterIdleHint)
|
||||
|
||||
q.logger.Debug().Str("sessionID", sessionID.String()).Str("src", originProxy.LocalAddr().String()).Str("dst", fmt.Sprintf("%s:%d", dstIP, dstPort)).Msgf("Registered session")
|
||||
return nil
|
||||
tracing.End(registerSpan)
|
||||
|
||||
resp := tunnelpogs.RegisterUdpSessionResponse{
|
||||
Spans: traceCtx.GetProtoSpans(),
|
||||
}
|
||||
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
func (q *QUICConnection) serveUDPSession(session *datagramsession.Session, closeAfterIdleHint time.Duration) {
|
||||
@@ -295,8 +352,12 @@ type streamReadWriteAcker struct {
|
||||
}
|
||||
|
||||
// AckConnection acks response back to the proxy.
|
||||
func (s *streamReadWriteAcker) AckConnection() error {
|
||||
return s.WriteConnectResponseData(nil)
|
||||
func (s *streamReadWriteAcker) AckConnection(tracePropagation string) error {
|
||||
metadata := quicpogs.Metadata{
|
||||
Key: tracing.CanonicalCloudflaredTracingHeader,
|
||||
Val: tracePropagation,
|
||||
}
|
||||
return s.WriteConnectResponseData(nil, metadata)
|
||||
}
|
||||
|
||||
// httpResponseAdapter translates responses written by the HTTP Proxy into ones that can be used in QUIC.
|
||||
@@ -308,6 +369,10 @@ func newHTTPResponseAdapter(s *quicpogs.RequestServerStream) httpResponseAdapter
|
||||
return httpResponseAdapter{s}
|
||||
}
|
||||
|
||||
func (hrw httpResponseAdapter) AddTrailer(trailerName, trailerValue string) {
|
||||
// we do not support trailers over QUIC
|
||||
}
|
||||
|
||||
func (hrw httpResponseAdapter) WriteRespHeaders(status int, header http.Header) error {
|
||||
metadata := make([]quicpogs.Metadata, 0)
|
||||
metadata = append(metadata, quicpogs.Metadata{Key: "HttpStatus", Val: strconv.Itoa(status)})
|
||||
@@ -324,14 +389,19 @@ func (hrw httpResponseAdapter) WriteErrorResponse(err error) {
|
||||
hrw.WriteConnectResponseData(err, quicpogs.Metadata{Key: "HttpStatus", Val: strconv.Itoa(http.StatusBadGateway)})
|
||||
}
|
||||
|
||||
func buildHTTPRequest(connectRequest *quicpogs.ConnectRequest, body io.ReadCloser) (*tracing.TracedRequest, error) {
|
||||
func buildHTTPRequest(
|
||||
ctx context.Context,
|
||||
connectRequest *quicpogs.ConnectRequest,
|
||||
body io.ReadCloser,
|
||||
log *zerolog.Logger,
|
||||
) (*tracing.TracedHTTPRequest, error) {
|
||||
metadata := connectRequest.MetadataMap()
|
||||
dest := connectRequest.Dest
|
||||
method := metadata[HTTPMethodKey]
|
||||
host := metadata[HTTPHostKey]
|
||||
isWebsocket := connectRequest.Type == quicpogs.ConnectionTypeWebsocket
|
||||
|
||||
req, err := http.NewRequest(method, dest, body)
|
||||
req, err := http.NewRequestWithContext(ctx, method, dest, body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -366,7 +436,7 @@ func buildHTTPRequest(connectRequest *quicpogs.ConnectRequest, body io.ReadClose
|
||||
stripWebsocketUpgradeHeader(req)
|
||||
|
||||
// Check for tracing on request
|
||||
tracedReq := tracing.NewTracedRequest(req)
|
||||
tracedReq := tracing.NewTracedHTTPRequest(req, log)
|
||||
return tracedReq, err
|
||||
}
|
||||
|
||||
@@ -384,3 +454,53 @@ func isTransferEncodingChunked(req *http.Request) bool {
|
||||
// separated value as well.
|
||||
return strings.Contains(strings.ToLower(transferEncodingVal), "chunked")
|
||||
}
|
||||
|
||||
// A helper struct that guarantees a call to close only affects read side, but not write side.
|
||||
type nopCloserReadWriter struct {
|
||||
io.ReadWriteCloser
|
||||
|
||||
// for use by Read only
|
||||
// we don't need a memory barrier here because there is an implicit assumption that
|
||||
// Read calls can't happen concurrently by different go-routines.
|
||||
sawEOF bool
|
||||
// should be updated and read using atomic primitives.
|
||||
// value is read in Read method and written in Close method, which could be done by different
|
||||
// go-routines.
|
||||
closed uint32
|
||||
}
|
||||
|
||||
func (np *nopCloserReadWriter) Read(p []byte) (n int, err error) {
|
||||
if np.sawEOF {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
if atomic.LoadUint32(&np.closed) > 0 {
|
||||
return 0, fmt.Errorf("closed by handler")
|
||||
}
|
||||
|
||||
n, err = np.ReadWriteCloser.Read(p)
|
||||
if err == io.EOF {
|
||||
np.sawEOF = true
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (np *nopCloserReadWriter) Close() error {
|
||||
atomic.StoreUint32(&np.closed, 1)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// returnPipe wraps DatagramMuxerV2 to satisfy the packet.FunnelUniPipe interface
|
||||
type returnPipe struct {
|
||||
muxer *quicpogs.DatagramMuxerV2
|
||||
}
|
||||
|
||||
func (rp *returnPipe) SendPacket(dst netip.Addr, pk packet.RawPacket) error {
|
||||
return rp.muxer.SendPacket(pk)
|
||||
}
|
||||
|
||||
func (rp *returnPipe) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
+66
-8
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -25,17 +26,21 @@ import (
|
||||
"github.com/cloudflare/cloudflared/datagramsession"
|
||||
quicpogs "github.com/cloudflare/cloudflared/quic"
|
||||
"github.com/cloudflare/cloudflared/tracing"
|
||||
"github.com/cloudflare/cloudflared/tunnelrpc/pogs"
|
||||
tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
|
||||
)
|
||||
|
||||
var (
|
||||
testTLSServerConfig = quicpogs.GenerateTLSConfig()
|
||||
testQUICConfig = &quic.Config{
|
||||
KeepAlivePeriod: 5 * time.Second,
|
||||
EnableDatagrams: true,
|
||||
ConnectionIDLength: 16,
|
||||
KeepAlivePeriod: 5 * time.Second,
|
||||
EnableDatagrams: true,
|
||||
}
|
||||
)
|
||||
|
||||
var _ ReadWriteAcker = (*streamReadWriteAcker)(nil)
|
||||
|
||||
// TestQUICServer tests if a quic server accepts and responds to a quic client with the acceptance protocol.
|
||||
// It also serves as a demonstration for communication with the QUIC connection started by a cloudflared.
|
||||
func TestQUICServer(t *testing.T) {
|
||||
@@ -220,7 +225,7 @@ func quicServer(
|
||||
|
||||
type mockOriginProxyWithRequest struct{}
|
||||
|
||||
func (moc *mockOriginProxyWithRequest) ProxyHTTP(w ResponseWriter, tr *tracing.TracedRequest, isWebsocket bool) error {
|
||||
func (moc *mockOriginProxyWithRequest) ProxyHTTP(w ResponseWriter, tr *tracing.TracedHTTPRequest, isWebsocket bool) error {
|
||||
// These are a series of crude tests to ensure the headers and http related data is transferred from
|
||||
// metadata.
|
||||
r := tr.Request
|
||||
@@ -475,9 +480,10 @@ func TestBuildHTTPRequest(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
log := zerolog.Nop()
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
req, err := buildHTTPRequest(test.connectRequest, test.body)
|
||||
req, err := buildHTTPRequest(context.Background(), test.connectRequest, test.body, &log)
|
||||
assert.NoError(t, err)
|
||||
test.req = test.req.WithContext(req.Context())
|
||||
assert.Equal(t, test.req, req.Request)
|
||||
@@ -486,7 +492,7 @@ func TestBuildHTTPRequest(t *testing.T) {
|
||||
}
|
||||
|
||||
func (moc *mockOriginProxyWithRequest) ProxyTCP(ctx context.Context, rwa ReadWriteAcker, tcpRequest *TCPRequest) error {
|
||||
rwa.AckConnection()
|
||||
rwa.AckConnection("")
|
||||
io.Copy(rwa, rwa)
|
||||
return nil
|
||||
}
|
||||
@@ -500,6 +506,7 @@ func TestServeUDPSession(t *testing.T) {
|
||||
defer udpListener.Close()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
val := udpListener.LocalAddr()
|
||||
|
||||
// Establish QUIC connection with edge
|
||||
edgeQUICSessionChan := make(chan quic.Connection)
|
||||
@@ -512,7 +519,7 @@ func TestServeUDPSession(t *testing.T) {
|
||||
edgeQUICSessionChan <- edgeQUICSession
|
||||
}()
|
||||
|
||||
qc := testQUICConnection(udpListener.LocalAddr(), t)
|
||||
qc := testQUICConnection(val, t)
|
||||
go qc.Serve(ctx)
|
||||
|
||||
edgeQUICSession := <-edgeQUICSessionChan
|
||||
@@ -522,6 +529,44 @@ func TestServeUDPSession(t *testing.T) {
|
||||
cancel()
|
||||
}
|
||||
|
||||
func TestNopCloserReadWriterCloseBeforeEOF(t *testing.T) {
|
||||
readerWriter := nopCloserReadWriter{ReadWriteCloser: &mockReaderNoopWriter{Reader: strings.NewReader("123456789")}}
|
||||
buffer := make([]byte, 5)
|
||||
|
||||
n, err := readerWriter.Read(buffer)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, n, 5)
|
||||
|
||||
// close
|
||||
require.NoError(t, readerWriter.Close())
|
||||
|
||||
// read should get error
|
||||
n, err = readerWriter.Read(buffer)
|
||||
require.Equal(t, n, 0)
|
||||
require.Equal(t, err, fmt.Errorf("closed by handler"))
|
||||
}
|
||||
|
||||
func TestNopCloserReadWriterCloseAfterEOF(t *testing.T) {
|
||||
readerWriter := nopCloserReadWriter{ReadWriteCloser: &mockReaderNoopWriter{Reader: strings.NewReader("123456789")}}
|
||||
buffer := make([]byte, 20)
|
||||
|
||||
n, err := readerWriter.Read(buffer)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, n, 9)
|
||||
|
||||
// force another read to read eof
|
||||
_, err = readerWriter.Read(buffer)
|
||||
require.Equal(t, err, io.EOF)
|
||||
|
||||
// close
|
||||
require.NoError(t, readerWriter.Close())
|
||||
|
||||
// read should get EOF still
|
||||
n, err = readerWriter.Read(buffer)
|
||||
require.Equal(t, n, 0)
|
||||
require.Equal(t, err, io.EOF)
|
||||
}
|
||||
|
||||
func serveSession(ctx context.Context, qc *QUICConnection, edgeQUICSession quic.Connection, closeType closeReason, expectedReason string, t *testing.T) {
|
||||
var (
|
||||
payload = []byte(t.Name())
|
||||
@@ -608,8 +653,8 @@ type mockSessionRPCServer struct {
|
||||
calledUnregisterChan chan struct{}
|
||||
}
|
||||
|
||||
func (s mockSessionRPCServer) RegisterUdpSession(ctx context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeIdleAfter time.Duration) error {
|
||||
return fmt.Errorf("mockSessionRPCServer doesn't implement RegisterUdpSession")
|
||||
func (s mockSessionRPCServer) RegisterUdpSession(ctx context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeIdleAfter time.Duration, traceContext string) (*pogs.RegisterUdpSessionResponse, error) {
|
||||
return nil, fmt.Errorf("mockSessionRPCServer doesn't implement RegisterUdpSession")
|
||||
}
|
||||
|
||||
func (s mockSessionRPCServer) UnregisterUdpSession(ctx context.Context, sessionID uuid.UUID, reason string) error {
|
||||
@@ -638,7 +683,20 @@ func testQUICConnection(udpListenerAddr net.Addr, t *testing.T) *QUICConnection
|
||||
&tunnelpogs.ConnectionOptions{},
|
||||
fakeControlStream{},
|
||||
&log,
|
||||
nil,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return qc
|
||||
}
|
||||
|
||||
type mockReaderNoopWriter struct {
|
||||
io.Reader
|
||||
}
|
||||
|
||||
func (m *mockReaderNoopWriter) Write(p []byte) (n int, err error) {
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (m *mockReaderNoopWriter) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
+5
-4
@@ -117,9 +117,6 @@ func (rsc *registrationServerClient) RegisterConnection(
|
||||
|
||||
observer.metrics.regSuccess.WithLabelValues("registerConnection").Inc()
|
||||
|
||||
observer.logServerInfo(connIndex, conn.Location, edgeAddress, fmt.Sprintf("Connection %s registered", conn.UUID))
|
||||
observer.sendConnectedEvent(connIndex, conn.Location)
|
||||
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
@@ -293,9 +290,13 @@ func (h *h2muxConnection) registerNamedTunnel(
|
||||
rpcClient := h.newRPCClientFunc(ctx, stream, h.observer.log)
|
||||
defer rpcClient.Close()
|
||||
|
||||
if _, err = rpcClient.RegisterConnection(ctx, namedTunnel, connOptions, h.connIndex, nil, h.observer); err != nil {
|
||||
registrationDetails, err := rpcClient.RegisterConnection(ctx, namedTunnel, connOptions, h.connIndex, nil, h.observer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.observer.logServerInfo(h.connIndex, registrationDetails.Location, nil, fmt.Sprintf("Connection %s registered", registrationDetails.UUID))
|
||||
h.observer.sendConnectedEvent(h.connIndex, H2mux, registrationDetails.Location)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -42,9 +42,3 @@ func (sc *errClosedSession) Error() string {
|
||||
return fmt.Sprintf("session closed by local due to %s", sc.message)
|
||||
}
|
||||
}
|
||||
|
||||
// newDatagram is an event when transport receives new datagram
|
||||
type newDatagram struct {
|
||||
sessionID uuid.UUID
|
||||
payload []byte
|
||||
}
|
||||
|
||||
+35
-66
@@ -7,9 +7,9 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/lucas-clemente/quic-go"
|
||||
"github.com/rs/zerolog"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -36,26 +36,25 @@ type Manager interface {
|
||||
type manager struct {
|
||||
registrationChan chan *registerSessionEvent
|
||||
unregistrationChan chan *unregisterSessionEvent
|
||||
datagramChan chan *newDatagram
|
||||
closedChan chan struct{}
|
||||
transport transport
|
||||
sendFunc transportSender
|
||||
receiveChan <-chan *packet.Session
|
||||
closedChan <-chan struct{}
|
||||
sessions map[uuid.UUID]*Session
|
||||
log *zerolog.Logger
|
||||
// timeout waiting for an API to finish. This can be overriden in test
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func NewManager(transport transport, log *zerolog.Logger) *manager {
|
||||
func NewManager(log *zerolog.Logger, sendF transportSender, receiveChan <-chan *packet.Session) *manager {
|
||||
return &manager{
|
||||
registrationChan: make(chan *registerSessionEvent),
|
||||
unregistrationChan: make(chan *unregisterSessionEvent),
|
||||
// datagramChan is buffered, so it can read more datagrams from transport while the event loop is processing other events
|
||||
datagramChan: make(chan *newDatagram, requestChanCapacity),
|
||||
closedChan: make(chan struct{}),
|
||||
transport: transport,
|
||||
sessions: make(map[uuid.UUID]*Session),
|
||||
log: log,
|
||||
timeout: defaultReqTimeout,
|
||||
sendFunc: sendF,
|
||||
receiveChan: receiveChan,
|
||||
closedChan: make(chan struct{}),
|
||||
sessions: make(map[uuid.UUID]*Session),
|
||||
log: log,
|
||||
timeout: defaultReqTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,49 +64,21 @@ func (m *manager) UpdateLogger(log *zerolog.Logger) {
|
||||
}
|
||||
|
||||
func (m *manager) Serve(ctx context.Context) error {
|
||||
errGroup, ctx := errgroup.WithContext(ctx)
|
||||
errGroup.Go(func() error {
|
||||
for {
|
||||
sessionID, payload, err := m.transport.ReceiveFrom()
|
||||
if err != nil {
|
||||
if aerr, ok := err.(*quic.ApplicationError); ok && uint64(aerr.ErrorCode) == uint64(quic.NoError) {
|
||||
return nil
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
datagram := &newDatagram{
|
||||
sessionID: sessionID,
|
||||
payload: payload,
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
// Only the event loop routine can update/lookup the sessions map to avoid concurrent access
|
||||
// Send the datagram to the event loop. It will find the session to send to
|
||||
case m.datagramChan <- datagram:
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
m.shutdownSessions(ctx.Err())
|
||||
return ctx.Err()
|
||||
// receiveChan is buffered, so the transport can read more datagrams from transport while the event loop is
|
||||
// processing other events
|
||||
case datagram := <-m.receiveChan:
|
||||
m.sendToSession(datagram)
|
||||
case registration := <-m.registrationChan:
|
||||
m.registerSession(ctx, registration)
|
||||
case unregistration := <-m.unregistrationChan:
|
||||
m.unregisterSession(unregistration)
|
||||
}
|
||||
})
|
||||
errGroup.Go(func() error {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case datagram := <-m.datagramChan:
|
||||
m.sendToSession(datagram)
|
||||
case registration := <-m.registrationChan:
|
||||
m.registerSession(ctx, registration)
|
||||
// TODO: TUN-5422: Unregister inactive session upon timeout
|
||||
case unregistration := <-m.unregistrationChan:
|
||||
m.unregisterSession(unregistration)
|
||||
}
|
||||
}
|
||||
})
|
||||
err := errGroup.Wait()
|
||||
close(m.closedChan)
|
||||
m.shutdownSessions(err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) shutdownSessions(err error) {
|
||||
@@ -149,16 +120,17 @@ func (m *manager) registerSession(ctx context.Context, registration *registerSes
|
||||
}
|
||||
|
||||
func (m *manager) newSession(id uuid.UUID, dstConn io.ReadWriteCloser) *Session {
|
||||
logger := m.log.With().Str("sessionID", id.String()).Logger()
|
||||
return &Session{
|
||||
ID: id,
|
||||
transport: m.transport,
|
||||
dstConn: dstConn,
|
||||
ID: id,
|
||||
sendFunc: m.sendFunc,
|
||||
dstConn: dstConn,
|
||||
// activeAtChan has low capacity. It can be full when there are many concurrent read/write. markActive() will
|
||||
// drop instead of blocking because last active time only needs to be an approximation
|
||||
activeAtChan: make(chan time.Time, 2),
|
||||
// capacity is 2 because close() and dstToTransport routine in Serve() can write to this channel
|
||||
closeChan: make(chan error, 2),
|
||||
log: m.log,
|
||||
log: &logger,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,16 +163,13 @@ func (m *manager) unregisterSession(unregistration *unregisterSessionEvent) {
|
||||
}
|
||||
}
|
||||
|
||||
func (m *manager) sendToSession(datagram *newDatagram) {
|
||||
session, ok := m.sessions[datagram.sessionID]
|
||||
func (m *manager) sendToSession(datagram *packet.Session) {
|
||||
session, ok := m.sessions[datagram.ID]
|
||||
if !ok {
|
||||
m.log.Error().Str("sessionID", datagram.sessionID.String()).Msg("session not found")
|
||||
m.log.Error().Str("sessionID", datagram.ID.String()).Msg("session not found")
|
||||
return
|
||||
}
|
||||
// session writes to destination over a connected UDP socket, which should not be blocking, so this call doesn't
|
||||
// need to run in another go routine
|
||||
_, err := session.transportToDst(datagram.payload)
|
||||
if err != nil {
|
||||
m.log.Err(err).Str("sessionID", datagram.sessionID.String()).Msg("Failed to write payload to session")
|
||||
}
|
||||
session.transportToDst(datagram.Payload)
|
||||
}
|
||||
|
||||
+115
-129
@@ -14,22 +14,30 @@ import (
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
var (
|
||||
nopLogger = zerolog.Nop()
|
||||
)
|
||||
|
||||
func TestManagerServe(t *testing.T) {
|
||||
const (
|
||||
sessions = 20
|
||||
msgs = 50
|
||||
sessions = 2
|
||||
msgs = 5
|
||||
remoteUnregisterMsg = "eyeball closed connection"
|
||||
)
|
||||
|
||||
mg, transport := newTestManager(1)
|
||||
|
||||
eyeballTracker := make(map[uuid.UUID]*datagramChannel)
|
||||
for i := 0; i < sessions; i++ {
|
||||
sessionID := uuid.New()
|
||||
eyeballTracker[sessionID] = newDatagramChannel(1)
|
||||
requestChan := make(chan *packet.Session)
|
||||
transport := mockQUICTransport{
|
||||
sessions: make(map[uuid.UUID]chan []byte),
|
||||
}
|
||||
for i := 0; i < sessions; i++ {
|
||||
transport.sessions[uuid.New()] = make(chan []byte)
|
||||
}
|
||||
|
||||
mg := NewManager(&nopLogger, transport.MuxSession, requestChan)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
serveDone := make(chan struct{})
|
||||
@@ -38,53 +46,42 @@ func TestManagerServe(t *testing.T) {
|
||||
close(serveDone)
|
||||
}(ctx)
|
||||
|
||||
go func(ctx context.Context) {
|
||||
for {
|
||||
sessionID, payload, err := transport.respChan.Receive(ctx)
|
||||
if err != nil {
|
||||
require.Equal(t, context.Canceled, err)
|
||||
return
|
||||
}
|
||||
respChan := eyeballTracker[sessionID]
|
||||
require.NoError(t, respChan.Send(ctx, sessionID, payload))
|
||||
}
|
||||
}(ctx)
|
||||
|
||||
errGroup, ctx := errgroup.WithContext(ctx)
|
||||
for sID, receiver := range eyeballTracker {
|
||||
for sessionID, eyeballRespChan := range transport.sessions {
|
||||
// Assign loop variables to local variables
|
||||
sID := sessionID
|
||||
payload := testPayload(sID)
|
||||
expectResp := testResponse(payload)
|
||||
|
||||
cfdConn, originConn := net.Pipe()
|
||||
|
||||
origin := mockOrigin{
|
||||
expectMsgCount: msgs,
|
||||
expectedMsg: payload,
|
||||
expectedResp: expectResp,
|
||||
conn: originConn,
|
||||
}
|
||||
|
||||
eyeball := mockEyeballSession{
|
||||
id: sID,
|
||||
expectedMsgCount: msgs,
|
||||
expectedMsg: payload,
|
||||
expectedResponse: expectResp,
|
||||
respReceiver: eyeballRespChan,
|
||||
}
|
||||
|
||||
// Assign loop variables to local variables
|
||||
sessionID := sID
|
||||
eyeballRespReceiver := receiver
|
||||
errGroup.Go(func() error {
|
||||
payload := testPayload(sessionID)
|
||||
expectResp := testResponse(payload)
|
||||
|
||||
cfdConn, originConn := net.Pipe()
|
||||
|
||||
origin := mockOrigin{
|
||||
expectMsgCount: msgs,
|
||||
expectedMsg: payload,
|
||||
expectedResp: expectResp,
|
||||
conn: originConn,
|
||||
}
|
||||
eyeball := mockEyeball{
|
||||
expectMsgCount: msgs,
|
||||
expectedMsg: expectResp,
|
||||
expectSessionID: sessionID,
|
||||
respReceiver: eyeballRespReceiver,
|
||||
}
|
||||
|
||||
session, err := mg.RegisterSession(ctx, sID, cfdConn)
|
||||
require.NoError(t, err)
|
||||
reqErrGroup, reqCtx := errgroup.WithContext(ctx)
|
||||
reqErrGroup.Go(func() error {
|
||||
return origin.serve()
|
||||
})
|
||||
reqErrGroup.Go(func() error {
|
||||
return eyeball.serve(reqCtx)
|
||||
return eyeball.serve(reqCtx, requestChan)
|
||||
})
|
||||
|
||||
session, err := mg.RegisterSession(ctx, sessionID, cfdConn)
|
||||
require.NoError(t, err)
|
||||
|
||||
sessionDone := make(chan struct{})
|
||||
go func() {
|
||||
closedByRemote, err := session.Serve(ctx, time.Minute*2)
|
||||
@@ -97,23 +94,17 @@ func TestManagerServe(t *testing.T) {
|
||||
close(sessionDone)
|
||||
}()
|
||||
|
||||
for i := 0; i < msgs; i++ {
|
||||
require.NoError(t, transport.newRequest(ctx, sessionID, testPayload(sessionID)))
|
||||
}
|
||||
|
||||
// Make sure eyeball and origin have received all messages before unregistering the session
|
||||
require.NoError(t, reqErrGroup.Wait())
|
||||
|
||||
require.NoError(t, mg.UnregisterSession(ctx, sessionID, remoteUnregisterMsg, true))
|
||||
require.NoError(t, mg.UnregisterSession(ctx, sID, remoteUnregisterMsg, true))
|
||||
<-sessionDone
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
require.NoError(t, errGroup.Wait())
|
||||
cancel()
|
||||
transport.close()
|
||||
<-serveDone
|
||||
}
|
||||
|
||||
@@ -122,7 +113,7 @@ func TestTimeout(t *testing.T) {
|
||||
testTimeout = time.Millisecond * 50
|
||||
)
|
||||
|
||||
mg, _ := newTestManager(1)
|
||||
mg := NewManager(&nopLogger, nil, nil)
|
||||
mg.timeout = testTimeout
|
||||
ctx := context.Background()
|
||||
sessionID := uuid.New()
|
||||
@@ -135,9 +126,51 @@ func TestTimeout(t *testing.T) {
|
||||
require.ErrorIs(t, err, context.DeadlineExceeded)
|
||||
}
|
||||
|
||||
func TestCloseTransportCloseSessions(t *testing.T) {
|
||||
mg, transport := newTestManager(1)
|
||||
ctx := context.Background()
|
||||
func TestUnregisterSessionCloseSession(t *testing.T) {
|
||||
sessionID := uuid.New()
|
||||
payload := []byte(t.Name())
|
||||
sender := newMockTransportSender(sessionID, payload)
|
||||
mg := NewManager(&nopLogger, sender.muxSession, nil)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
managerDone := make(chan struct{})
|
||||
go func() {
|
||||
err := mg.Serve(ctx)
|
||||
require.Error(t, err)
|
||||
close(managerDone)
|
||||
}()
|
||||
|
||||
cfdConn, originConn := net.Pipe()
|
||||
session, err := mg.RegisterSession(ctx, sessionID, cfdConn)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, session)
|
||||
|
||||
unregisteredChan := make(chan struct{})
|
||||
go func() {
|
||||
_, err := originConn.Write(payload)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = mg.UnregisterSession(ctx, sessionID, "eyeball closed session", true)
|
||||
require.NoError(t, err)
|
||||
|
||||
close(unregisteredChan)
|
||||
}()
|
||||
|
||||
closedByRemote, err := session.Serve(ctx, time.Minute)
|
||||
require.True(t, closedByRemote)
|
||||
require.Error(t, err)
|
||||
|
||||
<-unregisteredChan
|
||||
cancel()
|
||||
<-managerDone
|
||||
}
|
||||
|
||||
func TestManagerCtxDoneCloseSessions(t *testing.T) {
|
||||
sessionID := uuid.New()
|
||||
payload := []byte(t.Name())
|
||||
sender := newMockTransportSender(sessionID, payload)
|
||||
mg := NewManager(&nopLogger, sender.muxSession, nil)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
@@ -147,35 +180,26 @@ func TestCloseTransportCloseSessions(t *testing.T) {
|
||||
require.Error(t, err)
|
||||
}()
|
||||
|
||||
cfdConn, eyeballConn := net.Pipe()
|
||||
session, err := mg.RegisterSession(ctx, uuid.New(), cfdConn)
|
||||
cfdConn, originConn := net.Pipe()
|
||||
session, err := mg.RegisterSession(ctx, sessionID, cfdConn)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, session)
|
||||
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, err := eyeballConn.Write([]byte(t.Name()))
|
||||
_, err := originConn.Write(payload)
|
||||
require.NoError(t, err)
|
||||
transport.close()
|
||||
cancel()
|
||||
}()
|
||||
|
||||
closedByRemote, err := session.Serve(ctx, time.Minute)
|
||||
require.True(t, closedByRemote)
|
||||
require.False(t, closedByRemote)
|
||||
require.Error(t, err)
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func newTestManager(capacity uint) (*manager, *mockQUICTransport) {
|
||||
log := zerolog.Nop()
|
||||
transport := &mockQUICTransport{
|
||||
reqChan: newDatagramChannel(capacity),
|
||||
respChan: newDatagramChannel(capacity),
|
||||
}
|
||||
return NewManager(transport, &log), transport
|
||||
}
|
||||
|
||||
type mockOrigin struct {
|
||||
expectMsgCount int
|
||||
expectedMsg []byte
|
||||
@@ -197,7 +221,6 @@ func (mo *mockOrigin) serve() error {
|
||||
if !bytes.Equal(readBuffer[:n], mo.expectedMsg) {
|
||||
return fmt.Errorf("Expect %v, read %v", mo.expectedMsg, readBuffer[:n])
|
||||
}
|
||||
|
||||
_, err = mo.conn.Write(mo.expectedResp)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -214,72 +237,35 @@ func testResponse(msg []byte) []byte {
|
||||
return []byte(fmt.Sprintf("Response to %v", msg))
|
||||
}
|
||||
|
||||
type mockEyeball struct {
|
||||
expectMsgCount int
|
||||
expectedMsg []byte
|
||||
expectSessionID uuid.UUID
|
||||
respReceiver *datagramChannel
|
||||
type mockQUICTransport struct {
|
||||
sessions map[uuid.UUID]chan []byte
|
||||
}
|
||||
|
||||
func (me *mockEyeball) serve(ctx context.Context) error {
|
||||
for i := 0; i < me.expectMsgCount; i++ {
|
||||
sessionID, msg, err := me.respReceiver.Receive(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if sessionID != me.expectSessionID {
|
||||
return fmt.Errorf("Expect session %s, got %s", me.expectSessionID, sessionID)
|
||||
}
|
||||
if !bytes.Equal(msg, me.expectedMsg) {
|
||||
return fmt.Errorf("Expect %v, read %v", me.expectedMsg, msg)
|
||||
}
|
||||
}
|
||||
func (me *mockQUICTransport) MuxSession(session *packet.Session) error {
|
||||
s := me.sessions[session.ID]
|
||||
s <- session.Payload
|
||||
return nil
|
||||
}
|
||||
|
||||
// datagramChannel is a channel for Datagram with wrapper to send/receive with context
|
||||
type datagramChannel struct {
|
||||
datagramChan chan *newDatagram
|
||||
closedChan chan struct{}
|
||||
type mockEyeballSession struct {
|
||||
id uuid.UUID
|
||||
expectedMsgCount int
|
||||
expectedMsg []byte
|
||||
expectedResponse []byte
|
||||
respReceiver <-chan []byte
|
||||
}
|
||||
|
||||
func newDatagramChannel(capacity uint) *datagramChannel {
|
||||
return &datagramChannel{
|
||||
datagramChan: make(chan *newDatagram, capacity),
|
||||
closedChan: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (rc *datagramChannel) Send(ctx context.Context, sessionID uuid.UUID, payload []byte) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-rc.closedChan:
|
||||
return &errClosedSession{
|
||||
message: fmt.Errorf("datagram channel closed").Error(),
|
||||
byRemote: true,
|
||||
func (me *mockEyeballSession) serve(ctx context.Context, requestChan chan *packet.Session) error {
|
||||
for i := 0; i < me.expectedMsgCount; i++ {
|
||||
requestChan <- &packet.Session{
|
||||
ID: me.id,
|
||||
Payload: me.expectedMsg,
|
||||
}
|
||||
case rc.datagramChan <- &newDatagram{sessionID: sessionID, payload: payload}:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (rc *datagramChannel) Receive(ctx context.Context) (uuid.UUID, []byte, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return uuid.Nil, nil, ctx.Err()
|
||||
case <-rc.closedChan:
|
||||
err := &errClosedSession{
|
||||
message: fmt.Errorf("datagram channel closed").Error(),
|
||||
byRemote: true,
|
||||
resp := <-me.respReceiver
|
||||
if !bytes.Equal(resp, me.expectedResponse) {
|
||||
return fmt.Errorf("Expect %v, read %v", me.expectedResponse, resp)
|
||||
}
|
||||
return uuid.Nil, nil, err
|
||||
case msg := <-rc.datagramChan:
|
||||
return msg.sessionID, msg.payload, nil
|
||||
fmt.Println("Resp", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func (rc *datagramChannel) Close() {
|
||||
// No need to close msgChan, it will be garbage collect once there is no reference to it
|
||||
close(rc.closedChan)
|
||||
return nil
|
||||
}
|
||||
|
||||
+37
-30
@@ -2,12 +2,16 @@ package datagramsession
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -18,21 +22,20 @@ func SessionIdleErr(timeout time.Duration) error {
|
||||
return fmt.Errorf("session idle for %v", timeout)
|
||||
}
|
||||
|
||||
type transportSender func(session *packet.Session) error
|
||||
|
||||
// Session is a bidirectional pipe of datagrams between transport and dstConn
|
||||
// Currently the only implementation of transport is quic DatagramMuxer
|
||||
// Destination can be a connection with origin or with eyeball
|
||||
// When the destination is origin:
|
||||
// - Datagrams from edge are read by Manager from the transport. Manager finds the corresponding Session and calls the
|
||||
// write method of the Session to send to origin
|
||||
// - Datagrams from origin are read from conn and SentTo transport. Transport will return them to eyeball
|
||||
// - Manager receives datagrams from receiveChan and calls the transportToDst method of the Session to send to origin
|
||||
// - Datagrams from origin are read from conn and Send to transport using the transportSender callback. Transport will return them to eyeball
|
||||
// When the destination is eyeball:
|
||||
// - Datagrams from eyeball are read from conn and SentTo transport. Transport will send them to cloudflared
|
||||
// - Datagrams from cloudflared are read by Manager from the transport. Manager finds the corresponding Session and calls the
|
||||
// write method of the Session to send to eyeball
|
||||
// - Datagrams from eyeball are read from conn and Send to transport. Transport will send them to cloudflared using the transportSender callback.
|
||||
// - Manager receives datagrams from receiveChan and calls the transportToDst method of the Session to send to the eyeball
|
||||
type Session struct {
|
||||
ID uuid.UUID
|
||||
transport transport
|
||||
dstConn io.ReadWriteCloser
|
||||
ID uuid.UUID
|
||||
sendFunc transportSender
|
||||
dstConn io.ReadWriteCloser
|
||||
// activeAtChan is used to communicate the last read/write time
|
||||
activeAtChan chan time.Time
|
||||
closeChan chan error
|
||||
@@ -46,9 +49,16 @@ func (s *Session) Serve(ctx context.Context, closeAfterIdle time.Duration) (clos
|
||||
const maxPacketSize = 1500
|
||||
readBuffer := make([]byte, maxPacketSize)
|
||||
for {
|
||||
if err := s.dstToTransport(readBuffer); err != nil {
|
||||
s.closeChan <- err
|
||||
return
|
||||
if closeSession, err := s.dstToTransport(readBuffer); err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
s.log.Debug().Msg("Destination connection closed")
|
||||
} else {
|
||||
s.log.Error().Err(err).Msg("Failed to send session payload from destination to transport")
|
||||
}
|
||||
if closeSession {
|
||||
s.closeChan <- err
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
@@ -89,32 +99,29 @@ func (s *Session) waitForCloseCondition(ctx context.Context, closeAfterIdle time
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Session) dstToTransport(buffer []byte) error {
|
||||
func (s *Session) dstToTransport(buffer []byte) (closeSession bool, err error) {
|
||||
n, err := s.dstConn.Read(buffer)
|
||||
s.markActive()
|
||||
// https://pkg.go.dev/io#Reader suggests caller should always process n > 0 bytes
|
||||
if n > 0 {
|
||||
if n <= int(s.transport.MTU()) {
|
||||
err = s.transport.SendTo(s.ID, buffer[:n])
|
||||
} else {
|
||||
// drop packet for now, eventually reply with ICMP for PMTUD
|
||||
s.log.Debug().
|
||||
Str("session", s.ID.String()).
|
||||
Int("len", n).
|
||||
Int("mtu", s.transport.MTU()).
|
||||
Msg("dropped packet exceeding MTU")
|
||||
if n > 0 || err == nil {
|
||||
session := packet.Session{
|
||||
ID: s.ID,
|
||||
Payload: buffer[:n],
|
||||
}
|
||||
if sendErr := s.sendFunc(&session); sendErr != nil {
|
||||
return false, sendErr
|
||||
}
|
||||
}
|
||||
// Some UDP application might send 0-size payload.
|
||||
if err == nil && n == 0 {
|
||||
err = s.transport.SendTo(s.ID, []byte{})
|
||||
}
|
||||
return err
|
||||
return err != nil, err
|
||||
}
|
||||
|
||||
func (s *Session) transportToDst(payload []byte) (int, error) {
|
||||
s.markActive()
|
||||
return s.dstConn.Write(payload)
|
||||
n, err := s.dstConn.Write(payload)
|
||||
if err != nil {
|
||||
s.log.Err(err).Msg("Failed to write payload to session")
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Sends the last active time to the idle checker loop without blocking. activeAtChan will only be full when there
|
||||
|
||||
@@ -11,8 +11,11 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
// TestCloseSession makes sure a session will stop after context is done
|
||||
@@ -41,7 +44,8 @@ func testSessionReturns(t *testing.T, closeBy closeMethod, closeAfterIdle time.D
|
||||
cfdConn, originConn := net.Pipe()
|
||||
payload := testPayload(sessionID)
|
||||
|
||||
mg, _ := newTestManager(1)
|
||||
log := zerolog.Nop()
|
||||
mg := NewManager(&log, nil, nil)
|
||||
session := mg.newSession(sessionID, cfdConn)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
@@ -114,7 +118,9 @@ func testActiveSessionNotClosed(t *testing.T, readFromDst bool, writeToDst bool)
|
||||
cfdConn, originConn := net.Pipe()
|
||||
payload := testPayload(sessionID)
|
||||
|
||||
mg, _ := newTestManager(100)
|
||||
respChan := make(chan *packet.Session)
|
||||
sender := newMockTransportSender(sessionID, payload)
|
||||
mg := NewManager(&nopLogger, sender.muxSession, respChan)
|
||||
session := mg.newSession(sessionID, cfdConn)
|
||||
|
||||
startTime := time.Now()
|
||||
@@ -177,7 +183,7 @@ func testActiveSessionNotClosed(t *testing.T, readFromDst bool, writeToDst bool)
|
||||
|
||||
func TestMarkActiveNotBlocking(t *testing.T) {
|
||||
const concurrentCalls = 50
|
||||
mg, _ := newTestManager(1)
|
||||
mg := NewManager(&nopLogger, nil, nil)
|
||||
session := mg.newSession(uuid.New(), nil)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(concurrentCalls)
|
||||
@@ -190,11 +196,16 @@ func TestMarkActiveNotBlocking(t *testing.T) {
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// Some UDP application might send 0-size payload.
|
||||
func TestZeroBytePayload(t *testing.T) {
|
||||
sessionID := uuid.New()
|
||||
cfdConn, originConn := net.Pipe()
|
||||
|
||||
mg, transport := newTestManager(1)
|
||||
sender := sendOnceTransportSender{
|
||||
baseSender: newMockTransportSender(sessionID, make([]byte, 0)),
|
||||
sentChan: make(chan struct{}),
|
||||
}
|
||||
mg := NewManager(&nopLogger, sender.muxSession, nil)
|
||||
session := mg.newSession(sessionID, cfdConn)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
@@ -215,11 +226,39 @@ func TestZeroBytePayload(t *testing.T) {
|
||||
return nil
|
||||
})
|
||||
|
||||
receivedSessionID, payload, err := transport.respChan.Receive(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, payload, 0)
|
||||
require.Equal(t, sessionID, receivedSessionID)
|
||||
|
||||
<-sender.sentChan
|
||||
cancel()
|
||||
require.NoError(t, errGroup.Wait())
|
||||
}
|
||||
|
||||
type mockTransportSender struct {
|
||||
expectedSessionID uuid.UUID
|
||||
expectedPayload []byte
|
||||
}
|
||||
|
||||
func newMockTransportSender(expectedSessionID uuid.UUID, expectedPayload []byte) *mockTransportSender {
|
||||
return &mockTransportSender{
|
||||
expectedSessionID: expectedSessionID,
|
||||
expectedPayload: expectedPayload,
|
||||
}
|
||||
}
|
||||
|
||||
func (mts *mockTransportSender) muxSession(session *packet.Session) error {
|
||||
if session.ID != mts.expectedSessionID {
|
||||
return fmt.Errorf("Expect session %s, got %s", mts.expectedSessionID, session.ID)
|
||||
}
|
||||
if !bytes.Equal(session.Payload, mts.expectedPayload) {
|
||||
return fmt.Errorf("Expect %v, read %v", mts.expectedPayload, session.Payload)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type sendOnceTransportSender struct {
|
||||
baseSender *mockTransportSender
|
||||
sentChan chan struct{}
|
||||
}
|
||||
|
||||
func (sots *sendOnceTransportSender) muxSession(session *packet.Session) error {
|
||||
defer close(sots.sentChan)
|
||||
return sots.baseSender.muxSession(session)
|
||||
}
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
package datagramsession
|
||||
|
||||
import "github.com/google/uuid"
|
||||
|
||||
// Transport is a connection between cloudflared and edge that can multiplex datagrams from multiple sessions
|
||||
type transport interface {
|
||||
// SendTo writes payload for a session to the transport
|
||||
SendTo(sessionID uuid.UUID, payload []byte) error
|
||||
// ReceiveFrom reads the next datagram from the transport
|
||||
ReceiveFrom() (uuid.UUID, []byte, error)
|
||||
// Max transmission unit to receive from the transport
|
||||
MTU() int
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
package datagramsession
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type mockQUICTransport struct {
|
||||
reqChan *datagramChannel
|
||||
respChan *datagramChannel
|
||||
}
|
||||
|
||||
func (mt *mockQUICTransport) SendTo(sessionID uuid.UUID, payload []byte) error {
|
||||
buf := make([]byte, len(payload))
|
||||
// The QUIC implementation copies data to another buffer before returning https://github.com/lucas-clemente/quic-go/blob/v0.24.0/session.go#L1967-L1975
|
||||
copy(buf, payload)
|
||||
return mt.respChan.Send(context.Background(), sessionID, buf)
|
||||
}
|
||||
|
||||
func (mt *mockQUICTransport) ReceiveFrom() (uuid.UUID, []byte, error) {
|
||||
return mt.reqChan.Receive(context.Background())
|
||||
}
|
||||
|
||||
func (mt *mockQUICTransport) MTU() int {
|
||||
return 1280
|
||||
}
|
||||
|
||||
func (mt *mockQUICTransport) newRequest(ctx context.Context, sessionID uuid.UUID, payload []byte) error {
|
||||
return mt.reqChan.Send(ctx, sessionID, payload)
|
||||
}
|
||||
|
||||
func (mt *mockQUICTransport) close() {
|
||||
mt.reqChan.Close()
|
||||
mt.respChan.Close()
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.17.10 as builder
|
||||
FROM golang:1.18 as builder
|
||||
ENV GO111MODULE=on \
|
||||
CGO_ENABLED=0
|
||||
WORKDIR /go/src/github.com/cloudflare/cloudflared/
|
||||
|
||||
@@ -2,4 +2,11 @@
|
||||
|
||||
package main
|
||||
|
||||
import _ "crypto/tls/fipsonly"
|
||||
import (
|
||||
_ "crypto/tls/fipsonly"
|
||||
"github.com/cloudflare/cloudflared/cmd/cloudflared/tunnel"
|
||||
)
|
||||
|
||||
func init () {
|
||||
tunnel.FipsEnabled = true
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module github.com/cloudflare/cloudflared
|
||||
|
||||
go 1.17
|
||||
go 1.18
|
||||
|
||||
require (
|
||||
github.com/cloudflare/brotli-go v0.0.0-20191101163834-d34379f7ff93
|
||||
@@ -9,22 +9,21 @@ require (
|
||||
github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf
|
||||
github.com/facebookgo/grace v0.0.0-20180706040059-75cf19382434
|
||||
github.com/fsnotify/fsnotify v1.4.9
|
||||
github.com/gdamore/tcell v1.3.0
|
||||
github.com/getsentry/raven-go v0.0.0-20180517221441-ed7bcb39ff10
|
||||
github.com/gobwas/ws v1.0.4
|
||||
github.com/golang-collections/collections v0.0.0-20130729185459-604e922904d3
|
||||
github.com/google/gopacket v1.1.19
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/gorilla/mux v1.8.0
|
||||
github.com/gorilla/websocket v1.4.2
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/lucas-clemente/quic-go v0.27.1
|
||||
github.com/lucas-clemente/quic-go v0.28.1
|
||||
github.com/mattn/go-colorable v0.1.8
|
||||
github.com/miekg/dns v1.1.45
|
||||
github.com/mitchellh/go-homedir v1.1.0
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/prometheus/client_golang v1.12.1
|
||||
github.com/prometheus/client_model v0.2.0
|
||||
github.com/rivo/tview v0.0.0-20200712113419-c65badfc3d92
|
||||
github.com/rs/zerolog v1.20.0
|
||||
github.com/stretchr/testify v1.7.1
|
||||
github.com/urfave/cli/v2 v2.3.0
|
||||
@@ -35,11 +34,11 @@ require (
|
||||
go.opentelemetry.io/otel/trace v1.6.3
|
||||
go.opentelemetry.io/proto/otlp v0.15.0
|
||||
go.uber.org/automaxprocs v1.4.0
|
||||
golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f
|
||||
golang.org/x/net v0.0.0-20220114011407-0dd24b26b47d
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa
|
||||
golang.org/x/net v0.0.0-20220909164309-bea034e7d591
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
|
||||
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9
|
||||
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b
|
||||
golang.org/x/sys v0.0.0-20220808155132-1c4a2a72c664
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211
|
||||
google.golang.org/protobuf v1.28.0
|
||||
gopkg.in/coreos/go-oidc.v2 v2.2.1
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0
|
||||
@@ -55,6 +54,7 @@ require (
|
||||
github.com/certifi/gocertifi v0.0.0-20200211180108-c7c1fbc02894 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||
github.com/cheekybits/genny v1.0.0 // indirect
|
||||
github.com/cloudflare/circl v1.2.1-0.20220809205628-0a9554f37a47 // indirect
|
||||
github.com/coredns/caddy v1.1.1 // indirect
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
@@ -63,7 +63,6 @@ require (
|
||||
github.com/facebookgo/stack v0.0.0-20160209184415-751773369052 // indirect
|
||||
github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870 // indirect
|
||||
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 // indirect
|
||||
github.com/gdamore/encoding v1.0.0 // indirect
|
||||
github.com/go-logr/logr v1.2.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 // indirect
|
||||
@@ -73,12 +72,11 @@ require (
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-opentracing v0.0.0-20180507213350-8e809c8a8645 // indirect
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.0.3 // indirect
|
||||
github.com/marten-seemann/qtls-go1-16 v0.1.5 // indirect
|
||||
github.com/marten-seemann/qtls-go1-17 v0.1.1 // indirect
|
||||
github.com/marten-seemann/qtls-go1-18 v0.1.1 // indirect
|
||||
github.com/marten-seemann/qtls-go1-17 v0.1.2 // indirect
|
||||
github.com/marten-seemann/qtls-go1-18 v0.1.2 // indirect
|
||||
github.com/marten-seemann/qtls-go1-19 v0.1.0-beta.1 // indirect
|
||||
github.com/mattn/go-isatty v0.0.12 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.8 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
@@ -89,7 +87,6 @@ require (
|
||||
github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35 // indirect
|
||||
github.com/prometheus/common v0.32.1 // indirect
|
||||
github.com/prometheus/procfs v0.7.3 // indirect
|
||||
github.com/rivo/uniseg v0.1.0 // indirect
|
||||
github.com/russross/blackfriday/v2 v2.1.0 // indirect
|
||||
golang.org/x/mod v0.4.2 // indirect
|
||||
golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 // indirect
|
||||
@@ -105,7 +102,18 @@ require (
|
||||
|
||||
replace github.com/urfave/cli/v2 => github.com/ipostelnik/cli/v2 v2.3.1-0.20210324024421-b6ea8234fe3d
|
||||
|
||||
replace github.com/lucas-clemente/quic-go => github.com/chungthuang/quic-go v0.27.1-0.20220607112311-13144fbde8da
|
||||
replace github.com/lucas-clemente/quic-go => github.com/chungthuang/quic-go v0.27.1-0.20220809135021-ca330f1dec9f
|
||||
|
||||
// Avoid 'CVE-2022-21698'
|
||||
replace github.com/prometheus/golang_client => github.com/prometheus/golang_client v1.12.1
|
||||
|
||||
replace gopkg.in/yaml.v3 => gopkg.in/yaml.v3 v3.0.1
|
||||
|
||||
// Post-quantum tunnel RTG-1339
|
||||
replace (
|
||||
// branch go1.18
|
||||
github.com/marten-seemann/qtls-go1-18 => github.com/cloudflare/qtls-pq v0.0.0-20220824105406-fb955667e0af
|
||||
|
||||
// branch go1.19
|
||||
github.com/marten-seemann/qtls-go1-19 => github.com/cloudflare/qtls-pq v0.0.0-20220824104809-96561a41e0af
|
||||
)
|
||||
|
||||
@@ -70,7 +70,6 @@ github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBp
|
||||
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
|
||||
github.com/DataDog/datadog-go v4.4.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
|
||||
github.com/DataDog/gostackparse v0.5.0/go.mod h1:lTfqcJKqS9KnXQGnyQMCugq3u1FP6UZMfWR0aitKFMM=
|
||||
github.com/DataDog/sketches-go v1.0.0/go.mod h1:O+XkJHWk9w4hDwY2ZUDU31ZC9sNYlYo8DiFsxjYeo1k=
|
||||
@@ -100,27 +99,33 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g=
|
||||
github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s=
|
||||
github.com/bwesterb/go-ristretto v1.2.2/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
|
||||
github.com/cenkalti/backoff/v4 v4.1.2/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/certifi/gocertifi v0.0.0-20200211180108-c7c1fbc02894 h1:JLaf/iINcLyjwbtTsCJjc6rtlASgHeIJPrB6QmwURnA=
|
||||
github.com/certifi/gocertifi v0.0.0-20200211180108-c7c1fbc02894/go.mod h1:sGbDF6GwGcLpkNXPUTkMRoywsNa/ol15pxFe6ERfguA=
|
||||
github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
|
||||
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
|
||||
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
|
||||
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cheekybits/genny v1.0.0 h1:uGGa4nei+j20rOSeDeP5Of12XVm7TGUd4dJA9RDitfE=
|
||||
github.com/cheekybits/genny v1.0.0/go.mod h1:+tQajlRqAUrPI7DOSpB0XAqZYtQakVtB7wXkRAgjxjQ=
|
||||
github.com/chungthuang/quic-go v0.27.1-0.20220607112311-13144fbde8da h1:FmuwbQ8RU/ftTKnfz5diawqvQFH1KDB9wN2Q8S2wqds=
|
||||
github.com/chungthuang/quic-go v0.27.1-0.20220607112311-13144fbde8da/go.mod h1:AzgQoPda7N+3IqMMMkywBKggIFo2KT6pfnlrQ2QieeI=
|
||||
github.com/chungthuang/quic-go v0.27.1-0.20220809135021-ca330f1dec9f h1:UWC3XjwZzocdNCzzXxq9j/1SdHMZXhcTOsh/+gNRBUQ=
|
||||
github.com/chungthuang/quic-go v0.27.1-0.20220809135021-ca330f1dec9f/go.mod h1:oGz5DKK41cJt5+773+BSO9BXDsREY4HLf7+0odGAPO0=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
||||
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/cloudflare/brotli-go v0.0.0-20191101163834-d34379f7ff93 h1:QrGfkZDnMxcWHaYDdB7CmqS9i26OAnUj/xcus/abYkY=
|
||||
github.com/cloudflare/brotli-go v0.0.0-20191101163834-d34379f7ff93/go.mod h1:QiTe66jFdP7cUKMCCf/WrvDyYdtdmdZfVcdoLbzaKVY=
|
||||
github.com/cloudflare/circl v1.2.1-0.20220809205628-0a9554f37a47 h1:YzpECHxZ9TzO7LpnKmPxItSd79lLgrR5heIlnqU4dTU=
|
||||
github.com/cloudflare/circl v1.2.1-0.20220809205628-0a9554f37a47/go.mod h1:qhx8gBILsYlbam7h09SvHDSkjpe3TfLA7b/z4rxJvkE=
|
||||
github.com/cloudflare/golibs v0.0.0-20170913112048-333127dbecfc h1:Dvk3ySBsOm5EviLx6VCyILnafPcQinXGP5jbTdHUJgE=
|
||||
github.com/cloudflare/golibs v0.0.0-20170913112048-333127dbecfc/go.mod h1:HlgKKR8V5a1wroIDDIz3/A+T+9Janfq+7n1P5sEFdi0=
|
||||
github.com/cloudflare/qtls-pq v0.0.0-20220824104809-96561a41e0af h1:JMpOQAaXjRRBkUX73fTNe9mConJLFl6FsIp9fHdLm7Y=
|
||||
github.com/cloudflare/qtls-pq v0.0.0-20220824104809-96561a41e0af/go.mod h1:aIsWqC0WXyUiUxBl/RfxAjDyWE9CCLqvSMnCMTd/+bc=
|
||||
github.com/cloudflare/qtls-pq v0.0.0-20220824105406-fb955667e0af h1:bhCmedjwrOSyzLtHVeQ+KhimcNTSfs0P5T7kbRQS+gA=
|
||||
github.com/cloudflare/qtls-pq v0.0.0-20220824105406-fb955667e0af/go.mod h1:mW0BgKFFDAiSmOdUwoORtjo0V2vqw5QzVYRtKQqw/Jg=
|
||||
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||
github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
|
||||
github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
|
||||
@@ -189,10 +194,6 @@ github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=
|
||||
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
|
||||
github.com/gdamore/tcell v1.3.0 h1:r35w0JBADPZCVQijYebl6YMWWtHRqVEGt7kL2eBADRM=
|
||||
github.com/gdamore/tcell v1.3.0/go.mod h1:Hjvr+Ofd+gLglo7RYKxxnzCBmev3BzsS67MebKS4zMM=
|
||||
github.com/getkin/kin-openapi v0.76.0/go.mod h1:660oXbgy5JFMKreazJaQTw7o+X00qeSyhcnluiMv+Xg=
|
||||
github.com/getsentry/raven-go v0.0.0-20180517221441-ed7bcb39ff10 h1:YO10pIIBftO/kkTFdWhctH96grJ7qiy7bMdiZcIvPKs=
|
||||
github.com/getsentry/raven-go v0.0.0-20180517221441-ed7bcb39ff10/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ=
|
||||
@@ -298,6 +299,8 @@ github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8=
|
||||
github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo=
|
||||
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
|
||||
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
|
||||
github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
|
||||
@@ -343,7 +346,6 @@ github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/ad
|
||||
github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
|
||||
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
|
||||
github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw=
|
||||
github.com/grpc-ecosystem/grpc-gateway v1.16.0 h1:gmcG1KaJ57LophUzW0Hy8NmPhnMZb4M0+kPpLofRdBo=
|
||||
github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0 h1:BZHcxBETFHIdVyhyEfOvn/RdU/QGdLI4y34qQGjGWO0=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.7.0/go.mod h1:hgWBS7lorOAVIJEQMi4ZsPv9hVvWI6+ch50m39Pf2Ks=
|
||||
@@ -396,9 +398,6 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/lucasb-eyer/go-colorful v1.0.2/go.mod h1:0MS4r+7BZKSJ5mw4/S5MPN+qHFF1fYclkSPilDOKW0s=
|
||||
github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac=
|
||||
github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/lunixbochs/vtclean v1.0.0/go.mod h1:pHhQNgMf3btfWnGBVipUOjRYhoOsdGqdm/+2c2E2WMI=
|
||||
github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ=
|
||||
github.com/mailru/easyjson v0.0.0-20190312143242-1de009706dbe/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||
@@ -407,17 +406,12 @@ github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN
|
||||
github.com/marten-seemann/qpack v0.2.1/go.mod h1:F7Gl5L1jIgN1D11ucXefiuJS9UMVP2opoCp2jDKb7wc=
|
||||
github.com/marten-seemann/qtls-go1-16 v0.1.5 h1:o9JrYPPco/Nukd/HpOHMHZoBDXQqoNtUCmny98/1uqQ=
|
||||
github.com/marten-seemann/qtls-go1-16 v0.1.5/go.mod h1:gNpI2Ol+lRS3WwSOtIUUtRwZEQMXjYK+dQSBFbethAk=
|
||||
github.com/marten-seemann/qtls-go1-17 v0.1.1 h1:DQjHPq+aOzUeh9/lixAGunn6rIOQyWChPSI4+hgW7jc=
|
||||
github.com/marten-seemann/qtls-go1-17 v0.1.1/go.mod h1:C2ekUKcDdz9SDWxec1N/MvcXBpaX9l3Nx67XaR84L5s=
|
||||
github.com/marten-seemann/qtls-go1-18 v0.1.1 h1:qp7p7XXUFL7fpBvSS1sWD+uSqPvzNQK43DH+/qEkj0Y=
|
||||
github.com/marten-seemann/qtls-go1-18 v0.1.1/go.mod h1:mJttiymBAByA49mhlNZZGrH5u1uXYZJ+RW28Py7f4m4=
|
||||
github.com/marten-seemann/qtls-go1-17 v0.1.2 h1:JADBlm0LYiVbuSySCHeY863dNkcpMmDR7s0bLKJeYlQ=
|
||||
github.com/marten-seemann/qtls-go1-17 v0.1.2/go.mod h1:C2ekUKcDdz9SDWxec1N/MvcXBpaX9l3Nx67XaR84L5s=
|
||||
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
|
||||
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
|
||||
github.com/mattn/go-runewidth v0.0.8 h1:3tS41NlGYSmhhe/8fhGRzc+z3AYCw1Fe1WAyLuujKs0=
|
||||
github.com/mattn/go-runewidth v0.0.8/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/microcosm-cc/bluemonday v1.0.1/go.mod h1:hsXNsILzKxV+sX77C5b8FSuKF00vh2OMYv+xgHpAMF4=
|
||||
@@ -513,16 +507,11 @@ github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1
|
||||
github.com/rabbitmq/amqp091-go v1.1.0/go.mod h1:ogQDLSOACsLPsIq0NpbtiifNZi2YOz0VTJ0kHRghqbM=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
||||
github.com/rivo/tview v0.0.0-20200712113419-c65badfc3d92 h1:rqaqSUdaW+OBbjnsrOoiaJv43mSRARuvsAuirmdxu7E=
|
||||
github.com/rivo/tview v0.0.0-20200712113419-c65badfc3d92/go.mod h1:6lkG1x+13OShEf0EaOCaTQYyB7d5nSbb181KtjlS+84=
|
||||
github.com/rivo/uniseg v0.1.0 h1:+2KBaVoUmb9XzDsrx/Ct0W/EYOSFf/nWTauy++DprtY=
|
||||
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ=
|
||||
github.com/rs/zerolog v1.20.0 h1:38k9hgtUBdxFwE34yS8rTHmHBa4eN16E4DJlv177LNs=
|
||||
github.com/rs/zerolog v1.20.0/go.mod h1:IzD0RJ65iWH0w97OQQebJEvTZYvsCUm9WVLWBQrJRjo=
|
||||
github.com/russross/blackfriday v1.5.2 h1:HyvC0ARfnZBqnXwABFeSZHpKvJHJJfPz81GNueLj0oo=
|
||||
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
|
||||
@@ -635,8 +624,8 @@ golang.org/x/crypto v0.0.0-20201112155050-0c6587e931a9/go.mod h1:LzIPMQfyMNhhGPh
|
||||
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20210920023735-84f357641f63/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f h1:OeJjE6G4dgCY4PIXvIRQbE8+RX+uXZyGhUy/ksMGJoc=
|
||||
golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa h1:zuSxTR4o9y82ebqCUJYNGJbGPo6sKVl54f/TVDObg1c=
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||
@@ -725,8 +714,9 @@ golang.org/x/net v0.0.0-20210917221730-978cfadd31cf/go.mod h1:9nx3DQGgdP8bBQD5qx
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20211209124913-491a49abca63/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20220114011407-0dd24b26b47d h1:1n1fc535VhN8SYtD4cDUyNlfpAF2ROMM9+11equK3hs=
|
||||
golang.org/x/net v0.0.0-20220114011407-0dd24b26b47d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.0.0-20220909164309-bea034e7d591 h1:D0B/7al0LLrVC8aWF4+oxpv/m8bc7ViFfVS8/gXGdqI=
|
||||
golang.org/x/net v0.0.0-20220909164309-bea034e7d591/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
@@ -773,7 +763,6 @@ golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -831,11 +820,14 @@ golang.org/x/sys v0.0.0-20210831042530-f4d43177bf5e/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9 h1:XfKQ4OlFl8okEOr5UvAqFRVj8pY/4yfcXrddB8qAbU0=
|
||||
golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220808155132-1c4a2a72c664 h1:v1W7bwXHsnLLloWYTVEdvGvA7BHMeBYsPcF0GLDxIRs=
|
||||
golang.org/x/sys v0.0.0-20220808155132-1c4a2a72c664/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b h1:9zKuko04nR4gjZ4+DNjHqRlAJqbJETHwiNKDqTfOjfE=
|
||||
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
@@ -1106,9 +1098,6 @@ gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o=
|
||||
|
||||
@@ -265,6 +265,9 @@ func originRequestFromConfig(c config.OriginRequestConfig) OriginRequestConfig {
|
||||
if c.Http2Origin != nil {
|
||||
out.Http2Origin = *c.Http2Origin
|
||||
}
|
||||
if c.Access != nil {
|
||||
out.Access = *c.Access
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -310,6 +313,9 @@ type OriginRequestConfig struct {
|
||||
IPRules []ipaccess.Rule `yaml:"ipRules" json:"ipRules"`
|
||||
// Attempt to connect to origin with HTTP/2
|
||||
Http2Origin bool `yaml:"http2Origin" json:"http2Origin"`
|
||||
|
||||
// Access holds all access related configs
|
||||
Access config.AccessConfig `yaml:"access" json:"access,omitempty"`
|
||||
}
|
||||
|
||||
func (defaults *OriginRequestConfig) setConnectTimeout(overrides config.OriginRequestConfig) {
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
//go:build darwin
|
||||
|
||||
package ingress
|
||||
|
||||
// This file implements ICMPProxy for Darwin. It uses a non-privileged ICMP socket to send echo requests and listen for
|
||||
// echo replies. The source IP of the requests are rewritten to the bind IP of the socket and the socket reads all
|
||||
// messages, so we use echo ID to distinguish the replies. Each (source IP, destination IP, echo ID) is assigned a
|
||||
// unique echo ID.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"golang.org/x/net/icmp"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
type icmpProxy struct {
|
||||
srcFunnelTracker *packet.FunnelTracker
|
||||
echoIDTracker *echoIDTracker
|
||||
conn *icmp.PacketConn
|
||||
// Response is handled in one-by-one, so encoder can be shared between funnels
|
||||
encoder *packet.Encoder
|
||||
logger *zerolog.Logger
|
||||
idleTimeout time.Duration
|
||||
}
|
||||
|
||||
// echoIDTracker tracks which ID has been assigned. It first loops through assignment from lastAssignment to then end,
|
||||
// then from the beginning to lastAssignment.
|
||||
// ICMP echo are short lived. By the time an ID is revisited, it should have been released.
|
||||
type echoIDTracker struct {
|
||||
lock sync.Mutex
|
||||
// maps the source IP, destination IP and original echo ID to a unique echo ID obtained from assignment
|
||||
mapping map[flow3Tuple]uint16
|
||||
// assignment tracks if an ID is assigned using index as the ID
|
||||
// The size of the array is math.MaxUint16 because echo ID is 2 bytes
|
||||
assignment [math.MaxUint16]bool
|
||||
// nextAssignment is the next number to check for assigment
|
||||
nextAssignment uint16
|
||||
}
|
||||
|
||||
func newEchoIDTracker() *echoIDTracker {
|
||||
return &echoIDTracker{
|
||||
mapping: make(map[flow3Tuple]uint16),
|
||||
}
|
||||
}
|
||||
|
||||
// Get assignment or assign a new ID.
|
||||
func (eit *echoIDTracker) getOrAssign(key flow3Tuple) (id uint16, success bool) {
|
||||
eit.lock.Lock()
|
||||
defer eit.lock.Unlock()
|
||||
id, exists := eit.mapping[key]
|
||||
if exists {
|
||||
return id, true
|
||||
}
|
||||
|
||||
if eit.nextAssignment == math.MaxUint16 {
|
||||
eit.nextAssignment = 0
|
||||
}
|
||||
|
||||
for i, assigned := range eit.assignment[eit.nextAssignment:] {
|
||||
if !assigned {
|
||||
echoID := uint16(i) + eit.nextAssignment
|
||||
eit.set(key, echoID)
|
||||
return echoID, true
|
||||
}
|
||||
}
|
||||
for i, assigned := range eit.assignment[0:eit.nextAssignment] {
|
||||
if !assigned {
|
||||
echoID := uint16(i)
|
||||
eit.set(key, echoID)
|
||||
return echoID, true
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
// Caller should hold the lock
|
||||
func (eit *echoIDTracker) set(key flow3Tuple, assignedEchoID uint16) {
|
||||
eit.assignment[assignedEchoID] = true
|
||||
eit.mapping[key] = assignedEchoID
|
||||
eit.nextAssignment = assignedEchoID + 1
|
||||
}
|
||||
|
||||
func (eit *echoIDTracker) release(key flow3Tuple, assigned uint16) bool {
|
||||
eit.lock.Lock()
|
||||
defer eit.lock.Unlock()
|
||||
|
||||
currentEchoID, exists := eit.mapping[key]
|
||||
if exists && assigned == currentEchoID {
|
||||
delete(eit.mapping, key)
|
||||
eit.assignment[assigned] = false
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type echoFunnelID uint16
|
||||
|
||||
func (snf echoFunnelID) Type() string {
|
||||
return "echoID"
|
||||
}
|
||||
|
||||
func (snf echoFunnelID) String() string {
|
||||
return strconv.FormatUint(uint64(snf), 10)
|
||||
}
|
||||
|
||||
func newICMPProxy(listenIP netip.Addr, logger *zerolog.Logger, idleTimeout time.Duration) (*icmpProxy, error) {
|
||||
conn, err := newICMPConn(listenIP)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &icmpProxy{
|
||||
srcFunnelTracker: packet.NewFunnelTracker(),
|
||||
echoIDTracker: newEchoIDTracker(),
|
||||
encoder: packet.NewEncoder(),
|
||||
conn: conn,
|
||||
logger: logger,
|
||||
idleTimeout: idleTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (ip *icmpProxy) Request(pk *packet.ICMP, responder packet.FunnelUniPipe) error {
|
||||
if pk == nil {
|
||||
return errPacketNil
|
||||
}
|
||||
originalEcho, err := getICMPEcho(pk.Message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
echoIDTrackerKey := flow3Tuple{
|
||||
srcIP: pk.Src,
|
||||
dstIP: pk.Dst,
|
||||
originalEchoID: originalEcho.ID,
|
||||
}
|
||||
// TODO: TUN-6744 assign unique flow per (src, echo ID)
|
||||
assignedEchoID, success := ip.echoIDTracker.getOrAssign(echoIDTrackerKey)
|
||||
if !success {
|
||||
return fmt.Errorf("failed to assign unique echo ID")
|
||||
}
|
||||
newFunnelFunc := func() (packet.Funnel, error) {
|
||||
originalEcho, err := getICMPEcho(pk.Message)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
originSender := originSender{
|
||||
conn: ip.conn,
|
||||
echoIDTracker: ip.echoIDTracker,
|
||||
echoIDTrackerKey: echoIDTrackerKey,
|
||||
assignedEchoID: assignedEchoID,
|
||||
}
|
||||
icmpFlow := newICMPEchoFlow(pk.Src, &originSender, responder, int(assignedEchoID), originalEcho.ID, ip.encoder)
|
||||
return icmpFlow, nil
|
||||
}
|
||||
funnelID := echoFunnelID(assignedEchoID)
|
||||
funnel, isNew, err := ip.srcFunnelTracker.GetOrRegister(funnelID, newFunnelFunc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if isNew {
|
||||
ip.logger.Debug().
|
||||
Str("src", pk.Src.String()).
|
||||
Str("dst", pk.Dst.String()).
|
||||
Int("originalEchoID", originalEcho.ID).
|
||||
Int("assignedEchoID", int(assignedEchoID)).
|
||||
Msg("New flow")
|
||||
}
|
||||
icmpFlow, err := toICMPEchoFlow(funnel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return icmpFlow.sendToDst(pk.Dst, pk.Message)
|
||||
}
|
||||
|
||||
// Serve listens for responses to the requests until context is done
|
||||
func (ip *icmpProxy) Serve(ctx context.Context) error {
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
ip.conn.Close()
|
||||
}()
|
||||
go func() {
|
||||
ip.srcFunnelTracker.ScheduleCleanup(ctx, ip.idleTimeout)
|
||||
}()
|
||||
buf := make([]byte, mtu)
|
||||
icmpDecoder := packet.NewICMPDecoder()
|
||||
for {
|
||||
n, from, err := ip.conn.ReadFrom(buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply, err := parseReply(from, buf[:n])
|
||||
if err != nil {
|
||||
ip.logger.Debug().Err(err).Str("dst", from.String()).Msg("Failed to parse ICMP reply, continue to parse as full packet")
|
||||
// In unit test, we found out when the listener listens on 0.0.0.0, the socket reads the full packet after
|
||||
// the second reply
|
||||
if err := ip.handleFullPacket(icmpDecoder, buf[:n]); err != nil {
|
||||
ip.logger.Debug().Err(err).Str("dst", from.String()).Msg("Failed to parse ICMP reply as full packet")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !isEchoReply(reply.msg) {
|
||||
ip.logger.Debug().Str("dst", from.String()).Msgf("Drop ICMP %s from reply", reply.msg.Type)
|
||||
continue
|
||||
}
|
||||
if err := ip.sendReply(reply); err != nil {
|
||||
ip.logger.Error().Err(err).Str("dst", from.String()).Msg("Failed to send ICMP reply")
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ip *icmpProxy) handleFullPacket(decoder *packet.ICMPDecoder, rawPacket []byte) error {
|
||||
icmpPacket, err := decoder.Decode(packet.RawPacket{Data: rawPacket})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
echo, err := getICMPEcho(icmpPacket.Message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply := echoReply{
|
||||
from: icmpPacket.Src,
|
||||
msg: icmpPacket.Message,
|
||||
echo: echo,
|
||||
}
|
||||
if ip.sendReply(&reply); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ip *icmpProxy) sendReply(reply *echoReply) error {
|
||||
funnelID := echoFunnelID(reply.echo.ID)
|
||||
funnel, ok := ip.srcFunnelTracker.Get(funnelID)
|
||||
if !ok {
|
||||
return packet.ErrFunnelNotFound
|
||||
}
|
||||
icmpFlow, err := toICMPEchoFlow(funnel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return icmpFlow.returnToSrc(reply)
|
||||
}
|
||||
|
||||
// originSender wraps icmp.PacketConn to implement packet.FunnelUniPipe interface
|
||||
type originSender struct {
|
||||
conn *icmp.PacketConn
|
||||
echoIDTracker *echoIDTracker
|
||||
echoIDTrackerKey flow3Tuple
|
||||
assignedEchoID uint16
|
||||
}
|
||||
|
||||
func (os *originSender) SendPacket(dst netip.Addr, pk packet.RawPacket) error {
|
||||
_, err := os.conn.WriteTo(pk.Data, &net.UDPAddr{
|
||||
IP: dst.AsSlice(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (os *originSender) Close() error {
|
||||
os.echoIDTracker.release(os.echoIDTrackerKey, os.assignedEchoID)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//go:build darwin
|
||||
|
||||
package ingress
|
||||
|
||||
import (
|
||||
"math"
|
||||
"net/netip"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSingleEchoIDTracker(t *testing.T) {
|
||||
tracker := newEchoIDTracker()
|
||||
key := flow3Tuple{
|
||||
srcIP: netip.MustParseAddr("172.16.0.1"),
|
||||
dstIP: netip.MustParseAddr("172.16.0.2"),
|
||||
originalEchoID: 5182,
|
||||
}
|
||||
|
||||
// not assigned yet, so nothing to release
|
||||
require.False(t, tracker.release(key, 0))
|
||||
|
||||
echoID, ok := tracker.getOrAssign(key)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, uint16(0), echoID)
|
||||
|
||||
// Second time should return the same echo ID
|
||||
echoID, ok = tracker.getOrAssign(key)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, uint16(0), echoID)
|
||||
|
||||
// releasing a different ID returns false
|
||||
require.False(t, tracker.release(key, 1999))
|
||||
require.True(t, tracker.release(key, echoID))
|
||||
// releasing the second time returns false
|
||||
require.False(t, tracker.release(key, echoID))
|
||||
|
||||
// Move to the next IP
|
||||
echoID, ok = tracker.getOrAssign(key)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, uint16(1), echoID)
|
||||
}
|
||||
|
||||
func TestFullEchoIDTracker(t *testing.T) {
|
||||
var (
|
||||
dstIP = netip.MustParseAddr("192.168.0.1")
|
||||
originalEchoID = 41820
|
||||
)
|
||||
tracker := newEchoIDTracker()
|
||||
firstSrcIP := netip.MustParseAddr("172.16.0.1")
|
||||
srcIP := firstSrcIP
|
||||
|
||||
for i := uint16(0); i < math.MaxUint16; i++ {
|
||||
key := flow3Tuple{
|
||||
srcIP: srcIP,
|
||||
dstIP: dstIP,
|
||||
originalEchoID: originalEchoID,
|
||||
}
|
||||
echoID, ok := tracker.getOrAssign(key)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, i, echoID)
|
||||
|
||||
echoID, ok = tracker.get(key)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, i, echoID)
|
||||
|
||||
srcIP = srcIP.Next()
|
||||
}
|
||||
|
||||
key := flow3Tuple{
|
||||
srcIP: srcIP.Next(),
|
||||
dstIP: dstIP,
|
||||
originalEchoID: originalEchoID,
|
||||
}
|
||||
// All echo IDs are assigned
|
||||
echoID, ok := tracker.getOrAssign(key)
|
||||
require.False(t, ok)
|
||||
require.Equal(t, uint16(0), echoID)
|
||||
|
||||
srcIP = firstSrcIP
|
||||
for i := uint16(0); i < math.MaxUint16; i++ {
|
||||
key := flow3Tuple{
|
||||
srcIP: srcIP,
|
||||
dstIP: dstIP,
|
||||
originalEchoID: originalEchoID,
|
||||
}
|
||||
ok := tracker.release(key, i)
|
||||
require.True(t, ok)
|
||||
|
||||
echoID, ok = tracker.get(key)
|
||||
require.False(t, ok)
|
||||
require.Equal(t, uint16(0), echoID)
|
||||
srcIP = srcIP.Next()
|
||||
}
|
||||
|
||||
// The IDs are assignable again
|
||||
srcIP = firstSrcIP
|
||||
for i := uint16(0); i < math.MaxUint16; i++ {
|
||||
key := flow3Tuple{
|
||||
srcIP: srcIP,
|
||||
dstIP: dstIP,
|
||||
originalEchoID: originalEchoID,
|
||||
}
|
||||
echoID, ok := tracker.getOrAssign(key)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, i, echoID)
|
||||
|
||||
echoID, ok = tracker.get(key)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, i, echoID)
|
||||
srcIP = srcIP.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func (eit *echoIDTracker) get(key flow3Tuple) (id uint16, exist bool) {
|
||||
eit.lock.Lock()
|
||||
defer eit.lock.Unlock()
|
||||
id, exists := eit.mapping[key]
|
||||
return id, exists
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//go:build !darwin && !linux && (!windows || !cgo)
|
||||
|
||||
package ingress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
var errICMPProxyNotImplemented = fmt.Errorf("ICMP proxy is not implemented on %s %s", runtime.GOOS, runtime.GOARCH)
|
||||
|
||||
type icmpProxy struct{}
|
||||
|
||||
func (ip icmpProxy) Request(pk *packet.ICMP, responder packet.FunnelUniPipe) error {
|
||||
return errICMPProxyNotImplemented
|
||||
}
|
||||
|
||||
func (ip *icmpProxy) Serve(ctx context.Context) error {
|
||||
return errICMPProxyNotImplemented
|
||||
}
|
||||
|
||||
func newICMPProxy(listenIP netip.Addr, logger *zerolog.Logger, idleTimeout time.Duration) (*icmpProxy, error) {
|
||||
return nil, errICMPProxyNotImplemented
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//go:build linux
|
||||
|
||||
package ingress
|
||||
|
||||
// This file implements ICMPProxy for Linux. Each (source IP, destination IP, echo ID) opens a non-privileged ICMP socket.
|
||||
// The source IP of the requests are rewritten to the bind IP of the socket and echo ID rewritten to the port number of
|
||||
// the socket. The kernel ensures the socket only reads replies whose echo ID matches the port number.
|
||||
// For more information about the socket, see https://man7.org/linux/man-pages/man7/icmp.7.html and https://lwn.net/Articles/422330/
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
"golang.org/x/net/icmp"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
type icmpProxy struct {
|
||||
srcFunnelTracker *packet.FunnelTracker
|
||||
listenIP netip.Addr
|
||||
logger *zerolog.Logger
|
||||
idleTimeout time.Duration
|
||||
}
|
||||
|
||||
func newICMPProxy(listenIP netip.Addr, logger *zerolog.Logger, idleTimeout time.Duration) (*icmpProxy, error) {
|
||||
if err := testPermission(listenIP); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &icmpProxy{
|
||||
srcFunnelTracker: packet.NewFunnelTracker(),
|
||||
listenIP: listenIP,
|
||||
logger: logger,
|
||||
idleTimeout: idleTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func testPermission(listenIP netip.Addr) error {
|
||||
// Opens a non-privileged ICMP socket. On Linux the group ID of the process needs to be in ping_group_range
|
||||
conn, err := newICMPConn(listenIP)
|
||||
if err != nil {
|
||||
// TODO: TUN-6715 check if cloudflared is in ping_group_range if the check failed. If not log instruction to
|
||||
// change the group ID
|
||||
return err
|
||||
}
|
||||
// This conn is only to test if cloudflared has permission to open this type of socket
|
||||
conn.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ip *icmpProxy) Request(pk *packet.ICMP, responder packet.FunnelUniPipe) error {
|
||||
if pk == nil {
|
||||
return errPacketNil
|
||||
}
|
||||
originalEcho, err := getICMPEcho(pk.Message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newConnChan := make(chan *icmp.PacketConn, 1)
|
||||
newFunnelFunc := func() (packet.Funnel, error) {
|
||||
conn, err := newICMPConn(ip.listenIP)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to open ICMP socket")
|
||||
}
|
||||
newConnChan <- conn
|
||||
localUDPAddr, ok := conn.LocalAddr().(*net.UDPAddr)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("ICMP listener address %s is not net.UDPAddr", conn.LocalAddr())
|
||||
}
|
||||
originSender := originSender{conn: conn}
|
||||
echoID := localUDPAddr.Port
|
||||
icmpFlow := newICMPEchoFlow(pk.Src, &originSender, responder, echoID, originalEcho.ID, packet.NewEncoder())
|
||||
return icmpFlow, nil
|
||||
}
|
||||
funnelID := flow3Tuple{
|
||||
srcIP: pk.Src,
|
||||
dstIP: pk.Dst,
|
||||
originalEchoID: originalEcho.ID,
|
||||
}
|
||||
funnel, isNew, err := ip.srcFunnelTracker.GetOrRegister(funnelID, newFunnelFunc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
icmpFlow, err := toICMPEchoFlow(funnel)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if isNew {
|
||||
ip.logger.Debug().
|
||||
Str("src", pk.Src.String()).
|
||||
Str("dst", pk.Dst.String()).
|
||||
Int("originalEchoID", originalEcho.ID).
|
||||
Msg("New flow")
|
||||
conn := <-newConnChan
|
||||
go func() {
|
||||
defer ip.srcFunnelTracker.Unregister(funnelID, icmpFlow)
|
||||
if err := ip.listenResponse(icmpFlow, conn); err != nil {
|
||||
ip.logger.Debug().Err(err).
|
||||
Str("src", pk.Src.String()).
|
||||
Str("dst", pk.Dst.String()).
|
||||
Int("originalEchoID", originalEcho.ID).
|
||||
Msg("Failed to listen for ICMP echo response")
|
||||
}
|
||||
}()
|
||||
}
|
||||
if err := icmpFlow.sendToDst(pk.Dst, pk.Message); err != nil {
|
||||
return errors.Wrap(err, "failed to send ICMP echo request")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ip *icmpProxy) Serve(ctx context.Context) error {
|
||||
ip.srcFunnelTracker.ScheduleCleanup(ctx, ip.idleTimeout)
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (ip *icmpProxy) listenResponse(flow *icmpEchoFlow, conn *icmp.PacketConn) error {
|
||||
buf := make([]byte, mtu)
|
||||
for {
|
||||
n, from, err := conn.ReadFrom(buf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply, err := parseReply(from, buf[:n])
|
||||
if err != nil {
|
||||
ip.logger.Error().Err(err).Str("dst", from.String()).Msg("Failed to parse ICMP reply")
|
||||
continue
|
||||
}
|
||||
if !isEchoReply(reply.msg) {
|
||||
ip.logger.Debug().Str("dst", from.String()).Msgf("Drop ICMP %s from reply", reply.msg.Type)
|
||||
continue
|
||||
}
|
||||
if err := flow.returnToSrc(reply); err != nil {
|
||||
ip.logger.Err(err).Str("dst", from.String()).Msg("Failed to send ICMP reply")
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// originSender wraps icmp.PacketConn to implement packet.FunnelUniPipe interface
|
||||
type originSender struct {
|
||||
conn *icmp.PacketConn
|
||||
}
|
||||
|
||||
func (os *originSender) SendPacket(dst netip.Addr, pk packet.RawPacket) error {
|
||||
_, err := os.conn.WriteTo(pk.Data, &net.UDPAddr{
|
||||
IP: dst.AsSlice(),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (os *originSender) Close() error {
|
||||
return os.conn.Close()
|
||||
}
|
||||
|
||||
// Only linux uses flow3Tuple as FunnelID
|
||||
func (ft flow3Tuple) Type() string {
|
||||
return "srcIP_dstIP_echoID"
|
||||
}
|
||||
|
||||
func (ft flow3Tuple) String() string {
|
||||
return fmt.Sprintf("%s:%s:%d", ft.srcIP, ft.dstIP, ft.originalEchoID)
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package ingress
|
||||
|
||||
// This file extracts logic shared by Linux and Darwin implementation if ICMPProxy.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/icmp"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
// Opens a non-privileged ICMP socket on Linux and Darwin
|
||||
func newICMPConn(listenIP netip.Addr) (*icmp.PacketConn, error) {
|
||||
network := "udp6"
|
||||
if listenIP.Is4() {
|
||||
network = "udp4"
|
||||
}
|
||||
return icmp.ListenPacket(network, listenIP.String())
|
||||
}
|
||||
|
||||
func netipAddr(addr net.Addr) (netip.Addr, bool) {
|
||||
udpAddr, ok := addr.(*net.UDPAddr)
|
||||
if !ok {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
return netip.AddrFromSlice(udpAddr.IP)
|
||||
}
|
||||
|
||||
type flow3Tuple struct {
|
||||
srcIP netip.Addr
|
||||
dstIP netip.Addr
|
||||
originalEchoID int
|
||||
}
|
||||
|
||||
// icmpEchoFlow implements the packet.Funnel interface.
|
||||
type icmpEchoFlow struct {
|
||||
*packet.RawPacketFunnel
|
||||
assignedEchoID int
|
||||
originalEchoID int
|
||||
// it's up to the user to ensure respEncoder is not used concurrently
|
||||
respEncoder *packet.Encoder
|
||||
}
|
||||
|
||||
func newICMPEchoFlow(src netip.Addr, sendPipe, returnPipe packet.FunnelUniPipe, assignedEchoID, originalEchoID int, respEncoder *packet.Encoder) *icmpEchoFlow {
|
||||
return &icmpEchoFlow{
|
||||
RawPacketFunnel: packet.NewRawPacketFunnel(src, sendPipe, returnPipe),
|
||||
assignedEchoID: assignedEchoID,
|
||||
originalEchoID: originalEchoID,
|
||||
respEncoder: respEncoder,
|
||||
}
|
||||
}
|
||||
|
||||
// sendToDst rewrites the echo ID to the one assigned to this flow
|
||||
func (ief *icmpEchoFlow) sendToDst(dst netip.Addr, msg *icmp.Message) error {
|
||||
originalEcho, err := getICMPEcho(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sendMsg := icmp.Message{
|
||||
Type: msg.Type,
|
||||
Code: msg.Code,
|
||||
Body: &icmp.Echo{
|
||||
ID: ief.assignedEchoID,
|
||||
Seq: originalEcho.Seq,
|
||||
Data: originalEcho.Data,
|
||||
},
|
||||
}
|
||||
// For IPv4, the pseudoHeader is not used because the checksum is always calculated
|
||||
var pseudoHeader []byte = nil
|
||||
serializedPacket, err := sendMsg.Marshal(pseudoHeader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ief.SendToDst(dst, packet.RawPacket{Data: serializedPacket})
|
||||
}
|
||||
|
||||
// returnToSrc rewrites the echo ID to the original echo ID from the eyeball
|
||||
func (ief *icmpEchoFlow) returnToSrc(reply *echoReply) error {
|
||||
reply.echo.ID = ief.originalEchoID
|
||||
reply.msg.Body = reply.echo
|
||||
pk := packet.ICMP{
|
||||
IP: &packet.IP{
|
||||
Src: reply.from,
|
||||
Dst: ief.Src,
|
||||
Protocol: layers.IPProtocol(reply.msg.Type.Protocol()),
|
||||
TTL: packet.DefaultTTL,
|
||||
},
|
||||
Message: reply.msg,
|
||||
}
|
||||
serializedPacket, err := ief.respEncoder.Encode(&pk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ief.ReturnToSrc(serializedPacket)
|
||||
}
|
||||
|
||||
type echoReply struct {
|
||||
from netip.Addr
|
||||
msg *icmp.Message
|
||||
echo *icmp.Echo
|
||||
}
|
||||
|
||||
func parseReply(from net.Addr, rawMsg []byte) (*echoReply, error) {
|
||||
fromAddr, ok := netipAddr(from)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("cannot convert %s to netip.Addr", from)
|
||||
}
|
||||
proto := layers.IPProtocolICMPv4
|
||||
if fromAddr.Is6() {
|
||||
proto = layers.IPProtocolICMPv6
|
||||
}
|
||||
msg, err := icmp.ParseMessage(int(proto), rawMsg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
echo, err := getICMPEcho(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &echoReply{
|
||||
from: fromAddr,
|
||||
msg: msg,
|
||||
echo: echo,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func toICMPEchoFlow(funnel packet.Funnel) (*icmpEchoFlow, error) {
|
||||
icmpFlow, ok := funnel.(*icmpEchoFlow)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%v is not *ICMPEchoFunnel", funnel)
|
||||
}
|
||||
return icmpFlow, nil
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package ingress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
func TestFunnelIdleTimeout(t *testing.T) {
|
||||
const (
|
||||
idleTimeout = time.Second
|
||||
echoID = 42573
|
||||
startSeq = 8129
|
||||
)
|
||||
logger := zerolog.New(os.Stderr)
|
||||
proxy, err := newICMPProxy(localhostIP, &logger, idleTimeout)
|
||||
require.NoError(t, err)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
proxyDone := make(chan struct{})
|
||||
go func() {
|
||||
proxy.Serve(ctx)
|
||||
close(proxyDone)
|
||||
}()
|
||||
|
||||
// Send a packet to register the flow
|
||||
pk := packet.ICMP{
|
||||
IP: &packet.IP{
|
||||
Src: localhostIP,
|
||||
Dst: localhostIP,
|
||||
Protocol: layers.IPProtocolICMPv4,
|
||||
},
|
||||
Message: &icmp.Message{
|
||||
Type: ipv4.ICMPTypeEcho,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: echoID,
|
||||
Seq: startSeq,
|
||||
Data: []byte(t.Name()),
|
||||
},
|
||||
},
|
||||
}
|
||||
responder := echoFlowResponder{
|
||||
decoder: packet.NewICMPDecoder(),
|
||||
respChan: make(chan []byte),
|
||||
}
|
||||
require.NoError(t, proxy.Request(&pk, &responder))
|
||||
responder.validate(t, &pk)
|
||||
|
||||
// Send second request, should reuse the funnel
|
||||
require.NoError(t, proxy.Request(&pk, nil))
|
||||
responder.validate(t, &pk)
|
||||
|
||||
time.Sleep(idleTimeout * 2)
|
||||
newResponder := echoFlowResponder{
|
||||
decoder: packet.NewICMPDecoder(),
|
||||
respChan: make(chan []byte),
|
||||
}
|
||||
require.NoError(t, proxy.Request(&pk, &newResponder))
|
||||
newResponder.validate(t, &pk)
|
||||
|
||||
cancel()
|
||||
<-proxyDone
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
//go:build windows && cgo
|
||||
|
||||
package ingress
|
||||
|
||||
/*
|
||||
#include <iphlpapi.h>
|
||||
#include <icmpapi.h>
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"runtime/debug"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
const (
|
||||
// Value defined in https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketw
|
||||
AF_INET6 = 23
|
||||
icmpEchoReplyCode = 0
|
||||
nullParameter = uintptr(0)
|
||||
)
|
||||
|
||||
var (
|
||||
Iphlpapi = syscall.NewLazyDLL("Iphlpapi.dll")
|
||||
IcmpCreateFile_proc = Iphlpapi.NewProc("IcmpCreateFile")
|
||||
Icmp6CreateFile_proc = Iphlpapi.NewProc("Icmp6CreateFile")
|
||||
IcmpSendEcho_proc = Iphlpapi.NewProc("IcmpSendEcho")
|
||||
Icmp6SendEcho_proc = Iphlpapi.NewProc("Icmp6SendEcho2")
|
||||
echoReplySize = unsafe.Sizeof(echoReply{})
|
||||
echoV6ReplySize = unsafe.Sizeof(echoV6Reply{})
|
||||
icmpv6ErrMessageSize = 8
|
||||
ioStatusBlockSize = unsafe.Sizeof(ioStatusBlock{})
|
||||
endian = binary.LittleEndian
|
||||
)
|
||||
|
||||
// IP_STATUS code, see https://docs.microsoft.com/en-us/windows/win32/api/ipexport/ns-ipexport-icmp_echo_reply32#members
|
||||
// for possible values
|
||||
type ipStatus uint32
|
||||
|
||||
const (
|
||||
success ipStatus = 0
|
||||
bufTooSmall = iota + 11000
|
||||
destNetUnreachable
|
||||
destHostUnreachable
|
||||
destProtocolUnreachable
|
||||
destPortUnreachable
|
||||
noResources
|
||||
badOption
|
||||
hwError
|
||||
packetTooBig
|
||||
reqTimedOut
|
||||
badReq
|
||||
badRoute
|
||||
ttlExpiredTransit
|
||||
ttlExpiredReassembly
|
||||
paramProblem
|
||||
sourceQuench
|
||||
optionTooBig
|
||||
badDestination
|
||||
// Can be returned for malformed ICMP packets
|
||||
generalFailure = 11050
|
||||
)
|
||||
|
||||
// Additional IP_STATUS codes for ICMPv6 https://docs.microsoft.com/en-us/windows/win32/api/ipexport/ns-ipexport-icmpv6_echo_reply_lh#members
|
||||
const (
|
||||
ipv6DestUnreachable ipStatus = iota + 11040
|
||||
ipv6TimeExceeded
|
||||
ipv6BadHeader
|
||||
ipv6UnrecognizedNextHeader
|
||||
ipv6ICMPError
|
||||
ipv6DestScopeMismatch
|
||||
)
|
||||
|
||||
func (is ipStatus) String() string {
|
||||
switch is {
|
||||
case success:
|
||||
return "Success"
|
||||
case bufTooSmall:
|
||||
return "The reply buffer too small"
|
||||
case destNetUnreachable:
|
||||
return "The destination network was unreachable"
|
||||
case destHostUnreachable:
|
||||
return "The destination host was unreachable"
|
||||
case destProtocolUnreachable:
|
||||
return "The destination protocol was unreachable"
|
||||
case destPortUnreachable:
|
||||
return "The destination port was unreachable"
|
||||
case noResources:
|
||||
return "Insufficient IP resources were available"
|
||||
case badOption:
|
||||
return "A bad IP option was specified"
|
||||
case hwError:
|
||||
return "A hardware error occurred"
|
||||
case packetTooBig:
|
||||
return "The packet was too big"
|
||||
case reqTimedOut:
|
||||
return "The request timed out"
|
||||
case badReq:
|
||||
return "Bad request"
|
||||
case badRoute:
|
||||
return "Bad route"
|
||||
case ttlExpiredTransit:
|
||||
return "The TTL expired in transit"
|
||||
case ttlExpiredReassembly:
|
||||
return "The TTL expired during fragment reassembly"
|
||||
case paramProblem:
|
||||
return "A parameter problem"
|
||||
case sourceQuench:
|
||||
return "Datagrams are arriving too fast to be processed and datagrams may have been discarded"
|
||||
case optionTooBig:
|
||||
return "The IP option was too big"
|
||||
case badDestination:
|
||||
return "Bad destination"
|
||||
case ipv6DestUnreachable:
|
||||
return "IPv6 destination unreachable"
|
||||
case ipv6TimeExceeded:
|
||||
return "IPv6 time exceeded"
|
||||
case ipv6BadHeader:
|
||||
return "IPv6 bad IP header"
|
||||
case ipv6UnrecognizedNextHeader:
|
||||
return "IPv6 unrecognized next header"
|
||||
case ipv6ICMPError:
|
||||
return "IPv6 ICMP error"
|
||||
case ipv6DestScopeMismatch:
|
||||
return "IPv6 destination scope ID mismatch"
|
||||
case generalFailure:
|
||||
return "The ICMP packet might be malformed"
|
||||
default:
|
||||
return fmt.Sprintf("Unknown ip status %d", is)
|
||||
}
|
||||
}
|
||||
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/ipexport/ns-ipexport-ip_option_information
|
||||
type ipOption struct {
|
||||
TTL uint8
|
||||
Tos uint8
|
||||
Flags uint8
|
||||
OptionsSize uint8
|
||||
OptionsData uintptr
|
||||
}
|
||||
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/ipexport/ns-ipexport-icmp_echo_reply
|
||||
type echoReply struct {
|
||||
Address uint32
|
||||
Status ipStatus
|
||||
RoundTripTime uint32
|
||||
DataSize uint16
|
||||
Reserved uint16
|
||||
// The pointer size defers between 32-bit and 64-bit platforms
|
||||
DataPointer *byte
|
||||
Options ipOption
|
||||
}
|
||||
|
||||
type echoV6Reply struct {
|
||||
Address ipv6AddrEx
|
||||
Status ipStatus
|
||||
RoundTripTime uint32
|
||||
}
|
||||
|
||||
// https://docs.microsoft.com/en-us/windows/win32/api/ipexport/ns-ipexport-ipv6_address_ex
|
||||
// All the fields are in network byte order. The memory alignment is 4 bytes
|
||||
type ipv6AddrEx struct {
|
||||
port uint16
|
||||
// flowInfo is uint32. Because of field alignment, when we cast reply buffer to ipv6AddrEx, it starts at the 5th byte
|
||||
// But looking at the raw bytes, flowInfo starts at the 3rd byte. We device flowInfo into 2 uint16 so it's aligned
|
||||
flowInfoUpper uint16
|
||||
flowInfoLower uint16
|
||||
addr [8]uint16
|
||||
scopeID uint32
|
||||
}
|
||||
|
||||
// https://docs.microsoft.com/en-us/windows/win32/winsock/sockaddr-2
|
||||
type sockAddrIn6 struct {
|
||||
family int16
|
||||
// Can't embed ipv6AddrEx, that changes the memory alignment
|
||||
port uint16
|
||||
flowInfo uint32
|
||||
addr [16]byte
|
||||
scopeID uint32
|
||||
}
|
||||
|
||||
func newSockAddrIn6(addr netip.Addr) (*sockAddrIn6, error) {
|
||||
if !addr.Is6() {
|
||||
return nil, fmt.Errorf("%s is not IPv6", addr)
|
||||
}
|
||||
return &sockAddrIn6{
|
||||
family: AF_INET6,
|
||||
port: 10,
|
||||
addr: addr.As16(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_io_status_block#syntax
|
||||
type ioStatusBlock struct {
|
||||
// The first field is an union of NTSTATUS and PVOID. NTSTATUS is int32 while PVOID depends on the platform.
|
||||
// We model it as uintptr whose size depends on if the platform is 32-bit or 64-bit
|
||||
// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/596a1078-e883-4972-9bbc-49e60bebca55
|
||||
statusOrPointer uintptr
|
||||
information uintptr
|
||||
}
|
||||
|
||||
type icmpProxy struct {
|
||||
// An open handle that can send ICMP requests https://docs.microsoft.com/en-us/windows/win32/api/icmpapi/nf-icmpapi-icmpcreatefile
|
||||
handle uintptr
|
||||
// This is a ICMPv6 if srcSocketAddr is not nil
|
||||
srcSocketAddr *sockAddrIn6
|
||||
logger *zerolog.Logger
|
||||
// A pool of reusable *packet.Encoder
|
||||
encoderPool sync.Pool
|
||||
}
|
||||
|
||||
func newICMPProxy(listenIP netip.Addr, logger *zerolog.Logger, idleTimeout time.Duration) (*icmpProxy, error) {
|
||||
var (
|
||||
srcSocketAddr *sockAddrIn6
|
||||
handle uintptr
|
||||
err error
|
||||
)
|
||||
if listenIP.Is4() {
|
||||
handle, _, err = IcmpCreateFile_proc.Call()
|
||||
} else {
|
||||
srcSocketAddr, err = newSockAddrIn6(listenIP)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handle, _, err = Icmp6CreateFile_proc.Call()
|
||||
}
|
||||
// Windows procedure calls always return non-nil error constructed from the result of GetLastError.
|
||||
// Caller need to inspect the primary returned value
|
||||
if syscall.Handle(handle) == syscall.InvalidHandle {
|
||||
return nil, errors.Wrap(err, "invalid ICMP handle")
|
||||
}
|
||||
return &icmpProxy{
|
||||
handle: handle,
|
||||
srcSocketAddr: srcSocketAddr,
|
||||
logger: logger,
|
||||
encoderPool: sync.Pool{
|
||||
New: func() any {
|
||||
return packet.NewEncoder()
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (ip *icmpProxy) Serve(ctx context.Context) error {
|
||||
<-ctx.Done()
|
||||
syscall.CloseHandle(syscall.Handle(ip.handle))
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (ip *icmpProxy) Request(pk *packet.ICMP, responder packet.FunnelUniPipe) error {
|
||||
if pk == nil {
|
||||
return errPacketNil
|
||||
}
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ip.logger.Error().Interface("error", r).Msgf("Recover panic from sending icmp request/response, error %s", debug.Stack())
|
||||
}
|
||||
}()
|
||||
|
||||
echo, err := getICMPEcho(pk.Message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
respData, err := ip.icmpEchoRoundtrip(pk.Dst, echo)
|
||||
if err != nil {
|
||||
ip.logger.Err(err).Msg("ICMP echo roundtrip failed")
|
||||
return err
|
||||
}
|
||||
|
||||
err = ip.handleEchoReply(pk, echo, respData, responder)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "failed to handle ICMP echo reply")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ip *icmpProxy) handleEchoReply(request *packet.ICMP, echoReq *icmp.Echo, data []byte, responder packet.FunnelUniPipe) error {
|
||||
var replyType icmp.Type
|
||||
if request.Dst.Is4() {
|
||||
replyType = ipv4.ICMPTypeEchoReply
|
||||
} else {
|
||||
replyType = ipv6.ICMPTypeEchoReply
|
||||
}
|
||||
|
||||
pk := packet.ICMP{
|
||||
IP: &packet.IP{
|
||||
Src: request.Dst,
|
||||
Dst: request.Src,
|
||||
Protocol: layers.IPProtocol(request.Type.Protocol()),
|
||||
TTL: packet.DefaultTTL,
|
||||
},
|
||||
Message: &icmp.Message{
|
||||
Type: replyType,
|
||||
Code: icmpEchoReplyCode,
|
||||
Body: &icmp.Echo{
|
||||
ID: echoReq.ID,
|
||||
Seq: echoReq.Seq,
|
||||
Data: data,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
cachedEncoder := ip.encoderPool.Get()
|
||||
// The encoded packet is a slice to of the encoder, so we shouldn't return the encoder back to the pool until
|
||||
// the encoded packet is sent.
|
||||
defer ip.encoderPool.Put(cachedEncoder)
|
||||
encoder, ok := cachedEncoder.(*packet.Encoder)
|
||||
if !ok {
|
||||
return fmt.Errorf("encoderPool returned %T, expect *packet.Encoder", cachedEncoder)
|
||||
}
|
||||
|
||||
serializedPacket, err := encoder.Encode(&pk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return responder.SendPacket(request.Src, serializedPacket)
|
||||
}
|
||||
|
||||
func (ip *icmpProxy) icmpEchoRoundtrip(dst netip.Addr, echo *icmp.Echo) ([]byte, error) {
|
||||
if dst.Is6() {
|
||||
if ip.srcSocketAddr == nil {
|
||||
return nil, fmt.Errorf("cannot send ICMPv6 using ICMPv4 proxy")
|
||||
}
|
||||
resp, err := ip.icmp6SendEcho(dst, echo)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to send/receive ICMPv6 echo")
|
||||
}
|
||||
return resp.data, nil
|
||||
}
|
||||
if ip.srcSocketAddr != nil {
|
||||
return nil, fmt.Errorf("cannot send ICMPv4 using ICMPv6 proxy")
|
||||
}
|
||||
resp, err := ip.icmpSendEcho(dst, echo)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to send/receive ICMPv4 echo")
|
||||
}
|
||||
return resp.data, nil
|
||||
}
|
||||
|
||||
/*
|
||||
Wrapper to call https://docs.microsoft.com/en-us/windows/win32/api/icmpapi/nf-icmpapi-icmpsendecho
|
||||
Parameters:
|
||||
- IcmpHandle: Handle created by IcmpCreateFile
|
||||
- DestinationAddress: IPv4 in the form of https://docs.microsoft.com/en-us/windows/win32/api/inaddr/ns-inaddr-in_addr#syntax
|
||||
- RequestData: A pointer to echo data
|
||||
- RequestSize: Number of bytes in buffer pointed by echo data
|
||||
- RequestOptions: IP header options
|
||||
- ReplyBuffer: A pointer to the buffer for echoReply, options and data
|
||||
- ReplySize: Number of bytes allocated for ReplyBuffer
|
||||
- Timeout: Timeout in milliseconds to wait for a reply
|
||||
Returns:
|
||||
- the number of replies in uint32 https://docs.microsoft.com/en-us/windows/win32/api/icmpapi/nf-icmpapi-icmpsendecho#return-value
|
||||
To retain the reference allocated objects, conversion from pointer to uintptr must happen as arguments to the
|
||||
syscall function
|
||||
*/
|
||||
func (ip *icmpProxy) icmpSendEcho(dst netip.Addr, echo *icmp.Echo) (*echoResp, error) {
|
||||
dataSize := len(echo.Data)
|
||||
replySize := echoReplySize + uintptr(dataSize)
|
||||
replyBuf := make([]byte, replySize)
|
||||
noIPHeaderOption := nullParameter
|
||||
inAddr, err := inAddrV4(dst)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
replyCount, _, err := IcmpSendEcho_proc.Call(
|
||||
ip.handle,
|
||||
uintptr(inAddr),
|
||||
uintptr(unsafe.Pointer(&echo.Data[0])),
|
||||
uintptr(dataSize),
|
||||
noIPHeaderOption,
|
||||
uintptr(unsafe.Pointer(&replyBuf[0])),
|
||||
replySize,
|
||||
icmpRequestTimeoutMs,
|
||||
)
|
||||
if replyCount == 0 {
|
||||
// status is returned in 5th to 8th byte of reply buffer
|
||||
if status, parseErr := unmarshalIPStatus(replyBuf[4:8]); parseErr == nil && status != success {
|
||||
return nil, errors.Wrapf(err, "received ip status: %s", status)
|
||||
}
|
||||
return nil, errors.Wrap(err, "did not receive ICMP echo reply")
|
||||
} else if replyCount > 1 {
|
||||
ip.logger.Warn().Msgf("Received %d ICMP echo replies, only sending 1 back", replyCount)
|
||||
}
|
||||
return newEchoResp(replyBuf)
|
||||
}
|
||||
|
||||
// Third definition of https://docs.microsoft.com/en-us/windows/win32/api/inaddr/ns-inaddr-in_addr#syntax is address in uint32
|
||||
func inAddrV4(ip netip.Addr) (uint32, error) {
|
||||
if !ip.Is4() {
|
||||
return 0, fmt.Errorf("%s is not IPv4", ip)
|
||||
}
|
||||
v4 := ip.As4()
|
||||
return endian.Uint32(v4[:]), nil
|
||||
}
|
||||
|
||||
type echoResp struct {
|
||||
reply *echoReply
|
||||
data []byte
|
||||
}
|
||||
|
||||
func newEchoResp(replyBuf []byte) (*echoResp, error) {
|
||||
if len(replyBuf) == 0 {
|
||||
return nil, fmt.Errorf("reply buffer is empty")
|
||||
}
|
||||
// This is pattern 1 of https://pkg.go.dev/unsafe@master#Pointer, conversion of *replyBuf to *echoReply
|
||||
// replyBuf size is larger than echoReply
|
||||
reply := *(*echoReply)(unsafe.Pointer(&replyBuf[0]))
|
||||
if reply.Status != success {
|
||||
return nil, fmt.Errorf("status %d", reply.Status)
|
||||
}
|
||||
dataBufStart := len(replyBuf) - int(reply.DataSize)
|
||||
if dataBufStart < int(echoReplySize) {
|
||||
return nil, fmt.Errorf("reply buffer size %d is too small to hold data of size %d", len(replyBuf), int(reply.DataSize))
|
||||
}
|
||||
return &echoResp{
|
||||
reply: &reply,
|
||||
data: replyBuf[dataBufStart:],
|
||||
}, nil
|
||||
}
|
||||
|
||||
/*
|
||||
Wrapper to call https://docs.microsoft.com/en-us/windows/win32/api/icmpapi/nf-icmpapi-icmp6sendecho2
|
||||
Parameters:
|
||||
- IcmpHandle: Handle created by Icmp6CreateFile
|
||||
- Event (optional): Event object to be signaled when a reply arrives
|
||||
- ApcRoutine (optional): Routine to call when the calling thread is in an alertable thread and a reply arrives
|
||||
- ApcContext (optional): Optional parameter to ApcRoutine
|
||||
- SourceAddress: Source address of the request
|
||||
- DestinationAddress: Destination address of the request
|
||||
- RequestData: A pointer to echo data
|
||||
- RequestSize: Number of bytes in buffer pointed by echo data
|
||||
- RequestOptions (optional): A pointer to the IPv6 header options
|
||||
- ReplyBuffer: A pointer to the buffer for echoReply, options and data
|
||||
- ReplySize: Number of bytes allocated for ReplyBuffer
|
||||
- Timeout: Timeout in milliseconds to wait for a reply
|
||||
Returns:
|
||||
- the number of replies in uint32
|
||||
To retain the reference allocated objects, conversion from pointer to uintptr must happen as arguments to the
|
||||
syscall function
|
||||
*/
|
||||
|
||||
func (ip *icmpProxy) icmp6SendEcho(dst netip.Addr, echo *icmp.Echo) (*echoV6Resp, error) {
|
||||
dstAddr, err := newSockAddrIn6(dst)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dataSize := len(echo.Data)
|
||||
// Reply buffer needs to be big enough to hold an echoV6Reply, echo data, 8 bytes for ICMP error message
|
||||
// and ioStatusBlock
|
||||
replySize := echoV6ReplySize + uintptr(dataSize) + uintptr(icmpv6ErrMessageSize) + ioStatusBlockSize
|
||||
replyBuf := make([]byte, replySize)
|
||||
noEvent := nullParameter
|
||||
noApcRoutine := nullParameter
|
||||
noAppCtx := nullParameter
|
||||
noIPHeaderOption := nullParameter
|
||||
replyCount, _, err := Icmp6SendEcho_proc.Call(
|
||||
ip.handle,
|
||||
noEvent,
|
||||
noApcRoutine,
|
||||
noAppCtx,
|
||||
uintptr(unsafe.Pointer(ip.srcSocketAddr)),
|
||||
uintptr(unsafe.Pointer(dstAddr)),
|
||||
uintptr(unsafe.Pointer(&echo.Data[0])),
|
||||
uintptr(dataSize),
|
||||
noIPHeaderOption,
|
||||
uintptr(unsafe.Pointer(&replyBuf[0])),
|
||||
replySize,
|
||||
icmpRequestTimeoutMs,
|
||||
)
|
||||
if replyCount == 0 {
|
||||
// status is in the 4 bytes after ipv6AddrEx. The reply buffer size is at least size of ipv6AddrEx + 4
|
||||
if status, parseErr := unmarshalIPStatus(replyBuf[unsafe.Sizeof(ipv6AddrEx{}) : unsafe.Sizeof(ipv6AddrEx{})+4]); parseErr == nil && status != success {
|
||||
return nil, fmt.Errorf("received ip status: %s", status)
|
||||
}
|
||||
return nil, errors.Wrap(err, "did not receive ICMP echo reply")
|
||||
} else if replyCount > 1 {
|
||||
ip.logger.Warn().Msgf("Received %d ICMP echo replies, only sending 1 back", replyCount)
|
||||
}
|
||||
return newEchoV6Resp(replyBuf, dataSize)
|
||||
}
|
||||
|
||||
type echoV6Resp struct {
|
||||
reply *echoV6Reply
|
||||
data []byte
|
||||
}
|
||||
|
||||
func newEchoV6Resp(replyBuf []byte, dataSize int) (*echoV6Resp, error) {
|
||||
if len(replyBuf) == 0 {
|
||||
return nil, fmt.Errorf("reply buffer is empty")
|
||||
}
|
||||
reply := *(*echoV6Reply)(unsafe.Pointer(&replyBuf[0]))
|
||||
if reply.Status != success {
|
||||
return nil, fmt.Errorf("status %d", reply.Status)
|
||||
}
|
||||
if uintptr(len(replyBuf)) < unsafe.Sizeof(reply)+uintptr(dataSize) {
|
||||
return nil, fmt.Errorf("reply buffer size %d is too small to hold reply size %d + data size %d", len(replyBuf), echoV6ReplySize, dataSize)
|
||||
}
|
||||
return &echoV6Resp{
|
||||
reply: &reply,
|
||||
data: replyBuf[echoV6ReplySize : echoV6ReplySize+uintptr(dataSize)],
|
||||
}, nil
|
||||
}
|
||||
|
||||
func unmarshalIPStatus(replyBuf []byte) (ipStatus, error) {
|
||||
if len(replyBuf) != 4 {
|
||||
return 0, fmt.Errorf("ipStatus needs to be 4 bytes, got %d", len(replyBuf))
|
||||
}
|
||||
return ipStatus(endian.Uint32(replyBuf)), nil
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//go:build windows
|
||||
|
||||
package ingress
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/net/icmp"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestParseEchoReply tests parsing raw bytes from icmpSendEcho into echoResp
|
||||
func TestParseEchoReply(t *testing.T) {
|
||||
dst, err := inAddrV4(netip.MustParseAddr("192.168.10.20"))
|
||||
require.NoError(t, err)
|
||||
|
||||
validReplyData := []byte(t.Name())
|
||||
validReply := echoReply{
|
||||
Address: dst,
|
||||
Status: success,
|
||||
RoundTripTime: uint32(20),
|
||||
DataSize: uint16(len(validReplyData)),
|
||||
DataPointer: &validReplyData[0],
|
||||
Options: ipOption{
|
||||
TTL: 59,
|
||||
},
|
||||
}
|
||||
|
||||
destHostUnreachableReply := validReply
|
||||
destHostUnreachableReply.Status = destHostUnreachable
|
||||
|
||||
tests := []struct {
|
||||
testCase string
|
||||
replyBuf []byte
|
||||
expectedReply *echoReply
|
||||
expectedData []byte
|
||||
}{
|
||||
{
|
||||
testCase: "empty buffer",
|
||||
},
|
||||
{
|
||||
testCase: "status not success",
|
||||
replyBuf: destHostUnreachableReply.marshal(t, []byte{}),
|
||||
},
|
||||
{
|
||||
testCase: "valid reply",
|
||||
replyBuf: validReply.marshal(t, validReplyData),
|
||||
expectedReply: &validReply,
|
||||
expectedData: validReplyData,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
resp, err := newEchoResp(test.replyBuf)
|
||||
if test.expectedReply == nil {
|
||||
require.Error(t, err)
|
||||
require.Nil(t, resp)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, resp.reply, test.expectedReply)
|
||||
require.True(t, bytes.Equal(resp.data, test.expectedData))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestParseEchoV6Reply tests parsing raw bytes from icmp6SendEcho into echoV6Resp
|
||||
func TestParseEchoV6Reply(t *testing.T) {
|
||||
dst := netip.MustParseAddr("2606:3600:4500::3333").As16()
|
||||
var addr [8]uint16
|
||||
for i := 0; i < 8; i++ {
|
||||
addr[i] = binary.BigEndian.Uint16(dst[i*2 : i*2+2])
|
||||
}
|
||||
|
||||
validReplyData := []byte(t.Name())
|
||||
validReply := echoV6Reply{
|
||||
Address: ipv6AddrEx{
|
||||
addr: addr,
|
||||
},
|
||||
Status: success,
|
||||
RoundTripTime: 25,
|
||||
}
|
||||
|
||||
destHostUnreachableReply := validReply
|
||||
destHostUnreachableReply.Status = ipv6DestUnreachable
|
||||
|
||||
tests := []struct {
|
||||
testCase string
|
||||
replyBuf []byte
|
||||
expectedReply *echoV6Reply
|
||||
expectedData []byte
|
||||
}{
|
||||
{
|
||||
testCase: "empty buffer",
|
||||
},
|
||||
{
|
||||
testCase: "status not success",
|
||||
replyBuf: destHostUnreachableReply.marshal(t, []byte{}),
|
||||
},
|
||||
{
|
||||
testCase: "valid reply",
|
||||
replyBuf: validReply.marshal(t, validReplyData),
|
||||
expectedReply: &validReply,
|
||||
expectedData: validReplyData,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
resp, err := newEchoV6Resp(test.replyBuf, len(test.expectedData))
|
||||
if test.expectedReply == nil {
|
||||
require.Error(t, err)
|
||||
require.Nil(t, resp)
|
||||
} else {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, resp.reply, test.expectedReply)
|
||||
require.True(t, bytes.Equal(resp.data, test.expectedData))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendEchoErrors makes sure icmpSendEcho handles error cases
|
||||
func TestSendEchoErrors(t *testing.T) {
|
||||
testSendEchoErrors(t, netip.IPv4Unspecified())
|
||||
testSendEchoErrors(t, netip.IPv6Unspecified())
|
||||
}
|
||||
|
||||
func testSendEchoErrors(t *testing.T, listenIP netip.Addr) {
|
||||
proxy, err := newICMPProxy(listenIP, &noopLogger, time.Second)
|
||||
require.NoError(t, err)
|
||||
|
||||
echo := icmp.Echo{
|
||||
ID: 6193,
|
||||
Seq: 25712,
|
||||
Data: []byte(t.Name()),
|
||||
}
|
||||
documentIP := netip.MustParseAddr("192.0.2.200")
|
||||
if listenIP.Is6() {
|
||||
documentIP = netip.MustParseAddr("2001:db8::1")
|
||||
}
|
||||
resp, err := proxy.icmpEchoRoundtrip(documentIP, &echo)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, resp)
|
||||
}
|
||||
|
||||
func (er *echoReply) marshal(t *testing.T, data []byte) []byte {
|
||||
buf := new(bytes.Buffer)
|
||||
|
||||
for _, field := range []any{
|
||||
er.Address,
|
||||
er.Status,
|
||||
er.RoundTripTime,
|
||||
er.DataSize,
|
||||
er.Reserved,
|
||||
} {
|
||||
require.NoError(t, binary.Write(buf, endian, field))
|
||||
}
|
||||
|
||||
require.NoError(t, marshalPointer(buf, uintptr(unsafe.Pointer(er.DataPointer))))
|
||||
|
||||
for _, field := range []any{
|
||||
er.Options.TTL,
|
||||
er.Options.Tos,
|
||||
er.Options.Flags,
|
||||
er.Options.OptionsSize,
|
||||
} {
|
||||
require.NoError(t, binary.Write(buf, endian, field))
|
||||
}
|
||||
|
||||
require.NoError(t, marshalPointer(buf, er.Options.OptionsData))
|
||||
|
||||
padSize := buf.Len() % int(unsafe.Alignof(er))
|
||||
padding := make([]byte, padSize)
|
||||
n, err := buf.Write(padding)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, padSize, n)
|
||||
|
||||
n, err = buf.Write(data)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, len(data), n)
|
||||
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func marshalPointer(buf io.Writer, ptr uintptr) error {
|
||||
size := unsafe.Sizeof(ptr)
|
||||
switch size {
|
||||
case 4:
|
||||
return binary.Write(buf, endian, uint32(ptr))
|
||||
case 8:
|
||||
return binary.Write(buf, endian, uint64(ptr))
|
||||
default:
|
||||
return fmt.Errorf("unexpected pointer size %d", size)
|
||||
}
|
||||
}
|
||||
|
||||
func (er *echoV6Reply) marshal(t *testing.T, data []byte) []byte {
|
||||
buf := new(bytes.Buffer)
|
||||
|
||||
for _, field := range []any{
|
||||
er.Address.port,
|
||||
er.Address.flowInfoUpper,
|
||||
er.Address.flowInfoLower,
|
||||
er.Address.addr,
|
||||
er.Address.scopeID,
|
||||
} {
|
||||
require.NoError(t, binary.Write(buf, endian, field))
|
||||
}
|
||||
|
||||
padSize := buf.Len() % int(unsafe.Alignof(er))
|
||||
padding := make([]byte, padSize)
|
||||
n, err := buf.Write(padding)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, padSize, n)
|
||||
|
||||
for _, field := range []any{
|
||||
er.Status,
|
||||
er.RoundTripTime,
|
||||
} {
|
||||
require.NoError(t, binary.Write(buf, endian, field))
|
||||
}
|
||||
|
||||
n, err = buf.Write(data)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, len(data), n)
|
||||
|
||||
return buf.Bytes()
|
||||
}
|
||||
+6
-3
@@ -182,11 +182,14 @@ func validateIngress(ingress []config.UnvalidatedIngressRule, defaults OriginReq
|
||||
path := strings.TrimPrefix(r.Service, prefix)
|
||||
service = &unixSocketPath{path: path, scheme: "https"}
|
||||
} else if prefix := "http_status:"; strings.HasPrefix(r.Service, prefix) {
|
||||
status, err := strconv.Atoi(strings.TrimPrefix(r.Service, prefix))
|
||||
statusCode, err := strconv.Atoi(strings.TrimPrefix(r.Service, prefix))
|
||||
if err != nil {
|
||||
return Ingress{}, errors.Wrap(err, "invalid HTTP status")
|
||||
return Ingress{}, errors.Wrap(err, "invalid HTTP status code")
|
||||
}
|
||||
srv := newStatusCode(status)
|
||||
if statusCode < 100 || statusCode > 999 {
|
||||
return Ingress{}, fmt.Errorf("invalid HTTP status code: %d", statusCode)
|
||||
}
|
||||
srv := newStatusCode(statusCode)
|
||||
service = &srv
|
||||
} else if r.Service == HelloWorldService || r.Service == "hello-world" || r.Service == "helloworld" {
|
||||
service = new(helloWorld)
|
||||
|
||||
@@ -208,6 +208,14 @@ ingress:
|
||||
args: args{rawYAML: `
|
||||
ingress:
|
||||
- service: http_status:asdf
|
||||
`},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Invalid HTTP status code",
|
||||
args: args{rawYAML: `
|
||||
ingress:
|
||||
- service: http_status:8080
|
||||
`},
|
||||
wantErr: true,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package ingress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
const (
|
||||
// funnelIdleTimeout controls how long to wait to close a funnel without send/return
|
||||
funnelIdleTimeout = time.Second * 10
|
||||
mtu = 1500
|
||||
// icmpRequestTimeoutMs controls how long to wait for a reply
|
||||
icmpRequestTimeoutMs = 1000
|
||||
)
|
||||
|
||||
var (
|
||||
errPacketNil = fmt.Errorf("packet is nil")
|
||||
)
|
||||
|
||||
type icmpRouter struct {
|
||||
ipv4Proxy *icmpProxy
|
||||
ipv6Proxy *icmpProxy
|
||||
}
|
||||
|
||||
// NewICMPRouter doesn't return an error if either ipv4 proxy or ipv6 proxy can be created. The machine might only
|
||||
// support one of them
|
||||
func NewICMPRouter(logger *zerolog.Logger) (*icmpRouter, error) {
|
||||
// TODO: TUN-6741: don't bind to all interface
|
||||
ipv4Proxy, ipv4Err := newICMPProxy(netip.IPv4Unspecified(), logger, funnelIdleTimeout)
|
||||
ipv6Proxy, ipv6Err := newICMPProxy(netip.IPv6Unspecified(), logger, funnelIdleTimeout)
|
||||
if ipv4Err != nil && ipv6Err != nil {
|
||||
return nil, fmt.Errorf("cannot create ICMPv4 proxy: %v nor ICMPv6 proxy: %v", ipv4Err, ipv6Err)
|
||||
}
|
||||
if ipv4Err != nil {
|
||||
logger.Debug().Err(ipv4Err).Msg("failed to create ICMPv4 proxy, only ICMPv6 proxy is created")
|
||||
ipv4Proxy = nil
|
||||
}
|
||||
if ipv6Err != nil {
|
||||
logger.Debug().Err(ipv6Err).Msg("failed to create ICMPv6 proxy, only ICMPv4 proxy is created")
|
||||
ipv6Proxy = nil
|
||||
}
|
||||
return &icmpRouter{
|
||||
ipv4Proxy: ipv4Proxy,
|
||||
ipv6Proxy: ipv6Proxy,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (ir *icmpRouter) Serve(ctx context.Context) error {
|
||||
if ir.ipv4Proxy != nil && ir.ipv6Proxy != nil {
|
||||
errC := make(chan error, 2)
|
||||
go func() {
|
||||
errC <- ir.ipv4Proxy.Serve(ctx)
|
||||
}()
|
||||
go func() {
|
||||
errC <- ir.ipv6Proxy.Serve(ctx)
|
||||
}()
|
||||
return <-errC
|
||||
}
|
||||
if ir.ipv4Proxy != nil {
|
||||
return ir.ipv4Proxy.Serve(ctx)
|
||||
}
|
||||
if ir.ipv6Proxy != nil {
|
||||
return ir.ipv6Proxy.Serve(ctx)
|
||||
}
|
||||
return fmt.Errorf("ICMPv4 proxy and ICMPv6 proxy are both nil")
|
||||
}
|
||||
|
||||
func (ir *icmpRouter) Request(pk *packet.ICMP, responder packet.FunnelUniPipe) error {
|
||||
if pk.Dst.Is4() {
|
||||
if ir.ipv4Proxy != nil {
|
||||
return ir.ipv4Proxy.Request(pk, responder)
|
||||
}
|
||||
return fmt.Errorf("ICMPv4 proxy was not instantiated")
|
||||
}
|
||||
if ir.ipv6Proxy != nil {
|
||||
return ir.ipv6Proxy.Request(pk, responder)
|
||||
}
|
||||
return fmt.Errorf("ICMPv6 proxy was not instantiated")
|
||||
}
|
||||
|
||||
func getICMPEcho(msg *icmp.Message) (*icmp.Echo, error) {
|
||||
echo, ok := msg.Body.(*icmp.Echo)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("expect ICMP echo, got %s", msg.Type)
|
||||
}
|
||||
return echo, nil
|
||||
}
|
||||
|
||||
func isEchoReply(msg *icmp.Message) bool {
|
||||
return msg.Type == ipv4.ICMPTypeEchoReply || msg.Type == ipv6.ICMPTypeEchoReply
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
package ingress
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
var (
|
||||
noopLogger = zerolog.Nop()
|
||||
localhostIP = netip.MustParseAddr("127.0.0.1")
|
||||
localhostIPv6 = netip.MustParseAddr("::1")
|
||||
)
|
||||
|
||||
// TestICMPProxyEcho makes sure we can send ICMP echo via the Request method and receives response via the
|
||||
// ListenResponse method
|
||||
//
|
||||
// Note: if this test fails on your device under Linux, then most likely you need to make sure that your user
|
||||
// is allowed in ping_group_range. See the following gist for how to do that:
|
||||
// https://github.com/ValentinBELYN/icmplib/blob/main/docs/6-use-icmplib-without-privileges.md
|
||||
func TestICMPRouterEcho(t *testing.T) {
|
||||
testICMPRouterEcho(t, true)
|
||||
testICMPRouterEcho(t, false)
|
||||
}
|
||||
|
||||
func testICMPRouterEcho(t *testing.T, sendIPv4 bool) {
|
||||
const (
|
||||
echoID = 36571
|
||||
endSeq = 20
|
||||
)
|
||||
|
||||
router, err := NewICMPRouter(&noopLogger)
|
||||
require.NoError(t, err)
|
||||
|
||||
proxyDone := make(chan struct{})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go func() {
|
||||
router.Serve(ctx)
|
||||
close(proxyDone)
|
||||
}()
|
||||
|
||||
responder := echoFlowResponder{
|
||||
decoder: packet.NewICMPDecoder(),
|
||||
respChan: make(chan []byte, 1),
|
||||
}
|
||||
|
||||
protocol := layers.IPProtocolICMPv6
|
||||
if sendIPv4 {
|
||||
protocol = layers.IPProtocolICMPv4
|
||||
}
|
||||
localIPs := getLocalIPs(t, sendIPv4)
|
||||
ips := make([]*packet.IP, len(localIPs))
|
||||
for i, localIP := range localIPs {
|
||||
ips[i] = &packet.IP{
|
||||
Src: localIP,
|
||||
Dst: localIP,
|
||||
Protocol: protocol,
|
||||
TTL: packet.DefaultTTL,
|
||||
}
|
||||
}
|
||||
|
||||
var icmpType icmp.Type = ipv6.ICMPTypeEchoRequest
|
||||
if sendIPv4 {
|
||||
icmpType = ipv4.ICMPTypeEcho
|
||||
}
|
||||
for seq := 0; seq < endSeq; seq++ {
|
||||
for i, ip := range ips {
|
||||
pk := packet.ICMP{
|
||||
IP: ip,
|
||||
Message: &icmp.Message{
|
||||
Type: icmpType,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: echoID + i,
|
||||
Seq: seq,
|
||||
Data: []byte(fmt.Sprintf("icmp echo seq %d", seq)),
|
||||
},
|
||||
},
|
||||
}
|
||||
require.NoError(t, router.Request(&pk, &responder))
|
||||
responder.validate(t, &pk)
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
<-proxyDone
|
||||
}
|
||||
|
||||
// TestConcurrentRequests makes sure icmpRouter can send concurrent requests to the same destination with different
|
||||
// echo ID. This simulates concurrent ping to the same destination.
|
||||
func TestConcurrentRequestsToSameDst(t *testing.T) {
|
||||
const (
|
||||
concurrentPings = 5
|
||||
endSeq = 5
|
||||
)
|
||||
|
||||
router, err := NewICMPRouter(&noopLogger)
|
||||
require.NoError(t, err)
|
||||
|
||||
proxyDone := make(chan struct{})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go func() {
|
||||
router.Serve(ctx)
|
||||
close(proxyDone)
|
||||
}()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
// icmpv4 and icmpv6 each has concurrentPings
|
||||
wg.Add(concurrentPings * 2)
|
||||
for i := 0; i < concurrentPings; i++ {
|
||||
echoID := 38451 + i
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
responder := echoFlowResponder{
|
||||
decoder: packet.NewICMPDecoder(),
|
||||
respChan: make(chan []byte, 1),
|
||||
}
|
||||
for seq := 0; seq < endSeq; seq++ {
|
||||
pk := &packet.ICMP{
|
||||
IP: &packet.IP{
|
||||
Src: localhostIP,
|
||||
Dst: localhostIP,
|
||||
Protocol: layers.IPProtocolICMPv4,
|
||||
TTL: packet.DefaultTTL,
|
||||
},
|
||||
Message: &icmp.Message{
|
||||
Type: ipv4.ICMPTypeEcho,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: echoID,
|
||||
Seq: seq,
|
||||
Data: []byte(fmt.Sprintf("icmpv4 echo id %d, seq %d", echoID, seq)),
|
||||
},
|
||||
},
|
||||
}
|
||||
require.NoError(t, router.Request(pk, &responder))
|
||||
responder.validate(t, pk)
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
responder := echoFlowResponder{
|
||||
decoder: packet.NewICMPDecoder(),
|
||||
respChan: make(chan []byte, 1),
|
||||
}
|
||||
for seq := 0; seq < endSeq; seq++ {
|
||||
pk := &packet.ICMP{
|
||||
IP: &packet.IP{
|
||||
Src: localhostIPv6,
|
||||
Dst: localhostIPv6,
|
||||
Protocol: layers.IPProtocolICMPv6,
|
||||
TTL: packet.DefaultTTL,
|
||||
},
|
||||
Message: &icmp.Message{
|
||||
Type: ipv6.ICMPTypeEchoRequest,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: echoID,
|
||||
Seq: seq,
|
||||
Data: []byte(fmt.Sprintf("icmpv6 echo id %d, seq %d", echoID, seq)),
|
||||
},
|
||||
},
|
||||
}
|
||||
require.NoError(t, router.Request(pk, &responder))
|
||||
responder.validate(t, pk)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
cancel()
|
||||
<-proxyDone
|
||||
}
|
||||
|
||||
// TestICMPProxyRejectNotEcho makes sure it rejects messages other than echo
|
||||
func TestICMPRouterRejectNotEcho(t *testing.T) {
|
||||
msgs := []icmp.Message{
|
||||
{
|
||||
Type: ipv4.ICMPTypeDestinationUnreachable,
|
||||
Code: 1,
|
||||
Body: &icmp.DstUnreach{
|
||||
Data: []byte("original packet"),
|
||||
},
|
||||
},
|
||||
{
|
||||
Type: ipv4.ICMPTypeTimeExceeded,
|
||||
Code: 1,
|
||||
Body: &icmp.TimeExceeded{
|
||||
Data: []byte("original packet"),
|
||||
},
|
||||
},
|
||||
{
|
||||
Type: ipv4.ICMPType(2),
|
||||
Code: 0,
|
||||
Body: &icmp.PacketTooBig{
|
||||
MTU: 1280,
|
||||
Data: []byte("original packet"),
|
||||
},
|
||||
},
|
||||
}
|
||||
testICMPRouterRejectNotEcho(t, localhostIP, msgs)
|
||||
msgsV6 := []icmp.Message{
|
||||
{
|
||||
Type: ipv6.ICMPTypeDestinationUnreachable,
|
||||
Code: 3,
|
||||
Body: &icmp.DstUnreach{
|
||||
Data: []byte("original packet"),
|
||||
},
|
||||
},
|
||||
{
|
||||
Type: ipv6.ICMPTypeTimeExceeded,
|
||||
Code: 0,
|
||||
Body: &icmp.TimeExceeded{
|
||||
Data: []byte("original packet"),
|
||||
},
|
||||
},
|
||||
{
|
||||
Type: ipv6.ICMPTypePacketTooBig,
|
||||
Code: 0,
|
||||
Body: &icmp.PacketTooBig{
|
||||
MTU: 1280,
|
||||
Data: []byte("original packet"),
|
||||
},
|
||||
},
|
||||
}
|
||||
testICMPRouterRejectNotEcho(t, localhostIPv6, msgsV6)
|
||||
}
|
||||
|
||||
func testICMPRouterRejectNotEcho(t *testing.T, srcDstIP netip.Addr, msgs []icmp.Message) {
|
||||
router, err := NewICMPRouter(&noopLogger)
|
||||
require.NoError(t, err)
|
||||
|
||||
responder := echoFlowResponder{
|
||||
decoder: packet.NewICMPDecoder(),
|
||||
respChan: make(chan []byte),
|
||||
}
|
||||
protocol := layers.IPProtocolICMPv4
|
||||
if srcDstIP.Is6() {
|
||||
protocol = layers.IPProtocolICMPv6
|
||||
}
|
||||
for _, m := range msgs {
|
||||
pk := packet.ICMP{
|
||||
IP: &packet.IP{
|
||||
Src: srcDstIP,
|
||||
Dst: srcDstIP,
|
||||
Protocol: protocol,
|
||||
TTL: packet.DefaultTTL,
|
||||
},
|
||||
Message: &m,
|
||||
}
|
||||
require.Error(t, router.Request(&pk, &responder))
|
||||
}
|
||||
}
|
||||
|
||||
type echoFlowResponder struct {
|
||||
lock sync.Mutex
|
||||
decoder *packet.ICMPDecoder
|
||||
respChan chan []byte
|
||||
}
|
||||
|
||||
func (efr *echoFlowResponder) SendPacket(dst netip.Addr, pk packet.RawPacket) error {
|
||||
efr.lock.Lock()
|
||||
defer efr.lock.Unlock()
|
||||
copiedPacket := make([]byte, len(pk.Data))
|
||||
copy(copiedPacket, pk.Data)
|
||||
efr.respChan <- copiedPacket
|
||||
return nil
|
||||
}
|
||||
|
||||
func (efr *echoFlowResponder) Close() error {
|
||||
efr.lock.Lock()
|
||||
defer efr.lock.Unlock()
|
||||
close(efr.respChan)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (efr *echoFlowResponder) validate(t *testing.T, echoReq *packet.ICMP) {
|
||||
pk := <-efr.respChan
|
||||
decoded, err := efr.decoder.Decode(packet.RawPacket{Data: pk})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, decoded.Src, echoReq.Dst)
|
||||
require.Equal(t, decoded.Dst, echoReq.Src)
|
||||
require.Equal(t, echoReq.Protocol, decoded.Protocol)
|
||||
|
||||
if echoReq.Type == ipv4.ICMPTypeEcho {
|
||||
require.Equal(t, ipv4.ICMPTypeEchoReply, decoded.Type)
|
||||
} else {
|
||||
require.Equal(t, ipv6.ICMPTypeEchoReply, decoded.Type)
|
||||
}
|
||||
require.Equal(t, 0, decoded.Code)
|
||||
if echoReq.Type == ipv4.ICMPTypeEcho {
|
||||
require.NotZero(t, decoded.Checksum)
|
||||
} else {
|
||||
// For ICMPv6, the kernel will compute the checksum during transmission unless pseudo header is not nil
|
||||
require.Zero(t, decoded.Checksum)
|
||||
}
|
||||
|
||||
require.Equal(t, echoReq.Body, decoded.Body)
|
||||
}
|
||||
|
||||
func getLocalIPs(t *testing.T, ipv4 bool) []netip.Addr {
|
||||
interfaces, err := net.Interfaces()
|
||||
require.NoError(t, err)
|
||||
localIPs := []netip.Addr{}
|
||||
for _, i := range interfaces {
|
||||
// Skip TUN devices
|
||||
if strings.Contains(i.Name, "tun") {
|
||||
continue
|
||||
}
|
||||
addrs, err := i.Addrs()
|
||||
require.NoError(t, err)
|
||||
for _, addr := range addrs {
|
||||
if ipnet, ok := addr.(*net.IPNet); ok && (ipnet.IP.IsPrivate() || ipnet.IP.IsLoopback()) {
|
||||
if (ipv4 && ipnet.IP.To4() != nil) || (!ipv4 && ipnet.IP.To4() == nil) {
|
||||
localIPs = append(localIPs, netip.MustParseAddr(ipnet.IP.String()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return localIPs
|
||||
}
|
||||
@@ -182,25 +182,25 @@ func TestMarshalJSON(t *testing.T) {
|
||||
{
|
||||
name: "Nil",
|
||||
path: nil,
|
||||
expected: `{"hostname":"example.com","path":null,"service":"https://localhost:8000","originRequest":{"connectTimeout":30,"tlsTimeout":10,"tcpKeepAlive":30,"noHappyEyeballs":false,"keepAliveTimeout":90,"keepAliveConnections":100,"httpHostHeader":"","originServerName":"","caPool":"","noTLSVerify":false,"disableChunkedEncoding":false,"bastionMode":false,"proxyAddress":"127.0.0.1","proxyPort":0,"proxyType":"","ipRules":null,"http2Origin":false}}`,
|
||||
expected: `{"hostname":"example.com","path":null,"service":"https://localhost:8000","originRequest":{"connectTimeout":30,"tlsTimeout":10,"tcpKeepAlive":30,"noHappyEyeballs":false,"keepAliveTimeout":90,"keepAliveConnections":100,"httpHostHeader":"","originServerName":"","caPool":"","noTLSVerify":false,"disableChunkedEncoding":false,"bastionMode":false,"proxyAddress":"127.0.0.1","proxyPort":0,"proxyType":"","ipRules":null,"http2Origin":false,"access":{"Enabled":false}}}`,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "Nil regex",
|
||||
path: &Regexp{Regexp: nil},
|
||||
expected: `{"hostname":"example.com","path":null,"service":"https://localhost:8000","originRequest":{"connectTimeout":30,"tlsTimeout":10,"tcpKeepAlive":30,"noHappyEyeballs":false,"keepAliveTimeout":90,"keepAliveConnections":100,"httpHostHeader":"","originServerName":"","caPool":"","noTLSVerify":false,"disableChunkedEncoding":false,"bastionMode":false,"proxyAddress":"127.0.0.1","proxyPort":0,"proxyType":"","ipRules":null,"http2Origin":false}}`,
|
||||
expected: `{"hostname":"example.com","path":null,"service":"https://localhost:8000","originRequest":{"connectTimeout":30,"tlsTimeout":10,"tcpKeepAlive":30,"noHappyEyeballs":false,"keepAliveTimeout":90,"keepAliveConnections":100,"httpHostHeader":"","originServerName":"","caPool":"","noTLSVerify":false,"disableChunkedEncoding":false,"bastionMode":false,"proxyAddress":"127.0.0.1","proxyPort":0,"proxyType":"","ipRules":null,"http2Origin":false,"access":{"Enabled":false}}}`,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "Empty",
|
||||
path: &Regexp{Regexp: regexp.MustCompile("")},
|
||||
expected: `{"hostname":"example.com","path":"","service":"https://localhost:8000","originRequest":{"connectTimeout":30,"tlsTimeout":10,"tcpKeepAlive":30,"noHappyEyeballs":false,"keepAliveTimeout":90,"keepAliveConnections":100,"httpHostHeader":"","originServerName":"","caPool":"","noTLSVerify":false,"disableChunkedEncoding":false,"bastionMode":false,"proxyAddress":"127.0.0.1","proxyPort":0,"proxyType":"","ipRules":null,"http2Origin":false}}`,
|
||||
expected: `{"hostname":"example.com","path":"","service":"https://localhost:8000","originRequest":{"connectTimeout":30,"tlsTimeout":10,"tcpKeepAlive":30,"noHappyEyeballs":false,"keepAliveTimeout":90,"keepAliveConnections":100,"httpHostHeader":"","originServerName":"","caPool":"","noTLSVerify":false,"disableChunkedEncoding":false,"bastionMode":false,"proxyAddress":"127.0.0.1","proxyPort":0,"proxyType":"","ipRules":null,"http2Origin":false,"access":{"Enabled":false}}}`,
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "Basic",
|
||||
path: &Regexp{Regexp: regexp.MustCompile("/echo")},
|
||||
expected: `{"hostname":"example.com","path":"/echo","service":"https://localhost:8000","originRequest":{"connectTimeout":30,"tlsTimeout":10,"tcpKeepAlive":30,"noHappyEyeballs":false,"keepAliveTimeout":90,"keepAliveConnections":100,"httpHostHeader":"","originServerName":"","caPool":"","noTLSVerify":false,"disableChunkedEncoding":false,"bastionMode":false,"proxyAddress":"127.0.0.1","proxyPort":0,"proxyType":"","ipRules":null,"http2Origin":false}}`,
|
||||
expected: `{"hostname":"example.com","path":"/echo","service":"https://localhost:8000","originRequest":{"connectTimeout":30,"tlsTimeout":10,"tcpKeepAlive":30,"noHappyEyeballs":false,"keepAliveTimeout":90,"keepAliveConnections":100,"httpHostHeader":"","originServerName":"","caPool":"","noTLSVerify":false,"disableChunkedEncoding":false,"bastionMode":false,"proxyAddress":"127.0.0.1","proxyPort":0,"proxyType":"","ipRules":null,"http2Origin":false,"access":{"Enabled":false}}}`,
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
|
||||
+11
-11
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
func TestReadyServer_makeResponse(t *testing.T) {
|
||||
type fields struct {
|
||||
isConnected map[int]bool
|
||||
isConnected map[uint8]tunnelstate.ConnectionInfo
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -25,11 +25,11 @@ func TestReadyServer_makeResponse(t *testing.T) {
|
||||
{
|
||||
name: "One connection online => HTTP 200",
|
||||
fields: fields{
|
||||
isConnected: map[int]bool{
|
||||
0: false,
|
||||
1: false,
|
||||
2: true,
|
||||
3: false,
|
||||
isConnected: map[uint8]tunnelstate.ConnectionInfo{
|
||||
0: {IsConnected: false},
|
||||
1: {IsConnected: false},
|
||||
2: {IsConnected: true},
|
||||
3: {IsConnected: false},
|
||||
},
|
||||
},
|
||||
wantOK: true,
|
||||
@@ -38,11 +38,11 @@ func TestReadyServer_makeResponse(t *testing.T) {
|
||||
{
|
||||
name: "No connections online => no HTTP 200",
|
||||
fields: fields{
|
||||
isConnected: map[int]bool{
|
||||
0: false,
|
||||
1: false,
|
||||
2: false,
|
||||
3: false,
|
||||
isConnected: map[uint8]tunnelstate.ConnectionInfo{
|
||||
0: {IsConnected: false},
|
||||
1: {IsConnected: false},
|
||||
2: {IsConnected: false},
|
||||
3: {IsConnected: false},
|
||||
},
|
||||
},
|
||||
wantReadyConnections: 0,
|
||||
|
||||
@@ -355,7 +355,7 @@ func proxyHTTP(originProxy connection.OriginProxy, hostname string) (*http.Respo
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = originProxy.ProxyHTTP(respWriter, tracing.NewTracedRequest(req), false)
|
||||
err = originProxy.ProxyHTTP(respWriter, tracing.NewTracedHTTPRequest(req, &log), false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -500,7 +500,8 @@ func TestClosePreviousProxies(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, http.StatusTeapot, resp.StatusCode)
|
||||
|
||||
// The hello-world server in config v1 should have been stopped
|
||||
// The hello-world server in config v1 should have been stopped. We wait a bit since it's closed asynchronously.
|
||||
time.Sleep(time.Millisecond * 10)
|
||||
resp, err = proxyHTTP(originProxyV1, hostname)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, resp)
|
||||
@@ -604,7 +605,7 @@ func TestPersistentConnection(t *testing.T) {
|
||||
respWriter, err := connection.NewHTTP2RespWriter(req, wsRespReadWriter, connection.TypeWebsocket, &log)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = originProxy.ProxyHTTP(respWriter, tracing.NewTracedRequest(req), true)
|
||||
err = originProxy.ProxyHTTP(respWriter, tracing.NewTracedHTTPRequest(req, &log), true)
|
||||
require.NoError(t, err)
|
||||
}()
|
||||
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/net/icmp"
|
||||
)
|
||||
|
||||
func FindProtocol(p []byte) (layers.IPProtocol, error) {
|
||||
version, err := FindIPVersion(p)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
switch version {
|
||||
case 4:
|
||||
if len(p) < ipv4MinHeaderLen {
|
||||
return 0, fmt.Errorf("IPv4 packet should have at least %d bytes, got %d bytes", ipv4MinHeaderLen, len(p))
|
||||
}
|
||||
// Protocol is in the 10th byte of IPv4 header
|
||||
return layers.IPProtocol(p[9]), nil
|
||||
case 6:
|
||||
if len(p) < ipv6HeaderLen {
|
||||
return 0, fmt.Errorf("IPv6 packet should have at least %d bytes, got %d bytes", ipv6HeaderLen, len(p))
|
||||
}
|
||||
// Next header is in the 7th byte of IPv6 header
|
||||
return layers.IPProtocol(p[6]), nil
|
||||
default:
|
||||
return 0, fmt.Errorf("unknow ip version %d", version)
|
||||
}
|
||||
}
|
||||
|
||||
func FindIPVersion(p []byte) (uint8, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, fmt.Errorf("packet length is 0")
|
||||
}
|
||||
return p[0] >> 4, nil
|
||||
}
|
||||
|
||||
// IPDecoder decodes raw packets into IP. It can process packets sequentially without allocating
|
||||
// memory for the layers, so it cannot be called concurrently.
|
||||
type IPDecoder struct {
|
||||
ipv4 *layers.IPv4
|
||||
ipv6 *layers.IPv6
|
||||
layers uint8
|
||||
|
||||
v4parser *gopacket.DecodingLayerParser
|
||||
v6parser *gopacket.DecodingLayerParser
|
||||
}
|
||||
|
||||
func NewIPDecoder() *IPDecoder {
|
||||
var (
|
||||
ipv4 layers.IPv4
|
||||
ipv6 layers.IPv6
|
||||
)
|
||||
dlpv4 := gopacket.NewDecodingLayerParser(layers.LayerTypeIPv4)
|
||||
dlpv4.SetDecodingLayerContainer(gopacket.DecodingLayerSparse(nil))
|
||||
dlpv4.AddDecodingLayer(&ipv4)
|
||||
// Stop parsing when it encounter a layer that it doesn't have a parser
|
||||
dlpv4.IgnoreUnsupported = true
|
||||
|
||||
dlpv6 := gopacket.NewDecodingLayerParser(layers.LayerTypeIPv6)
|
||||
dlpv6.SetDecodingLayerContainer(gopacket.DecodingLayerSparse(nil))
|
||||
dlpv6.AddDecodingLayer(&ipv6)
|
||||
dlpv6.IgnoreUnsupported = true
|
||||
|
||||
return &IPDecoder{
|
||||
ipv4: &ipv4,
|
||||
ipv6: &ipv6,
|
||||
layers: 1,
|
||||
v4parser: dlpv4,
|
||||
v6parser: dlpv6,
|
||||
}
|
||||
}
|
||||
|
||||
func (pd *IPDecoder) Decode(packet RawPacket) (*IP, error) {
|
||||
// Should decode to IP layer
|
||||
decoded, err := pd.decodeByVersion(packet.Data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, layerType := range decoded {
|
||||
switch layerType {
|
||||
case layers.LayerTypeIPv4:
|
||||
return newIPv4(pd.ipv4)
|
||||
case layers.LayerTypeIPv6:
|
||||
return newIPv6(pd.ipv6)
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("no ip layer is decoded")
|
||||
}
|
||||
|
||||
func (pd *IPDecoder) decodeByVersion(packet []byte) ([]gopacket.LayerType, error) {
|
||||
version, err := FindIPVersion(packet)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decoded := make([]gopacket.LayerType, 0, pd.layers)
|
||||
switch version {
|
||||
case 4:
|
||||
err = pd.v4parser.DecodeLayers(packet, &decoded)
|
||||
case 6:
|
||||
err = pd.v6parser.DecodeLayers(packet, &decoded)
|
||||
default:
|
||||
err = fmt.Errorf("unknow ip version %d", version)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decoded, nil
|
||||
}
|
||||
|
||||
// ICMPDecoder decodes raw packets into IP and ICMP. It can process packets sequentially without allocating
|
||||
// memory for the layers, so it cannot be called concurrently.
|
||||
type ICMPDecoder struct {
|
||||
*IPDecoder
|
||||
icmpv4 *layers.ICMPv4
|
||||
icmpv6 *layers.ICMPv6
|
||||
}
|
||||
|
||||
func NewICMPDecoder() *ICMPDecoder {
|
||||
ipDecoder := NewIPDecoder()
|
||||
|
||||
var (
|
||||
icmpv4 layers.ICMPv4
|
||||
icmpv6 layers.ICMPv6
|
||||
)
|
||||
ipDecoder.layers++
|
||||
ipDecoder.v4parser.AddDecodingLayer(&icmpv4)
|
||||
ipDecoder.v6parser.AddDecodingLayer(&icmpv6)
|
||||
|
||||
return &ICMPDecoder{
|
||||
IPDecoder: ipDecoder,
|
||||
icmpv4: &icmpv4,
|
||||
icmpv6: &icmpv6,
|
||||
}
|
||||
}
|
||||
|
||||
func (pd *ICMPDecoder) Decode(packet RawPacket) (*ICMP, error) {
|
||||
// Should decode to IP and optionally ICMP layer
|
||||
decoded, err := pd.decodeByVersion(packet.Data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, layerType := range decoded {
|
||||
switch layerType {
|
||||
case layers.LayerTypeICMPv4:
|
||||
ipv4, err := newIPv4(pd.ipv4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msg, err := icmp.ParseMessage(int(layers.IPProtocolICMPv4), append(pd.icmpv4.Contents, pd.icmpv4.Payload...))
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to parse ICMPv4 message")
|
||||
}
|
||||
return &ICMP{
|
||||
IP: ipv4,
|
||||
Message: msg,
|
||||
}, nil
|
||||
case layers.LayerTypeICMPv6:
|
||||
ipv6, err := newIPv6(pd.ipv6)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msg, err := icmp.ParseMessage(int(layers.IPProtocolICMPv6), append(pd.icmpv6.Contents, pd.icmpv6.Payload...))
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "failed to parse ICMPv6")
|
||||
}
|
||||
return &ICMP{
|
||||
IP: ipv6,
|
||||
Message: msg,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
layers := make([]string, len(decoded))
|
||||
for i, l := range decoded {
|
||||
layers[i] = l.String()
|
||||
}
|
||||
return nil, fmt.Errorf("Expect to decode IP and ICMP layers, got %s", layers)
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"testing"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
)
|
||||
|
||||
func TestDecodeIP(t *testing.T) {
|
||||
ipDecoder := NewIPDecoder()
|
||||
icmpDecoder := NewICMPDecoder()
|
||||
udps := []UDP{
|
||||
{
|
||||
IP: IP{
|
||||
Src: netip.MustParseAddr("172.16.0.1"),
|
||||
Dst: netip.MustParseAddr("10.0.0.1"),
|
||||
Protocol: layers.IPProtocolUDP,
|
||||
},
|
||||
SrcPort: 31678,
|
||||
DstPort: 53,
|
||||
},
|
||||
{
|
||||
|
||||
IP: IP{
|
||||
Src: netip.MustParseAddr("fd51:2391:523:f4ee::1"),
|
||||
Dst: netip.MustParseAddr("fd51:2391:697:f4ee::2"),
|
||||
Protocol: layers.IPProtocolUDP,
|
||||
},
|
||||
SrcPort: 52139,
|
||||
DstPort: 1053,
|
||||
},
|
||||
}
|
||||
|
||||
encoder := NewEncoder()
|
||||
for _, udp := range udps {
|
||||
p, err := encoder.Encode(&udp)
|
||||
require.NoError(t, err)
|
||||
|
||||
ipPacket, err := ipDecoder.Decode(p)
|
||||
require.NoError(t, err)
|
||||
assertIPLayer(t, &udp.IP, ipPacket)
|
||||
|
||||
icmpPacket, err := icmpDecoder.Decode(p)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, icmpPacket)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeICMP(t *testing.T) {
|
||||
ipDecoder := NewIPDecoder()
|
||||
icmpDecoder := NewICMPDecoder()
|
||||
var (
|
||||
ipv4Packet = IP{
|
||||
Src: netip.MustParseAddr("172.16.0.1"),
|
||||
Dst: netip.MustParseAddr("10.0.0.1"),
|
||||
Protocol: layers.IPProtocolICMPv4,
|
||||
TTL: DefaultTTL,
|
||||
}
|
||||
ipv6Packet = IP{
|
||||
Src: netip.MustParseAddr("fd51:2391:523:f4ee::1"),
|
||||
Dst: netip.MustParseAddr("fd51:2391:697:f4ee::2"),
|
||||
Protocol: layers.IPProtocolICMPv6,
|
||||
TTL: DefaultTTL,
|
||||
}
|
||||
icmpID = 100
|
||||
icmpSeq = 52819
|
||||
)
|
||||
tests := []struct {
|
||||
testCase string
|
||||
packet *ICMP
|
||||
}{
|
||||
{
|
||||
testCase: "icmpv4 time exceed",
|
||||
packet: &ICMP{
|
||||
IP: &ipv4Packet,
|
||||
Message: &icmp.Message{
|
||||
Type: ipv4.ICMPTypeTimeExceeded,
|
||||
Code: 0,
|
||||
Body: &icmp.TimeExceeded{
|
||||
Data: []byte("original packet"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testCase: "icmpv4 echo",
|
||||
packet: &ICMP{
|
||||
IP: &ipv4Packet,
|
||||
Message: &icmp.Message{
|
||||
Type: ipv4.ICMPTypeEcho,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: icmpID,
|
||||
Seq: icmpSeq,
|
||||
Data: []byte("icmpv4 echo"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testCase: "icmpv6 destination unreachable",
|
||||
packet: &ICMP{
|
||||
IP: &ipv6Packet,
|
||||
Message: &icmp.Message{
|
||||
Type: ipv6.ICMPTypeDestinationUnreachable,
|
||||
Code: 4,
|
||||
Body: &icmp.DstUnreach{
|
||||
Data: []byte("original packet"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
testCase: "icmpv6 echo",
|
||||
packet: &ICMP{
|
||||
IP: &ipv6Packet,
|
||||
Message: &icmp.Message{
|
||||
Type: ipv6.ICMPTypeEchoRequest,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: icmpID,
|
||||
Seq: icmpSeq,
|
||||
Data: []byte("icmpv6 echo"),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
encoder := NewEncoder()
|
||||
for _, test := range tests {
|
||||
p, err := encoder.Encode(test.packet)
|
||||
require.NoError(t, err)
|
||||
|
||||
ipPacket, err := ipDecoder.Decode(p)
|
||||
require.NoError(t, err)
|
||||
if ipPacket.Src.Is4() {
|
||||
assertIPLayer(t, &ipv4Packet, ipPacket)
|
||||
} else {
|
||||
assertIPLayer(t, &ipv6Packet, ipPacket)
|
||||
}
|
||||
icmpPacket, err := icmpDecoder.Decode(p)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, ipPacket, icmpPacket.IP)
|
||||
|
||||
require.Equal(t, test.packet.Type, icmpPacket.Type)
|
||||
require.Equal(t, test.packet.Code, icmpPacket.Code)
|
||||
require.Equal(t, test.packet.Body, icmpPacket.Body)
|
||||
expectedBody, err := test.packet.Body.Marshal(test.packet.Type.Protocol())
|
||||
require.NoError(t, err)
|
||||
decodedBody, err := icmpPacket.Body.Marshal(test.packet.Type.Protocol())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, expectedBody, decodedBody)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDecodeBadPackets makes sure decoders don't decode invalid packets
|
||||
func TestDecodeBadPackets(t *testing.T) {
|
||||
var (
|
||||
srcIPv4 = net.ParseIP("172.16.0.1")
|
||||
dstIPv4 = net.ParseIP("10.0.0.1")
|
||||
)
|
||||
|
||||
ipLayer := layers.IPv4{
|
||||
Version: 10,
|
||||
SrcIP: srcIPv4,
|
||||
DstIP: dstIPv4,
|
||||
Protocol: layers.IPProtocolICMPv4,
|
||||
TTL: DefaultTTL,
|
||||
}
|
||||
icmpLayer := layers.ICMPv4{
|
||||
TypeCode: layers.CreateICMPv4TypeCode(uint8(ipv4.ICMPTypeEcho), 0),
|
||||
Id: 100,
|
||||
Seq: 52819,
|
||||
}
|
||||
wrongIPVersion, err := createPacket(&ipLayer, &icmpLayer, nil, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
tests := []struct {
|
||||
testCase string
|
||||
packet []byte
|
||||
}{
|
||||
{
|
||||
testCase: "unknown IP version",
|
||||
packet: wrongIPVersion,
|
||||
},
|
||||
{
|
||||
testCase: "invalid packet",
|
||||
packet: []byte("not a packet"),
|
||||
},
|
||||
{
|
||||
testCase: "zero length packet",
|
||||
packet: []byte{},
|
||||
},
|
||||
}
|
||||
|
||||
ipDecoder := NewIPDecoder()
|
||||
icmpDecoder := NewICMPDecoder()
|
||||
for _, test := range tests {
|
||||
ipPacket, err := ipDecoder.Decode(RawPacket{Data: test.packet})
|
||||
require.Error(t, err)
|
||||
require.Nil(t, ipPacket)
|
||||
|
||||
icmpPacket, err := icmpDecoder.Decode(RawPacket{Data: test.packet})
|
||||
require.Error(t, err)
|
||||
require.Nil(t, icmpPacket)
|
||||
}
|
||||
}
|
||||
|
||||
func createPacket(ipLayer, secondLayer, thirdLayer gopacket.SerializableLayer, body []byte) ([]byte, error) {
|
||||
payload := gopacket.Payload(body)
|
||||
packet := gopacket.NewSerializeBuffer()
|
||||
var err error
|
||||
if thirdLayer != nil {
|
||||
err = gopacket.SerializeLayers(packet, serializeOpts, ipLayer, secondLayer, thirdLayer, payload)
|
||||
} else {
|
||||
err = gopacket.SerializeLayers(packet, serializeOpts, ipLayer, secondLayer, payload)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return packet.Bytes(), nil
|
||||
}
|
||||
|
||||
func assertIPLayer(t *testing.T, expected, actual *IP) {
|
||||
require.Equal(t, expected.Src, actual.Src)
|
||||
require.Equal(t, expected.Dst, actual.Dst)
|
||||
require.Equal(t, expected.Protocol, actual.Protocol)
|
||||
require.Equal(t, expected.TTL, actual.TTL)
|
||||
}
|
||||
|
||||
type UDP struct {
|
||||
IP
|
||||
SrcPort, DstPort layers.UDPPort
|
||||
}
|
||||
|
||||
func (u *UDP) EncodeLayers() ([]gopacket.SerializableLayer, error) {
|
||||
ipLayers, err := u.IP.EncodeLayers()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
udpLayer := layers.UDP{
|
||||
SrcPort: u.SrcPort,
|
||||
DstPort: u.DstPort,
|
||||
}
|
||||
udpLayer.SetNetworkLayerForChecksum(ipLayers[0].(gopacket.NetworkLayer))
|
||||
return append(ipLayers, &udpLayer), nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package packet
|
||||
|
||||
import "github.com/google/gopacket"
|
||||
|
||||
var (
|
||||
serializeOpts = gopacket.SerializeOptions{
|
||||
FixLengths: true,
|
||||
ComputeChecksums: true,
|
||||
}
|
||||
)
|
||||
|
||||
// RawPacket represents a raw packet or one encoded by Encoder
|
||||
type RawPacket struct {
|
||||
Data []byte
|
||||
}
|
||||
|
||||
type Encoder struct {
|
||||
// buf is reusable because SerializeLayers calls the Clear method before each encoding
|
||||
buf gopacket.SerializeBuffer
|
||||
}
|
||||
|
||||
func NewEncoder() *Encoder {
|
||||
return &Encoder{
|
||||
buf: gopacket.NewSerializeBuffer(),
|
||||
}
|
||||
}
|
||||
|
||||
func (e Encoder) Encode(packet Packet) (RawPacket, error) {
|
||||
encodedLayers, err := packet.EncodeLayers()
|
||||
if err != nil {
|
||||
return RawPacket{}, err
|
||||
}
|
||||
if err := gopacket.SerializeLayers(e.buf, serializeOpts, encodedLayers...); err != nil {
|
||||
return RawPacket{}, err
|
||||
}
|
||||
return RawPacket{
|
||||
Data: e.buf.Bytes(),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrFunnelNotFound = errors.New("funnel not found")
|
||||
)
|
||||
|
||||
// Funnel is an abstraction to pipe from 1 src to 1 or more destinations
|
||||
type Funnel interface {
|
||||
// SendToDst sends a raw packet to a destination
|
||||
SendToDst(dst netip.Addr, pk RawPacket) error
|
||||
// ReturnToSrc returns a raw packet to the source
|
||||
ReturnToSrc(pk RawPacket) error
|
||||
// LastActive returns the last time SendToDst or ReturnToSrc is called
|
||||
LastActive() time.Time
|
||||
// Close closes the funnel. Further call to SendToDst or ReturnToSrc should return an error
|
||||
Close() error
|
||||
// Equal compares if 2 funnels are equivalent
|
||||
Equal(other Funnel) bool
|
||||
}
|
||||
|
||||
// FunnelUniPipe is a unidirectional pipe for sending raw packets
|
||||
type FunnelUniPipe interface {
|
||||
// SendPacket sends a packet to/from the funnel. It must not modify the packet,
|
||||
// and after return it must not read the packet
|
||||
SendPacket(dst netip.Addr, pk RawPacket) error
|
||||
Close() error
|
||||
}
|
||||
|
||||
// RawPacketFunnel is an implementation of Funnel that sends raw packets. It can be embedded in other structs to
|
||||
// satisfy the Funnel interface.
|
||||
type RawPacketFunnel struct {
|
||||
Src netip.Addr
|
||||
// last active unix time. Unit is seconds
|
||||
lastActive int64
|
||||
sendPipe FunnelUniPipe
|
||||
returnPipe FunnelUniPipe
|
||||
}
|
||||
|
||||
func NewRawPacketFunnel(src netip.Addr, sendPipe, returnPipe FunnelUniPipe) *RawPacketFunnel {
|
||||
return &RawPacketFunnel{
|
||||
Src: src,
|
||||
lastActive: time.Now().Unix(),
|
||||
sendPipe: sendPipe,
|
||||
returnPipe: returnPipe,
|
||||
}
|
||||
}
|
||||
|
||||
func (rpf *RawPacketFunnel) SendToDst(dst netip.Addr, pk RawPacket) error {
|
||||
rpf.updateLastActive()
|
||||
return rpf.sendPipe.SendPacket(dst, pk)
|
||||
}
|
||||
|
||||
func (rpf *RawPacketFunnel) ReturnToSrc(pk RawPacket) error {
|
||||
rpf.updateLastActive()
|
||||
return rpf.returnPipe.SendPacket(rpf.Src, pk)
|
||||
}
|
||||
|
||||
func (rpf *RawPacketFunnel) updateLastActive() {
|
||||
atomic.StoreInt64(&rpf.lastActive, time.Now().Unix())
|
||||
}
|
||||
|
||||
func (rpf *RawPacketFunnel) LastActive() time.Time {
|
||||
lastActive := atomic.LoadInt64(&rpf.lastActive)
|
||||
return time.Unix(lastActive, 0)
|
||||
}
|
||||
|
||||
func (rpf *RawPacketFunnel) Close() error {
|
||||
sendPipeErr := rpf.sendPipe.Close()
|
||||
returnPipeErr := rpf.returnPipe.Close()
|
||||
if sendPipeErr != nil {
|
||||
return sendPipeErr
|
||||
}
|
||||
if returnPipeErr != nil {
|
||||
return returnPipeErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rpf *RawPacketFunnel) Equal(other Funnel) bool {
|
||||
otherRawFunnel, ok := other.(*RawPacketFunnel)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if rpf.Src != otherRawFunnel.Src {
|
||||
return false
|
||||
}
|
||||
if rpf.sendPipe != otherRawFunnel.sendPipe {
|
||||
return false
|
||||
}
|
||||
if rpf.returnPipe != otherRawFunnel.returnPipe {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// FunnelID represents a key type that can be used by FunnelTracker
|
||||
type FunnelID interface {
|
||||
// Type returns the name of the type that implements the FunnelID
|
||||
Type() string
|
||||
fmt.Stringer
|
||||
}
|
||||
|
||||
// FunnelTracker tracks funnel from the perspective of eyeball to origin
|
||||
type FunnelTracker struct {
|
||||
lock sync.RWMutex
|
||||
funnels map[FunnelID]Funnel
|
||||
}
|
||||
|
||||
func NewFunnelTracker() *FunnelTracker {
|
||||
return &FunnelTracker{
|
||||
funnels: make(map[FunnelID]Funnel),
|
||||
}
|
||||
}
|
||||
|
||||
func (ft *FunnelTracker) ScheduleCleanup(ctx context.Context, idleTimeout time.Duration) {
|
||||
checkIdleTicker := time.NewTicker(idleTimeout)
|
||||
defer checkIdleTicker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-checkIdleTicker.C:
|
||||
ft.cleanup(idleTimeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ft *FunnelTracker) cleanup(idleTimeout time.Duration) {
|
||||
ft.lock.Lock()
|
||||
defer ft.lock.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
for id, funnel := range ft.funnels {
|
||||
lastActive := funnel.LastActive()
|
||||
if now.After(lastActive.Add(idleTimeout)) {
|
||||
funnel.Close()
|
||||
delete(ft.funnels, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ft *FunnelTracker) Get(id FunnelID) (Funnel, bool) {
|
||||
ft.lock.RLock()
|
||||
defer ft.lock.RUnlock()
|
||||
funnel, ok := ft.funnels[id]
|
||||
return funnel, ok
|
||||
}
|
||||
|
||||
// Registers a funnel. It replaces the current funnel.
|
||||
func (ft *FunnelTracker) GetOrRegister(id FunnelID, newFunnelFunc func() (Funnel, error)) (funnel Funnel, new bool, err error) {
|
||||
ft.lock.Lock()
|
||||
defer ft.lock.Unlock()
|
||||
currentFunnel, exists := ft.funnels[id]
|
||||
if exists {
|
||||
return currentFunnel, false, nil
|
||||
}
|
||||
newFunnel, err := newFunnelFunc()
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
ft.funnels[id] = newFunnel
|
||||
return newFunnel, true, nil
|
||||
}
|
||||
|
||||
// Unregisters a funnel if the funnel equals to the current funnel
|
||||
func (ft *FunnelTracker) Unregister(id FunnelID, funnel Funnel) (deleted bool) {
|
||||
ft.lock.Lock()
|
||||
defer ft.lock.Unlock()
|
||||
currentFunnel, exists := ft.funnels[id]
|
||||
if !exists {
|
||||
return true
|
||||
}
|
||||
if currentFunnel.Equal(funnel) {
|
||||
currentFunnel.Close()
|
||||
delete(ft.funnels, id)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package packet
|
||||
|
||||
import "net/netip"
|
||||
|
||||
type mockFunnelUniPipe struct {
|
||||
uniPipe chan RawPacket
|
||||
}
|
||||
|
||||
func (mfui *mockFunnelUniPipe) SendPacket(dst netip.Addr, pk RawPacket) error {
|
||||
mfui.uniPipe <- pk
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mfui *mockFunnelUniPipe) Close() error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
|
||||
"github.com/google/gopacket"
|
||||
"github.com/google/gopacket/layers"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
)
|
||||
|
||||
const (
|
||||
ipv4MinHeaderLen = 20
|
||||
ipv6HeaderLen = 40
|
||||
ipv4MinMTU = 576
|
||||
ipv6MinMTU = 1280
|
||||
icmpHeaderLen = 8
|
||||
// https://www.rfc-editor.org/rfc/rfc792 and https://datatracker.ietf.org/doc/html/rfc4443#section-3.3 define 2 codes.
|
||||
// 0 = ttl exceed in transit, 1 = fragment reassembly time exceeded
|
||||
icmpTTLExceedInTransitCode = 0
|
||||
DefaultTTL uint8 = 255
|
||||
)
|
||||
|
||||
// Packet represents an IP packet or a packet that is encapsulated by IP
|
||||
type Packet interface {
|
||||
// IPLayer returns the IP of the packet
|
||||
IPLayer() *IP
|
||||
// EncodeLayers returns the layers that make up this packet. They can be passed to an Encoder to serialize into RawPacket
|
||||
EncodeLayers() ([]gopacket.SerializableLayer, error)
|
||||
}
|
||||
|
||||
// IP represents a generic IP packet. It can be embedded in more specific IP protocols
|
||||
type IP struct {
|
||||
Src netip.Addr
|
||||
Dst netip.Addr
|
||||
Protocol layers.IPProtocol
|
||||
TTL uint8
|
||||
}
|
||||
|
||||
func newIPv4(ipLayer *layers.IPv4) (*IP, error) {
|
||||
src, ok := netip.AddrFromSlice(ipLayer.SrcIP)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("cannot convert source IP %s to netip.Addr", ipLayer.SrcIP)
|
||||
}
|
||||
dst, ok := netip.AddrFromSlice(ipLayer.DstIP)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("cannot convert source IP %s to netip.Addr", ipLayer.DstIP)
|
||||
}
|
||||
return &IP{
|
||||
Src: src,
|
||||
Dst: dst,
|
||||
Protocol: ipLayer.Protocol,
|
||||
TTL: ipLayer.TTL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newIPv6(ipLayer *layers.IPv6) (*IP, error) {
|
||||
src, ok := netip.AddrFromSlice(ipLayer.SrcIP)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("cannot convert source IP %s to netip.Addr", ipLayer.SrcIP)
|
||||
}
|
||||
dst, ok := netip.AddrFromSlice(ipLayer.DstIP)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("cannot convert source IP %s to netip.Addr", ipLayer.DstIP)
|
||||
}
|
||||
return &IP{
|
||||
Src: src,
|
||||
Dst: dst,
|
||||
Protocol: ipLayer.NextHeader,
|
||||
TTL: ipLayer.HopLimit,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (ip *IP) IPLayer() *IP {
|
||||
return ip
|
||||
}
|
||||
|
||||
func (ip *IP) isIPv4() bool {
|
||||
return ip.Src.Is4()
|
||||
}
|
||||
|
||||
func (ip *IP) EncodeLayers() ([]gopacket.SerializableLayer, error) {
|
||||
if ip.isIPv4() {
|
||||
return []gopacket.SerializableLayer{
|
||||
&layers.IPv4{
|
||||
Version: 4,
|
||||
SrcIP: ip.Src.AsSlice(),
|
||||
DstIP: ip.Dst.AsSlice(),
|
||||
Protocol: layers.IPProtocol(ip.Protocol),
|
||||
TTL: ip.TTL,
|
||||
},
|
||||
}, nil
|
||||
} else {
|
||||
return []gopacket.SerializableLayer{
|
||||
&layers.IPv6{
|
||||
Version: 6,
|
||||
SrcIP: ip.Src.AsSlice(),
|
||||
DstIP: ip.Dst.AsSlice(),
|
||||
NextHeader: layers.IPProtocol(ip.Protocol),
|
||||
HopLimit: ip.TTL,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// ICMP represents is an IP packet + ICMP message
|
||||
type ICMP struct {
|
||||
*IP
|
||||
*icmp.Message
|
||||
}
|
||||
|
||||
func (i *ICMP) EncodeLayers() ([]gopacket.SerializableLayer, error) {
|
||||
ipLayers, err := i.IP.EncodeLayers()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg, err := i.Marshal(nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
icmpLayer := gopacket.Payload(msg)
|
||||
return append(ipLayers, icmpLayer), nil
|
||||
}
|
||||
|
||||
func NewICMPTTLExceedPacket(originalIP *IP, originalPacket RawPacket, routerIP netip.Addr) *ICMP {
|
||||
var (
|
||||
protocol layers.IPProtocol
|
||||
icmpType icmp.Type
|
||||
)
|
||||
if originalIP.Dst.Is4() {
|
||||
protocol = layers.IPProtocolICMPv4
|
||||
icmpType = ipv4.ICMPTypeTimeExceeded
|
||||
} else {
|
||||
protocol = layers.IPProtocolICMPv6
|
||||
icmpType = ipv6.ICMPTypeTimeExceeded
|
||||
}
|
||||
return &ICMP{
|
||||
IP: &IP{
|
||||
Src: routerIP,
|
||||
Dst: originalIP.Src,
|
||||
Protocol: protocol,
|
||||
TTL: DefaultTTL,
|
||||
},
|
||||
Message: &icmp.Message{
|
||||
Type: icmpType,
|
||||
Code: icmpTTLExceedInTransitCode,
|
||||
Body: &icmp.TimeExceeded{
|
||||
Data: originalDatagram(originalPacket, originalIP.Dst.Is4()),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// originalDatagram returns a slice of the original datagram for ICMP error messages
|
||||
// https://www.rfc-editor.org/rfc/rfc1812#section-4.3.2.3 suggests to copy as much without exceeding 576 bytes.
|
||||
// https://datatracker.ietf.org/doc/html/rfc4443#section-3.3 suggests to copy as much without exceeding 1280 bytes
|
||||
func originalDatagram(originalPacket RawPacket, isIPv4 bool) []byte {
|
||||
var upperBound int
|
||||
if isIPv4 {
|
||||
upperBound = ipv4MinMTU - ipv4MinHeaderLen - icmpHeaderLen
|
||||
if upperBound > len(originalPacket.Data) {
|
||||
upperBound = len(originalPacket.Data)
|
||||
}
|
||||
} else {
|
||||
upperBound = ipv6MinMTU - ipv6HeaderLen - icmpHeaderLen
|
||||
if upperBound > len(originalPacket.Data) {
|
||||
upperBound = len(originalPacket.Data)
|
||||
}
|
||||
}
|
||||
return originalPacket.Data[:upperBound]
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/netip"
|
||||
"testing"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
)
|
||||
|
||||
func TestNewICMPTTLExceedPacket(t *testing.T) {
|
||||
ipv4Packet := IP{
|
||||
Src: netip.MustParseAddr("192.168.1.1"),
|
||||
Dst: netip.MustParseAddr("10.0.0.1"),
|
||||
Protocol: layers.IPProtocolICMPv4,
|
||||
TTL: 0,
|
||||
}
|
||||
icmpV4Packet := ICMP{
|
||||
IP: &ipv4Packet,
|
||||
Message: &icmp.Message{
|
||||
Type: ipv4.ICMPTypeEcho,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: 25821,
|
||||
Seq: 58129,
|
||||
Data: []byte("test ttl=0"),
|
||||
},
|
||||
},
|
||||
}
|
||||
assertTTLExceedPacket(t, &icmpV4Packet)
|
||||
icmpV4Packet.Body = &icmp.Echo{
|
||||
ID: 3487,
|
||||
Seq: 19183,
|
||||
Data: make([]byte, ipv4MinMTU),
|
||||
}
|
||||
assertTTLExceedPacket(t, &icmpV4Packet)
|
||||
ipv6Packet := IP{
|
||||
Src: netip.MustParseAddr("fd51:2391:523:f4ee::1"),
|
||||
Dst: netip.MustParseAddr("fd51:2391:697:f4ee::2"),
|
||||
Protocol: layers.IPProtocolICMPv6,
|
||||
TTL: 0,
|
||||
}
|
||||
icmpV6Packet := ICMP{
|
||||
IP: &ipv6Packet,
|
||||
Message: &icmp.Message{
|
||||
Type: ipv6.ICMPTypeEchoRequest,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: 25821,
|
||||
Seq: 58129,
|
||||
Data: []byte("test ttl=0"),
|
||||
},
|
||||
},
|
||||
}
|
||||
assertTTLExceedPacket(t, &icmpV6Packet)
|
||||
icmpV6Packet.Body = &icmp.Echo{
|
||||
ID: 1497,
|
||||
Seq: 39284,
|
||||
Data: make([]byte, ipv6MinMTU),
|
||||
}
|
||||
assertTTLExceedPacket(t, &icmpV6Packet)
|
||||
}
|
||||
|
||||
func assertTTLExceedPacket(t *testing.T, pk *ICMP) {
|
||||
encoder := NewEncoder()
|
||||
rawPacket, err := encoder.Encode(pk)
|
||||
require.NoError(t, err)
|
||||
|
||||
minMTU := ipv4MinMTU
|
||||
headerLen := ipv4MinHeaderLen
|
||||
routerIP := netip.MustParseAddr("172.16.0.3")
|
||||
if pk.Dst.Is6() {
|
||||
minMTU = ipv6MinMTU
|
||||
headerLen = ipv6HeaderLen
|
||||
routerIP = netip.MustParseAddr("fd51:2391:697:f4ee::3")
|
||||
}
|
||||
|
||||
ttlExceedPacket := NewICMPTTLExceedPacket(pk.IP, rawPacket, routerIP)
|
||||
require.Equal(t, routerIP, ttlExceedPacket.Src)
|
||||
require.Equal(t, pk.Src, ttlExceedPacket.Dst)
|
||||
require.Equal(t, pk.Protocol, ttlExceedPacket.Protocol)
|
||||
require.Equal(t, DefaultTTL, ttlExceedPacket.TTL)
|
||||
|
||||
timeExceed, ok := ttlExceedPacket.Body.(*icmp.TimeExceeded)
|
||||
require.True(t, ok)
|
||||
if len(rawPacket.Data) > minMTU {
|
||||
require.True(t, bytes.Equal(timeExceed.Data, rawPacket.Data[:minMTU-headerLen-icmpHeaderLen]))
|
||||
} else {
|
||||
require.True(t, bytes.Equal(timeExceed.Data, rawPacket.Data))
|
||||
}
|
||||
|
||||
rawTTLExceedPacket, err := encoder.Encode(ttlExceedPacket)
|
||||
require.NoError(t, err)
|
||||
if len(rawPacket.Data) > minMTU {
|
||||
require.Len(t, rawTTLExceedPacket.Data, minMTU)
|
||||
} else {
|
||||
require.Len(t, rawTTLExceedPacket.Data, headerLen+icmpHeaderLen+len(rawPacket.Data))
|
||||
require.True(t, bytes.Equal(rawPacket.Data, rawTTLExceedPacket.Data[headerLen+icmpHeaderLen:]))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
var (
|
||||
// Source IP in documentation range to return ICMP error messages if we can't determine the IP of this machine
|
||||
icmpv4ErrFallbackSrc = netip.MustParseAddr("192.0.2.30")
|
||||
icmpv6ErrFallbackSrc = netip.MustParseAddr("2001:db8::")
|
||||
)
|
||||
|
||||
// ICMPRouter sends ICMP messages and listens for their responses
|
||||
type ICMPRouter interface {
|
||||
// Serve starts listening for responses to the requests until context is done
|
||||
Serve(ctx context.Context) error
|
||||
// Request sends an ICMP message
|
||||
Request(pk *ICMP, responder FunnelUniPipe) error
|
||||
}
|
||||
|
||||
// Upstream of raw packets
|
||||
type Upstream interface {
|
||||
// ReceivePacket waits for the next raw packet from upstream
|
||||
ReceivePacket(ctx context.Context) (RawPacket, error)
|
||||
}
|
||||
|
||||
type Router struct {
|
||||
upstream Upstream
|
||||
returnPipe FunnelUniPipe
|
||||
icmpProxy ICMPRouter
|
||||
ipv4Src netip.Addr
|
||||
ipv6Src netip.Addr
|
||||
logger *zerolog.Logger
|
||||
}
|
||||
|
||||
func NewRouter(upstream Upstream, returnPipe FunnelUniPipe, icmpProxy ICMPRouter, logger *zerolog.Logger) *Router {
|
||||
ipv4Src, err := findLocalAddr(net.ParseIP("1.1.1.1"), 53)
|
||||
if err != nil {
|
||||
logger.Warn().Err(err).Msgf("Failed to determine the IPv4 for this machine. It will use %s as source IP for error messages such as ICMP TTL exceed", icmpv4ErrFallbackSrc)
|
||||
ipv4Src = icmpv4ErrFallbackSrc
|
||||
}
|
||||
ipv6Src, err := findLocalAddr(net.ParseIP("2606:4700:4700::1111"), 53)
|
||||
if err != nil {
|
||||
logger.Warn().Err(err).Msgf("Failed to determine the IPv6 for this machine. It will use %s as source IP for error messages such as ICMP TTL exceed", icmpv6ErrFallbackSrc)
|
||||
ipv6Src = icmpv6ErrFallbackSrc
|
||||
}
|
||||
return &Router{
|
||||
upstream: upstream,
|
||||
returnPipe: returnPipe,
|
||||
icmpProxy: icmpProxy,
|
||||
ipv4Src: ipv4Src,
|
||||
ipv6Src: ipv6Src,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) Serve(ctx context.Context) error {
|
||||
icmpDecoder := NewICMPDecoder()
|
||||
encoder := NewEncoder()
|
||||
for {
|
||||
rawPacket, err := r.upstream.ReceivePacket(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
icmpPacket, err := icmpDecoder.Decode(rawPacket)
|
||||
if err != nil {
|
||||
r.logger.Err(err).Msg("Failed to decode ICMP packet from quic datagram")
|
||||
continue
|
||||
}
|
||||
|
||||
if icmpPacket.TTL <= 1 {
|
||||
if err := r.sendTTLExceedMsg(icmpPacket, rawPacket, encoder); err != nil {
|
||||
r.logger.Err(err).Msg("Failed to return ICMP TTL exceed error")
|
||||
}
|
||||
continue
|
||||
}
|
||||
icmpPacket.TTL--
|
||||
|
||||
if err := r.icmpProxy.Request(icmpPacket, r.returnPipe); err != nil {
|
||||
r.logger.Err(err).
|
||||
Str("src", icmpPacket.Src.String()).
|
||||
Str("dst", icmpPacket.Dst.String()).
|
||||
Interface("type", icmpPacket.Type).
|
||||
Msg("Failed to send ICMP packet")
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) sendTTLExceedMsg(pk *ICMP, rawPacket RawPacket, encoder *Encoder) error {
|
||||
var srcIP netip.Addr
|
||||
if pk.Dst.Is4() {
|
||||
srcIP = r.ipv4Src
|
||||
} else {
|
||||
srcIP = r.ipv6Src
|
||||
}
|
||||
ttlExceedPacket := NewICMPTTLExceedPacket(pk.IP, rawPacket, srcIP)
|
||||
|
||||
encodedTTLExceed, err := encoder.Encode(ttlExceedPacket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.returnPipe.SendPacket(pk.Src, encodedTTLExceed)
|
||||
}
|
||||
|
||||
// findLocalAddr tries to dial UDP and returns the local address picked by the OS
|
||||
func findLocalAddr(dst net.IP, port int) (netip.Addr, error) {
|
||||
udpConn, err := net.DialUDP("udp", nil, &net.UDPAddr{
|
||||
IP: dst,
|
||||
Port: port,
|
||||
})
|
||||
if err != nil {
|
||||
return netip.Addr{}, err
|
||||
}
|
||||
defer udpConn.Close()
|
||||
localAddrPort, err := netip.ParseAddrPort(udpConn.LocalAddr().String())
|
||||
if err != nil {
|
||||
return netip.Addr{}, err
|
||||
}
|
||||
localAddr := localAddrPort.Addr()
|
||||
return localAddr, nil
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package packet
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"testing"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/net/ipv6"
|
||||
)
|
||||
|
||||
var (
|
||||
noopLogger = zerolog.Nop()
|
||||
)
|
||||
|
||||
func TestRouterReturnTTLExceed(t *testing.T) {
|
||||
upstream := &mockUpstream{
|
||||
source: make(chan RawPacket),
|
||||
}
|
||||
returnPipe := &mockFunnelUniPipe{
|
||||
uniPipe: make(chan RawPacket),
|
||||
}
|
||||
router := NewRouter(upstream, returnPipe, &mockICMPRouter{}, &noopLogger)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
routerStopped := make(chan struct{})
|
||||
go func() {
|
||||
router.Serve(ctx)
|
||||
close(routerStopped)
|
||||
}()
|
||||
|
||||
pk := ICMP{
|
||||
IP: &IP{
|
||||
Src: netip.MustParseAddr("192.168.1.1"),
|
||||
Dst: netip.MustParseAddr("10.0.0.1"),
|
||||
Protocol: layers.IPProtocolICMPv4,
|
||||
TTL: 1,
|
||||
},
|
||||
Message: &icmp.Message{
|
||||
Type: ipv4.ICMPTypeEcho,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: 12481,
|
||||
Seq: 8036,
|
||||
Data: []byte("TTL exceed"),
|
||||
},
|
||||
},
|
||||
}
|
||||
assertTTLExceed(t, &pk, router.ipv4Src, upstream, returnPipe)
|
||||
pk = ICMP{
|
||||
IP: &IP{
|
||||
Src: netip.MustParseAddr("fd51:2391:523:f4ee::1"),
|
||||
Dst: netip.MustParseAddr("fd51:2391:697:f4ee::2"),
|
||||
Protocol: layers.IPProtocolICMPv6,
|
||||
TTL: 1,
|
||||
},
|
||||
Message: &icmp.Message{
|
||||
Type: ipv6.ICMPTypeEchoRequest,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: 42583,
|
||||
Seq: 7039,
|
||||
Data: []byte("TTL exceed"),
|
||||
},
|
||||
},
|
||||
}
|
||||
assertTTLExceed(t, &pk, router.ipv6Src, upstream, returnPipe)
|
||||
|
||||
cancel()
|
||||
<-routerStopped
|
||||
}
|
||||
|
||||
func assertTTLExceed(t *testing.T, originalPacket *ICMP, expectedSrc netip.Addr, upstream *mockUpstream, returnPipe *mockFunnelUniPipe) {
|
||||
encoder := NewEncoder()
|
||||
rawPacket, err := encoder.Encode(originalPacket)
|
||||
require.NoError(t, err)
|
||||
|
||||
upstream.source <- rawPacket
|
||||
resp := <-returnPipe.uniPipe
|
||||
decoder := NewICMPDecoder()
|
||||
decoded, err := decoder.Decode(resp)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, expectedSrc, decoded.Src)
|
||||
require.Equal(t, originalPacket.Src, decoded.Dst)
|
||||
require.Equal(t, originalPacket.Protocol, decoded.Protocol)
|
||||
require.Equal(t, DefaultTTL, decoded.TTL)
|
||||
if originalPacket.Dst.Is4() {
|
||||
require.Equal(t, ipv4.ICMPTypeTimeExceeded, decoded.Type)
|
||||
} else {
|
||||
require.Equal(t, ipv6.ICMPTypeTimeExceeded, decoded.Type)
|
||||
}
|
||||
require.Equal(t, 0, decoded.Code)
|
||||
timeExceed, ok := decoded.Body.(*icmp.TimeExceeded)
|
||||
require.True(t, ok)
|
||||
require.True(t, bytes.Equal(rawPacket.Data, timeExceed.Data))
|
||||
}
|
||||
|
||||
type mockUpstream struct {
|
||||
source chan RawPacket
|
||||
}
|
||||
|
||||
func (ms *mockUpstream) ReceivePacket(ctx context.Context) (RawPacket, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return RawPacket{}, ctx.Err()
|
||||
case pk := <-ms.source:
|
||||
return pk, nil
|
||||
}
|
||||
}
|
||||
|
||||
type mockICMPRouter struct{}
|
||||
|
||||
func (mir mockICMPRouter) Serve(ctx context.Context) error {
|
||||
return fmt.Errorf("Serve not implemented by mockICMPRouter")
|
||||
}
|
||||
|
||||
func (mir mockICMPRouter) Request(pk *ICMP, responder FunnelUniPipe) error {
|
||||
return fmt.Errorf("Request not implemented by mockICMPRouter")
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package packet
|
||||
|
||||
import "github.com/google/uuid"
|
||||
|
||||
type Session struct {
|
||||
ID uuid.UUID
|
||||
Payload []byte
|
||||
}
|
||||
+34
-38
@@ -1,7 +1,6 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -29,6 +28,8 @@ const (
|
||||
LogFieldRule = "ingressRule"
|
||||
LogFieldOriginService = "originService"
|
||||
LogFieldFlowID = "flowID"
|
||||
|
||||
trailerHeaderName = "Trailer"
|
||||
)
|
||||
|
||||
// Proxy represents a means to Proxy between cloudflared and the origin services.
|
||||
@@ -63,7 +64,7 @@ func NewOriginProxy(
|
||||
// a simple roundtrip or a tcp/websocket dial depending on ingres rule setup.
|
||||
func (p *Proxy) ProxyHTTP(
|
||||
w connection.ResponseWriter,
|
||||
tr *tracing.TracedRequest,
|
||||
tr *tracing.TracedHTTPRequest,
|
||||
isWebsocket bool,
|
||||
) error {
|
||||
incrementRequests()
|
||||
@@ -108,7 +109,7 @@ func (p *Proxy) ProxyHTTP(
|
||||
}
|
||||
|
||||
rws := connection.NewHTTPResponseReadWriterAcker(w, req)
|
||||
if err := p.proxyStream(req.Context(), rws, dest, originProxy); err != nil {
|
||||
if err := p.proxyStream(tr.ToTracedContext(), rws, dest, originProxy); err != nil {
|
||||
rule, srv := ruleField(p.ingressRules, ruleNum)
|
||||
p.logRequestError(err, cfRay, "", rule, srv)
|
||||
return err
|
||||
@@ -137,9 +138,11 @@ func (p *Proxy) ProxyTCP(
|
||||
serveCtx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
tracedCtx := tracing.NewTracedContext(serveCtx, req.CfTraceID, p.log)
|
||||
|
||||
p.log.Debug().Str(LogFieldFlowID, req.FlowID).Msg("tcp proxy stream started")
|
||||
|
||||
if err := p.proxyStream(serveCtx, rwa, req.Dest, p.warpRouting.Proxy); err != nil {
|
||||
if err := p.proxyStream(tracedCtx, rwa, req.Dest, p.warpRouting.Proxy); err != nil {
|
||||
p.logRequestError(err, req.CFRay, req.FlowID, "", ingress.ServiceWarpRouting)
|
||||
return err
|
||||
}
|
||||
@@ -160,7 +163,7 @@ func ruleField(ing ingress.Ingress, ruleNum int) (ruleID string, srv string) {
|
||||
// ProxyHTTPRequest proxies requests of underlying type http and websocket to the origin service.
|
||||
func (p *Proxy) proxyHTTPRequest(
|
||||
w connection.ResponseWriter,
|
||||
tr *tracing.TracedRequest,
|
||||
tr *tracing.TracedHTTPRequest,
|
||||
httpService ingress.HTTPOriginProxy,
|
||||
isWebsocket bool,
|
||||
disableChunkedEncoding bool,
|
||||
@@ -205,15 +208,16 @@ func (p *Proxy) proxyHTTPRequest(
|
||||
tracing.EndWithStatusCode(ttfbSpan, resp.StatusCode)
|
||||
defer resp.Body.Close()
|
||||
|
||||
// resp headers can be nil
|
||||
if resp.Header == nil {
|
||||
resp.Header = make(http.Header)
|
||||
headers := make(http.Header, len(resp.Header))
|
||||
// copy headers
|
||||
for k, v := range resp.Header {
|
||||
headers[k] = v
|
||||
}
|
||||
|
||||
// Add spans to response header (if available)
|
||||
tr.AddSpans(resp.Header, p.log)
|
||||
tr.AddSpans(headers)
|
||||
|
||||
err = w.WriteRespHeaders(resp.StatusCode, resp.Header)
|
||||
err = w.WriteRespHeaders(resp.StatusCode, headers)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Error writing response header")
|
||||
}
|
||||
@@ -234,12 +238,10 @@ func (p *Proxy) proxyHTTPRequest(
|
||||
return nil
|
||||
}
|
||||
|
||||
if connection.IsServerSentEvent(resp.Header) {
|
||||
p.log.Debug().Msg("Detected Server-Side Events from Origin")
|
||||
p.writeEventStream(w, resp.Body)
|
||||
} else {
|
||||
_, _ = cfio.Copy(w, resp.Body)
|
||||
}
|
||||
_, _ = cfio.Copy(w, resp.Body)
|
||||
|
||||
// copy trailers
|
||||
copyTrailers(w, resp)
|
||||
|
||||
p.logOriginResponse(resp, fields)
|
||||
return nil
|
||||
@@ -248,17 +250,23 @@ func (p *Proxy) proxyHTTPRequest(
|
||||
// proxyStream proxies type TCP and other underlying types if the connection is defined as a stream oriented
|
||||
// ingress rule.
|
||||
func (p *Proxy) proxyStream(
|
||||
ctx context.Context,
|
||||
tr *tracing.TracedContext,
|
||||
rwa connection.ReadWriteAcker,
|
||||
dest string,
|
||||
connectionProxy ingress.StreamBasedOriginProxy,
|
||||
) error {
|
||||
ctx := tr.Context
|
||||
_, connectSpan := tr.Tracer().Start(ctx, "stream-connect")
|
||||
originConn, err := connectionProxy.EstablishConnection(ctx, dest)
|
||||
if err != nil {
|
||||
tracing.EndWithErrorStatus(connectSpan, err)
|
||||
return err
|
||||
}
|
||||
connectSpan.End()
|
||||
|
||||
if err := rwa.AckConnection(); err != nil {
|
||||
encodedSpans := tr.GetSpans()
|
||||
|
||||
if err := rwa.AckConnection(encodedSpans); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -288,26 +296,6 @@ func (wr *bidirectionalStream) Write(p []byte) (n int, err error) {
|
||||
return wr.writer.Write(p)
|
||||
}
|
||||
|
||||
func (p *Proxy) writeEventStream(w connection.ResponseWriter, respBody io.ReadCloser) {
|
||||
reader := bufio.NewReader(respBody)
|
||||
for {
|
||||
line, readErr := reader.ReadBytes('\n')
|
||||
|
||||
// We first try to write whatever we read even if an error occurred
|
||||
// The reason for doing it is to guarantee we really push everything to the eyeball side
|
||||
// before returning
|
||||
if len(line) > 0 {
|
||||
if _, writeErr := w.Write(line); writeErr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if readErr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Proxy) appendTagHeaders(r *http.Request) {
|
||||
for _, tag := range p.tags {
|
||||
r.Header.Add(TagHeaderNamePrefix+tag.Name, tag.Value)
|
||||
@@ -321,6 +309,14 @@ type logFields struct {
|
||||
flowID string
|
||||
}
|
||||
|
||||
func copyTrailers(w connection.ResponseWriter, response *http.Response) {
|
||||
for trailerHeader, trailerValues := range response.Trailer {
|
||||
for _, trailerValue := range trailerValues {
|
||||
w.AddTrailer(trailerHeader, trailerValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Proxy) logRequest(r *http.Request, fields logFields) {
|
||||
if fields.cfRay != "" {
|
||||
p.log.Debug().Msgf("CF-RAY: %s %s %s %s", fields.cfRay, r.Method, r.URL, r.Proto)
|
||||
|
||||
+42
-21
@@ -22,6 +22,8 @@ import (
|
||||
"github.com/urfave/cli/v2"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/cloudflare/cloudflared/cfio"
|
||||
|
||||
"github.com/cloudflare/cloudflared/config"
|
||||
"github.com/cloudflare/cloudflared/connection"
|
||||
"github.com/cloudflare/cloudflared/hello"
|
||||
@@ -62,6 +64,10 @@ func (w *mockHTTPRespWriter) WriteRespHeaders(status int, header http.Header) er
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *mockHTTPRespWriter) AddTrailer(trailerName, trailerValue string) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
func (w *mockHTTPRespWriter) Read(data []byte) (int, error) {
|
||||
return 0, fmt.Errorf("mockHTTPRespWriter doesn't implement io.Reader")
|
||||
}
|
||||
@@ -117,10 +123,17 @@ func newMockSSERespWriter() *mockSSERespWriter {
|
||||
}
|
||||
|
||||
func (w *mockSSERespWriter) Write(data []byte) (int, error) {
|
||||
w.writeNotification <- data
|
||||
newData := make([]byte, len(data))
|
||||
copy(newData, data)
|
||||
|
||||
w.writeNotification <- newData
|
||||
return len(data), nil
|
||||
}
|
||||
|
||||
func (w *mockSSERespWriter) WriteString(str string) (int, error) {
|
||||
return w.Write([]byte(str))
|
||||
}
|
||||
|
||||
func (w *mockSSERespWriter) ReadBytes() []byte {
|
||||
return <-w.writeNotification
|
||||
}
|
||||
@@ -147,7 +160,6 @@ func TestProxySingleOrigin(t *testing.T) {
|
||||
t.Run("testProxyHTTP", testProxyHTTP(proxy))
|
||||
t.Run("testProxyWebsocket", testProxyWebsocket(proxy))
|
||||
t.Run("testProxySSE", testProxySSE(proxy))
|
||||
t.Run("testProxySSEAllData", testProxySSEAllData(proxy))
|
||||
cancel()
|
||||
}
|
||||
|
||||
@@ -157,7 +169,8 @@ func testProxyHTTP(proxy connection.OriginProxy) func(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodGet, "http://localhost:8080", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = proxy.ProxyHTTP(responseWriter, tracing.NewTracedRequest(req), false)
|
||||
log := zerolog.Nop()
|
||||
err = proxy.ProxyHTTP(responseWriter, tracing.NewTracedHTTPRequest(req, &log), false)
|
||||
require.NoError(t, err)
|
||||
for _, tag := range testTags {
|
||||
assert.Equal(t, tag.Value, req.Header.Get(TagHeaderNamePrefix+tag.Name))
|
||||
@@ -184,7 +197,8 @@ func testProxyWebsocket(proxy connection.OriginProxy) func(t *testing.T) {
|
||||
|
||||
errGroup, ctx := errgroup.WithContext(ctx)
|
||||
errGroup.Go(func() error {
|
||||
err = proxy.ProxyHTTP(responseWriter, tracing.NewTracedRequest(req), true)
|
||||
log := zerolog.Nop()
|
||||
err = proxy.ProxyHTTP(responseWriter, tracing.NewTracedHTTPRequest(req, &log), true)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, http.StatusSwitchingProtocols, responseWriter.Code)
|
||||
@@ -245,7 +259,8 @@ func testProxySSE(proxy connection.OriginProxy) func(t *testing.T) {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
err = proxy.ProxyHTTP(responseWriter, tracing.NewTracedRequest(req), false)
|
||||
log := zerolog.Nop()
|
||||
err = proxy.ProxyHTTP(responseWriter, tracing.NewTracedHTTPRequest(req, &log), false)
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, http.StatusOK, responseWriter.Code)
|
||||
@@ -253,11 +268,8 @@ func testProxySSE(proxy connection.OriginProxy) func(t *testing.T) {
|
||||
|
||||
for i := 0; i < pushCount; i++ {
|
||||
line := responseWriter.ReadBytes()
|
||||
expect := fmt.Sprintf("%d\n", i)
|
||||
expect := fmt.Sprintf("%d\n\n", i)
|
||||
require.Equal(t, []byte(expect), line, fmt.Sprintf("Expect to read %v, got %v", expect, line))
|
||||
|
||||
line = responseWriter.ReadBytes()
|
||||
require.Equal(t, []byte("\n"), line, fmt.Sprintf("Expect to read '\n', got %v", line))
|
||||
}
|
||||
|
||||
cancel()
|
||||
@@ -267,17 +279,15 @@ func testProxySSE(proxy connection.OriginProxy) func(t *testing.T) {
|
||||
|
||||
// Regression test to guarantee that we always write the contents downstream even if EOF is reached without
|
||||
// hitting the delimiter
|
||||
func testProxySSEAllData(proxy *Proxy) func(t *testing.T) {
|
||||
return func(t *testing.T) {
|
||||
eyeballReader := io.NopCloser(strings.NewReader("data\r\r"))
|
||||
responseWriter := newMockSSERespWriter()
|
||||
func TestProxySSEAllData(t *testing.T) {
|
||||
eyeballReader := io.NopCloser(strings.NewReader("data\r\r"))
|
||||
responseWriter := newMockSSERespWriter()
|
||||
|
||||
// responseWriter uses an unbuffered channel, so we call in a different go-routine
|
||||
go proxy.writeEventStream(responseWriter, eyeballReader)
|
||||
// responseWriter uses an unbuffered channel, so we call in a different go-routine
|
||||
go cfio.Copy(responseWriter, eyeballReader)
|
||||
|
||||
result := string(<-responseWriter.writeNotification)
|
||||
require.Equal(t, "data\r\r", result)
|
||||
}
|
||||
result := string(<-responseWriter.writeNotification)
|
||||
require.Equal(t, "data\r\r", result)
|
||||
}
|
||||
|
||||
func TestProxyMultipleOrigins(t *testing.T) {
|
||||
@@ -357,7 +367,7 @@ func runIngressTestScenarios(t *testing.T, unvalidatedIngress []config.Unvalidat
|
||||
req, err := http.NewRequest(http.MethodGet, test.url, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = proxy.ProxyHTTP(responseWriter, tracing.NewTracedRequest(req), false)
|
||||
err = proxy.ProxyHTTP(responseWriter, tracing.NewTracedHTTPRequest(req, &log), false)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, test.expectedStatus, responseWriter.Code)
|
||||
@@ -404,7 +414,7 @@ func TestProxyError(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1", nil)
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Error(t, proxy.ProxyHTTP(responseWriter, tracing.NewTracedRequest(req), false))
|
||||
assert.Error(t, proxy.ProxyHTTP(responseWriter, tracing.NewTracedHTTPRequest(req, &log), false))
|
||||
}
|
||||
|
||||
type replayer struct {
|
||||
@@ -522,6 +532,7 @@ func TestConnections(t *testing.T) {
|
||||
},
|
||||
want: want{
|
||||
message: []byte("echo-test2"),
|
||||
headers: http.Header{},
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -541,6 +552,7 @@ func TestConnections(t *testing.T) {
|
||||
message: []byte("echo-test3"),
|
||||
// We expect no headers here because they are sent back via
|
||||
// the stream.
|
||||
headers: http.Header{},
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -682,7 +694,8 @@ func TestConnections(t *testing.T) {
|
||||
rwa := connection.NewHTTPResponseReadWriterAcker(respWriter, req)
|
||||
err = proxy.ProxyTCP(ctx, rwa, &connection.TCPRequest{Dest: dest})
|
||||
} else {
|
||||
err = proxy.ProxyHTTP(respWriter, tracing.NewTracedRequest(req), test.args.connectionType == connection.TypeWebsocket)
|
||||
log := zerolog.Nop()
|
||||
err = proxy.ProxyHTTP(respWriter, tracing.NewTracedHTTPRequest(req, &log), test.args.connectionType == connection.TypeWebsocket)
|
||||
}
|
||||
|
||||
cancel()
|
||||
@@ -819,6 +832,10 @@ func (w *wsRespWriter) WriteRespHeaders(status int, header http.Header) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *wsRespWriter) AddTrailer(trailerName, trailerValue string) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
// respHeaders is a test function to read respHeaders
|
||||
func (w *wsRespWriter) headers() http.Header {
|
||||
// Removing indeterminstic header because it cannot be asserted.
|
||||
@@ -846,6 +863,10 @@ func (m *mockTCPRespWriter) Write(p []byte) (n int, err error) {
|
||||
return m.w.Write(p)
|
||||
}
|
||||
|
||||
func (w *mockTCPRespWriter) AddTrailer(trailerName, trailerValue string) {
|
||||
// do nothing
|
||||
}
|
||||
|
||||
func (m *mockTCPRespWriter) WriteRespHeaders(status int, header http.Header) error {
|
||||
m.responseHeaders = header
|
||||
m.code = status
|
||||
|
||||
+61
-29
@@ -1,65 +1,97 @@
|
||||
package quic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/lucas-clemente/quic-go"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
const (
|
||||
sessionIDLen = len(uuid.UUID{})
|
||||
)
|
||||
|
||||
type BaseDatagramMuxer interface {
|
||||
// SendToSession suffix the session ID to the payload so the other end of the QUIC connection can demultiplex the
|
||||
// payload from multiple datagram sessions.
|
||||
SendToSession(session *packet.Session) error
|
||||
// ServeReceive starts a loop to receive datagrams from the QUIC connection
|
||||
ServeReceive(ctx context.Context) error
|
||||
}
|
||||
|
||||
type DatagramMuxer struct {
|
||||
session quic.Connection
|
||||
logger *zerolog.Logger
|
||||
session quic.Connection
|
||||
logger *zerolog.Logger
|
||||
demuxChan chan<- *packet.Session
|
||||
}
|
||||
|
||||
func NewDatagramMuxer(quicSession quic.Connection, logger *zerolog.Logger) (*DatagramMuxer, error) {
|
||||
func NewDatagramMuxer(quicSession quic.Connection, log *zerolog.Logger, demuxChan chan<- *packet.Session) *DatagramMuxer {
|
||||
logger := log.With().Uint8("datagramVersion", 1).Logger()
|
||||
return &DatagramMuxer{
|
||||
session: quicSession,
|
||||
logger: logger,
|
||||
}, nil
|
||||
session: quicSession,
|
||||
logger: &logger,
|
||||
demuxChan: demuxChan,
|
||||
}
|
||||
}
|
||||
|
||||
// SendTo suffix the session ID to the payload so the other end of the QUIC session can demultiplex
|
||||
// the payload from multiple datagram sessions
|
||||
func (dm *DatagramMuxer) SendTo(sessionID uuid.UUID, payload []byte) error {
|
||||
if len(payload) > maxDatagramPayloadSize {
|
||||
// TODO: TUN-5302 return ICMP packet too big message
|
||||
return fmt.Errorf("origin UDP payload has %d bytes, which exceeds transport MTU %d", len(payload), dm.MTU())
|
||||
// Maximum application payload to send to / receive from QUIC datagram frame
|
||||
func (dm *DatagramMuxer) mtu() int {
|
||||
return maxDatagramPayloadSize
|
||||
}
|
||||
|
||||
func (dm *DatagramMuxer) SendToSession(session *packet.Session) error {
|
||||
if len(session.Payload) > dm.mtu() {
|
||||
packetTooBigDropped.Inc()
|
||||
return fmt.Errorf("origin UDP payload has %d bytes, which exceeds transport MTU %d", len(session.Payload), dm.mtu())
|
||||
}
|
||||
msgWithID, err := suffixSessionID(sessionID, payload)
|
||||
payloadWithMetadata, err := suffixSessionID(session.ID, session.Payload)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to suffix session ID to datagram, it will be dropped")
|
||||
}
|
||||
if err := dm.session.SendMessage(msgWithID); err != nil {
|
||||
if err := dm.session.SendMessage(payloadWithMetadata); err != nil {
|
||||
return errors.Wrap(err, "Failed to send datagram back to edge")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReceiveFrom extracts datagram session ID, then sends the session ID and payload to session manager
|
||||
// which determines how to proxy to the origin. It assumes the datagram session has already been
|
||||
// registered with session manager through other side channel
|
||||
func (dm *DatagramMuxer) ReceiveFrom() (uuid.UUID, []byte, error) {
|
||||
msg, err := dm.session.ReceiveMessage()
|
||||
if err != nil {
|
||||
return uuid.Nil, nil, err
|
||||
func (dm *DatagramMuxer) ServeReceive(ctx context.Context) error {
|
||||
for {
|
||||
// Extracts datagram session ID, then sends the session ID and payload to receiver
|
||||
// which determines how to proxy to the origin. It assumes the datagram session has already been
|
||||
// registered with receiver through other side channel
|
||||
msg, err := dm.session.ReceiveMessage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := dm.demux(ctx, msg); err != nil {
|
||||
dm.logger.Error().Err(err).Msg("Failed to demux datagram")
|
||||
if err == context.Canceled {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
sessionID, payload, err := extractSessionID(msg)
|
||||
if err != nil {
|
||||
return uuid.Nil, nil, err
|
||||
}
|
||||
return sessionID, payload, nil
|
||||
}
|
||||
|
||||
// Maximum application payload to send to / receive from QUIC datagram frame
|
||||
func (dm *DatagramMuxer) MTU() int {
|
||||
return maxDatagramPayloadSize
|
||||
func (dm *DatagramMuxer) demux(ctx context.Context, msg []byte) error {
|
||||
sessionID, payload, err := extractSessionID(msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sessionDatagram := packet.Session{
|
||||
ID: sessionID,
|
||||
Payload: payload,
|
||||
}
|
||||
select {
|
||||
case dm.demuxChan <- &sessionDatagram:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// Each QUIC datagram should be suffixed with session ID.
|
||||
|
||||
+121
-26
@@ -1,22 +1,28 @@
|
||||
package quic
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/gopacket/layers"
|
||||
"github.com/google/uuid"
|
||||
"github.com/lucas-clemente/quic-go"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/net/icmp"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -52,9 +58,59 @@ func TestSuffixSessionIDError(t *testing.T) {
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestMaxDatagramPayload(t *testing.T) {
|
||||
payload := make([]byte, maxDatagramPayloadSize)
|
||||
func TestDatagram(t *testing.T) {
|
||||
maxPayload := make([]byte, maxDatagramPayloadSize)
|
||||
noPayloadSession := uuid.New()
|
||||
maxPayloadSession := uuid.New()
|
||||
sessionToPayload := []*packet.Session{
|
||||
{
|
||||
ID: noPayloadSession,
|
||||
Payload: make([]byte, 0),
|
||||
},
|
||||
{
|
||||
ID: maxPayloadSession,
|
||||
Payload: maxPayload,
|
||||
},
|
||||
}
|
||||
|
||||
packets := []packet.ICMP{
|
||||
{
|
||||
IP: &packet.IP{
|
||||
Src: netip.MustParseAddr("172.16.0.1"),
|
||||
Dst: netip.MustParseAddr("192.168.0.1"),
|
||||
Protocol: layers.IPProtocolICMPv4,
|
||||
},
|
||||
Message: &icmp.Message{
|
||||
Type: ipv4.ICMPTypeTimeExceeded,
|
||||
Code: 0,
|
||||
Body: &icmp.TimeExceeded{
|
||||
Data: []byte("original packet"),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
IP: &packet.IP{
|
||||
Src: netip.MustParseAddr("172.16.0.2"),
|
||||
Dst: netip.MustParseAddr("192.168.0.2"),
|
||||
Protocol: layers.IPProtocolICMPv4,
|
||||
},
|
||||
Message: &icmp.Message{
|
||||
Type: ipv4.ICMPTypeEcho,
|
||||
Code: 0,
|
||||
Body: &icmp.Echo{
|
||||
ID: 6182,
|
||||
Seq: 9151,
|
||||
Data: []byte("Test ICMP echo"),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
testDatagram(t, 1, sessionToPayload, nil)
|
||||
testDatagram(t, 2, sessionToPayload, packets)
|
||||
}
|
||||
|
||||
func testDatagram(t *testing.T, version uint8, sessionToPayloads []*packet.Session, packets []packet.ICMP) {
|
||||
quicConfig := &quic.Config{
|
||||
KeepAlivePeriod: 5 * time.Millisecond,
|
||||
EnableDatagrams: true,
|
||||
@@ -63,6 +119,8 @@ func TestMaxDatagramPayload(t *testing.T) {
|
||||
quicListener := newQUICListener(t, quicConfig)
|
||||
defer quicListener.Close()
|
||||
|
||||
logger := zerolog.Nop()
|
||||
|
||||
errGroup, ctx := errgroup.WithContext(context.Background())
|
||||
// Run edge side of datagram muxer
|
||||
errGroup.Go(func() error {
|
||||
@@ -72,22 +130,40 @@ func TestMaxDatagramPayload(t *testing.T) {
|
||||
return err
|
||||
}
|
||||
|
||||
logger := zerolog.Nop()
|
||||
muxer, err := NewDatagramMuxer(quicSession, &logger)
|
||||
if err != nil {
|
||||
return err
|
||||
sessionDemuxChan := make(chan *packet.Session, 16)
|
||||
|
||||
switch version {
|
||||
case 1:
|
||||
muxer := NewDatagramMuxer(quicSession, &logger, sessionDemuxChan)
|
||||
muxer.ServeReceive(ctx)
|
||||
case 2:
|
||||
muxer := NewDatagramMuxerV2(quicSession, &logger, sessionDemuxChan)
|
||||
muxer.ServeReceive(ctx)
|
||||
|
||||
icmpDecoder := packet.NewICMPDecoder()
|
||||
for _, pk := range packets {
|
||||
received, err := muxer.ReceivePacket(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
receivedICMP, err := icmpDecoder.Decode(received)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, pk.IP, receivedICMP.IP)
|
||||
require.Equal(t, pk.Type, receivedICMP.Type)
|
||||
require.Equal(t, pk.Code, receivedICMP.Code)
|
||||
require.Equal(t, pk.Body, receivedICMP.Body)
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown datagram version %d", version)
|
||||
}
|
||||
|
||||
sessionID, receivedPayload, err := muxer.ReceiveFrom()
|
||||
if err != nil {
|
||||
return err
|
||||
for _, expectedPayload := range sessionToPayloads {
|
||||
actualPayload := <-sessionDemuxChan
|
||||
require.Equal(t, expectedPayload, actualPayload)
|
||||
}
|
||||
require.Equal(t, testSessionID, sessionID)
|
||||
require.True(t, bytes.Equal(payload, receivedPayload))
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
largePayload := make([]byte, MaxDatagramFrameSize)
|
||||
// Run cloudflared side of datagram muxer
|
||||
errGroup.Go(func() error {
|
||||
tlsClientConfig := &tls.Config{
|
||||
@@ -97,24 +173,43 @@ func TestMaxDatagramPayload(t *testing.T) {
|
||||
// Establish quic connection
|
||||
quicSession, err := quic.DialAddrEarly(quicListener.Addr().String(), tlsClientConfig, quicConfig)
|
||||
require.NoError(t, err)
|
||||
|
||||
logger := zerolog.Nop()
|
||||
muxer, err := NewDatagramMuxer(quicSession, &logger)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer quicSession.CloseWithError(0, "")
|
||||
|
||||
// Wait a few milliseconds for MTU discovery to take place
|
||||
time.Sleep(time.Millisecond * 100)
|
||||
err = muxer.SendTo(testSessionID, payload)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
var muxer BaseDatagramMuxer
|
||||
switch version {
|
||||
case 1:
|
||||
muxer = NewDatagramMuxer(quicSession, &logger, nil)
|
||||
case 2:
|
||||
muxerV2 := NewDatagramMuxerV2(quicSession, &logger, nil)
|
||||
encoder := packet.NewEncoder()
|
||||
for _, pk := range packets {
|
||||
encodedPacket, err := encoder.Encode(&pk)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, muxerV2.SendPacket(encodedPacket))
|
||||
}
|
||||
// Payload larger than transport MTU, should not be sent
|
||||
require.Error(t, muxerV2.SendPacket(packet.RawPacket{
|
||||
Data: largePayload,
|
||||
}))
|
||||
muxer = muxerV2
|
||||
default:
|
||||
return fmt.Errorf("unknown datagram version %d", version)
|
||||
}
|
||||
|
||||
// Payload larger than transport MTU, should return an error
|
||||
largePayload := make([]byte, MaxDatagramFrameSize)
|
||||
err = muxer.SendTo(testSessionID, largePayload)
|
||||
require.Error(t, err)
|
||||
for _, session := range sessionToPayloads {
|
||||
require.NoError(t, muxer.SendToSession(session))
|
||||
}
|
||||
// Payload larger than transport MTU, should not be sent
|
||||
require.Error(t, muxer.SendToSession(&packet.Session{
|
||||
ID: testSessionID,
|
||||
Payload: largePayload,
|
||||
}))
|
||||
|
||||
// Wait for edge to finish receiving the messages
|
||||
time.Sleep(time.Millisecond * 100)
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package quic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/lucas-clemente/quic-go"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/rs/zerolog"
|
||||
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
)
|
||||
|
||||
type datagramV2Type byte
|
||||
|
||||
const (
|
||||
udp datagramV2Type = iota
|
||||
ip
|
||||
)
|
||||
|
||||
const (
|
||||
typeIDLen = 1
|
||||
// Same as sessionDemuxChan capacity
|
||||
packetChanCapacity = 128
|
||||
)
|
||||
|
||||
func suffixType(b []byte, datagramType datagramV2Type) ([]byte, error) {
|
||||
if len(b)+typeIDLen > MaxDatagramFrameSize {
|
||||
return nil, fmt.Errorf("datagram size %d exceeds max frame size %d", len(b), MaxDatagramFrameSize)
|
||||
}
|
||||
b = append(b, byte(datagramType))
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// Maximum application payload to send to / receive from QUIC datagram frame
|
||||
func (dm *DatagramMuxerV2) mtu() int {
|
||||
return maxDatagramPayloadSize
|
||||
}
|
||||
|
||||
type DatagramMuxerV2 struct {
|
||||
session quic.Connection
|
||||
logger *zerolog.Logger
|
||||
sessionDemuxChan chan<- *packet.Session
|
||||
packetDemuxChan chan packet.RawPacket
|
||||
}
|
||||
|
||||
func NewDatagramMuxerV2(
|
||||
quicSession quic.Connection,
|
||||
log *zerolog.Logger,
|
||||
sessionDemuxChan chan<- *packet.Session,
|
||||
) *DatagramMuxerV2 {
|
||||
logger := log.With().Uint8("datagramVersion", 2).Logger()
|
||||
return &DatagramMuxerV2{
|
||||
session: quicSession,
|
||||
logger: &logger,
|
||||
sessionDemuxChan: sessionDemuxChan,
|
||||
packetDemuxChan: make(chan packet.RawPacket, packetChanCapacity),
|
||||
}
|
||||
}
|
||||
|
||||
// SendToSession suffix the session ID and datagram version to the payload so the other end of the QUIC connection can
|
||||
// demultiplex the payload from multiple datagram sessions
|
||||
func (dm *DatagramMuxerV2) SendToSession(session *packet.Session) error {
|
||||
if len(session.Payload) > dm.mtu() {
|
||||
packetTooBigDropped.Inc()
|
||||
return fmt.Errorf("origin UDP payload has %d bytes, which exceeds transport MTU %d", len(session.Payload), dm.mtu())
|
||||
}
|
||||
msgWithID, err := suffixSessionID(session.ID, session.Payload)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to suffix session ID to datagram, it will be dropped")
|
||||
}
|
||||
msgWithIDAndType, err := suffixType(msgWithID, udp)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to suffix datagram type, it will be dropped")
|
||||
}
|
||||
if err := dm.session.SendMessage(msgWithIDAndType); err != nil {
|
||||
return errors.Wrap(err, "Failed to send datagram back to edge")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SendPacket suffix the datagram type to the packet. The other end of the QUIC connection can demultiplex by parsing
|
||||
// the payload as IP and look at the source and destination.
|
||||
func (dm *DatagramMuxerV2) SendPacket(pk packet.RawPacket) error {
|
||||
payloadWithVersion, err := suffixType(pk.Data, ip)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "Failed to suffix datagram type, it will be dropped")
|
||||
}
|
||||
if err := dm.session.SendMessage(payloadWithVersion); err != nil {
|
||||
return errors.Wrap(err, "Failed to send datagram back to edge")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Demux reads datagrams from the QUIC connection and demuxes depending on whether it's a session or packet
|
||||
func (dm *DatagramMuxerV2) ServeReceive(ctx context.Context) error {
|
||||
for {
|
||||
msg, err := dm.session.ReceiveMessage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := dm.demux(ctx, msg); err != nil {
|
||||
dm.logger.Error().Err(err).Msg("Failed to demux datagram")
|
||||
if err == context.Canceled {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (dm *DatagramMuxerV2) ReceivePacket(ctx context.Context) (packet.RawPacket, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return packet.RawPacket{}, ctx.Err()
|
||||
case pk := <-dm.packetDemuxChan:
|
||||
return pk, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (dm *DatagramMuxerV2) demux(ctx context.Context, msgWithType []byte) error {
|
||||
if len(msgWithType) < typeIDLen {
|
||||
return fmt.Errorf("QUIC datagram should have at least %d byte", typeIDLen)
|
||||
}
|
||||
msgType := datagramV2Type(msgWithType[len(msgWithType)-typeIDLen])
|
||||
msg := msgWithType[0 : len(msgWithType)-typeIDLen]
|
||||
switch msgType {
|
||||
case udp:
|
||||
return dm.handleSession(ctx, msg)
|
||||
case ip:
|
||||
return dm.handlePacket(ctx, msg)
|
||||
default:
|
||||
return fmt.Errorf("Unexpected datagram type %d", msgType)
|
||||
}
|
||||
}
|
||||
|
||||
func (dm *DatagramMuxerV2) handleSession(ctx context.Context, session []byte) error {
|
||||
sessionID, payload, err := extractSessionID(session)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sessionDatagram := packet.Session{
|
||||
ID: sessionID,
|
||||
Payload: payload,
|
||||
}
|
||||
select {
|
||||
case dm.sessionDemuxChan <- &sessionDatagram:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (dm *DatagramMuxerV2) handlePacket(ctx context.Context, pk []byte) error {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case dm.packetDemuxChan <- packet.RawPacket{
|
||||
Data: pk,
|
||||
}:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -144,6 +144,13 @@ var (
|
||||
}
|
||||
registerClient = sync.Once{}
|
||||
registerServer = sync.Once{}
|
||||
|
||||
packetTooBigDropped = prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: namespace,
|
||||
Subsystem: perspectiveString(logging.PerspectiveClient),
|
||||
Name: "packet_too_big_dropped",
|
||||
Help: "Count of packets received from origin that are too big to send to the edge and are dropped as a result",
|
||||
})
|
||||
)
|
||||
|
||||
// MetricsCollector abstracts the difference between client and server metrics from connTracer
|
||||
@@ -264,6 +271,7 @@ func newClientCollector(index uint8) MetricsCollector {
|
||||
clientMetrics.minRTT,
|
||||
clientMetrics.latestRTT,
|
||||
clientMetrics.smoothedRTT,
|
||||
packetTooBigDropped,
|
||||
)
|
||||
})
|
||||
return &clientCollector{
|
||||
|
||||
@@ -7,5 +7,5 @@ const (
|
||||
// 1220 is the default value https://github.com/lucas-clemente/quic-go/blob/84e03e59760ceee37359688871bb0688fcc4e98f/internal/protocol/params.go#L138
|
||||
MaxDatagramFrameSize = 1220
|
||||
// 3 more bytes are reserved at https://github.com/lucas-clemente/quic-go/blob/v0.24.0/internal/wire/datagram_frame.go#L61
|
||||
maxDatagramPayloadSize = MaxDatagramFrameSize - 3 - sessionIDLen
|
||||
maxDatagramPayloadSize = MaxDatagramFrameSize - 3 - sessionIDLen - typeIDLen
|
||||
)
|
||||
|
||||
@@ -247,12 +247,8 @@ func NewRPCClientStream(ctx context.Context, stream io.ReadWriteCloser, logger *
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (rcs *RPCClientStream) RegisterUdpSession(ctx context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeIdleAfterHint time.Duration) error {
|
||||
resp, err := rcs.client.RegisterUdpSession(ctx, sessionID, dstIP, dstPort, closeIdleAfterHint)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return resp.Err
|
||||
func (rcs *RPCClientStream) RegisterUdpSession(ctx context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeIdleAfterHint time.Duration, traceContext string) (*tunnelpogs.RegisterUdpSessionResponse, error) {
|
||||
return rcs.client.RegisterUdpSession(ctx, sessionID, dstIP, dstPort, closeIdleAfterHint, traceContext)
|
||||
}
|
||||
|
||||
func (rcs *RPCClientStream) UnregisterUdpSession(ctx context.Context, sessionID uuid.UUID, message string) error {
|
||||
|
||||
+69
-36
@@ -110,45 +110,74 @@ func TestConnectResponseMeta(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRegisterUdpSession(t *testing.T) {
|
||||
clientStream, serverStream := newMockRPCStreams()
|
||||
|
||||
unregisterMessage := "closed by eyeball"
|
||||
sessionRPCServer := mockSessionRPCServer{
|
||||
sessionID: uuid.New(),
|
||||
dstIP: net.IP{172, 16, 0, 1},
|
||||
dstPort: 8000,
|
||||
closeIdleAfter: testCloseIdleAfterHint,
|
||||
unregisterMessage: unregisterMessage,
|
||||
|
||||
var tests = []struct {
|
||||
name string
|
||||
sessionRPCServer mockSessionRPCServer
|
||||
}{
|
||||
{
|
||||
name: "RegisterUdpSession (no trace context)",
|
||||
sessionRPCServer: mockSessionRPCServer{
|
||||
sessionID: uuid.New(),
|
||||
dstIP: net.IP{172, 16, 0, 1},
|
||||
dstPort: 8000,
|
||||
closeIdleAfter: testCloseIdleAfterHint,
|
||||
unregisterMessage: unregisterMessage,
|
||||
traceContext: "",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "RegisterUdpSession (with trace context)",
|
||||
sessionRPCServer: mockSessionRPCServer{
|
||||
sessionID: uuid.New(),
|
||||
dstIP: net.IP{172, 16, 0, 1},
|
||||
dstPort: 8000,
|
||||
closeIdleAfter: testCloseIdleAfterHint,
|
||||
unregisterMessage: unregisterMessage,
|
||||
traceContext: "1241ce3ecdefc68854e8514e69ba42ca:b38f1bf5eae406f3:0:1",
|
||||
},
|
||||
},
|
||||
}
|
||||
logger := zerolog.Nop()
|
||||
sessionRegisteredChan := make(chan struct{})
|
||||
go func() {
|
||||
protocol, err := DetermineProtocol(serverStream)
|
||||
assert.NoError(t, err)
|
||||
rpcServerStream, err := NewRPCServerStream(serverStream, protocol)
|
||||
assert.NoError(t, err)
|
||||
err = rpcServerStream.Serve(sessionRPCServer, nil, &logger)
|
||||
assert.NoError(t, err)
|
||||
|
||||
serverStream.Close()
|
||||
close(sessionRegisteredChan)
|
||||
}()
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
logger := zerolog.Nop()
|
||||
clientStream, serverStream := newMockRPCStreams()
|
||||
sessionRegisteredChan := make(chan struct{})
|
||||
go func() {
|
||||
protocol, err := DetermineProtocol(serverStream)
|
||||
assert.NoError(t, err)
|
||||
rpcServerStream, err := NewRPCServerStream(serverStream, protocol)
|
||||
assert.NoError(t, err)
|
||||
err = rpcServerStream.Serve(test.sessionRPCServer, nil, &logger)
|
||||
assert.NoError(t, err)
|
||||
|
||||
rpcClientStream, err := NewRPCClientStream(context.Background(), clientStream, &logger)
|
||||
assert.NoError(t, err)
|
||||
serverStream.Close()
|
||||
close(sessionRegisteredChan)
|
||||
}()
|
||||
|
||||
assert.NoError(t, rpcClientStream.RegisterUdpSession(context.Background(), sessionRPCServer.sessionID, sessionRPCServer.dstIP, sessionRPCServer.dstPort, testCloseIdleAfterHint))
|
||||
rpcClientStream, err := NewRPCClientStream(context.Background(), clientStream, &logger)
|
||||
assert.NoError(t, err)
|
||||
|
||||
// Different sessionID, the RPC server should reject the registraion
|
||||
assert.Error(t, rpcClientStream.RegisterUdpSession(context.Background(), uuid.New(), sessionRPCServer.dstIP, sessionRPCServer.dstPort, testCloseIdleAfterHint))
|
||||
reg, err := rpcClientStream.RegisterUdpSession(context.Background(), test.sessionRPCServer.sessionID, test.sessionRPCServer.dstIP, test.sessionRPCServer.dstPort, testCloseIdleAfterHint, test.sessionRPCServer.traceContext)
|
||||
assert.NoError(t, err)
|
||||
assert.NoError(t, reg.Err)
|
||||
|
||||
assert.NoError(t, rpcClientStream.UnregisterUdpSession(context.Background(), sessionRPCServer.sessionID, unregisterMessage))
|
||||
// Different sessionID, the RPC server should reject the registraion
|
||||
reg, err = rpcClientStream.RegisterUdpSession(context.Background(), uuid.New(), test.sessionRPCServer.dstIP, test.sessionRPCServer.dstPort, testCloseIdleAfterHint, test.sessionRPCServer.traceContext)
|
||||
assert.NoError(t, err)
|
||||
assert.Error(t, reg.Err)
|
||||
|
||||
// Different sessionID, the RPC server should reject the unregistraion
|
||||
assert.Error(t, rpcClientStream.UnregisterUdpSession(context.Background(), uuid.New(), unregisterMessage))
|
||||
assert.NoError(t, rpcClientStream.UnregisterUdpSession(context.Background(), test.sessionRPCServer.sessionID, unregisterMessage))
|
||||
|
||||
rpcClientStream.Close()
|
||||
<-sessionRegisteredChan
|
||||
// Different sessionID, the RPC server should reject the unregistraion
|
||||
assert.Error(t, rpcClientStream.UnregisterUdpSession(context.Background(), uuid.New(), unregisterMessage))
|
||||
|
||||
rpcClientStream.Close()
|
||||
<-sessionRegisteredChan
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestManageConfiguration(t *testing.T) {
|
||||
@@ -198,22 +227,26 @@ type mockSessionRPCServer struct {
|
||||
dstPort uint16
|
||||
closeIdleAfter time.Duration
|
||||
unregisterMessage string
|
||||
traceContext string
|
||||
}
|
||||
|
||||
func (s mockSessionRPCServer) RegisterUdpSession(_ context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeIdleAfter time.Duration) error {
|
||||
func (s mockSessionRPCServer) RegisterUdpSession(_ context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeIdleAfter time.Duration, traceContext string) (*tunnelpogs.RegisterUdpSessionResponse, error) {
|
||||
if s.sessionID != sessionID {
|
||||
return fmt.Errorf("expect session ID %s, got %s", s.sessionID, sessionID)
|
||||
return nil, fmt.Errorf("expect session ID %s, got %s", s.sessionID, sessionID)
|
||||
}
|
||||
if !s.dstIP.Equal(dstIP) {
|
||||
return fmt.Errorf("expect destination IP %s, got %s", s.dstIP, dstIP)
|
||||
return nil, fmt.Errorf("expect destination IP %s, got %s", s.dstIP, dstIP)
|
||||
}
|
||||
if s.dstPort != dstPort {
|
||||
return fmt.Errorf("expect destination port %d, got %d", s.dstPort, dstPort)
|
||||
return nil, fmt.Errorf("expect destination port %d, got %d", s.dstPort, dstPort)
|
||||
}
|
||||
if s.closeIdleAfter != closeIdleAfter {
|
||||
return fmt.Errorf("expect closeIdleAfter %d, got %d", s.closeIdleAfter, closeIdleAfter)
|
||||
return nil, fmt.Errorf("expect closeIdleAfter %d, got %d", s.closeIdleAfter, closeIdleAfter)
|
||||
}
|
||||
return nil
|
||||
if s.traceContext != traceContext {
|
||||
return nil, fmt.Errorf("expect traceContext %s, got %s", s.traceContext, traceContext)
|
||||
}
|
||||
return &tunnelpogs.RegisterUdpSessionResponse{}, nil
|
||||
}
|
||||
|
||||
func (s mockSessionRPCServer) UnregisterUdpSession(_ context.Context, sessionID uuid.UUID, message string) error {
|
||||
|
||||
@@ -41,3 +41,14 @@ func (s *SafeStreamCloser) Close() error {
|
||||
s.stream.CancelRead(0)
|
||||
return s.stream.Close()
|
||||
}
|
||||
|
||||
func (s *SafeStreamCloser) CloseWrite() error {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
|
||||
// As documented by the quic-go library, this doesn't actually close the entire stream.
|
||||
// It prevents further writes, which in turn will result in an EOF signal being sent the other side of stream when
|
||||
// reading.
|
||||
// We can still read from this stream.
|
||||
return s.stream.Close()
|
||||
}
|
||||
|
||||
@@ -12,9 +12,9 @@ type ConnAwareLogger struct {
|
||||
logger *zerolog.Logger
|
||||
}
|
||||
|
||||
func NewConnAwareLogger(logger *zerolog.Logger, observer *connection.Observer) *ConnAwareLogger {
|
||||
func NewConnAwareLogger(logger *zerolog.Logger, tracker *tunnelstate.ConnTracker, observer *connection.Observer) *ConnAwareLogger {
|
||||
connAwareLogger := &ConnAwareLogger{
|
||||
tracker: tunnelstate.NewConnTracker(logger),
|
||||
tracker: tracker,
|
||||
logger: logger,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package supervisor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// When experimental post-quantum tunnels are enabled, and we're hitting an
|
||||
// issue creating the tunnel, we'll report the first error
|
||||
// to https://pqtunnels.cloudflareresearch.com.
|
||||
|
||||
var (
|
||||
PQKexes = [...]tls.CurveID{
|
||||
tls.CurveID(0xfe30), // X25519Kyber512Draft00
|
||||
tls.CurveID(0xfe31), // X25519Kyber768Draft00
|
||||
}
|
||||
PQKexNames map[tls.CurveID]string = map[tls.CurveID]string{
|
||||
tls.CurveID(0xfe30): "X25519Kyber512Draft00",
|
||||
tls.CurveID(0xfe31): "X25519Kyber768Draft00",
|
||||
}
|
||||
|
||||
pqtMux sync.Mutex // protects pqtSubmitted and pqtWaitForMessage
|
||||
pqtSubmitted bool // whether an error has already been submitted
|
||||
|
||||
// Number of errors to ignore before printing elaborate instructions.
|
||||
pqtWaitForMessage int
|
||||
)
|
||||
|
||||
func handlePQTunnelError(rep error, config *TunnelConfig) {
|
||||
needToMessage := false
|
||||
|
||||
pqtMux.Lock()
|
||||
needToSubmit := !pqtSubmitted
|
||||
if needToSubmit {
|
||||
pqtSubmitted = true
|
||||
}
|
||||
pqtWaitForMessage--
|
||||
if pqtWaitForMessage < 0 {
|
||||
pqtWaitForMessage = 5
|
||||
needToMessage = true
|
||||
}
|
||||
pqtMux.Unlock()
|
||||
|
||||
if needToMessage {
|
||||
config.Log.Info().Msgf(
|
||||
"\n\n" +
|
||||
"===================================================================================\n" +
|
||||
"You are hitting an error while using the experimental post-quantum tunnels feature.\n" +
|
||||
"\n" +
|
||||
"Please check:\n" +
|
||||
"\n" +
|
||||
" https://pqtunnels.cloudflareresearch.com\n" +
|
||||
"\n" +
|
||||
"for known problems.\n" +
|
||||
"===================================================================================\n\n",
|
||||
)
|
||||
}
|
||||
|
||||
if needToSubmit {
|
||||
go submitPQTunnelError(rep, config)
|
||||
}
|
||||
}
|
||||
|
||||
func submitPQTunnelError(rep error, config *TunnelConfig) {
|
||||
body, err := json.Marshal(struct {
|
||||
Group int `json:"g"`
|
||||
Message string `json:"m"`
|
||||
Version string `json:"v"`
|
||||
}{
|
||||
Group: int(PQKexes[config.PQKexIdx]),
|
||||
Message: rep.Error(),
|
||||
Version: config.ReportedVersion,
|
||||
})
|
||||
if err != nil {
|
||||
config.Log.Err(err).Msg("Failed to create error report")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := http.Post(
|
||||
"https://pqtunnels.cloudflareresearch.com",
|
||||
"application/json",
|
||||
bytes.NewBuffer(body),
|
||||
)
|
||||
if err != nil {
|
||||
config.Log.Err(err).Msg(
|
||||
"Failed to submit post-quantum tunnel error report",
|
||||
)
|
||||
return
|
||||
}
|
||||
if resp.StatusCode != 200 {
|
||||
config.Log.Error().Msgf(
|
||||
"Failed to submit post-quantum tunnel error report: status %d",
|
||||
resp.StatusCode,
|
||||
)
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -15,10 +16,12 @@ import (
|
||||
"github.com/cloudflare/cloudflared/edgediscovery"
|
||||
"github.com/cloudflare/cloudflared/edgediscovery/allregions"
|
||||
"github.com/cloudflare/cloudflared/h2mux"
|
||||
"github.com/cloudflare/cloudflared/ingress"
|
||||
"github.com/cloudflare/cloudflared/orchestration"
|
||||
"github.com/cloudflare/cloudflared/retry"
|
||||
"github.com/cloudflare/cloudflared/signal"
|
||||
tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
|
||||
"github.com/cloudflare/cloudflared/tunnelstate"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -43,7 +46,7 @@ type Supervisor struct {
|
||||
config *TunnelConfig
|
||||
orchestrator *orchestration.Orchestrator
|
||||
edgeIPs *edgediscovery.Edge
|
||||
edgeTunnelServer EdgeTunnelServer
|
||||
edgeTunnelServer *EdgeTunnelServer
|
||||
tunnelErrors chan tunnelError
|
||||
tunnelsConnecting map[int]chan struct{}
|
||||
tunnelsProtocolFallback map[int]*protocolFallback
|
||||
@@ -88,7 +91,9 @@ func NewSupervisor(config *TunnelConfig, orchestrator *orchestration.Orchestrato
|
||||
}
|
||||
|
||||
reconnectCredentialManager := newReconnectCredentialManager(connection.MetricsNamespace, connection.TunnelSubsystem, config.HAConnections)
|
||||
log := NewConnAwareLogger(config.Log, config.Observer)
|
||||
|
||||
tracker := tunnelstate.NewConnTracker(config.Log)
|
||||
log := NewConnAwareLogger(config.Log, tracker, config.Observer)
|
||||
|
||||
var edgeAddrHandler EdgeAddrHandler
|
||||
if isStaticEdge { // static edge addresses
|
||||
@@ -106,11 +111,19 @@ func NewSupervisor(config *TunnelConfig, orchestrator *orchestration.Orchestrato
|
||||
credentialManager: reconnectCredentialManager,
|
||||
edgeAddrs: edgeIPs,
|
||||
edgeAddrHandler: edgeAddrHandler,
|
||||
tracker: tracker,
|
||||
reconnectCh: reconnectCh,
|
||||
gracefulShutdownC: gracefulShutdownC,
|
||||
connAwareLogger: log,
|
||||
}
|
||||
|
||||
icmpRouter, err := ingress.NewICMPRouter(config.Log)
|
||||
if err != nil {
|
||||
log.Logger().Warn().Err(err).Msg("Failed to create icmp router, ICMP proxy feature is disabled")
|
||||
} else {
|
||||
edgeTunnelServer.icmpRouter = icmpRouter
|
||||
}
|
||||
|
||||
useReconnectToken := false
|
||||
if config.ClassicTunnel != nil {
|
||||
useReconnectToken = config.ClassicTunnel.UseReconnectToken
|
||||
@@ -121,7 +134,7 @@ func NewSupervisor(config *TunnelConfig, orchestrator *orchestration.Orchestrato
|
||||
config: config,
|
||||
orchestrator: orchestrator,
|
||||
edgeIPs: edgeIPs,
|
||||
edgeTunnelServer: edgeTunnelServer,
|
||||
edgeTunnelServer: &edgeTunnelServer,
|
||||
tunnelErrors: make(chan tunnelError),
|
||||
tunnelsConnecting: map[int]chan struct{}{},
|
||||
tunnelsProtocolFallback: map[int]*protocolFallback{},
|
||||
@@ -138,6 +151,18 @@ func (s *Supervisor) Run(
|
||||
ctx context.Context,
|
||||
connectedSignal *signal.Signal,
|
||||
) error {
|
||||
if s.edgeTunnelServer.icmpRouter != nil {
|
||||
go func() {
|
||||
if err := s.edgeTunnelServer.icmpRouter.Serve(ctx); err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
s.log.Logger().Info().Err(err).Msg("icmp router terminated")
|
||||
} else {
|
||||
s.log.Logger().Err(err).Msg("icmp router terminated")
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
if err := s.initialize(ctx, connectedSignal); err != nil {
|
||||
if err == errEarlyShutdown {
|
||||
return nil
|
||||
@@ -245,7 +270,7 @@ func (s *Supervisor) initialize(
|
||||
s.config.HAConnections = availableAddrs
|
||||
}
|
||||
s.tunnelsProtocolFallback[0] = &protocolFallback{
|
||||
retry.BackoffHandler{MaxRetries: s.config.Retries},
|
||||
retry.BackoffHandler{MaxRetries: s.config.Retries, RetryForever: true},
|
||||
s.config.ProtocolSelector.Current(),
|
||||
false,
|
||||
}
|
||||
@@ -267,12 +292,11 @@ func (s *Supervisor) initialize(
|
||||
// At least one successful connection, so start the rest
|
||||
for i := 1; i < s.config.HAConnections; i++ {
|
||||
s.tunnelsProtocolFallback[i] = &protocolFallback{
|
||||
retry.BackoffHandler{MaxRetries: s.config.Retries},
|
||||
retry.BackoffHandler{MaxRetries: s.config.Retries, RetryForever: true},
|
||||
s.config.ProtocolSelector.Current(),
|
||||
false,
|
||||
}
|
||||
ch := signal.New(make(chan struct{}))
|
||||
go s.startTunnel(ctx, i, ch)
|
||||
go s.startTunnel(ctx, i, s.newConnectedTunnelSignal(i))
|
||||
time.Sleep(registrationInterval)
|
||||
}
|
||||
return nil
|
||||
|
||||
+113
-103
@@ -21,11 +21,13 @@ import (
|
||||
"github.com/cloudflare/cloudflared/edgediscovery/allregions"
|
||||
"github.com/cloudflare/cloudflared/h2mux"
|
||||
"github.com/cloudflare/cloudflared/orchestration"
|
||||
"github.com/cloudflare/cloudflared/packet"
|
||||
quicpogs "github.com/cloudflare/cloudflared/quic"
|
||||
"github.com/cloudflare/cloudflared/retry"
|
||||
"github.com/cloudflare/cloudflared/signal"
|
||||
"github.com/cloudflare/cloudflared/tunnelrpc"
|
||||
tunnelpogs "github.com/cloudflare/cloudflared/tunnelrpc/pogs"
|
||||
"github.com/cloudflare/cloudflared/tunnelstate"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -33,6 +35,8 @@ const (
|
||||
FeatureSerializedHeaders = "serialized_headers"
|
||||
FeatureQuickReconnects = "quick_reconnects"
|
||||
FeatureAllowRemoteConfig = "allow_remote_config"
|
||||
FeatureDatagramV2 = "support_datagram_v2"
|
||||
FeaturePostQuantum = "postquantum"
|
||||
)
|
||||
|
||||
type TunnelConfig struct {
|
||||
@@ -56,6 +60,11 @@ type TunnelConfig struct {
|
||||
Retries uint
|
||||
RunFromTerminal bool
|
||||
|
||||
NeedPQ bool
|
||||
|
||||
// Index into PQKexes of post-quantum kex to use if NeedPQ is set.
|
||||
PQKexIdx int
|
||||
|
||||
NamedTunnel *connection.NamedTunnelProperties
|
||||
ClassicTunnel *connection.ClassicTunnelProperties
|
||||
MuxerConfig *connection.MuxerConfig
|
||||
@@ -190,11 +199,13 @@ type EdgeTunnelServer struct {
|
||||
edgeAddrs *edgediscovery.Edge
|
||||
reconnectCh chan ReconnectSignal
|
||||
gracefulShutdownC <-chan struct{}
|
||||
tracker *tunnelstate.ConnTracker
|
||||
icmpRouter packet.ICMPRouter
|
||||
|
||||
connAwareLogger *ConnAwareLogger
|
||||
}
|
||||
|
||||
func (e EdgeTunnelServer) Serve(ctx context.Context, connIndex uint8, protocolFallback *protocolFallback, connectedSignal *signal.Signal) error {
|
||||
func (e *EdgeTunnelServer) Serve(ctx context.Context, connIndex uint8, protocolFallback *protocolFallback, connectedSignal *signal.Signal) error {
|
||||
haConnections.Inc()
|
||||
defer haConnections.Dec()
|
||||
|
||||
@@ -226,20 +237,14 @@ func (e EdgeTunnelServer) Serve(ctx context.Context, connIndex uint8, protocolFa
|
||||
// to another protocol when a particular metal doesn't support new protocol
|
||||
// Each connection can also have it's own IP version because individual connections might fallback
|
||||
// to another IP version.
|
||||
err, recoverable := ServeTunnel(
|
||||
err, recoverable := e.serveTunnel(
|
||||
ctx,
|
||||
connLog,
|
||||
e.credentialManager,
|
||||
e.config,
|
||||
e.orchestrator,
|
||||
addr,
|
||||
connIndex,
|
||||
connectedFuse,
|
||||
protocolFallback,
|
||||
e.cloudflaredUUID,
|
||||
e.reconnectCh,
|
||||
protocolFallback.protocol,
|
||||
e.gracefulShutdownC,
|
||||
)
|
||||
|
||||
// If the connection is recoverable, we want to maintain the same IP
|
||||
@@ -272,6 +277,12 @@ func (e EdgeTunnelServer) Serve(ctx context.Context, connIndex uint8, protocolFa
|
||||
return err
|
||||
}
|
||||
|
||||
// If a single connection has connected with the current protocol, we know we know we don't have to fallback
|
||||
// to a different protocol.
|
||||
if e.tracker.HasConnectedWith(e.config.ProtocolSelector.Current()) {
|
||||
return err
|
||||
}
|
||||
|
||||
if !selectNextProtocol(
|
||||
connLog.Logger(),
|
||||
protocolFallback,
|
||||
@@ -312,16 +323,11 @@ func selectNextProtocol(
|
||||
selector connection.ProtocolSelector,
|
||||
cause error,
|
||||
) bool {
|
||||
var idleTimeoutError *quic.IdleTimeoutError
|
||||
isNetworkActivityTimeout := errors.As(cause, &idleTimeoutError)
|
||||
edgeQuicDialError, ok := cause.(*connection.EdgeQuicDialError)
|
||||
if !isNetworkActivityTimeout && ok {
|
||||
isNetworkActivityTimeout = errors.As(edgeQuicDialError.Cause, &idleTimeoutError)
|
||||
}
|
||||
isQuicBroken := isQuicBroken(cause)
|
||||
_, hasFallback := selector.Fallback()
|
||||
|
||||
if protocolBackoff.ReachedMaxRetries() || (hasFallback && isNetworkActivityTimeout) {
|
||||
if isNetworkActivityTimeout {
|
||||
if protocolBackoff.ReachedMaxRetries() || (hasFallback && isQuicBroken) {
|
||||
if isQuicBroken {
|
||||
connLog.Warn().Msg("If this log occurs persistently, and cloudflared is unable to connect to " +
|
||||
"Cloudflare Network with `quic` protocol, then most likely your machine/network is getting its egress " +
|
||||
"UDP to port 7844 (or others) blocked or dropped. Make sure to allow egress connectivity as per " +
|
||||
@@ -350,22 +356,30 @@ func selectNextProtocol(
|
||||
return true
|
||||
}
|
||||
|
||||
func isQuicBroken(cause error) bool {
|
||||
var idleTimeoutError *quic.IdleTimeoutError
|
||||
if errors.As(cause, &idleTimeoutError) {
|
||||
return true
|
||||
}
|
||||
|
||||
var transportError *quic.TransportError
|
||||
if errors.As(cause, &transportError) && strings.Contains(cause.Error(), "operation not permitted") {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// ServeTunnel runs a single tunnel connection, returns nil on graceful shutdown,
|
||||
// on error returns a flag indicating if error can be retried
|
||||
func ServeTunnel(
|
||||
func (e *EdgeTunnelServer) serveTunnel(
|
||||
ctx context.Context,
|
||||
connLog *ConnAwareLogger,
|
||||
credentialManager *reconnectCredentialManager,
|
||||
config *TunnelConfig,
|
||||
orchestrator *orchestration.Orchestrator,
|
||||
addr *allregions.EdgeAddr,
|
||||
connIndex uint8,
|
||||
fuse *h2mux.BooleanFuse,
|
||||
backoff *protocolFallback,
|
||||
cloudflaredUUID uuid.UUID,
|
||||
reconnectCh chan ReconnectSignal,
|
||||
protocol connection.Protocol,
|
||||
gracefulShutdownC <-chan struct{},
|
||||
) (err error, recoverable bool) {
|
||||
// Treat panics as recoverable errors
|
||||
defer func() {
|
||||
@@ -380,21 +394,15 @@ func ServeTunnel(
|
||||
}
|
||||
}()
|
||||
|
||||
defer config.Observer.SendDisconnect(connIndex)
|
||||
err, recoverable = serveTunnel(
|
||||
defer e.config.Observer.SendDisconnect(connIndex)
|
||||
err, recoverable = e.serveConnection(
|
||||
ctx,
|
||||
connLog,
|
||||
credentialManager,
|
||||
config,
|
||||
orchestrator,
|
||||
addr,
|
||||
connIndex,
|
||||
fuse,
|
||||
backoff,
|
||||
cloudflaredUUID,
|
||||
reconnectCh,
|
||||
protocol,
|
||||
gracefulShutdownC,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
@@ -407,7 +415,7 @@ func ServeTunnel(
|
||||
connLog.ConnAwareLogger().Err(err).Msg("Register tunnel error from server side")
|
||||
// Don't send registration error return from server to Sentry. They are
|
||||
// logged on server side
|
||||
if incidents := config.IncidentLookup.ActiveIncidents(); len(incidents) > 0 {
|
||||
if incidents := e.config.IncidentLookup.ActiveIncidents(); len(incidents) > 0 {
|
||||
connLog.ConnAwareLogger().Msg(activeIncidentsMsg(incidents))
|
||||
}
|
||||
return err.Cause, !err.Permanent
|
||||
@@ -433,92 +441,73 @@ func ServeTunnel(
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func serveTunnel(
|
||||
func (e *EdgeTunnelServer) serveConnection(
|
||||
ctx context.Context,
|
||||
connLog *ConnAwareLogger,
|
||||
credentialManager *reconnectCredentialManager,
|
||||
config *TunnelConfig,
|
||||
orchestrator *orchestration.Orchestrator,
|
||||
addr *allregions.EdgeAddr,
|
||||
connIndex uint8,
|
||||
fuse *h2mux.BooleanFuse,
|
||||
backoff *protocolFallback,
|
||||
cloudflaredUUID uuid.UUID,
|
||||
reconnectCh chan ReconnectSignal,
|
||||
protocol connection.Protocol,
|
||||
gracefulShutdownC <-chan struct{},
|
||||
) (err error, recoverable bool) {
|
||||
connectedFuse := &connectedFuse{
|
||||
fuse: fuse,
|
||||
backoff: backoff,
|
||||
}
|
||||
controlStream := connection.NewControlStream(
|
||||
config.Observer,
|
||||
e.config.Observer,
|
||||
connectedFuse,
|
||||
config.NamedTunnel,
|
||||
e.config.NamedTunnel,
|
||||
connIndex,
|
||||
addr.UDP.IP,
|
||||
nil,
|
||||
gracefulShutdownC,
|
||||
config.GracePeriod,
|
||||
e.gracefulShutdownC,
|
||||
e.config.GracePeriod,
|
||||
protocol,
|
||||
)
|
||||
|
||||
switch protocol {
|
||||
case connection.QUIC, connection.QUICWarp:
|
||||
connOptions := config.connectionOptions(addr.UDP.String(), uint8(backoff.Retries()))
|
||||
return ServeQUIC(ctx,
|
||||
connOptions := e.config.connectionOptions(addr.UDP.String(), uint8(backoff.Retries()))
|
||||
return e.serveQUIC(ctx,
|
||||
addr.UDP,
|
||||
config,
|
||||
orchestrator,
|
||||
connLog,
|
||||
connOptions,
|
||||
controlStream,
|
||||
connIndex,
|
||||
reconnectCh,
|
||||
gracefulShutdownC)
|
||||
connIndex)
|
||||
|
||||
case connection.HTTP2, connection.HTTP2Warp:
|
||||
edgeConn, err := edgediscovery.DialEdge(ctx, dialTimeout, config.EdgeTLSConfigs[protocol], addr.TCP)
|
||||
edgeConn, err := edgediscovery.DialEdge(ctx, dialTimeout, e.config.EdgeTLSConfigs[protocol], addr.TCP)
|
||||
if err != nil {
|
||||
connLog.ConnAwareLogger().Err(err).Msg("Unable to establish connection with Cloudflare edge")
|
||||
return err, true
|
||||
}
|
||||
|
||||
connOptions := config.connectionOptions(edgeConn.LocalAddr().String(), uint8(backoff.Retries()))
|
||||
if err := ServeHTTP2(
|
||||
connOptions := e.config.connectionOptions(edgeConn.LocalAddr().String(), uint8(backoff.Retries()))
|
||||
if err := e.serveHTTP2(
|
||||
ctx,
|
||||
connLog,
|
||||
config,
|
||||
orchestrator,
|
||||
edgeConn,
|
||||
connOptions,
|
||||
controlStream,
|
||||
connIndex,
|
||||
gracefulShutdownC,
|
||||
reconnectCh,
|
||||
); err != nil {
|
||||
return err, false
|
||||
}
|
||||
|
||||
default:
|
||||
edgeConn, err := edgediscovery.DialEdge(ctx, dialTimeout, config.EdgeTLSConfigs[protocol], addr.TCP)
|
||||
edgeConn, err := edgediscovery.DialEdge(ctx, dialTimeout, e.config.EdgeTLSConfigs[protocol], addr.TCP)
|
||||
if err != nil {
|
||||
connLog.ConnAwareLogger().Err(err).Msg("Unable to establish connection with Cloudflare edge")
|
||||
return err, true
|
||||
}
|
||||
|
||||
if err := ServeH2mux(
|
||||
if err := e.serveH2mux(
|
||||
ctx,
|
||||
connLog,
|
||||
credentialManager,
|
||||
config,
|
||||
orchestrator,
|
||||
edgeConn,
|
||||
connIndex,
|
||||
connectedFuse,
|
||||
cloudflaredUUID,
|
||||
reconnectCh,
|
||||
gracefulShutdownC,
|
||||
); err != nil {
|
||||
return err, false
|
||||
}
|
||||
@@ -534,29 +523,27 @@ func (r unrecoverableError) Error() string {
|
||||
return r.err.Error()
|
||||
}
|
||||
|
||||
func ServeH2mux(
|
||||
func (e *EdgeTunnelServer) serveH2mux(
|
||||
ctx context.Context,
|
||||
connLog *ConnAwareLogger,
|
||||
credentialManager *reconnectCredentialManager,
|
||||
config *TunnelConfig,
|
||||
orchestrator *orchestration.Orchestrator,
|
||||
edgeConn net.Conn,
|
||||
connIndex uint8,
|
||||
connectedFuse *connectedFuse,
|
||||
cloudflaredUUID uuid.UUID,
|
||||
reconnectCh chan ReconnectSignal,
|
||||
gracefulShutdownC <-chan struct{},
|
||||
) error {
|
||||
if e.config.NeedPQ {
|
||||
return unrecoverableError{errors.New("H2Mux transport does not support post-quantum")}
|
||||
}
|
||||
connLog.Logger().Debug().Msgf("Connecting via h2mux")
|
||||
// Returns error from parsing the origin URL or handshake errors
|
||||
handler, err, recoverable := connection.NewH2muxConnection(
|
||||
orchestrator,
|
||||
config.GracePeriod,
|
||||
config.MuxerConfig,
|
||||
e.orchestrator,
|
||||
e.config.GracePeriod,
|
||||
e.config.MuxerConfig,
|
||||
edgeConn,
|
||||
connIndex,
|
||||
config.Observer,
|
||||
gracefulShutdownC,
|
||||
e.config.Observer,
|
||||
e.gracefulShutdownC,
|
||||
e.config.Log,
|
||||
)
|
||||
if err != nil {
|
||||
if !recoverable {
|
||||
@@ -568,42 +555,48 @@ func ServeH2mux(
|
||||
errGroup, serveCtx := errgroup.WithContext(ctx)
|
||||
|
||||
errGroup.Go(func() error {
|
||||
if config.NamedTunnel != nil {
|
||||
connOptions := config.connectionOptions(edgeConn.LocalAddr().String(), uint8(connectedFuse.backoff.Retries()))
|
||||
return handler.ServeNamedTunnel(serveCtx, config.NamedTunnel, connOptions, connectedFuse)
|
||||
if e.config.NamedTunnel != nil {
|
||||
connOptions := e.config.connectionOptions(edgeConn.LocalAddr().String(), uint8(connectedFuse.backoff.Retries()))
|
||||
return handler.ServeNamedTunnel(serveCtx, e.config.NamedTunnel, connOptions, connectedFuse)
|
||||
}
|
||||
registrationOptions := config.registrationOptions(connIndex, edgeConn.LocalAddr().String(), cloudflaredUUID)
|
||||
return handler.ServeClassicTunnel(serveCtx, config.ClassicTunnel, credentialManager, registrationOptions, connectedFuse)
|
||||
registrationOptions := e.config.registrationOptions(connIndex, edgeConn.LocalAddr().String(), e.cloudflaredUUID)
|
||||
return handler.ServeClassicTunnel(serveCtx, e.config.ClassicTunnel, e.credentialManager, registrationOptions, connectedFuse)
|
||||
})
|
||||
|
||||
errGroup.Go(func() error {
|
||||
return listenReconnect(serveCtx, reconnectCh, gracefulShutdownC)
|
||||
err := listenReconnect(serveCtx, e.reconnectCh, e.gracefulShutdownC)
|
||||
if err != nil {
|
||||
// forcefully break the connection (this is only used for testing)
|
||||
// errgroup will return context canceled for the handler.ServeClassicTunnel
|
||||
connLog.Logger().Debug().Msg("Forcefully breaking h2mux connection")
|
||||
}
|
||||
return err
|
||||
})
|
||||
|
||||
return errGroup.Wait()
|
||||
}
|
||||
|
||||
func ServeHTTP2(
|
||||
func (e *EdgeTunnelServer) serveHTTP2(
|
||||
ctx context.Context,
|
||||
connLog *ConnAwareLogger,
|
||||
config *TunnelConfig,
|
||||
orchestrator *orchestration.Orchestrator,
|
||||
tlsServerConn net.Conn,
|
||||
connOptions *tunnelpogs.ConnectionOptions,
|
||||
controlStreamHandler connection.ControlStreamHandler,
|
||||
connIndex uint8,
|
||||
gracefulShutdownC <-chan struct{},
|
||||
reconnectCh chan ReconnectSignal,
|
||||
) error {
|
||||
if e.config.NeedPQ {
|
||||
return unrecoverableError{errors.New("HTTP/2 transport does not support post-quantum")}
|
||||
}
|
||||
|
||||
connLog.Logger().Debug().Msgf("Connecting via http2")
|
||||
h2conn := connection.NewHTTP2Connection(
|
||||
tlsServerConn,
|
||||
orchestrator,
|
||||
e.orchestrator,
|
||||
connOptions,
|
||||
config.Observer,
|
||||
e.config.Observer,
|
||||
connIndex,
|
||||
controlStreamHandler,
|
||||
config.Log,
|
||||
e.config.Log,
|
||||
)
|
||||
|
||||
errGroup, serveCtx := errgroup.WithContext(ctx)
|
||||
@@ -612,11 +605,11 @@ func ServeHTTP2(
|
||||
})
|
||||
|
||||
errGroup.Go(func() error {
|
||||
err := listenReconnect(serveCtx, reconnectCh, gracefulShutdownC)
|
||||
err := listenReconnect(serveCtx, e.reconnectCh, e.gracefulShutdownC)
|
||||
if err != nil {
|
||||
// forcefully break the connection (this is only used for testing)
|
||||
// errgroup will return context canceled for the h2conn.Serve
|
||||
connLog.Logger().Debug().Msg("Forcefully breaking http2 connection")
|
||||
_ = tlsServerConn.Close()
|
||||
}
|
||||
return err
|
||||
})
|
||||
@@ -624,19 +617,31 @@ func ServeHTTP2(
|
||||
return errGroup.Wait()
|
||||
}
|
||||
|
||||
func ServeQUIC(
|
||||
func (e *EdgeTunnelServer) serveQUIC(
|
||||
ctx context.Context,
|
||||
edgeAddr *net.UDPAddr,
|
||||
config *TunnelConfig,
|
||||
orchestrator *orchestration.Orchestrator,
|
||||
connLogger *ConnAwareLogger,
|
||||
connOptions *tunnelpogs.ConnectionOptions,
|
||||
controlStreamHandler connection.ControlStreamHandler,
|
||||
connIndex uint8,
|
||||
reconnectCh chan ReconnectSignal,
|
||||
gracefulShutdownC <-chan struct{},
|
||||
) (err error, recoverable bool) {
|
||||
tlsConfig := config.EdgeTLSConfigs[connection.QUIC]
|
||||
tlsConfig := e.config.EdgeTLSConfigs[connection.QUIC]
|
||||
|
||||
if e.config.NeedPQ {
|
||||
// If the user passes the -post-quantum flag, we override
|
||||
// CurvePreferences to only support hybrid post-quantum key agreements.
|
||||
cs := make([]tls.CurveID, len(PQKexes))
|
||||
copy(cs, PQKexes[:])
|
||||
|
||||
// It is unclear whether Kyber512 or Kyber768 will become the standard.
|
||||
// Kyber768 is a bit bigger (and doesn't fit in one initial
|
||||
// datagram anymore). We're enabling both, but pick randomly which
|
||||
// one to put first. (TLS will use the first one in the list
|
||||
// and allows a fallback to the second.)
|
||||
cs[0], cs[e.config.PQKexIdx] = cs[e.config.PQKexIdx], cs[0]
|
||||
tlsConfig.CurvePreferences = cs
|
||||
}
|
||||
|
||||
quicConfig := &quic.Config{
|
||||
HandshakeIdleTimeout: quicpogs.HandshakeIdleTimeout,
|
||||
MaxIdleTimeout: quicpogs.MaxIdleTimeout,
|
||||
@@ -652,11 +657,16 @@ func ServeQUIC(
|
||||
quicConfig,
|
||||
edgeAddr,
|
||||
tlsConfig,
|
||||
orchestrator,
|
||||
e.orchestrator,
|
||||
connOptions,
|
||||
controlStreamHandler,
|
||||
connLogger.Logger())
|
||||
connLogger.Logger(),
|
||||
e.icmpRouter)
|
||||
if err != nil {
|
||||
if e.config.NeedPQ {
|
||||
handlePQTunnelError(err, e.config)
|
||||
}
|
||||
|
||||
connLogger.ConnAwareLogger().Err(err).Msgf("Failed to create new quic connection")
|
||||
return err, true
|
||||
}
|
||||
@@ -671,11 +681,11 @@ func ServeQUIC(
|
||||
})
|
||||
|
||||
errGroup.Go(func() error {
|
||||
err := listenReconnect(serveCtx, reconnectCh, gracefulShutdownC)
|
||||
err := listenReconnect(serveCtx, e.reconnectCh, e.gracefulShutdownC)
|
||||
if err != nil {
|
||||
// forcefully break the connection (this is only used for testing)
|
||||
// errgroup will return context canceled for the quicConn.Serve
|
||||
connLogger.Logger().Debug().Msg("Forcefully breaking quic connection")
|
||||
quicConn.Close()
|
||||
}
|
||||
return err
|
||||
})
|
||||
|
||||
@@ -44,6 +44,7 @@ func TestWaitForBackoffFallback(t *testing.T) {
|
||||
mockFetcher.fetch(),
|
||||
resolveTTL,
|
||||
&log,
|
||||
false,
|
||||
)
|
||||
assert.NoError(t, err)
|
||||
|
||||
@@ -104,6 +105,7 @@ func TestWaitForBackoffFallback(t *testing.T) {
|
||||
mockFetcher.fetch(),
|
||||
resolveTTL,
|
||||
&log,
|
||||
false,
|
||||
)
|
||||
assert.NoError(t, err)
|
||||
protoFallback = &protocolFallback{backoff, protocolSelector.Current(), false}
|
||||
|
||||
@@ -40,12 +40,21 @@ func NewCertReloader(certPath, keyPath string) (*CertReloader, error) {
|
||||
}
|
||||
|
||||
// Cert returns the TLS certificate most recently read by the CertReloader.
|
||||
// This method works as a direct utility method for tls.Config#Cert.
|
||||
func (cr *CertReloader) Cert(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
cr.Lock()
|
||||
defer cr.Unlock()
|
||||
return cr.certificate, nil
|
||||
}
|
||||
|
||||
// ClientCert returns the TLS certificate most recently read by the CertReloader.
|
||||
// This method works as a direct utility method for tls.Config#ClientCert.
|
||||
func (cr *CertReloader) ClientCert(certRequestInfo *tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
||||
cr.Lock()
|
||||
defer cr.Unlock()
|
||||
return cr.certificate, nil
|
||||
}
|
||||
|
||||
// LoadCert loads a TLS certificate from the CertReloader's specified filepath.
|
||||
// Call this after writing a new certificate to the disk (e.g. after renewing a certificate)
|
||||
func (cr *CertReloader) LoadCert() error {
|
||||
@@ -131,7 +140,10 @@ func CreateTunnelConfig(c *cli.Context, serverName string) (*tls.Config, error)
|
||||
}
|
||||
|
||||
if tlsConfig.RootCAs == nil {
|
||||
rootCAPool := x509.NewCertPool()
|
||||
rootCAPool, err := x509.SystemCertPool()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "unable to get x509 system cert pool")
|
||||
}
|
||||
cfRootCA, err := GetCloudflareRootCA()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not append Cloudflare Root CAs to cloudflared certificate pool")
|
||||
|
||||
+15
-9
@@ -12,15 +12,16 @@ import (
|
||||
|
||||
// Config is the user provided parameters to create a tls.Config
|
||||
type TLSParameters struct {
|
||||
Cert string
|
||||
Key string
|
||||
GetCertificate *CertReloader
|
||||
ClientCAs []string
|
||||
RootCAs []string
|
||||
ServerName string
|
||||
CurvePreferences []tls.CurveID
|
||||
MinVersion uint16 // min tls version. If zero, TLS1.0 is defined as minimum.
|
||||
MaxVersion uint16 // max tls version. If zero, last TLS version is used defined as limit (currently TLS1.3)
|
||||
Cert string
|
||||
Key string
|
||||
GetCertificate *CertReloader
|
||||
GetClientCertificate *CertReloader
|
||||
ClientCAs []string
|
||||
RootCAs []string
|
||||
ServerName string
|
||||
CurvePreferences []tls.CurveID
|
||||
MinVersion uint16 // min tls version. If zero, TLS1.0 is defined as minimum.
|
||||
MaxVersion uint16 // max tls version. If zero, last TLS version is used defined as limit (currently TLS1.3)
|
||||
}
|
||||
|
||||
// GetConfig returns a TLS configuration according to the Config set by the user.
|
||||
@@ -43,6 +44,11 @@ func GetConfig(p *TLSParameters) (*tls.Config, error) {
|
||||
tlsconfig.GetCertificate = p.GetCertificate.Cert
|
||||
}
|
||||
|
||||
if p.GetClientCertificate != nil {
|
||||
// GetClientCertificate is called when using an HTTP client library and mTLS is required.
|
||||
tlsconfig.GetClientCertificate = p.GetClientCertificate.ClientCert
|
||||
}
|
||||
|
||||
if len(p.ClientCAs) > 0 {
|
||||
// set of root certificate authorities that servers use if required to verify a client certificate
|
||||
// by the policy in ClientAuth
|
||||
|
||||
+22
-9
@@ -24,6 +24,9 @@ type InMemoryClient interface {
|
||||
// Spans returns a copy of the list of in-memory stored spans as a base64
|
||||
// encoded otlp protobuf string.
|
||||
Spans() (string, error)
|
||||
// ProtoSpans returns a copy of the list of in-memory stored spans as otlp
|
||||
// protobuf byte array.
|
||||
ProtoSpans() ([]byte, error)
|
||||
}
|
||||
|
||||
// InMemoryOtlpClient is a client implementation for otlptrace.Client
|
||||
@@ -55,21 +58,26 @@ func (mc *InMemoryOtlpClient) UploadTraces(_ context.Context, protoSpans []*trac
|
||||
|
||||
// Spans returns the list of in-memory stored spans as a base64 encoded otlp protobuf string.
|
||||
func (mc *InMemoryOtlpClient) Spans() (string, error) {
|
||||
mc.mu.Lock()
|
||||
defer mc.mu.Unlock()
|
||||
if len(mc.spans) <= 0 {
|
||||
return "", errNoTraces
|
||||
}
|
||||
pbRequest := &coltracepb.ExportTraceServiceRequest{
|
||||
ResourceSpans: mc.spans,
|
||||
}
|
||||
data, err := proto.Marshal(pbRequest)
|
||||
data, err := mc.ProtoSpans()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(data), nil
|
||||
}
|
||||
|
||||
// ProtoSpans returns the list of in-memory stored spans as the protobuf byte array.
|
||||
func (mc *InMemoryOtlpClient) ProtoSpans() ([]byte, error) {
|
||||
mc.mu.Lock()
|
||||
defer mc.mu.Unlock()
|
||||
if len(mc.spans) <= 0 {
|
||||
return nil, errNoTraces
|
||||
}
|
||||
pbRequest := &coltracepb.ExportTraceServiceRequest{
|
||||
ResourceSpans: mc.spans,
|
||||
}
|
||||
return proto.Marshal(pbRequest)
|
||||
}
|
||||
|
||||
// NoopOtlpClient is a client implementation for otlptrace.Client that does nothing
|
||||
type NoopOtlpClient struct{}
|
||||
|
||||
@@ -89,3 +97,8 @@ func (mc *NoopOtlpClient) UploadTraces(_ context.Context, _ []*tracepb.ResourceS
|
||||
func (mc *NoopOtlpClient) Spans() (string, error) {
|
||||
return "", errNoopTracer
|
||||
}
|
||||
|
||||
// Spans always returns no traces error
|
||||
func (mc *NoopOtlpClient) ProtoSpans() ([]byte, error) {
|
||||
return nil, errNoopTracer
|
||||
}
|
||||
|
||||
+107
-20
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
otelContrib "go.opentelemetry.io/contrib/propagators/jaeger"
|
||||
@@ -33,6 +34,9 @@ const (
|
||||
|
||||
MaxErrorDescriptionLen = 100
|
||||
traceHttpStatusCodeKey = "upstreamStatusCode"
|
||||
|
||||
traceID128bitsWidth = 128 / 4
|
||||
separator = ":"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -66,22 +70,50 @@ func Init(version string) {
|
||||
cloudflaredVersionAttribute = semconv.ProcessRuntimeVersionKey.String(version)
|
||||
}
|
||||
|
||||
type TracedRequest struct {
|
||||
type TracedHTTPRequest struct {
|
||||
*http.Request
|
||||
trace.TracerProvider
|
||||
exporter InMemoryClient
|
||||
*cfdTracer
|
||||
}
|
||||
|
||||
// NewTracedRequest creates a new tracer for the current request context.
|
||||
func NewTracedRequest(req *http.Request) *TracedRequest {
|
||||
// NewTracedHTTPRequest creates a new tracer for the current HTTP request context.
|
||||
func NewTracedHTTPRequest(req *http.Request, log *zerolog.Logger) *TracedHTTPRequest {
|
||||
ctx, exists := extractTrace(req)
|
||||
if !exists {
|
||||
return &TracedRequest{req, trace.NewNoopTracerProvider(), &NoopOtlpClient{}}
|
||||
return &TracedHTTPRequest{req, &cfdTracer{trace.NewNoopTracerProvider(), &NoopOtlpClient{}, log}}
|
||||
}
|
||||
return &TracedHTTPRequest{req.WithContext(ctx), newCfdTracer(ctx, log)}
|
||||
}
|
||||
|
||||
func (tr *TracedHTTPRequest) ToTracedContext() *TracedContext {
|
||||
return &TracedContext{tr.Context(), tr.cfdTracer}
|
||||
}
|
||||
|
||||
type TracedContext struct {
|
||||
context.Context
|
||||
*cfdTracer
|
||||
}
|
||||
|
||||
// NewTracedContext creates a new tracer for the current context.
|
||||
func NewTracedContext(ctx context.Context, traceContext string, log *zerolog.Logger) *TracedContext {
|
||||
ctx, exists := extractTraceFromString(ctx, traceContext)
|
||||
if !exists {
|
||||
return &TracedContext{ctx, &cfdTracer{trace.NewNoopTracerProvider(), &NoopOtlpClient{}, log}}
|
||||
}
|
||||
return &TracedContext{ctx, newCfdTracer(ctx, log)}
|
||||
}
|
||||
|
||||
type cfdTracer struct {
|
||||
trace.TracerProvider
|
||||
exporter InMemoryClient
|
||||
log *zerolog.Logger
|
||||
}
|
||||
|
||||
// NewCfdTracer creates a new tracer for the current request context.
|
||||
func newCfdTracer(ctx context.Context, log *zerolog.Logger) *cfdTracer {
|
||||
mc := new(InMemoryOtlpClient)
|
||||
exp, err := otlptrace.New(req.Context(), mc)
|
||||
exp, err := otlptrace.New(ctx, mc)
|
||||
if err != nil {
|
||||
return &TracedRequest{req, trace.NewNoopTracerProvider(), &NoopOtlpClient{}}
|
||||
return &cfdTracer{trace.NewNoopTracerProvider(), &NoopOtlpClient{}, log}
|
||||
}
|
||||
tp := tracesdk.NewTracerProvider(
|
||||
// We want to dump to in-memory exporter immediately
|
||||
@@ -98,42 +130,70 @@ func NewTracedRequest(req *http.Request) *TracedRequest {
|
||||
)),
|
||||
)
|
||||
|
||||
return &TracedRequest{req.WithContext(ctx), tp, mc}
|
||||
return &cfdTracer{tp, mc, log}
|
||||
}
|
||||
|
||||
func (cft *TracedRequest) Tracer() trace.Tracer {
|
||||
func (cft *cfdTracer) Tracer() trace.Tracer {
|
||||
return cft.TracerProvider.Tracer(tracerInstrumentName)
|
||||
}
|
||||
|
||||
// Spans returns the spans as base64 encoded protobuf otlp traces.
|
||||
func (cft *TracedRequest) AddSpans(headers http.Header, log *zerolog.Logger) {
|
||||
if headers == nil {
|
||||
log.Error().Msgf("provided headers map is nil")
|
||||
return
|
||||
}
|
||||
|
||||
// GetSpans returns the spans as base64 encoded string of protobuf otlp traces.
|
||||
func (cft *cfdTracer) GetSpans() (enc string) {
|
||||
enc, err := cft.exporter.Spans()
|
||||
switch err {
|
||||
case nil:
|
||||
break
|
||||
case errNoTraces:
|
||||
log.Error().Err(err).Msgf("expected traces to be available")
|
||||
cft.log.Trace().Err(err).Msgf("expected traces to be available")
|
||||
return
|
||||
case errNoopTracer:
|
||||
return // noop tracer has no traces
|
||||
default:
|
||||
log.Error().Err(err)
|
||||
cft.log.Debug().Err(err)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// GetProtoSpans returns the spans as the otlp traces in protobuf byte array.
|
||||
func (cft *cfdTracer) GetProtoSpans() (proto []byte) {
|
||||
proto, err := cft.exporter.ProtoSpans()
|
||||
switch err {
|
||||
case nil:
|
||||
break
|
||||
case errNoTraces:
|
||||
cft.log.Trace().Err(err).Msgf("expected traces to be available")
|
||||
return
|
||||
case errNoopTracer:
|
||||
return // noop tracer has no traces
|
||||
default:
|
||||
cft.log.Debug().Err(err)
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// AddSpans assigns spans as base64 encoded protobuf otlp traces to provided
|
||||
// HTTP headers.
|
||||
func (cft *cfdTracer) AddSpans(headers http.Header) {
|
||||
if headers == nil {
|
||||
return
|
||||
}
|
||||
|
||||
enc := cft.GetSpans()
|
||||
// No need to add header if no traces
|
||||
if enc == "" {
|
||||
log.Error().Msgf("no traces provided and no error from exporter")
|
||||
return
|
||||
}
|
||||
|
||||
headers[CanonicalCloudflaredTracingHeader] = []string{enc}
|
||||
}
|
||||
|
||||
// End will set the OK status for the span and then end it.
|
||||
func End(span trace.Span) {
|
||||
endSpan(span, -1, codes.Ok, nil)
|
||||
}
|
||||
|
||||
// EndWithErrorStatus will set a status for the span and then end it.
|
||||
func EndWithErrorStatus(span trace.Span, err error) {
|
||||
endSpan(span, -1, codes.Error, err)
|
||||
@@ -166,6 +226,33 @@ func endSpan(span trace.Span, upstreamStatusCode int, spanStatusCode codes.Code,
|
||||
span.End()
|
||||
}
|
||||
|
||||
// extractTraceFromString will extract the trace information from the provided
|
||||
// propagated trace string context.
|
||||
func extractTraceFromString(ctx context.Context, trace string) (context.Context, bool) {
|
||||
if trace == "" {
|
||||
return ctx, false
|
||||
}
|
||||
// Jaeger specific separator
|
||||
parts := strings.Split(trace, separator)
|
||||
if len(parts) != 4 {
|
||||
return ctx, false
|
||||
}
|
||||
if parts[0] == "" {
|
||||
return ctx, false
|
||||
}
|
||||
// Correctly left pad the trace to a length of 32
|
||||
if len(parts[0]) < traceID128bitsWidth {
|
||||
left := traceID128bitsWidth - len(parts[0])
|
||||
parts[0] = strings.Repeat("0", left) + parts[0]
|
||||
trace = strings.Join(parts, separator)
|
||||
}
|
||||
|
||||
// Override the 'cf-trace-id' as 'uber-trace-id' so the jaeger propagator can extract it.
|
||||
traceHeader := map[string]string{TracerContextNameOverride: trace}
|
||||
remoteCtx := otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier(traceHeader))
|
||||
return remoteCtx, true
|
||||
}
|
||||
|
||||
// extractTrace attempts to check for a cf-trace-id from a request and return the
|
||||
// trace context with the provided http.Request.
|
||||
func extractTrace(req *http.Request) (context.Context, bool) {
|
||||
|
||||
+11
-6
@@ -14,38 +14,42 @@ import (
|
||||
)
|
||||
|
||||
func TestNewCfTracer(t *testing.T) {
|
||||
log := zerolog.Nop()
|
||||
req := httptest.NewRequest("GET", "http://localhost", nil)
|
||||
req.Header.Add(TracerContextName, "14cb070dde8e51fc5ae8514e69ba42ca:b38f1bf5eae406f3:0:1")
|
||||
tr := NewTracedRequest(req)
|
||||
tr := NewTracedHTTPRequest(req, &log)
|
||||
assert.NotNil(t, tr)
|
||||
assert.IsType(t, tracesdk.NewTracerProvider(), tr.TracerProvider)
|
||||
assert.IsType(t, &InMemoryOtlpClient{}, tr.exporter)
|
||||
}
|
||||
|
||||
func TestNewCfTracerMultiple(t *testing.T) {
|
||||
log := zerolog.Nop()
|
||||
req := httptest.NewRequest("GET", "http://localhost", nil)
|
||||
req.Header.Add(TracerContextName, "1241ce3ecdefc68854e8514e69ba42ca:b38f1bf5eae406f3:0:1")
|
||||
req.Header.Add(TracerContextName, "14cb070dde8e51fc5ae8514e69ba42ca:b38f1bf5eae406f3:0:1")
|
||||
tr := NewTracedRequest(req)
|
||||
tr := NewTracedHTTPRequest(req, &log)
|
||||
assert.NotNil(t, tr)
|
||||
assert.IsType(t, tracesdk.NewTracerProvider(), tr.TracerProvider)
|
||||
assert.IsType(t, &InMemoryOtlpClient{}, tr.exporter)
|
||||
}
|
||||
|
||||
func TestNewCfTracerNilHeader(t *testing.T) {
|
||||
log := zerolog.Nop()
|
||||
req := httptest.NewRequest("GET", "http://localhost", nil)
|
||||
req.Header[http.CanonicalHeaderKey(TracerContextName)] = nil
|
||||
tr := NewTracedRequest(req)
|
||||
tr := NewTracedHTTPRequest(req, &log)
|
||||
assert.NotNil(t, tr)
|
||||
assert.IsType(t, trace.NewNoopTracerProvider(), tr.TracerProvider)
|
||||
assert.IsType(t, &NoopOtlpClient{}, tr.exporter)
|
||||
}
|
||||
|
||||
func TestNewCfTracerInvalidHeaders(t *testing.T) {
|
||||
log := zerolog.Nop()
|
||||
req := httptest.NewRequest("GET", "http://localhost", nil)
|
||||
for _, test := range [][]string{nil, {""}} {
|
||||
req.Header[http.CanonicalHeaderKey(TracerContextName)] = test
|
||||
tr := NewTracedRequest(req)
|
||||
tr := NewTracedHTTPRequest(req, &log)
|
||||
assert.NotNil(t, tr)
|
||||
assert.IsType(t, trace.NewNoopTracerProvider(), tr.TracerProvider)
|
||||
assert.IsType(t, &NoopOtlpClient{}, tr.exporter)
|
||||
@@ -53,9 +57,10 @@ func TestNewCfTracerInvalidHeaders(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAddingSpansWithNilMap(t *testing.T) {
|
||||
log := zerolog.Nop()
|
||||
req := httptest.NewRequest("GET", "http://localhost", nil)
|
||||
req.Header.Add(TracerContextName, "14cb070dde8e51fc5ae8514e69ba42ca:b38f1bf5eae406f3:0:1")
|
||||
tr := NewTracedRequest(req)
|
||||
tr := NewTracedHTTPRequest(req, &log)
|
||||
|
||||
exporter := tr.exporter.(*InMemoryOtlpClient)
|
||||
|
||||
@@ -65,5 +70,5 @@ func TestAddingSpansWithNilMap(t *testing.T) {
|
||||
assert.NoError(t, err)
|
||||
|
||||
// a panic shouldn't occur
|
||||
tr.AddSpans(nil, &zerolog.Logger{})
|
||||
tr.AddSpans(nil)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,11 @@ import (
|
||||
)
|
||||
|
||||
type SessionManager interface {
|
||||
RegisterUdpSession(ctx context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeAfterIdleHint time.Duration) error
|
||||
// RegisterUdpSession is the call provided to cloudflared to handle an incoming
|
||||
// capnproto RegisterUdpSession request from the edge.
|
||||
RegisterUdpSession(ctx context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeAfterIdleHint time.Duration, traceContext string) (*RegisterUdpSessionResponse, error)
|
||||
// UnregisterUdpSession is the call provided to cloudflared to handle an incoming
|
||||
// capnproto UnregisterUdpSession request from the edge.
|
||||
UnregisterUdpSession(ctx context.Context, sessionID uuid.UUID, message string) error
|
||||
}
|
||||
|
||||
@@ -50,9 +54,17 @@ func (i SessionManager_PogsImpl) RegisterUdpSession(p tunnelrpc.SessionManager_r
|
||||
|
||||
closeIdleAfterHint := time.Duration(p.Params.CloseAfterIdleHint())
|
||||
|
||||
resp := RegisterUdpSessionResponse{}
|
||||
registrationErr := i.impl.RegisterUdpSession(p.Ctx, sessionID, dstIP, dstPort, closeIdleAfterHint)
|
||||
traceContext, err := p.Params.TraceContext()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, registrationErr := i.impl.RegisterUdpSession(p.Ctx, sessionID, dstIP, dstPort, closeIdleAfterHint, traceContext)
|
||||
if registrationErr != nil {
|
||||
// Make sure to assign a response even if one is not returned from register
|
||||
if resp == nil {
|
||||
resp = &RegisterUdpSessionResponse{}
|
||||
}
|
||||
resp.Err = registrationErr
|
||||
}
|
||||
|
||||
@@ -85,13 +97,17 @@ func (i SessionManager_PogsImpl) UnregisterUdpSession(p tunnelrpc.SessionManager
|
||||
}
|
||||
|
||||
type RegisterUdpSessionResponse struct {
|
||||
Err error
|
||||
Err error
|
||||
Spans []byte // Spans in protobuf format
|
||||
}
|
||||
|
||||
func (p *RegisterUdpSessionResponse) Marshal(s tunnelrpc.RegisterUdpSessionResponse) error {
|
||||
if p.Err != nil {
|
||||
return s.SetErr(p.Err.Error())
|
||||
}
|
||||
if err := s.SetSpans(p.Spans); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -103,6 +119,10 @@ func (p *RegisterUdpSessionResponse) Unmarshal(s tunnelrpc.RegisterUdpSessionRes
|
||||
if respErr != "" {
|
||||
p.Err = fmt.Errorf(respErr)
|
||||
}
|
||||
p.Spans, err = s.Spans()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -116,7 +136,7 @@ func (c SessionManager_PogsClient) Close() error {
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
func (c SessionManager_PogsClient) RegisterUdpSession(ctx context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeAfterIdleHint time.Duration) (*RegisterUdpSessionResponse, error) {
|
||||
func (c SessionManager_PogsClient) RegisterUdpSession(ctx context.Context, sessionID uuid.UUID, dstIP net.IP, dstPort uint16, closeAfterIdleHint time.Duration, traceContext string) (*RegisterUdpSessionResponse, error) {
|
||||
client := tunnelrpc.SessionManager{Client: c.Client}
|
||||
promise := client.RegisterUdpSession(ctx, func(p tunnelrpc.SessionManager_registerUdpSession_Params) error {
|
||||
if err := p.SetSessionId(sessionID[:]); err != nil {
|
||||
@@ -127,6 +147,7 @@ func (c SessionManager_PogsClient) RegisterUdpSession(ctx context.Context, sessi
|
||||
}
|
||||
p.SetDstPort(dstPort)
|
||||
p.SetCloseAfterIdleHint(int64(closeAfterIdleHint))
|
||||
p.SetTraceContext(traceContext)
|
||||
return nil
|
||||
})
|
||||
result, err := promise.Result().Struct()
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user