testing ae wkwkwk
Browse filesbruv i don't know
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+6
- Hasil OBS/2024-03-01 15-05-14.mkvAdded+3
- Hasil OBS/2024-03-05 07-38-44.mkvAdded+3
- Hasil OBS/2024-03-13 13-08-26.mkvAdded+3
- Hasil OBS/2024-03-21 08-06-23.mkvAdded+3
- Hasil OBS/2024-04-19 13-14-59.mkvAdded+3
- Hasil OBS/VPN.mp4Added+3
- Hasil OBS/snowflake-main/.gitignoreAdded+19
- Hasil OBS/snowflake-main/.gitlab-ci.ymlAdded+276
- Hasil OBS/snowflake-main/.gitmodulesAdded
- Hasil OBS/snowflake-main/.travis.ymlAdded+13
- Hasil OBS/snowflake-main/CONTRIBUTING.mdAdded+5
- Hasil OBS/snowflake-main/ChangeLogAdded+195
- Hasil OBS/snowflake-main/LICENSEAdded+32
- Hasil OBS/snowflake-main/README.mdAdded+109
- Hasil OBS/snowflake-main/VagrantfileAdded+67
- Hasil OBS/snowflake-main/broker/README.mdAdded+58
- Hasil OBS/snowflake-main/broker/amp.goAdded+77
- Hasil OBS/snowflake-main/broker/bridge-list.goAdded+94
- Hasil OBS/snowflake-main/broker/bridge-list_test.goAdded+64
- Hasil OBS/snowflake-main/broker/broker.goAdded+363
- Hasil OBS/snowflake-main/broker/http.goAdded+260
- Hasil OBS/snowflake-main/broker/ipc.goAdded+281
- Hasil OBS/snowflake-main/broker/metrics.goAdded+355
- Hasil OBS/snowflake-main/broker/prometheus.goAdded+83
- Hasil OBS/snowflake-main/broker/snowflake-broker_test.goAdded+1003
- Hasil OBS/snowflake-main/broker/snowflake-heap.goAdded+52
- Hasil OBS/snowflake-main/broker/sqs.goAdded+211
- Hasil OBS/snowflake-main/broker/sqs_test.goAdded+338
- Hasil OBS/snowflake-main/broker/test_geoipAdded+1236
- Hasil OBS/snowflake-main/broker/test_geoip6Added+693
- Hasil OBS/snowflake-main/client/README.mdAdded+111
- Hasil OBS/snowflake-main/client/lib/interfaces.goAdded+24
- Hasil OBS/snowflake-main/client/lib/lib_test.goAdded+221
- Hasil OBS/snowflake-main/client/lib/peers.goAdded+138
- Hasil OBS/snowflake-main/client/lib/rendezvous.goAdded+229
- Hasil OBS/snowflake-main/client/lib/rendezvous_ampcache.goAdded+127
- Hasil OBS/snowflake-main/client/lib/rendezvous_http.goAdded+80
- Hasil OBS/snowflake-main/client/lib/rendezvous_sqs.goAdded+139
- Hasil OBS/snowflake-main/client/lib/rendezvous_test.goAdded+398
- Hasil OBS/snowflake-main/client/lib/snowflake.goAdded+405
- Hasil OBS/snowflake-main/client/lib/turbotunnel.goAdded+68
- Hasil OBS/snowflake-main/client/lib/util.goAdded+71
- Hasil OBS/snowflake-main/client/lib/webrtc.goAdded+327
- Hasil OBS/snowflake-main/client/snowflake.goAdded+319
- Hasil OBS/snowflake-main/client/torrcAdded+9
- Hasil OBS/snowflake-main/client/torrc.localhostAdded+6
- Hasil OBS/snowflake-main/common/amp/armor_decoder.goAdded+136
- Hasil OBS/snowflake-main/common/amp/armor_encoder.goAdded+176
- Hasil OBS/snowflake-main/common/amp/armor_test.goAdded+226
52 unmodified lines53545552 unmodified lines*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text52 unmodified lines53545556575859606152 unmodified lines*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -textHasil[[:space:]]OBS/2024-03-01[[:space:]]15-05-14.mkv filter=lfs diff=lfs merge=lfs -textHasil[[:space:]]OBS/2024-03-05[[:space:]]07-38-44.mkv filter=lfs diff=lfs merge=lfs -textHasil[[:space:]]OBS/2024-03-13[[:space:]]13-08-26.mkv filter=lfs diff=lfs merge=lfs -textHasil[[:space:]]OBS/2024-03-21[[:space:]]08-06-23.mkv filter=lfs diff=lfs merge=lfs -textHasil[[:space:]]OBS/2024-04-19[[:space:]]13-14-59.mkv filter=lfs diff=lfs merge=lfs -textHasil[[:space:]]OBS/VPN.mp4 filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:dfa3175065e7665417632ff3b8264f69600bdb3ce352fed54c20b932a9c26667size 15742463123version https://git-lfs.github.com/spec/v1oid sha256:79b8f34ca64faf98c6c6254662e5fff86dd4b3a04cee6fe4a3db4038e0c53a2dsize 1104403179123version https://git-lfs.github.com/spec/v1oid sha256:9b37483becef0a7e0c3d123ec8ca0e1787e2f3d8f70683957592526e1bb057aasize 695890420123version https://git-lfs.github.com/spec/v1oid sha256:08017aaf84d704785fcdee22c4c4f4ef6fec63fadb8b5d32ee5624c05715736asize 2547140569123version https://git-lfs.github.com/spec/v1oid sha256:d4a0108128fb20fe809b41472a899a137e1badd43828ffea83191100d9e06b5esize 2039097475123version https://git-lfs.github.com/spec/v1oid sha256:d44160e5df71a9502030dbee338b6480ace719aa5a9a85ff266ad297c8717551size 714802112345678910111213141516171819*.swp*.swo*.swn*.swm.DS_Storedatadir/broker/brokerclient/clientserver/serverproxy/proxyprobetest/probetestsnowflake.logignore/
# from running the vagrant setup/.vagrant//sdk-tools-linux-*.zip*/android-ndk-*/tools/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
variables: DEBIAN_FRONTEND: noninteractive DEBIAN_OLD_STABLE: buster DEBIAN_STABLE: bullseye REPRODUCIBLE_FLAGS: -trimpath -ldflags=-buildid=
# set up apt for automated use.apt-template: &apt-template- export LC_ALL=C.UTF-8- export DEBIAN_FRONTEND=noninteractive- echo Etc/UTC > /etc/timezone- echo 'quiet "1";' 'APT::Install-Recommends "0";' 'APT::Install-Suggests "0";' 'APT::Acquire::Retries "20";' 'APT::Get::Assume-Yes "true";' 'Dpkg::Use-Pty "0";' > /etc/apt/apt.conf.d/99gitlab- apt-get update- apt-get dist-upgrade
# Set things up to use the OS-native packages for Go. Anything that# is downloaded by go during the `go fmt` stage is not coming from the# Debian/Ubuntu repo. So those would need to be packaged for this to# make it into Debian and/or Ubuntu..debian-native-template: &debian-native-template variables: GOPATH: /usr/share/gocode before_script: - apt-get update - apt-get -qy install --no-install-recommends build-essential ca-certificates git golang golang-github-cheekybits-genny-dev golang-github-jtolds-gls-dev golang-github-klauspost-reedsolomon-dev golang-github-lucas-clemente-quic-go-dev golang-github-smartystreets-assertions-dev golang-github-smartystreets-goconvey-dev golang-github-tjfoc-gmsm-dev golang-github-xtaci-kcp-dev golang-github-xtaci-smux-dev golang-golang-x-crypto-dev golang-golang-x-net-dev golang-goptlib-dev golang-golang-x-sys-dev golang-golang-x-text-dev golang-golang-x-xerrors-dev lbzip2
# use Go installed as part of the official, Debian-based Docker images.golang-docker-debian-template: &golang-docker-debian-template before_script: - apt-get update - apt-get -qy install --no-install-recommends ca-certificates git lbzip2
.go-test: &go-test - gofmt -d . - test -z "$(go fmt ./...)" - go vet ./... - go test -v -race ./...
- cd $CI_PROJECT_DIR/client/ - go get - go build $REPRODUCIBLE_FLAGS
.test-template: &test-template artifacts: name: "${CI_PROJECT_PATH}_${CI_JOB_STAGE}_${CI_JOB_ID}_${CI_COMMIT_REF_NAME}_${CI_COMMIT_SHA}" paths: - client/*.aar - client/*.jar - client/client expire_in: 1 week when: on_success after_script: - echo "Download debug artifacts from https://gitlab.com/${CI_PROJECT_PATH}/-/jobs" # this file changes every time but should not be cached - rm -f $GRADLE_USER_HOME/caches/modules-2/modules-2.lock - rm -rf $GRADLE_USER_HOME/caches/*/plugin-resolution/
# -- jobs ------------------------------------------------------------
android: image: golang:1.21-$DEBIAN_STABLE variables: ANDROID_HOME: /usr/lib/android-sdk LANG: C.UTF-8 cache: paths: - .gradle/wrapper - .gradle/caches <<: *test-template before_script: - *apt-template - apt-get install android-sdk-platform-23 android-sdk-platform-tools build-essential curl default-jdk-headless git gnupg unzip wget ca-certificates lbzip2
- ndk=android-ndk-r21e-linux-x86_64.zip - wget --continue --no-verbose https://dl.google.com/android/repository/$ndk - echo "ad7ce5467e18d40050dc51b8e7affc3e635c85bd8c59be62de32352328ed467e $ndk" > $ndk.sha256 - sha256sum -c $ndk.sha256 - unzip -q $ndk - rm ${ndk}* - mv android-ndk-* $ANDROID_HOME/ndk-bundle/
- chmod -R a+rX $ANDROID_HOME script: - *go-test - export GRADLE_USER_HOME=$CI_PROJECT_DIR/.gradle - go version - go env
- go get golang.org/x/mobile/cmd/gomobile - go get golang.org/x/mobile/cmd/gobind - go install golang.org/x/mobile/cmd/gobind - go install golang.org/x/mobile/cmd/gomobile - gomobile init
- cd $CI_PROJECT_DIR/client # gomobile builds a shared library not a CLI executable - sed -i 's,^package main$,package snowflakeclient,' *.go - go get golang.org/x/mobile/bind - gomobile bind -v -target=android $REPRODUCIBLE_FLAGS .
go-1.21: image: golang:1.21-$DEBIAN_STABLE <<: *golang-docker-debian-template <<: *test-template script: - *go-test
debian-testing: image: debian:testing <<: *debian-native-template <<: *test-template script: - *go-test
shadow-integration: image: golang:1.21-$DEBIAN_STABLE variables: SHADOW_VERSION: "193924aae0dab30ffda0abe29467f552949849fa" TGEN_VERSION: "v1.1.2" cache: key: sf-integration-$SHADOW_VERSION-$TGEN_VERSION paths: - /opt/ artifacts: paths: - shadow.data.tar.gz when: on_failure script: - apt-get update - apt-get install -y git tor - mkdir -p ~/.local/bin - mkdir -p ~/.local/src - export PATH=$PATH:$CI_PROJECT_DIR/opt/bin/
# Install shadow and tgen - pushd ~/.local/src - | if [ ! -f opt/shadow/bin/shadow ] then echo "The required version of shadow was not cached, building from source" git clone --shallow-since=2021-08-01 https://github.com/shadow/shadow.git pushd shadow/ git checkout $SHADOW_VERSION CONTAINER=debian:stable-slim ci/container_scripts/install_deps.sh CC=gcc CONTAINER=debian:stable-slim ci/container_scripts/install_extra_deps.sh export PATH="$HOME/.cargo/bin:${PATH}" ./setup build --jobs $(nproc) --prefix $CI_PROJECT_DIR/opt/ ./setup install popd fi - | if [ ! -f opt/shadow/bin/tgen ] then echo "The required version of tgen was not cached, building from source" git clone --branch $TGEN_VERSION --depth 1 https://github.com/shadow/tgen.git pushd tgen/ apt-get install -y cmake libglib2.0-dev libigraph-dev mkdir build && cd build cmake .. -DCMAKE_INSTALL_PREFIX=$CI_PROJECT_DIR/opt/ make make install popd fi install $CI_PROJECT_DIR/opt/bin/tgen ~/.local/bin/tgen - popd
# Apply snowflake patch(es) - | git clone --depth 1 https://github.com/cohosh/shadow-snowflake-minimal git am -3 shadow-snowflake-minimal/*.patch
# Install snowflake binaries to .local folder - | for app in "proxy" "client" "server" "broker" "probetest"; do pushd $app go build install $app ~/.local/bin/snowflake-$app popd done
# Install stun server - GOBIN=~/.local/bin go install github.com/gortc/stund@latest
# Run a minimal snowflake shadow experiment - pushd shadow-snowflake-minimal/ - shadow --log-level=debug --model-unblocked-syscall-latency=true snowflake-minimal.yaml > shadow.log - tar -czvf $CI_PROJECT_DIR/shadow.data.tar.gz shadow.data/
# Check to make sure streams succeeded - | if [ $(grep -c "stream-success" shadow.data/hosts/snowflakeclient/tgen.1006.stdout) = 10 ] then echo "All streams in shadow completed successfully" else echo "Shadow simulation failed" exit 1 fi
generate_tarball: stage: deploy image: golang:1.21-$DEBIAN_STABLE rules: - if: $CI_COMMIT_TAG script: - go mod vendor - tar czf ${CI_PROJECT_NAME}-${CI_COMMIT_TAG}.tar.gz --transform "s,^,${CI_PROJECT_NAME}-${CI_COMMIT_TAG}/," * after_script: - echo TAR_JOB_ID=$CI_JOB_ID >> generate_tarball.env artifacts: paths: - ${CI_PROJECT_NAME}-${CI_COMMIT_TAG}.tar.gz reports: dotenv: generate_tarball.env
release-job: stage: deploy image: registry.gitlab.com/gitlab-org/release-cli:latest rules: - if: $CI_COMMIT_TAG needs: - job: generate_tarball artifacts: true script: - echo "running release_job" release: name: 'Release $CI_COMMIT_TAG' description: 'Created using the release-cli' tag_name: '$CI_COMMIT_TAG' ref: '$CI_COMMIT_TAG' assets: links: - name: '${CI_PROJECT_NAME}-${CI_COMMIT_TAG}.tar.gz' url: '${CI_PROJECT_URL}/-/jobs/${TAR_JOB_ID}/artifacts/file/${CI_PROJECT_NAME}-${CI_COMMIT_TAG}.tar.gz' 12345678910111213language: go
dist: xenial
go_import_path: git.torproject.org/pluggable-transports/snowflake.git/v2
go: - 1.13.x
script: - test -z "$(go fmt ./...)" - go vet ./... - go test -v -race ./...12345
- When editing Go, please run `go fmt` before every commit.
- You may run tests locally with either `go test` or `npm test` for Go and JavaScript, respectively.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195Changes in version v2.9.1 - 2024-02-27- Issue 40335: Fix release job- Change deprecated io/ioutil package to io package- Bump versions of dependencies
Changes in version v2.9.0 - 2024-02-05- Issue 40285: Add vcs revision to version string- Issue 40294: Update recommended torrc options in client README- Issue 40306: Scrub space-separated IP addresses- Add proxy commandline option for probe server URL- Use SetNet setting in probest to ignore net.Interfaces error- Add probetest commandline option for STUN URL- Issue 26151: Implement SQS rendezvous in client and broker- Add broker metrics to track rendezvous method- Cosmetic code quality fixes- Bump versions of dependencies
Changes in version v2.8.1 - 2023-12-21- Issue 40276: Reduce allocations in encapsulation.ReadData- Issue 40310: Remove excessive logging for closed proxy connections- Issue 40278: Add network fix for old version of android to proxy- Bump versions of dependencies
Changes in version v2.8.0 - 2023-11-20- Issue 40069: Add outbound proxy support- Issue 40301: Fix for a bug in domain fronting configurations- Issue 40302: Remove throughput summary from proxy logger- Issue 40302: Change proxy stats logging to only log stats for traffic that occurred in the summary interval- Update renovate bot configuration to use Go 1.21- Bump versions of dependencies
Changes in version v2.7.0 - 2023-10-167142fa3 fix(proxy): Correctly close connection pipe when dealing with error6393af6 Remove proxy churn measurements from broker.a615e8b fix(proxy): remove _potential_ deadlockd434549 Maintain backward compatability with old clients9fdfb3d Randomly select front domain from comma-separated list5cdf52c Update dependencies1559963 chore(deps): update module github.com/xtaci/kcp-go/v5 to v5.6.360e66be Remove Golang 1.20 from CI Testing1d069ca Update CI targets to test android from golang 1.213a050c6 Use ShouldBeNil to check for nil valuese45e8e5 chore(deps): update module github.com/smartystreets/goconvey to v1.8.1f47ca18 chore(deps): update module gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/goptlib to v1.5.0106da49 chore(deps): update module github.com/pion/webrtc/v3 to v3.2.202844ac6 Update CI targets to include only Go 1.20 and 1.21f4e1ab9 chore(deps): update module golang.org/x/net to v0.15.0caaff70 Update module golang.org/x/sys to v0.12.0
Changes in version v2.6.1 - 2023-09-11- a3bfc28 Update module golang.org/x/crypto to v0.12.0- e37e15a Update golang Docker tag to v1.21- b632c7d Workaround for shadow in lieu of AF_NETLINK support- 0cb2975 Update module golang.org/x/net to v0.13.0 [SECURITY]- f73fe6e Keep the 'v' from the tag on the released .tar.gz- 8104732 Change DefaultRelayURL back to wss://snowflake.torproject.net/.- d932cb2 feat: add option to expose the stats by using metrics- af73ab7 Add renovate config- aaeab3f Update dependencies- 58c3121 Close temporary UDPSession in TestQueuePacketConnWriteToKCP.- 80980a3 Fix a comment left over from turbotunnel-quic.- 08d1c6d Bump minimum required version of go
Changes in version v2.6.0 - 2023-06-19- Issue 40243: Implement datachannel flow control at proxy- Issue 40087: Append Let's Encrypt ISRG Root X1 to cert pool- Issue 40198: Use IP_BIND_ADDRESS_NO_PORT when dialing the ORPort on linux- Move from gitweb to gitlab- Add warning log at broker when proxy does not connect with client- Fix unit tests after SDP validation- Soften non-critical log from error to warning- Issue 40231: Validate SDP offers and answers- Add scanner error check to ClusterCounter.Count- Fix server benchmark tests- Issue 40260: Use a sync.Pool to reuse QueuePacketConn buffers- Issue 40043: Restore ListenAndServe error in server- Update pion webrtc library versions- Issue 40108: Add outbound address config option to proxy- Issue 40260: Fix a data race in the Snowflake server- Issue 40216: Add utls-imitate, utls-nosni documentation to the README- Fix up/down traffic stats in standalone proxy- Issue 40226: Filter out ICE servers that are not STUN- Issue 40226: Update README to reflect the type of ICE servers we support- Issue 40226: Parse ICE servers using the pion/ice library function- Bring client torrc up to date with Tor Browser
Changes in version v2.5.1 - 2023-01-18- Issue 40249: Fix issue with Skip Hello Verify patch
Changes in version v2.5.0 - 2023-01-18- Issue 40249: Apply Skip Hello Verify Migration
Changes in version v2.4.3 - 2023-01-16- Fix version number in version.go
Changes in version v2.4.2 - 2023-01-13- Issue 40208: Enhance help info for capacity flag- Issue 40232: Update README and fix help output- Issue 40173: Increase clientIDAddrMapCapacity- Issue 40177: Manually unlock mutex in ClientMap.SendQueue- Issue 40177: Have SnowflakeClientConn implement io.WriterTo- Issue 40179: Reduce turbotunnel queueSize from 2048 to 512- Issue 40187/40199: Take ownership of buffer in QueuePacketConn QueueIncoming/WriteTo- Add more tests for URL encoded IPs (safelog)- Fix server flag name- Issue 40200: Use multiple parallel KCP state machines in the server- Add a num-turbotunnel server transport option- Issue: 40241: Switch default proxy STUN server to stun.l.google.com
Changes in version v2.4.1 - 2022-12-01- Issue 40224: Bug fix in utls roundtripper
Changes in version v2.4.0 - 2022-11-29- Fix proxy command line help output- Issue 40123: Reduce multicast DNS candidates- Add ICE ephemeral ports range setting- Reformat using Go 1.19- Update CI tests to include latest and minimum Go versions- Issue 40184: Use fixed unit for bandwidth logging- Update gorilla/websocket to v1.5.0- Issue 40175: Server performance improvements- Issue 40183: Change snowflake proxy log verbosity- Issue 40117: Display proxy NAT type in logs- Issue 40198: Add a `orport-srcaddr` server transport option- Add gofmt output to CI test- Issue 40185: Change bandwidth type from int to int64 to prevent overflow- Add version output support to snowflake- Issue 40229: Change regexes for ipv6 addresses to catch url-encoded addresses- Issue 40220: Close stale connections in standalone proxy
Changes in version v2.3.0 - 2022-06-23- Issue 40146: Avoid performing two NAT probe tests at startup- Issue 40134: Log messages from client NAT check failures are confusing- Issue 34075: Implement metrics to measure snowflake churn- Issue 28651: Prepare all pieces of the snowflake pipeline for a second snowflake bridge- Issue 40129: Distributed Snowflake Server Support
Changes in version v2.2.0 - 2022-05-25
- Issue 40099: Initialize SnowflakeListener.closed- Add connection failure events for proxy timeouts- Issue 40103: Fix proxy logging verb tense- Fix up and downstream metrics output for proxy- Issue 40054: uTLS for broker negotiation- Forward bridge fingerprint from client to broker (WIP, Issue 28651)- Issue 40104: Make it easier to configure proxy type- Remove version from ClientPollRequest- Issue 40124: Move tor-specific code out of library- Issue 40115: Scrub pt event logs- Issue 40127: Bump webrtc and dtls library versions- Bump version of webrtc and dtls to fix dtls CVEs- Issue 40141: Ensure library calls of events can be scrubbed
Changes in version v2.1.0 - 2022-02-08
- Issue 40098: Remove support for legacy one shot mode- Issue 40079: Make connection summary at proxy privacy preserving- Issue 40076: Add snowflake event API for notifications of connection events- Issue 40084: Increase capacity of client address map at the server- Issue 40060: Further clean up snowflake server logs- Issue 40089: Validate proxy and client supplied strings at broker- Issue 40014: Update version of DTLS library to include fingerprinting fixes- Issue 40075: Support recurring NAT type check in standalone proxy
Changes in version v2.0.0 - 2021-11-04
- Turn the standalone snowflake proxy code into a library- Clean up and reworked the snowflake client and server library code- Unify broker/bridge domains to *.torproject.net- Updates to the snowflake library documentation- New package functions to define and set a rendezvous method with thebroker- Factor out the broker geoip code into its own external library- Bug fix to check error calls in preparePeerConnection- Bug fixes in snowflake tests- Issue 40059: add the ability to pass in snowflake arguments through SOCKS- Increase buffer sizes for sending and receiving snowflake data- Issue 25985: rendezvous with the broker using AMP cache- Issue 40055: wait for the full poll interval between proxy polls
Changes in version v1.1.0 - 2021-07-13
- Refactors of the Snowflake broker code- Refactors of the Snowflake proxy code- Issue 40048: assign proxies based on self-reported client load- Issue 40052: fixed a memory leak in the server accept loop- Version bump of kcp and smux libraries- Bug fix to pass the correct client address to the Snowflake bridge metricscounter- Bug fixes to prevent race conditions in the Snowflake client
Changes in version v1.0.0 - 2021-06-07
- Initial release.1234567891011121314151617181920212223242526272829303132 This file contains the license for "Snowflake" a free software project which provides a WebRTC pluggable transport.
================================================================================Copyright (c) 2016, Serene Han, Arlo BreaultCopyright (c) 2019-2020, The Tor Project, Inc
Redistribution and use in source and binary forms, with or without modification,are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, thislist of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,this list of conditions and the following disclaimer in the documentation and/orother materials provided with the distribution.
* Neither the names of the copyright owners nor the names of itscontributors may be used to endorse or promote products derived from thissoftware without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ANDANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FORANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ONANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.================================================================================123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109# Snowflake
[](https://travis-ci.org/keroserene/snowflake)
Pluggable Transport using WebRTC, inspired by Flashproxy.
<!-- START doctoc generated TOC please keep comment here to allow auto update --><!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->**Table of Contents**
- [Structure of this Repository](#structure-of-this-repository)- [Usage](#usage) - [Using Snowflake with Tor](#using-snowflake-with-tor) - [Running a Snowflake Proxy](#running-a-snowflake-proxy) - [Using the Snowflake Library with Other Applications](#using-the-snowflake-library-with-other-applications)- [Test Environment](#test-environment)- [FAQ](#faq)- [More info and links](#more-info-and-links)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
### Structure of this Repository
- `broker/` contains code for the Snowflake broker- `doc/` contains Snowflake documentation and manpages- `client/` contains the Tor pluggable transport client and client library code- `common/` contains generic libraries used by multiple pieces of Snowflake- `proxy/` contains code for the Go standalone Snowflake proxy- `probetest/` contains code for a NAT probetesting service- `server/` contains the Tor pluggable transport server and server library code
### Usage
Snowflake is currently deployed as a pluggable transport for Tor.
#### Using Snowflake with Tor
To use the Snowflake client with Tor, you will need to add the appropriate `Bridge` and `ClientTransportPlugin` lines to your [torrc](https://2019.www.torproject.org/docs/tor-manual.html.en) file. See the [client README](client) for more information on building and running the Snowflake client.
#### Running a Snowflake Proxy
You can contribute to Snowflake by running a Snowflake proxy. We have the option to run a proxy in your browser or as a standalone Go program. See our [community documentation](https://community.torproject.org/relay/setup/snowflake/) for more details.
#### Using the Snowflake Library with Other Applications
Snowflake can be used as a Go API, and adheres to the [v2.1 pluggable transports specification](). For more information on using the Snowflake Go library, see the [Snowflake library documentation](doc/using-the-snowflake-library.md).
### Test Environment
There is a Docker-based test environment at https://github.com/cohosh/snowbox.
### FAQ
**Q: How does it work?**
In the Tor use-case:
1. Volunteers visit websites which host the "snowflake" proxy. (justlike flashproxy)2. Tor clients automatically find available browser proxies via the Broker(the domain fronted signaling channel).3. Tor client and browser proxy establish a WebRTC peer connection.4. Proxy connects to some relay.5. Tor occurs.
More detailed information about how clients, snowflake proxies, and the Brokerfit together on the way...
**Q: What are the benefits of this PT compared with other PTs?**
Snowflake combines the advantages of flashproxy and meek. Primarily:
- It has the convenience of Meek, but can support magnitudes moreusers with negligible CDN costs. (Domain fronting is only used for briefsignalling / NAT-piercing to setup the P2P WebRTC DataChannels which handlethe actual traffic.)
- Arbitrarily high numbers of volunteer proxies are possible like inflashproxy, but NATs are no longer a usability barrier - no need formanual port forwarding!
**Q: Why is this called Snowflake?**
It utilizes the "ICE" negotiation via WebRTC, and also involves a greatabundance of ephemeral and short-lived (and special!) volunteer proxies...
### More info and links
We have more documentation in the [Snowflake wiki](https://gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/-/wikis/home) and at https://snowflake.torproject.org/.
##### -- Android AAR Reproducible Build Setup --
Using `gomobile` it is possible to build snowflake as shared libraries for allthe architectures supported by Android. This is in the _.gitlab-ci.yml_, whichruns in GitLab CI. It is also possible to run this setup in a Virtual Machineusing [vagrant](https://www.vagrantup.com/). Just run `vagrant up` and it willcreate and provision the VM. `vagrant ssh` to get into the VM to use it as adevelopment environment.
##### uTLS Settings
Snowflake communicate with broker that serves as signaling server with TLS based domain fronting connection, which may be identified by its usage of Go language TLS stack.
uTLS is a software library designed to initiate the TLS Client Hello fingerprint of browsers or other popular software's TLS stack to evade censorship based on TLS client hello fingerprint with `-utls-imitate` . You can use `-version` to see a list of supported values.
Depending on client and server configuration, it may not always work as expected as not all extensions are correctly implemented.
You can also remove SNI (Server Name Indication) from client hello to evade censorship with `-utls-nosni`, not all servers supports this.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667require 'pathname'require 'tempfile'require 'yaml'
srvpath = Pathname.new(File.dirname(__FILE__)).realpathconfigfile = YAML.load_file(File.join(srvpath, "/.gitlab-ci.yml"))remote_url = 'https://gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake'
# set up essential environment variablesenv = configfile['variables']env = env.merge(configfile['android']['variables'])env['CI_PROJECT_DIR'] = '/builds/tpo/anti-censorship/pluggable-transports/snowflake'env_file = Tempfile.new('env')File.chmod(0644, env_file.path)env.each do |k,v| env_file.write("export #{k}='#{v}'\n")endenv_file.rewind
sourcepath = '/etc/profile.d/env.sh'header = "#!/bin/bash -ex\nsource #{sourcepath}\ncd $CI_PROJECT_DIR\n"
before_script_file = Tempfile.new('before_script')File.chmod(0755, before_script_file.path)before_script_file.write(header)configfile['android']['before_script'].flatten.each do |line| before_script_file.write(line) before_script_file.write("\n")endbefore_script_file.rewind
script_file = Tempfile.new('script')File.chmod(0755, script_file.path)script_file.write(header)configfile['android']['script'].flatten.each do |line| script_file.write(line) script_file.write("\n")endscript_file.rewind
Vagrant.configure("2") do |config| config.vm.box = "debian/bullseye64" config.vm.synced_folder '.', '/vagrant', disabled: true config.vm.provision "file", source: env_file.path, destination: 'env.sh' config.vm.provision :shell, inline: <<-SHELL set -ex mv ~vagrant/env.sh #{sourcepath} source #{sourcepath} test -d /go || mkdir /go mkdir -p $(dirname $CI_PROJECT_DIR) chown -R vagrant.vagrant $(dirname $CI_PROJECT_DIR) apt-get update apt-get -qy install --no-install-recommends git git clone #{remote_url} $CI_PROJECT_DIR chmod -R a+rX,u+w /go $CI_PROJECT_DIR chown -R vagrant.vagrant /go $CI_PROJECT_DIRSHELL config.vm.provision "file", source: before_script_file.path, destination: 'before_script.sh' config.vm.provision "file", source: script_file.path, destination: 'script.sh' config.vm.provision :shell, inline: '/home/vagrant/before_script.sh' config.vm.provision :shell, privileged: false, inline: '/home/vagrant/script.sh'
# remove this or comment it out to use VirtualBox instead of libvirt config.vm.provider :libvirt do |libvirt| libvirt.memory = 1536 endend12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758<!-- START doctoc generated TOC please keep comment here to allow auto update --><!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->**Table of Contents**
- [Overview](#overview)- [Running your own](#running-your-own)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
This is the Broker component of Snowflake.
### Overview
The Broker handles the rendezvous by matching SnowflakeClients with Proxies, and passing their WebRTC Session Descriptions(the "signaling" step). This allows Clients and Proxies to establisha Peer connection.
It is analogous to Flashproxy's[Facilitator](https://trac.torproject.org/projects/tor/wiki/FlashProxyFAQ),but bidirectional and domain-fronted.
The Broker expects:
- Clients to send their SDP offer in a POST request, which will then block until the Broker responds with the answer of the matched Proxy.- Proxies to announce themselves with a POST request, to which the Broker responds with some Client's SDP offer. The Proxy should then send a second POST request soon after containing its SDP answer, which the Broker passes back to the same Client.
### Running your own
The server uses TLS by default.There is a `--disable-tls` option for testing purposes,but you should use TLS in production.
The server automatically fetches certificatesfrom [Let's Encrypt](https://en.wikipedia.org/wiki/Let's_Encrypt) as needed.Use the `--acme-hostnames` option to tell the serverwhat hostnames it may request certificates for.You can optionally provide a contact email address,using the `--acme-email` option,so that Let's Encrypt can inform you of any problems.
In order to fetch certificates automatically,the server needs to open an additional HTTP listener on port 80.On Linux, you can use the `setcap` program,part of libcap2, to enable the broker to bind to low-numbered portswithout having to run as root:```setcap 'cap_net_bind_service=+ep' /usr/local/bin/broker```You can control the listening broker port with the --addr option.Port 443 is the default.
You'll need to provide the URL of the custom brokerto the client plugin using the `--url $URL` flag.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677package main
import ( "log" "net/http" "strings"
"gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/amp" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/messages")
// ampClientOffers is the AMP-speaking endpoint for client poll messages,// intended for access via an AMP cache. In contrast to the other clientOffers,// the client's encoded poll message is stored in the URL path rather than the// HTTP request body (because an AMP cache does not support POST), and the// encoded client poll response is sent back as AMP-armored HTML.func ampClientOffers(i *IPC, w http.ResponseWriter, r *http.Request) { // The encoded client poll message immediately follows the /amp/client/ // path prefix, so this function unfortunately needs to be aware of and // remote its own routing prefix. path := strings.TrimPrefix(r.URL.Path, "/amp/client/") if path == r.URL.Path { // The path didn't start with the expected prefix. This probably // indicates an internal bug. log.Println("ampClientOffers: unexpected prefix in path") w.WriteHeader(http.StatusInternalServerError) return }
var encPollReq []byte var response []byte var err error
encPollReq, err = amp.DecodePath(path) if err == nil { arg := messages.Arg{ Body: encPollReq, RemoteAddr: "", RendezvousMethod: messages.RendezvousAmpCache, } err = i.ClientOffers(arg, &response) } else { response, err = (&messages.ClientPollResponse{ Error: "cannot decode URL path", }).EncodePollResponse() }
if err != nil { // We couldn't even construct a JSON object containing an error // message :( Nothing to do but signal an error at the HTTP // layer. The AMP cache will translate this 500 status into a // 404 status. // https://amp.dev/documentation/guides-and-tutorials/learn/amp-caches-and-cors/amp-cache-urls/#redirect-%26-error-handling log.Printf("ampClientOffers: %v", err) w.WriteHeader(http.StatusInternalServerError) return }
w.Header().Set("Content-Type", "text/html") // Attempt to hint to an AMP cache not to waste resources caching this // document. "The Google AMP Cache considers any document fresh for at // least 15 seconds." // https://developers.google.com/amp/cache/overview#google-amp-cache-updates w.Header().Set("Cache-Control", "max-age=15") w.WriteHeader(http.StatusOK)
enc, err := amp.NewArmorEncoder(w) if err != nil { log.Printf("amp.NewArmorEncoder: %v", err) return } defer enc.Close()
if _, err := enc.Write(response); err != nil { log.Printf("ampClientOffers: unable to write answer: %v", err) }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394/* (*BridgeListHolderFileBased).LoadBridgeInfo loads a Snowflake Server bridge info description file, its format is as follows:
This file should be in newline-delimited JSON format(https://jsonlines.org/). For each line, the format of json data should be in the format of: {"displayName":"default", "webSocketAddress":"wss://snowflake.torproject.net/", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80A72"}
displayName:string is the name of this bridge. This value is not currently used programmatically.
webSocketAddress:string is the WebSocket URL of this bridge. This will be the address proxy used to connect to this snowflake server.
fingerprint:string is the identifier of the bridge. This will be used by a client to identify the bridge it wishes to connect to.
The existence of ANY other fields is NOT permitted.
The file will be considered invalid if there is at least one invalid json record. In this case, an error will be returned, and none of the records will be loaded.*/
package main
import ( "bufio" "bytes" "encoding/json" "errors" "io" "sync"
"gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/bridgefingerprint")
var ErrBridgeNotFound = errors.New("bridge not found")
func NewBridgeListHolder() BridgeListHolderFileBased { return &bridgeListHolder{}}
type bridgeListHolder struct { bridgeInfo map[bridgefingerprint.Fingerprint]BridgeInfo accessBridgeInfo sync.RWMutex}
type BridgeListHolder interface { GetBridgeInfo(bridgefingerprint.Fingerprint) (BridgeInfo, error)}
type BridgeListHolderFileBased interface { BridgeListHolder LoadBridgeInfo(reader io.Reader) error}
type BridgeInfo struct { DisplayName string `json:"displayName"` WebSocketAddress string `json:"webSocketAddress"` Fingerprint string `json:"fingerprint"`}
func (h *bridgeListHolder) GetBridgeInfo(fingerprint bridgefingerprint.Fingerprint) (BridgeInfo, error) { h.accessBridgeInfo.RLock() defer h.accessBridgeInfo.RUnlock() if bridgeInfo, ok := h.bridgeInfo[fingerprint]; ok { return bridgeInfo, nil } return BridgeInfo{}, ErrBridgeNotFound}
func (h *bridgeListHolder) LoadBridgeInfo(reader io.Reader) error { bridgeInfoMap := map[bridgefingerprint.Fingerprint]BridgeInfo{} inputScanner := bufio.NewScanner(reader) for inputScanner.Scan() { inputLine := inputScanner.Bytes() bridgeInfo := BridgeInfo{} decoder := json.NewDecoder(bytes.NewReader(inputLine)) decoder.DisallowUnknownFields() if err := decoder.Decode(&bridgeInfo); err != nil { return err }
var bridgeFingerprint bridgefingerprint.Fingerprint var err error if bridgeFingerprint, err = bridgefingerprint.FingerprintFromHexString(bridgeInfo.Fingerprint); err != nil { return err }
bridgeInfoMap[bridgeFingerprint] = bridgeInfo } h.accessBridgeInfo.Lock() defer h.accessBridgeInfo.Unlock() h.bridgeInfo = bridgeInfoMap return nil}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364package main
import ( "bytes" "encoding/hex" . "github.com/smartystreets/goconvey/convey" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/bridgefingerprint" "testing")
const DefaultBridges = `{"displayName":"default", "webSocketAddress":"wss://snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80A72"}`
const ImaginaryBridges = `{"displayName":"default", "webSocketAddress":"wss://snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80A72"}{"displayName":"imaginary-1", "webSocketAddress":"wss://imaginary-1-snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80B00"}{"displayName":"imaginary-2", "webSocketAddress":"wss://imaginary-2-snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80B01"}{"displayName":"imaginary-3", "webSocketAddress":"wss://imaginary-3-snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80B02"}{"displayName":"imaginary-4", "webSocketAddress":"wss://imaginary-4-snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80B03"}{"displayName":"imaginary-5", "webSocketAddress":"wss://imaginary-5-snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80B04"}{"displayName":"imaginary-6", "webSocketAddress":"wss://imaginary-6-snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80B05"}{"displayName":"imaginary-7", "webSocketAddress":"wss://imaginary-7-snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80B06"}{"displayName":"imaginary-8", "webSocketAddress":"wss://imaginary-8-snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80B07"}{"displayName":"imaginary-9", "webSocketAddress":"wss://imaginary-9-snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80B08"}{"displayName":"imaginary-10", "webSocketAddress":"wss://imaginary-10-snowflake.torproject.org", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80B09"}`
func TestBridgeLoad(t *testing.T) { Convey("load default list", t, func() { bridgeList := NewBridgeListHolder() So(bridgeList.LoadBridgeInfo(bytes.NewReader([]byte(DefaultBridges))), ShouldBeNil) { bridgeFingerprint := [20]byte{} { n, err := hex.Decode(bridgeFingerprint[:], []byte("2B280B23E1107BB62ABFC40DDCC8824814F80A72")) So(n, ShouldEqual, 20) So(err, ShouldBeNil) } Fingerprint, err := bridgefingerprint.FingerprintFromBytes(bridgeFingerprint[:]) So(err, ShouldBeNil) bridgeInfo, err := bridgeList.GetBridgeInfo(Fingerprint) So(err, ShouldBeNil) So(bridgeInfo.DisplayName, ShouldEqual, "default") So(bridgeInfo.WebSocketAddress, ShouldEqual, "wss://snowflake.torproject.org") } }) Convey("load imaginary list", t, func() { bridgeList := NewBridgeListHolder() So(bridgeList.LoadBridgeInfo(bytes.NewReader([]byte(ImaginaryBridges))), ShouldBeNil) { bridgeFingerprint := [20]byte{} { n, err := hex.Decode(bridgeFingerprint[:], []byte("2B280B23E1107BB62ABFC40DDCC8824814F80B07")) So(n, ShouldEqual, 20) So(err, ShouldBeNil) } Fingerprint, err := bridgefingerprint.FingerprintFromBytes(bridgeFingerprint[:]) So(err, ShouldBeNil) bridgeInfo, err := bridgeList.GetBridgeInfo(Fingerprint) So(err, ShouldBeNil) So(bridgeInfo.DisplayName, ShouldEqual, "imaginary-8") So(bridgeInfo.WebSocketAddress, ShouldEqual, "wss://imaginary-8-snowflake.torproject.org") } })}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363/*Broker acts as the HTTP signaling channel.It matches clients and snowflake proxies by passing correspondingSessionDescriptions in order to negotiate a WebRTC connection.*/package main
import ( "bytes" "container/heap" "context" "crypto/tls" "flag" "io" "log" "net/http" "os" "os/signal" "strings" "sync" "syscall" "time"
"gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/bridgefingerprint"
"github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/namematcher" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/safelog" "golang.org/x/crypto/acme/autocert")
type BrokerContext struct { snowflakes *SnowflakeHeap restrictedSnowflakes *SnowflakeHeap // Maps keeping track of snowflakeIDs required to match SDP answers from // the second http POST. Restricted snowflakes can only be matched up with // clients behind an unrestricted NAT. idToSnowflake map[string]*Snowflake // Synchronization for the snowflake map and heap snowflakeLock sync.Mutex proxyPolls chan *ProxyPoll metrics *Metrics
bridgeList BridgeListHolderFileBased allowedRelayPattern string presumedPatternForLegacyClient string}
func (ctx *BrokerContext) GetBridgeInfo(fingerprint bridgefingerprint.Fingerprint) (BridgeInfo, error) { return ctx.bridgeList.GetBridgeInfo(fingerprint)}
func NewBrokerContext(metricsLogger *log.Logger) *BrokerContext { snowflakes := new(SnowflakeHeap) heap.Init(snowflakes) rSnowflakes := new(SnowflakeHeap) heap.Init(rSnowflakes) metrics, err := NewMetrics(metricsLogger)
if err != nil { panic(err.Error()) }
if metrics == nil { panic("Failed to create metrics") }
bridgeListHolder := NewBridgeListHolder()
const DefaultBridges = `{"displayName":"default", "webSocketAddress":"wss://snowflake.torproject.net/", "fingerprint":"2B280B23E1107BB62ABFC40DDCC8824814F80A72"}` bridgeListHolder.LoadBridgeInfo(bytes.NewReader([]byte(DefaultBridges)))
return &BrokerContext{ snowflakes: snowflakes, restrictedSnowflakes: rSnowflakes, idToSnowflake: make(map[string]*Snowflake), proxyPolls: make(chan *ProxyPoll), metrics: metrics, bridgeList: bridgeListHolder, }}
// Proxies may poll for client offers concurrently.type ProxyPoll struct { id string proxyType string natType string clients int offerChannel chan *ClientOffer}
// Registers a Snowflake and waits for some Client to send an offer,// as part of the polling logic of the proxy handler.func (ctx *BrokerContext) RequestOffer(id string, proxyType string, natType string, clients int) *ClientOffer { request := new(ProxyPoll) request.id = id request.proxyType = proxyType request.natType = natType request.clients = clients request.offerChannel = make(chan *ClientOffer) ctx.proxyPolls <- request // Block until an offer is available, or timeout which sends a nil offer. offer := <-request.offerChannel return offer}
// goroutine which matches clients to proxies and sends SDP offers along.// Safely processes proxy requests, responding to them with either an available// client offer or nil on timeout / none are available.func (ctx *BrokerContext) Broker() { for request := range ctx.proxyPolls { snowflake := ctx.AddSnowflake(request.id, request.proxyType, request.natType, request.clients) // Wait for a client to avail an offer to the snowflake. go func(request *ProxyPoll) { select { case offer := <-snowflake.offerChannel: request.offerChannel <- offer case <-time.After(time.Second * ProxyTimeout): // This snowflake is no longer available to serve clients. ctx.snowflakeLock.Lock() defer ctx.snowflakeLock.Unlock() if snowflake.index != -1 { if request.natType == NATUnrestricted { heap.Remove(ctx.snowflakes, snowflake.index) } else { heap.Remove(ctx.restrictedSnowflakes, snowflake.index) } ctx.metrics.promMetrics.AvailableProxies.With(prometheus.Labels{"nat": request.natType, "type": request.proxyType}).Dec() delete(ctx.idToSnowflake, snowflake.id) close(request.offerChannel) } } }(request) }}
// Create and add a Snowflake to the heap.// Required to keep track of proxies between providing them// with an offer and awaiting their second POST with an answer.func (ctx *BrokerContext) AddSnowflake(id string, proxyType string, natType string, clients int) *Snowflake { snowflake := new(Snowflake) snowflake.id = id snowflake.clients = clients snowflake.proxyType = proxyType snowflake.natType = natType snowflake.offerChannel = make(chan *ClientOffer) snowflake.answerChannel = make(chan string) ctx.snowflakeLock.Lock() if natType == NATUnrestricted { heap.Push(ctx.snowflakes, snowflake) } else { heap.Push(ctx.restrictedSnowflakes, snowflake) } ctx.metrics.promMetrics.AvailableProxies.With(prometheus.Labels{"nat": natType, "type": proxyType}).Inc() ctx.idToSnowflake[id] = snowflake ctx.snowflakeLock.Unlock() return snowflake}
func (ctx *BrokerContext) InstallBridgeListProfile(reader io.Reader, relayPattern, presumedPatternForLegacyClient string) error { if err := ctx.bridgeList.LoadBridgeInfo(reader); err != nil { return err } ctx.allowedRelayPattern = relayPattern ctx.presumedPatternForLegacyClient = presumedPatternForLegacyClient return nil}
func (ctx *BrokerContext) CheckProxyRelayPattern(pattern string, nonSupported bool) bool { if nonSupported { pattern = ctx.presumedPatternForLegacyClient } proxyPattern := namematcher.NewNameMatcher(pattern) brokerPattern := namematcher.NewNameMatcher(ctx.allowedRelayPattern) return proxyPattern.IsSupersetOf(brokerPattern)}
// Client offer contains an SDP, bridge fingerprint and the NAT type of the clienttype ClientOffer struct { natType string sdp []byte fingerprint []byte}
func main() { var acmeEmail string var acmeHostnamesCommas string var acmeCertCacheDir string var addr string var geoipDatabase string var geoip6Database string var bridgeListFilePath, allowedRelayPattern, presumedPatternForLegacyClient string var brokerSQSQueueName, brokerSQSQueueRegion string var disableTLS bool var certFilename, keyFilename string var disableGeoip bool var metricsFilename string var unsafeLogging bool
flag.StringVar(&acmeEmail, "acme-email", "", "optional contact email for Let's Encrypt notifications") flag.StringVar(&acmeHostnamesCommas, "acme-hostnames", "", "comma-separated hostnames for TLS certificate") flag.StringVar(&certFilename, "cert", "", "TLS certificate file") flag.StringVar(&keyFilename, "key", "", "TLS private key file") flag.StringVar(&acmeCertCacheDir, "acme-cert-cache", "acme-cert-cache", "directory in which certificates should be cached") flag.StringVar(&addr, "addr", ":443", "address to listen on") flag.StringVar(&geoipDatabase, "geoipdb", "/usr/share/tor/geoip", "path to correctly formatted geoip database mapping IPv4 address ranges to country codes") flag.StringVar(&geoip6Database, "geoip6db", "/usr/share/tor/geoip6", "path to correctly formatted geoip database mapping IPv6 address ranges to country codes") flag.StringVar(&bridgeListFilePath, "bridge-list-path", "", "file path for bridgeListFile") flag.StringVar(&allowedRelayPattern, "allowed-relay-pattern", "", "allowed pattern for relay host name") flag.StringVar(&presumedPatternForLegacyClient, "default-relay-pattern", "", "presumed pattern for legacy client") flag.StringVar(&brokerSQSQueueName, "broker-sqs-name", "", "name of broker SQS queue to listen for incoming messages on") flag.StringVar(&brokerSQSQueueRegion, "broker-sqs-region", "", "name of AWS region of broker SQS queue") flag.BoolVar(&disableTLS, "disable-tls", false, "don't use HTTPS") flag.BoolVar(&disableGeoip, "disable-geoip", false, "don't use geoip for stats collection") flag.StringVar(&metricsFilename, "metrics-log", "", "path to metrics logging output") flag.BoolVar(&unsafeLogging, "unsafe-logging", false, "prevent logs from being scrubbed") flag.Parse()
var err error var metricsFile io.Writer var logOutput io.Writer = os.Stderr if unsafeLogging { log.SetOutput(logOutput) } else { // We want to send the log output through our scrubber first log.SetOutput(&safelog.LogScrubber{Output: logOutput}) }
log.SetFlags(log.LstdFlags | log.LUTC)
if metricsFilename != "" { metricsFile, err = os.OpenFile(metricsFilename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil { log.Fatal(err.Error()) } } else { metricsFile = os.Stdout }
metricsLogger := log.New(metricsFile, "", 0)
ctx := NewBrokerContext(metricsLogger)
if bridgeListFilePath != "" { bridgeListFile, err := os.Open(bridgeListFilePath) if err != nil { log.Fatal(err.Error()) } err = ctx.InstallBridgeListProfile(bridgeListFile, allowedRelayPattern, presumedPatternForLegacyClient) if err != nil { log.Fatal(err.Error()) } }
if !disableGeoip { err = ctx.metrics.LoadGeoipDatabases(geoipDatabase, geoip6Database) if err != nil { log.Fatal(err.Error()) } }
go ctx.Broker()
i := &IPC{ctx}
http.HandleFunc("/robots.txt", robotsTxtHandler)
http.Handle("/proxy", SnowflakeHandler{i, proxyPolls}) http.Handle("/client", SnowflakeHandler{i, clientOffers}) http.Handle("/answer", SnowflakeHandler{i, proxyAnswers}) http.Handle("/debug", SnowflakeHandler{i, debugHandler}) http.Handle("/metrics", MetricsHandler{metricsFilename, metricsHandler}) http.Handle("/prometheus", promhttp.HandlerFor(ctx.metrics.promMetrics.registry, promhttp.HandlerOpts{}))
http.Handle("/amp/client/", SnowflakeHandler{i, ampClientOffers})
server := http.Server{ Addr: addr, }
// Run SQS Handler to continuously poll and process messages from SQS if brokerSQSQueueName != "" && brokerSQSQueueRegion != "" { log.Printf("Loading SQSHandler using SQS Queue %s in region %s\n", brokerSQSQueueName, brokerSQSQueueRegion) sqsHandlerContext := context.Background() cfg, err := config.LoadDefaultConfig(sqsHandlerContext, config.WithRegion(brokerSQSQueueRegion)) if err != nil { log.Fatal(err) } client := sqs.NewFromConfig(cfg) sqsHandler, err := newSQSHandler(sqsHandlerContext, client, brokerSQSQueueName, brokerSQSQueueRegion, i) if err != nil { log.Fatal(err) } go sqsHandler.PollAndHandleMessages(sqsHandlerContext) }
sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGHUP)
// go routine to handle a SIGHUP signal to allow the broker operator to send // a SIGHUP signal when the geoip database files are updated, without requiring // a restart of the broker go func() { for { signal := <-sigChan log.Printf("Received signal: %s. Reloading geoip databases.", signal) if err = ctx.metrics.LoadGeoipDatabases(geoipDatabase, geoip6Database); err != nil { log.Fatalf("reload of Geo IP databases on signal %s returned error: %v", signal, err) } } }()
// Handle the various ways of setting up TLS. The legal configurations // are: // --acme-hostnames (with optional --acme-email and/or --acme-cert-cache) // --cert and --key together // --disable-tls // The outputs of this block of code are the disableTLS, // needHTTP01Listener, certManager, and getCertificate variables. if acmeHostnamesCommas != "" { acmeHostnames := strings.Split(acmeHostnamesCommas, ",") log.Printf("ACME hostnames: %q", acmeHostnames)
var cache autocert.Cache if err = os.MkdirAll(acmeCertCacheDir, 0700); err != nil { log.Printf("Warning: Couldn't create cache directory %q (reason: %s) so we're *not* using our certificate cache.", acmeCertCacheDir, err) } else { cache = autocert.DirCache(acmeCertCacheDir) }
certManager := autocert.Manager{ Cache: cache, Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist(acmeHostnames...), Email: acmeEmail, } go func() { log.Printf("Starting HTTP-01 listener") log.Fatal(http.ListenAndServe(":80", certManager.HTTPHandler(nil))) }()
server.TLSConfig = &tls.Config{GetCertificate: certManager.GetCertificate} err = server.ListenAndServeTLS("", "") } else if certFilename != "" && keyFilename != "" { if acmeEmail != "" || acmeHostnamesCommas != "" { log.Fatalf("The --cert and --key options are not allowed with --acme-email or --acme-hostnames.") } err = server.ListenAndServeTLS(certFilename, keyFilename) } else if disableTLS { err = server.ListenAndServe() } else { log.Fatal("the --acme-hostnames, --cert and --key, or --disable-tls option is required") }
if err != nil { log.Fatal(err) }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260package main
import ( "bytes" "errors" "fmt" "io" "log" "net/http" "os"
"gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/messages")
const ( readLimit = 100000 // Maximum number of bytes to be read from an HTTP request)
// Implements the http.Handler interfacetype SnowflakeHandler struct { *IPC handle func(*IPC, http.ResponseWriter, *http.Request)}
func (sh SnowflakeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Session-ID") // Return early if it's CORS preflight. if "OPTIONS" == r.Method { return } sh.handle(sh.IPC, w, r)}
// Implements the http.Handler interfacetype MetricsHandler struct { logFilename string handle func(string, http.ResponseWriter, *http.Request)}
func (mh MetricsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Session-ID") // Return early if it's CORS preflight. if "OPTIONS" == r.Method { return } mh.handle(mh.logFilename, w, r)}
func robotsTxtHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") if _, err := w.Write([]byte("User-agent: *\nDisallow: /\n")); err != nil { log.Printf("robotsTxtHandler unable to write, with this error: %v", err) }}
func metricsHandler(metricsFilename string, w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8")
if metricsFilename == "" { http.NotFound(w, r) return } metricsFile, err := os.OpenFile(metricsFilename, os.O_RDONLY, 0644) if err != nil { log.Println("Error opening metrics file for reading") http.NotFound(w, r) return }
if _, err := io.Copy(w, metricsFile); err != nil { log.Printf("copying metricsFile returned error: %v", err) }}
func debugHandler(i *IPC, w http.ResponseWriter, r *http.Request) { var response string
err := i.Debug(new(interface{}), &response) if err != nil { log.Println(err) w.WriteHeader(http.StatusInternalServerError) return }
if _, err := w.Write([]byte(response)); err != nil { log.Printf("writing proxy information returned error: %v ", err) }}
/*For snowflake proxies to request a client from the Broker.*/func proxyPolls(i *IPC, w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, readLimit)) if err != nil { log.Println("Invalid data.", err.Error()) w.WriteHeader(http.StatusBadRequest) return }
arg := messages.Arg{ Body: body, RemoteAddr: r.RemoteAddr, }
var response []byte err = i.ProxyPolls(arg, &response) switch { case err == nil: case errors.Is(err, messages.ErrBadRequest): w.WriteHeader(http.StatusBadRequest) return case errors.Is(err, messages.ErrInternal): fallthrough default: log.Println(err) w.WriteHeader(http.StatusInternalServerError) return }
if _, err := w.Write(response); err != nil { log.Printf("proxyPolls unable to write offer with error: %v", err) }}
/*Expects a WebRTC SDP offer in the Request to give to an assignedsnowflake proxy, which responds with the SDP answer to be sent inthe HTTP response back to the client.*/func clientOffers(i *IPC, w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, readLimit)) if err != nil { log.Printf("Error reading client request: %s", err.Error()) w.WriteHeader(http.StatusBadRequest) return }
err = validateSDP(body) if err != nil { log.Println("Error client SDP: ", err.Error()) w.WriteHeader(http.StatusBadRequest) return }
// Handle the legacy version // // We support two client message formats. The legacy format is for backwards // compatability and relies heavily on HTTP headers and status codes to convey // information. isLegacy := false if len(body) > 0 && body[0] == '{' { isLegacy = true req := messages.ClientPollRequest{ Offer: string(body), NAT: r.Header.Get("Snowflake-NAT-Type"), } body, err = req.EncodeClientPollRequest() if err != nil { log.Printf("Error shimming the legacy request: %s", err.Error()) w.WriteHeader(http.StatusInternalServerError) return } }
arg := messages.Arg{ Body: body, RemoteAddr: "", RendezvousMethod: messages.RendezvousHttp, }
var response []byte err = i.ClientOffers(arg, &response) if err != nil { log.Println(err) w.WriteHeader(http.StatusInternalServerError) return }
if isLegacy { resp, err := messages.DecodeClientPollResponse(response) if err != nil { log.Println(err) w.WriteHeader(http.StatusInternalServerError) return } switch resp.Error { case "": response = []byte(resp.Answer) case messages.StrNoProxies: w.WriteHeader(http.StatusServiceUnavailable) return case messages.StrTimedOut: w.WriteHeader(http.StatusGatewayTimeout) return default: panic("unknown error") } }
if _, err := w.Write(response); err != nil { log.Printf("clientOffers unable to write answer with error: %v", err) }}
/*Expects snowflake proxies which have previously successfully receivedan offer from proxyHandler to respond with an answer in an HTTP POST,which the broker will pass back to the original client.*/func proxyAnswers(i *IPC, w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, readLimit)) if err != nil { log.Println("Invalid data.", err.Error()) w.WriteHeader(http.StatusBadRequest) return }
err = validateSDP(body) if err != nil { log.Println("Error proxy SDP: ", err.Error()) w.WriteHeader(http.StatusBadRequest) return }
arg := messages.Arg{ Body: body, RemoteAddr: "", }
var response []byte err = i.ProxyAnswers(arg, &response) switch { case err == nil: case errors.Is(err, messages.ErrBadRequest): w.WriteHeader(http.StatusBadRequest) return case errors.Is(err, messages.ErrInternal): fallthrough default: log.Println(err) w.WriteHeader(http.StatusInternalServerError) return }
if _, err := w.Write(response); err != nil { log.Printf("proxyAnswers unable to write answer response with error: %v", err) }}
func validateSDP(SDP []byte) error { // TODO: more validation likely needed if !bytes.Contains(SDP, []byte("a=candidate")) { return fmt.Errorf("SDP contains no candidate") }
return nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281package main
import ( "container/heap" "encoding/hex" "fmt" "log" "net" "time"
"gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/bridgefingerprint"
"github.com/prometheus/client_golang/prometheus" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/messages")
const ( ClientTimeout = 10 ProxyTimeout = 10
NATUnknown = "unknown" NATRestricted = "restricted" NATUnrestricted = "unrestricted")
type IPC struct { ctx *BrokerContext}
func (i *IPC) Debug(_ interface{}, response *string) error { var unknowns int var natRestricted, natUnrestricted, natUnknown int proxyTypes := make(map[string]int)
i.ctx.snowflakeLock.Lock() s := fmt.Sprintf("current snowflakes available: %d\n", len(i.ctx.idToSnowflake)) for _, snowflake := range i.ctx.idToSnowflake { if messages.KnownProxyTypes[snowflake.proxyType] { proxyTypes[snowflake.proxyType]++ } else { unknowns++ }
switch snowflake.natType { case NATRestricted: natRestricted++ case NATUnrestricted: natUnrestricted++ default: natUnknown++ }
} i.ctx.snowflakeLock.Unlock()
for pType, num := range proxyTypes { s += fmt.Sprintf("\t%s proxies: %d\n", pType, num) } s += fmt.Sprintf("\tunknown proxies: %d", unknowns)
s += fmt.Sprintf("\nNAT Types available:") s += fmt.Sprintf("\n\trestricted: %d", natRestricted) s += fmt.Sprintf("\n\tunrestricted: %d", natUnrestricted) s += fmt.Sprintf("\n\tunknown: %d", natUnknown)
*response = s return nil}
func (i *IPC) ProxyPolls(arg messages.Arg, response *[]byte) error { sid, proxyType, natType, clients, relayPattern, relayPatternSupported, err := messages.DecodeProxyPollRequestWithRelayPrefix(arg.Body) if err != nil { return messages.ErrBadRequest }
if !relayPatternSupported { i.ctx.metrics.lock.Lock() i.ctx.metrics.proxyPollWithoutRelayURLExtension++ i.ctx.metrics.promMetrics.ProxyPollWithoutRelayURLExtensionTotal.With(prometheus.Labels{"nat": natType, "type": proxyType}).Inc() i.ctx.metrics.lock.Unlock() } else { i.ctx.metrics.lock.Lock() i.ctx.metrics.proxyPollWithRelayURLExtension++ i.ctx.metrics.promMetrics.ProxyPollWithRelayURLExtensionTotal.With(prometheus.Labels{"nat": natType, "type": proxyType}).Inc() i.ctx.metrics.lock.Unlock() }
if !i.ctx.CheckProxyRelayPattern(relayPattern, !relayPatternSupported) { i.ctx.metrics.lock.Lock() i.ctx.metrics.proxyPollRejectedWithRelayURLExtension++ i.ctx.metrics.promMetrics.ProxyPollRejectedForRelayURLExtensionTotal.With(prometheus.Labels{"nat": natType, "type": proxyType}).Inc() i.ctx.metrics.lock.Unlock()
log.Printf("bad request: rejected relay pattern from proxy = %v", messages.ErrBadRequest) b, err := messages.EncodePollResponseWithRelayURL("", false, "", "", "incorrect relay pattern") *response = b if err != nil { return messages.ErrInternal } return nil }
// Log geoip stats remoteIP, _, err := net.SplitHostPort(arg.RemoteAddr) if err != nil { log.Println("Warning: cannot process proxy IP: ", err.Error()) } else { i.ctx.metrics.lock.Lock() i.ctx.metrics.UpdateCountryStats(remoteIP, proxyType, natType) i.ctx.metrics.lock.Unlock() }
var b []byte
// Wait for a client to avail an offer to the snowflake, or timeout if nil. offer := i.ctx.RequestOffer(sid, proxyType, natType, clients)
if offer == nil { i.ctx.metrics.lock.Lock() i.ctx.metrics.proxyIdleCount++ i.ctx.metrics.promMetrics.ProxyPollTotal.With(prometheus.Labels{"nat": natType, "status": "idle"}).Inc() i.ctx.metrics.lock.Unlock()
b, err = messages.EncodePollResponse("", false, "") if err != nil { return messages.ErrInternal }
*response = b return nil }
i.ctx.metrics.promMetrics.ProxyPollTotal.With(prometheus.Labels{"nat": natType, "status": "matched"}).Inc() var relayURL string bridgeFingerprint, err := bridgefingerprint.FingerprintFromBytes(offer.fingerprint) if err != nil { return messages.ErrBadRequest } if info, err := i.ctx.bridgeList.GetBridgeInfo(bridgeFingerprint); err != nil { return err } else { relayURL = info.WebSocketAddress } b, err = messages.EncodePollResponseWithRelayURL(string(offer.sdp), true, offer.natType, relayURL, "") if err != nil { return messages.ErrInternal } *response = b
return nil}
func sendClientResponse(resp *messages.ClientPollResponse, response *[]byte) error { data, err := resp.EncodePollResponse() if err != nil { log.Printf("error encoding answer") return messages.ErrInternal } else { *response = []byte(data) return nil }}
func (i *IPC) ClientOffers(arg messages.Arg, response *[]byte) error {
startTime := time.Now()
req, err := messages.DecodeClientPollRequest(arg.Body) if err != nil { return sendClientResponse(&messages.ClientPollResponse{Error: err.Error()}, response) }
offer := &ClientOffer{ natType: req.NAT, sdp: []byte(req.Offer), }
fingerprint, err := hex.DecodeString(req.Fingerprint) if err != nil { return sendClientResponse(&messages.ClientPollResponse{Error: err.Error()}, response) }
BridgeFingerprint, err := bridgefingerprint.FingerprintFromBytes(fingerprint) if err != nil { return sendClientResponse(&messages.ClientPollResponse{Error: err.Error()}, response) }
if _, err := i.ctx.GetBridgeInfo(BridgeFingerprint); err != nil { return err }
offer.fingerprint = BridgeFingerprint.ToBytes()
snowflake := i.matchSnowflake(offer.natType) if snowflake != nil { snowflake.offerChannel <- offer } else { i.ctx.metrics.lock.Lock() i.ctx.metrics.clientDeniedCount[arg.RendezvousMethod]++ i.ctx.metrics.promMetrics.ClientPollTotal.With(prometheus.Labels{"nat": offer.natType, "status": "denied", "rendezvous_method": string(arg.RendezvousMethod)}).Inc() if offer.natType == NATUnrestricted { i.ctx.metrics.clientUnrestrictedDeniedCount[arg.RendezvousMethod]++ } else { i.ctx.metrics.clientRestrictedDeniedCount[arg.RendezvousMethod]++ } i.ctx.metrics.lock.Unlock() resp := &messages.ClientPollResponse{Error: messages.StrNoProxies} return sendClientResponse(resp, response) }
// Wait for the answer to be returned on the channel or timeout. select { case answer := <-snowflake.answerChannel: i.ctx.metrics.lock.Lock() i.ctx.metrics.clientProxyMatchCount[arg.RendezvousMethod]++ i.ctx.metrics.promMetrics.ClientPollTotal.With(prometheus.Labels{"nat": offer.natType, "status": "matched", "rendezvous_method": string(arg.RendezvousMethod)}).Inc() i.ctx.metrics.lock.Unlock() resp := &messages.ClientPollResponse{Answer: answer} err = sendClientResponse(resp, response) // Initial tracking of elapsed time. i.ctx.metrics.clientRoundtripEstimate = time.Since(startTime) / time.Millisecond case <-time.After(time.Second * ClientTimeout): log.Println("Client: Timed out.") resp := &messages.ClientPollResponse{Error: messages.StrTimedOut} err = sendClientResponse(resp, response) }
i.ctx.snowflakeLock.Lock() i.ctx.metrics.promMetrics.AvailableProxies.With(prometheus.Labels{"nat": snowflake.natType, "type": snowflake.proxyType}).Dec() delete(i.ctx.idToSnowflake, snowflake.id) i.ctx.snowflakeLock.Unlock()
return err}
func (i *IPC) matchSnowflake(natType string) *Snowflake { i.ctx.snowflakeLock.Lock() defer i.ctx.snowflakeLock.Unlock()
// Proiritize known restricted snowflakes for unrestricted clients if natType == NATUnrestricted && i.ctx.restrictedSnowflakes.Len() > 0 { return heap.Pop(i.ctx.restrictedSnowflakes).(*Snowflake) }
if i.ctx.snowflakes.Len() > 0 { return heap.Pop(i.ctx.snowflakes).(*Snowflake) }
return nil}
func (i *IPC) ProxyAnswers(arg messages.Arg, response *[]byte) error { answer, id, err := messages.DecodeAnswerRequest(arg.Body) if err != nil || answer == "" { return messages.ErrBadRequest }
var success = true i.ctx.snowflakeLock.Lock() snowflake, ok := i.ctx.idToSnowflake[id] i.ctx.snowflakeLock.Unlock() if !ok || snowflake == nil { // The snowflake took too long to respond with an answer, so its client // disappeared / the snowflake is no longer recognized by the Broker. success = false log.Printf("Warning: matching with snowflake client failed") }
b, err := messages.EncodeAnswerResponse(success) if err != nil { log.Printf("Error encoding answer: %s", err.Error()) return messages.ErrInternal } *response = b
if success { snowflake.answerChannel <- answer }
return nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355/*We export metrics in the format specified in our broker spec:https://gitweb.torproject.org/pluggable-transports/snowflake.git/tree/doc/broker-spec.txt*/
package main
import ( "fmt" "log" "math" "net" "sort" "sync" "time"
"github.com/prometheus/client_golang/prometheus" "gitlab.torproject.org/tpo/anti-censorship/geoip" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/messages")
const ( prometheusNamespace = "snowflake" metricsResolution = 60 * 60 * 24 * time.Second //86400 seconds)
type CountryStats struct { // map[proxyType][address]bool proxies map[string]map[string]bool unknown map[string]bool
natRestricted map[string]bool natUnrestricted map[string]bool natUnknown map[string]bool
counts map[string]int}
// Implements Observabletype Metrics struct { logger *log.Logger geoipdb *geoip.Geoip
countryStats CountryStats clientRoundtripEstimate time.Duration proxyIdleCount uint clientDeniedCount map[messages.RendezvousMethod]uint clientRestrictedDeniedCount map[messages.RendezvousMethod]uint clientUnrestrictedDeniedCount map[messages.RendezvousMethod]uint clientProxyMatchCount map[messages.RendezvousMethod]uint
proxyPollWithRelayURLExtension uint proxyPollWithoutRelayURLExtension uint proxyPollRejectedWithRelayURLExtension uint
// synchronization for access to snowflake metrics lock sync.Mutex
promMetrics *PromMetrics}
type record struct { cc string count int}type records []record
func (r records) Len() int { return len(r) }func (r records) Swap(i, j int) { r[i], r[j] = r[j], r[i] }func (r records) Less(i, j int) bool { if r[i].count == r[j].count { return r[i].cc > r[j].cc } return r[i].count < r[j].count}
func (s CountryStats) Display() string { output := ""
// Use the records struct to sort our counts map by value. rs := records{} for cc, count := range s.counts { rs = append(rs, record{cc: cc, count: count}) } sort.Sort(sort.Reverse(rs)) for _, r := range rs { output += fmt.Sprintf("%s=%d,", r.cc, r.count) }
// cut off trailing "," if len(output) > 0 { return output[:len(output)-1] }
return output}
func (m *Metrics) UpdateCountryStats(addr string, proxyType string, natType string) {
var country string var ok bool
addresses, ok := m.countryStats.proxies[proxyType] if !ok { if m.countryStats.unknown[addr] { return } m.countryStats.unknown[addr] = true } else { if addresses[addr] { return } addresses[addr] = true }
ip := net.ParseIP(addr) if m.geoipdb == nil { return } country, ok = m.geoipdb.GetCountryByAddr(ip) if !ok { country = "??" } m.countryStats.counts[country]++
m.promMetrics.ProxyTotal.With(prometheus.Labels{ "nat": natType, "type": proxyType, "cc": country, }).Inc()
switch natType { case NATRestricted: m.countryStats.natRestricted[addr] = true case NATUnrestricted: m.countryStats.natUnrestricted[addr] = true default: m.countryStats.natUnknown[addr] = true }
}
func (m *Metrics) LoadGeoipDatabases(geoipDB string, geoip6DB string) error {
// Load geoip databases var err error log.Println("Loading geoip databases") m.geoipdb, err = geoip.New(geoipDB, geoip6DB) return err}
func NewMetrics(metricsLogger *log.Logger) (*Metrics, error) { m := new(Metrics)
m.clientDeniedCount = make(map[messages.RendezvousMethod]uint) m.clientRestrictedDeniedCount = make(map[messages.RendezvousMethod]uint) m.clientUnrestrictedDeniedCount = make(map[messages.RendezvousMethod]uint) m.clientProxyMatchCount = make(map[messages.RendezvousMethod]uint)
m.countryStats = CountryStats{ counts: make(map[string]int), proxies: make(map[string]map[string]bool), unknown: make(map[string]bool), natRestricted: make(map[string]bool), natUnrestricted: make(map[string]bool), natUnknown: make(map[string]bool), } for pType := range messages.KnownProxyTypes { m.countryStats.proxies[pType] = make(map[string]bool) }
m.logger = metricsLogger m.promMetrics = initPrometheus()
// Write to log file every day with updated metrics go m.logMetrics()
return m, nil}
// Logs metrics in intervals specified by metricsResolutionfunc (m *Metrics) logMetrics() { heartbeat := time.Tick(metricsResolution) for range heartbeat { m.printMetrics() m.zeroMetrics() }}
func (m *Metrics) printMetrics() { m.lock.Lock() m.logger.Println( "snowflake-stats-end", time.Now().UTC().Format("2006-01-02 15:04:05"), fmt.Sprintf("(%d s)", int(metricsResolution.Seconds())), ) m.logger.Println("snowflake-ips", m.countryStats.Display()) total := len(m.countryStats.unknown) for pType, addresses := range m.countryStats.proxies { m.logger.Printf("snowflake-ips-%s %d\n", pType, len(addresses)) total += len(addresses) } m.logger.Println("snowflake-ips-total", total) m.logger.Println("snowflake-idle-count", binCount(m.proxyIdleCount)) m.logger.Println("snowflake-proxy-poll-with-relay-url-count", binCount(m.proxyPollWithRelayURLExtension)) m.logger.Println("snowflake-proxy-poll-without-relay-url-count", binCount(m.proxyPollWithoutRelayURLExtension)) m.logger.Println("snowflake-proxy-rejected-for-relay-url-count", binCount(m.proxyPollRejectedWithRelayURLExtension))
m.logger.Println("client-denied-count", binCount(sumMapValues(&m.clientDeniedCount))) m.logger.Println("client-restricted-denied-count", binCount(sumMapValues(&m.clientRestrictedDeniedCount))) m.logger.Println("client-unrestricted-denied-count", binCount(sumMapValues(&m.clientUnrestrictedDeniedCount))) m.logger.Println("client-snowflake-match-count", binCount(sumMapValues(&m.clientProxyMatchCount)))
for _, rendezvousMethod := range [3]messages.RendezvousMethod{ messages.RendezvousHttp, messages.RendezvousAmpCache, messages.RendezvousSqs, } { m.logger.Printf("client-%s-count %d\n", rendezvousMethod, binCount( m.clientDeniedCount[rendezvousMethod]+m.clientProxyMatchCount[rendezvousMethod], )) }
m.logger.Println("snowflake-ips-nat-restricted", len(m.countryStats.natRestricted)) m.logger.Println("snowflake-ips-nat-unrestricted", len(m.countryStats.natUnrestricted)) m.logger.Println("snowflake-ips-nat-unknown", len(m.countryStats.natUnknown)) m.lock.Unlock()}
// Restores all metrics to original valuesfunc (m *Metrics) zeroMetrics() { m.proxyIdleCount = 0 m.clientDeniedCount = make(map[messages.RendezvousMethod]uint) m.clientRestrictedDeniedCount = make(map[messages.RendezvousMethod]uint) m.clientUnrestrictedDeniedCount = make(map[messages.RendezvousMethod]uint) m.proxyPollRejectedWithRelayURLExtension = 0 m.proxyPollWithRelayURLExtension = 0 m.proxyPollWithoutRelayURLExtension = 0 m.clientProxyMatchCount = make(map[messages.RendezvousMethod]uint) m.countryStats.counts = make(map[string]int) for pType := range m.countryStats.proxies { m.countryStats.proxies[pType] = make(map[string]bool) } m.countryStats.unknown = make(map[string]bool) m.countryStats.natRestricted = make(map[string]bool) m.countryStats.natUnrestricted = make(map[string]bool) m.countryStats.natUnknown = make(map[string]bool)}
// Rounds up a count to the nearest multiple of 8.func binCount(count uint) uint { return uint((math.Ceil(float64(count) / 8)) * 8)}
func sumMapValues(m *map[messages.RendezvousMethod]uint) uint { var s uint = 0 for _, v := range *m { s += v } return s}
type PromMetrics struct { registry *prometheus.Registry ProxyTotal *prometheus.CounterVec ProxyPollTotal *RoundedCounterVec ClientPollTotal *RoundedCounterVec AvailableProxies *prometheus.GaugeVec
ProxyPollWithRelayURLExtensionTotal *RoundedCounterVec ProxyPollWithoutRelayURLExtensionTotal *RoundedCounterVec
ProxyPollRejectedForRelayURLExtensionTotal *RoundedCounterVec}
// Initialize metrics for prometheus exporterfunc initPrometheus() *PromMetrics { promMetrics := &PromMetrics{}
promMetrics.registry = prometheus.NewRegistry()
promMetrics.ProxyTotal = prometheus.NewCounterVec( prometheus.CounterOpts{ Namespace: prometheusNamespace, Name: "proxy_total", Help: "The number of unique snowflake IPs", }, []string{"type", "nat", "cc"}, )
promMetrics.AvailableProxies = prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: prometheusNamespace, Name: "available_proxies", Help: "The number of currently available snowflake proxies", }, []string{"type", "nat"}, )
promMetrics.ProxyPollTotal = NewRoundedCounterVec( prometheus.CounterOpts{ Namespace: prometheusNamespace, Name: "rounded_proxy_poll_total", Help: "The number of snowflake proxy polls, rounded up to a multiple of 8", }, []string{"nat", "status"}, )
promMetrics.ProxyPollWithRelayURLExtensionTotal = NewRoundedCounterVec( prometheus.CounterOpts{ Namespace: prometheusNamespace, Name: "rounded_proxy_poll_with_relay_url_extension_total", Help: "The number of snowflake proxy polls with Relay URL Extension, rounded up to a multiple of 8", }, []string{"nat", "type"}, )
promMetrics.ProxyPollWithoutRelayURLExtensionTotal = NewRoundedCounterVec( prometheus.CounterOpts{ Namespace: prometheusNamespace, Name: "rounded_proxy_poll_without_relay_url_extension_total", Help: "The number of snowflake proxy polls without Relay URL Extension, rounded up to a multiple of 8", }, []string{"nat", "type"}, )
promMetrics.ProxyPollRejectedForRelayURLExtensionTotal = NewRoundedCounterVec( prometheus.CounterOpts{ Namespace: prometheusNamespace, Name: "rounded_proxy_poll_rejected_relay_url_extension_total", Help: "The number of snowflake proxy polls rejected by Relay URL Extension, rounded up to a multiple of 8", }, []string{"nat", "type"}, )
promMetrics.ClientPollTotal = NewRoundedCounterVec( prometheus.CounterOpts{ Namespace: prometheusNamespace, Name: "rounded_client_poll_total", Help: "The number of snowflake client polls, rounded up to a multiple of 8", }, []string{"nat", "status", "rendezvous_method"}, )
// We need to register our metrics so they can be exported. promMetrics.registry.MustRegister( promMetrics.ClientPollTotal, promMetrics.ProxyPollTotal, promMetrics.ProxyTotal, promMetrics.AvailableProxies, promMetrics.ProxyPollWithRelayURLExtensionTotal, promMetrics.ProxyPollWithoutRelayURLExtensionTotal, promMetrics.ProxyPollRejectedForRelayURLExtensionTotal, )
return promMetrics}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283/*Implements some additional prometheus metrics that we need for privacy preservingcounts of users and proxies*/
package main
import ( "sync/atomic"
"github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" "google.golang.org/protobuf/proto")
// New Prometheus counter type that produces rounded counts of metrics// for privacy preserving reasonstype RoundedCounter interface { prometheus.Metric
Inc()}
type roundedCounter struct { total uint64 //reflects the true count value uint64 //reflects the rounded count
desc *prometheus.Desc labelPairs []*dto.LabelPair}
// Implements the RoundedCounter interfacefunc (c *roundedCounter) Inc() { atomic.AddUint64(&c.total, 1) if c.total > c.value { atomic.AddUint64(&c.value, 8) }}
// Implements the prometheus.Metric interfacefunc (c *roundedCounter) Desc() *prometheus.Desc { return c.desc}
// Implements the prometheus.Metric interfacefunc (c *roundedCounter) Write(m *dto.Metric) error { m.Label = c.labelPairs
m.Counter = &dto.Counter{Value: proto.Float64(float64(c.value))} return nil}
// New prometheus vector type that will track RoundedCounter metrics// accross multiple labelstype RoundedCounterVec struct { *prometheus.MetricVec}
func NewRoundedCounterVec(opts prometheus.CounterOpts, labelNames []string) *RoundedCounterVec { desc := prometheus.NewDesc( prometheus.BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), opts.Help, labelNames, opts.ConstLabels, ) return &RoundedCounterVec{ MetricVec: prometheus.NewMetricVec(desc, func(lvs ...string) prometheus.Metric { if len(lvs) != len(labelNames) { panic("inconsistent cardinality") } return &roundedCounter{desc: desc, labelPairs: prometheus.MakeLabelPairs(desc, lvs)} }), }}
// Helper function to return the underlying RoundedCounter metric from MetricVecfunc (v *RoundedCounterVec) With(labels prometheus.Labels) RoundedCounter { metric, err := v.GetMetricWith(labels) if err != nil { panic(err) } return metric.(RoundedCounter)}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003package main
import ( "bytes" "container/heap" "encoding/hex" "fmt" "io" "log" "net/http" "net/http/httptest" "os" "sync" "testing" "time"
. "github.com/smartystreets/goconvey/convey" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/amp" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/messages")
func NullLogger() *log.Logger { logger := log.New(os.Stdout, "", 0) logger.SetOutput(io.Discard) return logger}
var promOnce sync.Once
var ( sdp = "v=0\r\n" + "o=- 123456789 987654321 IN IP4 0.0.0.0\r\n" + "s=-\r\n" + "t=0 0\r\n" + "a=fingerprint:sha-256 12:34\r\n" + "a=extmap-allow-mixed\r\n" + "a=group:BUNDLE 0\r\n" + "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n" + "c=IN IP4 0.0.0.0\r\n" + "a=setup:actpass\r\n" + "a=mid:0\r\n" + "a=sendrecv\r\n" + "a=sctp-port:5000\r\n" + "a=ice-ufrag:CoVEaiFXRGVzshXG\r\n" + "a=ice-pwd:aOrOZXraTfFKzyeBxIXYYKjSgRVPGhUx\r\n" + "a=candidate:1000 1 udp 2000 8.8.8.8 3000 typ host\r\n" + "a=end-of-candidates\r\n"
sid = "ymbcCMto7KHNGYlp")
func createClientOffer(sdp, nat, fingerprint string) (*bytes.Reader, error) { clientRequest := &messages.ClientPollRequest{ Offer: sdp, NAT: nat, Fingerprint: fingerprint, } encOffer, err := clientRequest.EncodeClientPollRequest() if err != nil { return nil, err } offer := bytes.NewReader(encOffer) return offer, nil}
func createProxyAnswer(sdp, sid string) (*bytes.Reader, error) { proxyRequest, err := messages.EncodeAnswerRequest(sdp, sid) if err != nil { return nil, err } answer := bytes.NewReader(proxyRequest) return answer, nil}
func decodeAMPArmorToString(r io.Reader) (string, error) { dec, err := amp.NewArmorDecoder(r) if err != nil { return "", err } p, err := io.ReadAll(dec) return string(p), err}
func TestBroker(t *testing.T) {
defaultBridgeValue, _ := hex.DecodeString("2B280B23E1107BB62ABFC40DDCC8824814F80A72") var defaultBridge [20]byte copy(defaultBridge[:], defaultBridgeValue)
Convey("Context", t, func() { buf := new(bytes.Buffer) ctx := NewBrokerContext(log.New(buf, "", 0)) i := &IPC{ctx}
Convey("Adds Snowflake", func() { So(ctx.snowflakes.Len(), ShouldEqual, 0) So(len(ctx.idToSnowflake), ShouldEqual, 0) ctx.AddSnowflake("foo", "", NATUnrestricted, 0) So(ctx.snowflakes.Len(), ShouldEqual, 1) So(len(ctx.idToSnowflake), ShouldEqual, 1) })
Convey("Broker goroutine matches clients with proxies", func() { p := new(ProxyPoll) p.id = "test" p.natType = "unrestricted" p.offerChannel = make(chan *ClientOffer) go func(ctx *BrokerContext) { ctx.proxyPolls <- p close(ctx.proxyPolls) }(ctx) ctx.Broker() So(ctx.snowflakes.Len(), ShouldEqual, 1) snowflake := heap.Pop(ctx.snowflakes).(*Snowflake) snowflake.offerChannel <- &ClientOffer{sdp: []byte("test offer")} offer := <-p.offerChannel So(ctx.idToSnowflake["test"], ShouldNotBeNil) So(offer.sdp, ShouldResemble, []byte("test offer")) So(ctx.snowflakes.Len(), ShouldEqual, 0) })
Convey("Request an offer from the Snowflake Heap", func() { done := make(chan *ClientOffer) go func() { offer := ctx.RequestOffer("test", "", NATUnrestricted, 0) done <- offer }() request := <-ctx.proxyPolls request.offerChannel <- &ClientOffer{sdp: []byte("test offer")} offer := <-done So(offer.sdp, ShouldResemble, []byte("test offer")) })
Convey("Responds to HTTP client offers...", func() { w := httptest.NewRecorder() data, err := createClientOffer(sdp, NATUnknown, "") r, err := http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil)
Convey("with HTTP Bad Request when client offer contains invalid SDP", func() { data, err = createClientOffer("fake", NATUnknown, "") invalidRequest, err := http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil) clientOffers(i, w, invalidRequest) So(w.Code, ShouldEqual, http.StatusBadRequest) })
Convey("with error when no snowflakes are available.", func() { clientOffers(i, w, r) So(w.Code, ShouldEqual, http.StatusOK) So(w.Body.String(), ShouldEqual, `{"error":"no snowflake proxies currently available"}`)
// Ensure that denial is correctly recorded in metrics ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, `client-denied-count 8client-restricted-denied-count 8client-unrestricted-denied-count 0client-snowflake-match-count 0client-http-count 8client-ampcache-count 0client-sqs-count 0`) })
Convey("with a proxy answer if available.", func() { done := make(chan bool) // Prepare a fake proxy to respond with. snowflake := ctx.AddSnowflake("test", "", NATUnrestricted, 0) go func() { clientOffers(i, w, r) done <- true }() offer := <-snowflake.offerChannel So(offer.sdp, ShouldResemble, []byte(sdp)) snowflake.answerChannel <- "test answer" <-done So(w.Body.String(), ShouldEqual, `{"answer":"test answer"}`) So(w.Code, ShouldEqual, http.StatusOK)
// Ensure that match is correctly recorded in metrics ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, `client-denied-count 0client-restricted-denied-count 0client-unrestricted-denied-count 0client-snowflake-match-count 8client-http-count 8client-ampcache-count 0client-sqs-count 0`) })
Convey("with unrestricted proxy to unrestricted client if there are no restricted proxies", func() { snowflake := ctx.AddSnowflake("test", "", NATUnrestricted, 0) offerData, err := createClientOffer(sdp, NATUnrestricted, "") So(err, ShouldBeNil) r, err := http.NewRequest("POST", "snowflake.broker/client", offerData)
done := make(chan bool) go func() { clientOffers(i, w, r) done <- true }()
select { case <-snowflake.offerChannel: case <-time.After(250 * time.Millisecond): So(false, ShouldBeTrue) return } snowflake.answerChannel <- "test answer"
<-done So(w.Body.String(), ShouldEqual, `{"answer":"test answer"}`) })
Convey("Times out when no proxy responds.", func() { if testing.Short() { return } done := make(chan bool) snowflake := ctx.AddSnowflake("fake", "", NATUnrestricted, 0) go func() { clientOffers(i, w, r) // Takes a few seconds here... done <- true }() offer := <-snowflake.offerChannel So(offer.sdp, ShouldResemble, []byte(sdp)) <-done So(w.Code, ShouldEqual, http.StatusOK) So(w.Body.String(), ShouldEqual, `{"error":"timed out waiting for answer!"}`) }) })
Convey("Responds to HTTP legacy client offers...", func() { w := httptest.NewRecorder() // legacy offer starts with { offer := bytes.NewReader([]byte(fmt.Sprintf(`{%v}`, sdp))) r, err := http.NewRequest("POST", "snowflake.broker/client", offer) So(err, ShouldBeNil) r.Header.Set("Snowflake-NAT-TYPE", "restricted")
Convey("with HTTP Bad Request when client offer contains invalid SDP", func() { invalidOffer := bytes.NewReader([]byte("{test}")) invalidRequest, err := http.NewRequest("POST", "snowflake.broker/client", invalidOffer) So(err, ShouldBeNil) clientOffers(i, w, invalidRequest) So(w.Code, ShouldEqual, http.StatusBadRequest) })
Convey("with 503 when no snowflakes are available.", func() { clientOffers(i, w, r) So(w.Code, ShouldEqual, http.StatusServiceUnavailable) So(w.Body.String(), ShouldEqual, "")
// Ensure that denial is correctly recorded in metrics ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, `client-denied-count 8client-restricted-denied-count 8client-unrestricted-denied-count 0client-snowflake-match-count 0client-http-count 8client-ampcache-count 0client-sqs-count 0`) })
Convey("with a proxy answer if available.", func() { done := make(chan bool) // Prepare a fake proxy to respond with. snowflake := ctx.AddSnowflake("fake", "", NATUnrestricted, 0) go func() { clientOffers(i, w, r) done <- true }() offer := <-snowflake.offerChannel So(offer.sdp, ShouldResemble, []byte(fmt.Sprintf(`{%v}`, sdp))) snowflake.answerChannel <- "fake answer" <-done So(w.Body.String(), ShouldEqual, "fake answer") So(w.Code, ShouldEqual, http.StatusOK)
// Ensure that match is correctly recorded in metrics ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, `client-denied-count 0client-restricted-denied-count 0client-unrestricted-denied-count 0client-snowflake-match-count 8client-http-count 8client-ampcache-count 0client-sqs-count 0`) })
Convey("Times out when no proxy responds.", func() { if testing.Short() { return } done := make(chan bool) snowflake := ctx.AddSnowflake("fake", "", NATUnrestricted, 0) go func() { clientOffers(i, w, r) // Takes a few seconds here... done <- true }() offer := <-snowflake.offerChannel So(offer.sdp, ShouldResemble, []byte(fmt.Sprintf(`{%v}`, sdp))) <-done So(w.Code, ShouldEqual, http.StatusGatewayTimeout) })
})
Convey("Responds to AMP client offers...", func() { w := httptest.NewRecorder() encPollReq := []byte("1.0\n{\"offer\": \"fake\", \"nat\": \"unknown\"}") r, err := http.NewRequest("GET", "/amp/client/"+amp.EncodePath(encPollReq), nil) So(err, ShouldBeNil)
Convey("with status 200 when request is badly formatted.", func() { r, err := http.NewRequest("GET", "/amp/client/bad", nil) So(err, ShouldBeNil) ampClientOffers(i, w, r) body, err := decodeAMPArmorToString(w.Body) So(err, ShouldBeNil) So(body, ShouldEqual, `{"error":"cannot decode URL path"}`) })
Convey("with error when no snowflakes are available.", func() { ampClientOffers(i, w, r) So(w.Code, ShouldEqual, http.StatusOK) body, err := decodeAMPArmorToString(w.Body) So(err, ShouldBeNil) So(body, ShouldEqual, `{"error":"no snowflake proxies currently available"}`)
// Ensure that denial is correctly recorded in metrics ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, `client-denied-count 8client-restricted-denied-count 8client-unrestricted-denied-count 0client-snowflake-match-count 0client-http-count 0client-ampcache-count 8client-sqs-count 0`) })
Convey("with a proxy answer if available.", func() { done := make(chan bool) // Prepare a fake proxy to respond with. snowflake := ctx.AddSnowflake("fake", "", NATUnrestricted, 0) go func() { ampClientOffers(i, w, r) done <- true }() offer := <-snowflake.offerChannel So(offer.sdp, ShouldResemble, []byte("fake")) snowflake.answerChannel <- "fake answer" <-done body, err := decodeAMPArmorToString(w.Body) So(err, ShouldBeNil) So(body, ShouldEqual, `{"answer":"fake answer"}`) So(w.Code, ShouldEqual, http.StatusOK)
// Ensure that match is correctly recorded in metrics ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, `client-denied-count 0client-restricted-denied-count 0client-unrestricted-denied-count 0client-snowflake-match-count 8client-http-count 0client-ampcache-count 8client-sqs-count 0`) })
Convey("Times out when no proxy responds.", func() { if testing.Short() { return } done := make(chan bool) snowflake := ctx.AddSnowflake("fake", "", NATUnrestricted, 0) go func() { ampClientOffers(i, w, r) // Takes a few seconds here... done <- true }() offer := <-snowflake.offerChannel So(offer.sdp, ShouldResemble, []byte("fake")) <-done So(w.Code, ShouldEqual, http.StatusOK) body, err := decodeAMPArmorToString(w.Body) So(err, ShouldBeNil) So(body, ShouldEqual, `{"error":"timed out waiting for answer!"}`) })
})
Convey("Responds to proxy polls...", func() { done := make(chan bool) w := httptest.NewRecorder() data := bytes.NewReader([]byte(`{"Sid":"ymbcCMto7KHNGYlp","Version":"1.0"}`)) r, err := http.NewRequest("POST", "snowflake.broker/proxy", data) So(err, ShouldBeNil)
Convey("with a client offer if available.", func() { go func(i *IPC) { proxyPolls(i, w, r) done <- true }(i) // Pass a fake client offer to this proxy p := <-ctx.proxyPolls So(p.id, ShouldEqual, "ymbcCMto7KHNGYlp") p.offerChannel <- &ClientOffer{sdp: []byte("fake offer"), fingerprint: defaultBridge[:]} <-done So(w.Code, ShouldEqual, http.StatusOK) So(w.Body.String(), ShouldEqual, `{"Status":"client match","Offer":"fake offer","NAT":"","RelayURL":"wss://snowflake.torproject.net/"}`) })
Convey("return empty 200 OK when no client offer is available.", func() { go func(i *IPC) { proxyPolls(i, w, r) done <- true }(i) p := <-ctx.proxyPolls So(p.id, ShouldEqual, "ymbcCMto7KHNGYlp") // nil means timeout p.offerChannel <- nil <-done So(w.Body.String(), ShouldEqual, `{"Status":"no match","Offer":"","NAT":"","RelayURL":""}`) So(w.Code, ShouldEqual, http.StatusOK) }) })
Convey("Responds to proxy answers...", func() { done := make(chan bool) s := ctx.AddSnowflake(sid, "", NATUnrestricted, 0) w := httptest.NewRecorder()
data, err := createProxyAnswer(sdp, sid) So(err, ShouldBeNil)
Convey("by passing to the client if valid.", func() { r, err := http.NewRequest("POST", "snowflake.broker/answer", data) So(err, ShouldBeNil) go func(i *IPC) { proxyAnswers(i, w, r) done <- true }(i) answer := <-s.answerChannel <-done So(w.Code, ShouldEqual, http.StatusOK) So(answer, ShouldResemble, sdp) })
Convey("with client gone status if the proxy ID is not recognized", func() { data, err := createProxyAnswer(sdp, "invalid") r, err := http.NewRequest("POST", "snowflake.broker/answer", data) So(err, ShouldBeNil) proxyAnswers(i, w, r) So(w.Code, ShouldEqual, http.StatusOK) b, err := io.ReadAll(w.Body) So(err, ShouldBeNil) So(b, ShouldResemble, []byte(`{"Status":"client gone"}`)) })
Convey("with error if the proxy gives invalid answer", func() { data := bytes.NewReader(nil) r, err := http.NewRequest("POST", "snowflake.broker/answer", data) So(err, ShouldBeNil) proxyAnswers(i, w, r) So(w.Code, ShouldEqual, http.StatusBadRequest) })
Convey("with error if the proxy writes too much data", func() { data := bytes.NewReader(make([]byte, 100001)) r, err := http.NewRequest("POST", "snowflake.broker/answer", data) So(err, ShouldBeNil) proxyAnswers(i, w, r) So(w.Code, ShouldEqual, http.StatusBadRequest) })
})
})
Convey("End-To-End", t, func() { ctx := NewBrokerContext(NullLogger()) i := &IPC{ctx}
Convey("Check for client/proxy data race", func() { proxy_done := make(chan bool) client_done := make(chan bool)
go ctx.Broker()
// Make proxy poll wp := httptest.NewRecorder() datap := bytes.NewReader([]byte(`{"Sid":"ymbcCMto7KHNGYlp","Version":"1.0"}`)) rp, err := http.NewRequest("POST", "snowflake.broker/proxy", datap) So(err, ShouldBeNil)
go func(i *IPC) { proxyPolls(i, wp, rp) proxy_done <- true }(i)
// Client offer wc := httptest.NewRecorder() datac, err := createClientOffer(sdp, NATUnknown, "") So(err, ShouldBeNil) rc, err := http.NewRequest("POST", "snowflake.broker/client", datac) So(err, ShouldBeNil)
go func() { clientOffers(i, wc, rc) client_done <- true }()
<-proxy_done So(wp.Code, ShouldEqual, http.StatusOK)
// Proxy answers wp = httptest.NewRecorder() datap, err = createProxyAnswer(sdp, sid) So(err, ShouldBeNil) rp, err = http.NewRequest("POST", "snowflake.broker/answer", datap) So(err, ShouldBeNil) go func(i *IPC) { proxyAnswers(i, wp, rp) proxy_done <- true }(i)
<-proxy_done <-client_done
})
Convey("Ensure correct snowflake brokering", func() { done := make(chan bool) polled := make(chan bool)
// Proxy polls with its ID first... dataP := bytes.NewReader([]byte(`{"Sid":"ymbcCMto7KHNGYlp","Version":"1.0"}`)) wP := httptest.NewRecorder() rP, err := http.NewRequest("POST", "snowflake.broker/proxy", dataP) So(err, ShouldBeNil) go func() { proxyPolls(i, wP, rP) polled <- true }()
// Manually do the Broker goroutine action here for full control. p := <-ctx.proxyPolls So(p.id, ShouldEqual, "ymbcCMto7KHNGYlp") s := ctx.AddSnowflake(p.id, "", NATUnrestricted, 0) go func() { offer := <-s.offerChannel p.offerChannel <- offer }() So(ctx.idToSnowflake["ymbcCMto7KHNGYlp"], ShouldNotBeNil)
// Client request blocks until proxy answer arrives. wC := httptest.NewRecorder() dataC, err := createClientOffer(sdp, NATUnknown, "") So(err, ShouldBeNil) rC, err := http.NewRequest("POST", "snowflake.broker/client", dataC) So(err, ShouldBeNil) go func() { clientOffers(i, wC, rC) done <- true }()
<-polled So(wP.Code, ShouldEqual, http.StatusOK) So(wP.Body.String(), ShouldResemble, fmt.Sprintf(`{"Status":"client match","Offer":%#q,"NAT":"unknown","RelayURL":"wss://snowflake.torproject.net/"}`, sdp)) So(ctx.idToSnowflake[sid], ShouldNotBeNil)
// Follow up with the answer request afterwards wA := httptest.NewRecorder() dataA, err := createProxyAnswer(sdp, sid) So(err, ShouldBeNil) rA, err := http.NewRequest("POST", "snowflake.broker/answer", dataA) So(err, ShouldBeNil) proxyAnswers(i, wA, rA) So(wA.Code, ShouldEqual, http.StatusOK)
<-done So(wC.Code, ShouldEqual, http.StatusOK) So(wC.Body.String(), ShouldEqual, fmt.Sprintf(`{"answer":%#q}`, sdp)) }) })}
func TestSnowflakeHeap(t *testing.T) { Convey("SnowflakeHeap", t, func() { h := new(SnowflakeHeap) heap.Init(h) So(h.Len(), ShouldEqual, 0) s1 := new(Snowflake) s2 := new(Snowflake) s3 := new(Snowflake) s4 := new(Snowflake) s1.clients = 4 s2.clients = 5 s3.clients = 3 s4.clients = 1
heap.Push(h, s1) So(h.Len(), ShouldEqual, 1) heap.Push(h, s2) So(h.Len(), ShouldEqual, 2) heap.Push(h, s3) So(h.Len(), ShouldEqual, 3) heap.Push(h, s4) So(h.Len(), ShouldEqual, 4)
heap.Remove(h, 0) So(h.Len(), ShouldEqual, 3)
r := heap.Pop(h).(*Snowflake) So(h.Len(), ShouldEqual, 2) So(r.clients, ShouldEqual, 3) So(r.index, ShouldEqual, -1)
r = heap.Pop(h).(*Snowflake) So(h.Len(), ShouldEqual, 1) So(r.clients, ShouldEqual, 4) So(r.index, ShouldEqual, -1)
r = heap.Pop(h).(*Snowflake) So(h.Len(), ShouldEqual, 0) So(r.clients, ShouldEqual, 5) So(r.index, ShouldEqual, -1) })}
func TestInvalidGeoipFile(t *testing.T) { Convey("Geoip", t, func() { // Make sure things behave properly if geoip file fails to load ctx := NewBrokerContext(NullLogger()) if err := ctx.metrics.LoadGeoipDatabases("invalid_filename", "invalid_filename6"); err != nil { log.Printf("loading geo ip databases returned error: %v", err) } ctx.metrics.UpdateCountryStats("127.0.0.1", "", NATUnrestricted) So(ctx.metrics.geoipdb, ShouldBeNil)
})}
func TestMetrics(t *testing.T) { Convey("Test metrics...", t, func() { done := make(chan bool) buf := new(bytes.Buffer) ctx := NewBrokerContext(log.New(buf, "", 0)) i := &IPC{ctx}
err := ctx.metrics.LoadGeoipDatabases("test_geoip", "test_geoip6") So(err, ShouldBeNil)
//Test addition of proxy polls Convey("for proxy polls", func() { w := httptest.NewRecorder() data := bytes.NewReader([]byte("{\"Sid\":\"ymbcCMto7KHNGYlp\",\"Version\":\"1.0\"}")) r, err := http.NewRequest("POST", "snowflake.broker/proxy", data) r.RemoteAddr = "129.97.208.23:8888" //CA geoip So(err, ShouldBeNil) go func(i *IPC) { proxyPolls(i, w, r) done <- true }(i) p := <-ctx.proxyPolls //manually unblock poll p.offerChannel <- nil <-done
w = httptest.NewRecorder() data = bytes.NewReader([]byte(`{"Sid":"ymbcCMto7KHNGYlp","Version":"1.0","Type":"standalone"}`)) r, err = http.NewRequest("POST", "snowflake.broker/proxy", data) r.RemoteAddr = "129.97.208.23:8888" //CA geoip So(err, ShouldBeNil) go func(i *IPC) { proxyPolls(i, w, r) done <- true }(i) p = <-ctx.proxyPolls //manually unblock poll p.offerChannel <- nil <-done
w = httptest.NewRecorder() data = bytes.NewReader([]byte(`{"Sid":"ymbcCMto7KHNGYlp","Version":"1.0","Type":"badge"}`)) r, err = http.NewRequest("POST", "snowflake.broker/proxy", data) r.RemoteAddr = "129.97.208.23:8888" //CA geoip So(err, ShouldBeNil) go func(i *IPC) { proxyPolls(i, w, r) done <- true }(i) p = <-ctx.proxyPolls //manually unblock poll p.offerChannel <- nil <-done
w = httptest.NewRecorder() data = bytes.NewReader([]byte(`{"Sid":"ymbcCMto7KHNGYlp","Version":"1.0","Type":"webext"}`)) r, err = http.NewRequest("POST", "snowflake.broker/proxy", data) r.RemoteAddr = "129.97.208.23:8888" //CA geoip So(err, ShouldBeNil) go func(i *IPC) { proxyPolls(i, w, r) done <- true }(i) p = <-ctx.proxyPolls //manually unblock poll p.offerChannel <- nil <-done ctx.metrics.printMetrics()
metricsStr := buf.String() So(metricsStr, ShouldStartWith, "snowflake-stats-end "+time.Now().UTC().Format("2006-01-02 15:04:05")+" (86400 s)\nsnowflake-ips CA=4\n") So(metricsStr, ShouldContainSubstring, "\nsnowflake-ips-standalone 1\n") So(metricsStr, ShouldContainSubstring, "\nsnowflake-ips-badge 1\n") So(metricsStr, ShouldContainSubstring, "\nsnowflake-ips-webext 1\n") So(metricsStr, ShouldEndWith, `snowflake-ips-total 4snowflake-idle-count 8snowflake-proxy-poll-with-relay-url-count 0snowflake-proxy-poll-without-relay-url-count 8snowflake-proxy-rejected-for-relay-url-count 0client-denied-count 0client-restricted-denied-count 0client-unrestricted-denied-count 0client-snowflake-match-count 0client-http-count 0client-ampcache-count 0client-sqs-count 0snowflake-ips-nat-restricted 0snowflake-ips-nat-unrestricted 0snowflake-ips-nat-unknown 1`) })
//Test addition of client failures Convey("for no proxies available", func() { w := httptest.NewRecorder() data, err := createClientOffer(sdp, NATUnknown, "") So(err, ShouldBeNil) r, err := http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil)
clientOffers(i, w, r)
ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, `client-denied-count 8client-restricted-denied-count 8client-unrestricted-denied-count 0client-snowflake-match-count 0client-http-count 8client-ampcache-count 0client-sqs-count 0`)
// Test reset buf.Reset() ctx.metrics.zeroMetrics() ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, "\nsnowflake-ips \n") So(buf.String(), ShouldContainSubstring, "\nsnowflake-ips-standalone 0\n") So(buf.String(), ShouldContainSubstring, "\nsnowflake-ips-badge 0\n") So(buf.String(), ShouldContainSubstring, "\nsnowflake-ips-webext 0\n") So(buf.String(), ShouldContainSubstring, `snowflake-ips-total 0snowflake-idle-count 0snowflake-proxy-poll-with-relay-url-count 0snowflake-proxy-poll-without-relay-url-count 0snowflake-proxy-rejected-for-relay-url-count 0client-denied-count 0client-restricted-denied-count 0client-unrestricted-denied-count 0client-snowflake-match-count 0client-http-count 0client-ampcache-count 0client-sqs-count 0snowflake-ips-nat-restricted 0snowflake-ips-nat-unrestricted 0snowflake-ips-nat-unknown 0`) }) //Test addition of client matches Convey("for client-proxy match", func() { w := httptest.NewRecorder() data, err := createClientOffer(sdp, NATUnknown, "") So(err, ShouldBeNil) r, err := http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil)
// Prepare a fake proxy to respond with. snowflake := ctx.AddSnowflake("fake", "", NATUnrestricted, 0) go func() { clientOffers(i, w, r) done <- true }() offer := <-snowflake.offerChannel So(offer.sdp, ShouldResemble, []byte(sdp)) snowflake.answerChannel <- "fake answer" <-done
ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, "client-denied-count 0\nclient-restricted-denied-count 0\nclient-unrestricted-denied-count 0\nclient-snowflake-match-count 8") }) //Test rounding boundary Convey("binning boundary", func() { w := httptest.NewRecorder() data, err := createClientOffer(sdp, NATRestricted, "") So(err, ShouldBeNil) r, err := http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil) clientOffers(i, w, r)
w = httptest.NewRecorder() data, err = createClientOffer(sdp, NATRestricted, "") So(err, ShouldBeNil) r, err = http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil) clientOffers(i, w, r)
w = httptest.NewRecorder() data, err = createClientOffer(sdp, NATRestricted, "") So(err, ShouldBeNil) r, err = http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil) clientOffers(i, w, r)
w = httptest.NewRecorder() data, err = createClientOffer(sdp, NATRestricted, "") So(err, ShouldBeNil) r, err = http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil) clientOffers(i, w, r)
w = httptest.NewRecorder() data, err = createClientOffer(sdp, NATRestricted, "") So(err, ShouldBeNil) r, err = http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil) clientOffers(i, w, r)
w = httptest.NewRecorder() data, err = createClientOffer(sdp, NATRestricted, "") So(err, ShouldBeNil) r, err = http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil) clientOffers(i, w, r)
w = httptest.NewRecorder() data, err = createClientOffer(sdp, NATRestricted, "") So(err, ShouldBeNil) r, err = http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil) clientOffers(i, w, r)
w = httptest.NewRecorder() data, err = createClientOffer(sdp, NATRestricted, "") So(err, ShouldBeNil) r, err = http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil) clientOffers(i, w, r)
ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, "client-denied-count 8\nclient-restricted-denied-count 8\nclient-unrestricted-denied-count 0\n")
w = httptest.NewRecorder() data, err = createClientOffer(sdp, NATRestricted, "") So(err, ShouldBeNil) r, err = http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil) clientOffers(i, w, r)
buf.Reset() ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, "client-denied-count 16\nclient-restricted-denied-count 16\nclient-unrestricted-denied-count 0\n") })
//Test unique ip Convey("proxy counts by unique ip", func() { w := httptest.NewRecorder() data := bytes.NewReader([]byte(`{"Sid":"ymbcCMto7KHNGYlp","Version":"1.0"}`)) r, err := http.NewRequest("POST", "snowflake.broker/proxy", data) r.RemoteAddr = "129.97.208.23:8888" //CA geoip So(err, ShouldBeNil) go func(i *IPC) { proxyPolls(i, w, r) done <- true }(i) p := <-ctx.proxyPolls //manually unblock poll p.offerChannel <- nil <-done
data = bytes.NewReader([]byte(`{"Sid":"ymbcCMto7KHNGYlp","Version":"1.0"}`)) r, err = http.NewRequest("POST", "snowflake.broker/proxy", data) if err != nil { log.Printf("unable to get NewRequest with error: %v", err) } r.RemoteAddr = "129.97.208.23:8888" //CA geoip go func(i *IPC) { proxyPolls(i, w, r) done <- true }(i) p = <-ctx.proxyPolls //manually unblock poll p.offerChannel <- nil <-done
ctx.metrics.printMetrics() metricsStr := buf.String() So(metricsStr, ShouldContainSubstring, "snowflake-ips CA=1\n") So(metricsStr, ShouldContainSubstring, "snowflake-ips-total 1\n") }) //Test NAT types Convey("proxy counts by NAT type", func() { w := httptest.NewRecorder() data := bytes.NewReader([]byte(`{"Sid":"ymbcCMto7KHNGYlp","Version":"1.2","Type":"unknown","NAT":"restricted"}`)) r, err := http.NewRequest("POST", "snowflake.broker/proxy", data) r.RemoteAddr = "129.97.208.23:8888" //CA geoip So(err, ShouldBeNil) go func(i *IPC) { proxyPolls(i, w, r) done <- true }(i) p := <-ctx.proxyPolls //manually unblock poll p.offerChannel <- nil <-done
ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, "snowflake-ips-nat-restricted 1\nsnowflake-ips-nat-unrestricted 0\nsnowflake-ips-nat-unknown 0")
data = bytes.NewReader([]byte(`{"Sid":"ymbcCMto7KHNGYlp","Version":"1.2","Type":"unknown","NAT":"unrestricted"}`)) r, err = http.NewRequest("POST", "snowflake.broker/proxy", data) if err != nil { log.Printf("unable to get NewRequest with error: %v", err) } r.RemoteAddr = "129.97.208.24:8888" //CA geoip go func(i *IPC) { proxyPolls(i, w, r) done <- true }(i) p = <-ctx.proxyPolls //manually unblock poll p.offerChannel <- nil <-done
ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, "snowflake-ips-nat-restricted 1\nsnowflake-ips-nat-unrestricted 1\nsnowflake-ips-nat-unknown 0") })
Convey("client failures by NAT type", func() { w := httptest.NewRecorder() data, err := createClientOffer(sdp, NATRestricted, "") So(err, ShouldBeNil) r, err := http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil)
clientOffers(i, w, r)
ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, "client-denied-count 8\nclient-restricted-denied-count 8\nclient-unrestricted-denied-count 0\nclient-snowflake-match-count 0")
buf.Reset() ctx.metrics.zeroMetrics()
data, err = createClientOffer(sdp, NATUnrestricted, "") So(err, ShouldBeNil) r, err = http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil)
clientOffers(i, w, r)
ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, "client-denied-count 8\nclient-restricted-denied-count 0\nclient-unrestricted-denied-count 8\nclient-snowflake-match-count 0")
buf.Reset() ctx.metrics.zeroMetrics()
data, err = createClientOffer(sdp, NATUnknown, "") So(err, ShouldBeNil) r, err = http.NewRequest("POST", "snowflake.broker/client", data) So(err, ShouldBeNil)
clientOffers(i, w, r)
ctx.metrics.printMetrics() So(buf.String(), ShouldContainSubstring, "client-denied-count 8\nclient-restricted-denied-count 8\nclient-unrestricted-denied-count 0\nclient-snowflake-match-count 0") }) Convey("for country stats order", func() {
stats := map[string]int{ "IT": 50, "FR": 200, "TZ": 100, "CN": 250, "RU": 150, "CA": 1, "BE": 1, "PH": 1, } ctx.metrics.countryStats.counts = stats So(ctx.metrics.countryStats.Display(), ShouldEqual, "CN=250,FR=200,RU=150,TZ=100,IT=50,BE=1,CA=1,PH=1") }) })}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152/*Keeping track of pending available snowflake proxies.*/
package main
/*The Snowflake struct contains a single interactionover the offer and answer channels.*/type Snowflake struct { id string proxyType string natType string offerChannel chan *ClientOffer answerChannel chan string clients int index int}
// Implements heap.Interface, and holds Snowflakes.type SnowflakeHeap []*Snowflake
func (sh SnowflakeHeap) Len() int { return len(sh) }
func (sh SnowflakeHeap) Less(i, j int) bool { // Snowflakes serving less clients should sort earlier. return sh[i].clients < sh[j].clients}
func (sh SnowflakeHeap) Swap(i, j int) { sh[i], sh[j] = sh[j], sh[i] sh[i].index = i sh[j].index = j}
func (sh *SnowflakeHeap) Push(s interface{}) { n := len(*sh) snowflake := s.(*Snowflake) snowflake.index = n *sh = append(*sh, snowflake)}
// Only valid when Len() > 0.func (sh *SnowflakeHeap) Pop() interface{} { flakes := *sh n := len(flakes) snowflake := flakes[n-1] snowflake.index = -1 *sh = flakes[0 : n-1] return snowflake}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211package main
import ( "context" "log" "strconv" "strings" "time"
"github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/messages" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/sqsclient")
const ( cleanupThreshold = -2 * time.Minute)
type sqsHandler struct { SQSClient sqsclient.SQSClient SQSQueueURL *string IPC *IPC cleanupInterval time.Duration}
func (r *sqsHandler) pollMessages(ctx context.Context, chn chan<- *types.Message) { for { select { case <-ctx.Done(): // if context is cancelled return default: res, err := r.SQSClient.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{ QueueUrl: r.SQSQueueURL, MaxNumberOfMessages: 10, WaitTimeSeconds: 15, MessageAttributeNames: []string{ string(types.QueueAttributeNameAll), }, })
if err != nil { log.Printf("SQSHandler: encountered error while polling for messages: %v\n", err) continue }
for _, message := range res.Messages { chn <- &message } } }}
func (r *sqsHandler) cleanupClientQueues(ctx context.Context) { for range time.NewTicker(r.cleanupInterval).C { // Runs at fixed intervals to clean up any client queues that were last changed more than 2 minutes ago select { case <-ctx.Done(): // if context is cancelled return default: queueURLsList := []string{} var nextToken *string for { res, err := r.SQSClient.ListQueues(ctx, &sqs.ListQueuesInput{ QueueNamePrefix: aws.String("snowflake-client-"), MaxResults: aws.Int32(1000), NextToken: nextToken, }) if err != nil { log.Printf("SQSHandler: encountered error while retrieving client queues to clean up: %v\n", err) // client queues will be cleaned up the next time the cleanup operation is triggered automatically break } queueURLsList = append(queueURLsList, res.QueueUrls...) if res.NextToken == nil { break } else { nextToken = res.NextToken } }
numDeleted := 0 cleanupCutoff := time.Now().Add(cleanupThreshold) for _, queueURL := range queueURLsList { if !strings.Contains(queueURL, "snowflake-client-") { continue } res, err := r.SQSClient.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{ QueueUrl: aws.String(queueURL), AttributeNames: []types.QueueAttributeName{types.QueueAttributeNameLastModifiedTimestamp}, }) if err != nil { // According to the AWS SQS docs, the deletion process for a queue can take up to 60 seconds. So the queue // can be in the process of being deleted, but will still be returned by the ListQueues operation, but // fail when we try to GetQueueAttributes for the queue log.Printf("SQSHandler: encountered error while getting attribute of client queue %s. queue may already be deleted.\n", queueURL) continue } lastModifiedInt64, err := strconv.ParseInt(res.Attributes[string(types.QueueAttributeNameLastModifiedTimestamp)], 10, 64) if err != nil { log.Printf("SQSHandler: encountered invalid lastModifiedTimetamp value from client queue %s: %v\n", queueURL, err) continue } lastModified := time.Unix(lastModifiedInt64, 0) if lastModified.Before(cleanupCutoff) { _, err := r.SQSClient.DeleteQueue(ctx, &sqs.DeleteQueueInput{ QueueUrl: aws.String(queueURL), }) if err != nil { log.Printf("SQSHandler: encountered error when deleting client queue %s: %v\n", queueURL, err) continue } else { numDeleted += 1 }
} } log.Printf("SQSHandler: finished running iteration of client queue cleanup. found and deleted %d client queues.\n", numDeleted) } }}
func (r *sqsHandler) handleMessage(context context.Context, message *types.Message) { var encPollReq []byte var response []byte var err error
clientID := message.MessageAttributes["ClientID"].StringValue if clientID == nil { log.Println("SQSHandler: got SDP offer in SQS message with no client ID. ignoring this message.") return }
res, err := r.SQSClient.CreateQueue(context, &sqs.CreateQueueInput{ QueueName: aws.String("snowflake-client-" + *clientID), }) if err != nil { log.Printf("SQSHandler: error encountered when creating answer queue for client %s: %v\n", *clientID, err) return } answerSQSURL := res.QueueUrl
encPollReq = []byte(*message.Body) arg := messages.Arg{ Body: encPollReq, RemoteAddr: "", RendezvousMethod: messages.RendezvousSqs, } err = r.IPC.ClientOffers(arg, &response)
if err != nil { log.Printf("SQSHandler: error encountered when handling message: %v\n", err) return }
r.SQSClient.SendMessage(context, &sqs.SendMessageInput{ QueueUrl: answerSQSURL, MessageBody: aws.String(string(response)), })}
func (r *sqsHandler) deleteMessage(context context.Context, message *types.Message) { r.SQSClient.DeleteMessage(context, &sqs.DeleteMessageInput{ QueueUrl: r.SQSQueueURL, ReceiptHandle: message.ReceiptHandle, })}
func newSQSHandler(context context.Context, client sqsclient.SQSClient, sqsQueueName string, region string, i *IPC) (*sqsHandler, error) { // Creates the queue if a queue with the same name doesn't exist. If a queue with the same name and attributes // already exists, then nothing will happen. If a queue with the same name, but different attributes exists, then // an error will be returned res, err := client.CreateQueue(context, &sqs.CreateQueueInput{ QueueName: aws.String(sqsQueueName), Attributes: map[string]string{ "MessageRetentionPeriod": strconv.FormatInt(int64((5 * time.Minute).Seconds()), 10), }, })
if err != nil { return nil, err }
return &sqsHandler{ SQSClient: client, SQSQueueURL: res.QueueUrl, IPC: i, cleanupInterval: time.Second * 30, }, nil}
func (r *sqsHandler) PollAndHandleMessages(ctx context.Context) { log.Println("SQSHandler: Starting to poll for messages at: " + *r.SQSQueueURL) messagesChn := make(chan *types.Message, 2) go r.pollMessages(ctx, messagesChn) go r.cleanupClientQueues(ctx)
for message := range messagesChn { select { case <-ctx.Done(): // if context is cancelled return default: r.handleMessage(ctx, message) r.deleteMessage(ctx, message) } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338package main
import ( "bytes" "context" "errors" "log" "strconv" "sync" "testing" "time"
"github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" "github.com/golang/mock/gomock" . "github.com/smartystreets/goconvey/convey" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/sqsclient")
func TestSQS(t *testing.T) {
Convey("Context", t, func() { buf := new(bytes.Buffer) ipcCtx := NewBrokerContext(log.New(buf, "", 0)) i := &IPC{ipcCtx}
var logBuffer bytes.Buffer log.SetOutput(&logBuffer)
Convey("Responds to SQS client offers...", func() { ctrl := gomock.NewController(t) mockSQSClient := sqsclient.NewMockSQSClient(ctrl)
brokerSQSQueueName := "example-name" responseQueueURL := aws.String("https://sqs.us-east-1.amazonaws.com/testing")
runSQSHandler := func(sqsHandlerContext context.Context) { mockSQSClient.EXPECT().CreateQueue(sqsHandlerContext, &sqs.CreateQueueInput{ QueueName: aws.String(brokerSQSQueueName), Attributes: map[string]string{ "MessageRetentionPeriod": strconv.FormatInt(int64((5 * time.Minute).Seconds()), 10), }, }).Return(&sqs.CreateQueueOutput{ QueueUrl: responseQueueURL, }, nil).Times(1) sqsHandler, err := newSQSHandler(sqsHandlerContext, mockSQSClient, brokerSQSQueueName, "example-region", i) So(err, ShouldBeNil) go sqsHandler.PollAndHandleMessages(sqsHandlerContext) }
messageBody := aws.String("1.0\n{\"offer\": \"fake\", \"nat\": \"unknown\"}") receiptHandle := "fake-receipt-handle" sqsReceiveMessageInput := sqs.ReceiveMessageInput{ QueueUrl: responseQueueURL, MaxNumberOfMessages: 10, WaitTimeSeconds: 15, MessageAttributeNames: []string{ string(types.QueueAttributeNameAll), }, } sqsDeleteMessageInput := sqs.DeleteMessageInput{ QueueUrl: responseQueueURL, ReceiptHandle: &receiptHandle, }
Convey("by ignoring it if no client id specified", func(c C) { var wg sync.WaitGroup wg.Add(1)
sqsHandlerContext, sqsCancelFunc := context.WithCancel(context.Background()) defer sqsCancelFunc() defer wg.Wait() mockSQSClient.EXPECT().ReceiveMessage(sqsHandlerContext, &sqsReceiveMessageInput).MinTimes(1).DoAndReturn( func(ctx context.Context, input *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { return &sqs.ReceiveMessageOutput{ Messages: []types.Message{ { Body: messageBody, ReceiptHandle: &receiptHandle, }, }, }, nil }, ) mockSQSClient.EXPECT().DeleteMessage(sqsHandlerContext, &sqsDeleteMessageInput).Times(1).Do( func(ctx context.Context, input *sqs.DeleteMessageInput, optFns ...func(*sqs.Options)) { defer wg.Done() c.So(logBuffer.String(), ShouldContainSubstring, "SQSHandler: got SDP offer in SQS message with no client ID. ignoring this message.") mockSQSClient.EXPECT().DeleteMessage(sqsHandlerContext, &sqsDeleteMessageInput).AnyTimes() }, ) runSQSHandler(sqsHandlerContext) })
Convey("by doing nothing if an error occurs upon receipt of the message", func(c C) { var wg sync.WaitGroup wg.Add(2)
sqsHandlerContext, sqsCancelFunc := context.WithCancel(context.Background()) defer sqsCancelFunc() defer wg.Wait()
numTimes := 0 // When ReceiveMessage is called for the first time, the error has not had a chance to be logged yet. // Therefore, we opt to wait for the second call because we are guaranteed that the error was logged // by then. mockSQSClient.EXPECT().ReceiveMessage(sqsHandlerContext, &sqsReceiveMessageInput).MinTimes(2).DoAndReturn( func(ctx context.Context, input *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { numTimes += 1 if numTimes <= 2 { wg.Done() if numTimes == 2 { c.So(logBuffer.String(), ShouldContainSubstring, "SQSHandler: encountered error while polling for messages: error") } } return nil, errors.New("error") }, ) runSQSHandler(sqsHandlerContext) })
Convey("by attempting to create a new sqs queue...", func() { clientId := "fake-id" sqsCreateQueueInput := sqs.CreateQueueInput{ QueueName: aws.String("snowflake-client-fake-id"), }
expectReceiveMessageReturnsValidMessage := func(sqsHandlerContext context.Context) { mockSQSClient.EXPECT().ReceiveMessage(sqsHandlerContext, &sqsReceiveMessageInput).AnyTimes().DoAndReturn( func(ctx context.Context, input *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) { return &sqs.ReceiveMessageOutput{ Messages: []types.Message{ { Body: messageBody, MessageAttributes: map[string]types.MessageAttributeValue{ "ClientID": {StringValue: &clientId}, }, ReceiptHandle: &receiptHandle, }, }, }, nil }, ) }
Convey("and does not attempt to send a message via SQS if queue creation fails.", func(c C) { var wg sync.WaitGroup wg.Add(2)
sqsHandlerContext, sqsCancelFunc := context.WithCancel(context.Background()) defer sqsCancelFunc() defer wg.Wait()
expectReceiveMessageReturnsValidMessage(sqsHandlerContext) mockSQSClient.EXPECT().CreateQueue(sqsHandlerContext, &sqsCreateQueueInput).Return(nil, errors.New("error")).AnyTimes() numTimes := 0 mockSQSClient.EXPECT().DeleteMessage(sqsHandlerContext, &sqsDeleteMessageInput).MinTimes(2).Do( func(ctx context.Context, input *sqs.DeleteMessageInput, optFns ...func(*sqs.Options)) { numTimes += 1 if numTimes <= 2 { wg.Done() if numTimes == 2 { c.So(logBuffer.String(), ShouldContainSubstring, "SQSHandler: error encountered when creating answer queue for client fake-id: error") } } }, ) runSQSHandler(sqsHandlerContext) })
Convey("and responds with a proxy answer if available.", func(c C) { var wg sync.WaitGroup wg.Add(1)
sqsHandlerContext, sqsCancelFunc := context.WithCancel(context.Background()) defer sqsCancelFunc() defer wg.Wait()
expectReceiveMessageReturnsValidMessage(sqsHandlerContext) mockSQSClient.EXPECT().CreateQueue(sqsHandlerContext, &sqsCreateQueueInput).Return(&sqs.CreateQueueOutput{ QueueUrl: responseQueueURL, }, nil).AnyTimes() mockSQSClient.EXPECT().DeleteMessage(sqsHandlerContext, &sqsDeleteMessageInput).AnyTimes() numTimes := 0 mockSQSClient.EXPECT().SendMessage(sqsHandlerContext, gomock.Any()).MinTimes(1).DoAndReturn( func(ctx context.Context, input *sqs.SendMessageInput, optFns ...func(*sqs.Options)) (*sqs.SendMessageOutput, error) { numTimes += 1 if numTimes == 1 { c.So(input.MessageBody, ShouldEqual, aws.String("{\"answer\":\"fake answer\"}")) // Ensure that match is correctly recorded in metrics ipcCtx.metrics.printMetrics() c.So(buf.String(), ShouldContainSubstring, `client-denied-count 0client-restricted-denied-count 0client-unrestricted-denied-count 0client-snowflake-match-count 8client-http-count 0client-ampcache-count 0client-sqs-count 8`) wg.Done() } return &sqs.SendMessageOutput{}, nil }, ) runSQSHandler(sqsHandlerContext)
snowflake := ipcCtx.AddSnowflake("fake", "", NATUnrestricted, 0)
offer := <-snowflake.offerChannel So(offer.sdp, ShouldResemble, []byte("fake"))
snowflake.answerChannel <- "fake answer" }) }) })
Convey("Cleans up SQS client queues...", func() { brokerSQSQueueName := "example-name" responseQueueURL := aws.String("https://sqs.us-east-1.amazonaws.com/testing")
ctrl := gomock.NewController(t) mockSQSClient := sqsclient.NewMockSQSClient(ctrl)
runSQSHandler := func(sqsHandlerContext context.Context) {
mockSQSClient.EXPECT().CreateQueue(sqsHandlerContext, &sqs.CreateQueueInput{ QueueName: aws.String(brokerSQSQueueName), Attributes: map[string]string{ "MessageRetentionPeriod": strconv.FormatInt(int64((5 * time.Minute).Seconds()), 10), }, }).Return(&sqs.CreateQueueOutput{ QueueUrl: responseQueueURL, }, nil).Times(1)
mockSQSClient.EXPECT().ReceiveMessage(sqsHandlerContext, gomock.Any()).AnyTimes().Return( &sqs.ReceiveMessageOutput{ Messages: []types.Message{}, }, nil, )
sqsHandler, err := newSQSHandler(sqsHandlerContext, mockSQSClient, brokerSQSQueueName, "example-region", i) So(err, ShouldBeNil) // Set the cleanup interval to 1 ns so we can immediately test the cleanup logic sqsHandler.cleanupInterval = time.Nanosecond
go sqsHandler.PollAndHandleMessages(sqsHandlerContext) }
Convey("does nothing if there are no open queues.", func() { var wg sync.WaitGroup wg.Add(1) sqsHandlerContext, sqsCancelFunc := context.WithCancel(context.Background()) defer wg.Wait()
mockSQSClient.EXPECT().ListQueues(sqsHandlerContext, &sqs.ListQueuesInput{ QueueNamePrefix: aws.String("snowflake-client-"), MaxResults: aws.Int32(1000), NextToken: nil, }).DoAndReturn(func(ctx context.Context, input *sqs.ListQueuesInput, optFns ...func(*sqs.Options)) (*sqs.ListQueuesOutput, error) { wg.Done() // Cancel the handler context since we are only interested in testing one iteration of the cleanup sqsCancelFunc() return &sqs.ListQueuesOutput{ QueueUrls: []string{}, }, nil })
runSQSHandler(sqsHandlerContext) })
Convey("deletes open queue when there is one open queue.", func(c C) { var wg sync.WaitGroup wg.Add(1) sqsHandlerContext, sqsCancelFunc := context.WithCancel(context.Background())
clientQueueUrl1 := "https://sqs.us-east-1.amazonaws.com/snowflake-client-1" clientQueueUrl2 := "https://sqs.us-east-1.amazonaws.com/snowflake-client-2"
gomock.InOrder( mockSQSClient.EXPECT().ListQueues(sqsHandlerContext, &sqs.ListQueuesInput{ QueueNamePrefix: aws.String("snowflake-client-"), MaxResults: aws.Int32(1000), NextToken: nil, }).Times(1).Return(&sqs.ListQueuesOutput{ QueueUrls: []string{ clientQueueUrl1, clientQueueUrl2, }, }, nil), mockSQSClient.EXPECT().ListQueues(sqsHandlerContext, &sqs.ListQueuesInput{ QueueNamePrefix: aws.String("snowflake-client-"), MaxResults: aws.Int32(1000), NextToken: nil, }).Times(1).DoAndReturn(func(ctx context.Context, input *sqs.ListQueuesInput, optFns ...func(*sqs.Options)) (*sqs.ListQueuesOutput, error) { // Executed on second iteration of cleanupClientQueues loop. This means that one full iteration has completed and we can verify the results of that iteration wg.Done() sqsCancelFunc() c.So(logBuffer.String(), ShouldContainSubstring, "SQSHandler: finished running iteration of client queue cleanup. found and deleted 2 client queues.") return &sqs.ListQueuesOutput{ QueueUrls: []string{}, }, nil }), )
gomock.InOrder( mockSQSClient.EXPECT().GetQueueAttributes(sqsHandlerContext, &sqs.GetQueueAttributesInput{ QueueUrl: aws.String(clientQueueUrl1), AttributeNames: []types.QueueAttributeName{types.QueueAttributeNameLastModifiedTimestamp}, }).Times(1).Return(&sqs.GetQueueAttributesOutput{ Attributes: map[string]string{ string(types.QueueAttributeNameLastModifiedTimestamp): "0", }}, nil),
mockSQSClient.EXPECT().GetQueueAttributes(sqsHandlerContext, &sqs.GetQueueAttributesInput{ QueueUrl: aws.String(clientQueueUrl2), AttributeNames: []types.QueueAttributeName{types.QueueAttributeNameLastModifiedTimestamp}, }).Times(1).Return(&sqs.GetQueueAttributesOutput{ Attributes: map[string]string{ string(types.QueueAttributeNameLastModifiedTimestamp): "0", }}, nil), )
gomock.InOrder( mockSQSClient.EXPECT().DeleteQueue(sqsHandlerContext, &sqs.DeleteQueueInput{ QueueUrl: aws.String(clientQueueUrl1), }).Return(&sqs.DeleteQueueOutput{}, nil), mockSQSClient.EXPECT().DeleteQueue(sqsHandlerContext, &sqs.DeleteQueueInput{ QueueUrl: aws.String(clientQueueUrl2), }).Return(&sqs.DeleteQueueOutput{}, nil), )
runSQSHandler(sqsHandlerContext) wg.Wait() }) }) })}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236# Last updated based on February 7 2018 Maxmind GeoLite2 Country# wget https://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz# gunzip GeoLite2-Country.mmdb.gz# python mmdb-convert.py GeoLite2-Country.mmdb16777216,16777471,AU16777472,16778239,CN16778240,16779263,AU16779264,16781311,CN16781312,16785407,JP16785408,16793599,CN16793600,16809983,JP16809984,16842751,TH16842752,16843007,CN16843008,16843263,AU16843264,16859135,CN16859136,16875519,JP16875520,16908287,TH16908288,16909055,CN16909056,16909311,US16909312,16941055,CN16941056,16973823,TH16973824,17039359,CN17039360,17039615,AU2111307776,2111832063,CN2111832064,2112487423,TW2112487424,2112618495,VN2112618496,2112880639,NZ2112880640,2113560063,KR2113560064,2113560319,SG2113560320,2113683455,KR2113683456,2113684607,JP2113684608,2113684671,TW2113684672,2113685663,JP2113685664,2113685695,SG2113685696,2113687999,JP2113688000,2113688031,AU2113688032,2113688959,JP2113688960,2113688991,SG2113688992,2113691135,JP2113691136,2113691391,SG2113691392,2113692415,JP2113692416,2113692671,HK2113692672,2113693599,JP2113693600,2113693615,HK2113693616,2113693879,JP2113693880,2113693887,AU2113693888,2113693951,JP2113693952,2113694207,HK2113694208,2113695279,JP2113695280,2113695287,SG2113695288,2113716223,JP2113716224,2113724927,SG2113724928,2113725183,IN2113725184,2113728511,SG2113728512,2113732607,JP2113732608,2113761279,AU2113761280,2113765375,VN2113765376,2113798143,HK2113798144,2113811455,AU2113811456,2113812479,GB2113812480,2113813503,JP2113813504,2113830911,AU2113830912,2113863679,CN2113863680,2113929215,AU2113929216,2130706431,JP2147483648,2147483903,NL2147483904,2147484671,RO2147484672,2147485695,TR2147485696,2147487743,DK2147487744,2147489791,NO2147489792,2147491839,RU2147491840,2147494911,DE2147494912,2147495167,RO2147495168,2147495423,DE2147495424,2147496959,RO2147496960,2147497215,ES2147497216,2147497471,RO2147497472,2147497727,PL2147497728,2147498239,DE2147498240,2147498495,RO2147498496,2147500031,DE2147500032,2147501055,NL2147501056,2147501311,SK2147501312,2147501567,NL2147501568,2147501823,GL2147501824,2147502079,US2147502080,2147504127,DK2147504128,2147508223,RU2147508224,2147510271,DE2147510272,2147510783,UA2147510784,2147511039,RU2147511040,2147512319,CY2147512320,2147514879,DE2147514880,2147516415,IT2147516416,2147520511,RU2147520512,2147524607,DE2147524608,2147526655,RU2147526656,2147528703,UA2147528704,2147532799,CZ2147532800,2147534847,DE2147534848,2147549183,CY2147549184,2147557375,US2147557376,2147557631,TW2147557632,2147557887,SG2147557888,2147558143,DE2147558144,2147558399,TH2147558400,2147558655,KR2147558656,2147558911,TW2147558912,2147559167,SG2147559168,2147559423,TH2147559424,2147559679,SG2147559680,2147559935,US2147559936,2147560191,DE2147560192,2147560447,RU2147560448,2147560703,TH2147560704,2147560959,TW2147560960,2147562239,US2147562240,2147562495,RU2147562496,2147563263,US2147563264,2147563519,RU2147563520,2147564287,US2147564288,2147564543,AE2147564544,2147564799,US2147564800,2147565055,SG2147565056,2147565311,HK2147565312,2147565999,TW2147566000,2147566047,JP2147566048,2147566079,TW2147566080,2147569407,US2147569408,2147569663,TH2147569664,2147570431,US2147570432,2147570687,JP2147570688,2147571455,US2147571456,2147571711,SG2147571712,2147573503,US2147573504,2147573759,SG2147573760,2147575039,US2147575040,2147575551,TW2147575552,2147575807,SG2147575808,2147576575,US2147576576,2147576831,TW2147576832,2147577087,TH2147577088,2147577599,ID2147577600,2147579647,US2147579648,2147579903,ID2147579904,2147580927,US2147580928,2147581183,ID2147581184,2147581439,TH2147581440,2147592703,US2147592704,2147592959,HK2147592960,2147600127,US2147600128,2147600383,SG2147600384,2147603711,US2147603712,2147603967,IN2147603968,2147942399,US2147942400,2148007935,DE2148007936,2148220515,US2148220516,2148220535,AU2148220536,2148229151,US2148229152,2148229183,CA2148229184,2148459007,US2148459008,2148459519,TW2148459520,2148532223,US2148532224,2148597759,GB2148597760,2148925439,US2148925440,2148990975,JP2148990976,2149253119,US2149253120,2149384191,JP2149384192,2150039551,US2150039552,2150105087,NO2150105088,2150203391,GB2150203392,2150236159,AF2150236160,2150301695,US2150301696,2150367231,CA2150367232,2150432767,US2150432768,2150498303,IT2150498304,2150957055,US2150957056,2151022591,JP2151022592,2151743487,US2151743488,2151759871,BY2151759872,2151768063,US2151768064,2151770111,GB2151770112,2151772159,BA2151772160,2151776255,IT2151776256,2151778303,AT2151778304,2151780351,RU2151780352,2151782399,DE2151782400,2151784447,ES2151784448,2151792639,IR2151792640,2151794687,CH2151794688,2151796735,IT2151796736,2151800831,DE2151800832,2151809023,PT2151809024,2151940095,IT2151940096,2152464383,RU2152464384,2152529919,DK2152529920,2152562687,NO2152562688,2152595455,DK2152595456,2152726527,FR2152726528,2153119743,US2153119744,2153185279,GB2153185280,2153250815,SE2153250816,2153381887,US2153381888,2153382143,JP2153382144,2153383679,US2153383680,2153383935,HK2153383936,2153384447,US2153384448,2153385471,GB2153385472,2153385599,AT2153385600,2153385663,CZ2153385664,2153385727,FI2153385728,2153385791,PL2153385792,2153385855,PT2153385856,2153385919,TR2153385920,2153385983,US2153385984,2153387007,GB2153387008,2153387263,CH2153387264,2153387519,IS2153387520,2153387775,IE2153387776,2153388031,CH2153388032,2153388287,ES2153388288,2153388543,PL2153388544,2153391615,US2153391616,2153391871,HK2153391872,2153394431,US2153394432,2153394943,SG2153394944,2153395455,US2153395456,2153395711,VN2153395712,2153396991,US2153396992,2153397247,IL2153397248,2153397503,IN2153397504,2153397759,SA2153397760,2153398015,QA2153398016,2153398271,BH2153398272,2153398783,JP2153398784,2153399551,US2153399552,2153399807,KR2153399808,2153400319,HK2153400320,2153401087,TW2153401088,2153401599,MO2153401600,2153402111,VN2153402112,2153402367,PH2153402368,2153403135,KR2153403136,2153406463,US2153406464,2153407487,JP2153407488,2153407743,HK2153407744,2153407999,AE2153408000,2153408511,BR2153408512,2153408767,AU2153408768,2153409023,PA2153409024,2153409279,AR2153409280,2153409535,CR2153409536,2153409791,CO2153409792,2153410047,MX2153410048,2153410303,CA2153410304,2153410559,TW2153410560,2153410815,PA2153410816,2153411071,AR2153411072,2153411327,CR2153411328,2153411583,CO2153411584,2153411839,MX2153411840,2153412095,SV2153412096,2153412351,TW2153412352,2153412607,UY2153412608,2153413119,AU2153413120,2153413631,BR2153413632,2153578495,US2153578496,2153644031,FR2153644032,2153906175,US2153906176,2153971711,GB2153971712,2154037247,US2154037248,2154102783,CA2154102784,2154430463,US2154430464,2154495999,SG2154496000,2154561535,US2154561536,2154627071,CN2154627072,2155610111,US2155610112,2155675647,UA2155675648,2155806719,US2155806720,2155808767,IT2155810816,2155812863,FR2155812864,2155814911,GB2155814912,2155819007,NL2155819008,2155819519,DE2155819520,2155821055,CH2155821056,2155823103,IT2155823104,2155825151,DE2155825152,2155827199,AE2155827200,2155831295,PL2155831296,2155833343,RU2155833344,2155833855,SE2155833856,2155834623,NL2155834624,2155834879,LU2155834880,2155835391,NL2155835392,2155839487,RO2155839488,2155843583,FR2155843584,2155845631,RU2155845632,2155847679,DE2155847680,2155849727,ES2155849728,2155851775,TR2155853824,2155855871,SE2155855872,2155872255,SA2155872256,2156003327,US2156003328,2156134399,AT2156134400,2156265471,US2156265472,2156331007,KR2156331008,2156593151,US2156593152,2156658687,IL2156658688,2156691455,IR2156691456,2156697599,FR2156697600,2156699647,GR2156699648,2156703743,RU2156703744,2156707839,BG2156707840,2156709887,RU2156709888,2156711935,ES2156711936,2156713983,DE2156713984,2156716031,NL2156716032,2156718079,RO2156718080,2156720127,IS2156720128,2156724223,BY2156724224,2156855295,CH2156855296,2156920831,US2156920832,2156986367,CA2156986368,2159017983,US2159017984,2159083519,DE2159083520,2159149055,US2159149056,2159280127,CH2159280128,2159542271,US2159542272,2159607807,AU2159607808,2159673343,IN2159673344,2159869951,US2159869952,2159935487,CA2159935488,2160525311,US2160525312,2160533503,SG2160533504,2160541695,NL2160541696,2160590847,SG2160590848,2160656383,US2160656384,2160657407,BR2160657408,2160658431,HN2160658432,2160661503,BR2160661504,2160662527,AR2160662528,2160664575,BR2160664576,2160666623,CL2160666624,2160676863,BR2160676864,2160677887,AR2160677888,2160678911,BR2160678912,2160679935,GF2160679936,2160684031,BR2160684032,2160685055,AR2160685056,2160686079,DO2160686080,2160687103,CL2160687104,2160690175,BR2160690176,2160691199,AR2160691200,2160693247,BR2160693248,2160694271,CR2160694272,2160697343,BR2160697344,2160698367,EC2160698368,2160699391,BR2160699392,2160700415,AR2160700416,2160713727,BR2160713728,2160714751,CL2160714752,2160716799,BR2160716800,2160717823,AR2160717824,2160721919,BR2160721920,2160852991,US2160852992,2160885759,RU2160885760,2160893951,AT2160893952,2160902143,RU2160902144,2160906239,NL2160906240,2160908287,FR2160908288,2160910335,PL2160910336,2160914431,NL2160914432,2160918527,SA2160918528,2161508351,US2161508352,2161573887,FI2161573888,2162687999,US2162688000,2162753535,GB2162753536,2162819071,CA2162819072,2162884607,SA2162884608,2163212287,US2163212288,2163277823,GB2163277824,2163408895,US2163408896,2163474431,GB2163474432,2163605503,US2163605504,2163638271,DE2163638272,2163638527,US2163638528,2163671039,DE2163671040,2163867647,US2163867648,2163933183,AU2163933184,2164260863,US2164260864,2164326399,CM2164326400,2164981759,US2164981760,2165112831,GB2165112832,2165178367,DE2165178368,2165309439,US2165309440,2165374975,SE2165374976,2165440511,US2165440512,2165506047,NG2165506048,2165571583,US2165571584,2165637119,FR2165637120,2165964799,US2165964800,2166030335,DE2166030336,2166095871,AT2166095872,2166161407,CN2166161408,2166292479,US2166292480,2166358015,GB2166358016,2166562559,US2166562560,2166562815,FI2166562816,2166571007,US2166571008,2166575103,GB2166575104,2166594559,US2166594560,2166594815,PL2166594816,2166729471,US2166729472,2166729727,CA2166729728,2167209983,US2167209984,2167242751,DZ2167242752,2167275519,BF2167275520,2167930879,US2167930880,2167996415,NG2167996416,2168193023,US2168193024,2168258559,JP2168258560,2168651775,US2168651776,2168717311,GB2168717312,2168782847,US2168782848,2168913919,DE2168913920,2169372671,US2169372672,2169438207,AU2169438208,2170028031,US2170028032,2170093567,FR2170093568,2170159103,US2170159104,2170224639,VE2170224640,2170421247,US2170421248,2170486783,AU2170486784,2170552319,US2170552320,2170617855,AU2170617856,2170683391,CA2170683392,2170814463,US2170814464,2170879999,CA2170880000,2170945535,US2170945536,2171011071,FR3652593408,3652593471,ES3652593472,3652593511,FR3652593512,3652593519,ES3652593520,3652593631,FR3652593632,3652593663,PT3652593664,3652593943,FR3652593944,3652593951,ES3652593952,3652595007,FR3652595008,3652595071,DE3652595072,3652595167,FR3652595168,3652595183,ES3652595184,3652595871,FR3652595872,3652595935,PL3652595936,3652596351,FR3652596352,3652596415,IT3652596416,3652596479,FR3652596480,3652596543,ES3652596544,3652596799,FR3652596800,3652596831,CZ3652596832,3652597183,FR3652597184,3652597247,DE3652597248,3652597375,FR3652597376,3652597383,ES3652597384,3652597407,FR3652597408,3652597439,PL3652597440,3652597887,FR3652597888,3652597903,GB3652597904,3652599569,FR3652599570,3652599570,PT3652599571,3652599679,FR3652599680,3652599743,IT3652599744,3652601855,FR3652601856,3652603903,PL3652603904,3652608191,FR3652608192,3652608223,PT3652608224,3652608255,FR3652608256,3652608511,GB3652608512,3652608639,FR3652608640,3652608767,GB3652608768,3652609023,FR3652609024,3652609279,GB3652609280,3652609503,FR3652609504,3652609535,FI3652609536,3652609727,FR3652609728,3652609759,PL3652609760,3652609791,CZ3652609792,3652609823,FR3652609824,3652609855,CZ3652609856,3652609919,FR3652609920,3652609983,ES3652609984,3652610047,BE3652610048,3652611135,FR3652611136,3652611199,ES3652611200,3652611231,FR3652611232,3652611263,PT3652611264,3652611679,FR3652611680,3652611711,PT3652611712,3652611775,NL3652611776,3652612223,FR3652612224,3652612287,ES3652612288,3652612351,FR3652612352,3652612479,GB3652612480,3652612543,IE3652612544,3652612607,NL3652612608,3652613335,FR3652613336,3652613343,ES3652613344,3652613375,FR3652613376,3652613407,FI3652613408,3652613615,FR3652613616,3652613623,ES3652613624,3652613679,FR3652613680,3652613695,LT3652613696,3652614015,FR3652614016,3652614079,BE3652614080,3652615871,FR3652615872,3652615935,DE3652615936,3652620639,FR3652620640,3652620671,CZ3652620672,3652620735,PT3652620736,3652620799,FR3652620800,3652620831,PT3652620832,3652621247,FR3652621248,3652621311,DE3652621312,3652621375,FR3652621376,3652621439,ES3652621440,3652621503,FR3652621504,3652621567,IT3652621568,3652621631,FR3652621632,3652621663,PT3652621664,3652621823,FR3652621824,3652621951,IE3652621952,3652622271,FR3652622272,3652622335,GB3652622336,3652622879,FR3652622880,3652622911,CZ3652622912,3652623679,FR3652623680,3652623807,NL3652623808,3652624191,FR3652624192,3652624319,IT3652624320,3652628479,FR3652628480,3652628543,IT3652628544,3652628607,FR3652628608,3652628639,PL3652628640,3652628855,FR3652628856,3652628863,ES3652628864,3652629743,FR3652629744,3652629759,ES3652629760,3652630015,FR3652630016,3652630031,ES3652630032,3652630079,FR3652630080,3652630111,PL3652630112,3652631295,FR3652631296,3652631359,BE3652631360,3652631391,FR3652631392,3652631407,CH3652631408,3652631423,FR3652631424,3652631455,PL3652631456,3652631551,FR3652631552,3652631583,CZ3652631584,3652631807,FR3652631808,3652631823,GB3652631824,3652632031,FR3652632032,3652632063,PT3652632064,3652632303,FR3652632304,3652632311,ES3652632312,3652633599,FR3652633600,3652634623,DE3652634624,3652635647,PL3652635648,3652638655,FR3652638656,3652638719,ES3652638720,3652638815,FR3652638816,3652638847,FI3652638848,3652638975,GB3652638976,3652639359,FR3652639360,3652639423,DE3652639424,3652639679,FR3652639680,3652639807,NL3652639808,3652640575,FR3652640576,3652640703,GB3652640704,3652640711,FR3652640712,3652640719,ES3652640720,3652640767,FR3652640768,3652640831,ES3652640832,3652641727,FR3652641728,3652641791,GB3652641792,3652642111,FR3652642112,3652642175,IE3652642176,3652642239,FR3652642240,3652642303,DE3652642304,3652642367,FR3652642368,3652642431,GB3652642432,3652642719,FR3652642720,3652642751,PT3652642752,3652642975,FR3652642976,3652643007,IE3652643008,3652643375,FR3652643376,3652643379,ES3652643380,3652643519,FR3652643520,3652643583,NL3652643584,3652643647,ES3652643648,3652644031,FR3652644032,3652644063,BE3652644064,3652644199,FR3652644200,3652644215,ES3652644216,3652644223,FR3652644224,3652644239,NL3652644240,3652644247,FR3652644248,3652644255,ES3652644256,3652644351,FR3652644352,3652644383,FI3652644384,3652644415,PL3652644416,3652644575,FR3652644576,3652644607,DE3652644608,3652645119,FR3652645120,3652645503,GB3652645504,3652645663,FR3652645664,3652645695,FI3652645696,3652645887,FR3652645888,3652646015,NL3652646016,3652646079,ES3652646080,3652646111,FR3652646112,3652646143,CZ3652646144,3652646271,NL3652646272,3652646655,FR3652646656,3652646719,ES3652646720,3652646799,FR3652646800,3652646815,PL3652646816,3652646847,FR3652646848,3652646863,FI3652646864,3652648847,FR3652648848,3652648863,LT3652648864,3652648895,FI3652648896,3652648959,DE3652648960,3652714495,IE3652714496,3653238783,DE3653238784,3653369855,CH3653369856,3653373951,IT3653373952,3653378047,NL3653378048,3653382143,DE3653382144,3653386239,CH3653386240,3653390335,DE3653390336,3653394431,FR3653394432,3653402623,NL3653402624,3653406557,GB3653406558,3653406558,GN3653406559,3653406617,GB3653406618,3653406618,GN3653406619,3653407103,GB3653407104,3653407111,UG3653407112,3653408071,GB3653408072,3653408079,NG3653408080,3653408231,GB3653408232,3653408239,KE3653408240,3653410815,GB3653410816,3653414911,CZ3653414912,3653419007,IT3653419008,3653423103,IL3653423104,3653427199,GB3653427200,3653431295,DE3653431296,3653435391,RU3653435392,3653439487,DE3653439488,3653443583,FR3653443584,3653447679,DE3653447680,3653451775,LV3653451776,3653464063,RU3653464064,3653468159,NL3653468160,3653472255,GR3653476352,3653480447,CZ3653480448,3653484543,DK3653484544,3653488639,TR3653488640,3653492735,RU3653492736,3653500927,NL3653500928,3653505023,GB3653505024,3653509119,KZ3653509120,3653513215,NL3653513216,3653517311,NO3653517312,3653525503,AT3653525504,3653529599,RU3653529600,3653533695,CZ3653533696,3653537791,IT3653537792,3653541887,AT3653541888,3653545983,UA3653545984,3653550079,CH3653550080,3653554175,MK3653554176,3653558271,CZ3653558272,3653566463,GB3653566464,3653570559,RU3653570560,3653574655,ES3653574656,3653578751,CZ3653578752,3653582847,SE3653582848,3653586943,PL3653586944,3653591039,DE3653591040,3653595135,LU3653595136,3653599231,RU3653599232,3653601279,CH3653601280,3653603327,BA3653603328,3653607423,CZ3653611520,3653615615,HU3653615616,3653619711,RU3653619712,3653623807,CH3653623808,3653636095,RU3653636096,3653640191,NL3653640192,3653648383,GB3653648384,3653652479,SE3653652480,3653656575,RU3653656576,3653660671,GB3653660672,3653664767,CZ3653664768,3653668863,DE3653668864,3653672959,SE3653672960,3653681151,RU3653681152,3653685247,ES3653685248,3653689343,DK3653689344,3653693439,LV3653693440,3653697535,DE3653697536,3653705727,IT3653705728,3653708331,NO3653708332,3653708332,FI3653708333,3653713919,NO3653713920,3653718015,DE3653718016,3653722111,AT3653722112,3653730303,LV3653730304,3653734399,BA3653734400,3653738495,KE3653738496,3653746687,GB3653746688,3653750783,DE3653750784,3653754879,RU3653754880,3653758975,UA3653758976,3653763071,RU3653763072,3654025215,IT3654025216,3654287359,GB3654287360,3654608404,SE3654608405,3654608405,NO3654608406,3654608895,SE3654608896,3654609919,NO3654609920,3654610431,SE3654610432,3654610943,FR3654610944,3654610951,SE3654610952,3654610959,DE3654610960,3654612231,SE3654612232,3654612239,AT3654612240,3654612271,SE3654612272,3654612287,AT3654612288,3654614047,SE3654614048,3654614063,GB3654614064,3654614079,SE3654614080,3654614271,FI3654614272,3654811647,SE3654811648,3654942719,ES3654942720,3655073791,IR3655073792,3655335935,IT3655335936,3657433087,DE3657433088,3659415455,CN3659415456,3659415487,SG3659415488,3659530239,CN3659530240,3659595775,TW3659595776,3659628543,ID3659628544,3659661311,JP3659661312,3659792383,TW3659792384,3660054527,KR3660054528,3660578815,JP3660578816,3661103103,KR3661103104,3663986687,CN3663986688,3663987711,AU3663987712,3663987967,ID3663987968,3663989247,JP3663989248,3663989503,VN3663989504,3663989759,ID3663989760,3663990271,AU3663990272,3663990527,VN3663990528,3663990783,JP3663990784,3663991295,HK3663991296,3663991551,MY3663991552,3663991807,AU3663992064,3663992319,NZ3663992320,3663992575,MY3663992576,3663993599,NZ3663993600,3663996159,ID3663996160,3663996415,AU3663996416,3663996671,TH3663996672,3663997183,AU3663997184,3663997439,ID3663997440,3663997695,JP3663997696,3663997951,AU3663997952,3663998207,MY3663998208,3663998463,JP3663998464,3663998975,TH3663998976,3663999487,IN3663999488,3663999743,AU3664000000,3664000767,AU3664000768,3664001023,ID3664001024,3664001279,NZ3664001280,3664001535,LK3664001536,3664001791,MY3664002048,3664002303,VN3664002304,3664002559,LK3664002560,3664003327,ID3664003328,3664003583,NZ3664003584,3664003839,TH3664003840,3664004095,JP3664004352,3664004607,MY3664004864,3664005119,KH3664005120,3664005887,ID3664005888,3664006143,MY3664006144,3664006399,AU3664006400,3664006655,PF3664006656,3664006911,AU3664007168,3664008191,AU3664008192,3664008447,MN3664008448,3664008703,PK3664008960,3664010239,AU3664010240,3664052223,CN3664052224,3664084991,NZ3664084992,3664117759,KR3664117760,3664248831,HK3664248832,3664642047,CN3664642048,3664707583,JP3664707584,3664773119,MY3664773120,3666870271,JP3666870272,3666960455,KR3666960456,3666960456,US3666960457,3667918847,KR3667918848,3668967423,TW3668967424,3669491711,JP3669491712,3669557247,TW3669557248,3669590015,AU3669590016,3669606399,JP3669606400,3669614591,CN3669614592,3669616639,NZ3669616640,3669618687,AU3669618688,3669620735,CN3669620736,3669622783,IN3669622784,3669688319,SG3669688320,3669753855,TW3669753856,3670015999,HK3670016000,3671064575,CN3671064576,3671130111,MY3671130112,3671195647,KR3671195648,3671326719,TW3671326720,3671392255,SG3671392256,3671457791,HK3671457792,3671588863,AU3671588864,3672637439,JP3672637440,3673161727,KR3673161728,3673686015,CN3673686016,3673751551,IN3673751552,3673817087,CN3673817088,3673882623,HK3673882624,3673948159,JP3673948160,3674210303,HK3674210304,3678404607,JP3678404608,3678535679,IN3678535680,3678666751,JP3678666752,3678928895,TW3678928896,3678994431,CN3678994432,3679027199,HK3679027200,3679059967,JP3679059968,3679158271,SG3679158272,3679191039,JP3679191040,3679453183,HK3679453184,3679584255,TW3679584256,3679649791,CN3679649792,3679682559,ID3679682560,3679715327,CN3679715328,3679977471,TW3679977472,3680108543,NZ3680108544,3680124927,TW3680124928,3680125951,IN3680125952,3680129023,CN3680129024,3680133119,PH3680133120,3680137215,IN3680137216,3680141311,HK3680141312,3680174079,AU3680174080,3680206847,TW3680206848,3680239615,IN3680239616,3680403455,MY3680403456,3680436223,JP3680436224,3680501759,MY3680501760,3682598911,JP3682598912,3684575268,CN3684575269,3684575269,HK3684575270,3684696063,CN3684696064,3688366079,JP3688366080,3689938943,CN3689938944,3690070015,KR3690070016,3690463231,CN3690463232,3690987519,KR3690987520,3695181823,JP3695181824,3697278975,KR3697278976,3697573887,JP3697573888,3697582079,GB3697582080,3697586175,SG3697586176,3697606655,JP3697606656,3697655807,AU3697655808,3697672191,CN3697672192,3697737727,JP3697737728,3697803263,KR3697803264,3698327551,JP3698327552,3698589695,CN3698589696,3699376127,KR3699376128,3700424703,TW3700424704,3700752383,JP3700752384,3700817919,KR3700817920,3700981759,JP3700981760,3701014527,CN3701014528,3701080063,JP3701080064,3701211135,CN3701211136,3701252095,JP3701252096,3701256191,NC3701256192,3701258239,SG3701258240,3701260287,IN3701260288,3701293055,JP3701293056,3701301247,AU3701301248,3701305343,ID3701305344,3701309439,TW3701309440,3701374975,JP3701374976,3701375999,IN3701376000,3701377023,HK3701377024,3701380095,IN3701380096,3701381119,KH3701381120,3701390335,IN3701390336,3701391359,AU3701391360,3701392383,IN3701392384,3701393407,HK3701393408,3701394431,MY3701394432,3701395455,BD3701395456,3701396479,MY3701396480,3701397247,NZ3701397248,3701397503,AU3701397504,3701398527,JP3701398528,3701399551,MV3701399552,3701400575,HK3701400576,3701401599,TW3701401600,3701402623,BD3701402624,3701403647,BT3701403648,3701404671,CN3701404672,3701405695,HK3701405696,3701406719,JP3701406720,3701407743,HK3701407744,3701473279,JP3701473280,3704619007,CN3704619008,3705667583,JP3705667584,3705929727,IN3705929728,3706060799,TW3706060800,3706126335,KR3706126336,3706142719,CN3706142720,3706159103,VN3706159104,3706191871,CN3706191872,3706207107,SG3706207108,3706207108,US3706207109,3706208255,SG3706208256,3706224639,CN3706224640,3706225663,HK3706225664,3706226687,JP3706226688,3706231807,HK3706231808,3706232831,JP3706232832,3706233343,HK3706233344,3706234367,JP3706234368,3706237951,HK3706237952,3706238975,JP3706238976,3706244095,HK3706244096,3706244863,JP3706244864,3706245887,HK3706245888,3706246143,JP3706246144,3706253823,HK3706253824,3706254335,JP3706254336,3706256895,HK3706256896,3706257151,JP3706257152,3706257407,HK3706257408,3706322943,AU3706322944,3706388479,CN3706388480,3706781695,AU3706781696,3706847231,HK3706847232,3706978303,CN3706978304,3707109375,AU3707109376,3707174911,HK3707174912,3707207679,JP3707207680,3707208703,BD3707208704,3707209727,NZ3707209728,3707211775,CN3707211776,3707215871,NP3707215872,3707217919,BD3707217920,3707219967,ID3707219968,3707222015,AU3707222016,3707224063,JP3707224064,3707240447,LK3707240448,3707568127,CN3707568128,3707633663,AU3707633664,3707699199,JP3707699200,3707764735,SG3707764736,3708600319,CN3708600320,3708616703,JP3708616704,3708813311,CN3708813312,3715629055,JP3715629056,3715653631,TW3715653632,3715655679,BD3715655680,3715657727,IN3715657728,3715661823,SG3715661824,3715670015,AU3715670016,3715671039,KH3715671040,3715672063,AU3715672064,3715674111,JP3715674112,3715678207,HK3715678208,3715694591,PK3715694592,3715710975,VN3715710976,3715719167,AU3715719168,3715727359,PH3715727360,3715729151,AU3715729152,3715729407,NZ3715729408,3715735551,AU3715735552,3715741695,JP3715741696,3715743743,PH3715743744,3715760127,JP3715760128,3715891199,CN3715891200,3716153343,HK3716153344,3716170239,SG3716170240,3716170494,TH3716170495,3716171519,SG3716171520,3716171775,JP3716171776,3716172031,SG3716172032,3716172287,JP3716172288,3716173055,SG3716173056,3716173311,JP3716173312,3716173567,SG3716173568,3716173823,JP3716173824,3716174079,SG3716174080,3716174083,TH3716174084,3716174335,JP3716174336,3716175615,SG3716175616,3716176895,JP3716176896,3716178175,SG3716178176,3716178943,JP3716178944,3716179967,SG3716179968,3716181759,JP3716181760,3716182783,SG3716182784,3716183295,JP3716183296,3716183551,SG3716183552,3716184063,JP3716184064,3716184319,SG3716184320,3716184575,JP3716184576,3716184831,SG3716184832,3716185087,JP3716185088,3716186111,SG3716186112,3716415487,CN3716415488,3716431871,VN3716431872,3716440063,KR3716440064,3716444159,JP3716444160,3716446207,PK3716446208,3716464639,JP3716464640,3716481023,ID3716481024,3716489215,VN3716489216,3716493311,MY3716493312,3716497407,KR3716497408,3716513791,JP3716513792,3716530175,KR3716530176,3716538367,AU3716538368,3716546559,CN3716546560,3716677631,IN3716677632,3716808703,CN3716808704,3718840319,KR3718840320,3718905855,TW3718905856,3719036927,JP3719036928,3719823359,CN3719823360,3720347647,JP3720347648,3720859647,CN3720859648,3720863743,AU3720863744,3723493375,CN3723493376,3725590527,JP3725590528,3730833407,CN3730833408,3732602879,KR3732602880,3732668415,TH3732668416,3732733951,ID3732733952,3732799487,CN3732799488,3732832255,PH3732832256,3732865023,CN3732865024,3732930559,PH3732930560,3733979135,CN3733979136,3734503423,JP3734503424,3734765567,NZ3734765568,3734896639,TW3734896640,3735027711,JP3735027712,3735289855,CN3735289856,3735388159,SG3735388160,3735404543,LK3735404544,3735420927,ID3735420928,3735551999,HK3735552000,3739222015,CN3739222016,3739570175,JP3739570176,3739572223,ID3739572224,3739574271,AU3739574272,3739680767,JP3739680768,3739697151,KR3739697152,3739746303,JP3739746304,3740270591,KR3740270592,3740925951,CN3740925952,3741024255,TW3741024256,3741057023,KR3741057024,3741319167,VN3741319168,3742367743,CN3742367744,3742629887,HK3742629888,3742760959,CN3742760960,3742892031,TW3742892032,3742957567,TH3742957568,3742973951,PH3742973952,3742982143,SG3742982144,3742986239,ID3742986240,3742988287,AU3742988288,3742990335,VU3742990336,3743006719,JP3743006720,3743014911,TH3743014912,3743016959,AU3743016960,3743019007,SG3743019008,3743022079,MY3743022080,3743023103,BD3743023104,3743027199,TW3743027200,3743028223,IN3743028224,3743029247,AF3743029248,3743030271,NZ3743030272,3743035391,IN3743035392,3743039487,HK3743039488,3743055871,TW3743055872,3743088639,KR3743088640,3743093647,AU3743093648,3743093648,NZ3743093649,3743096831,AU3743096832,3743105023,TW3743105024,3743106047,AU3743106048,3743109119,JP3743109120,3743113215,BD3743113216,3743115263,AU3743115264,3743117311,VN3743117312,3743118335,BD3743118336,3743119359,JP3743119360,3743120383,IN3743120384,3743121407,JP3743121408,3743125503,MY3743125504,3743129599,ID3743129600,3743130623,HK3743130624,3743130879,SG3743130880,3743131135,HK3743131136,3743133695,SG3743133696,3743134719,AU3743134720,3743135743,JP3743135744,3743136767,CN3743136768,3743137791,MY3743137792,3743154175,TH3743154176,3743186943,MY3743186944,3743219711,KR3743219712,3743252479,JP3743252480,3743264767,NC3743264768,3743268863,JP3743268864,3743272959,IN3743272960,3743273983,CN3743273984,3743275007,BD3743275008,3743276031,HK3743276032,3743277055,IN3743277056,3743281151,PK3743281152,3743282175,AU3743282176,3743283199,JP3743283200,3743284223,HK3743284224,3743285247,CN3743285248,3743416319,IN3743416320,3745513471,KR3745513472,3749052415,CN3749052416,3749183487,HK3749183488,3749838847,CN3749838848,3749839871,SG3749839872,3749840895,IN3749840896,3749841919,CN3749841920,3749842943,AU3749842944,3749843967,PH3749843968,3749844991,ID3749844992,3749846015,AU3749846016,3749847039,IN3749847040,3749855231,HK3749855232,3749969919,KR3749969920,3750232063,JP3750232064,3750756351,TW3750756352,3752067071,CN3752067072,3752132607,ID3752132608,3752133631,BD3752133632,3752134655,ID3752134656,3752136703,TW3752136704,3752137727,NZ3752137728,3752138751,JP3752138752,3752140799,IN3752140800,3752148991,JP3752148992,3752153087,NZ3752153088,3752157183,JP3752157184,3752165375,AU3752165376,3752198143,KR3752198144,3752329215,CN3752329216,3752853503,KR3752853504,3753902079,IN3753902080,3754033151,CN3754033152,3754164223,KR3754164224,3754229759,IN3754229760,3754295295,HK3754295296,3754426367,CN3754426368,3754491903,TW3754491904,3754688511,CN3754688512,3754950655,TH3754950656,3755474943,CN3755474944,3755737087,JP3755737088,3755868159,CN3755868160,3755933695,KR3755933696,3755966463,JP3755966464,3755974655,IN3755974656,3755976703,JP3755976704,3755978751,KH3755978752,3755986943,CN3755986944,3755988991,JP3755988992,3755990015,HK3755990016,3755991039,SG3755991040,3755999231,JP3755999232,3757047807,IN3757047808,3757834239,CN3757834240,3757850623,AU3757850624,3757858815,JP3757858816,3757862911,AU3757862912,3757867007,JP3757867008,3757875519,CN3757875520,3757875583,HK3757875584,3757899775,CN3757899776,3757965311,KR3757965312,3758063615,CN3758063616,3758079999,HK3758080000,3758088191,KR3758088192,3758090239,ID3758090240,3758091263,AU3758091264,3758092287,CN3758092288,3758093311,HK3758093312,3758094335,IN3758094336,3758095359,HK3758095360,3758095871,CN3758095872,3758096127,SG3758096128,3758096383,AU123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693# Last updated based on February 7 2018 Maxmind GeoLite2 Country# wget https://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz# gunzip GeoLite2-Country.mmdb.gz# python mmdb-convert.py GeoLite2-Country.mmdb600:8801:9400:5a1:948b:ab15:dde3:61a3,600:8801:9400:5a1:948b:ab15:dde3:61a3,US2001:200::,2001:200:ffff:ffff:ffff:ffff:ffff:ffff,JP2001:208::,2001:208:ffff:ffff:ffff:ffff:ffff:ffff,SG2001:218::,2001:218:ffff:ffff:ffff:ffff:ffff:ffff,JP2001:220::,2001:220:ffff:ffff:ffff:ffff:ffff:ffff,KR2001:230::,2001:230:ffff:ffff:ffff:ffff:ffff:ffff,KR2001:238::,2001:238:ffff:ffff:ffff:ffff:ffff:ffff,TW2001:240::,2001:240:ffff:ffff:ffff:ffff:ffff:ffff,JP2620:21:2000::,2620:21:2000:ffff:ffff:ffff:ffff:ffff,US2620:21:4000::,2620:21:4000:ffff:ffff:ffff:ffff:ffff,US2620:21:6000::,2620:21:600f:ffff:ffff:ffff:ffff:ffff,US2620:21:8000::,2620:21:8000:ffff:ffff:ffff:ffff:ffff,US2620:21:a000::,2620:21:a000:ffff:ffff:ffff:ffff:ffff,US2620:21:c000::,2620:21:c000:ffff:ffff:ffff:ffff:ffff,CA2620:21:e000::,2620:21:e000:ffff:ffff:ffff:ffff:ffff,US2620:22::,2620:22::ffff:ffff:ffff:ffff:ffff,US2620:22:2000::,2620:22:2000:ffff:ffff:ffff:ffff:ffff,US2620:22:4000::,2620:22:4000:ffff:ffff:ffff:ffff:ffff,CA2620:22:6000::,2620:22:6000:ffff:ffff:ffff:ffff:ffff,US2620:c2:8000::,2620:c2:8000:ffff:ffff:ffff:ffff:ffff,US2620:c2:c000::,2620:c2:c000:ffff:ffff:ffff:ffff:ffff,US2620:c3::,2620:c3::ffff:ffff:ffff:ffff:ffff,US2620:c3:4000::,2620:c3:4000:ffff:ffff:ffff:ffff:ffff,US2620:c3:8000::,2620:c3:8000:ffff:ffff:ffff:ffff:ffff,US2620:c3:c000::,2620:c3:c00f:ffff:ffff:ffff:ffff:ffff,US2620:c4::,2620:c4::ffff:ffff:ffff:ffff:ffff,US2620:c4:4000::,2620:c4:4000:ffff:ffff:ffff:ffff:ffff,US2620:c4:8000::,2620:c4:8000:ffff:ffff:ffff:ffff:ffff,US2620:c4:c000::,2620:c4:c000:ffff:ffff:ffff:ffff:ffff,CA2620:c5::,2620:c5::ffff:ffff:ffff:ffff:ffff,US2620:c5:4000::,2620:c5:4000:ffff:ffff:ffff:ffff:ffff,US2620:c5:c000::,2620:c5:c000:ffff:ffff:ffff:ffff:ffff,US2620:c6::,2620:c6::ffff:ffff:ffff:ffff:ffff,US2620:c6:4000::,2620:c6:4000:ffff:ffff:ffff:ffff:ffff,US2620:c6:8000::,2620:c6:8000:ffff:ffff:ffff:ffff:ffff,US2620:c6:c000::,2620:c6:c000:ffff:ffff:ffff:ffff:ffff,US2620:c7::,2620:c7::ffff:ffff:ffff:ffff:ffff,US2620:c7:4000::,2620:c7:4000:ffff:ffff:ffff:ffff:ffff,US2620:c7:8000::,2620:c7:8000:ffff:ffff:ffff:ffff:ffff,US2620:c7:c000::,2620:c7:c000:ffff:ffff:ffff:ffff:ffff,US2620:c8::,2620:c8::ffff:ffff:ffff:ffff:ffff,US2620:c8:4000::,2620:c8:4000:ffff:ffff:ffff:ffff:ffff,US2620:c8:c000::,2620:c8:c00f:ffff:ffff:ffff:ffff:ffff,US2620:c9::,2620:c9::ffff:ffff:ffff:ffff:ffff,US2620:c9:4000::,2620:c9:4000:ffff:ffff:ffff:ffff:ffff,US2620:c9:8000::,2620:c9:8000:ffff:ffff:ffff:ffff:ffff,US2620:c9:c000::,2620:c9:c000:ffff:ffff:ffff:ffff:ffff,US2620:ca::,2620:ca::ffff:ffff:ffff:ffff:ffff,US2620:ca:4000::,2620:ca:4000:ffff:ffff:ffff:ffff:ffff,US2620:ca:8000::,2620:ca:8000:ffff:ffff:ffff:ffff:ffff,US2620:ca:c000::,2620:ca:c000:ffff:ffff:ffff:ffff:ffff,US2620:cb::,2620:cb:f:ffff:ffff:ffff:ffff:ffff,US2620:cb:4000::,2620:cb:4000:ffff:ffff:ffff:ffff:ffff,US2620:cb:8000::,2620:cb:8000:ffff:ffff:ffff:ffff:ffff,US2620:cb:c000::,2620:cb:c000:ffff:ffff:ffff:ffff:ffff,US2620:cc::,2620:cc::ffff:ffff:ffff:ffff:ffff,US2620:cc:4000::,2620:cc:4000:ffff:ffff:ffff:ffff:ffff,US2620:cc:8000::,2620:cc:8000:ffff:ffff:ffff:ffff:ffff,US2620:cc:c000::,2620:cc:c000:ffff:ffff:ffff:ffff:ffff,US2620:cd::,2620:cd::ffff:ffff:ffff:ffff:ffff,US2620:cd:4000::,2620:cd:4000:ffff:ffff:ffff:ffff:ffff,US2620:cd:8000::,2620:cd:8000:ffff:ffff:ffff:ffff:ffff,US2620:cd:c000::,2620:cd:c000:ffff:ffff:ffff:ffff:ffff,US2620:ce::,2620:ce::ffff:ffff:ffff:ffff:ffff,US2620:ce:4000::,2620:ce:4000:ffff:ffff:ffff:ffff:ffff,US2620:ce:8000::,2620:ce:8000:ffff:ffff:ffff:ffff:ffff,US2620:ce:c000::,2620:ce:c000:ffff:ffff:ffff:ffff:ffff,US2620:cf:4000::,2620:cf:4000:ffff:ffff:ffff:ffff:ffff,US2620:cf:8000::,2620:cf:8000:ffff:ffff:ffff:ffff:ffff,US2620:cf:c000::,2620:cf:c00f:ffff:ffff:ffff:ffff:ffff,US2620:d0::,2620:d0::ffff:ffff:ffff:ffff:ffff,US2620:d0:4000::,2620:d0:4000:ffff:ffff:ffff:ffff:ffff,US2620:d0:8000::,2620:d0:8000:ffff:ffff:ffff:ffff:ffff,US2620:d0:c000::,2620:d0:c000:ffff:ffff:ffff:ffff:ffff,US2620:d1::,2620:d1::ffff:ffff:ffff:ffff:ffff,US2620:d1:4000::,2620:d1:4000:ffff:ffff:ffff:ffff:ffff,US2620:d1:8000::,2620:d1:8000:ffff:ffff:ffff:ffff:ffff,US2620:d1:c000::,2620:d1:c000:ffff:ffff:ffff:ffff:ffff,US2620:d2::,2620:d2::ffff:ffff:ffff:ffff:ffff,US2620:d2:4000::,2620:d2:4000:ffff:ffff:ffff:ffff:ffff,US2620:d2:8000::,2620:d2:8000:ffff:ffff:ffff:ffff:ffff,US2620:d2:c000::,2620:d2:c000:ffff:ffff:ffff:ffff:ffff,CA2620:d3:4000::,2620:d3:4000:ffff:ffff:ffff:ffff:ffff,US2620:d3:8000::,2620:d3:8000:ffff:ffff:ffff:ffff:ffff,US2620:d3:c000::,2620:d3:c000:ffff:ffff:ffff:ffff:ffff,US2620:d4::,2620:d4::ffff:ffff:ffff:ffff:ffff,US2620:d4:4000::,2620:d4:4000:ffff:ffff:ffff:ffff:ffff,US2620:d4:8000::,2620:d4:8000:ffff:ffff:ffff:ffff:ffff,US2620:d5::,2620:d5::ffff:ffff:ffff:ffff:ffff,US2620:d5:4000::,2620:d5:4000:ffff:ffff:ffff:ffff:ffff,US2620:d5:8000::,2620:d5:8000:ffff:ffff:ffff:ffff:ffff,US2620:d5:c000::,2620:d5:c000:ffff:ffff:ffff:ffff:ffff,US2620:d6::,2620:d6::ffff:ffff:ffff:ffff:ffff,US2620:d6:4000::,2620:d6:4000:ffff:ffff:ffff:ffff:ffff,US2620:d6:8000::,2620:d6:8000:ffff:ffff:ffff:ffff:ffff,US2620:d6:c000::,2620:d6:c000:ffff:ffff:ffff:ffff:ffff,US2620:d7::,2620:d7::ffff:ffff:ffff:ffff:ffff,US2620:d7:4000::,2620:d7:4000:ffff:ffff:ffff:ffff:ffff,CA2620:d7:8000::,2620:d7:8000:ffff:ffff:ffff:ffff:ffff,US2620:d7:c000::,2620:d7:c000:ffff:ffff:ffff:ffff:ffff,US2620:d8::,2620:d8::ffff:ffff:ffff:ffff:ffff,US2620:d8:4000::,2620:d8:4000:ffff:ffff:ffff:ffff:ffff,US2620:d8:8000::,2620:d8:8000:ffff:ffff:ffff:ffff:ffff,US2620:d8:c000::,2620:d8:c000:ffff:ffff:ffff:ffff:ffff,US2620:d9::,2620:d9::ffff:ffff:ffff:ffff:ffff,US2620:d9:4000::,2620:d9:4000:ffff:ffff:ffff:ffff:ffff,US2620:d9:8000::,2620:d9:8000:ffff:ffff:ffff:ffff:ffff,US2620:d9:c000::,2620:d9:c000:ffff:ffff:ffff:ffff:ffff,US2620:da::,2620:da::ffff:ffff:ffff:ffff:ffff,US2620:da:4000::,2620:da:4000:ffff:ffff:ffff:ffff:ffff,US2620:da:c000::,2620:da:c000:ffff:ffff:ffff:ffff:ffff,US2620:db::,2620:db::ffff:ffff:ffff:ffff:ffff,US2620:db:4000::,2620:db:4000:ffff:ffff:ffff:ffff:ffff,CA2620:db:8000::,2620:db:8000:ffff:ffff:ffff:ffff:ffff,US2620:db:c000::,2620:db:c000:ffff:ffff:ffff:ffff:ffff,US2620:dc::,2620:dc::ffff:ffff:ffff:ffff:ffff,US2620:dc:8::,2620:dc:8:ffff:ffff:ffff:ffff:ffff,US2620:dc:4000::,2620:dc:40ff:ffff:ffff:ffff:ffff:ffff,US2620:dc:8000::,2620:dc:8000:ffff:ffff:ffff:ffff:ffff,CA2620:dc:c000::,2620:dc:c000:ffff:ffff:ffff:ffff:ffff,US2620:dd::,2620:dd::ffff:ffff:ffff:ffff:ffff,CA2620:dd:4000::,2620:dd:4000:ffff:ffff:ffff:ffff:ffff,US2620:dd:8000::,2620:dd:8000:ffff:ffff:ffff:ffff:ffff,US2620:dd:c000::,2620:dd:c000:ffff:ffff:ffff:ffff:ffff,US2620:de::,2620:de::ffff:ffff:ffff:ffff:ffff,US2620:de:4000::,2620:de:4000:ffff:ffff:ffff:ffff:ffff,US2620:de:8000::,2620:de:8000:ffff:ffff:ffff:ffff:ffff,US2620:de:c000::,2620:de:c000:ffff:ffff:ffff:ffff:ffff,US2620:df::,2620:df::ffff:ffff:ffff:ffff:ffff,US2620:df:4000::,2620:df:400f:ffff:ffff:ffff:ffff:ffff,US2620:df:8000::,2620:df:8000:ffff:ffff:ffff:ffff:ffff,US2620:df:c000::,2620:df:c000:ffff:ffff:ffff:ffff:ffff,US2620:e0::,2620:e0::ffff:ffff:ffff:ffff:ffff,US2620:e0:4000::,2620:e0:4000:ffff:ffff:ffff:ffff:ffff,US2620:e0:8000::,2620:e0:8000:ffff:ffff:ffff:ffff:ffff,US2620:e0:c000::,2620:e0:c000:ffff:ffff:ffff:ffff:ffff,US2620:e1::,2620:e1::ffff:ffff:ffff:ffff:ffff,US2620:e1:4000::,2620:e1:4000:ffff:ffff:ffff:ffff:ffff,US2620:e1:8000::,2620:e1:8000:ffff:ffff:ffff:ffff:ffff,US2620:e1:c000::,2620:e1:c000:ffff:ffff:ffff:ffff:ffff,VG2620:e2::,2620:e2::ffff:ffff:ffff:ffff:ffff,US2620:e2:4000::,2620:e2:4000:ffff:ffff:ffff:ffff:ffff,US2620:e2:8000::,2620:e2:8000:ffff:ffff:ffff:ffff:ffff,US2620:e2:c000::,2620:e2:c000:ffff:ffff:ffff:ffff:ffff,US2620:e3::,2620:e3::ffff:ffff:ffff:ffff:ffff,US2620:e3:4000::,2620:e3:4000:ffff:ffff:ffff:ffff:ffff,US2620:e3:8000::,2620:e3:8000:ffff:ffff:ffff:ffff:ffff,US2620:e3:c000::,2620:e3:c000:ffff:ffff:ffff:ffff:ffff,US2620:e4::,2620:e4::ffff:ffff:ffff:ffff:ffff,US2620:e4:4000::,2620:e4:4000:ffff:ffff:ffff:ffff:ffff,US2620:e4:8000::,2620:e4:8000:ffff:ffff:ffff:ffff:ffff,US2620:e4:c000::,2620:e4:c000:ffff:ffff:ffff:ffff:ffff,US2620:e5::,2620:e5::ffff:ffff:ffff:ffff:ffff,US2620:e5:4000::,2620:e5:4000:ffff:ffff:ffff:ffff:ffff,US2620:e5:8000::,2620:e5:8000:ffff:ffff:ffff:ffff:ffff,US2620:e5:c000::,2620:e5:c000:ffff:ffff:ffff:ffff:ffff,US2620:e6::,2620:e6::ffff:ffff:ffff:ffff:ffff,US2620:e6:4000::,2620:e6:4000:ffff:ffff:ffff:ffff:ffff,US2620:e6:8000::,2620:e6:8000:ffff:ffff:ffff:ffff:ffff,US2620:e6:c000::,2620:e6:c000:ffff:ffff:ffff:ffff:ffff,US2620:e7::,2620:e7::ffff:ffff:ffff:ffff:ffff,US2620:e7:4000::,2620:e7:4000:ffff:ffff:ffff:ffff:ffff,US2620:e7:8000::,2620:e7:8000:ffff:ffff:ffff:ffff:ffff,CA2620:e7:c000::,2620:e7:c000:ffff:ffff:ffff:ffff:ffff,US2620:e8::,2620:e8::ffff:ffff:ffff:ffff:ffff,US2620:e8:4000::,2620:e8:4000:ffff:ffff:ffff:ffff:ffff,US2620:e8:8000::,2620:e8:8000:ffff:ffff:ffff:ffff:ffff,US2620:e8:c000::,2620:e8:c000:ffff:ffff:ffff:ffff:ffff,US2620:e9::,2620:e9::ffff:ffff:ffff:ffff:ffff,US2620:e9:4000::,2620:e9:4000:ffff:ffff:ffff:ffff:ffff,US2620:e9:8000::,2620:e9:8000:ffff:ffff:ffff:ffff:ffff,US2620:e9:c000::,2620:e9:c000:ffff:ffff:ffff:ffff:ffff,US2620:ea::,2620:ea:f:ffff:ffff:ffff:ffff:ffff,US2620:ea:4000::,2620:ea:4000:ffff:ffff:ffff:ffff:ffff,US2620:ea:8000::,2620:ea:8000:ffff:ffff:ffff:ffff:ffff,US2620:eb::,2620:eb::ffff:ffff:ffff:ffff:ffff,US2620:eb:4000::,2620:eb:4000:ffff:ffff:ffff:ffff:ffff,US2620:eb:8000::,2620:eb:8000:ffff:ffff:ffff:ffff:ffff,US2620:eb:c000::,2620:eb:c000:ffff:ffff:ffff:ffff:ffff,US2620:ec::,2620:ec::ffff:ffff:ffff:ffff:ffff,US2620:ec:4000::,2620:ec:4000:ffff:ffff:ffff:ffff:ffff,US2620:ec:8000::,2620:ec:8000:ffff:ffff:ffff:ffff:ffff,US2620:ec:c000::,2620:ec:c000:ffff:ffff:ffff:ffff:ffff,US2620:ed::,2620:ed::ffff:ffff:ffff:ffff:ffff,US2620:ed:4000::,2620:ed:4000:ffff:ffff:ffff:ffff:ffff,CA2620:ed:8000::,2620:ed:8000:ffff:ffff:ffff:ffff:ffff,US2620:ed:c000::,2620:ed:c000:ffff:ffff:ffff:ffff:ffff,US2620:ee::,2620:ee::ffff:ffff:ffff:ffff:ffff,US2620:ee:4000::,2620:ee:4000:ffff:ffff:ffff:ffff:ffff,US2620:ee:8000::,2620:ee:8000:ffff:ffff:ffff:ffff:ffff,US2620:ee:c000::,2620:ee:c00f:ffff:ffff:ffff:ffff:ffff,US2620:ef:4000::,2620:ef:4000:ffff:ffff:ffff:ffff:ffff,US2620:ef:8000::,2620:ef:8000:ffff:ffff:ffff:ffff:ffff,US2620:ef:c000::,2620:ef:c000:ffff:ffff:ffff:ffff:ffff,US2620:f0::,2620:f0::ffff:ffff:ffff:ffff:ffff,US2620:f0:4000::,2620:f0:400f:ffff:ffff:ffff:ffff:ffff,US2620:f0:8000::,2620:f0:8000:ffff:ffff:ffff:ffff:ffff,US2620:f0:c000::,2620:f0:c002:ffff:ffff:ffff:ffff:ffff,US2620:f0:c003::,2620:f0:c003:ffff:ffff:ffff:ffff:ffff,NL2620:f0:c004::,2620:f0:c004:ffff:ffff:ffff:ffff:ffff,US2620:f0:c005::,2620:f0:c005:ffff:ffff:ffff:ffff:ffff,SG2620:f0:c006::,2620:f0:c009:ffff:ffff:ffff:ffff:ffff,US2620:f0:c00a::,2620:f0:c00a:ffff:ffff:ffff:ffff:ffff,CA2620:f0:c00b::,2620:f0:c00f:ffff:ffff:ffff:ffff:ffff,US2620:f1:4000::,2620:f1:4000:ffff:ffff:ffff:ffff:ffff,CA2620:f1:8000::,2620:f1:8000:ffff:ffff:ffff:ffff:ffff,US2620:f1:c000::,2620:f1:c000:ffff:ffff:ffff:ffff:ffff,US2620:f2::,2620:f2::ffff:ffff:ffff:ffff:ffff,CA2620:f2:4000::,2620:f2:4000:ffff:ffff:ffff:ffff:ffff,US2620:f2:8000::,2620:f2:8000:ffff:ffff:ffff:ffff:ffff,US2620:f2:c000::,2620:f2:c000:ffff:ffff:ffff:ffff:ffff,US2620:f3::,2620:f3::ffff:ffff:ffff:ffff:ffff,US2620:f3:4000::,2620:f3:4000:ffff:ffff:ffff:ffff:ffff,US2620:f3:8000::,2620:f3:8000:ffff:ffff:ffff:ffff:ffff,US2620:f3:c000::,2620:f3:c000:ffff:ffff:ffff:ffff:ffff,US2620:f4::,2620:f4::ffff:ffff:ffff:ffff:ffff,US2620:f4:4000::,2620:f4:40ff:ffff:ffff:ffff:ffff:ffff,US2620:f4:8000::,2620:f4:8000:ffff:ffff:ffff:ffff:ffff,CA2620:f4:c000::,2620:f4:c000:ffff:ffff:ffff:ffff:ffff,US2620:f5::,2620:f5::ffff:ffff:ffff:ffff:ffff,US2620:f5:4000::,2620:f5:4000:ffff:ffff:ffff:ffff:ffff,US2620:f5:8000::,2620:f5:8000:ffff:ffff:ffff:ffff:ffff,US2620:f5:c000::,2620:f5:c000:ffff:ffff:ffff:ffff:ffff,US2620:f6::,2620:f6::ffff:ffff:ffff:ffff:ffff,CA2620:f6:4000::,2620:f6:400f:ffff:ffff:ffff:ffff:ffff,US2620:f6:8000::,2620:f6:8000:ffff:ffff:ffff:ffff:ffff,US2620:f6:c000::,2620:f6:c000:ffff:ffff:ffff:ffff:ffff,CA2620:f7::,2620:f7::ffff:ffff:ffff:ffff:ffff,US2620:f7:4000::,2620:f7:4000:ffff:ffff:ffff:ffff:ffff,US2620:f7:8000::,2620:f7:8000:ffff:ffff:ffff:ffff:ffff,US2620:f7:c000::,2620:f7:c000:ffff:ffff:ffff:ffff:ffff,US2620:f8::,2620:f8::ffff:ffff:ffff:ffff:ffff,US2620:f8:4000::,2620:f8:4000:ffff:ffff:ffff:ffff:ffff,US2620:f8:8000::,2620:f8:8000:ffff:ffff:ffff:ffff:ffff,US2620:f8:c000::,2620:f8:c000:ffff:ffff:ffff:ffff:ffff,US2620:f9::,2620:f9:f:ffff:ffff:ffff:ffff:ffff,US2620:f9:4000::,2620:f9:4000:ffff:ffff:ffff:ffff:ffff,US2620:f9:8000::,2620:f9:8000:ffff:ffff:ffff:ffff:ffff,US2620:f9:c000::,2620:f9:c000:ffff:ffff:ffff:ffff:ffff,US2620:fa::,2620:fa::ffff:ffff:ffff:ffff:ffff,US2620:fa:4000::,2620:fa:4000:ffff:ffff:ffff:ffff:ffff,US2620:fa:8000::,2620:fa:8000:ffff:ffff:ffff:ffff:ffff,CA2620:fa:c000::,2620:fa:c000:ffff:ffff:ffff:ffff:ffff,US2620:fb::,2620:fb::ffff:ffff:ffff:ffff:ffff,US2620:fb:4000::,2620:fb:4000:ffff:ffff:ffff:ffff:ffff,US2620:fb:8000::,2620:fb:8000:ffff:ffff:ffff:ffff:ffff,US2620:fc::,2620:fc::ffff:ffff:ffff:ffff:ffff,CA2620:fc:4000::,2620:fc:4000:ffff:ffff:ffff:ffff:ffff,CA2620:fc:8000::,2620:fc:8000:ffff:ffff:ffff:ffff:ffff,US2620:fc:c000::,2620:fc:c000:ffff:ffff:ffff:ffff:ffff,US2620:fd::,2620:fd::ffff:ffff:ffff:ffff:ffff,CA2620:fd:4000::,2620:fd:4000:ffff:ffff:ffff:ffff:ffff,US2620:fd:8000::,2620:fd:8000:ffff:ffff:ffff:ffff:ffff,US2620:fd:c000::,2620:fd:c000:ffff:ffff:ffff:ffff:ffff,CA2620:fe::,2620:fe::ffff:ffff:ffff:ffff:ffff,US2620:fe:2040::,2620:fe:2040:ffff:ffff:ffff:ffff:ffff,US2620:fe:8000::,2620:fe:8000:ffff:ffff:ffff:ffff:ffff,US2620:fe:c000::,2620:fe:c000:ffff:ffff:ffff:ffff:ffff,US2620:ff::,2620:ff::ffff:ffff:ffff:ffff:ffff,US2620:ff:4000::,2620:ff:4000:ffff:ffff:ffff:ffff:ffff,US2620:ff:8000::,2620:ff:8000:ffff:ffff:ffff:ffff:ffff,US2620:ff:c000::,2620:ff:c000:ffff:ffff:ffff:ffff:ffff,US2620:100::,2620:100:f:ffff:ffff:ffff:ffff:ffff,US2620:100:3000::,2620:100:3007:ffff:ffff:ffff:ffff:ffff,US2620:100:4000::,2620:100:403f:ffff:ffff:ffff:ffff:ffff,US2620:100:5000::,2620:100:5007:ffff:ffff:ffff:ffff:ffff,US2620:100:6000::,2620:100:60ff:ffff:ffff:ffff:ffff:ffff,US2620:100:7000::,2620:100:700f:ffff:ffff:ffff:ffff:ffff,US2620:100:8000::,2620:100:8003:ffff:ffff:ffff:ffff:ffff,US2620:100:9000::,2620:100:900f:ffff:ffff:ffff:ffff:ffff,US2620:100:a000::,2620:100:a00f:ffff:ffff:ffff:ffff:ffff,US2620:100:c000::,2620:100:c03f:ffff:ffff:ffff:ffff:ffff,US2620:100:d000::,2620:100:d00f:ffff:ffff:ffff:ffff:ffff,US2620:100:e000::,2620:100:e00f:ffff:ffff:ffff:ffff:ffff,US2620:100:f000::,2620:100:f00f:ffff:ffff:ffff:ffff:ffff,US2620:101::,2620:101:3:ffff:ffff:ffff:ffff:ffff,US2620:101:1000::,2620:101:103f:ffff:ffff:ffff:ffff:ffff,US2620:101:2000::,2620:101:201f:ffff:ffff:ffff:ffff:ffff,US2620:101:3000::,2620:101:303f:ffff:ffff:ffff:ffff:ffff,US2620:101:4000::,2620:101:403f:ffff:ffff:ffff:ffff:ffff,US2620:101:5000::,2620:101:503f:ffff:ffff:ffff:ffff:ffff,US2620:101:6000::,2620:101:6001:ffff:ffff:ffff:ffff:ffff,US2620:101:7000::,2620:101:7001:ffff:ffff:ffff:ffff:ffff,US2620:101:8000::,2620:101:80f1:ffff:ffff:ffff:ffff:ffff,US2620:101:80f2::,2620:101:80f2:7fff:ffff:ffff:ffff:ffff,CA2620:101:80f2:8000::,2620:101:80ff:ffff:ffff:ffff:ffff:ffff,US2620:101:9000::,2620:101:900f:ffff:ffff:ffff:ffff:ffff,US2620:101:b000::,2620:101:b07f:ffff:ffff:ffff:ffff:ffff,US2620:101:c000::,2620:101:c0ff:ffff:ffff:ffff:ffff:ffff,CA2620:101:d000::,2620:101:d007:ffff:ffff:ffff:ffff:ffff,US2620:101:e000::,2620:101:e00f:ffff:ffff:ffff:ffff:ffff,US2620:101:f000::,2620:101:f001:ffff:ffff:ffff:ffff:ffff,CA2620:102::,2620:102:f:ffff:ffff:ffff:ffff:ffff,US2620:102:2000::,2620:102:200f:ffff:ffff:ffff:ffff:ffff,US2620:102:3000::,2620:102:300f:ffff:ffff:ffff:ffff:ffff,US2620:102:4000::,2620:102:403f:ffff:ffff:ffff:ffff:ffff,US2a07:14c0::,2a07:14c7:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:1500::,2a07:1507:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:1540::,2a07:1547:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:1580::,2a07:1587:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:15c0::,2a07:15c7:ffff:ffff:ffff:ffff:ffff:ffff,TR2a07:1600::,2a07:1607:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:1640::,2a07:1647:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:1680::,2a07:1687:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:16c0::,2a07:16c7:ffff:ffff:ffff:ffff:ffff:ffff,ES2a07:1700::,2a07:1707:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:1740::,2a07:1747:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:1780::,2a07:1787:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:17c0::,2a07:17c7:ffff:ffff:ffff:ffff:ffff:ffff,UA2a07:1800::,2a07:1807:ffff:ffff:ffff:ffff:ffff:ffff,AT2a07:1840::,2a07:1847:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:1880::,2a07:1887:ffff:ffff:ffff:ffff:ffff:ffff,IT2a07:18c0::,2a07:18c7:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:1900::,2a07:1907:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:1940::,2a07:1947:ffff:ffff:ffff:ffff:ffff:ffff,IT2a07:1980::,2a07:1987:ffff:ffff:ffff:ffff:ffff:ffff,IL2a07:19c0::,2a07:19c7:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:1a00::,2a07:1a07:ffff:ffff:ffff:ffff:ffff:ffff,ES2a07:1a40::,2a07:1a47:ffff:ffff:ffff:ffff:ffff:ffff,PL2a07:1a80::,2a07:1a80:6fff:ffff:ffff:ffff:ffff:ffff,SE2a07:1a80:7000::,2a07:1a80:70ff:ffff:ffff:ffff:ffff:ffff,AT2a07:1a80:7100::,2a07:1a87:ffff:ffff:ffff:ffff:ffff:ffff,SE2a07:1ac0::,2a07:1ac7:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:1b00::,2a07:1b07:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:1b40::,2a07:1b47:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:1b80::,2a07:1b87:ffff:ffff:ffff:ffff:ffff:ffff,AT2a07:1bc0::,2a07:1bc7:ffff:ffff:ffff:ffff:ffff:ffff,PL2a07:1c00::,2a07:1c07:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:1c40::,2a07:1c44:3ff:ffff:ffff:ffff:ffff:ffff,AT2a07:1c44:400::,2a07:1c44:4ff:ffff:ffff:ffff:ffff:ffff,DE2a07:1c44:500::,2a07:1c44:609:ffff:ffff:ffff:ffff:ffff,AT2a07:1c44:60a::,2a07:1c44:60a:ffff:ffff:ffff:ffff:ffff,DE2a07:1c44:60b::,2a07:1c44:619:ffff:ffff:ffff:ffff:ffff,AT2a07:1c44:61a::,2a07:1c44:61a:ffff:ffff:ffff:ffff:ffff,KR2a07:1c44:61b::,2a07:1c44:67f:ffff:ffff:ffff:ffff:ffff,AT2a07:1c44:680::,2a07:1c44:6bf:ffff:ffff:ffff:ffff:ffff,KR2a07:1c44:6c0::,2a07:1c44:6ff:ffff:ffff:ffff:ffff:ffff,DE2a07:1c44:700::,2a07:1c44:70f:ffff:ffff:ffff:ffff:ffff,US2a07:1c44:710::,2a07:1c44:1800:ffff:ffff:ffff:ffff:ffff,AT2a07:1c44:1801::,2a07:1c44:1802:ffff:ffff:ffff:ffff:ffff,US2a07:1c44:1803::,2a07:1c44:35ff:ffff:ffff:ffff:ffff:ffff,AT2a07:1c44:3600::,2a07:1c44:36ff:ffff:ffff:ffff:ffff:ffff,GB2a07:1c44:3700::,2a07:1c44:3fff:ffff:ffff:ffff:ffff:ffff,AT2a07:1c44:4000::,2a07:1c44:40ff:ffff:ffff:ffff:ffff:ffff,US2a07:1c44:4100::,2a07:1c44:42ff:ffff:ffff:ffff:ffff:ffff,AT2a07:1c44:4300::,2a07:1c44:43ff:ffff:ffff:ffff:ffff:ffff,HR2a07:1c44:4400::,2a07:1c44:4fff:ffff:ffff:ffff:ffff:ffff,AT2a07:1c44:5000::,2a07:1c44:51ff:ffff:ffff:ffff:ffff:ffff,US2a07:1c44:5200::,2a07:1c47:ffff:ffff:ffff:ffff:ffff:ffff,AT2a07:1c80::,2a07:1c87:ffff:ffff:ffff:ffff:ffff:ffff,SE2a07:1cc0::,2a07:1cc7:ffff:ffff:ffff:ffff:ffff:ffff,PL2a07:1d00::,2a07:1d07:ffff:ffff:ffff:ffff:ffff:ffff,IR2a07:1d40::,2a07:1d47:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:1d80::,2a07:1d87:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:1dc0::,2a07:1dc7:ffff:ffff:ffff:ffff:ffff:ffff,PL2a07:1e00::,2a07:1e07:ffff:ffff:ffff:ffff:ffff:ffff,KZ2a07:1e40::,2a07:1e47:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:1e80::,2a07:1e87:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:1ec0::,2a07:1ec7:ffff:ffff:ffff:ffff:ffff:ffff,IT2a07:1f00::,2a07:1f07:ffff:ffff:ffff:ffff:ffff:ffff,CH2a07:1f40::,2a07:1f47:ffff:ffff:ffff:ffff:ffff:ffff,CZ2a07:1f80::,2a07:1f87:ffff:ffff:ffff:ffff:ffff:ffff,US2a07:1fc0::,2a07:1fc7:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:2000::,2a07:2007:ffff:ffff:ffff:ffff:ffff:ffff,IQ2a07:2040::,2a07:2047:ffff:ffff:ffff:ffff:ffff:ffff,ES2a07:2080::,2a07:2087:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:20c0::,2a07:20c7:ffff:ffff:ffff:ffff:ffff:ffff,CZ2a07:2100::,2a07:2107:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:2140::,2a07:2147:ffff:ffff:ffff:ffff:ffff:ffff,CH2a07:2180::,2a07:2187:ffff:ffff:ffff:ffff:ffff:ffff,SE2a07:21c0::,2a07:21c7:ffff:ffff:ffff:ffff:ffff:ffff,TR2a07:2200::,2a07:2207:ffff:ffff:ffff:ffff:ffff:ffff,IR2a07:2240::,2a07:2247:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:2280::,2a07:2287:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:2300::,2a07:2307:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:2340::,2a07:2347:ffff:ffff:ffff:ffff:ffff:ffff,SE2a07:2380::,2a07:2387:ffff:ffff:ffff:ffff:ffff:ffff,ES2a07:23c0::,2a07:23c7:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:2400::,2a07:2407:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:2440::,2a07:2447:ffff:ffff:ffff:ffff:ffff:ffff,SE2a07:2480::,2a07:2487:ffff:ffff:ffff:ffff:ffff:ffff,IR2a07:24c0::,2a07:24c7:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:2500::,2a07:2507:ffff:ffff:ffff:ffff:ffff:ffff,DK2a07:2540::,2a07:2547:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:2580::,2a07:2587:ffff:ffff:ffff:ffff:ffff:ffff,IT2a07:25c0::,2a07:25c7:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:2600::,2a07:2607:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:2640::,2a07:2647:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:2680::,2a07:2687:ffff:ffff:ffff:ffff:ffff:ffff,DK2a07:26c0::,2a07:26c7:ffff:ffff:ffff:ffff:ffff:ffff,BE2a07:2700::,2a07:2707:ffff:ffff:ffff:ffff:ffff:ffff,TR2a07:2740::,2a07:2747:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:2780::,2a07:2787:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:27c0::,2a07:27c7:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:2800::,2a07:2807:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:2840::,2a07:2847:ffff:ffff:ffff:ffff:ffff:ffff,IT2a07:2880::,2a07:2887:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:28c0::,2a07:28c7:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:2900::,2a07:291f:ffff:ffff:ffff:ffff:ffff:ffff,CH2a07:2a00::,2a07:2a07:ffff:ffff:ffff:ffff:ffff:ffff,ES2a07:2a40::,2a07:2a47:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:2a80::,2a07:2a87:ffff:ffff:ffff:ffff:ffff:ffff,SE2a07:2ac0::,2a07:2ac7:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:2b00::,2a07:2b07:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:2b40::,2a07:2b47:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:2b80::,2a07:2b87:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:2bc0::,2a07:2bc7:ffff:ffff:ffff:ffff:ffff:ffff,ES2a07:2c00::,2a07:2c07:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:2c40::,2a07:2c47:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:2c80::,2a07:2c87:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:2cc0::,2a07:2cc7:ffff:ffff:ffff:ffff:ffff:ffff,IT2a07:2d00::,2a07:2d07:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:2d40::,2a07:2d47:ffff:ffff:ffff:ffff:ffff:ffff,CH2a07:2d80::,2a07:2d87:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:2dc0::,2a07:2dc7:ffff:ffff:ffff:ffff:ffff:ffff,FI2a07:2e00::,2a07:2e07:ffff:ffff:ffff:ffff:ffff:ffff,CH2a07:2e40::,2a07:2e47:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:2e80::,2a07:2e87:ffff:ffff:ffff:ffff:ffff:ffff,IT2a07:2ec0::,2a07:2ec7:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:2f00::,2a07:2f07:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:2f40::,2a07:2f47:ffff:ffff:ffff:ffff:ffff:ffff,UA2a07:2f80::,2a07:2f87:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:2fc0::,2a07:2fc7:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:3000::,2a07:3007:ffff:ffff:ffff:ffff:ffff:ffff,ES2a07:3040::,2a07:3047:ffff:ffff:ffff:ffff:ffff:ffff,PL2a07:3080::,2a07:3087:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:30c0::,2a07:30c7:ffff:ffff:ffff:ffff:ffff:ffff,CZ2a07:3100::,2a07:3107:ffff:ffff:ffff:ffff:ffff:ffff,RO2a07:3140::,2a07:3147:ffff:ffff:ffff:ffff:ffff:ffff,BE2a07:3180::,2a07:3187:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:31c0::,2a07:31c7:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:3200::,2a07:3207:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:3240::,2a07:3247:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:3280::,2a07:3287:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:32c0::,2a07:32c7:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:3300::,2a07:3307:ffff:ffff:ffff:ffff:ffff:ffff,TR2a07:3340::,2a07:3347:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:3380::,2a07:3387:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:33c0::,2a07:33c7:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:3400::,2a07:3407:ffff:ffff:ffff:ffff:ffff:ffff,UA2a07:3440::,2a07:3447:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:3480::,2a07:3487:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:3500::,2a07:3507:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:3540::,2a07:3547:ffff:ffff:ffff:ffff:ffff:ffff,IT2a07:3580::,2a07:3587:ffff:ffff:ffff:ffff:ffff:ffff,ES2a07:35c0::,2a07:35c7:ffff:ffff:ffff:ffff:ffff:ffff,UA2a07:3600::,2a07:3607:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:3640::,2a07:3647:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:3680::,2a07:3687:ffff:ffff:ffff:ffff:ffff:ffff,LB2a07:36c0::,2a07:36c7:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:3700::,2a07:3707:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:3740::,2a07:3747:ffff:ffff:ffff:ffff:ffff:ffff,AT2a07:3780::,2a07:3787:ffff:ffff:ffff:ffff:ffff:ffff,IS2a07:37c0::,2a07:37c7:ffff:ffff:ffff:ffff:ffff:ffff,BE2a07:3800::,2a07:3807:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:3840::,2a07:3847:ffff:ffff:ffff:ffff:ffff:ffff,HR2a07:3880::,2a07:3887:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:38c0::,2a07:38c7:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:3900::,2a07:3907:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:3940::,2a07:3947:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:3980::,2a07:3987:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:39c0::,2a07:39c7:ffff:ffff:ffff:ffff:ffff:ffff,DK2a07:3a00::,2a07:3a07:ffff:ffff:ffff:ffff:ffff:ffff,ES2a07:3a80::,2a07:3a87:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:3ac0::,2a07:3ac7:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:3b00::,2a07:3b07:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:3b40::,2a07:3b47:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:3b80::,2a07:3b87:ffff:ffff:ffff:ffff:ffff:ffff,GI2a07:3bc0::,2a07:3bc7:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:3c00::,2a07:3c07:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:3c40::,2a07:3c47:ffff:ffff:ffff:ffff:ffff:ffff,DE2a07:3c80::,2a07:3c87:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:3d00::,2a07:3d07:ffff:ffff:ffff:ffff:ffff:ffff,IT2a07:3d80::,2a07:3d87:ffff:ffff:ffff:ffff:ffff:ffff,CZ2a07:3dc0::,2a07:3dc7:ffff:ffff:ffff:ffff:ffff:ffff,DK2a07:3e00::,2a07:3e07:ffff:ffff:ffff:ffff:ffff:ffff,CH2a07:3e40::,2a07:3e47:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:3e80::,2a07:3e87:ffff:ffff:ffff:ffff:ffff:ffff,NL2a07:3ec0::,2a07:3ec7:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:3f00::,2a07:3f07:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:3f40::,2a07:3f47:ffff:ffff:ffff:ffff:ffff:ffff,IE2a07:3f80::,2a07:3f87:ffff:ffff:ffff:ffff:ffff:ffff,SK2a07:3fc0::,2a07:3fc7:ffff:ffff:ffff:ffff:ffff:ffff,SE2a07:4000::,2a07:4007:ffff:ffff:ffff:ffff:ffff:ffff,NO2a07:4040::,2a07:4047:ffff:ffff:ffff:ffff:ffff:ffff,SE2a07:4080::,2a07:4087:ffff:ffff:ffff:ffff:ffff:ffff,AT2a07:40c0::,2a07:40c7:ffff:ffff:ffff:ffff:ffff:ffff,IL2a07:4100::,2a07:4107:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:4140::,2a07:4147:ffff:ffff:ffff:ffff:ffff:ffff,MD2a07:4180::,2a07:4187:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:41c0::,2a07:41c7:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:4200::,2a07:4207:ffff:ffff:ffff:ffff:ffff:ffff,FR2a07:4240::,2a07:4247:ffff:ffff:ffff:ffff:ffff:ffff,RU2a07:4280::,2a07:4287:ffff:ffff:ffff:ffff:ffff:ffff,GB2a07:42c0::,2a07:42c7:ffff:ffff:ffff:ffff:ffff:ffff,DK2a07:4340::,2a07:4347:ffff:ffff:ffff:ffff:ffff:ffff,AE2a0c:af80::,2a0c:af87:ffff:ffff:ffff:ffff:ffff:ffff,GB2c0f:f950::,2c0f:f950:ffff:ffff:ffff:ffff:ffff:ffff,SS2c0f:f958::,2c0f:f958:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:f960::,2c0f:f960:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:f968::,2c0f:f968:ffff:ffff:ffff:ffff:ffff:ffff,MZ2c0f:f970::,2c0f:f970:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:f978::,2c0f:f978:ffff:ffff:ffff:ffff:ffff:ffff,CD2c0f:f980::,2c0f:f980:ffff:ffff:ffff:ffff:ffff:ffff,NA2c0f:f988::,2c0f:f988:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:f990::,2c0f:f990:ffff:ffff:ffff:ffff:ffff:ffff,GN2c0f:f998::,2c0f:f998:ffff:ffff:ffff:ffff:ffff:ffff,MR2c0f:f9a0::,2c0f:f9a0:ffff:ffff:ffff:ffff:ffff:ffff,MW2c0f:f9a8::,2c0f:f9a8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:f9b0::,2c0f:f9b0:ffff:ffff:ffff:ffff:ffff:ffff,GA2c0f:f9b8::,2c0f:f9b8:1:ffff:ffff:ffff:ffff:ffff,MU2c0f:f9b8:2::,2c0f:f9b8:2:ffff:ffff:ffff:ffff:ffff,US2c0f:f9b8:3::,2c0f:f9b8:ffff:ffff:ffff:ffff:ffff:ffff,MU2c0f:f9c0::,2c0f:f9c0:ffff:ffff:ffff:ffff:ffff:ffff,BW2c0f:f9c8::,2c0f:f9c8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:f9d0::,2c0f:f9d0:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:f9d8::,2c0f:f9d8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:f9e0::,2c0f:f9e0:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:f9e8::,2c0f:f9e8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:f9f0::,2c0f:f9f0:ffff:ffff:ffff:ffff:ffff:ffff,MG2c0f:f9f8::,2c0f:f9f8:ffff:ffff:ffff:ffff:ffff:ffff,BJ2c0f:fa00::,2c0f:fa00:ffff:ffff:ffff:ffff:ffff:ffff,GH2c0f:fa08::,2c0f:fa08:ffff:ffff:ffff:ffff:ffff:ffff,CD2c0f:fa10::,2c0f:fa10:fffc:ffff:ffff:ffff:ffff:ffff,MU2c0f:fa10:fffd::,2c0f:fa10:fffd:7fff:ffff:ffff:ffff:ffff,ZM2c0f:fa10:fffd:8000::,2c0f:fa10:ffff:ffff:ffff:ffff:ffff:ffff,MU2c0f:fa18::,2c0f:fa18:ffff:ffff:ffff:ffff:ffff:ffff,MA2c0f:fa20::,2c0f:fa20:ffff:ffff:ffff:ffff:ffff:ffff,SS2c0f:fa28::,2c0f:fa28:ffff:ffff:ffff:ffff:ffff:ffff,MG2c0f:fa38::,2c0f:fa38:ffff:ffff:ffff:ffff:ffff:ffff,AO2c0f:fa40::,2c0f:fa40:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fa48::,2c0f:fa48:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fa58::,2c0f:fa58:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fa60::,2c0f:fa60:ffff:ffff:ffff:ffff:ffff:ffff,AO2c0f:fa68::,2c0f:fa68:ffff:ffff:ffff:ffff:ffff:ffff,GH2c0f:fa70::,2c0f:fa70:ffff:ffff:ffff:ffff:ffff:ffff,AO2c0f:fa78::,2c0f:fa78:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fa80::,2c0f:fa80:ffff:ffff:ffff:ffff:ffff:ffff,AO2c0f:fa88::,2c0f:fa88:ffff:ffff:ffff:ffff:ffff:ffff,ST2c0f:fa90::,2c0f:fa90:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fa98::,2c0f:fa98:ffff:ffff:ffff:ffff:ffff:ffff,ZW2c0f:faa0::,2c0f:faa7:ffff:ffff:ffff:ffff:ffff:ffff,SD2c0f:fab0::,2c0f:fabf:ffff:ffff:ffff:ffff:ffff:ffff,TN2c0f:fac0::,2c0f:fac0:ffff:ffff:ffff:ffff:ffff:ffff,MW2c0f:fac8::,2c0f:fac8:ffff:ffff:ffff:ffff:ffff:ffff,BW2c0f:fad8::,2c0f:fad8:ffff:ffff:ffff:ffff:ffff:ffff,CM2c0f:fae0::,2c0f:fae0:ffff:ffff:ffff:ffff:ffff:ffff,CM2c0f:fae8::,2c0f:fae8:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:faf0::,2c0f:faf0:ffff:ffff:ffff:ffff:ffff:ffff,AO2c0f:faf8::,2c0f:faf8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fb00::,2c0f:fb00:ffff:ffff:ffff:ffff:ffff:ffff,UG2c0f:fb08::,2c0f:fb08:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fb10::,2c0f:fb10:ffff:ffff:ffff:ffff:ffff:ffff,LY2c0f:fb18::,2c0f:fb18:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fb20::,2c0f:fb20:ffff:ffff:ffff:ffff:ffff:ffff,MA2c0f:fb30::,2c0f:fb30:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fb38::,2c0f:fb38:ffff:ffff:ffff:ffff:ffff:ffff,SO2c0f:fb40::,2c0f:fb40:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fb48::,2c0f:fb48:ffff:ffff:ffff:ffff:ffff:ffff,MZ2c0f:fb50::,2c0f:fb50:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:fb58::,2c0f:fb58:ffff:ffff:ffff:ffff:ffff:ffff,AO2c0f:fb60::,2c0f:fb60:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:fb68::,2c0f:fb68:ffff:ffff:ffff:ffff:ffff:ffff,LS2c0f:fb70::,2c0f:fb70:ffff:ffff:ffff:ffff:ffff:ffff,AO2c0f:fb78::,2c0f:fb78:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:fb80::,2c0f:fb80:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fb88::,2c0f:fb88:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:fb90::,2c0f:fb90:ffff:ffff:ffff:ffff:ffff:ffff,MZ2c0f:fb98::,2c0f:fb98:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:fba0::,2c0f:fba0:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fba8::,2c0f:fba8:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:fbb0::,2c0f:fbb0:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fbb8::,2c0f:fbb8:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:fbc0::,2c0f:fbc0:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fbc8::,2c0f:fbc8:ffff:ffff:ffff:ffff:ffff:ffff,UG2c0f:fbd0::,2c0f:fbd0:ffff:ffff:ffff:ffff:ffff:ffff,GN2c0f:fbd8::,2c0f:fbd8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fbe0::,2c0f:fc1f:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fc40::,2c0f:fc40:ffff:ffff:ffff:ffff:ffff:ffff,EG2c0f:fc48::,2c0f:fc48:ffff:ffff:ffff:ffff:ffff:ffff,MW2c0f:fc58::,2c0f:fc58:ffff:ffff:ffff:ffff:ffff:ffff,MW2c0f:fc60::,2c0f:fc61:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:fc68::,2c0f:fc68:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fc70::,2c0f:fc70:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:fc80::,2c0f:fc80:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:fc88::,2c0f:fc89:ffff:ffff:ffff:ffff:ffff:ffff,EG2c0f:fc90::,2c0f:fc90:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:fc98::,2c0f:fc98:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:fca0::,2c0f:fca0:ffff:ffff:ffff:ffff:ffff:ffff,GH2c0f:fca8::,2c0f:fca8:ffff:ffff:ffff:ffff:ffff:ffff,GH2c0f:fcb0::,2c0f:fcb0:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fcb8::,2c0f:fcb8:ffff:ffff:ffff:ffff:ffff:ffff,GM2c0f:fcc8::,2c0f:fcc8:ffff:ffff:ffff:ffff:ffff:ffff,ZM2c0f:fcd0::,2c0f:fcd0:ffff:ffff:ffff:ffff:ffff:ffff,ZM2c0f:fcd8::,2c0f:fcd8:ffff:ffff:ffff:ffff:ffff:ffff,SO2c0f:fce0::,2c0f:fce0:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:fce8::,2c0f:fce8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fcf0::,2c0f:fcf0:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:fcf8::,2c0f:fcf8:ffff:ffff:ffff:ffff:ffff:ffff,GH2c0f:fd00::,2c0f:fd00:ffff:ffff:ffff:ffff:ffff:ffff,LS2c0f:fd08::,2c0f:fd08:ffff:ffff:ffff:ffff:ffff:ffff,GM2c0f:fd10::,2c0f:fd10:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:fd18::,2c0f:fd18:ffff:ffff:ffff:ffff:ffff:ffff,SC2c0f:fd20::,2c0f:fd20:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:fd28::,2c0f:fd28:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:fd30::,2c0f:fd30:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:fd38::,2c0f:fd38:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:fd40::,2c0f:fd40:ffff:ffff:ffff:ffff:ffff:ffff,ZM2c0f:fd48::,2c0f:fd48:ffff:ffff:ffff:ffff:ffff:ffff,ZW2c0f:fd50::,2c0f:fd50:ffff:ffff:ffff:ffff:ffff:ffff,MW2c0f:fd58::,2c0f:fd58:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fd60::,2c0f:fd60:ffff:ffff:ffff:ffff:ffff:ffff,UG2c0f:fd68::,2c0f:fd68:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fd78::,2c0f:fd78:ffff:ffff:ffff:ffff:ffff:ffff,BI2c0f:fd80::,2c0f:fd80:ffff:ffff:ffff:ffff:ffff:ffff,BF2c0f:fd88::,2c0f:fd88:ffff:ffff:ffff:ffff:ffff:ffff,GH2c0f:fd90::,2c0f:fd90:ffff:ffff:ffff:ffff:ffff:ffff,ZM2c0f:fd98::,2c0f:fd98:ffff:ffff:ffff:ffff:ffff:ffff,ZM2c0f:fda0::,2c0f:fda0:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fda8::,2c0f:fda8:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:fdb0::,2c0f:fdb0:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:fdb8::,2c0f:fdb8:ffff:ffff:ffff:ffff:ffff:ffff,UG2c0f:fdc0::,2c0f:fdc0:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:fdc8::,2c0f:fdc8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fdd0::,2c0f:fdd0:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fdd8::,2c0f:fdd8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fde8::,2c0f:fde8:ffff:ffff:ffff:ffff:ffff:ffff,MW2c0f:fdf0::,2c0f:fdf0:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fdf8::,2c0f:fdf8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fe08::,2c0f:fe08:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:fe10::,2c0f:fe10:ffff:ffff:ffff:ffff:ffff:ffff,UG2c0f:fe18::,2c0f:fe18:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fe20::,2c0f:fe20:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fe28::,2c0f:fe28:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fe30::,2c0f:fe30:ffff:ffff:ffff:ffff:ffff:ffff,MU2c0f:fe38::,2c0f:fe38:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:fe40::,2c0f:fe40:8001:f:ffff:ffff:ffff:ffff,MU2c0f:fe40:8001:10::,2c0f:fe40:8001:10:ffff:ffff:ffff:ffff,KE2c0f:fe40:8001:11::,2c0f:fe40:80fe:ffff:ffff:ffff:ffff:ffff,MU2c0f:fe40:80ff::,2c0f:fe40:80ff:7fff:ffff:ffff:ffff:ffff,KE2c0f:fe40:80ff:8000::,2c0f:fe40:ffff:ffff:ffff:ffff:ffff:ffff,MU2c0f:fe50::,2c0f:fe50:ffff:ffff:ffff:ffff:ffff:ffff,DZ2c0f:fe58::,2c0f:fe58:ffff:ffff:ffff:ffff:ffff:ffff,LS2c0f:fe60::,2c0f:fe60:ffff:ffff:ffff:ffff:ffff:ffff,RW2c0f:fe68::,2c0f:fe68:ffff:ffff:ffff:ffff:ffff:ffff,MU2c0f:fe70::,2c0f:fe70:ffff:ffff:ffff:ffff:ffff:ffff,UG2c0f:fe78::,2c0f:fe78:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fe88::,2c0f:fe88:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:fe90::,2c0f:fe90:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fe98::,2c0f:fe98:ffff:ffff:ffff:ffff:ffff:ffff,TZ2c0f:fea0::,2c0f:fea0:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:fea8::,2c0f:fea8:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:feb0::,2c0f:feb0:16:ffff:ffff:ffff:ffff:ffff,MU2c0f:feb0:17::,2c0f:feb0:17:7fff:ffff:ffff:ffff:ffff,KE2c0f:feb0:17:8000::,2c0f:feb0:1e:ffff:ffff:ffff:ffff:ffff,MU2c0f:feb0:1f::,2c0f:feb0:1f:7fff:ffff:ffff:ffff:ffff,ZA2c0f:feb0:1f:8000::,2c0f:feb0:1f:ffff:ffff:ffff:ffff:ffff,MU2c0f:feb0:20::,2c0f:feb0:20:7fff:ffff:ffff:ffff:ffff,ZA2c0f:feb0:20:8000::,2c0f:feb0:2f:7fff:ffff:ffff:ffff:ffff,MU2c0f:feb0:2f:8000::,2c0f:feb0:2f:ffff:ffff:ffff:ffff:ffff,ZA2c0f:feb0:30::,2c0f:feb1:ffff:ffff:ffff:ffff:ffff:ffff,MU2c0f:feb8::,2c0f:feb8:ffff:ffff:ffff:ffff:ffff:ffff,ZM2c0f:fec0::,2c0f:fec0:ffff:ffff:ffff:ffff:ffff:ffff,UG2c0f:fec8::,2c0f:fec8:ffff:ffff:ffff:ffff:ffff:ffff,SD2c0f:fed8::,2c0f:fed8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:fee0::,2c0f:fee0:ffff:ffff:ffff:ffff:ffff:ffff,EG2c0f:fef0::,2c0f:fef0:ffff:ffff:ffff:ffff:ffff:ffff,SC2c0f:fef8::,2c0f:fef8:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:ff00::,2c0f:ff00:ffff:ffff:ffff:ffff:ffff:ffff,BW2c0f:ff08::,2c0f:ff08:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:ff10::,2c0f:ff10:ffff:ffff:ffff:ffff:ffff:ffff,CD2c0f:ff18::,2c0f:ff18:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:ff20::,2c0f:ff20:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:ff28::,2c0f:ff28:ffff:ffff:ffff:ffff:ffff:ffff,SD2c0f:ff30::,2c0f:ff30:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:ff40::,2c0f:ff80:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:ff88::,2c0f:ff88:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:ff90::,2c0f:ff90:ffff:ffff:ffff:ffff:ffff:ffff,KE2c0f:ff98::,2c0f:ff98:ffff:ffff:ffff:ffff:ffff:ffff,UG2c0f:ffa0::,2c0f:ffa0:ffff:ffff:ffff:ffff:ffff:ffff,UG2c0f:ffa8::,2c0f:ffa8:ffff:ffff:ffff:ffff:ffff:ffff,LS2c0f:ffb0::,2c0f:ffb0:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:ffb8::,2c0f:ffb8:ffff:ffff:ffff:ffff:ffff:ffff,SD2c0f:ffc0::,2c0f:ffc0:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:ffc8::,2c0f:ffc8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:ffd0::,2c0f:ffd0:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:ffd8::,2c0f:ffd8:ffff:ffff:ffff:ffff:ffff:ffff,ZA2c0f:ffe8::,2c0f:ffe8:ffff:ffff:ffff:ffff:ffff:ffff,NG2c0f:fff0::,2c0f:fff0:ffff:ffff:ffff:ffff:ffff:ffff,NG123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111<!-- START doctoc generated TOC please keep comment here to allow auto update --><!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->**Table of Contents**
- [Dependencies](#dependencies)- [Building the Snowflake client](#building-the-snowflake-client)- [Running the Snowflake client with Tor](#running-the-snowflake-client-with-tor)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
This is the Tor client component of Snowflake.
It is based on the [goptlib](https://gitweb.torproject.org/pluggable-transports/goptlib.git/) pluggable transports library for Tor.
### Dependencies
- Go 1.15+- We use the [pion/webrtc](https://github.com/pion/webrtc) library for WebRTC communication with Snowflake proxies. Note: running `go get` will fetch this dependency automatically during the build process.
### Building the Snowflake client
To build the Snowflake client, make sure you are in the `client/` directory, and then run:
```go getgo build```
### Running the Snowflake client with Tor
The Snowflake client can be configured with SOCKS options. We have a few example `torrc` files in this directory. We recommend the following `torrc` options by default:```UseBridges 1
ClientTransportPlugin snowflake exec ./client -log snowflake.log
Bridge snowflake 192.0.2.3:80 2B280B23E1107BB62ABFC40DDCC8824814F80A72 fingerprint=2B280B23E1107BB62ABFC40DDCC8824814F80A72 url=https://snowflake-broker.torproject.net.global.prod.fastly.net/ fronts=foursquare.com,github.githubassets.com ice=stun:stun.l.google.com:19302,stun:stun.antisip.com:3478,stun:stun.bluesip.net:3478,stun:stun.dus.net:3478,stun:stun.epygi.com:3478,stun:stun.sonetel.com:3478,stun:stun.uls.co.za:3478,stun:stun.voipgate.com:3478,stun:stun.voys.nl:3478 utls-imitate=hellorandomizedalpn```
`fingerprint=` is the fingerprint of bridge that the client will ultimately be connecting to.
`url=` is the URL of a broker instance. If you would like to try out Snowflake with your own broker, simply provide the URL of your broker instance with this option.
`fronts=` is an optional, comma-seperated list front domains for the broker request.
`ice=` is a comma-separated list of ICE servers. These must be STUN (over UDP) servers with the form stun:<var>host</var>[:<var>port</var>]. We recommend using servers that have implemented NAT discovery. See our wiki page on [NAT traversal](https://gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/-/wikis/NAT-matching) for more information.
`utls-imitate=` configuration instructs the client to use fingerprinting resistance when connecting when rendez-vous'ing with the broker.
To bootstrap Tor, run:```tor -f torrc```This should start the client plugin, bootstrapping to 100% using WebRTC.
### Registration methods
The Snowflake client supports a few different ways of communicating with the broker.This initial step is sometimes called rendezvous.
#### Domain fronting HTTPS
For domain fronting rendezvous, use the `-url` and `-front` command-line options together.[Domain fronting](https://www.bamsoftware.com/papers/fronting/)hides the externally visible domain name from an external observer,making it appear that the Snowflake client is communicating with some serverother than the Snowflake broker.
* `-url` is the HTTPS URL of a forwarder to the broker, on some service that supports domain fronting, such as a CDN.* `-front` is the domain name to show externally. It must be another domain on the same service.
Example:```-url https://snowflake-broker.torproject.net.global.prod.fastly.net/ \-front cdn.sstatic.net \```
#### AMP cache
For AMP cache rendezvous, use the `-url`, `-ampcache`, and `-front` command-line options together.[AMP](https://amp.dev/documentation/) is a standard for web pages for mobile computers.An [AMP cache](https://amp.dev/documentation/guides-and-tutorials/learn/amp-caches-and-cors/how_amp_pages_are_cached/)is a cache and proxy specialized for AMP pages.The Snowflake broker has the ability to make its client registration responses look like AMP pages,so it can be accessed through an AMP cache.When you use AMP cache rendezvous, it appears to an observer that the Snowflake clientis accessing an AMP cache, or some other domain operated by the same organization.You still need to use the `-front` command-line option, because the[format of AMP cache URLs](https://amp.dev/documentation/guides-and-tutorials/learn/amp-caches-and-cors/amp-cache-urls/)would otherwise reveal the domain name of the broker.
There is only one AMP cache that works with this option,the Google AMP cache at https://cdn.ampproject.org/.
* `-url` is the HTTPS URL of the broker.* `-ampcache` is `https://cdn.ampproject.org/`.* `-front` is any Google domain, such as `www.google.com`.
Example:```-url https://snowflake-broker.torproject.net/ \-ampcache https://cdn.ampproject.org/ \-front www.google.com \```
#### Direct access
It is also possible to access the broker directly using HTTPS, without domain fronting,for testing purposes. This mode is not suitable for circumvention, because thebroker is easily blocked by its address.123456789101112131415161718192021222324package snowflake_client
// Tongue is an interface for catching Snowflakes. (aka the remote dialer)type Tongue interface { // Catch makes a connection to a new snowflake. Catch() (*WebRTCPeer, error)
// GetMax returns the maximum number of snowflakes a client can have. GetMax() int}
// SnowflakeCollector is an interface for managing a client's collection of snowflakes.type SnowflakeCollector interface { // Collect adds a snowflake to the collection. // The implementation of Collect should decide how to connect to and maintain // the connection to the WebRTCPeer. Collect() (*WebRTCPeer, error)
// Pop removes and returns the most available snowflake from the collection. Pop() *WebRTCPeer
// Melted returns a channel that will signal when the collector has stopped. Melted() <-chan struct{}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221package snowflake_client
import ( "fmt" "net" "testing" "time"
. "github.com/smartystreets/goconvey/convey" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/event")
type FakeDialer struct { max int}
func (w FakeDialer) Catch() (*WebRTCPeer, error) { fmt.Println("Caught a dummy snowflake.") return &WebRTCPeer{closed: make(chan struct{})}, nil}
func (w FakeDialer) GetMax() int { return w.max}
type FakeSocksConn struct { net.Conn rejected bool}
func (f FakeSocksConn) Reject() error { f.rejected = true return nil}func (f FakeSocksConn) Grant(addr *net.TCPAddr) error { return nil }
func TestSnowflakeClient(t *testing.T) {
Convey("Peers", t, func() { Convey("Can construct", func() { d := &FakeDialer{max: 1} p, _ := NewPeers(d) So(p.Tongue.GetMax(), ShouldEqual, 1) So(p.snowflakeChan, ShouldNotBeNil) So(cap(p.snowflakeChan), ShouldEqual, 1) })
Convey("Collecting a Snowflake requires a Tongue.", func() { p, err := NewPeers(nil) So(err, ShouldNotBeNil) // Set the dialer so that collection is possible. d := &FakeDialer{max: 1} p, err = NewPeers(d) _, err = p.Collect() So(err, ShouldBeNil) So(p.Count(), ShouldEqual, 1) // S _, err = p.Collect() })
Convey("Collection continues until capacity.", func() { c := 5 p, _ := NewPeers(FakeDialer{max: c}) // Fill up to capacity. for i := 0; i < c; i++ { fmt.Println("Adding snowflake ", i) _, err := p.Collect() So(err, ShouldBeNil) So(p.Count(), ShouldEqual, i+1) } // But adding another gives an error. So(p.Count(), ShouldEqual, c) _, err := p.Collect() So(err, ShouldNotBeNil) So(p.Count(), ShouldEqual, c)
// But popping allows it to continue. s := p.Pop() s.Close() So(s, ShouldNotBeNil) So(p.Count(), ShouldEqual, c-1)
_, err = p.Collect() So(err, ShouldBeNil) So(p.Count(), ShouldEqual, c) })
Convey("Count correctly purges peers marked for deletion.", func() { p, _ := NewPeers(FakeDialer{max: 5}) p.Collect() p.Collect() p.Collect() p.Collect() So(p.Count(), ShouldEqual, 4) s := p.Pop() s.Close() So(p.Count(), ShouldEqual, 3) s = p.Pop() s.Close() So(p.Count(), ShouldEqual, 2) })
Convey("End Closes all peers.", func() { cnt := 5 p, _ := NewPeers(FakeDialer{max: cnt}) for i := 0; i < cnt; i++ { p.activePeers.PushBack(&WebRTCPeer{closed: make(chan struct{})}) } So(p.Count(), ShouldEqual, cnt) p.End() <-p.Melted() So(p.Count(), ShouldEqual, 0) })
Convey("Pop skips over closed peers.", func() { p, _ := NewPeers(FakeDialer{max: 4}) wc1, _ := p.Collect() wc2, _ := p.Collect() wc3, _ := p.Collect() So(wc1, ShouldNotBeNil) So(wc2, ShouldNotBeNil) So(wc3, ShouldNotBeNil) wc1.Close() r := p.Pop() So(p.Count(), ShouldEqual, 2) So(r, ShouldEqual, wc2) wc4, _ := p.Collect() wc2.Close() wc3.Close() r = p.Pop() So(r, ShouldEqual, wc4) })
Convey("Terminate Connect() loop", func() { p, _ := NewPeers(FakeDialer{max: 4}) go func() { for { p.Collect() select { case <-p.Melted(): return default: } } }() <-time.After(10 * time.Second)
p.End() <-p.Melted() So(p.Count(), ShouldEqual, 0) })
})
Convey("Dialers", t, func() { Convey("Can construct WebRTCDialer.", func() { broker := &BrokerChannel{} d := NewWebRTCDialer(broker, nil, 1) So(d, ShouldNotBeNil) So(d.BrokerChannel, ShouldNotBeNil) }) SkipConvey("WebRTCDialer can Catch a snowflake.", func() { broker := &BrokerChannel{} d := NewWebRTCDialer(broker, nil, 1) conn, err := d.Catch() So(conn, ShouldBeNil) So(err, ShouldNotBeNil) }) })
}
func TestWebRTCPeer(t *testing.T) { Convey("WebRTCPeer", t, func(c C) { p := &WebRTCPeer{closed: make(chan struct{}), eventsLogger: event.NewSnowflakeEventDispatcher()} Convey("checks for staleness", func() { go p.checkForStaleness(time.Second) <-time.After(2 * time.Second) So(p.Closed(), ShouldEqual, true) }) })}
func TestICEServerParser(t *testing.T) { Convey("Test parsing of ICE servers", t, func() { for _, test := range []struct { input []string urls [][]string length int }{ { []string{"stun:stun.l.google.com:19302", "stun:stun.ekiga.net"}, [][]string{[]string{"stun:stun.l.google.com:19302"}, []string{"stun:stun.ekiga.net:3478"}}, 2, }, { []string{"stun:stun1.l.google.com:19302", "stun.ekiga.net", "stun:stun.example.com:1234/path?query", "https://example.com", "turn:relay.metered.ca:80?transport=udp"}, [][]string{[]string{"stun:stun1.l.google.com:19302"}}, 1, }, } { servers := parseIceServers(test.input)
if test.urls == nil { So(servers, ShouldBeNil) } else { So(servers, ShouldNotBeNil) }
So(len(servers), ShouldEqual, test.length)
for _, server := range servers { So(test.urls, ShouldContain, server.URLs) }
}
})}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138package snowflake_client
import ( "container/list" "errors" "fmt" "log" "sync")
// Peers is a container that keeps track of multiple WebRTC remote peers.// Implements |SnowflakeCollector|.//// Maintaining a set of pre-connected Peers with fresh but inactive datachannels// allows allows rapid recovery when the current WebRTC Peer disconnects.//// Note: For now, only one remote can be active at any given moment.// This is a property of Tor circuits & its current multiplexing constraints,// but could be updated if that changes.// (Also, this constraint does not necessarily apply to the more generic PT// version of Snowflake)type Peers struct { Tongue bytesLogger bytesLogger
snowflakeChan chan *WebRTCPeer activePeers *list.List
melt chan struct{}
collectLock sync.Mutex}
// NewPeers constructs a fresh container of remote peers.func NewPeers(tongue Tongue) (*Peers, error) { p := &Peers{} // Use buffered go channel to pass snowflakes onwards to the SOCKS handler. if tongue == nil { return nil, errors.New("missing Tongue to catch Snowflakes with") } p.snowflakeChan = make(chan *WebRTCPeer, tongue.GetMax()) p.activePeers = list.New() p.melt = make(chan struct{}) p.Tongue = tongue return p, nil}
// Collect connects to and adds a new remote peer as part of |SnowflakeCollector| interface.func (p *Peers) Collect() (*WebRTCPeer, error) { // Engage the Snowflake Catching interface, which must be available. p.collectLock.Lock() defer p.collectLock.Unlock() select { case <-p.melt: return nil, fmt.Errorf("Snowflakes have melted") default: } if nil == p.Tongue { return nil, errors.New("missing Tongue to catch Snowflakes with") } cnt := p.Count() capacity := p.Tongue.GetMax() s := fmt.Sprintf("Currently at [%d/%d]", cnt, capacity) if cnt >= capacity { return nil, fmt.Errorf("At capacity [%d/%d]", cnt, capacity) } log.Println("WebRTC: Collecting a new Snowflake.", s) // BUG: some broker conflict here. connection, err := p.Tongue.Catch() if nil != err { return nil, err } // Track new valid Snowflake in internal collection and pass along. p.activePeers.PushBack(connection) p.snowflakeChan <- connection return connection, nil}
// Pop blocks until an available, valid snowflake appears.// Pop will return nil after End has been called.func (p *Peers) Pop() *WebRTCPeer { for { snowflake, ok := <-p.snowflakeChan if !ok { return nil } if snowflake.Closed() { continue } // Set to use the same rate-limited traffic logger to keep consistency. snowflake.bytesLogger = p.bytesLogger return snowflake }}
// Melted returns a channel that will close when peers stop being collected.// Melted is a necessary part of |SnowflakeCollector| interface.func (p *Peers) Melted() <-chan struct{} { return p.melt}
// Count returns the total available Snowflakes (including the active ones)// The count only reduces when connections themselves close, rather than when// they are popped.func (p *Peers) Count() int { p.purgeClosedPeers() return p.activePeers.Len()}
func (p *Peers) purgeClosedPeers() { for e := p.activePeers.Front(); e != nil; { next := e.Next() conn := e.Value.(*WebRTCPeer) // Purge those marked for deletion. if conn.Closed() { p.activePeers.Remove(e) } e = next }}
// End closes all active connections to Peers contained here, and stops the// collection of future Peers.func (p *Peers) End() { close(p.melt) p.collectLock.Lock() defer p.collectLock.Unlock() close(p.snowflakeChan) cnt := p.Count() for e := p.activePeers.Front(); e != nil; { next := e.Next() conn := e.Value.(*WebRTCPeer) conn.Close() p.activePeers.Remove(e) e = next } log.Printf("WebRTC: melted all %d snowflakes.", cnt)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229// WebRTC rendezvous requires the exchange of SessionDescriptions between// peers in order to establish a PeerConnection.
package snowflake_client
import ( "crypto/tls" "errors" "fmt" "net/url"
"log" "net/http" "sync" "time"
"github.com/pion/webrtc/v3" utls "github.com/refraction-networking/utls" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/certs" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/event" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/messages" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/nat" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/util" utlsutil "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/utls")
const ( brokerErrorUnexpected string = "Unexpected error, no answer." rendezvousErrorMsg string = "One of SQS, AmpCache, or Domain Fronting rendezvous methods must be used."
readLimit = 100000 //Maximum number of bytes to be read from an HTTP response)
// RendezvousMethod represents a way of communicating with the broker: sending// an encoded client poll request (SDP offer) and receiving an encoded client// poll response (SDP answer) in return. RendezvousMethod is used by// BrokerChannel, which is in charge of encoding and decoding, and all other// tasks that are independent of the rendezvous method.type RendezvousMethod interface { Exchange([]byte) ([]byte, error)}
// BrokerChannel uses a RendezvousMethod to communicate with the Snowflake broker.// The BrokerChannel is responsible for encoding and decoding SDP offers and answers;// RendezvousMethod is responsible for the exchange of encoded information.type BrokerChannel struct { Rendezvous RendezvousMethod keepLocalAddresses bool natType string lock sync.Mutex BridgeFingerprint string}
// We make a copy of DefaultTransport because we want the default Dial// and TLSHandshakeTimeout settings. But we want to disable the default// ProxyFromEnvironment setting.func createBrokerTransport(proxy *url.URL) http.RoundTripper { tlsConfig := &tls.Config{ RootCAs: certs.GetRootCAs(), } transport := &http.Transport{TLSClientConfig: tlsConfig} transport.Proxy = nil if proxy != nil { transport.Proxy = http.ProxyURL(proxy) } transport.ResponseHeaderTimeout = 15 * time.Second return transport}
func newBrokerChannelFromConfig(config ClientConfig) (*BrokerChannel, error) { log.Println("Rendezvous using Broker at:", config.BrokerURL)
if len(config.FrontDomains) != 0 { log.Printf("Domain fronting using a randomly selected domain from: %v", config.FrontDomains) }
brokerTransport := createBrokerTransport(config.CommunicationProxy)
if config.UTLSClientID != "" { utlsClientHelloID, err := utlsutil.NameToUTLSID(config.UTLSClientID) if err != nil { return nil, fmt.Errorf("unable to create broker channel: %v", err) } utlsConfig := &utls.Config{ RootCAs: certs.GetRootCAs(), } brokerTransport = utlsutil.NewUTLSHTTPRoundTripperWithProxy(utlsClientHelloID, utlsConfig, brokerTransport, config.UTLSRemoveSNI, config.CommunicationProxy) }
var rendezvous RendezvousMethod var err error if config.SQSQueueURL != "" { if config.AmpCacheURL != "" || config.BrokerURL != "" { log.Fatalln("Multiple rendezvous methods specified. " + rendezvousErrorMsg) } if config.SQSAccessKeyID == "" || config.SQSSecretKey == "" { log.Fatalln("sqsakid and sqsskey must be specified to use SQS rendezvous method.") } log.Println("Through SQS queue at:", config.SQSQueueURL) rendezvous, err = newSQSRendezvous(config.SQSQueueURL, config.SQSAccessKeyID, config.SQSSecretKey, brokerTransport) } else if config.AmpCacheURL != "" && config.BrokerURL != "" { log.Println("Through AMP cache at:", config.AmpCacheURL) rendezvous, err = newAMPCacheRendezvous( config.BrokerURL, config.AmpCacheURL, config.FrontDomains, brokerTransport) } else if config.BrokerURL != "" { rendezvous, err = newHTTPRendezvous( config.BrokerURL, config.FrontDomains, brokerTransport) } else { log.Fatalln("No rendezvous method was specified. " + rendezvousErrorMsg) } if err != nil { return nil, err }
return &BrokerChannel{ Rendezvous: rendezvous, keepLocalAddresses: config.KeepLocalAddresses, natType: nat.NATUnknown, BridgeFingerprint: config.BridgeFingerprint, }, nil}
// Negotiate uses a RendezvousMethod to send the client's WebRTC SDP offer// and receive a snowflake proxy WebRTC SDP answer in return.func (bc *BrokerChannel) Negotiate(offer *webrtc.SessionDescription) ( *webrtc.SessionDescription, error) { // Ideally, we could specify an `RTCIceTransportPolicy` that would handle // this for us. However, "public" was removed from the draft spec. // See https://developer.mozilla.org/en-US/docs/Web/API/RTCConfiguration#RTCIceTransportPolicy_enum if !bc.keepLocalAddresses { offer = &webrtc.SessionDescription{ Type: offer.Type, SDP: util.StripLocalAddresses(offer.SDP), } } offerSDP, err := util.SerializeSessionDescription(offer) if err != nil { return nil, err }
// Encode the client poll request. bc.lock.Lock() req := &messages.ClientPollRequest{ Offer: offerSDP, NAT: bc.natType, Fingerprint: bc.BridgeFingerprint, } encReq, err := req.EncodeClientPollRequest() bc.lock.Unlock() if err != nil { return nil, err }
// Do the exchange using our RendezvousMethod. encResp, err := bc.Rendezvous.Exchange(encReq) if err != nil { return nil, err } log.Printf("Received answer: %s", string(encResp))
// Decode the client poll response. resp, err := messages.DecodeClientPollResponse(encResp) if err != nil { return nil, err } if resp.Error != "" { return nil, errors.New(resp.Error) } return util.DeserializeSessionDescription(resp.Answer)}
// SetNATType sets the NAT type of the client so we can send it to the WebRTC broker.func (bc *BrokerChannel) SetNATType(NATType string) { bc.lock.Lock() bc.natType = NATType bc.lock.Unlock() log.Printf("NAT Type: %s", NATType)}
// WebRTCDialer implements the |Tongue| interface to catch snowflakes, using BrokerChannel.type WebRTCDialer struct { *BrokerChannel webrtcConfig *webrtc.Configuration max int
eventLogger event.SnowflakeEventReceiver proxy *url.URL}
// Deprecated: Use NewWebRTCDialerWithEventsAndProxy insteadfunc NewWebRTCDialer(broker *BrokerChannel, iceServers []webrtc.ICEServer, max int) *WebRTCDialer { return NewWebRTCDialerWithEventsAndProxy(broker, iceServers, max, nil, nil)}
// Deprecated: Use NewWebRTCDialerWithEventsAndProxy insteadfunc NewWebRTCDialerWithEvents(broker *BrokerChannel, iceServers []webrtc.ICEServer, max int, eventLogger event.SnowflakeEventReceiver) *WebRTCDialer { return NewWebRTCDialerWithEventsAndProxy(broker, iceServers, max, eventLogger, nil)}
// NewWebRTCDialerWithEventsAndProxy constructs a new WebRTCDialer.func NewWebRTCDialerWithEventsAndProxy(broker *BrokerChannel, iceServers []webrtc.ICEServer, max int, eventLogger event.SnowflakeEventReceiver, proxy *url.URL) *WebRTCDialer { config := webrtc.Configuration{ ICEServers: iceServers, }
return &WebRTCDialer{ BrokerChannel: broker, webrtcConfig: &config, max: max,
eventLogger: eventLogger, proxy: proxy, }}
// Catch initializes a WebRTC Connection by signaling through the BrokerChannel.func (w WebRTCDialer) Catch() (*WebRTCPeer, error) { // TODO: [#25591] Fetch ICE server information from Broker. // TODO: [#25596] Consider TURN servers here too. return NewWebRTCPeerWithEventsAndProxy(w.webrtcConfig, w.BrokerChannel, w.eventLogger, w.proxy)}
// GetMax returns the maximum number of snowflakes to collect.func (w WebRTCDialer) GetMax() int { return w.max}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127package snowflake_client
import ( "errors" "io" "log" "math/rand" "net/http" "net/url" "time"
"gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/amp")
// ampCacheRendezvous is a RendezvousMethod that communicates with the// .../amp/client route of the broker, optionally over an AMP cache proxy, and// with optional domain fronting.type ampCacheRendezvous struct { brokerURL *url.URL cacheURL *url.URL // Optional AMP cache URL. fronts []string // Optional front domains to replace url.Host in requests. transport http.RoundTripper // Used to make all requests.}
// newAMPCacheRendezvous creates a new ampCacheRendezvous that contacts the// broker at the given URL, optionally proxying through an AMP cache, and with// an optional front domain. transport is the http.RoundTripper used to make all// requests.func newAMPCacheRendezvous(broker, cache string, fronts []string, transport http.RoundTripper) (*ampCacheRendezvous, error) { brokerURL, err := url.Parse(broker) if err != nil { return nil, err } var cacheURL *url.URL if cache != "" { var err error cacheURL, err = url.Parse(cache) if err != nil { return nil, err } } return &CacheRendezvous{ brokerURL: brokerURL, cacheURL: cacheURL, fronts: fronts, transport: transport, }, nil}
func (r *ampCacheRendezvous) Exchange(encPollReq []byte) ([]byte, error) { log.Println("Negotiating via AMP cache rendezvous...") log.Println("Broker URL:", r.brokerURL) log.Println("AMP cache URL:", r.cacheURL)
// We cannot POST a body through an AMP cache, so instead we GET and // encode the client poll request message into the URL. reqURL := r.brokerURL.ResolveReference(&url.URL{ Path: "amp/client/" + amp.EncodePath(encPollReq), })
if r.cacheURL != nil { // Rewrite reqURL to its AMP cache version. var err error reqURL, err = amp.CacheURL(reqURL, r.cacheURL, "c") if err != nil { return nil, err } }
req, err := http.NewRequest("GET", reqURL.String(), nil) if err != nil { return nil, err }
if len(r.fronts) != 0 { // Do domain fronting. Replace the domain in the URL's with a randomly // selected front, and store the original domain the HTTP Host header. rand.Seed(time.Now().UnixNano()) front := r.fronts[rand.Intn(len(r.fronts))] log.Println("Front domain:", front) req.Host = req.URL.Host req.URL.Host = front }
resp, err := r.transport.RoundTrip(req) if err != nil { return nil, err } defer resp.Body.Close()
log.Printf("AMP cache rendezvous response: %s", resp.Status) if resp.StatusCode != http.StatusOK { // A non-200 status indicates an error: // * If the broker returns a page with invalid AMP, then the AMP // cache returns a redirect that would bypass the cache. // * If the broker returns a 5xx status, the AMP cache // translates it to a 404. // https://amp.dev/documentation/guides-and-tutorials/learn/amp-caches-and-cors/amp-cache-urls/#redirect-%26-error-handling return nil, errors.New(brokerErrorUnexpected) } if _, err := resp.Location(); err == nil { // The Google AMP Cache may return a "silent redirect" with // status 200, a Location header set, and a JavaScript redirect // in the body. The redirect points directly at the origin // server for the request (bypassing the AMP cache). We do not // follow redirects nor execute JavaScript, but in any case we // cannot extract information from this response and can only // treat it as an error. return nil, errors.New(brokerErrorUnexpected) }
lr := io.LimitReader(resp.Body, readLimit+1) dec, err := amp.NewArmorDecoder(lr) if err != nil { return nil, err } encPollResp, err := io.ReadAll(dec) if err != nil { return nil, err } if lr.(*io.LimitedReader).N == 0 { // We hit readLimit while decoding AMP armor, that's an error. return nil, io.ErrUnexpectedEOF }
return encPollResp, err}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980package snowflake_client
import ( "bytes" "errors" "io" "log" "math/rand" "net/http" "net/url" "time")
// httpRendezvous is a RendezvousMethod that communicates with the .../client// route of the broker over HTTP or HTTPS, with optional domain fronting.type httpRendezvous struct { brokerURL *url.URL fronts []string // Optional front domain to replace url.Host in requests. transport http.RoundTripper // Used to make all requests.}
// newHTTPRendezvous creates a new httpRendezvous that contacts the broker at// the given URL, with an optional front domain. transport is the// http.RoundTripper used to make all requests.func newHTTPRendezvous(broker string, fronts []string, transport http.RoundTripper) (*httpRendezvous, error) { brokerURL, err := url.Parse(broker) if err != nil { return nil, err } return &httpRendezvous{ brokerURL: brokerURL, fronts: fronts, transport: transport, }, nil}
func (r *httpRendezvous) Exchange(encPollReq []byte) ([]byte, error) { log.Println("Negotiating via HTTP rendezvous...") log.Println("Target URL: ", r.brokerURL.Host)
// Suffix the path with the broker's client registration handler. reqURL := r.brokerURL.ResolveReference(&url.URL{Path: "client"}) req, err := http.NewRequest("POST", reqURL.String(), bytes.NewReader(encPollReq)) if err != nil { return nil, err }
if len(r.fronts) != 0 { // Do domain fronting. Replace the domain in the URL's with a randomly // selected front, and store the original domain the HTTP Host header. rand.Seed(time.Now().UnixNano()) front := r.fronts[rand.Intn(len(r.fronts))] log.Println("Front URL: ", front) req.Host = req.URL.Host req.URL.Host = front }
resp, err := r.transport.RoundTrip(req) if err != nil { return nil, err } defer resp.Body.Close()
log.Printf("HTTP rendezvous response: %s", resp.Status) if resp.StatusCode != http.StatusOK { return nil, errors.New(brokerErrorUnexpected) }
return limitedRead(resp.Body, readLimit)}
func limitedRead(r io.Reader, limit int64) ([]byte, error) { p, err := io.ReadAll(&io.LimitedReader{R: r, N: limit + 1}) if err != nil { return p, err } else if int64(len(p)) == limit+1 { return p[0:limit], io.ErrUnexpectedEOF } return p, err}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139package snowflake_client
import ( "context" "crypto/rand" "encoding/hex" "log" "net/http" "net/url" "regexp" "time"
"github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/sqsclient")
type sqsRendezvous struct { transport http.RoundTripper sqsClientID string sqsClient sqsclient.SQSClient sqsURL *url.URL timeout time.Duration numRetries int}
func newSQSRendezvous(sqsQueue string, sqsAccessKeyId string, sqsSecretKey string, transport http.RoundTripper) (*sqsRendezvous, error) { sqsURL, err := url.Parse(sqsQueue) if err != nil { return nil, err }
var id [8]byte _, err = rand.Read(id[:]) if err != nil { log.Fatal(err) } clientID := hex.EncodeToString(id[:])
queueURL := sqsURL.String() hostName := sqsURL.Hostname()
regionRegex, _ := regexp.Compile(`^sqs\.([\w-]+)\.amazonaws\.com$`) res := regionRegex.FindStringSubmatch(hostName) if len(res) < 2 { log.Fatal("Could not extract AWS region from SQS URL. Ensure that the SQS Queue URL provided is valid.") } region := res[1] cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithCredentialsProvider( credentials.NewStaticCredentialsProvider(sqsAccessKeyId, sqsSecretKey, ""), ), config.WithRegion(region), ) if err != nil { log.Fatal(err) } client := sqs.NewFromConfig(cfg)
log.Println("Queue URL: ", queueURL) log.Println("SQS Client ID: ", clientID)
return &sqsRendezvous{ transport: transport, sqsClientID: clientID, sqsClient: client, sqsURL: sqsURL, timeout: time.Second, numRetries: 5, }, nil}
func (r *sqsRendezvous) Exchange(encPollReq []byte) ([]byte, error) { log.Println("Negotiating via SQS Queue rendezvous...")
_, err := r.sqsClient.SendMessage(context.TODO(), &sqs.SendMessageInput{ MessageAttributes: map[string]types.MessageAttributeValue{ "ClientID": { DataType: aws.String("String"), StringValue: aws.String(r.sqsClientID), }, }, MessageBody: aws.String(string(encPollReq)), QueueUrl: aws.String(r.sqsURL.String()), }) if err != nil { return nil, err }
time.Sleep(r.timeout) // wait for client queue to be created by the broker
var responseQueueURL *string for i := 0; i < r.numRetries; i++ { // The SQS queue corresponding to the client where the SDP Answer will be placed // may not be created yet. We will retry up to 5 times before we error out. var res *sqs.GetQueueUrlOutput res, err = r.sqsClient.GetQueueUrl(context.TODO(), &sqs.GetQueueUrlInput{ QueueName: aws.String("snowflake-client-" + r.sqsClientID), }) if err != nil { log.Println(err) log.Printf("Attempt %d of %d to retrieve URL of response SQS queue failed.\n", i+1, r.numRetries) time.Sleep(r.timeout) } else { responseQueueURL = res.QueueUrl break } } if err != nil { return nil, err }
var answer string for i := 0; i < r.numRetries; i++ { // Waiting for SDP Answer from proxy to be placed in SQS queue. // We will retry upt to 5 times before we error out. res, err := r.sqsClient.ReceiveMessage(context.TODO(), &sqs.ReceiveMessageInput{ QueueUrl: responseQueueURL, MaxNumberOfMessages: 1, WaitTimeSeconds: 20, }) if err != nil { return nil, err } if len(res.Messages) == 0 { log.Printf("Attempt %d of %d to receive message from response SQS queue failed. No message found in queue.\n", i+1, r.numRetries) delay := float64(i)/2.0 + 1 time.Sleep(time.Duration(delay*1000) * (r.timeout / 1000)) } else { answer = *res.Messages[0].Body break } }
return []byte(answer), nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398package snowflake_client
import ( "bytes" "errors" "fmt" "io" "net/http" "net/url" "testing"
"github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" "github.com/golang/mock/gomock" . "github.com/smartystreets/goconvey/convey" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/amp" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/messages" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/nat" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/sqsclient")
// mockTransport's RoundTrip method returns a response with a fake status and// body.type mockTransport struct { statusCode int body []byte}
func (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) { return &http.Response{ Status: fmt.Sprintf("%d %s", t.statusCode, http.StatusText(t.statusCode)), StatusCode: t.statusCode, Body: io.NopCloser(bytes.NewReader(t.body)), }, nil}
// errorTransport's RoundTrip method returns an error.type errorTransport struct { err error}
func (t errorTransport) RoundTrip(req *http.Request) (*http.Response, error) { return nil, t.err}
// makeEncPollReq returns an encoded client poll request containing a given// offer.func makeEncPollReq(offer string) []byte { encPollReq, err := (&messages.ClientPollRequest{ Offer: offer, NAT: nat.NATUnknown, }).EncodeClientPollRequest() if err != nil { panic(err) } return encPollReq}
// makeEncPollResp returns an encoded client poll response with given answer and// error strings.func makeEncPollResp(answer, errorStr string) []byte { encPollResp, err := (&messages.ClientPollResponse{ Answer: answer, Error: errorStr, }).EncodePollResponse() if err != nil { panic(err) } return encPollResp}
var fakeEncPollReq = makeEncPollReq(`{"type":"offer","sdp":"test"}`)
func TestHTTPRendezvous(t *testing.T) { Convey("HTTP rendezvous", t, func() { Convey("Construct httpRendezvous with no front domain", func() { transport := &mockTransport{http.StatusOK, []byte{}} rend, err := newHTTPRendezvous("http://test.broker", []string{}, transport) So(err, ShouldBeNil) So(rend.brokerURL, ShouldNotBeNil) So(rend.brokerURL.Host, ShouldResemble, "test.broker") So(rend.fronts, ShouldEqual, []string{}) So(rend.transport, ShouldEqual, transport) })
Convey("Construct httpRendezvous *with* front domain", func() { transport := &mockTransport{http.StatusOK, []byte{}} rend, err := newHTTPRendezvous("http://test.broker", []string{"front"}, transport) So(err, ShouldBeNil) So(rend.brokerURL, ShouldNotBeNil) So(rend.brokerURL.Host, ShouldResemble, "test.broker") So(rend.fronts, ShouldContain, "front") So(rend.transport, ShouldEqual, transport) })
Convey("httpRendezvous.Exchange responds with answer", func() { fakeEncPollResp := makeEncPollResp( `{"answer": "{\"type\":\"answer\",\"sdp\":\"fake\"}" }`, "", ) rend, err := newHTTPRendezvous("http://test.broker", []string{}, &mockTransport{http.StatusOK, fakeEncPollResp}) So(err, ShouldBeNil) answer, err := rend.Exchange(fakeEncPollReq) So(err, ShouldBeNil) So(answer, ShouldResemble, fakeEncPollResp) })
Convey("httpRendezvous.Exchange responds with no answer", func() { fakeEncPollResp := makeEncPollResp( "", `{"error": "no snowflake proxies currently available"}`, ) rend, err := newHTTPRendezvous("http://test.broker", []string{}, &mockTransport{http.StatusOK, fakeEncPollResp}) So(err, ShouldBeNil) answer, err := rend.Exchange(fakeEncPollReq) So(err, ShouldBeNil) So(answer, ShouldResemble, fakeEncPollResp) })
Convey("httpRendezvous.Exchange fails with unexpected HTTP status code", func() { rend, err := newHTTPRendezvous("http://test.broker", []string{}, &mockTransport{http.StatusInternalServerError, []byte{}}) So(err, ShouldBeNil) answer, err := rend.Exchange(fakeEncPollReq) So(err, ShouldNotBeNil) So(answer, ShouldBeNil) So(err.Error(), ShouldResemble, brokerErrorUnexpected) })
Convey("httpRendezvous.Exchange fails with error", func() { transportErr := errors.New("error") rend, err := newHTTPRendezvous("http://test.broker", []string{}, &errorTransport{err: transportErr}) So(err, ShouldBeNil) answer, err := rend.Exchange(fakeEncPollReq) So(err, ShouldEqual, transportErr) So(answer, ShouldBeNil) })
Convey("httpRendezvous.Exchange fails with large read", func() { rend, err := newHTTPRendezvous("http://test.broker", []string{}, &mockTransport{http.StatusOK, make([]byte, readLimit+1)}) So(err, ShouldBeNil) _, err = rend.Exchange(fakeEncPollReq) So(err, ShouldEqual, io.ErrUnexpectedEOF) }) })}
func ampArmorEncode(p []byte) []byte { var buf bytes.Buffer enc, err := amp.NewArmorEncoder(&buf) if err != nil { panic(err) } _, err = enc.Write(p) if err != nil { panic(err) } err = enc.Close() if err != nil { panic(err) } return buf.Bytes()}
func TestAMPCacheRendezvous(t *testing.T) { Convey("AMP cache rendezvous", t, func() { Convey("Construct ampCacheRendezvous with no cache and no front domain", func() { transport := &mockTransport{http.StatusOK, []byte{}} rend, err := newAMPCacheRendezvous("http://test.broker", "", []string{}, transport) So(err, ShouldBeNil) So(rend.brokerURL, ShouldNotBeNil) So(rend.brokerURL.String(), ShouldResemble, "http://test.broker") So(rend.cacheURL, ShouldBeNil) So(rend.fronts, ShouldResemble, []string{}) So(rend.transport, ShouldEqual, transport) })
Convey("Construct ampCacheRendezvous with cache and no front domain", func() { transport := &mockTransport{http.StatusOK, []byte{}} rend, err := newAMPCacheRendezvous("http://test.broker", "https://amp.cache/", []string{}, transport) So(err, ShouldBeNil) So(rend.brokerURL, ShouldNotBeNil) So(rend.brokerURL.String(), ShouldResemble, "http://test.broker") So(rend.cacheURL, ShouldNotBeNil) So(rend.cacheURL.String(), ShouldResemble, "https://amp.cache/") So(rend.fronts, ShouldResemble, []string{}) So(rend.transport, ShouldEqual, transport) })
Convey("Construct ampCacheRendezvous with no cache and front domain", func() { transport := &mockTransport{http.StatusOK, []byte{}} rend, err := newAMPCacheRendezvous("http://test.broker", "", []string{"front"}, transport) So(err, ShouldBeNil) So(rend.brokerURL, ShouldNotBeNil) So(rend.brokerURL.String(), ShouldResemble, "http://test.broker") So(rend.cacheURL, ShouldBeNil) So(rend.fronts, ShouldContain, "front") So(rend.transport, ShouldEqual, transport) })
Convey("Construct ampCacheRendezvous with cache and front domain", func() { transport := &mockTransport{http.StatusOK, []byte{}} rend, err := newAMPCacheRendezvous("http://test.broker", "https://amp.cache/", []string{"front"}, transport) So(err, ShouldBeNil) So(rend.brokerURL, ShouldNotBeNil) So(rend.brokerURL.String(), ShouldResemble, "http://test.broker") So(rend.cacheURL, ShouldNotBeNil) So(rend.cacheURL.String(), ShouldResemble, "https://amp.cache/") So(rend.fronts, ShouldContain, "front") So(rend.transport, ShouldEqual, transport) })
Convey("ampCacheRendezvous.Exchange responds with answer", func() { fakeEncPollResp := makeEncPollResp( `{"answer": "{\"type\":\"answer\",\"sdp\":\"fake\"}" }`, "", ) rend, err := newAMPCacheRendezvous("http://test.broker", "", []string{}, &mockTransport{http.StatusOK, ampArmorEncode(fakeEncPollResp)}) So(err, ShouldBeNil) answer, err := rend.Exchange(fakeEncPollReq) So(err, ShouldBeNil) So(answer, ShouldResemble, fakeEncPollResp) })
Convey("ampCacheRendezvous.Exchange responds with no answer", func() { fakeEncPollResp := makeEncPollResp( "", `{"error": "no snowflake proxies currently available"}`, ) rend, err := newAMPCacheRendezvous("http://test.broker", "", []string{}, &mockTransport{http.StatusOK, ampArmorEncode(fakeEncPollResp)}) So(err, ShouldBeNil) answer, err := rend.Exchange(fakeEncPollReq) So(err, ShouldBeNil) So(answer, ShouldResemble, fakeEncPollResp) })
Convey("ampCacheRendezvous.Exchange fails with unexpected HTTP status code", func() { rend, err := newAMPCacheRendezvous("http://test.broker", "", []string{}, &mockTransport{http.StatusInternalServerError, []byte{}}) So(err, ShouldBeNil) answer, err := rend.Exchange(fakeEncPollReq) So(err, ShouldNotBeNil) So(answer, ShouldBeNil) So(err.Error(), ShouldResemble, brokerErrorUnexpected) })
Convey("ampCacheRendezvous.Exchange fails with error", func() { transportErr := errors.New("error") rend, err := newAMPCacheRendezvous("http://test.broker", "", []string{}, &errorTransport{err: transportErr}) So(err, ShouldBeNil) answer, err := rend.Exchange(fakeEncPollReq) So(err, ShouldEqual, transportErr) So(answer, ShouldBeNil) })
Convey("ampCacheRendezvous.Exchange fails with large read", func() { // readLimit should apply to the raw HTTP body, not the // encoded bytes. Encode readLimit bytes—the encoded // size will be larger—and try to read the body. It // should fail. rend, err := newAMPCacheRendezvous("http://test.broker", "", []string{}, &mockTransport{http.StatusOK, ampArmorEncode(make([]byte, readLimit))}) So(err, ShouldBeNil) _, err = rend.Exchange(fakeEncPollReq) // We may get io.ErrUnexpectedEOF here, or something // like "missing </pre> tag". So(err, ShouldNotBeNil) }) })}
func TestSQSRendezvous(t *testing.T) { Convey("SQS Rendezvous", t, func() {
Convey("Construct SQS queue rendezvous", func() { transport := &mockTransport{http.StatusOK, []byte{}} rend, err := newSQSRendezvous("https://sqs.us-east-1.amazonaws.com", "some-access-key-id", "some-secret-key", transport)
So(err, ShouldBeNil) So(rend.sqsClientID, ShouldNotBeNil) So(rend.sqsClient, ShouldNotBeNil) So(rend.sqsURL, ShouldNotBeNil) So(rend.sqsURL.String(), ShouldResemble, "https://sqs.us-east-1.amazonaws.com") })
ctrl := gomock.NewController(t) mockSqsClient := sqsclient.NewMockSQSClient(ctrl) responseQueueURL := "https://sqs.us-east-1.amazonaws.com/testing" sqsClientID := "test123" sqsUrl, _ := url.Parse("https://sqs.us-east-1.amazonaws.com/broker") fakeEncPollResp := makeEncPollResp( `{"answer": "{\"type\":\"answer\",\"sdp\":\"fake\"}" }`, "", ) sqsRendezvous := sqsRendezvous{ transport: &mockTransport{http.StatusOK, []byte{}}, sqsClientID: sqsClientID, sqsClient: mockSqsClient, sqsURL: sqsUrl, timeout: 0, numRetries: 5, }
Convey("sqsRendezvous.Exchange responds with answer", func() { mockSqsClient.EXPECT().SendMessage(gomock.Any(), &sqs.SendMessageInput{ MessageAttributes: map[string]types.MessageAttributeValue{ "ClientID": { DataType: aws.String("String"), StringValue: aws.String(sqsClientID), }, }, MessageBody: aws.String(string(fakeEncPollResp)), QueueUrl: aws.String(sqsUrl.String()), }) mockSqsClient.EXPECT().GetQueueUrl(gomock.Any(), &sqs.GetQueueUrlInput{ QueueName: aws.String("snowflake-client-" + sqsClientID), }).Return(&sqs.GetQueueUrlOutput{ QueueUrl: aws.String(responseQueueURL), }, nil) mockSqsClient.EXPECT().ReceiveMessage(gomock.Any(), gomock.Eq(&sqs.ReceiveMessageInput{ QueueUrl: &responseQueueURL, MaxNumberOfMessages: 1, WaitTimeSeconds: 20, })).Return(&sqs.ReceiveMessageOutput{ Messages: []types.Message{{Body: aws.String("answer")}}, }, nil)
answer, err := sqsRendezvous.Exchange(fakeEncPollResp)
So(answer, ShouldEqual, []byte("answer")) So(err, ShouldBeNil) })
Convey("sqsRendezvous.Exchange cannot get queue url", func() { mockSqsClient.EXPECT().SendMessage(gomock.Any(), &sqs.SendMessageInput{ MessageAttributes: map[string]types.MessageAttributeValue{ "ClientID": { DataType: aws.String("String"), StringValue: aws.String(sqsClientID), }, }, MessageBody: aws.String(string(fakeEncPollResp)), QueueUrl: aws.String(sqsUrl.String()), }) for i := 0; i < sqsRendezvous.numRetries; i++ { mockSqsClient.EXPECT().GetQueueUrl(gomock.Any(), &sqs.GetQueueUrlInput{ QueueName: aws.String("snowflake-client-" + sqsClientID), }).Return(nil, errors.New("test error")) }
answer, err := sqsRendezvous.Exchange(fakeEncPollResp)
So(answer, ShouldBeNil) So(err, ShouldNotBeNil) So(err, ShouldEqual, errors.New("test error")) })
Convey("sqsRendezvous.Exchange does not receive answer", func() { mockSqsClient.EXPECT().SendMessage(gomock.Any(), &sqs.SendMessageInput{ MessageAttributes: map[string]types.MessageAttributeValue{ "ClientID": { DataType: aws.String("String"), StringValue: aws.String(sqsClientID), }, }, MessageBody: aws.String(string(fakeEncPollResp)), QueueUrl: aws.String(sqsUrl.String()), }) mockSqsClient.EXPECT().GetQueueUrl(gomock.Any(), &sqs.GetQueueUrlInput{ QueueName: aws.String("snowflake-client-" + sqsClientID), }).Return(&sqs.GetQueueUrlOutput{ QueueUrl: aws.String(responseQueueURL), }, nil) for i := 0; i < sqsRendezvous.numRetries; i++ { mockSqsClient.EXPECT().ReceiveMessage(gomock.Any(), gomock.Eq(&sqs.ReceiveMessageInput{ QueueUrl: &responseQueueURL, MaxNumberOfMessages: 1, WaitTimeSeconds: 20, })).Return(&sqs.ReceiveMessageOutput{ Messages: []types.Message{}, }, nil) }
answer, err := sqsRendezvous.Exchange(fakeEncPollResp)
So(answer, ShouldEqual, []byte{}) So(err, ShouldBeNil) }) })}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405/*Package snowflake_client implements functionality necessary for a client to establish a connectionto a server using Snowflake.
Included in the package is a Transport type that implements the Pluggable Transports v2.1 Go APIspecification. To use Snowflake, you must first create a client from a configuration:
config := snowflake_client.ClientConfig{ BrokerURL: "https://snowflake-broker.example.com", FrontDomain: "https://friendlyfrontdomain.net", // ... } transport, err := snowflake_client.NewSnowflakeClient(config) if err != nil { // handle error }
The Dial function connects to a Snowflake server:
conn, err := transport.Dial() if err != nil { // handle error } defer conn.Close()*/package snowflake_client
import ( "context" "errors" "log" "math/rand" "net" "net/url" "strings" "time"
"github.com/pion/ice/v2" "github.com/pion/webrtc/v3" "github.com/xtaci/kcp-go/v5" "github.com/xtaci/smux"
"gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/event" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/nat" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/turbotunnel")
const ( // ReconnectTimeout is the time a Snowflake client will wait before collecting // more snowflakes. ReconnectTimeout = 10 * time.Second // SnowflakeTimeout is the time a Snowflake client will wait before determining that // a remote snowflake has been disconnected. If no new messages are sent or received // in this time period, the client will terminate the connection with the remote // peer and collect a new snowflake. SnowflakeTimeout = 20 * time.Second // DataChannelTimeout is how long the client will wait for the OnOpen callback // on a newly created DataChannel. DataChannelTimeout = 10 * time.Second
// WindowSize is the number of packets in the send and receive window of a KCP connection. WindowSize = 65535 // StreamSize controls the maximum amount of in flight data between a client and server. StreamSize = 1048576 // 1MB)
type dummyAddr struct{}
func (addr dummyAddr) Network() string { return "dummy" }func (addr dummyAddr) String() string { return "dummy" }
// Transport is a structure with methods that conform to the Go PT v2.1 API// https://github.com/Pluggable-Transports/Pluggable-Transports-spec/blob/master/releases/PTSpecV2.1/Pluggable%20Transport%20Specification%20v2.1%20-%20Go%20Transport%20API.pdftype Transport struct { dialer *WebRTCDialer
// EventDispatcher is the event bus for snowflake events. // When an important event happens, it will be distributed here. eventDispatcher event.SnowflakeEventDispatcher}
// ClientConfig defines how the SnowflakeClient will connect to the broker and Snowflake proxies.type ClientConfig struct { // BrokerURL is the full URL of the Snowflake broker that the client will connect to. BrokerURL string // AmpCacheURL is the full URL of a valid AMP cache. A nonzero value indicates // that AMP cache will be used as the rendezvous method with the broker. AmpCacheURL string // SQSQueueURL is the full URL of an AWS SQS Queue. A nonzero value indicates // that SQS queue will be used as the rendezvous method with the broker. SQSQueueURL string // Access Key ID and Secret Key of the credentials used to access the AWS SQS Qeueue SQSAccessKeyID string SQSSecretKey string // FrontDomain is the full URL of an optional front domain that can be used with either // the AMP cache or HTTP domain fronting rendezvous method. FrontDomain string // ICEAddresses are a slice of ICE server URLs that will be used for NAT traversal and // the creation of the client's WebRTC SDP offer. FrontDomains []string // ICEAddresses are a slice of ICE server URLs that will be used for NAT traversal and // the creation of the client's WebRTC SDP offer. ICEAddresses []string // KeepLocalAddresses is an optional setting that will prevent the removal of local or // invalid addresses from the client's SDP offer. This is useful for local deployments // and testing. KeepLocalAddresses bool // Max is the maximum number of snowflake proxy peers that the client should attempt to // connect to. Defaults to 1. Max int // UTLSClientID is the type of user application that snowflake should imitate. // If an empty value is provided, it will use Go's default TLS implementation UTLSClientID string // UTLSRemoveSNI is the flag to control whether SNI should be removed from Client Hello // when uTLS is used. UTLSRemoveSNI bool // BridgeFingerprint is the fingerprint of the bridge that the client will eventually // connect to, as specified in the Bridge line of the torrc. BridgeFingerprint string // CommunicationProxy is the proxy address for network communication CommunicationProxy *url.URL}
// NewSnowflakeClient creates a new Snowflake transport client that can spawn multiple// Snowflake connections.//// brokerURL and frontDomain are the urls for the broker host and domain fronting host// iceAddresses are the STUN/TURN urls needed for WebRTC negotiation// keepLocalAddresses is a flag to enable sending local network addresses (for testing purposes)// max is the maximum number of snowflakes the client should gather for each SOCKS connectionfunc NewSnowflakeClient(config ClientConfig) (*Transport, error) { log.Println("\n\n\n --- Starting Snowflake Client ---")
iceServers := parseIceServers(config.ICEAddresses) // chooses a random subset of servers from inputs rand.Seed(time.Now().UnixNano()) rand.Shuffle(len(iceServers), func(i, j int) { iceServers[i], iceServers[j] = iceServers[j], iceServers[i] }) if len(iceServers) > 2 { iceServers = iceServers[:(len(iceServers)+1)/2] } log.Printf("Using ICE servers:") for _, server := range iceServers { log.Printf("url: %v", strings.Join(server.URLs, " ")) }
// Maintain backwards compatability with old FrontDomain field of ClientConfig if (len(config.FrontDomains) == 0) && (config.FrontDomain != "") { config.FrontDomains = []string{config.FrontDomain} }
// Rendezvous with broker using the given parameters. broker, err := newBrokerChannelFromConfig(config) if err != nil { return nil, err } go updateNATType(iceServers, broker, config.CommunicationProxy)
max := 1 if config.Max > max { max = config.Max } eventsLogger := event.NewSnowflakeEventDispatcher() transport := &Transport{dialer: NewWebRTCDialerWithEventsAndProxy(broker, iceServers, max, eventsLogger, config.CommunicationProxy), eventDispatcher: eventsLogger}
return transport, nil}
// Dial creates a new Snowflake connection.// Dial starts the collection of snowflakes and returns a SnowflakeConn that is a// wrapper around a smux.Stream that will reliably deliver data to a Snowflake// server through one or more snowflake proxies.func (t *Transport) Dial() (net.Conn, error) { // Cleanup functions to run before returning, in case of an error. var cleanup []func() defer func() { // Run cleanup in reverse order, as defer does. for i := len(cleanup) - 1; i >= 0; i-- { cleanup[i]() } }()
// Prepare to collect remote WebRTC peers. snowflakes, err := NewPeers(t.dialer) if err != nil { return nil, err } cleanup = append(cleanup, func() { snowflakes.End() })
// Use a real logger to periodically output how much traffic is happening. snowflakes.bytesLogger = newBytesSyncLogger()
log.Printf("---- SnowflakeConn: begin collecting snowflakes ---") go connectLoop(snowflakes)
// Create a new smux session log.Printf("---- SnowflakeConn: starting a new session ---") pconn, sess, err := newSession(snowflakes) if err != nil { return nil, err } cleanup = append(cleanup, func() { pconn.Close() sess.Close() })
// On the smux session we overlay a stream. stream, err := sess.OpenStream() if err != nil { return nil, err } // Begin exchanging data. log.Printf("---- SnowflakeConn: begin stream %v ---", stream.ID()) cleanup = append(cleanup, func() { stream.Close() })
// All good, clear the cleanup list. cleanup = nil return &SnowflakeConn{Stream: stream, sess: sess, pconn: pconn, snowflakes: snowflakes}, nil}
func (t *Transport) AddSnowflakeEventListener(receiver event.SnowflakeEventReceiver) { t.eventDispatcher.AddSnowflakeEventListener(receiver)}
func (t *Transport) RemoveSnowflakeEventListener(receiver event.SnowflakeEventReceiver) { t.eventDispatcher.RemoveSnowflakeEventListener(receiver)}
// SetRendezvousMethod sets the rendezvous method to the Snowflake broker.func (t *Transport) SetRendezvousMethod(r RendezvousMethod) { t.dialer.Rendezvous = r}
// SnowflakeConn is a reliable connection to a snowflake server that implements net.Conn.type SnowflakeConn struct { *smux.Stream sess *smux.Session pconn net.PacketConn snowflakes *Peers}
// Close closes the connection.//// The collection of snowflake proxies for this connection is stopped.func (conn *SnowflakeConn) Close() error { log.Printf("---- SnowflakeConn: closed stream %v ---", conn.ID()) conn.Stream.Close() log.Printf("---- SnowflakeConn: end collecting snowflakes ---") conn.snowflakes.End() conn.pconn.Close() log.Printf("---- SnowflakeConn: discarding finished session ---") conn.sess.Close() return nil // TODO: return errors if any of the above do}
// loop through all provided STUN servers until we exhaust the list or find// one that is compatible with RFC 5780func updateNATType(servers []webrtc.ICEServer, broker *BrokerChannel, proxy *url.URL) { var restrictedNAT bool var err error for _, server := range servers { addr := strings.TrimPrefix(server.URLs[0], "stun:") restrictedNAT, err = nat.CheckIfRestrictedNATWithProxy(addr, proxy)
if err != nil { log.Printf("Warning: NAT checking failed for server at %s: %s", addr, err) } else { if restrictedNAT { broker.SetNATType(nat.NATRestricted) } else { broker.SetNATType(nat.NATUnrestricted) } break } } if err != nil { broker.SetNATType(nat.NATUnknown) }}
// Returns a slice of webrtc.ICEServer given a slice of addressesfunc parseIceServers(addresses []string) []webrtc.ICEServer { var servers []webrtc.ICEServer if len(addresses) == 0 { return nil } for _, address := range addresses { address = strings.TrimSpace(address)
// ice.ParseURL recognizes many types of ICE servers, // but we only support stun over UDP currently u, err := url.Parse(address) if err != nil { log.Printf("Warning: Parsing ICE server %v resulted in error: %v, skipping", address, err) continue } if u.Scheme != "stun" { log.Printf("Warning: Only stun: (STUN over UDP) servers are supported currently, skipping %v", address) continue }
// add default port, other sanity checks parsedURL, err := ice.ParseURL(address) if err != nil { log.Printf("Warning: Parsing ICE server %v resulted in error: %v, skipping", address, err) continue }
servers = append(servers, webrtc.ICEServer{ URLs: []string{parsedURL.String()}, }) } return servers}
// newSession returns a new smux.Session and the net.PacketConn it is running// over. The net.PacketConn successively connects through Snowflake proxies// pulled from snowflakes.func newSession(snowflakes SnowflakeCollector) (net.PacketConn, *smux.Session, error) { clientID := turbotunnel.NewClientID()
// We build a persistent KCP session on a sequence of ephemeral WebRTC // connections. This dialContext tells RedialPacketConn how to get a new // WebRTC connection when the previous one dies. Inside each WebRTC // connection, we use encapsulationPacketConn to encode packets into a // stream. dialContext := func(ctx context.Context) (net.PacketConn, error) { log.Printf("redialing on same connection") // Obtain an available WebRTC remote. May block. conn := snowflakes.Pop() if conn == nil { return nil, errors.New("handler: Received invalid Snowflake") } log.Println("---- Handler: snowflake assigned ----") // Send the magic Turbo Tunnel token. _, err := conn.Write(turbotunnel.Token[:]) if err != nil { return nil, err } // Send ClientID prefix. _, err = conn.Write(clientID[:]) if err != nil { return nil, err } return newEncapsulationPacketConn(dummyAddr{}, dummyAddr{}, conn), nil } pconn := turbotunnel.NewRedialPacketConn(dummyAddr{}, dummyAddr{}, dialContext)
// conn is built on the underlying RedialPacketConn—when one WebRTC // connection dies, another one will be found to take its place. The // sequence of packets across multiple WebRTC connections drives the KCP // engine. conn, err := kcp.NewConn2(dummyAddr{}, nil, 0, 0, pconn) if err != nil { pconn.Close() return nil, nil, err } // Permit coalescing the payloads of consecutive sends. conn.SetStreamMode(true) // Set the maximum send and receive window sizes to a high number // Removes KCP bottlenecks: https://gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/-/issues/40026 conn.SetWindowSize(WindowSize, WindowSize) // Disable the dynamic congestion window (limit only by the // maximum of local and remote static windows). conn.SetNoDelay( 0, // default nodelay 0, // default interval 0, // default resend 1, // nc=1 => congestion window off ) // On the KCP connection we overlay an smux session and stream. smuxConfig := smux.DefaultConfig() smuxConfig.Version = 2 smuxConfig.KeepAliveTimeout = 10 * time.Minute smuxConfig.MaxStreamBuffer = StreamSize
sess, err := smux.Client(conn, smuxConfig) if err != nil { conn.Close() pconn.Close() return nil, nil, err }
return pconn, sess, err}
// Maintain |SnowflakeCapacity| number of available WebRTC connections, to// transfer to the Tor SOCKS handler when needed.func connectLoop(snowflakes SnowflakeCollector) { for { timer := time.After(ReconnectTimeout) _, err := snowflakes.Collect() if err != nil { log.Printf("WebRTC: %v Retrying...", err) } select { case <-timer: continue case <-snowflakes.Melted(): log.Println("ConnectLoop: stopped.") return } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768package snowflake_client
import ( "bufio" "errors" "io" "net" "time"
"gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/encapsulation")
var errNotImplemented = errors.New("not implemented")
// encapsulationPacketConn implements the net.PacketConn interface over an// io.ReadWriteCloser stream, using the encapsulation package to represent// packets in a stream.type encapsulationPacketConn struct { io.ReadWriteCloser localAddr net.Addr remoteAddr net.Addr bw *bufio.Writer}
// NewEncapsulationPacketConn makesfunc newEncapsulationPacketConn( localAddr, remoteAddr net.Addr, conn io.ReadWriteCloser,) *encapsulationPacketConn { return &encapsulationPacketConn{ ReadWriteCloser: conn, localAddr: localAddr, remoteAddr: remoteAddr, bw: bufio.NewWriter(conn), }}
// ReadFrom reads an encapsulated packet from the stream.func (c *encapsulationPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { n, err := encapsulation.ReadData(c.ReadWriteCloser, p) if err == io.ErrShortBuffer { err = nil } return n, c.remoteAddr, err}
// WriteTo writes an encapsulated packet to the stream.func (c *encapsulationPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) { // addr is ignored. _, err := encapsulation.WriteData(c.bw, p) if err == nil { err = c.bw.Flush() } if err != nil { return 0, err } return len(p), nil}
// LocalAddr returns the localAddr value that was passed to// NewEncapsulationPacketConn.func (c *encapsulationPacketConn) LocalAddr() net.Addr { return c.localAddr}
func (c *encapsulationPacketConn) SetDeadline(t time.Time) error { return errNotImplemented }func (c *encapsulationPacketConn) SetReadDeadline(t time.Time) error { return errNotImplemented }func (c *encapsulationPacketConn) SetWriteDeadline(t time.Time) error { return errNotImplemented }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071package snowflake_client
import ( "log" "time")
const ( LogTimeInterval = 5 * time.Second)
type bytesLogger interface { addOutbound(int64) addInbound(int64)}
// Default bytesLogger does nothing.type bytesNullLogger struct{}
func (b bytesNullLogger) addOutbound(amount int64) {}func (b bytesNullLogger) addInbound(amount int64) {}
// bytesSyncLogger uses channels to safely log from multiple sources with output// occuring at reasonable intervals.type bytesSyncLogger struct { outboundChan chan int64 inboundChan chan int64}
// newBytesSyncLogger returns a new bytesSyncLogger and starts it loggin.func newBytesSyncLogger() *bytesSyncLogger { b := &bytesSyncLogger{ outboundChan: make(chan int64, 5), inboundChan: make(chan int64, 5), } go b.log() return b}
func (b *bytesSyncLogger) log() { var outbound, inbound int64 var outEvents, inEvents int ticker := time.NewTicker(LogTimeInterval) for { select { case <-ticker.C: if outEvents > 0 || inEvents > 0 { log.Printf("Traffic Bytes (in|out): %d | %d -- (%d OnMessages, %d Sends)", inbound, outbound, inEvents, outEvents) } outbound = 0 outEvents = 0 inbound = 0 inEvents = 0 case amount := <-b.outboundChan: outbound += amount outEvents++ case amount := <-b.inboundChan: inbound += amount inEvents++ } }}
func (b *bytesSyncLogger) addOutbound(amount int64) { b.outboundChan <- amount}
func (b *bytesSyncLogger) addInbound(amount int64) { b.inboundChan <- amount}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327package snowflake_client
import ( "crypto/rand" "encoding/hex" "errors" "fmt" "io" "log" "net/url" "strings" "sync" "time"
"github.com/pion/ice/v2" "github.com/pion/transport/v2" "github.com/pion/transport/v2/stdnet" "github.com/pion/webrtc/v3"
"gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/event" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/proxy")
// WebRTCPeer represents a WebRTC connection to a remote snowflake proxy.//// Each WebRTCPeer only ever has one DataChannel that is used as the peer's transport.type WebRTCPeer struct { id string pc *webrtc.PeerConnection transport *webrtc.DataChannel
recvPipe *io.PipeReader writePipe *io.PipeWriter
mu sync.Mutex // protects the following: lastReceive time.Time
open chan struct{} // Channel to notify when datachannel opens closed chan struct{}
once sync.Once // Synchronization for PeerConnection destruction
bytesLogger bytesLogger eventsLogger event.SnowflakeEventReceiver proxy *url.URL}
// Deprecated: Use NewWebRTCPeerWithEventsAndProxy Instead.func NewWebRTCPeer( config *webrtc.Configuration, broker *BrokerChannel,) (*WebRTCPeer, error) { return NewWebRTCPeerWithEventsAndProxy(config, broker, nil, nil)}
// Deprecated: Use NewWebRTCPeerWithEventsAndProxy Instead.func NewWebRTCPeerWithEvents( config *webrtc.Configuration, broker *BrokerChannel, eventsLogger event.SnowflakeEventReceiver,) (*WebRTCPeer, error) { return NewWebRTCPeerWithEventsAndProxy(config, broker, eventsLogger, nil)}
// NewWebRTCPeerWithEventsAndProxy constructs a WebRTC PeerConnection to a snowflake proxy.//// The creation of the peer handles the signaling to the Snowflake broker, including// the exchange of SDP information, the creation of a PeerConnection, and the establishment// of a DataChannel to the Snowflake proxy.func NewWebRTCPeerWithEventsAndProxy( config *webrtc.Configuration, broker *BrokerChannel, eventsLogger event.SnowflakeEventReceiver, proxy *url.URL,) (*WebRTCPeer, error) { if eventsLogger == nil { eventsLogger = event.NewSnowflakeEventDispatcher() }
connection := new(WebRTCPeer) { var buf [8]byte if _, err := rand.Read(buf[:]); err != nil { panic(err) } connection.id = "snowflake-" + hex.EncodeToString(buf[:]) } connection.closed = make(chan struct{})
// Override with something that's not NullLogger to have real logging. connection.bytesLogger = &bytesNullLogger{}
// Pipes remain the same even when DataChannel gets switched. connection.recvPipe, connection.writePipe = io.Pipe()
connection.eventsLogger = eventsLogger connection.proxy = proxy
err := connection.connect(config, broker) if err != nil { connection.Close() return nil, err } return connection, nil}
// Read bytes from local SOCKS.// As part of |io.ReadWriter|func (c *WebRTCPeer) Read(b []byte) (int, error) { return c.recvPipe.Read(b)}
// Writes bytes out to remote WebRTC.// As part of |io.ReadWriter|func (c *WebRTCPeer) Write(b []byte) (int, error) { err := c.transport.Send(b) if err != nil { return 0, err } c.bytesLogger.addOutbound(int64(len(b))) return len(b), nil}
// Closed returns a boolean indicated whether the peer is closed.func (c *WebRTCPeer) Closed() bool { select { case <-c.closed: return true default: } return false}
// Close closes the connection the snowflake proxy.func (c *WebRTCPeer) Close() error { c.once.Do(func() { close(c.closed) c.cleanup() log.Printf("WebRTC: Closing") }) return nil}
// Prevent long-lived broken remotes.// Should also update the DataChannel in underlying go-webrtc's to make Closes// more immediate / responsive.func (c *WebRTCPeer) checkForStaleness(timeout time.Duration) { c.mu.Lock() c.lastReceive = time.Now() c.mu.Unlock() for { c.mu.Lock() lastReceive := c.lastReceive c.mu.Unlock() if time.Since(lastReceive) > timeout { log.Printf("WebRTC: No messages received for %v -- closing stale connection.", timeout) err := errors.New("no messages received, closing stale connection") c.eventsLogger.OnNewSnowflakeEvent(event.EventOnSnowflakeConnectionFailed{Error: err}) c.Close() return } select { case <-c.closed: return case <-time.After(time.Second): } }}
// connect does the bulk of the work: gather ICE candidates, send the SDP offer to broker,// receive an answer from broker, and wait for data channel to openfunc (c *WebRTCPeer) connect(config *webrtc.Configuration, broker *BrokerChannel) error { log.Println(c.id, " connecting...") err := c.preparePeerConnection(config) localDescription := c.pc.LocalDescription() c.eventsLogger.OnNewSnowflakeEvent(event.EventOnOfferCreated{ WebRTCLocalDescription: localDescription, Error: err, }) if err != nil { return err }
answer, err := broker.Negotiate(localDescription) c.eventsLogger.OnNewSnowflakeEvent(event.EventOnBrokerRendezvous{ WebRTCRemoteDescription: answer, Error: err, }) if err != nil { return err } log.Printf("Received Answer.\n") err = c.pc.SetRemoteDescription(*answer) if nil != err { log.Println("WebRTC: Unable to SetRemoteDescription:", err) return err }
// Wait for the datachannel to open or time out select { case <-c.open: case <-time.After(DataChannelTimeout): c.transport.Close() err = errors.New("timeout waiting for DataChannel.OnOpen") c.eventsLogger.OnNewSnowflakeEvent(event.EventOnSnowflakeConnectionFailed{Error: err}) return err }
go c.checkForStaleness(SnowflakeTimeout) return nil}
// preparePeerConnection creates a new WebRTC PeerConnection and returns it// after non-trickle ICE candidate gathering is complete.func (c *WebRTCPeer) preparePeerConnection(config *webrtc.Configuration) error { var err error s := webrtc.SettingEngine{} s.SetICEMulticastDNSMode(ice.MulticastDNSModeDisabled) // Use the SetNet setting https://pkg.go.dev/github.com/pion/webrtc/v3#SettingEngine.SetNet // to get snowflake working in shadow (where the AF_NETLINK family is not implemented). // These two lines of code functionally revert a new change in pion by silently ignoring // when net.Interfaces() fails, rather than throwing an error var vnet transport.Net vnet, _ = stdnet.NewNet()
if c.proxy != nil { if err = proxy.CheckProxyProtocolSupport(c.proxy); err != nil { return err } socksClient := proxy.NewSocks5UDPClient(c.proxy) vnet = proxy.NewTransportWrapper(&socksClient, vnet) }
s.SetNet(vnet) api := webrtc.NewAPI(webrtc.WithSettingEngine(s)) c.pc, err = api.NewPeerConnection(*config) if err != nil { log.Printf("NewPeerConnection ERROR: %s", err) return err } ordered := true dataChannelOptions := &webrtc.DataChannelInit{ Ordered: &ordered, } // We must create the data channel before creating an offer // https://github.com/pion/webrtc/wiki/Release-WebRTC@v3.0.0#a-data-channel-is-no-longer-implicitly-created-with-a-peerconnection dc, err := c.pc.CreateDataChannel(c.id, dataChannelOptions) if err != nil { log.Printf("CreateDataChannel ERROR: %s", err) return err } dc.OnOpen(func() { c.eventsLogger.OnNewSnowflakeEvent(event.EventOnSnowflakeConnected{}) log.Println("WebRTC: DataChannel.OnOpen") close(c.open) }) dc.OnClose(func() { log.Println("WebRTC: DataChannel.OnClose") c.Close() }) dc.OnError(func(err error) { c.eventsLogger.OnNewSnowflakeEvent(event.EventOnSnowflakeConnectionFailed{Error: err}) }) dc.OnMessage(func(msg webrtc.DataChannelMessage) { if len(msg.Data) <= 0 { log.Println("0 length message---") } n, err := c.writePipe.Write(msg.Data) c.bytesLogger.addInbound(int64(n)) if err != nil { // TODO: Maybe shouldn't actually close. log.Println("Error writing to SOCKS pipe") if inerr := c.writePipe.CloseWithError(err); inerr != nil { log.Printf("c.writePipe.CloseWithError returned error: %v", inerr) } } c.mu.Lock() c.lastReceive = time.Now() c.mu.Unlock() }) c.transport = dc c.open = make(chan struct{}) log.Println("WebRTC: DataChannel created")
offer, err := c.pc.CreateOffer(nil) // TODO: Potentially timeout and retry if ICE isn't working. if err != nil { log.Println("Failed to prepare offer", err) c.pc.Close() return err } log.Println("WebRTC: Created offer")
// Allow candidates to accumulate until ICEGatheringStateComplete. done := webrtc.GatheringCompletePromise(c.pc) // Start gathering candidates err = c.pc.SetLocalDescription(offer) if err != nil { log.Println("Failed to apply offer", err) c.pc.Close() return err } log.Println("WebRTC: Set local description")
<-done // Wait for ICE candidate gathering to complete.
if !strings.Contains(c.pc.LocalDescription().SDP, "\na=candidate:") { return fmt.Errorf("SDP offer contains no candidate") } return nil}
// cleanup closes all channels and transportsfunc (c *WebRTCPeer) cleanup() { // Close this side of the SOCKS pipe. if c.writePipe != nil { // c.writePipe can be nil in tests. c.writePipe.Close() } if nil != c.transport { log.Printf("WebRTC: closing DataChannel") c.transport.Close() } if nil != c.pc { log.Printf("WebRTC: closing PeerConnection") err := c.pc.Close() if nil != err { log.Printf("Error closing peerconnection...") } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319// Client transport plugin for the Snowflake pluggable transport.package main
import ( "flag" "fmt" "io" "log" "net" "os" "os/signal" "path/filepath" "strconv" "strings" "sync" "syscall"
pt "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/goptlib"
sf "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/client/lib" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/event" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/proxy" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/safelog" "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/v2/common/version")
const ( DefaultSnowflakeCapacity = 1)
type ptEventLogger struct {}
func NewPTEventLogger() event.SnowflakeEventReceiver { return &ptEventLogger{}}
func (p ptEventLogger) OnNewSnowflakeEvent(e event.SnowflakeEvent) { pt.Log(pt.LogSeverityNotice, e.String())}
// Exchanges bytes between two ReadWriters.// (In this case, between a SOCKS connection and a snowflake transport conn)func copyLoop(socks, sfconn io.ReadWriter) { done := make(chan struct{}, 2) go func() { if _, err := io.Copy(socks, sfconn); err != nil { log.Printf("copying Snowflake to SOCKS resulted in error: %v", err) } done <- struct{}{} }() go func() { if _, err := io.Copy(sfconn, socks); err != nil { log.Printf("copying SOCKS to Snowflake resulted in error: %v", err) } done <- struct{}{} }() <-done log.Println("copy loop ended")}
// Accept local SOCKS connections and connect to a Snowflake connectionfunc socksAcceptLoop(ln *pt.SocksListener, config sf.ClientConfig, shutdown chan struct{}, wg *sync.WaitGroup) { defer ln.Close() for { conn, err := ln.AcceptSocks() if err != nil { if err, ok := err.(net.Error); ok && err.Temporary() { continue } log.Printf("SOCKS accept error: %s", err) break } log.Printf("SOCKS accepted: %v", conn.Req) wg.Add(1) go func() { defer wg.Done() defer conn.Close()
// Check to see if our command line options are overriden by SOCKS options if arg, ok := conn.Req.Args.Get("ampcache"); ok { config.AmpCacheURL = arg } if arg, ok := conn.Req.Args.Get("sqsqueue"); ok { config.SQSQueueURL = arg } if arg, ok := conn.Req.Args.Get("sqsakid"); ok { config.SQSAccessKeyID = arg } if arg, ok := conn.Req.Args.Get("sqsskey"); ok { config.SQSSecretKey = arg } if arg, ok := conn.Req.Args.Get("fronts"); ok { if arg != "" { config.FrontDomains = strings.Split(strings.TrimSpace(arg), ",") } } else if arg, ok := conn.Req.Args.Get("front"); ok { config.FrontDomains = strings.Split(strings.TrimSpace(arg), ",") } if arg, ok := conn.Req.Args.Get("ice"); ok { config.ICEAddresses = strings.Split(strings.TrimSpace(arg), ",") } if arg, ok := conn.Req.Args.Get("max"); ok { max, err := strconv.Atoi(arg) if err != nil { conn.Reject() log.Println("Invalid SOCKS arg: max=", arg) return } config.Max = max } if arg, ok := conn.Req.Args.Get("url"); ok { config.BrokerURL = arg } if arg, ok := conn.Req.Args.Get("utls-nosni"); ok { switch strings.ToLower(arg) { case "true": fallthrough case "yes": config.UTLSRemoveSNI = true } } if arg, ok := conn.Req.Args.Get("utls-imitate"); ok { config.UTLSClientID = arg } if arg, ok := conn.Req.Args.Get("fingerprint"); ok { config.BridgeFingerprint = arg } transport, err := sf.NewSnowflakeClient(config) if err != nil { conn.Reject() log.Println("Failed to start snowflake transport: ", err) return } transport.AddSnowflakeEventListener(NewPTEventLogger()) err = conn.Grant(&net.TCPAddr{IP: net.IPv4zero, Port: 0}) if err != nil { log.Printf("conn.Grant error: %s", err) return }
handler := make(chan struct{}) go func() { defer close(handler) sconn, err := transport.Dial() if err != nil { log.Printf("dial error: %s", err) return } defer sconn.Close() // copy between the created Snowflake conn and the SOCKS conn copyLoop(conn, sconn) }() select { case <-shutdown: log.Println("Received shutdown signal") case <-handler: log.Println("Handler ended") } return }() }}
func main() { iceServersCommas := flag.String("ice", "", "comma-separated list of ICE servers") brokerURL := flag.String("url", "", "URL of signaling broker") frontDomain := flag.String("front", "", "front domain") frontDomainsCommas := flag.String("fronts", "", "comma-separated list of front domains") ampCacheURL := flag.String("ampcache", "", "URL of AMP cache to use as a proxy for signaling") sqsQueueURL := flag.String("sqsqueue", "", "URL of SQS Queue to use as a proxy for signaling") sqsAccessKeyId := flag.String("sqsakid", "", "Access Key ID for credentials to access SQS Queue ") sqsSecretKey := flag.String("sqsskey", "", "Secret Key for credentials to access SQS Queue") logFilename := flag.String("log", "", "name of log file") logToStateDir := flag.Bool("log-to-state-dir", false, "resolve the log file relative to tor's pt state dir") keepLocalAddresses := flag.Bool("keep-local-addresses", false, "keep local LAN address ICE candidates") unsafeLogging := flag.Bool("unsafe-logging", false, "prevent logs from being scrubbed") max := flag.Int("max", DefaultSnowflakeCapacity, "capacity for number of multiplexed WebRTC peers") versionFlag := flag.Bool("version", false, "display version info to stderr and quit")
// Deprecated oldLogToStateDir := flag.Bool("logToStateDir", false, "use -log-to-state-dir instead") oldKeepLocalAddresses := flag.Bool("keepLocalAddresses", false, "use -keep-local-addresses instead")
flag.Parse()
if *versionFlag { fmt.Fprintf(os.Stderr, "snowflake-client %s", version.ConstructResult()) os.Exit(0) }
log.SetFlags(log.LstdFlags | log.LUTC)
// Don't write to stderr; versions of tor earlier than about 0.3.5.6 do // not read from the pipe, and eventually we will deadlock because the // buffer is full. // https://bugs.torproject.org/26360 // https://bugs.torproject.org/25600#comment:14 var logOutput = io.Discard if *logFilename != "" { if *logToStateDir || *oldLogToStateDir { stateDir, err := pt.MakeStateDir() if err != nil { log.Fatal(err) } *logFilename = filepath.Join(stateDir, *logFilename) } logFile, err := os.OpenFile(*logFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) if err != nil { log.Fatal(err) } defer logFile.Close() logOutput = logFile } if *unsafeLogging { log.SetOutput(logOutput) } else { // We want to send the log output through our scrubber first log.SetOutput(&safelog.LogScrubber{Output: logOutput}) }
log.Printf("snowflake-client %s\n", version.GetVersion())
iceAddresses := strings.Split(strings.TrimSpace(*iceServersCommas), ",")
var frontDomains []string if *frontDomainsCommas != "" { frontDomains = strings.Split(strings.TrimSpace(*frontDomainsCommas), ",") }
// Maintain backwards compatability with legacy commandline option if (len(frontDomains) == 0) && (*frontDomain != "") { frontDomains = []string{*frontDomain} }
config := sf.ClientConfig{ BrokerURL: *brokerURL, AmpCacheURL: *ampCacheURL, SQSQueueURL: *sqsQueueURL, SQSAccessKeyID: *sqsAccessKeyId, SQSSecretKey: *sqsSecretKey, FrontDomains: frontDomains, ICEAddresses: iceAddresses, KeepLocalAddresses: *keepLocalAddresses || *oldKeepLocalAddresses, Max: *max, }
// Begin goptlib client process. ptInfo, err := pt.ClientSetup(nil) if err != nil { log.Fatal(err) } if ptInfo.ProxyURL != nil { if err := proxy.CheckProxyProtocolSupport(ptInfo.ProxyURL); err != nil { pt.ProxyError("proxy is not supported:" + err.Error()) os.Exit(1) } else { config.CommunicationProxy = ptInfo.ProxyURL client := proxy.NewSocks5UDPClient(config.CommunicationProxy) conn, err := client.ListenPacket("udp", nil) if err != nil { pt.ProxyError("proxy test failure:" + err.Error()) os.Exit(1) } conn.Close() pt.ProxyDone() } } listeners := make([]net.Listener, 0) shutdown := make(chan struct{}) var wg sync.WaitGroup for _, methodName := range ptInfo.MethodNames { switch methodName { case "snowflake": // TODO: Be able to recover when SOCKS dies. ln, err := pt.ListenSocks("tcp", "127.0.0.1:0") if err != nil { pt.CmethodError(methodName, err.Error()) break } log.Printf("Started SOCKS listener at %v.", ln.Addr()) go socksAcceptLoop(ln, config, shutdown, &wg) pt.Cmethod(methodName, ln.Version(), ln.Addr()) listeners = append(listeners, ln) default: pt.CmethodError(methodName, "no such method") } } pt.CmethodsDone()
sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGTERM)
if os.Getenv("TOR_PT_EXIT_ON_STDIN_CLOSE") == "1" { // This environment variable means we should treat EOF on stdin // just like SIGTERM: https://bugs.torproject.org/15435. go func() { if _, err := io.Copy(io.Discard, os.Stdin); err != nil { log.Printf("calling io.Copy(io.Discard, os.Stdin) returned error: %v", err) } log.Printf("synthesizing SIGTERM because of stdin close") sigChan <- syscall.SIGTERM }() }
// Wait for a signal. <-sigChan log.Println("stopping snowflake")
// Signal received, shut down. for _, ln := range listeners { ln.Close() } close(shutdown) wg.Wait() log.Println("snowflake is done.")}123456789UseBridges 1DataDirectory datadir
ClientTransportPlugin snowflake exec ./client -log snowflake.log
Bridge snowflake 192.0.2.3:80 2B280B23E1107BB62ABFC40DDCC8824814F80A72 fingerprint=2B280B23E1107BB62ABFC40DDCC8824814F80A72 url=https://snowflake-broker.torproject.net.global.prod.fastly.net/ fronts=foursquare.com,github.githubassets.com ice=stun:stun.l.google.com:19302,stun:stun.antisip.com:3478,stun:stun.bluesip.net:3478,stun:stun.dus.net:3478,stun:stun.epygi.com:3478,stun:stun.sonetel.com:3478,stun:stun.uls.co.za:3478,stun:stun.voipgate.com:3478,stun:stun.voys.nl:3478 utls-imitate=hellorandomizedalpnBridge snowflake 192.0.2.4:80 8838024498816A039FCBBAB14E6F40A0843051FA fingerprint=8838024498816A039FCBBAB14E6F40A0843051FA url=https://snowflake-broker.torproject.net.global.prod.fastly.net/ fronts=foursquare.com,github.githubassets.com ice=stun:stun.l.google.com:19302,stun:stun.antisip.com:3478,stun:stun.bluesip.net:3478,stun:stun.dus.net:3478,stun:stun.epygi.com:3478,stun:stun.sonetel.net:3478,stun:stun.uls.co.za:3478,stun:stun.voipgate.com:3478,stun:stun.voys.nl:3478 utls-imitate=hellorandomizedalpn
SocksPort auto123456UseBridges 1DataDirectory datadir
ClientTransportPlugin snowflake exec ./client -keep-local-addresses
Bridge snowflake 192.0.2.3:1 url=http://localhost:8080/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136package amp
import ( "bufio" "bytes" "encoding/base64" "fmt" "io"
"golang.org/x/net/html")
// ErrUnknownVersion is the error returned when the first character inside the// element encoding (but outside the base64 encoding) is not '0'.type ErrUnknownVersion byte
func (err ErrUnknownVersion) Error() string { return fmt.Sprintf("unknown armor version indicator %+q", byte(err))}
func isASCIIWhitespace(b byte) bool { switch b { // https://infra.spec.whatwg.org/#ascii-whitespace case '\x09', '\x0a', '\x0c', '\x0d', '\x20': return true default: return false }}
func splitASCIIWhitespace(data []byte, atEOF bool) (advance int, token []byte, err error) { var i, j int // Skip initial whitespace. for i = 0; i < len(data); i++ { if !isASCIIWhitespace(data[i]) { break } } // Look for next whitespace. for j = i; j < len(data); j++ { if isASCIIWhitespace(data[j]) { return j + 1, data[i:j], nil } } // We reached the end of data without finding more whitespace. Only // consider it a token if we are at EOF. if atEOF && i < j { return j, data[i:j], nil } // Otherwise, request more data. return i, nil, nil}
func decodeToWriter(w io.Writer, r io.Reader) (int64, error) { tokenizer := html.NewTokenizer(r) // Set a memory limit on token sizes, otherwise the tokenizer will // buffer text indefinitely if it is not broken up by other token types. tokenizer.SetMaxBuf(elementSizeLimit) active := false total := int64(0) for { tt := tokenizer.Next() switch tt { case html.ErrorToken: err := tokenizer.Err() if err == io.EOF { err = nil } if err == nil && active { return total, fmt.Errorf("missing </pre> tag") } return total, err case html.TextToken: if active { // Re-join the separate chunks of text and // feed them to the decoder. scanner := bufio.NewScanner(bytes.NewReader(tokenizer.Text())) scanner.Split(splitASCIIWhitespace) for scanner.Scan() { n, err := w.Write(scanner.Bytes()) total += int64(n) if err != nil { return total, err } } if err := scanner.Err(); err != nil { return total, err } } case html.StartTagToken: tn, _ := tokenizer.TagName() if string(tn) == "pre" { if active { // nesting not allowed return total, fmt.Errorf("unexpected %s", tokenizer.Token()) } active = true } case html.EndTagToken: tn, _ := tokenizer.TagName() if string(tn) == "pre" { if !active { // stray end tag return total, fmt.Errorf("unexpected %s", tokenizer.Token()) } active = false } } }}
// NewArmorDecoder returns a new AMP armor decoder.func NewArmorDecoder(r io.Reader) (io.Reader, error) { pr, pw := io.Pipe() go func() { _, err := decodeToWriter(pw, r) pw.CloseWithError(err) }()
// The first byte inside the element encoding is a server–client // protocol version indicator. var version [1]byte _, err := pr.Read(version[:]) if err != nil { pr.CloseWithError(err) return nil, err } switch version[0] { case '0': return base64.NewDecoder(base64.StdEncoding, pr), nil default: err := ErrUnknownVersion(version[0]) pr.CloseWithError(err) return nil, err }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176package amp
import ( "encoding/base64" "io")
// https://amp.dev/boilerplate/// https://amp.dev/documentation/guides-and-tutorials/learn/spec/amp-boilerplate/?format=websites// https://amp.dev/documentation/guides-and-tutorials/learn/spec/amphtml/?format=websites#the-amp-html-formatconst ( boilerplateStart = `<!doctype html><html amp><head><meta charset="utf-8"><script async src="https://cdn.ampproject.org/v0.js"></script><link rel="canonical" href="#"><meta name="viewport" content="width=device-width"><style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript></head><body>` boilerplateEnd = `</body></html>`)
const ( // We restrict the amount of text may go inside an HTML element, in // order to limit the amount a decoder may have to buffer. elementSizeLimit = 32 * 1024
// The payload is conceptually a long base64-encoded string, but we // break the string into short chunks separated by whitespace. This is // to protect against modification by AMP caches, which reportedly may // truncate long words in text: // https://bugs.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/25985#note_2592348 bytesPerChunk = 32
// We set the number of chunks per element so as to stay under // elementSizeLimit. Here, we assume that there is 1 byte of whitespace // after each chunk (with an additional whitespace byte at the beginning // of the element). chunksPerElement = (elementSizeLimit - 1) / (bytesPerChunk + 1))
// The AMP armor encoder is a chain of a base64 encoder (base64.NewEncoder) and// an HTML element encoder (elementEncoder). A top-level encoder (armorEncoder)// coordinates these two, and handles prepending and appending the AMP// boilerplate. armorEncoder's Write method writes data into the base64 encoder,// where it makes its way through the chain.
// NewArmorEncoder returns a new AMP armor encoder. Anything written to the// returned io.WriteCloser will be encoded and written to w. The caller must// call Close to flush any partially written data and output the AMP boilerplate// trailer.func NewArmorEncoder(w io.Writer) (io.WriteCloser, error) { // Immediately write the AMP boilerplate header. _, err := w.Write([]byte(boilerplateStart)) if err != nil { return nil, err }
element := &elementEncoder{w: w} // Write a server–client protocol version indicator, outside the base64 // layer. _, err = element.Write([]byte{'0'}) if err != nil { return nil, err }
base64 := base64.NewEncoder(base64.StdEncoding, element) return &armorEncoder{ w: w, element: element, base64: base64, }, nil}
type armorEncoder struct { base64 io.WriteCloser element *elementEncoder w io.Writer}
func (enc *armorEncoder) Write(p []byte) (int, error) { // Write into the chain base64 | element | w. return enc.base64.Write(p)}
func (enc *armorEncoder) Close() error { // Close the base64 encoder first, to flush out any buffered data and // the final padding. err := enc.base64.Close() if err != nil { return err }
// Next, close the element encoder, to close any open elements. err = enc.element.Close() if err != nil { return err }
// Finally, output the AMP boilerplate trailer. _, err = enc.w.Write([]byte(boilerplateEnd)) if err != nil { return err }
return nil}
// elementEncoder arranges written data into pre elements, with the text within// separated into chunks. It does no HTML encoding, so data written must not// contain any bytes that are meaningful in HTML.type elementEncoder struct { w io.Writer chunkCounter int elementCounter int}
func (enc *elementEncoder) Write(p []byte) (n int, err error) { total := 0 for len(p) > 0 { if enc.elementCounter == 0 && enc.chunkCounter == 0 { _, err := enc.w.Write([]byte("<pre>\n")) if err != nil { return total, err } }
n := bytesPerChunk - enc.chunkCounter if n > len(p) { n = len(p) } nn, err := enc.w.Write(p[:n]) if err != nil { return total, err } total += nn p = p[n:]
enc.chunkCounter += n if enc.chunkCounter >= bytesPerChunk { enc.chunkCounter = 0 enc.elementCounter += 1 nn, err = enc.w.Write([]byte("\n")) if err != nil { return total, err } total += nn }
if enc.elementCounter >= chunksPerElement { enc.elementCounter = 0 nn, err = enc.w.Write([]byte("</pre>\n")) if err != nil { return total, err } total += nn } } return total, nil}
func (enc *elementEncoder) Close() error { var err error if !(enc.elementCounter == 0 && enc.chunkCounter == 0) { if enc.chunkCounter == 0 { _, err = enc.w.Write([]byte("</pre>\n")) } else { _, err = enc.w.Write([]byte("\n</pre>\n")) } } return err}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226package amp
import ( "io" "math/rand" "strings" "testing")
func armorDecodeToString(src string) (string, error) { dec, err := NewArmorDecoder(strings.NewReader(src)) if err != nil { return "", err } p, err := io.ReadAll(dec) return string(p), err}
func TestArmorDecoder(t *testing.T) { for _, test := range []struct { input string expectedOutput string expectedErr bool }{ {`<pre>0</pre>`, "", false, }, {`<pre>0aGVsbG8gd29ybGQK</pre>`, "hello world\n", false, }, // bad version indicator {`<pre>1aGVsbG8gd29ybGQK</pre>`, "", true, }, // text outside <pre> elements {`0aGVsbG8gd29ybGQKblah blah blah<pre>0aGVsbG8gd29ybGQK</pre>0aGVsbG8gd29ybGQKblah blah blah`, "hello world\n", false, }, {`<pre>0QUJDREVGR0hJSktMTU5PUFFSU1RVVld</pre>junk<pre>YWVowMTIzNDU2Nzg5Cg=</pre><pre>=</pre>`, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n", false, }, // no <pre> elements, hence no version indicator {`aGVsbG8gd29ybGQKblah blah blahaGVsbG8gd29ybGQKaGVsbG8gd29ybGQKblah blah blah`, "", true, }, // empty <pre> elements, hence no version indicator {`aGVsbG8gd29ybGQKblah blah blah<pre> </pre>aGVsbG8gd29ybGQKaGVsbG8gd29ybGQK<pre></pre>blah blah blah`, "", true, }, // other elements inside <pre> { "blah <pre>0aGVsb<p>G8gd29</p>ybGQK</pre>", "hello world\n", false, }, // HTML comment { "blah <!-- <pre>aGVsbG8gd29ybGQK</pre> -->", "", true, }, // all kinds of ASCII whitespace { "blah <pre>\x200\x09aG\x0aV\x0csb\x0dG8\x20gd29ybGQK</pre>", "hello world\n", false, },
// bad padding {`<pre>0QUJDREVGR0hJSktMTU5PUFFSU1RVVld</pre>junk<pre>YWVowMTIzNDU2Nzg5Cg=</pre>`, "", true, }, /* // per-chunk base64 // test disabled because Go stdlib handles this incorrectly: // https://github.com/golang/go/issues/31626 { "<pre>QQ==</pre><pre>Qg==</pre>", "", true, }, */ // missing </pre> { "blah <pre></pre><pre>0aGVsbG8gd29ybGQK", "", true, }, // nested <pre> { "blah <pre>0aGVsb<pre>G8gd29</pre>ybGQK</pre>", "", true, }, } { output, err := armorDecodeToString(test.input) if test.expectedErr && err == nil { t.Errorf("%+q → (%+q, %v), expected error", test.input, output, err) continue } if !test.expectedErr && err != nil { t.Errorf("%+q → (%+q, %v), expected no error", test.input, output, err) continue } if !test.expectedErr && output != test.expectedOutput { t.Errorf("%+q → (%+q, %v), expected (%+q, %v)", test.input, output, err, test.expectedOutput, nil) continue } }}
func armorRoundTrip(s string) (string, error) { var encoded strings.Builder enc, err := NewArmorEncoder(&encoded) if err != nil { return "", err } _, err = io.Copy(enc, strings.NewReader(s)) if err != nil { return "", err } err = enc.Close() if err != nil { return "", err } return armorDecodeToString(encoded.String())}
func TestArmorRoundTrip(t *testing.T) { lengths := make([]int, 0) // Test short strings and lengths around elementSizeLimit thresholds. for i := 0; i < bytesPerChunk*2; i++ { lengths = append(lengths, i) } for i := -10; i < +10; i++ { lengths = append(lengths, elementSizeLimit+i) lengths = append(lengths, 2*elementSizeLimit+i) } for _, n := range lengths { buf := make([]byte, n) rand.Read(buf) input := string(buf) output, err := armorRoundTrip(input) if err != nil { t.Errorf("length %d → error %v", n, err) continue } if output != input { t.Errorf("length %d → %+q", n, output) continue } }}.gitattributes+6
Hasil OBS/2024-03-01 15-05-14.mkvAdded+3
Hasil OBS/2024-03-05 07-38-44.mkvAdded+3
Hasil OBS/2024-03-13 13-08-26.mkvAdded+3
Hasil OBS/2024-03-21 08-06-23.mkvAdded+3
Hasil OBS/2024-04-19 13-14-59.mkvAdded+3
Hasil OBS/VPN.mp4Added+3
Hasil OBS/snowflake-main/.gitignoreAdded+19
Hasil OBS/snowflake-main/.gitlab-ci.ymlAdded+276
Hasil OBS/snowflake-main/.gitmodulesAdded
Hasil OBS/snowflake-main/.travis.ymlAdded+13
Hasil OBS/snowflake-main/CONTRIBUTING.mdAdded+5
Hasil OBS/snowflake-main/ChangeLogAdded+195
Hasil OBS/snowflake-main/LICENSEAdded+32
Hasil OBS/snowflake-main/README.mdAdded+109
Hasil OBS/snowflake-main/VagrantfileAdded+67
Hasil OBS/snowflake-main/broker/README.mdAdded+58
Hasil OBS/snowflake-main/broker/amp.goAdded+77
Hasil OBS/snowflake-main/broker/bridge-list.goAdded+94
Hasil OBS/snowflake-main/broker/bridge-list_test.goAdded+64
Hasil OBS/snowflake-main/broker/broker.goAdded+363
Hasil OBS/snowflake-main/broker/http.goAdded+260
Hasil OBS/snowflake-main/broker/ipc.goAdded+281
Hasil OBS/snowflake-main/broker/metrics.goAdded+355
Hasil OBS/snowflake-main/broker/prometheus.goAdded+83
Hasil OBS/snowflake-main/broker/snowflake-broker_test.goAdded+1003
Hasil OBS/snowflake-main/broker/snowflake-heap.goAdded+52
Hasil OBS/snowflake-main/broker/sqs.goAdded+211
Hasil OBS/snowflake-main/broker/sqs_test.goAdded+338
Hasil OBS/snowflake-main/broker/test_geoipAdded+1236
Hasil OBS/snowflake-main/broker/test_geoip6Added+693
Hasil OBS/snowflake-main/client/README.mdAdded+111
Hasil OBS/snowflake-main/client/lib/interfaces.goAdded+24
Hasil OBS/snowflake-main/client/lib/lib_test.goAdded+221
Hasil OBS/snowflake-main/client/lib/peers.goAdded+138
Hasil OBS/snowflake-main/client/lib/rendezvous.goAdded+229
Hasil OBS/snowflake-main/client/lib/rendezvous_ampcache.goAdded+127
Hasil OBS/snowflake-main/client/lib/rendezvous_http.goAdded+80
Hasil OBS/snowflake-main/client/lib/rendezvous_sqs.goAdded+139
Hasil OBS/snowflake-main/client/lib/rendezvous_test.goAdded+398
Hasil OBS/snowflake-main/client/lib/snowflake.goAdded+405
Hasil OBS/snowflake-main/client/lib/turbotunnel.goAdded+68
Hasil OBS/snowflake-main/client/lib/util.goAdded+71
Hasil OBS/snowflake-main/client/lib/webrtc.goAdded+327
Hasil OBS/snowflake-main/client/snowflake.goAdded+319
Hasil OBS/snowflake-main/client/torrcAdded+9
Hasil OBS/snowflake-main/client/torrc.localhostAdded+6
Hasil OBS/snowflake-main/common/amp/armor_decoder.goAdded+136
Hasil OBS/snowflake-main/common/amp/armor_encoder.goAdded+176
Hasil OBS/snowflake-main/common/amp/armor_test.goAdded+226