├── .github ├── FUNDING.yml └── workflows │ ├── build.yml │ ├── nightly.yml │ └── release.yml ├── .gitignore ├── .vscode └── settings.json ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── docker-compose.yml ├── uthash.h ├── wg-obfuscator.c ├── wg-obfuscator.conf ├── wg-obfuscator.h └── wg-obfuscator.service /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [ClusterM] 2 | custom: ["https://www.buymeacoffee.com/cluster", "https://boosty.to/cluster"] 3 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | workflow_dispatch: 9 | 10 | env: 11 | IMAGE_NAME: wg-obfuscator 12 | PLATFORMS: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6,linux/386,linux/ppc64le,linux/s390x 13 | 14 | jobs: 15 | 16 | build-docker: 17 | runs-on: ubuntu-latest 18 | 19 | strategy: 20 | matrix: 21 | platform: [linux/amd64, linux/arm64, linux/arm/v7, linux/arm/v6, linux/386, linux/ppc64le, linux/s390x] 22 | fail-fast: false 23 | 24 | steps: 25 | - name: Checkout code 26 | uses: actions/checkout@v4 27 | 28 | - name: Set up Docker Buildx 29 | uses: docker/setup-buildx-action@v3 30 | 31 | - name: Prepare filename and tag 32 | id: prep 33 | run: | 34 | SAFE_PLATFORM="${{ matrix.platform }}" 35 | SAFE_PLATFORM=$(echo "$SAFE_PLATFORM" | sed 's|linux/||;s|/|-|g') 36 | echo "safe_platform=$SAFE_PLATFORM" >> $GITHUB_OUTPUT 37 | 38 | - name: Build per-arch image and export as tar 39 | uses: docker/build-push-action@v5 40 | with: 41 | push: false 42 | tags: ${{ env.IMAGE_NAME }}:${{ env.IMAGE_NAME }}-${{ steps.prep.outputs.safe_platform }} 43 | platforms: ${{ matrix.platform }} 44 | outputs: type=docker,dest=${{ env.IMAGE_NAME }}-docker-${{ steps.prep.outputs.safe_platform }}.tar 45 | context: . 46 | 47 | - name: Upload image tar 48 | uses: actions/upload-artifact@v4 49 | with: 50 | name: ${{ env.IMAGE_NAME }}-docker-${{ steps.prep.outputs.safe_platform }}.tar 51 | path: ${{ env.IMAGE_NAME }}-docker-${{ steps.prep.outputs.safe_platform }}.tar 52 | 53 | build-linux: 54 | runs-on: ubuntu-latest 55 | steps: 56 | - name: Checkout 57 | uses: actions/checkout@v4 58 | - name: make clean all x64 59 | run: make clean all 60 | - name: Upload artifact 61 | uses: actions/upload-artifact@v4 62 | with: 63 | name: wg-obfuscator-linux-x64.zip 64 | path: . 65 | - name: apt update 66 | run: sudo apt-get update 67 | - name: Get ARM toolchain 68 | run: sudo apt-get install gcc-arm-linux-gnueabihf gcc-aarch64-linux-gnu 69 | - name: make clean all arm 70 | run: make clean all CC=arm-linux-gnueabihf-gcc 71 | - name: Upload artifact 72 | uses: actions/upload-artifact@v4 73 | with: 74 | name: wg-obfuscator-linux-arm.zip 75 | path: . 76 | - name: make clean all arm64 77 | run: make clean all CC=aarch64-linux-gnu-gcc 78 | - name: Upload artifact 79 | uses: actions/upload-artifact@v4 80 | with: 81 | name: ${{ env.IMAGE_NAME }}-linux-arm64.zip 82 | path: . 83 | 84 | build-macos: 85 | runs-on: macos-latest 86 | steps: 87 | - name: Install argp 88 | run: brew install argp-standalone 89 | - name: Checkout 90 | uses: actions/checkout@v4 91 | - name: make clean all 92 | run: make clean all 93 | - name: Upload artifact 94 | uses: actions/upload-artifact@v4 95 | with: 96 | name: ${{ env.IMAGE_NAME }}-macos.zip 97 | path: . 98 | 99 | build-windows: 100 | runs-on: windows-latest 101 | defaults: 102 | run: 103 | shell: msys2 {0} 104 | steps: 105 | - uses: msys2/setup-msys2@v2 106 | with: 107 | update: true 108 | install: >- 109 | base-devel 110 | gcc 111 | git 112 | libargp-devel 113 | - name: Checkout 114 | uses: actions/checkout@v4 115 | - name: make clean all 116 | run: make clean all 117 | - name: Upload artifact 118 | uses: actions/upload-artifact@v4 119 | with: 120 | name: ${{ env.IMAGE_NAME }}-windows.zip 121 | path: . 122 | -------------------------------------------------------------------------------- /.github/workflows/nightly.yml: -------------------------------------------------------------------------------- 1 | name: Publish Nightly Docker Image 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | workflow_dispatch: 7 | 8 | env: 9 | IMAGE_NAME: wg-obfuscator 10 | PLATFORMS: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6,linux/386,linux/ppc64le,linux/s390x 11 | 12 | jobs: 13 | public-nightly: 14 | runs-on: ubuntu-latest 15 | permissions: 16 | contents: read 17 | packages: write 18 | 19 | strategy: 20 | fail-fast: false 21 | 22 | steps: 23 | - name: Checkout code 24 | uses: actions/checkout@v4 25 | 26 | - name: Set up Docker Buildx 27 | uses: docker/setup-buildx-action@v3 28 | 29 | - name: Log in to Docker Hub 30 | uses: docker/login-action@v3 31 | with: 32 | username: ${{ secrets.DOCKERHUB_USERNAME }} 33 | password: ${{ secrets.DOCKERHUB_TOKEN }} 34 | 35 | - name: Build and push multiarch image 36 | uses: docker/build-push-action@v5 37 | with: 38 | push: true 39 | tags: | 40 | clustermeerkat/${{ env.IMAGE_NAME }}:nightly 41 | platforms: ${{ env.PLATFORMS }} 42 | context: . 43 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Create Release 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | env: 7 | IMAGE_NAME: wg-obfuscator 8 | PLATFORMS: linux/amd64,linux/arm64,linux/arm/v7,linux/arm/v6,linux/386,linux/ppc64le,linux/s390x 9 | 10 | jobs: 11 | 12 | create-release: 13 | runs-on: ubuntu-latest 14 | permissions: 15 | contents: write 16 | steps: 17 | - name: Checkout code 18 | uses: actions/checkout@v4 19 | 20 | - name: Prepare version 21 | id: prep 22 | run: | 23 | VERSION=$(grep WG_OBFUSCATOR_VERSION wg-obfuscator.h | awk '{print $3}' | sed 's|"||g' | tr -d '\r') 24 | echo "version=$VERSION" >> $GITHUB_OUTPUT 25 | 26 | - name: Create Release 27 | id: create_release 28 | uses: ncipollo/release-action@v1 29 | with: 30 | token: ${{ secrets.GITHUB_TOKEN }} 31 | tag: v${{ steps.prep.outputs.version }} 32 | commit: ${{ github.head_ref || github.ref_name }} 33 | name: v${{ steps.prep.outputs.version }} 34 | draft: true 35 | 36 | - name: Output Release URL File 37 | run: echo "${{ steps.create_release.outputs.upload_url }}" > release_url.txt 38 | 39 | - name: Save Release URL File for publish 40 | uses: actions/upload-artifact@v4 41 | with: 42 | name: release_url 43 | path: release_url.txt 44 | 45 | 46 | build-docker: 47 | needs: create-release 48 | runs-on: ubuntu-latest 49 | permissions: 50 | contents: write 51 | 52 | strategy: 53 | matrix: 54 | platform: [linux/amd64, linux/arm64, linux/arm/v7, linux/arm/v6, linux/386, linux/ppc64le, linux/s390x] 55 | fail-fast: false 56 | 57 | steps: 58 | - name: Checkout code 59 | uses: actions/checkout@v4 60 | 61 | - name: Set up Docker Buildx 62 | uses: docker/setup-buildx-action@v3 63 | 64 | - name: Prepare filename, tag and version 65 | id: prep 66 | run: | 67 | SAFE_PLATFORM="${{ matrix.platform }}" 68 | SAFE_PLATFORM=$(echo "$SAFE_PLATFORM" | sed 's|linux/||;s|/|-|g') 69 | echo "safe_platform=$SAFE_PLATFORM" >> $GITHUB_OUTPUT 70 | VERSION=$(grep WG_OBFUSCATOR_VERSION wg-obfuscator.h | awk '{print $3}' | sed 's|"||g' | tr -d '\r') 71 | echo "version=$VERSION" >> $GITHUB_OUTPUT 72 | 73 | - name: Build per-arch image and export as tar 74 | uses: docker/build-push-action@v5 75 | with: 76 | push: false 77 | tags: ${{ env.IMAGE_NAME }}:${{ env.IMAGE_NAME }}-${{ steps.prep.outputs.safe_platform }} 78 | platforms: ${{ matrix.platform }} 79 | outputs: type=docker,dest=${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-docker-${{ steps.prep.outputs.safe_platform }}.tar 80 | context: . 81 | 82 | - name: Load Release URL File from release job 83 | uses: actions/download-artifact@v4.1.7 84 | with: 85 | name: release_url 86 | 87 | - name: Get Release File Name & Upload URL 88 | id: get_release_info 89 | run: | 90 | value=`cat release_url.txt` 91 | echo upload_url=$value >> $GITHUB_OUTPUT 92 | 93 | - name: Upload to release 94 | uses: actions/upload-release-asset@v1 95 | env: 96 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 97 | with: 98 | upload_url: ${{ steps.get_release_info.outputs.upload_url }} 99 | asset_path: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-docker-${{ steps.prep.outputs.safe_platform }}.tar 100 | asset_name: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-docker-${{ steps.prep.outputs.safe_platform }}.tar 101 | asset_content_type: tar 102 | 103 | 104 | build-linux-x64: 105 | needs: create-release 106 | runs-on: ubuntu-latest 107 | permissions: 108 | contents: write 109 | steps: 110 | - name: Checkout 111 | uses: actions/checkout@v4 112 | 113 | - name: make x64 114 | run: make clean all RELEASE=1 115 | 116 | - name: Prepare version 117 | id: prep 118 | run: | 119 | VERSION=$(grep WG_OBFUSCATOR_VERSION wg-obfuscator.h | awk '{print $3}' | sed 's|"||g' | tr -d '\r') 120 | echo "version=$VERSION" >> $GITHUB_OUTPUT 121 | 122 | - name: zip 123 | run: zip ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-linux-x64.zip LICENSE *.md ${{ env.IMAGE_NAME }} 124 | 125 | - name: Load Release URL File from release job 126 | uses: actions/download-artifact@v4.1.7 127 | with: 128 | name: release_url 129 | 130 | - name: Get Release File Name & Upload URL 131 | id: get_release_info 132 | run: | 133 | value=`cat release_url.txt` 134 | echo upload_url=$value >> $GITHUB_OUTPUT 135 | 136 | - name: Upload to release 137 | uses: actions/upload-release-asset@v1 138 | env: 139 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 140 | with: 141 | upload_url: ${{ steps.get_release_info.outputs.upload_url }} 142 | asset_path: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-linux-x64.zip 143 | asset_name: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-linux-x64.zip 144 | asset_content_type: zip 145 | 146 | 147 | build-linux-arm: 148 | needs: create-release 149 | runs-on: ubuntu-latest 150 | permissions: 151 | contents: write 152 | steps: 153 | - name: Checkout 154 | uses: actions/checkout@v4 155 | 156 | - name: apt update 157 | run: sudo apt-get update 158 | 159 | - name: Get ARM toolchain 160 | run: sudo apt-get install gcc-arm-linux-gnueabihf gcc-aarch64-linux-gnu 161 | 162 | - name: make arm 163 | run: make all CC=arm-linux-gnueabihf-gcc RELEASE=1 164 | 165 | - name: Prepare version 166 | id: prep 167 | run: | 168 | VERSION=$(grep WG_OBFUSCATOR_VERSION wg-obfuscator.h | awk '{print $3}' | sed 's|"||g' | tr -d '\r') 169 | echo "version=$VERSION" >> $GITHUB_OUTPUT 170 | 171 | - name: zip 172 | run: zip ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-linux-arm.zip LICENSE *.md ${{ env.IMAGE_NAME }} 173 | 174 | - name: Load Release URL File from release job 175 | uses: actions/download-artifact@v4.1.7 176 | with: 177 | name: release_url 178 | 179 | - name: Get Release File Name & Upload URL 180 | id: get_release_info 181 | run: | 182 | value=`cat release_url.txt` 183 | echo upload_url=$value >> $GITHUB_OUTPUT 184 | 185 | - name: Upload to release 186 | uses: actions/upload-release-asset@v1 187 | env: 188 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 189 | with: 190 | upload_url: ${{ steps.get_release_info.outputs.upload_url }} 191 | asset_path: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-linux-arm.zip 192 | asset_name: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-linux-arm.zip 193 | asset_content_type: zip 194 | 195 | 196 | build-linux-arm64: 197 | needs: create-release 198 | runs-on: ubuntu-latest 199 | permissions: 200 | contents: write 201 | steps: 202 | - name: Checkout 203 | uses: actions/checkout@v4 204 | 205 | - name: apt update 206 | run: sudo apt-get update 207 | 208 | - name: Get ARM toolchain 209 | run: sudo apt-get install gcc-arm-linux-gnueabihf gcc-aarch64-linux-gnu 210 | 211 | - name: make all arm64 212 | run: make all CC=aarch64-linux-gnu-gcc RELEASE=1 213 | 214 | - name: Prepare version 215 | id: prep 216 | run: | 217 | VERSION=$(grep WG_OBFUSCATOR_VERSION wg-obfuscator.h | awk '{print $3}' | sed 's|"||g' | tr -d '\r') 218 | echo "version=$VERSION" >> $GITHUB_OUTPUT 219 | 220 | - name: zip 221 | run: zip ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-linux-arm64.zip LICENSE *.md ${{ env.IMAGE_NAME }} 222 | 223 | - name: Load Release URL File from release job 224 | uses: actions/download-artifact@v4.1.7 225 | with: 226 | name: release_url 227 | 228 | - name: Get Release File Name & Upload URL 229 | id: get_release_info 230 | run: | 231 | value=`cat release_url.txt` 232 | echo upload_url=$value >> $GITHUB_OUTPUT 233 | 234 | - name: Upload to release 235 | uses: actions/upload-release-asset@v1 236 | env: 237 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 238 | with: 239 | upload_url: ${{ steps.get_release_info.outputs.upload_url }} 240 | asset_path: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-linux-arm64.zip 241 | asset_name: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-linux-arm64.zip 242 | asset_content_type: zip 243 | 244 | 245 | build-macos: 246 | needs: create-release 247 | runs-on: macos-latest 248 | permissions: 249 | contents: write 250 | steps: 251 | - name: Install argp 252 | run: brew install argp-standalone 253 | 254 | - name: Checkout 255 | uses: actions/checkout@v4 256 | 257 | - name: make clean all 258 | run: make clean all RELEASE=1 259 | 260 | - name: Prepare version 261 | id: prep 262 | run: | 263 | VERSION=$(grep WG_OBFUSCATOR_VERSION wg-obfuscator.h | awk '{print $3}' | sed 's|"||g' | tr -d '\r') 264 | echo "version=$VERSION" >> $GITHUB_OUTPUT 265 | 266 | - name: zip 267 | run: zip ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-macos.zip LICENSE *.md ${{ env.IMAGE_NAME }} 268 | 269 | - name: Load Release URL File from release job 270 | uses: actions/download-artifact@v4.1.7 271 | with: 272 | name: release_url 273 | 274 | - name: Get Release File Name & Upload URL 275 | id: get_release_info 276 | run: | 277 | value=`cat release_url.txt` 278 | echo upload_url=$value >> $GITHUB_OUTPUT 279 | 280 | - name: Upload to release 281 | uses: actions/upload-release-asset@v1 282 | env: 283 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 284 | with: 285 | upload_url: ${{ steps.get_release_info.outputs.upload_url }} 286 | asset_path: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-macos.zip 287 | asset_name: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-macos.zip 288 | asset_content_type: zip 289 | 290 | 291 | build-windows: 292 | needs: create-release 293 | runs-on: windows-latest 294 | permissions: 295 | contents: write 296 | defaults: 297 | run: 298 | shell: msys2 {0} 299 | steps: 300 | - uses: msys2/setup-msys2@v2 301 | with: 302 | update: true 303 | install: >- 304 | base-devel 305 | gcc 306 | git 307 | libargp-devel 308 | zip 309 | 310 | - name: Checkout 311 | uses: actions/checkout@v4 312 | 313 | - name: make clean all 314 | run: make clean all RELEASE=1 315 | 316 | - name: Prepare version 317 | id: prep 318 | run: | 319 | VERSION=$(grep WG_OBFUSCATOR_VERSION wg-obfuscator.h | awk '{print $3}' | sed 's|"||g' | tr -d '\r') 320 | echo "version=$VERSION" >> $GITHUB_OUTPUT 321 | 322 | - name: zip 323 | run: zip ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-windows-x64.zip LICENSE *.md *.dll *.exe 324 | 325 | - name: Load Release URL File from release job 326 | uses: actions/download-artifact@v4.1.7 327 | with: 328 | name: release_url 329 | 330 | - name: Get Release File Name & Upload URL 331 | id: get_release_info 332 | run: | 333 | value=`cat release_url.txt` 334 | echo upload_url=$value >> $GITHUB_OUTPUT 335 | 336 | - name: Upload to release 337 | uses: actions/upload-release-asset@v1 338 | env: 339 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 340 | with: 341 | upload_url: ${{ steps.get_release_info.outputs.upload_url }} 342 | asset_path: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-windows-x64.zip 343 | asset_name: ${{ env.IMAGE_NAME }}-v${{ steps.prep.outputs.version }}-windows-x64.zip 344 | asset_content_type: zip 345 | 346 | push-to-docker-hub: 347 | runs-on: ubuntu-latest 348 | permissions: 349 | contents: read 350 | packages: write 351 | 352 | strategy: 353 | fail-fast: false 354 | 355 | steps: 356 | - name: Checkout code 357 | uses: actions/checkout@v4 358 | 359 | - name: Set up Docker Buildx 360 | uses: docker/setup-buildx-action@v3 361 | 362 | - name: Log in to Docker Hub 363 | uses: docker/login-action@v3 364 | with: 365 | username: ${{ secrets.DOCKERHUB_USERNAME }} 366 | password: ${{ secrets.DOCKERHUB_TOKEN }} 367 | 368 | - name: Get version 369 | id: prep 370 | run: | 371 | VERSION=$(grep WG_OBFUSCATOR_VERSION wg-obfuscator.h | awk '{print $3}' | sed 's|"||g' | tr -d '\r') 372 | echo "version=$VERSION" >> $GITHUB_OUTPUT 373 | 374 | - name: Build and push multiarch image 375 | uses: docker/build-push-action@v5 376 | with: 377 | push: true 378 | tags: | 379 | clustermeerkat/${{ env.IMAGE_NAME }}:latest 380 | clustermeerkat/${{ env.IMAGE_NAME }}:${{ steps.prep.outputs.version }} 381 | platforms: ${{ env.PLATFORMS }} 382 | context: . 383 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe 2 | wg-obfuscator 3 | *.o 4 | *.dll 5 | *dump 6 | commit.h 7 | .vscode/ 8 | .wg-obfuscator.conf 9 | .idea/ 10 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "C_Cpp.default.compilerPath": "D:\\Soft\\msys64\\usr\\bin\\gcc.exe", 3 | "C_Cpp.default.includePath": [ 4 | "D:\\Soft\\msys64\\clang64\\include\\**", 5 | "D:\\Soft\\msys64\\usr\\include" 6 | ], 7 | "files.associations": { 8 | "string.h": "c", 9 | "inet.h": "c", 10 | "argp.h": "c" 11 | } 12 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Stage 1: Build 2 | FROM alpine:latest AS build 3 | WORKDIR /src 4 | RUN apk add --no-cache build-base argp-standalone 5 | COPY *.c *.h Makefile ./ 6 | RUN make clean && make CC="gcc -static" LDFLAGS="-largp" 7 | 8 | # Stage 2: Runtime 9 | FROM scratch 10 | WORKDIR /app 11 | COPY --from=build /src/wg-obfuscator ./wg-obfuscator 12 | COPY wg-obfuscator.conf /etc/wg-obfuscator/wg-obfuscator.conf 13 | ENTRYPOINT ["./wg-obfuscator", "-c", "/etc/wg-obfuscator/wg-obfuscator.conf"] 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PROG_NAME = wg-obfuscator 2 | CONFIG = wg-obfuscator.conf 3 | SERVICE_FILE = wg-obfuscator.service 4 | COMMIT := 5 | COMMIT_INFO = commit.h 6 | HEADERS = wg-obfuscator.h 7 | 8 | RELEASE ?= 0 9 | 10 | RM = rm -f 11 | CC = gcc 12 | ifdef DEBUG 13 | CFLAGS = -g -O0 -Wall -DDEBUG 14 | else 15 | CFLAGS = -O2 -Wall 16 | endif 17 | OBJS = wg-obfuscator.o 18 | EXEDIR = . 19 | 20 | LDFLAGS += 21 | 22 | ifeq ($(OS),Windows_NT) 23 | TARGET = $(EXEDIR)/$(PROG_NAME).exe 24 | else 25 | TARGET = $(EXEDIR)/$(PROG_NAME) 26 | endif 27 | 28 | # build on macos(arm) support 29 | IS_MACARM := 0 30 | ifneq ($(OS),Windows_NT) 31 | UNAME_S := $(shell uname -s) 32 | ifeq ($(UNAME_S),Darwin) 33 | UNAME_P := $(shell uname -p) 34 | ifneq ($(filter arm%,$(UNAME_P)),) 35 | CFLAGS += -I$(shell brew --prefix)/include 36 | IS_MACARM = 1 37 | endif 38 | endif 39 | endif 40 | 41 | ifeq ($(OS),Windows_NT) 42 | CFLAGS += -Wno-stringop-truncation 43 | LDFLAGS += -largp 44 | TARGET = $(EXEDIR)/$(PROG_NAME).exe 45 | else 46 | TARGET = $(EXEDIR)/$(PROG_NAME) 47 | # build on macos(arm) support 48 | UNAME_S := $(shell uname -s) 49 | ifeq ($(UNAME_S),Darwin) 50 | LDFLAGS += -largp 51 | ifeq ($(IS_MACARM), 1) 52 | LDFLAGS += -L$(shell brew --prefix)/lib 53 | endif 54 | else 55 | CFLAGS += -Wno-stringop-truncation 56 | endif 57 | endif 58 | 59 | all: $(TARGET) 60 | 61 | $(COMMIT_INFO): 62 | # Try to get commit hash from git 63 | ifeq ($(RELEASE),0) 64 | @COMMIT=$$(git rev-parse --short HEAD 2>/dev/null) ; \ 65 | if [ -n "$$COMMIT" ]; then \ 66 | echo "#define COMMIT \"$$COMMIT\"" > $(COMMIT_INFO) ; \ 67 | else \ 68 | echo > $(COMMIT_INFO) ; \ 69 | fi 70 | else 71 | rm -rf $(COMMIT_INFO) 72 | touch $(COMMIT_INFO) 73 | endif 74 | 75 | clean: 76 | $(RM) *.o $(COMMIT_INFO) 77 | ifeq ($(OS),Windows_NT) 78 | @if [ -f "$(TARGET)" ]; then for f in `cygcheck "$(TARGET)" | grep .dll | grep msys` ; do rm -f $(EXEDIR)/`basename "$$f"` ; done fi 79 | endif 80 | $(RM) $(TARGET) 81 | 82 | $(OBJS): 83 | 84 | %.o : %.c 85 | $(CC) $(CFLAGS) -o $@ -c $< 86 | 87 | $(TARGET): $(COMMIT_INFO) $(OBJS) $(HEADERS) 88 | $(CC) -o $(TARGET) $(OBJS) $(LDFLAGS) 89 | ifeq ($(OS),Windows_NT) 90 | @for f in `cygcheck "$(TARGET)" | grep .dll | grep msys` ; do if [ ! -f "$(EXEDIR)/`basename $$f`" ] ; then cp -vf `cygpath "$$f"` $(EXEDIR)/ ; fi ; done 91 | endif 92 | 93 | install: $(TARGET) 94 | ifeq ($(OS),Windows_NT) 95 | @echo "Windows is not supported for install" 96 | else 97 | install -m 755 $(TARGET) $(DESTDIR)/usr/bin 98 | @if [ ! -f "$(DESTDIR)/etc/$(CONFIG)" ]; then \ 99 | install -m 644 $(CONFIG) $(DESTDIR)/etc; \ 100 | else \ 101 | echo "$(DESTDIR)/etc/$(CONFIG) already exists, skipping"; \ 102 | fi 103 | install -m 644 $(SERVICE_FILE) $(DESTDIR)/etc/systemd/system 104 | systemctl daemon-reload 105 | systemctl enable $(SERVICE_FILE) 106 | systemctl restart $(SERVICE_FILE) 107 | endif 108 | 109 | .PHONY: clean install $(COMMIT_INFO) 110 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WireGuard Obfuscator 2 | 3 | WireGuard Obfuscator is a tool designed to make WireGuard traffic look like random data, making it significantly harder to detect by DPI (Deep Packet Inspection) systems. This can be extremely useful if your ISP or government tries to block or throttle WireGuard traffic. 4 | 5 | - [Feature overview](#feature-overview) 6 | - [Basic Concept](#basic-concept) 7 | - [Configuration](#configuration) 8 | - [Two-Way Mode](#two-way-mode) 9 | - [How to Build and Install](#how-to-build-and-install) 10 | - [Linux](#linux) 11 | - [Windows](#windows) 12 | - [macOS](#macos) 13 | - [Android](#android) 14 | - [Running Docker Container on Linux](#running-docker-container-on-linux) 15 | - [Running Docker Container on MikroTik Routers](#running-docker-container-on-mikrotik-routers-routeros-74) 16 | - [Caveats and Recommendations](#caveats-and-recommendations) 17 | - [Credits](#credits) 18 | - [Support the Developer and the Project](#support-the-developer-and-the-project) 19 | 20 | 21 | ## Feature overview 22 | 23 | What started as a quick-and-dirty solution just for personal use has grown into a fully-featured project with the following capabilities: 24 | 25 | * **WireGuard-specific design** 26 | This obfuscator is purpose-built for the WireGuard protocol: it recognizes WireGuard packet types and actively monitors handshake success to ensure reliable operation. 27 | * **Key-based obfuscation** 28 | Obfuscation is performed using a user-specified key. While this arguably makes it more like encryption, keep in mind that strong cryptography is not the goal here—WireGuard itself already handles secure encryption. The key's purpose is to make your traffic look unrecognizable, not unbreakable. 29 | * **Symmetric operation** 30 | You can use the obfuscator on both ends of a WireGuard tunnel, or just one—it will figure out automatically whether packets are obfuscated or not, and will always do the right thing. 31 | * **Packet salting** 32 | Each packet gets a random salt, ensuring that even identical packets always look different after obfuscation. This further frustrates signature-based DPI systems. 33 | * **Handshake randomization** 34 | WireGuard handshake packets are padded with random dummy data, so their obfuscated sizes vary widely. This makes it difficult for anyone monitoring traffic to spot patterns or reliably fingerprint handshakes. Even data packets can have their size increased by a few random bytes too. 35 | * **Very fast and efficient** 36 | The obfuscator is designed to be extremely fast, with minimal CPU and memory overhead. It can handle high traffic loads without noticeable performance degradation. 37 | * **Built-in NAT table** 38 | The application features a high-performance, built-in NAT table. This allows hundreds of clients to connect to a single server port while preserving fast, efficient forwarding. Each client’s address and port are mapped to a unique server-side port. 39 | * **Static (manual) bindings / two-way mode** 40 | You can manually define static NAT table entries, which enables "two-way" mode—allowing both WireGuard peers to initiate connections toward each other through the obfuscator. 41 | * **Multi-section configuration files** 42 | Supports both simple configuration files and command-line arguments for quick one-off runs or advanced automation. You can define multiple obfuscator instances within a single configuration file. 43 | * **Detailed and customizable logging** 44 | Verbosity levels range from errors-only to full packet-level traces for advanced troubleshooting and analytics. 45 | * **Cross-platform and lightweight** 46 | Available as binaries for Linux, Windows, and Mac, as well as tiny multi-arch Docker images (amd64, arm64, arm/v7, arm/v6, 386, ppc64le, s390x). The images are extremely small and suitable even for embedded routers like MikroTik. 47 | * **Very low dependency footprint** 48 | No huge libraries or frameworks. 49 | * **Android client coming soon?** 50 | A native Android version of the obfuscator is planned, allowing you to obfuscate WireGuard traffic directly on Android devices (including phones, tablets, or Android TVs). This will make it possible to use the obfuscator together with mobile WireGuard clients or WireGuard running on smart TVs. 51 | 52 | 53 | ## Basic Concept 54 | 55 | ``` 56 | ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ ┌────────────────┐ 57 | | WireGuard peer | | WireGuard peer | | WireGuard peer | | WireGuard peer | 58 | └───────▲────────┘ └───────▲────────┘ └────────▲───────┘ └───────▲────────┘ 59 | | | └──────┐ ┌─────┘ 60 | ┌───────▼────────┐ ┌───────▼────────┐ ┌─────▼────▼─────┐ 61 | | Obfuscator | | Obfuscator | | Obfuscator | 62 | └───────▲────────┘ └───────▲────────┘ └────────▲───────┘ 63 | | | | 64 | ┌───────▼──────────────────▼─────────────────────────────▼────────────────┐ 65 | | | | Internet | | 66 | └───────▲──────────────────▲─────────────────────────────▲────────────────┘ 67 | | | | 68 | | ┌───────▼────────┐ | 69 | └─────────>| Obfuscator |<───────────────────┘ 70 | └───────▲────────┘ 71 | | 72 | ┌───────────▼────────────┐ 73 | | WireGuard server peer | 74 | └────────────────────────┘ 75 | ``` 76 | 77 | In most cases, the obfuscator is used in a scenario where there is a clear separation between a server (with a static or public IP address) and clients (which may be behind NAT). We’ll focus on this setup here. 78 | If **both** ends have public IPs and can initiate connections to each other, see the section on ["Two-way mode"](#two-way-mode) below. 79 | 80 | Usually, the obfuscator is installed on the same device as your WireGuard client or server. In this setup, you configure WireGuard to connect to the obfuscator’s address and port (typically `127.0.0.1` and a custom port), while the *real* remote address and port are specified in the obfuscator’s configuration. 81 | 82 | For example, a standard WireGuard client configuration: 83 | 84 | ``` 85 | [Peer] 86 | Endpoint = example.com:19999 87 | ``` 88 | 89 | would become: 90 | 91 | ``` 92 | [Peer] 93 | Endpoint = 127.0.0.1:3333 94 | ``` 95 | 96 | And the obfuscator would be launched/configured like this: 97 | 98 | ``` 99 | source-lport = 3333 100 | target = example.com:19999 101 | ``` 102 | 103 | On the **server** side, the WireGuard config: 104 | 105 | ``` 106 | [Interface] 107 | ListenPort = 19999 108 | ``` 109 | 110 | would be changed to: 111 | 112 | ``` 113 | [Interface] 114 | ListenPort = 5555 115 | ``` 116 | 117 | With the obfuscator running with this config: 118 | 119 | ``` 120 | source-lport = 19999 121 | target = 127.0.0.1:5555 122 | ``` 123 | 124 | The application maintains its own internal address mapping table, so a single server-side obfuscator can handle connections from multiple clients—each with their own obfuscator instance—using just one server port. Likewise, on the client side, a single obfuscator can support connections to multiple peers (though this is rarely needed in typical use). 125 | 126 | The obfuscator automatically determines the direction (obfuscation or deobfuscation) for each packet, so the configuration files on both the client and server sides look nearly identical. The only thing that matters is that both sides use the same key. 127 | 128 | **The key** is simply a text string. Cryptographic strength is not required here—feel free to use any common word or phrase (longer is better, but even four or five characters is usually enough in practice). The main thing is that your key is not the same as everyone else’s! 129 | 130 | 131 | ## Configuration 132 | 133 | You can pass parameters to the obfuscator using a configuration file or command line arguments. Available parameters are: 134 | * `source-if` 135 | Source interface to listen on. Optional, default is `0.0.0.0`, e.g. all interfaces. Can be used to listen only on a specific interface. 136 | * `source-lport` 137 | Source port to listen. Source client should connect to this port. Required. 138 | * `target` 139 | Target address and port in `address:port` format. Obfuscated/deobfuscated data will be forwarded to this address. Required. 140 | * `key` 141 | Obfuscation key. Just string. Longer - better. Required, must be 1-255 characters long. 142 | * `static-bindings` 143 | Comma-separated static bindings for two-way mode as :: 144 | (see ["Two-way mode"](#two-way-mode)) 145 | * `verbose` 146 | Verbosity level, 0-4. Optional, default is 2. 147 | 0 - ERRORS (critical errors only) 148 | 1 - WARNINGS (important messages: startup and shutdown messages) 149 | 2 - INFO (informational messages: status messages, connection established, etc.) 150 | 3 - DEBUG (detailed debug messages) 151 | 4 - TRACE (very detailed debug messages, including packet dumps) 152 | 153 | You can use configuration file with those parameters in `key=value` format. For example: 154 | ``` 155 | # Instance name 156 | [main] 157 | 158 | source-lport = 13255 159 | target = 10.13.1.100:13255 160 | key = love 161 | static-bindings = 1.2.3.4:12883:6670, 5.6.7.8:12083:6679 162 | verbose = 2 163 | 164 | # You can specify multiple instances 165 | [second_server] 166 | source-if = 0.0.0.0 167 | source-lport = 13255 168 | target = 10.13.1.100:13255 169 | key = hate 170 | verbose = 4 171 | ``` 172 | 173 | As you can see, the configuration file allows you to define settings for multiple obfuscator instances. This makes it easy to run several copies of the obfuscator with different settings, all from a single configuration file. 174 | 175 | You can pass the configuration file to the obfuscator using `--config` argument. For example: 176 | ```bash 177 | wg-obfuscator --config /etc/wg-obfuscator.conf 178 | ``` 179 | 180 | You can also pass parameters using command line arguments. For example: 181 | ```bash 182 | wg-obfuscator --source-lport 13255 --target 10.13.1.100:13255 --key test 183 | ``` 184 | Type `wg-obfuscator.exe --help` for more information. 185 | 186 | Don't forget to check the [Caveats and Recommendations](#caveats-and-recommendations) section below for important notes on configuration and usage. 187 | 188 | 189 | ### Two-Way Mode 190 | (for advanced users) 191 | 192 | In some setups, both WireGuard peers have public IP addresses and can each initiate connections. In this scenario, you need both ends to accept and send connections through the obfuscator. This is where **two-way mode** comes in. 193 | 194 | #### What Are Static Bindings? 195 | 196 | A **static binding** tells the obfuscator, right from startup, which peer IPs and ports should be mapped to which local ports. This allows the obfuscator to know exactly how to route packets from the server to the correct local WireGuard instance—**even if that peer hasn’t sent any packets yet.** 197 | Without static bindings, the obfuscator only learns how to forward packets after seeing traffic from a client. 198 | 199 | #### Example: Two-way WireGuard with Obfuscation 200 | 201 | Suppose you have two peers: 202 | 203 | * **Peer A**: Public IP `1.2.3.4`, runs WireGuard locally on port `5555`, the obfuscator listens on port `15555` externally and on port `7777` internally 204 | * **Peer B**: Public IP `5.6.7.8`, runs WireGuard locally on port `6666`, the obfuscator listens on port `16666` externally and on port `8888` internally 205 | 206 | **Peer A WireGuard config** (`1.2.3.4`): 207 | 208 | ``` 209 | [Interface] 210 | PrivateKey = 211 | ListenPort = 5555 212 | 213 | [Peer] 214 | PublicKey = 215 | Endpoint = 127.0.0.1:15555 216 | ``` 217 | 218 | **Peer A Obfuscator config** (`1.2.3.4`): 219 | 220 | ``` 221 | source-lport = 15555 222 | target = 5.6.7.8:16666 223 | static-bindings = 127.0.0.1:5555:7777 224 | key = your_secret_key 225 | ``` 226 | 227 | **Peer B WireGuard config** (`5.6.7.8`): 228 | 229 | ``` 230 | [Interface] 231 | PrivateKey = 232 | ListenPort = 6666 233 | 234 | [Peer] 235 | PublicKey = 236 | Endpoint = 127.0.0.1:8888 237 | ``` 238 | 239 | **Peer B Obfuscator config** (`5.6.7.8`): 240 | 241 | ``` 242 | source-lport = 16666 243 | target = 127.0.0.1:6666 244 | static-bindings = 1.2.3.4:7777:8888 245 | key = your_secret_key 246 | ``` 247 | 248 | In this example the line: 249 | 250 | ``` 251 | static-bindings = 1.2.3.4:7777:8888 252 | ``` 253 | 254 | means: 255 | 256 | * **If the obfuscator receives a UDP packet from `1.2.3.4`, where the sender’s *source port* is `7777`,** 257 | * it will associate that remote peer with a local UDP socket that uses port `8888` as its *source port* when sending packets out. 258 | 259 | So when the obfuscator sends packets to the peer's `target`, it does so from port `8888`. 260 | This allows the remote obfuscator to recognize which static mapping (and which local WireGuard instance or socket) should handle returning packets, based on the source port used by the sender. 261 | 262 | > **Note:** 263 | > In UDP, the source port matters for this association. The packet will always be sent *to* the port specified in `target`, but the source port (the third value in the static binding) tells the obfuscator which local port to use for sending. 264 | 265 | ``` 266 | ┌───────────────────────────┐ ┌───────────────────────────┐ 267 | │ Peer A (1.2.3.4) │ │ Peer B (5.6.7.8) │ 268 | │ ┌─────────────┐ │ │ ┌─────────────┐ │ 269 | │ │ WireGuard │ │ │ │ WireGuard │ │ 270 | │ │ (5555) │ │ │ │ (6666) │ │ 271 | │ └─────▲───────┘ │ │ └─────▲───────┘ │ 272 | │ │ │ │ │ │ 273 | │ ┌─────▼───────┐ │ │ ┌─────▼───────┐ │ 274 | │ │ Obfuscator │ │ │ │ Obfuscator │ │ 275 | │ │ │ │ │ │ │ │ 276 | │ │ │ │ │ │ │ │ 277 | │ │ source-lport│ │ │ │ source-lport│ │ 278 | │ │ 15555 │ │ │ │ 16666 │ │ 279 | │ │ │ │ │ │ │ │ 280 | │ │ static-bind.│ │ │ │ static-bind.│ │ 281 | │ │ 127.0.0.1:5555:7777 │ │ │ 1.2.3.4:7777:8888 │ 282 | │ └─────▼───────┘ │ │ └─────▼───────┘ │ 283 | │ │ │ │ │ │ 284 | └─────────┼─────────────────┘ └─────────┼─────────────────┘ 285 | │ │ 286 | │ UDP/obfuscated traffic │ 287 | │ │ 288 | (source:7777, dest:16666) (source:8888, dest:15555) 289 | │<--------------------------------------->│ 290 | ``` 291 | 292 | **Legend:** 293 | 294 | * When Peer A’s obfuscator sends a packet to Peer B’s obfuscator: 295 | * The packet is sent *from* port `7777` (as set in static-bindings on A) *to* port `16666` on Peer B. 296 | * When Peer B’s obfuscator replies: 297 | * The packet is sent *from* port `8888` (as set in static-bindings on B) *to* port `15555` on Peer A. 298 | * The static binding line: 299 | * `1.2.3.4:7777:8888` (on B) means: "packets *from* 1.2.3.4, *source port* 7777 → will be mapped to local UDP socket using *source port* 8888 for outbound packets". 300 | 301 | **Step-by-step: How a Packet Travels in Two-way Mode** 302 | 303 | **1. Peer A sends a packet:** 304 | 305 | * WireGuard on Peer A creates a packet. 306 | * The packet goes to A’s local obfuscator (`127.0.0.1:15555`). 307 | * The obfuscator sends the packet to Peer B’s obfuscator (`5.6.7.8:16666`), using `7777` as the source port. 308 | * On the network, the packet is: 309 | `source: 1.2.3.4:7777 → destination: 5.6.7.8:16666` 310 | 311 | **2. Peer B receives the packet:** 312 | 313 | * Peer B’s obfuscator sees a packet coming from `1.2.3.4:7777`. 314 | * It checks its static bindings and finds `1.2.3.4:7777:8888`, so it knows to associate this traffic with its local UDP socket bound to port `8888`. 315 | * The obfuscator passes the packet to local WireGuard on port `6666`. 316 | 317 | **3. Peer B responds:** 318 | 319 | * WireGuard on B sends a response to A, which is routed to B’s obfuscator (`127.0.0.1:8888`). 320 | * The obfuscator sends the packet to Peer A’s obfuscator (`1.2.3.4:15555`), using `8888` as the source port. 321 | * On the network: 322 | `source: 5.6.7.8:8888 → destination: 1.2.3.4:15555` 323 | 324 | **4. Peer A receives the response:** 325 | 326 | * Peer A’s obfuscator sees a packet coming from `5.6.7.8:8888`. 327 | * It checks its static bindings (`127.0.0.1:5555:7777`) and knows to deliver the packet to the local WireGuard instance on port `5555`. 328 | 329 | Packets sent from Peer B to Peer A follow the exact same steps, but in the reverse order. 330 | 331 | #### Summary 332 | 333 | With static bindings, each obfuscator knows in advance how to forward packets between the server and local WireGuard, regardless of which peer initiates the connection. This enables fully bidirectional, peer-to-peer WireGuard tunnels—*even if both sides can initiate connections at any time.* 334 | 335 | 336 | ## How to build and install 337 | 338 | You can always find the latest release (source code and ready-to-use binaries for Linux, Windows, and macOS) at: 339 | https://github.com/ClusterM/wg-obfuscator/releases 340 | 341 | ### Linux 342 | On Linux, the obfuscator can be installed as a systemd service for automatic startup and management. 343 | 344 | To build and install on Linux, simply run: 345 | ```sh 346 | make 347 | sudo make install 348 | ``` 349 | 350 | This will install the obfuscator as a systemd service. 351 | You can start it with: 352 | ```sh 353 | sudo systemctl start wg-obfuscator 354 | ``` 355 | 356 | The configuration file is located at: 357 | `/etc/wg-obfuscator.conf` 358 | 359 | ### Windows 360 | To build on Windows, you need [MSYS2](https://www.msys2.org/) and the following packages: 361 | * `base-devel` 362 | * `gcc` 363 | * `git` 364 | * `libargp-devel` 365 | 366 | Install the required packages, then run: 367 | ```sh 368 | make 369 | ``` 370 | > **Note:** On Windows, the obfuscator is only available as a command-line application. Run it from the MSYS2 terminal and manage startup manually. 371 | 372 | ### macOS 373 | On macOS, install the `argp-standalone` package via Homebrew: 374 | ```sh 375 | brew install argp-standalone 376 | ``` 377 | 378 | Then build as usual: 379 | ```sh 380 | make 381 | ``` 382 | > **Note:** On macOS, the obfuscator is only available as a command-line application. You need to run it from the terminal and manage startup yourself. 383 | 384 | ### Android 385 | Android support is planned. 386 | 387 | ### Running Docker Container on Linux 388 | 389 | WireGuard Obfuscator is available as a multi-architecture Docker image: 390 | **[clustermeerkat/wg-obfuscator on Docker Hub](https://hub.docker.com/repository/docker/clustermeerkat/wg-obfuscator)** 391 | 392 | **Supported tags:** 393 | 394 | * **`latest`** — always points to the most recent stable release. 395 | * **`nightly`** — built automatically from the current main branch; may be unstable. Use only for testing new features. 396 | * **Version tags** (e.g. `1.0`, `1.1`) — for specific releases. 397 | 398 | **Architectures available:** 399 | 400 | * `linux/amd64` 401 | * `linux/arm64` 402 | * `linux/arm/v7` 403 | * `linux/arm/v6` 404 | * `linux/386` 405 | * `linux/ppc64le` 406 | * `linux/s390x` 407 | 408 | #### Example: docker-compose.yml 409 | 410 | > **Note:** 411 | > Make sure to match the exposed port (`13255` in the example below) with the `source-lport` value in your configuration file. 412 | 413 | ```yaml 414 | version: '3.8' 415 | 416 | services: 417 | wg-obfuscator: 418 | image: clustermeerkat/wg-obfuscator:latest 419 | volumes: 420 | - ./.wg-obfuscator.conf:/etc/wg-obfuscator/wg-obfuscator.conf 421 | ports: 422 | - "13255:13255/udp" 423 | container_name: wg-obfuscator-container 424 | restart: unless-stopped 425 | ``` 426 | 427 | * **`image`** can be changed to use a specific tag (e.g., `clustermeerkat/wg-obfuscator:1.1`). 428 | * Place your config as `.wg-obfuscator.conf` in the same directory as `docker-compose.yml`, or adjust the volume path. 429 | * **Port mapping** (`13255:13255/udp`) must correspond to your obfuscator’s listen port. 430 | 431 | #### Running manually 432 | 433 | You can also run the container directly: 434 | 435 | ```sh 436 | docker run -d \ 437 | --name wg-obfuscator \ 438 | -v $PWD/.wg-obfuscator.conf:/etc/wg-obfuscator/wg-obfuscator.conf \ 439 | -p 13255:13255/udp \ 440 | clustermeerkat/wg-obfuscator:latest 441 | ``` 442 | 443 | ### Running Docker Container on MikroTik Routers (RouterOS 7.4+) 444 | 445 | WireGuard Obfuscator can run as a container on MikroTik devices with **RouterOS 7.4+** (ARM64/x86\_64). 446 | 447 | #### Quick Setup 448 | 449 | ##### 1. Install the `container` package 450 | 451 | * Download the latest **Extra Packages** for your RouterOS version and platform from [mikrotik.com/download](https://mikrotik.com/download) 452 | * Extract and upload `container-*.npk` to the router 453 | * Reboot the router 454 | 455 | ##### 2. Enable container device mode (**only required once!**) 456 | 457 | ```shell 458 | /system/device-mode/update container=yes 459 | ``` 460 | 461 | * Confirm when prompted: 462 | – For most models, press the physical reset button 463 | – On x86, do a full power-off (cold reboot) 464 | 465 | ##### 3. Configure container registry (one time) 466 | 467 | ```shell 468 | /container/config/set registry-url=https://registry-1.docker.io tmpdir=temp 469 | ``` 470 | 471 | ##### 4. Create a veth interface for container networking 472 | 473 | ```shell 474 | /interface/veth/add name=veth-wg-ob address=192.168.100.2/24 gateway=192.168.100.1 475 | ``` 476 | 477 | ##### 5. Create and mount a config directory 478 | 479 | ```shell 480 | /container/mounts/add dst=/etc/wg-obfuscator name=wg-obfuscator-config src=/wg-obfuscator 481 | ``` 482 | 483 | ##### 6. Add and start the container 484 | 485 | ```shell 486 | /container/add \ 487 | interface=veth-wg-ob \ 488 | logging=yes \ 489 | mounts=wg-obfuscator-config \ 490 | name=wg-obfuscator \ 491 | root-dir=wg-obfuscator-data \ 492 | start-on-boot=yes \ 493 | remote-image=clustermeerkat/wg-obfuscator:latest 494 | ``` 495 | 496 | ##### 7. Edit your config file 497 | 498 | * After the **first launch**, a default example config file will appear at `/wg-obfuscator/wg-obfuscator.conf` on your router. 499 | * **Edit this file** to match your actual WireGuard and obfuscator settings. 500 | You can use WinBox, WebFig, or the `/file edit` command in the MikroTik terminal. 501 | 502 | ##### 8. Forward UDP ports to the container 503 | 504 | ```shell 505 | /ip firewall nat add chain=dstnat action=dst-nat protocol=udp dst-port=13255 to-addresses=192.168.100.2 to-ports=13255 506 | ``` 507 | 508 | * Replace `13255` and the IP as needed for your network. 509 | 510 | ##### 9. Enable container logging (one time) 511 | 512 | ```shell 513 | /system logging add topics=container 514 | ``` 515 | 516 | ##### 10. Restart the container 517 | 518 | ```shell 519 | /container/stop [/container/find where name="wg-obfuscator"] 520 | /container/start [/container/find where name="wg-obfuscator"] 521 | ``` 522 | 523 | ##### 11. Check logs 524 | ```shell 525 | /log print where topics~"container" 526 | ``` 527 | You should see logs indicating the container has started successfully and is ready to process WireGuard traffic. 528 | 529 | **Notes:** 530 | 531 | * `container` package and device-mode are only needed once per router. 532 | * No external disk is required; image is small and uses internal storage. 533 | * See [MikroTik Containers Docs](https://help.mikrotik.com/docs/display/ROS/Containers) for advanced usage. 534 | * Don't forget to change WireGuard's `Endpoint` to point to the obfuscator's IP and port. 535 | * Don't forget about the [Caveats and Recommendations](#caveats-and-recommendations) section below, especially regarding endpoint exclusion and routing loops. 536 | 537 | 538 | ## Caveats and Recommendations 539 | 540 | * **Endpoint Exclusion and Routing Loops:** 541 | WireGuard automatically excludes the server's IP address (as specified in the `Endpoint`) from the `AllowedIPs` list. 542 | If the obfuscator is running on the same machine as your WireGuard client or server, this can lead to a subtle issue: after the handshake, all traffic to the VPN server might get routed *through the VPN tunnel itself* (causing a routing loop or connection loss). 543 | **Solution:** Make sure to manually exclude the real (public) IP address of your VPN server from the `AllowedIPs` list in your WireGuard config. You can use this script: https://colab.research.google.com/drive/1spIsqkB4YOsctmZV83aG1HKISFFxxMCZ 544 | * **PersistentKeepalive:** 545 | To maintain a stable connection—especially when clients are behind NAT or firewalls—it is recommended to use WireGuard’s `PersistentKeepalive` option. A value of `25` or `60` seconds is generally sufficient. 546 | * **Initial Handshake Requirement:** 547 | After starting the obfuscator, no traffic will flow between WireGuard peers until a successful handshake has been established. 548 | If you restart the obfuscator *without* restarting WireGuard itself, it may take some time for the peers to re-establish the handshake and resume traffic. You can speed this up by briefly toggling the WireGuard interface. 549 | * **IPv6 Support:** 550 | The obfuscator does not currently support IPv6. It only works with IPv4 addresses and ports. 551 | 552 | 553 | ## Credits 554 | * [WireGuard](https://www.wireguard.com/) - the VPN protocol this tool is designed to obfuscate. 555 | * [uthash](https://troydhanson.github.io/uthash/) - a great C library for hash tables, used for the NAT table. 556 | 557 | 558 | ## Support the Developer and the Project 559 | 560 | * [GitHub Sponsors](https://github.com/sponsors/ClusterM) 561 | * [Buy Me A Coffee](https://www.buymeacoffee.com/cluster) 562 | * [Donation Alerts](https://www.donationalerts.com/r/clustermeerkat) 563 | * [Boosty](https://boosty.to/cluster) 564 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | wg-obfuscator: 5 | build: 6 | context: . 7 | dockerfile: Dockerfile 8 | volumes: 9 | - ./.wg-obfuscator.conf:/etc/wg-obfuscator/wg-obfuscator.conf 10 | ports: 11 | - "13255:13255/udp" 12 | container_name: wg-obfuscator-container 13 | restart: unless-stopped 14 | -------------------------------------------------------------------------------- /uthash.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2003-2025, Troy D. Hanson https://troydhanson.github.io/uthash/ 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | 11 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 12 | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 13 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 14 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 15 | OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 16 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 17 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 18 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 19 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 20 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | */ 23 | 24 | #ifndef UTHASH_H 25 | #define UTHASH_H 26 | 27 | #define UTHASH_VERSION 2.3.0 28 | 29 | #include /* memcmp, memset, strlen */ 30 | #include /* ptrdiff_t */ 31 | #include /* exit */ 32 | 33 | #if defined(HASH_NO_STDINT) && HASH_NO_STDINT 34 | /* The user doesn't have , and must figure out their own way 35 | to provide definitions for uint8_t and uint32_t. */ 36 | #else 37 | #include /* uint8_t, uint32_t */ 38 | #endif 39 | 40 | /* These macros use decltype or the earlier __typeof GNU extension. 41 | As decltype is only available in newer compilers (VS2010 or gcc 4.3+ 42 | when compiling c++ source) this code uses whatever method is needed 43 | or, for VS2008 where neither is available, uses casting workarounds. */ 44 | #if !defined(DECLTYPE) && !defined(NO_DECLTYPE) 45 | #if defined(_MSC_VER) /* MS compiler */ 46 | #if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ 47 | #define DECLTYPE(x) (decltype(x)) 48 | #else /* VS2008 or older (or VS2010 in C mode) */ 49 | #define NO_DECLTYPE 50 | #endif 51 | #elif defined(__MCST__) /* Elbrus C Compiler */ 52 | #define DECLTYPE(x) (__typeof(x)) 53 | #elif defined(__BORLANDC__) || defined(__ICCARM__) || defined(__LCC__) || defined(__WATCOMC__) 54 | #define NO_DECLTYPE 55 | #else /* GNU, Sun and other compilers */ 56 | #define DECLTYPE(x) (__typeof(x)) 57 | #endif 58 | #endif 59 | 60 | #ifdef NO_DECLTYPE 61 | #define DECLTYPE(x) 62 | #define DECLTYPE_ASSIGN(dst,src) \ 63 | do { \ 64 | char **_da_dst = (char**)(&(dst)); \ 65 | *_da_dst = (char*)(src); \ 66 | } while (0) 67 | #else 68 | #define DECLTYPE_ASSIGN(dst,src) \ 69 | do { \ 70 | (dst) = DECLTYPE(dst)(src); \ 71 | } while (0) 72 | #endif 73 | 74 | #ifndef uthash_malloc 75 | #define uthash_malloc(sz) malloc(sz) /* malloc fcn */ 76 | #endif 77 | #ifndef uthash_free 78 | #define uthash_free(ptr,sz) free(ptr) /* free fcn */ 79 | #endif 80 | #ifndef uthash_bzero 81 | #define uthash_bzero(a,n) memset(a,'\0',n) 82 | #endif 83 | #ifndef uthash_strlen 84 | #define uthash_strlen(s) strlen(s) 85 | #endif 86 | 87 | #ifndef HASH_FUNCTION 88 | #define HASH_FUNCTION(keyptr,keylen,hashv) HASH_JEN(keyptr, keylen, hashv) 89 | #endif 90 | 91 | #ifndef HASH_KEYCMP 92 | #define HASH_KEYCMP(a,b,n) memcmp(a,b,n) 93 | #endif 94 | 95 | #ifndef uthash_noexpand_fyi 96 | #define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ 97 | #endif 98 | #ifndef uthash_expand_fyi 99 | #define uthash_expand_fyi(tbl) /* can be defined to log expands */ 100 | #endif 101 | 102 | #ifndef HASH_NONFATAL_OOM 103 | #define HASH_NONFATAL_OOM 0 104 | #endif 105 | 106 | #if HASH_NONFATAL_OOM 107 | /* malloc failures can be recovered from */ 108 | 109 | #ifndef uthash_nonfatal_oom 110 | #define uthash_nonfatal_oom(obj) do {} while (0) /* non-fatal OOM error */ 111 | #endif 112 | 113 | #define HASH_RECORD_OOM(oomed) do { (oomed) = 1; } while (0) 114 | #define IF_HASH_NONFATAL_OOM(x) x 115 | 116 | #else 117 | /* malloc failures result in lost memory, hash tables are unusable */ 118 | 119 | #ifndef uthash_fatal 120 | #define uthash_fatal(msg) exit(-1) /* fatal OOM error */ 121 | #endif 122 | 123 | #define HASH_RECORD_OOM(oomed) uthash_fatal("out of memory") 124 | #define IF_HASH_NONFATAL_OOM(x) 125 | 126 | #endif 127 | 128 | /* initial number of buckets */ 129 | #define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */ 130 | #define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */ 131 | #define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */ 132 | 133 | /* calculate the element whose hash handle address is hhp */ 134 | #define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) 135 | /* calculate the hash handle from element address elp */ 136 | #define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle*)(void*)(((char*)(elp)) + ((tbl)->hho))) 137 | 138 | #define HASH_ROLLBACK_BKT(hh, head, itemptrhh) \ 139 | do { \ 140 | struct UT_hash_handle *_hd_hh_item = (itemptrhh); \ 141 | unsigned _hd_bkt; \ 142 | HASH_TO_BKT(_hd_hh_item->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ 143 | (head)->hh.tbl->buckets[_hd_bkt].count++; \ 144 | _hd_hh_item->hh_next = NULL; \ 145 | _hd_hh_item->hh_prev = NULL; \ 146 | } while (0) 147 | 148 | #define HASH_VALUE(keyptr,keylen,hashv) \ 149 | do { \ 150 | HASH_FUNCTION(keyptr, keylen, hashv); \ 151 | } while (0) 152 | 153 | #define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out) \ 154 | do { \ 155 | (out) = NULL; \ 156 | if (head) { \ 157 | unsigned _hf_bkt; \ 158 | HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \ 159 | if (HASH_BLOOM_TEST((head)->hh.tbl, hashval)) { \ 160 | HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \ 161 | } \ 162 | } \ 163 | } while (0) 164 | 165 | #define HASH_FIND(hh,head,keyptr,keylen,out) \ 166 | do { \ 167 | (out) = NULL; \ 168 | if (head) { \ 169 | unsigned _hf_hashv; \ 170 | HASH_VALUE(keyptr, keylen, _hf_hashv); \ 171 | HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \ 172 | } \ 173 | } while (0) 174 | 175 | #ifdef HASH_BLOOM 176 | #define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM) 177 | #define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL) 178 | #define HASH_BLOOM_MAKE(tbl,oomed) \ 179 | do { \ 180 | (tbl)->bloom_nbits = HASH_BLOOM; \ 181 | (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ 182 | if (!(tbl)->bloom_bv) { \ 183 | HASH_RECORD_OOM(oomed); \ 184 | } else { \ 185 | uthash_bzero((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ 186 | (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ 187 | } \ 188 | } while (0) 189 | 190 | #define HASH_BLOOM_FREE(tbl) \ 191 | do { \ 192 | uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ 193 | } while (0) 194 | 195 | #define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8U] |= (1U << ((idx)%8U))) 196 | #define HASH_BLOOM_BITTEST(bv,idx) ((bv[(idx)/8U] & (1U << ((idx)%8U))) != 0) 197 | 198 | #define HASH_BLOOM_ADD(tbl,hashv) \ 199 | HASH_BLOOM_BITSET((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) 200 | 201 | #define HASH_BLOOM_TEST(tbl,hashv) \ 202 | HASH_BLOOM_BITTEST((tbl)->bloom_bv, ((hashv) & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) 203 | 204 | #else 205 | #define HASH_BLOOM_MAKE(tbl,oomed) 206 | #define HASH_BLOOM_FREE(tbl) 207 | #define HASH_BLOOM_ADD(tbl,hashv) 208 | #define HASH_BLOOM_TEST(tbl,hashv) 1 209 | #define HASH_BLOOM_BYTELEN 0U 210 | #endif 211 | 212 | #define HASH_MAKE_TABLE(hh,head,oomed) \ 213 | do { \ 214 | (head)->hh.tbl = (UT_hash_table*)uthash_malloc(sizeof(UT_hash_table)); \ 215 | if (!(head)->hh.tbl) { \ 216 | HASH_RECORD_OOM(oomed); \ 217 | } else { \ 218 | uthash_bzero((head)->hh.tbl, sizeof(UT_hash_table)); \ 219 | (head)->hh.tbl->tail = &((head)->hh); \ 220 | (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ 221 | (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ 222 | (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ 223 | (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ 224 | HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ 225 | (head)->hh.tbl->signature = HASH_SIGNATURE; \ 226 | if (!(head)->hh.tbl->buckets) { \ 227 | HASH_RECORD_OOM(oomed); \ 228 | uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ 229 | } else { \ 230 | uthash_bzero((head)->hh.tbl->buckets, \ 231 | HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ 232 | HASH_BLOOM_MAKE((head)->hh.tbl, oomed); \ 233 | IF_HASH_NONFATAL_OOM( \ 234 | if (oomed) { \ 235 | uthash_free((head)->hh.tbl->buckets, \ 236 | HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ 237 | uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ 238 | } \ 239 | ) \ 240 | } \ 241 | } \ 242 | } while (0) 243 | 244 | #define HASH_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \ 245 | do { \ 246 | (replaced) = NULL; \ 247 | HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ 248 | if (replaced) { \ 249 | HASH_DELETE(hh, head, replaced); \ 250 | } \ 251 | HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \ 252 | } while (0) 253 | 254 | #define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \ 255 | do { \ 256 | (replaced) = NULL; \ 257 | HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ 258 | if (replaced) { \ 259 | HASH_DELETE(hh, head, replaced); \ 260 | } \ 261 | HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \ 262 | } while (0) 263 | 264 | #define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ 265 | do { \ 266 | unsigned _hr_hashv; \ 267 | HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ 268 | HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \ 269 | } while (0) 270 | 271 | #define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn) \ 272 | do { \ 273 | unsigned _hr_hashv; \ 274 | HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ 275 | HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \ 276 | } while (0) 277 | 278 | #define HASH_APPEND_LIST(hh, head, add) \ 279 | do { \ 280 | (add)->hh.next = NULL; \ 281 | (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ 282 | (head)->hh.tbl->tail->next = (add); \ 283 | (head)->hh.tbl->tail = &((add)->hh); \ 284 | } while (0) 285 | 286 | #define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \ 287 | do { \ 288 | do { \ 289 | if (cmpfcn(DECLTYPE(head)(_hs_iter), add) > 0) { \ 290 | break; \ 291 | } \ 292 | } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ 293 | } while (0) 294 | 295 | #ifdef NO_DECLTYPE 296 | #undef HASH_AKBI_INNER_LOOP 297 | #define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \ 298 | do { \ 299 | char *_hs_saved_head = (char*)(head); \ 300 | do { \ 301 | DECLTYPE_ASSIGN(head, _hs_iter); \ 302 | if (cmpfcn(head, add) > 0) { \ 303 | DECLTYPE_ASSIGN(head, _hs_saved_head); \ 304 | break; \ 305 | } \ 306 | DECLTYPE_ASSIGN(head, _hs_saved_head); \ 307 | } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ 308 | } while (0) 309 | #endif 310 | 311 | #if HASH_NONFATAL_OOM 312 | 313 | #define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed) \ 314 | do { \ 315 | if (!(oomed)) { \ 316 | unsigned _ha_bkt; \ 317 | (head)->hh.tbl->num_items++; \ 318 | HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ 319 | HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \ 320 | if (oomed) { \ 321 | HASH_ROLLBACK_BKT(hh, head, &(add)->hh); \ 322 | HASH_DELETE_HH(hh, head, &(add)->hh); \ 323 | (add)->hh.tbl = NULL; \ 324 | uthash_nonfatal_oom(add); \ 325 | } else { \ 326 | HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ 327 | HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ 328 | } \ 329 | } else { \ 330 | (add)->hh.tbl = NULL; \ 331 | uthash_nonfatal_oom(add); \ 332 | } \ 333 | } while (0) 334 | 335 | #else 336 | 337 | #define HASH_ADD_TO_TABLE(hh,head,keyptr,keylen_in,hashval,add,oomed) \ 338 | do { \ 339 | unsigned _ha_bkt; \ 340 | (head)->hh.tbl->num_items++; \ 341 | HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ 342 | HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], hh, &(add)->hh, oomed); \ 343 | HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ 344 | HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ 345 | } while (0) 346 | 347 | #endif 348 | 349 | 350 | #define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \ 351 | do { \ 352 | IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; ) \ 353 | (add)->hh.hashv = (hashval); \ 354 | (add)->hh.key = (char*) (keyptr); \ 355 | (add)->hh.keylen = (unsigned) (keylen_in); \ 356 | if (!(head)) { \ 357 | (add)->hh.next = NULL; \ 358 | (add)->hh.prev = NULL; \ 359 | HASH_MAKE_TABLE(hh, add, _ha_oomed); \ 360 | IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { ) \ 361 | (head) = (add); \ 362 | IF_HASH_NONFATAL_OOM( } ) \ 363 | } else { \ 364 | void *_hs_iter = (head); \ 365 | (add)->hh.tbl = (head)->hh.tbl; \ 366 | HASH_AKBI_INNER_LOOP(hh, head, add, cmpfcn); \ 367 | if (_hs_iter) { \ 368 | (add)->hh.next = _hs_iter; \ 369 | if (((add)->hh.prev = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev)) { \ 370 | HH_FROM_ELMT((head)->hh.tbl, (add)->hh.prev)->next = (add); \ 371 | } else { \ 372 | (head) = (add); \ 373 | } \ 374 | HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev = (add); \ 375 | } else { \ 376 | HASH_APPEND_LIST(hh, head, add); \ 377 | } \ 378 | } \ 379 | HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \ 380 | HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE_INORDER"); \ 381 | } while (0) 382 | 383 | #define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn) \ 384 | do { \ 385 | unsigned _hs_hashv; \ 386 | HASH_VALUE(keyptr, keylen_in, _hs_hashv); \ 387 | HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \ 388 | } while (0) 389 | 390 | #define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \ 391 | HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn) 392 | 393 | #define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn) \ 394 | HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn) 395 | 396 | #define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add) \ 397 | do { \ 398 | IF_HASH_NONFATAL_OOM( int _ha_oomed = 0; ) \ 399 | (add)->hh.hashv = (hashval); \ 400 | (add)->hh.key = (const void*) (keyptr); \ 401 | (add)->hh.keylen = (unsigned) (keylen_in); \ 402 | if (!(head)) { \ 403 | (add)->hh.next = NULL; \ 404 | (add)->hh.prev = NULL; \ 405 | HASH_MAKE_TABLE(hh, add, _ha_oomed); \ 406 | IF_HASH_NONFATAL_OOM( if (!_ha_oomed) { ) \ 407 | (head) = (add); \ 408 | IF_HASH_NONFATAL_OOM( } ) \ 409 | } else { \ 410 | (add)->hh.tbl = (head)->hh.tbl; \ 411 | HASH_APPEND_LIST(hh, head, add); \ 412 | } \ 413 | HASH_ADD_TO_TABLE(hh, head, keyptr, keylen_in, hashval, add, _ha_oomed); \ 414 | HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE"); \ 415 | } while (0) 416 | 417 | #define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ 418 | do { \ 419 | unsigned _ha_hashv; \ 420 | HASH_VALUE(keyptr, keylen_in, _ha_hashv); \ 421 | HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \ 422 | } while (0) 423 | 424 | #define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add) \ 425 | HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add) 426 | 427 | #define HASH_ADD(hh,head,fieldname,keylen_in,add) \ 428 | HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add) 429 | 430 | #define HASH_TO_BKT(hashv,num_bkts,bkt) \ 431 | do { \ 432 | bkt = ((hashv) & ((num_bkts) - 1U)); \ 433 | } while (0) 434 | 435 | /* delete "delptr" from the hash table. 436 | * "the usual" patch-up process for the app-order doubly-linked-list. 437 | * The use of _hd_hh_del below deserves special explanation. 438 | * These used to be expressed using (delptr) but that led to a bug 439 | * if someone used the same symbol for the head and deletee, like 440 | * HASH_DELETE(hh,users,users); 441 | * We want that to work, but by changing the head (users) below 442 | * we were forfeiting our ability to further refer to the deletee (users) 443 | * in the patch-up process. Solution: use scratch space to 444 | * copy the deletee pointer, then the latter references are via that 445 | * scratch pointer rather than through the repointed (users) symbol. 446 | */ 447 | #define HASH_DELETE(hh,head,delptr) \ 448 | HASH_DELETE_HH(hh, head, &(delptr)->hh) 449 | 450 | #define HASH_DELETE_HH(hh,head,delptrhh) \ 451 | do { \ 452 | const struct UT_hash_handle *_hd_hh_del = (delptrhh); \ 453 | if ((_hd_hh_del->prev == NULL) && (_hd_hh_del->next == NULL)) { \ 454 | HASH_BLOOM_FREE((head)->hh.tbl); \ 455 | uthash_free((head)->hh.tbl->buckets, \ 456 | (head)->hh.tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ 457 | uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ 458 | (head) = NULL; \ 459 | } else { \ 460 | unsigned _hd_bkt; \ 461 | if (_hd_hh_del == (head)->hh.tbl->tail) { \ 462 | (head)->hh.tbl->tail = HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev); \ 463 | } \ 464 | if (_hd_hh_del->prev != NULL) { \ 465 | HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev)->next = _hd_hh_del->next; \ 466 | } else { \ 467 | DECLTYPE_ASSIGN(head, _hd_hh_del->next); \ 468 | } \ 469 | if (_hd_hh_del->next != NULL) { \ 470 | HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->next)->prev = _hd_hh_del->prev; \ 471 | } \ 472 | HASH_TO_BKT(_hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ 473 | HASH_DEL_IN_BKT((head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ 474 | (head)->hh.tbl->num_items--; \ 475 | } \ 476 | HASH_FSCK(hh, head, "HASH_DELETE_HH"); \ 477 | } while (0) 478 | 479 | /* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ 480 | #define HASH_FIND_STR(head,findstr,out) \ 481 | do { \ 482 | unsigned _uthash_hfstr_keylen = (unsigned)uthash_strlen(findstr); \ 483 | HASH_FIND(hh, head, findstr, _uthash_hfstr_keylen, out); \ 484 | } while (0) 485 | #define HASH_ADD_STR(head,strfield,add) \ 486 | do { \ 487 | unsigned _uthash_hastr_keylen = (unsigned)uthash_strlen((add)->strfield); \ 488 | HASH_ADD(hh, head, strfield[0], _uthash_hastr_keylen, add); \ 489 | } while (0) 490 | #define HASH_REPLACE_STR(head,strfield,add,replaced) \ 491 | do { \ 492 | unsigned _uthash_hrstr_keylen = (unsigned)uthash_strlen((add)->strfield); \ 493 | HASH_REPLACE(hh, head, strfield[0], _uthash_hrstr_keylen, add, replaced); \ 494 | } while (0) 495 | #define HASH_FIND_INT(head,findint,out) \ 496 | HASH_FIND(hh,head,findint,sizeof(int),out) 497 | #define HASH_ADD_INT(head,intfield,add) \ 498 | HASH_ADD(hh,head,intfield,sizeof(int),add) 499 | #define HASH_REPLACE_INT(head,intfield,add,replaced) \ 500 | HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced) 501 | #define HASH_FIND_PTR(head,findptr,out) \ 502 | HASH_FIND(hh,head,findptr,sizeof(void *),out) 503 | #define HASH_ADD_PTR(head,ptrfield,add) \ 504 | HASH_ADD(hh,head,ptrfield,sizeof(void *),add) 505 | #define HASH_REPLACE_PTR(head,ptrfield,add,replaced) \ 506 | HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced) 507 | #define HASH_DEL(head,delptr) \ 508 | HASH_DELETE(hh,head,delptr) 509 | 510 | /* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. 511 | * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. 512 | */ 513 | #ifdef HASH_DEBUG 514 | #include /* fprintf, stderr */ 515 | #define HASH_OOPS(...) do { fprintf(stderr, __VA_ARGS__); exit(-1); } while (0) 516 | #define HASH_FSCK(hh,head,where) \ 517 | do { \ 518 | struct UT_hash_handle *_thh; \ 519 | if (head) { \ 520 | unsigned _bkt_i; \ 521 | unsigned _count = 0; \ 522 | char *_prev; \ 523 | for (_bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; ++_bkt_i) { \ 524 | unsigned _bkt_count = 0; \ 525 | _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ 526 | _prev = NULL; \ 527 | while (_thh) { \ 528 | if (_prev != (char*)(_thh->hh_prev)) { \ 529 | HASH_OOPS("%s: invalid hh_prev %p, actual %p\n", \ 530 | (where), (void*)_thh->hh_prev, (void*)_prev); \ 531 | } \ 532 | _bkt_count++; \ 533 | _prev = (char*)(_thh); \ 534 | _thh = _thh->hh_next; \ 535 | } \ 536 | _count += _bkt_count; \ 537 | if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ 538 | HASH_OOPS("%s: invalid bucket count %u, actual %u\n", \ 539 | (where), (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ 540 | } \ 541 | } \ 542 | if (_count != (head)->hh.tbl->num_items) { \ 543 | HASH_OOPS("%s: invalid hh item count %u, actual %u\n", \ 544 | (where), (head)->hh.tbl->num_items, _count); \ 545 | } \ 546 | _count = 0; \ 547 | _prev = NULL; \ 548 | _thh = &(head)->hh; \ 549 | while (_thh) { \ 550 | _count++; \ 551 | if (_prev != (char*)_thh->prev) { \ 552 | HASH_OOPS("%s: invalid prev %p, actual %p\n", \ 553 | (where), (void*)_thh->prev, (void*)_prev); \ 554 | } \ 555 | _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ 556 | _thh = (_thh->next ? HH_FROM_ELMT((head)->hh.tbl, _thh->next) : NULL); \ 557 | } \ 558 | if (_count != (head)->hh.tbl->num_items) { \ 559 | HASH_OOPS("%s: invalid app item count %u, actual %u\n", \ 560 | (where), (head)->hh.tbl->num_items, _count); \ 561 | } \ 562 | } \ 563 | } while (0) 564 | #else 565 | #define HASH_FSCK(hh,head,where) 566 | #endif 567 | 568 | /* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to 569 | * the descriptor to which this macro is defined for tuning the hash function. 570 | * The app can #include to get the prototype for write(2). */ 571 | #ifdef HASH_EMIT_KEYS 572 | #define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ 573 | do { \ 574 | unsigned _klen = fieldlen; \ 575 | write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ 576 | write(HASH_EMIT_KEYS, keyptr, (unsigned long)fieldlen); \ 577 | } while (0) 578 | #else 579 | #define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) 580 | #endif 581 | 582 | /* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */ 583 | #define HASH_BER(key,keylen,hashv) \ 584 | do { \ 585 | unsigned _hb_keylen = (unsigned)keylen; \ 586 | const unsigned char *_hb_key = (const unsigned char*)(key); \ 587 | (hashv) = 0; \ 588 | while (_hb_keylen-- != 0U) { \ 589 | (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \ 590 | } \ 591 | } while (0) 592 | 593 | 594 | /* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at 595 | * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx 596 | * (archive link: https://archive.is/Ivcan ) 597 | */ 598 | #define HASH_SAX(key,keylen,hashv) \ 599 | do { \ 600 | unsigned _sx_i; \ 601 | const unsigned char *_hs_key = (const unsigned char*)(key); \ 602 | hashv = 0; \ 603 | for (_sx_i=0; _sx_i < keylen; _sx_i++) { \ 604 | hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ 605 | } \ 606 | } while (0) 607 | /* FNV-1a variation */ 608 | #define HASH_FNV(key,keylen,hashv) \ 609 | do { \ 610 | unsigned _fn_i; \ 611 | const unsigned char *_hf_key = (const unsigned char*)(key); \ 612 | (hashv) = 2166136261U; \ 613 | for (_fn_i=0; _fn_i < keylen; _fn_i++) { \ 614 | hashv = hashv ^ _hf_key[_fn_i]; \ 615 | hashv = hashv * 16777619U; \ 616 | } \ 617 | } while (0) 618 | 619 | #define HASH_OAT(key,keylen,hashv) \ 620 | do { \ 621 | unsigned _ho_i; \ 622 | const unsigned char *_ho_key=(const unsigned char*)(key); \ 623 | hashv = 0; \ 624 | for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ 625 | hashv += _ho_key[_ho_i]; \ 626 | hashv += (hashv << 10); \ 627 | hashv ^= (hashv >> 6); \ 628 | } \ 629 | hashv += (hashv << 3); \ 630 | hashv ^= (hashv >> 11); \ 631 | hashv += (hashv << 15); \ 632 | } while (0) 633 | 634 | #define HASH_JEN_MIX(a,b,c) \ 635 | do { \ 636 | a -= b; a -= c; a ^= ( c >> 13 ); \ 637 | b -= c; b -= a; b ^= ( a << 8 ); \ 638 | c -= a; c -= b; c ^= ( b >> 13 ); \ 639 | a -= b; a -= c; a ^= ( c >> 12 ); \ 640 | b -= c; b -= a; b ^= ( a << 16 ); \ 641 | c -= a; c -= b; c ^= ( b >> 5 ); \ 642 | a -= b; a -= c; a ^= ( c >> 3 ); \ 643 | b -= c; b -= a; b ^= ( a << 10 ); \ 644 | c -= a; c -= b; c ^= ( b >> 15 ); \ 645 | } while (0) 646 | 647 | #define HASH_JEN(key,keylen,hashv) \ 648 | do { \ 649 | unsigned _hj_i,_hj_j,_hj_k; \ 650 | unsigned const char *_hj_key=(unsigned const char*)(key); \ 651 | hashv = 0xfeedbeefu; \ 652 | _hj_i = _hj_j = 0x9e3779b9u; \ 653 | _hj_k = (unsigned)(keylen); \ 654 | while (_hj_k >= 12U) { \ 655 | _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ 656 | + ( (unsigned)_hj_key[2] << 16 ) \ 657 | + ( (unsigned)_hj_key[3] << 24 ) ); \ 658 | _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ 659 | + ( (unsigned)_hj_key[6] << 16 ) \ 660 | + ( (unsigned)_hj_key[7] << 24 ) ); \ 661 | hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ 662 | + ( (unsigned)_hj_key[10] << 16 ) \ 663 | + ( (unsigned)_hj_key[11] << 24 ) ); \ 664 | \ 665 | HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ 666 | \ 667 | _hj_key += 12; \ 668 | _hj_k -= 12U; \ 669 | } \ 670 | hashv += (unsigned)(keylen); \ 671 | switch ( _hj_k ) { \ 672 | case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \ 673 | case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \ 674 | case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \ 675 | case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \ 676 | case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \ 677 | case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \ 678 | case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \ 679 | case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \ 680 | case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \ 681 | case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \ 682 | case 1: _hj_i += _hj_key[0]; /* FALLTHROUGH */ \ 683 | default: ; \ 684 | } \ 685 | HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ 686 | } while (0) 687 | 688 | /* The Paul Hsieh hash function */ 689 | #undef get16bits 690 | #if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ 691 | || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) 692 | #define get16bits(d) (*((const uint16_t *) (d))) 693 | #endif 694 | 695 | #if !defined (get16bits) 696 | #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ 697 | +(uint32_t)(((const uint8_t *)(d))[0]) ) 698 | #endif 699 | #define HASH_SFH(key,keylen,hashv) \ 700 | do { \ 701 | unsigned const char *_sfh_key=(unsigned const char*)(key); \ 702 | uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \ 703 | \ 704 | unsigned _sfh_rem = _sfh_len & 3U; \ 705 | _sfh_len >>= 2; \ 706 | hashv = 0xcafebabeu; \ 707 | \ 708 | /* Main loop */ \ 709 | for (;_sfh_len > 0U; _sfh_len--) { \ 710 | hashv += get16bits (_sfh_key); \ 711 | _sfh_tmp = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv; \ 712 | hashv = (hashv << 16) ^ _sfh_tmp; \ 713 | _sfh_key += 2U*sizeof (uint16_t); \ 714 | hashv += hashv >> 11; \ 715 | } \ 716 | \ 717 | /* Handle end cases */ \ 718 | switch (_sfh_rem) { \ 719 | case 3: hashv += get16bits (_sfh_key); \ 720 | hashv ^= hashv << 16; \ 721 | hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)]) << 18; \ 722 | hashv += hashv >> 11; \ 723 | break; \ 724 | case 2: hashv += get16bits (_sfh_key); \ 725 | hashv ^= hashv << 11; \ 726 | hashv += hashv >> 17; \ 727 | break; \ 728 | case 1: hashv += *_sfh_key; \ 729 | hashv ^= hashv << 10; \ 730 | hashv += hashv >> 1; \ 731 | break; \ 732 | default: ; \ 733 | } \ 734 | \ 735 | /* Force "avalanching" of final 127 bits */ \ 736 | hashv ^= hashv << 3; \ 737 | hashv += hashv >> 5; \ 738 | hashv ^= hashv << 4; \ 739 | hashv += hashv >> 17; \ 740 | hashv ^= hashv << 25; \ 741 | hashv += hashv >> 6; \ 742 | } while (0) 743 | 744 | /* iterate over items in a known bucket to find desired item */ 745 | #define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out) \ 746 | do { \ 747 | if ((head).hh_head != NULL) { \ 748 | DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \ 749 | } else { \ 750 | (out) = NULL; \ 751 | } \ 752 | while ((out) != NULL) { \ 753 | if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \ 754 | if (HASH_KEYCMP((out)->hh.key, keyptr, keylen_in) == 0) { \ 755 | break; \ 756 | } \ 757 | } \ 758 | if ((out)->hh.hh_next != NULL) { \ 759 | DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (out)->hh.hh_next)); \ 760 | } else { \ 761 | (out) = NULL; \ 762 | } \ 763 | } \ 764 | } while (0) 765 | 766 | /* add an item to a bucket */ 767 | #define HASH_ADD_TO_BKT(head,hh,addhh,oomed) \ 768 | do { \ 769 | UT_hash_bucket *_ha_head = &(head); \ 770 | _ha_head->count++; \ 771 | (addhh)->hh_next = _ha_head->hh_head; \ 772 | (addhh)->hh_prev = NULL; \ 773 | if (_ha_head->hh_head != NULL) { \ 774 | _ha_head->hh_head->hh_prev = (addhh); \ 775 | } \ 776 | _ha_head->hh_head = (addhh); \ 777 | if ((_ha_head->count >= ((_ha_head->expand_mult + 1U) * HASH_BKT_CAPACITY_THRESH)) \ 778 | && !(addhh)->tbl->noexpand) { \ 779 | HASH_EXPAND_BUCKETS(addhh,(addhh)->tbl, oomed); \ 780 | IF_HASH_NONFATAL_OOM( \ 781 | if (oomed) { \ 782 | HASH_DEL_IN_BKT(head,addhh); \ 783 | } \ 784 | ) \ 785 | } \ 786 | } while (0) 787 | 788 | /* remove an item from a given bucket */ 789 | #define HASH_DEL_IN_BKT(head,delhh) \ 790 | do { \ 791 | UT_hash_bucket *_hd_head = &(head); \ 792 | _hd_head->count--; \ 793 | if (_hd_head->hh_head == (delhh)) { \ 794 | _hd_head->hh_head = (delhh)->hh_next; \ 795 | } \ 796 | if ((delhh)->hh_prev) { \ 797 | (delhh)->hh_prev->hh_next = (delhh)->hh_next; \ 798 | } \ 799 | if ((delhh)->hh_next) { \ 800 | (delhh)->hh_next->hh_prev = (delhh)->hh_prev; \ 801 | } \ 802 | } while (0) 803 | 804 | /* Bucket expansion has the effect of doubling the number of buckets 805 | * and redistributing the items into the new buckets. Ideally the 806 | * items will distribute more or less evenly into the new buckets 807 | * (the extent to which this is true is a measure of the quality of 808 | * the hash function as it applies to the key domain). 809 | * 810 | * With the items distributed into more buckets, the chain length 811 | * (item count) in each bucket is reduced. Thus by expanding buckets 812 | * the hash keeps a bound on the chain length. This bounded chain 813 | * length is the essence of how a hash provides constant time lookup. 814 | * 815 | * The calculation of tbl->ideal_chain_maxlen below deserves some 816 | * explanation. First, keep in mind that we're calculating the ideal 817 | * maximum chain length based on the *new* (doubled) bucket count. 818 | * In fractions this is just n/b (n=number of items,b=new num buckets). 819 | * Since the ideal chain length is an integer, we want to calculate 820 | * ceil(n/b). We don't depend on floating point arithmetic in this 821 | * hash, so to calculate ceil(n/b) with integers we could write 822 | * 823 | * ceil(n/b) = (n/b) + ((n%b)?1:0) 824 | * 825 | * and in fact a previous version of this hash did just that. 826 | * But now we have improved things a bit by recognizing that b is 827 | * always a power of two. We keep its base 2 log handy (call it lb), 828 | * so now we can write this with a bit shift and logical AND: 829 | * 830 | * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) 831 | * 832 | */ 833 | #define HASH_EXPAND_BUCKETS(hh,tbl,oomed) \ 834 | do { \ 835 | unsigned _he_bkt; \ 836 | unsigned _he_bkt_i; \ 837 | struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ 838 | UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ 839 | _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ 840 | sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U); \ 841 | if (!_he_new_buckets) { \ 842 | HASH_RECORD_OOM(oomed); \ 843 | } else { \ 844 | uthash_bzero(_he_new_buckets, \ 845 | sizeof(struct UT_hash_bucket) * (tbl)->num_buckets * 2U); \ 846 | (tbl)->ideal_chain_maxlen = \ 847 | ((tbl)->num_items >> ((tbl)->log2_num_buckets+1U)) + \ 848 | ((((tbl)->num_items & (((tbl)->num_buckets*2U)-1U)) != 0U) ? 1U : 0U); \ 849 | (tbl)->nonideal_items = 0; \ 850 | for (_he_bkt_i = 0; _he_bkt_i < (tbl)->num_buckets; _he_bkt_i++) { \ 851 | _he_thh = (tbl)->buckets[ _he_bkt_i ].hh_head; \ 852 | while (_he_thh != NULL) { \ 853 | _he_hh_nxt = _he_thh->hh_next; \ 854 | HASH_TO_BKT(_he_thh->hashv, (tbl)->num_buckets * 2U, _he_bkt); \ 855 | _he_newbkt = &(_he_new_buckets[_he_bkt]); \ 856 | if (++(_he_newbkt->count) > (tbl)->ideal_chain_maxlen) { \ 857 | (tbl)->nonideal_items++; \ 858 | if (_he_newbkt->count > _he_newbkt->expand_mult * (tbl)->ideal_chain_maxlen) { \ 859 | _he_newbkt->expand_mult++; \ 860 | } \ 861 | } \ 862 | _he_thh->hh_prev = NULL; \ 863 | _he_thh->hh_next = _he_newbkt->hh_head; \ 864 | if (_he_newbkt->hh_head != NULL) { \ 865 | _he_newbkt->hh_head->hh_prev = _he_thh; \ 866 | } \ 867 | _he_newbkt->hh_head = _he_thh; \ 868 | _he_thh = _he_hh_nxt; \ 869 | } \ 870 | } \ 871 | uthash_free((tbl)->buckets, (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \ 872 | (tbl)->num_buckets *= 2U; \ 873 | (tbl)->log2_num_buckets++; \ 874 | (tbl)->buckets = _he_new_buckets; \ 875 | (tbl)->ineff_expands = ((tbl)->nonideal_items > ((tbl)->num_items >> 1)) ? \ 876 | ((tbl)->ineff_expands+1U) : 0U; \ 877 | if ((tbl)->ineff_expands > 1U) { \ 878 | (tbl)->noexpand = 1; \ 879 | uthash_noexpand_fyi(tbl); \ 880 | } \ 881 | uthash_expand_fyi(tbl); \ 882 | } \ 883 | } while (0) 884 | 885 | 886 | /* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ 887 | /* Note that HASH_SORT assumes the hash handle name to be hh. 888 | * HASH_SRT was added to allow the hash handle name to be passed in. */ 889 | #define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) 890 | #define HASH_SRT(hh,head,cmpfcn) \ 891 | do { \ 892 | unsigned _hs_i; \ 893 | unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ 894 | struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ 895 | if (head != NULL) { \ 896 | _hs_insize = 1; \ 897 | _hs_looping = 1; \ 898 | _hs_list = &((head)->hh); \ 899 | while (_hs_looping != 0U) { \ 900 | _hs_p = _hs_list; \ 901 | _hs_list = NULL; \ 902 | _hs_tail = NULL; \ 903 | _hs_nmerges = 0; \ 904 | while (_hs_p != NULL) { \ 905 | _hs_nmerges++; \ 906 | _hs_q = _hs_p; \ 907 | _hs_psize = 0; \ 908 | for (_hs_i = 0; _hs_i < _hs_insize; ++_hs_i) { \ 909 | _hs_psize++; \ 910 | _hs_q = ((_hs_q->next != NULL) ? \ 911 | HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ 912 | if (_hs_q == NULL) { \ 913 | break; \ 914 | } \ 915 | } \ 916 | _hs_qsize = _hs_insize; \ 917 | while ((_hs_psize != 0U) || ((_hs_qsize != 0U) && (_hs_q != NULL))) { \ 918 | if (_hs_psize == 0U) { \ 919 | _hs_e = _hs_q; \ 920 | _hs_q = ((_hs_q->next != NULL) ? \ 921 | HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ 922 | _hs_qsize--; \ 923 | } else if ((_hs_qsize == 0U) || (_hs_q == NULL)) { \ 924 | _hs_e = _hs_p; \ 925 | if (_hs_p != NULL) { \ 926 | _hs_p = ((_hs_p->next != NULL) ? \ 927 | HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \ 928 | } \ 929 | _hs_psize--; \ 930 | } else if ((cmpfcn( \ 931 | DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_p)), \ 932 | DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_q)) \ 933 | )) <= 0) { \ 934 | _hs_e = _hs_p; \ 935 | if (_hs_p != NULL) { \ 936 | _hs_p = ((_hs_p->next != NULL) ? \ 937 | HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \ 938 | } \ 939 | _hs_psize--; \ 940 | } else { \ 941 | _hs_e = _hs_q; \ 942 | _hs_q = ((_hs_q->next != NULL) ? \ 943 | HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ 944 | _hs_qsize--; \ 945 | } \ 946 | if ( _hs_tail != NULL ) { \ 947 | _hs_tail->next = ((_hs_e != NULL) ? \ 948 | ELMT_FROM_HH((head)->hh.tbl, _hs_e) : NULL); \ 949 | } else { \ 950 | _hs_list = _hs_e; \ 951 | } \ 952 | if (_hs_e != NULL) { \ 953 | _hs_e->prev = ((_hs_tail != NULL) ? \ 954 | ELMT_FROM_HH((head)->hh.tbl, _hs_tail) : NULL); \ 955 | } \ 956 | _hs_tail = _hs_e; \ 957 | } \ 958 | _hs_p = _hs_q; \ 959 | } \ 960 | if (_hs_tail != NULL) { \ 961 | _hs_tail->next = NULL; \ 962 | } \ 963 | if (_hs_nmerges <= 1U) { \ 964 | _hs_looping = 0; \ 965 | (head)->hh.tbl->tail = _hs_tail; \ 966 | DECLTYPE_ASSIGN(head, ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ 967 | } \ 968 | _hs_insize *= 2U; \ 969 | } \ 970 | HASH_FSCK(hh, head, "HASH_SRT"); \ 971 | } \ 972 | } while (0) 973 | 974 | /* This function selects items from one hash into another hash. 975 | * The end result is that the selected items have dual presence 976 | * in both hashes. There is no copy of the items made; rather 977 | * they are added into the new hash through a secondary hash 978 | * hash handle that must be present in the structure. */ 979 | #define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ 980 | do { \ 981 | unsigned _src_bkt, _dst_bkt; \ 982 | void *_last_elt = NULL, *_elt; \ 983 | UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ 984 | ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ 985 | if ((src) != NULL) { \ 986 | for (_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ 987 | for (_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ 988 | _src_hh != NULL; \ 989 | _src_hh = _src_hh->hh_next) { \ 990 | _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ 991 | if (cond(_elt)) { \ 992 | IF_HASH_NONFATAL_OOM( int _hs_oomed = 0; ) \ 993 | _dst_hh = (UT_hash_handle*)(void*)(((char*)_elt) + _dst_hho); \ 994 | _dst_hh->key = _src_hh->key; \ 995 | _dst_hh->keylen = _src_hh->keylen; \ 996 | _dst_hh->hashv = _src_hh->hashv; \ 997 | _dst_hh->prev = _last_elt; \ 998 | _dst_hh->next = NULL; \ 999 | if (_last_elt_hh != NULL) { \ 1000 | _last_elt_hh->next = _elt; \ 1001 | } \ 1002 | if ((dst) == NULL) { \ 1003 | DECLTYPE_ASSIGN(dst, _elt); \ 1004 | HASH_MAKE_TABLE(hh_dst, dst, _hs_oomed); \ 1005 | IF_HASH_NONFATAL_OOM( \ 1006 | if (_hs_oomed) { \ 1007 | uthash_nonfatal_oom(_elt); \ 1008 | (dst) = NULL; \ 1009 | continue; \ 1010 | } \ 1011 | ) \ 1012 | } else { \ 1013 | _dst_hh->tbl = (dst)->hh_dst.tbl; \ 1014 | } \ 1015 | HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ 1016 | HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt], hh_dst, _dst_hh, _hs_oomed); \ 1017 | (dst)->hh_dst.tbl->num_items++; \ 1018 | IF_HASH_NONFATAL_OOM( \ 1019 | if (_hs_oomed) { \ 1020 | HASH_ROLLBACK_BKT(hh_dst, dst, _dst_hh); \ 1021 | HASH_DELETE_HH(hh_dst, dst, _dst_hh); \ 1022 | _dst_hh->tbl = NULL; \ 1023 | uthash_nonfatal_oom(_elt); \ 1024 | continue; \ 1025 | } \ 1026 | ) \ 1027 | HASH_BLOOM_ADD(_dst_hh->tbl, _dst_hh->hashv); \ 1028 | _last_elt = _elt; \ 1029 | _last_elt_hh = _dst_hh; \ 1030 | } \ 1031 | } \ 1032 | } \ 1033 | } \ 1034 | HASH_FSCK(hh_dst, dst, "HASH_SELECT"); \ 1035 | } while (0) 1036 | 1037 | #define HASH_CLEAR(hh,head) \ 1038 | do { \ 1039 | if ((head) != NULL) { \ 1040 | HASH_BLOOM_FREE((head)->hh.tbl); \ 1041 | uthash_free((head)->hh.tbl->buckets, \ 1042 | (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ 1043 | uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ 1044 | (head) = NULL; \ 1045 | } \ 1046 | } while (0) 1047 | 1048 | #define HASH_OVERHEAD(hh,head) \ 1049 | (((head) != NULL) ? ( \ 1050 | (size_t)(((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ 1051 | ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \ 1052 | sizeof(UT_hash_table) + \ 1053 | (HASH_BLOOM_BYTELEN))) : 0U) 1054 | 1055 | #ifdef NO_DECLTYPE 1056 | #define HASH_ITER(hh,head,el,tmp) \ 1057 | for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \ 1058 | (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL))) 1059 | #else 1060 | #define HASH_ITER(hh,head,el,tmp) \ 1061 | for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \ 1062 | (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL))) 1063 | #endif 1064 | 1065 | /* obtain a count of items in the hash */ 1066 | #define HASH_COUNT(head) HASH_CNT(hh,head) 1067 | #define HASH_CNT(hh,head) ((head != NULL)?((head)->hh.tbl->num_items):0U) 1068 | 1069 | typedef struct UT_hash_bucket { 1070 | struct UT_hash_handle *hh_head; 1071 | unsigned count; 1072 | 1073 | /* expand_mult is normally set to 0. In this situation, the max chain length 1074 | * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If 1075 | * the bucket's chain exceeds this length, bucket expansion is triggered). 1076 | * However, setting expand_mult to a non-zero value delays bucket expansion 1077 | * (that would be triggered by additions to this particular bucket) 1078 | * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. 1079 | * (The multiplier is simply expand_mult+1). The whole idea of this 1080 | * multiplier is to reduce bucket expansions, since they are expensive, in 1081 | * situations where we know that a particular bucket tends to be overused. 1082 | * It is better to let its chain length grow to a longer yet-still-bounded 1083 | * value, than to do an O(n) bucket expansion too often. 1084 | */ 1085 | unsigned expand_mult; 1086 | 1087 | } UT_hash_bucket; 1088 | 1089 | /* random signature used only to find hash tables in external analysis */ 1090 | #define HASH_SIGNATURE 0xa0111fe1u 1091 | #define HASH_BLOOM_SIGNATURE 0xb12220f2u 1092 | 1093 | typedef struct UT_hash_table { 1094 | UT_hash_bucket *buckets; 1095 | unsigned num_buckets, log2_num_buckets; 1096 | unsigned num_items; 1097 | struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ 1098 | ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ 1099 | 1100 | /* in an ideal situation (all buckets used equally), no bucket would have 1101 | * more than ceil(#items/#buckets) items. that's the ideal chain length. */ 1102 | unsigned ideal_chain_maxlen; 1103 | 1104 | /* nonideal_items is the number of items in the hash whose chain position 1105 | * exceeds the ideal chain maxlen. these items pay the penalty for an uneven 1106 | * hash distribution; reaching them in a chain traversal takes >ideal steps */ 1107 | unsigned nonideal_items; 1108 | 1109 | /* ineffective expands occur when a bucket doubling was performed, but 1110 | * afterward, more than half the items in the hash had nonideal chain 1111 | * positions. If this happens on two consecutive expansions we inhibit any 1112 | * further expansion, as it's not helping; this happens when the hash 1113 | * function isn't a good fit for the key domain. When expansion is inhibited 1114 | * the hash will still work, albeit no longer in constant time. */ 1115 | unsigned ineff_expands, noexpand; 1116 | 1117 | uint32_t signature; /* used only to find hash tables in external analysis */ 1118 | #ifdef HASH_BLOOM 1119 | uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ 1120 | uint8_t *bloom_bv; 1121 | uint8_t bloom_nbits; 1122 | #endif 1123 | 1124 | } UT_hash_table; 1125 | 1126 | typedef struct UT_hash_handle { 1127 | struct UT_hash_table *tbl; 1128 | void *prev; /* prev element in app order */ 1129 | void *next; /* next element in app order */ 1130 | struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ 1131 | struct UT_hash_handle *hh_next; /* next hh in bucket order */ 1132 | const void *key; /* ptr to enclosing struct's key */ 1133 | unsigned keylen; /* enclosing struct's key len */ 1134 | unsigned hashv; /* result of hash-fcn(key) */ 1135 | } UT_hash_handle; 1136 | 1137 | #endif /* UTHASH_H */ 1138 | -------------------------------------------------------------------------------- /wg-obfuscator.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include "wg-obfuscator.h" 12 | #include "uthash.h" 13 | #include "commit.h" 14 | 15 | #define log(level, fmt, ...) { if (verbose >= (level)) \ 16 | fprintf(stderr, "[%s][%c] " fmt "\n", section_name, \ 17 | ( \ 18 | (level) == LL_ERROR ? 'E' \ 19 | : (level) == LL_WARN ? 'W' \ 20 | : (level) == LL_INFO ? 'I' \ 21 | : (level) == LL_DEBUG ? 'D' \ 22 | : (level) == LL_TRACE ? 'T' \ 23 | : '?' \ 24 | ), ##__VA_ARGS__); \ 25 | } 26 | #define trace(fmt, ...) if (verbose >= LL_TRACE) fprintf(stderr, fmt, ##__VA_ARGS__) 27 | 28 | // Listening socket for receiving data from the clients 29 | static int listen_sock = 0; 30 | // Hash table for client connections 31 | static client_entry_t *conn_table = NULL; 32 | 33 | #ifdef USE_EPOLL 34 | static int epfd = 0; 35 | #endif 36 | 37 | // Main parameters (TODO: IPv6?) 38 | static char section_name[256] = DEFAULT_INSTANCE_NAME; 39 | // Listening port for the obfuscator 40 | static int listen_port = -1; 41 | // Host and port to forward the data to 42 | static char forward_host_port[256] = {0}; 43 | // Key for obfuscation 44 | static char xor_key[256] = {0}; 45 | // Client interface 46 | static char client_interface[256] = {0}; 47 | // Static bindings for two-way mode 48 | static char static_bindings[2048] = {0}; 49 | // Verbosity level 50 | static char verbose_str[256] = {0}; 51 | static int verbose = LL_INFO; 52 | 53 | /** 54 | * @brief Prints an error message related to a specific section. 55 | * 56 | * This function prints an error message prefixed by the provided string and section name. 57 | * Additional arguments can be provided for formatted output. 58 | * 59 | * @param str The error message prefix. 60 | * @param section The name of the section related to the error. 61 | * @param ... Additional arguments for formatting the error message. 62 | */ 63 | static void perror_sect(char *str, char* section, ...) 64 | { 65 | char buf[512]; 66 | va_list args; 67 | va_start(args, section); 68 | vsnprintf(buf, sizeof(buf), str, args); 69 | va_end(args); 70 | 71 | char msg[1024]; 72 | snprintf(msg, sizeof(msg), "[%s][E] %s", section, buf); 73 | perror(msg); 74 | } 75 | 76 | #define serror(x, ...) perror_sect(x, section_name, ##__VA_ARGS__) 77 | 78 | 79 | /** 80 | * @brief Removes leading and trailing whitespace characters from the input string. 81 | * 82 | * This function modifies the input string in place by trimming any whitespace 83 | * characters (such as spaces, tabs, or newlines) from both the beginning and end. 84 | * 85 | * @param s Pointer to the null-terminated string to be trimmed. 86 | * @return Pointer to the trimmed string (same as input pointer). 87 | */ 88 | static char *trim(char *s) { 89 | char *end; 90 | // Trim leading spaces, tabs, carriage returns and newlines 91 | while (*s && (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')) s++; 92 | if (!*s) return s; 93 | // Trim trailing spaces, tabs, carriage returns and newlines 94 | end = s + strlen(s) - 1; 95 | while (end > s && (*end == ' ' || *end == '\t' || *end == '\r' || *end == '\n')) *end-- = 0; 96 | return s; 97 | } 98 | 99 | /** 100 | * @brief Reads and processes the configuration file. 101 | * 102 | * This function opens the specified configuration file and parses its contents 103 | * to initialize or update the application's configuration settings. 104 | * 105 | * @param filename The path to the configuration file to be read. 106 | */ 107 | static void read_config_file(char *filename) 108 | { 109 | // Read configuration from the file 110 | char line[256]; 111 | FILE *config_file = fopen(filename, "r"); 112 | if (config_file == NULL) { 113 | perror("Can't open config file"); 114 | exit(EXIT_FAILURE); 115 | } 116 | int listen_port_set = 0; 117 | int forward_host_port_set = 0; 118 | int xor_key_set = 0; 119 | int something_set = 0; 120 | 121 | while (fgets(line, sizeof(line), config_file)) { 122 | // Remove trailing newlines, carriage returns, spaces and tabs 123 | while (strlen(line) && (line[strlen(line) - 1] == '\n' || line[strlen(line) - 1] == '\r' 124 | || line[strlen(line) - 1] == ' ' || line[strlen(line) - 1] == '\t')) { 125 | line[strlen(line) - 1] = 0; 126 | } 127 | // Remove leading spaces and tabs 128 | while (strlen(line) && (line[0] == ' ' || line[0] == '\t')) { 129 | memmove(line, line + 1, strlen(line)); 130 | } 131 | // Ignore comments 132 | char *comment_index = strstr(line, "#"); 133 | if (comment_index != NULL) { 134 | *comment_index = 0; 135 | } 136 | // Skip empty lines or with spaces only 137 | if (strspn(line, " \t\r\n") == strlen(line)) { 138 | continue; 139 | } 140 | 141 | // It can be new section 142 | if (line[0] == '[' && line[strlen(line) - 1] == ']') { 143 | if (something_set) { 144 | // new config, need to fork the process 145 | if (fork() == 0) { 146 | return; 147 | } 148 | } 149 | size_t len = strlen(line) - 2; 150 | if (len > sizeof(section_name) - 1) { 151 | len = sizeof(section_name) - 1; 152 | } 153 | strncpy(section_name, line + 1, len); 154 | 155 | // Reset all the parameters 156 | listen_port = -1; 157 | memset(forward_host_port, 0, sizeof(forward_host_port)); 158 | memset(xor_key, 0, sizeof(xor_key)); 159 | memset(client_interface, 0, sizeof(client_interface)); 160 | memset(static_bindings, 0, sizeof(static_bindings)); 161 | memset(verbose_str, 0, sizeof(verbose_str)); 162 | verbose = 2; 163 | listen_port_set = 0; 164 | forward_host_port_set = 0; 165 | xor_key_set = 0; 166 | something_set = 0; 167 | continue; 168 | } 169 | 170 | // Parse key-value pairs 171 | char *key = strtok(line, "="); 172 | key = trim(key); 173 | while (strlen(key) && (key[strlen(key) - 1] == ' ' || key[strlen(key) - 1] == '\t' || key[strlen(key) - 1] == '\r' || key[strlen(key) - 1] == '\n')) { 174 | key[strlen(key) - 1] = 0; 175 | } 176 | char *value = strtok(NULL, "="); 177 | if (value == NULL) { 178 | log(LL_ERROR, "Invalid configuration line: %s", line); 179 | exit(EXIT_FAILURE); 180 | } 181 | value = trim(value); 182 | if (!*value) { 183 | log(LL_ERROR, "Invalid configuration line: %s", line); 184 | exit(EXIT_FAILURE); 185 | } 186 | 187 | if (strcmp(key, "source-lport") == 0) { 188 | listen_port = atoi(value); 189 | listen_port_set = 1; 190 | something_set = 1; 191 | } else if (strcmp(key, "target") == 0) { 192 | strncpy(forward_host_port, value, sizeof(forward_host_port) - 1); 193 | forward_host_port_set = 1; 194 | something_set = 1; 195 | } else if (strcmp(key, "key") == 0) { 196 | strncpy(xor_key, value, sizeof(xor_key) - 1); 197 | xor_key_set = 1; 198 | something_set = 1; 199 | } else if (strcmp(key, "source-if") == 0) { 200 | strncpy(client_interface, value, sizeof(client_interface) - 1); 201 | something_set = 1; 202 | } 203 | else if (strcmp(key, "target-if") == 0) { 204 | //strncpy(forward_interface, value, sizeof(forward_interface) - 1); 205 | log(LL_WARN, "The 'target-if' option is deprecated and will be ignored."); 206 | something_set = 1; 207 | } else if (strcmp(key, "source") == 0) { 208 | //strncpy(client_fixed_addr_port, value, sizeof(client_fixed_addr_port) - 1); 209 | log(LL_WARN, "The 'source' option is deprecated and will be ignored."); 210 | something_set = 1; 211 | } else if (strcmp(key, "target-lport") == 0) { 212 | //server_local_port = atoi(value); 213 | log(LL_WARN, "The 'target-lport' option is deprecated and will be ignored."); 214 | something_set = 1; 215 | } 216 | else if (strcmp(key, "static-bindings") == 0) { 217 | strncpy(static_bindings, value, sizeof(static_bindings) - 1); 218 | something_set = 1; 219 | } 220 | else if (strcmp(key, "verbose") == 0) { 221 | strncpy(verbose_str, value, sizeof(verbose_str) - 1); 222 | something_set = 1; 223 | } else { 224 | log(LL_ERROR, "Unknown configuration key: %s", key); 225 | exit(EXIT_FAILURE); 226 | } 227 | } 228 | fclose(config_file); 229 | if (!listen_port_set) { 230 | log(LL_ERROR, "'source-lport' is not set in the configuration file"); 231 | exit(EXIT_FAILURE); 232 | } 233 | if (!forward_host_port_set) { 234 | log(LL_ERROR, "'target' is not set in the configuration file"); 235 | exit(EXIT_FAILURE); 236 | } 237 | if (!xor_key_set) { 238 | log(LL_ERROR, "'key' is not set in the configuration file"); 239 | exit(EXIT_FAILURE); 240 | } 241 | } 242 | 243 | /* Parse a single option. */ 244 | static error_t 245 | parse_opt (int key, char *arg, struct argp_state *state) 246 | { 247 | switch (key) 248 | { 249 | case 'c': 250 | read_config_file(arg); 251 | break; 252 | case 'i': 253 | strncpy(client_interface, arg, sizeof(client_interface) - 1); 254 | break; 255 | case 's': 256 | log(LL_WARN, "The 'source' option is deprecated and will be ignored."); 257 | break; 258 | case 'p': 259 | listen_port = atoi(arg); 260 | break; 261 | case 'o': 262 | log(LL_WARN, "The 'target-if' option is deprecated and will be ignored."); 263 | break; 264 | case 't': 265 | strncpy(forward_host_port, arg, sizeof(forward_host_port) - 1); 266 | break; 267 | case 'r': 268 | log(LL_WARN, "The 'target-lport' option is deprecated and will be ignored."); 269 | break; 270 | case 'b': 271 | strncpy(static_bindings, arg, sizeof(static_bindings) - 1); 272 | break; 273 | case 'k': 274 | strncpy(xor_key, arg, sizeof(xor_key)); 275 | break; 276 | case 'v': 277 | strncpy(verbose_str, arg, sizeof(verbose_str) - 1); 278 | break; 279 | default: 280 | return ARGP_ERR_UNKNOWN; 281 | } 282 | return 0; 283 | } 284 | 285 | /* The options we understand. */ 286 | static const struct argp_option options[] = { 287 | { "config", 'c', "", 0, "Read configuration from file (can be used instead of the rest arguments)", .group = 0 }, 288 | { "source-if", 'i', "", 0, "Source interface to listen on (optional, default - 0.0.0.0, e.g. all)", .group = 1 }, 289 | { "source", 's', ":", OPTION_HIDDEN, "Source client address and port (optional, default - auto, dynamic)", .group = 2 }, 290 | { "source-lport", 'p', "", 0, "Source port to listen", .group = 3 }, 291 | { "target-if", 'o', "", OPTION_HIDDEN, "Target interface to use (optional, default - 0.0.0.0, e.g. all)", .group = 4 }, 292 | { "target", 't', ":", 0, "Target IP and port", .group = 5 }, 293 | { "target-lport", 'r', "", OPTION_HIDDEN, "Target port to listen (optional, default - random)", .group = 6 }, 294 | { "key", 'k', "", 0, "Obfuscation key (required, must be 1-255 characters long)", .group = 7 }, 295 | { "static-bindings", 'b', "::,...", 0, "Comma-separated static bindings for two-way mode as ::", .group = 8 }, 296 | { "verbose", 'v', "<0-4>", 0, "Verbosity level (optional, default - 2)", .group = 9 }, 297 | { " ", 0, 0, OPTION_DOC , "0 - ERRORS (critical errors only)", .group = 9 }, 298 | { " ", 0, 0, OPTION_DOC , "1 - WARNINGS (important messages: startup and shutdown messages)", .group = 9 }, 299 | { " ", 0, 0, OPTION_DOC , "2 - INFO (informational messages: status messages, connection established, etc.)", .group = 9 }, 300 | { " ", 0, 0, OPTION_DOC , "3 - DEBUG (detailed debug messages)", .group = 9 }, 301 | { " ", 0, 0, OPTION_DOC , "4 - TRACE (very detailed debug messages, including packet dumps)", .group = 9 }, 302 | { 0 } 303 | }; 304 | 305 | /* Our argp parser. */ 306 | static struct argp argp = { 307 | .options = options, 308 | .parser = parse_opt, 309 | .args_doc = NULL, 310 | #ifdef COMMIT 311 | .doc = "WireGuard Obfuscator\n(commit " COMMIT " @ " WG_OBFUSCATOR_GIT_REPO ")" 312 | #else 313 | .doc = "WireGuard Obfuscator v" WG_OBFUSCATOR_VERSION 314 | #endif 315 | }; 316 | 317 | /** 318 | * Checks if the given data is obfuscated. 319 | * 320 | * @param data Pointer to the data buffer to check. 321 | * @return uint8_t Returns a non-zero value if the data is obfuscated, 0 otherwise. 322 | */ 323 | static inline uint8_t is_obfuscated(uint8_t *data) { 324 | return !(*((uint32_t*)data) >= 1 && *((uint32_t*)data) <= 4); 325 | } 326 | 327 | /** 328 | * @brief XORs the data in the given buffer with the provided key. 329 | * 330 | * This function applies a repeating XOR operation to each byte in the buffer 331 | * using the specified key. The key is repeated as necessary to match the length 332 | * of the buffer. 333 | * 334 | * @param buffer Pointer to the data buffer to be XORed. 335 | * @param length Length of the data buffer in bytes. 336 | * @param key Pointer to the key used for XOR operation. 337 | * @param key_length Length of the key in bytes. 338 | */ 339 | static inline void xor_data(uint8_t *buffer, int length, char *key, int key_length) { 340 | // Calculate the CRC8 based on the key 341 | uint8_t crc = 0, j; 342 | int i; 343 | for (i = 0; i < length; i++) 344 | { 345 | // Get key byte and add the data length and the key length 346 | uint8_t inbyte = key[i % key_length] + length + key_length; 347 | for (j=0; j<8; j++) 348 | { 349 | uint8_t mix = (crc ^ inbyte) & 0x01; 350 | crc >>= 1; 351 | if (mix) { 352 | crc ^= 0x8C; 353 | } 354 | inbyte >>= 1; 355 | } 356 | // XOR the data with the CRC 357 | buffer[i] ^= crc; 358 | } 359 | } 360 | 361 | /** 362 | * @brief Encodes the given buffer using the specified key and version. 363 | * 364 | * This function applies an encoding algorithm to the input buffer using the provided key and version. 365 | * 366 | * @param buffer Pointer to the data buffer to encode. 367 | * @param length Length of the data buffer in bytes. 368 | * @param key Pointer to the key used for encoding. 369 | * @param key_length Length of the key in bytes. 370 | * @param version Encoding version to use. 371 | * @return 0 on success, or a negative value on error. 372 | */ 373 | static inline int encode(uint8_t *buffer, int length, char *key, int key_length, uint8_t version) { 374 | if (version >= 1) { 375 | uint32_t packet_type = *((uint32_t*)buffer); 376 | // Add some randomness to the packet 377 | uint8_t rnd = 1 + (rand() % 255); 378 | buffer[0] ^= rnd; // Xor the first byte to a random value 379 | buffer[1] = rnd; // Set the second byte to a random value 380 | // Add dummy data to the packet 381 | if (length < MAX_DUMMY_LENGTH_TOTAL) { 382 | uint16_t dummy_length = 0; 383 | switch (packet_type) { 384 | case WG_TYPE_HANDSHAKE: 385 | case WG_TYPE_HANDSHAKE_RESP: 386 | // length to MAX_DUMMY_LENGTH_HANDSHAKE 387 | dummy_length = rand() % MAX_DUMMY_LENGTH_HANDSHAKE; 388 | break; 389 | case WG_TYPE_COOKIE: 390 | case WG_TYPE_DATA: 391 | // length to MAX_DUMMY_LENGTH_HANDSHAKE 392 | #if MAX_DUMMY_LENGTH_DATA > 0 393 | dummy_length = rand() % MAX_DUMMY_LENGTH_DATA; 394 | #endif 395 | break; 396 | default: 397 | //assert(0); 398 | break; 399 | } 400 | *((uint16_t*)(buffer+2)) = dummy_length; // Set the dummy length in the packet 401 | if (length + dummy_length > MAX_DUMMY_LENGTH_TOTAL) { 402 | dummy_length = MAX_DUMMY_LENGTH_TOTAL - length; 403 | } 404 | if (dummy_length > 0) { 405 | int i = length; 406 | length += dummy_length; 407 | for (; i < length; ++i) { 408 | buffer[i] = 0xFF; // Fill with FFs, random data is not needed 409 | } 410 | } 411 | } 412 | } 413 | 414 | xor_data(buffer, length, key, key_length); 415 | 416 | return length; 417 | } 418 | 419 | static inline int decode(uint8_t *buffer, int length, char *key, int key_length, uint8_t *version_out) { 420 | xor_data(buffer, length, key, key_length); 421 | 422 | if (!is_obfuscated(buffer)) { 423 | // Looks like an old version 424 | *version_out = 0; 425 | return length; 426 | } 427 | 428 | buffer[0] ^= buffer[1]; // Restore the first byte by XORing it with the second byte 429 | buffer[1] = 0; // Set the second byte to 0 430 | length -= *((uint16_t*)(buffer+2)); // Remove dummy data length from the packet 431 | *((uint16_t*)(buffer+2)) = 0; // Reset the dummy length field to 0 432 | return length; 433 | } 434 | 435 | /** 436 | * @brief Handles incoming signals for the application. 437 | * 438 | * This function is registered as a signal handler and is invoked when the process 439 | * receives a signal. The specific actions taken depend on the signal received. 440 | * 441 | * @param signal The signal number received by the process. 442 | */ 443 | static void signal_handler(int signal) { 444 | client_entry_t *current_entry, *tmp; 445 | 446 | switch (signal) { 447 | case -1: 448 | case SIGINT: 449 | case SIGTERM: 450 | // Close all connections and clean up 451 | if (listen_sock) { 452 | close(listen_sock); 453 | } 454 | HASH_ITER(hh, conn_table, current_entry, tmp) { 455 | if (current_entry->server_sock) { 456 | close(current_entry->server_sock); 457 | } 458 | HASH_DEL(conn_table, current_entry); 459 | free(current_entry); 460 | } 461 | #ifdef USE_EPOLL 462 | if (epfd) { 463 | close(epfd); 464 | } 465 | #endif 466 | log(LL_WARN, "Stopped."); 467 | break; 468 | } 469 | exit(signal != -1 ? EXIT_SUCCESS : EXIT_FAILURE); 470 | } 471 | #define FAILURE() signal_handler(-1) 472 | 473 | /** 474 | * @brief Creates a new client_entry_t structure and initializes it with the provided client and forward addresses. 475 | * 476 | * @param client_addr Pointer to a struct sockaddr_in representing the client's address. 477 | * @param forward_addr Pointer to a struct sockaddr_in representing the address to which traffic should be forwarded. 478 | * @return Pointer to the newly created client_entry_t structure, or NULL on failure. 479 | */ 480 | static client_entry_t * new_client_entry(struct sockaddr_in *client_addr, struct sockaddr_in *forward_addr) { 481 | if (HASH_COUNT(conn_table) >= MAX_CLIENTS) { 482 | log(LL_ERROR, "Maximum number of clients reached (%d), cannot add new client", MAX_CLIENTS); 483 | return NULL; 484 | } 485 | client_entry_t * client_entry = malloc(sizeof(client_entry_t)); 486 | if (!client_entry) { 487 | log(LL_ERROR, "Failed to allocate memory for client entry"); 488 | return NULL; 489 | } 490 | memset(client_entry, 0, sizeof(client_entry_t)); 491 | memcpy(&client_entry->client_addr, client_addr, sizeof(client_entry->client_addr)); 492 | client_entry->server_sock = socket(AF_INET, SOCK_DGRAM, 0); 493 | if (client_entry->server_sock < 0) { 494 | serror("Failed to create server socket for client"); 495 | free(client_entry); 496 | return NULL; 497 | } 498 | // Set the server address to the specified one 499 | connect(client_entry->server_sock, (struct sockaddr *)forward_addr, sizeof(*forward_addr)); 500 | // Get the assigned port number 501 | socklen_t our_addr_len = sizeof(client_entry->our_addr); 502 | if (getsockname(client_entry->server_sock, (struct sockaddr *)&client_entry->our_addr, &our_addr_len) == -1) { 503 | serror("Failed to get socket port number"); 504 | FAILURE(); 505 | } 506 | 507 | #ifdef USE_EPOLL 508 | struct epoll_event e = { 509 | .events = EPOLLIN, 510 | .data.ptr = client_entry 511 | }; 512 | if (epoll_ctl(epfd, EPOLL_CTL_ADD, client_entry->server_sock, &e) != 0) { 513 | serror("epoll_ctl for client socket"); 514 | close(client_entry->server_sock); 515 | free(client_entry); 516 | return NULL; 517 | } 518 | #endif 519 | 520 | HASH_ADD(hh, conn_table, client_addr, sizeof(*client_addr), client_entry); 521 | 522 | log(LL_DEBUG, "Added binding: %s:%d:%d", 523 | inet_ntoa(client_entry->client_addr.sin_addr), ntohs(client_entry->client_addr.sin_port), 524 | ntohs(client_entry->our_addr.sin_port)); 525 | 526 | return client_entry; 527 | } 528 | 529 | /** 530 | * @brief Creates a new static client entry. 531 | * 532 | * This function allocates and initializes a new client_entry_t structure 533 | * using the provided client and forward addresses, as well as the specified local port. 534 | * 535 | * @param client_addr Pointer to a sockaddr_in structure representing the client's address. 536 | * @param forward_addr Pointer to a sockaddr_in structure representing the address to forward to. 537 | * @param local_port The local port number to connect to the server. 538 | * @return Pointer to the newly created client_entry_t structure, or NULL on failure. 539 | */ 540 | static client_entry_t * new_client_entry_static(struct sockaddr_in *client_addr, struct sockaddr_in *forward_addr, uint16_t local_port) { 541 | if (HASH_COUNT(conn_table) >= MAX_CLIENTS) { 542 | log(LL_ERROR, "Maximum number of clients reached (%d), cannot add new client", MAX_CLIENTS); 543 | return NULL; 544 | } 545 | 546 | // Check if such client already exists 547 | client_entry_t *existing_entry; 548 | HASH_FIND(hh, conn_table, client_addr, sizeof(*client_addr), existing_entry); 549 | if (existing_entry) { 550 | log(LL_ERROR, "Binding with client %s:%d already exists", 551 | inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port)); 552 | return NULL; 553 | } 554 | 555 | client_entry_t * client_entry = malloc(sizeof(client_entry_t)); 556 | if (!client_entry) { 557 | log(LL_ERROR, "Failed to allocate memory for client entry"); 558 | return NULL; 559 | } 560 | memset(client_entry, 0, sizeof(client_entry_t)); 561 | memcpy(&client_entry->client_addr, client_addr, sizeof(client_entry->client_addr)); 562 | client_entry->server_sock = socket(AF_INET, SOCK_DGRAM, 0); 563 | if (client_entry->server_sock < 0) { 564 | serror("Failed to create server socket for client"); 565 | free(client_entry); 566 | return NULL; 567 | } 568 | // Bind the socket to the specified local port 569 | client_entry->our_addr.sin_family = AF_INET; 570 | // TODO: ability to bind to a specific address 571 | client_entry->our_addr.sin_addr.s_addr = INADDR_ANY; 572 | client_entry->our_addr.sin_port = htons(local_port); 573 | // Set the local port number 574 | if (bind(client_entry->server_sock, (struct sockaddr *)&client_entry->our_addr, sizeof(client_entry->our_addr)) < 0) { 575 | serror("Failed to bind server socket to %s:%d", 576 | inet_ntoa(client_entry->our_addr.sin_addr), local_port); 577 | close(client_entry->server_sock); 578 | free(client_entry); 579 | return NULL; 580 | } 581 | // Set the server address to the specified one 582 | connect(client_entry->server_sock, (struct sockaddr *)forward_addr, sizeof(*forward_addr)); 583 | 584 | #ifdef USE_EPOLL 585 | struct epoll_event e = { 586 | .events = EPOLLIN, 587 | .data.ptr = client_entry 588 | }; 589 | if (epoll_ctl(epfd, EPOLL_CTL_ADD, client_entry->server_sock, &e) != 0) { 590 | serror("epoll_ctl for client socket"); 591 | close(client_entry->server_sock); 592 | free(client_entry); 593 | return NULL; 594 | } 595 | #endif 596 | 597 | client_entry->is_static = 1; 598 | 599 | HASH_ADD(hh, conn_table, client_addr, sizeof(*client_addr), client_entry); 600 | 601 | // log(LL_DEBUG, "Added static binding: %s:%d:%d", 602 | // inet_ntoa(client_entry->client_addr.sin_addr), ntohs(client_entry->client_addr.sin_port), 603 | // ntohs(client_entry->our_addr.sin_port)); 604 | 605 | return client_entry; 606 | } 607 | 608 | #ifndef USE_EPOLL 609 | static client_entry_t *find_by_server_sock(int fd) { 610 | client_entry_t *e, *tmp; 611 | HASH_ITER(hh, conn_table, e, tmp) { 612 | if (e->server_sock == fd) return e; 613 | } 614 | return NULL; 615 | } 616 | #endif 617 | 618 | int main(int argc, char *argv[]) { 619 | struct sockaddr_in 620 | listen_addr, // Address for listening socket, for receiving data from the client 621 | forward_addr; // Address for forwarding socket, for sending data to the server 622 | uint8_t buffer[BUFFER_SIZE]; 623 | char target_host[256] = {0}; 624 | int target_port = -1; 625 | int key_length = 0; 626 | unsigned long s_listen_addr_client = INADDR_ANY; 627 | long now, last_cleanup_time = 0; 628 | 629 | #ifdef USE_EPOLL 630 | struct epoll_event events[MAX_EVENTS]; 631 | #else 632 | struct pollfd pollfds[MAX_CLIENTS + 1]; 633 | #endif 634 | 635 | if (verbose >= LL_WARN) { 636 | #ifdef COMMIT 637 | fprintf(stderr, "Starting WireGuard Obfuscator (commit " COMMIT " @ " WG_OBFUSCATOR_GIT_REPO ")\n"); 638 | #else 639 | fprintf(stderr, "Starting WireGuard Obfuscator v" WG_OBFUSCATOR_VERSION "\n"); 640 | #endif 641 | } 642 | 643 | /* Parse command line arguments */ 644 | if (argc == 1) { 645 | fprintf(stderr, "No arguments provided, use \"%s --help\" command for usage information\n", argv[0]); 646 | exit(EXIT_FAILURE); 647 | } 648 | if (argp_parse(&argp, argc, argv, 0, 0, 0) != 0) { 649 | fprintf(stderr, "Failed to parse command line arguments\n"); 650 | exit(EXIT_FAILURE); 651 | } 652 | 653 | /* Check the parameters */ 654 | 655 | // Check the listening port 656 | if (listen_port < 0) { 657 | log(LL_ERROR, "'source-lport' is not set"); 658 | exit(EXIT_FAILURE); 659 | } 660 | 661 | // Check the target host and port 662 | if (!forward_host_port[0]) { 663 | log(LL_ERROR, "'target' is not set"); 664 | exit(EXIT_FAILURE); 665 | } else { 666 | char *port_delimiter = strchr(forward_host_port, ':'); 667 | if (port_delimiter == NULL) { 668 | log(LL_ERROR, "Invalid target host:port format: %s", forward_host_port); 669 | exit(EXIT_FAILURE); 670 | } 671 | *port_delimiter = 0; 672 | strncpy(target_host, forward_host_port, sizeof(target_host) - 1); 673 | target_port = atoi(port_delimiter + 1); 674 | if (target_port <= 0) { 675 | log(LL_ERROR, "Invalid target port: %s", port_delimiter + 1); 676 | exit(EXIT_FAILURE); 677 | } 678 | } 679 | 680 | // Check the key 681 | key_length = strlen(xor_key); 682 | if (key_length == 0) { 683 | log(LL_ERROR, "Key is not set"); 684 | exit(EXIT_FAILURE); 685 | } 686 | 687 | // Check the client interface 688 | if (client_interface[0]) { 689 | s_listen_addr_client = inet_addr(client_interface); 690 | if (s_listen_addr_client == INADDR_NONE) { 691 | struct hostent *he = gethostbyname(client_interface); 692 | if (he == NULL) { 693 | log(LL_ERROR, "Invalid source interface: %s", client_interface); 694 | exit(EXIT_FAILURE); 695 | } 696 | s_listen_addr_client = *(unsigned long *)he->h_addr; 697 | } 698 | } 699 | 700 | // Check and set the verbosity level 701 | if (verbose_str[0]) { 702 | verbose = atoi(verbose_str); 703 | if (verbose < 0 || verbose > 4) { 704 | log(LL_ERROR, "Invalid verbosity level: %s (must be between 0 and 4)", verbose_str); 705 | exit(EXIT_FAILURE); 706 | } 707 | } 708 | 709 | /* Set up signal handlers */ 710 | signal(SIGINT, signal_handler); 711 | signal(SIGTERM, signal_handler); 712 | 713 | /* Create listening socket */ 714 | if ((listen_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { 715 | serror("Can't create source socket to listen"); 716 | exit(EXIT_FAILURE); 717 | } 718 | 719 | /* Bind the listening socket to the specified address and port */ 720 | memset(&listen_addr, 0, sizeof(listen_addr)); 721 | listen_addr.sin_family = AF_INET; 722 | listen_addr.sin_addr.s_addr = s_listen_addr_client; 723 | listen_addr.sin_port = htons(listen_port); 724 | if (bind(listen_sock, (struct sockaddr *)&listen_addr, sizeof(listen_addr)) < 0) { 725 | serror("Failed to bind source socket to %s:%d", 726 | inet_ntoa(listen_addr.sin_addr), ntohs(listen_addr.sin_port)); 727 | FAILURE(); 728 | } 729 | log(LL_WARN, "Listening on port %s:%d for source", inet_ntoa(listen_addr.sin_addr), ntohs(listen_addr.sin_port)); 730 | 731 | /* Use epoll for events if enabled */ 732 | #ifdef USE_EPOLL 733 | epfd = epoll_create1(0); 734 | if (epfd < 0) { 735 | serror("epoll_create1"); 736 | FAILURE(); 737 | } 738 | { 739 | struct epoll_event ev = { 740 | .events = EPOLLIN, 741 | .data.fd = listen_sock 742 | }; 743 | if (epoll_ctl(epfd, EPOLL_CTL_ADD, listen_sock, &ev) != 0) { 744 | serror("epoll_ctl for listen_sock"); 745 | FAILURE(); 746 | } 747 | } 748 | #endif 749 | 750 | /* Set up forward address */ 751 | memset(&forward_addr, 0, sizeof(forward_addr)); 752 | forward_addr.sin_family = AF_INET; 753 | struct hostent *host = gethostbyname(target_host); 754 | if (host == NULL) { 755 | log(LL_ERROR, "Can't resolve hostname: %s", target_host); 756 | FAILURE(); 757 | } 758 | log(LL_DEBUG, "Resolved target hostname '%s' to %s", target_host, inet_ntoa(*(struct in_addr *)host->h_addr)); 759 | forward_addr.sin_addr = *(struct in_addr *)host->h_addr; 760 | if (target_port <= 0 || target_port > 65535) { 761 | log(LL_ERROR, "Invalid target port: %d", target_port); 762 | FAILURE(); 763 | } 764 | forward_addr.sin_port = htons(target_port); 765 | log(LL_WARN, "Target: %s:%d", target_host, target_port); 766 | 767 | /* Add static bindings if provided */ 768 | if (static_bindings[0]) { 769 | // Parse static bindings 770 | char *binding = strtok(static_bindings, ","); 771 | while (binding) { 772 | // Trim leading and trailing spaces 773 | binding = trim(binding); 774 | char *colon1 = strchr(binding, ':'); 775 | if (!colon1) { 776 | log(LL_ERROR, "Invalid static binding format: %s", binding); 777 | exit(EXIT_FAILURE); 778 | } 779 | char *colon2 = strchr(colon1 + 1, ':'); 780 | if (!colon2) { 781 | log(LL_ERROR, "Invalid static binding format: %s", binding); 782 | exit(EXIT_FAILURE); 783 | } 784 | *colon1 = 0; 785 | *colon2 = 0; 786 | 787 | struct sockaddr_in client_addr = {0}; 788 | client_addr.sin_family = AF_INET; 789 | struct hostent *host = gethostbyname(binding); 790 | if (host == NULL) { 791 | log(LL_ERROR, "Can't resolve hostname '%s' for static binding '%s:%s:%s'", 792 | binding, binding, colon1 + 1, colon2 + 1); 793 | FAILURE(); 794 | } 795 | log(LL_DEBUG, "Resolved static binding hostname '%s' to %s", binding, inet_ntoa(*(struct in_addr *)host->h_addr)); 796 | client_addr.sin_addr = *(struct in_addr *)host->h_addr; 797 | int remote_port = atoi(colon1 + 1); 798 | if (remote_port <= 0 || remote_port > 65535) { 799 | log(LL_ERROR, "Invalid port '%s' for static binding '%s:%s:%s'", 800 | colon1 + 1, binding, colon1 + 1, colon2 + 1); 801 | FAILURE(); 802 | } 803 | int local_port = atoi(colon2 + 1); 804 | if (local_port <= 0 || local_port > 65535) { 805 | log(LL_ERROR, "Invalid port '%s' for static binding '%s:%s:%s'", 806 | colon2 + 1, binding, colon1 + 1, colon2 + 1); 807 | FAILURE(); 808 | } 809 | client_addr.sin_port = htons(remote_port); 810 | 811 | if (!new_client_entry_static(&client_addr, &forward_addr, local_port)) { 812 | log(LL_ERROR, "Failed to create static binding: %s:%s:%s", 813 | binding, colon1 + 1, colon2 + 1); 814 | FAILURE(); 815 | } 816 | 817 | log(LL_WARN, "Added static binding: %s:%d <-> %d:obfuscator:%d <-> %s:%d", 818 | binding, remote_port, listen_port, 819 | local_port, target_host, target_port); 820 | 821 | binding = strtok(NULL, ","); 822 | } 823 | } 824 | 825 | log(LL_WARN, "WireGuard obfuscator successfully started"); 826 | 827 | /* Main loop */ 828 | while (1) { 829 | // Using epoll or poll to wait for events 830 | #ifdef USE_EPOLL 831 | int events_n = epoll_wait(epfd, events, MAX_EVENTS, POLL_TIMEOUT); 832 | if (events_n < 0) { 833 | serror("epoll_wait"); 834 | FAILURE(); 835 | } 836 | #else 837 | int nfds = 0; 838 | pollfds[nfds].fd = listen_sock; 839 | pollfds[nfds].events = POLLIN; 840 | nfds++; 841 | client_entry_t *entry, *tmp; 842 | HASH_ITER(hh, conn_table, entry, tmp) { 843 | if (nfds >= MAX_CLIENTS) { 844 | log(LL_DEBUG, "Too many clients, cannot add more"); 845 | break; 846 | } 847 | pollfds[nfds].fd = entry->server_sock; 848 | pollfds[nfds].events = POLLIN; 849 | nfds++; 850 | } 851 | int ret = poll(pollfds, nfds, POLL_TIMEOUT); 852 | if (ret < 0) { 853 | serror("poll"); 854 | FAILURE(); 855 | } 856 | #endif 857 | 858 | // Get the current time 859 | struct timespec now_ts; 860 | clock_gettime(CLOCK_MONOTONIC, &now_ts); 861 | now = now_ts.tv_sec * 1000 + now_ts.tv_nsec / 1000000; 862 | 863 | #ifdef USE_EPOLL 864 | for (int e = 0; e < events_n; e++) { 865 | struct epoll_event *event = &events[e]; 866 | if (event->data.fd == listen_sock) { 867 | #else 868 | for (int e = 0; e < nfds; e++) if (pollfds[e].revents & POLLIN) { 869 | if (pollfds[e].fd == listen_sock) { 870 | #endif 871 | /* *** Handle incoming data from the clients *** */ 872 | struct sockaddr_in sender_addr = {0}; 873 | socklen_t sender_addr_len = sizeof(sender_addr); 874 | int length = recvfrom(listen_sock, buffer, BUFFER_SIZE, 0, (struct sockaddr *)&sender_addr, &sender_addr_len); 875 | if (length < 0) { 876 | serror("recvfrom"); 877 | continue; 878 | } 879 | if (length < 4) { 880 | log(LL_DEBUG, "Received too short packet from %s:%d (%d bytes), ignoring", inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port), length); 881 | continue; 882 | } 883 | 884 | client_entry_t *client_entry; 885 | HASH_FIND(hh, conn_table, &sender_addr, sizeof(sender_addr), client_entry); 886 | 887 | uint8_t obfuscated = is_obfuscated(buffer); 888 | uint8_t version = OBFUSCATION_VERSION; 889 | 890 | if (verbose >= LL_TRACE) { 891 | log(LL_TRACE, "Received %d bytes from %s:%d to %s:%d (known=%s, obfuscated=%s)", 892 | length, 893 | inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port), 894 | target_host, target_port, 895 | client_entry ? "yes" : "no", obfuscated ? "yes" : "no"); 896 | if (obfuscated) { 897 | trace("X->: "); 898 | } else { 899 | trace("O->: "); 900 | } 901 | for (int i = 0; i < length; ++i) { 902 | trace("%02X ", buffer[i]); 903 | } 904 | trace("\n"); 905 | } 906 | 907 | if (obfuscated) { 908 | // decode 909 | length = decode(buffer, length, xor_key, key_length, &version); 910 | if (length < 4) { 911 | log(LL_ERROR, "Failed to decode packet from %s:%d (too short, length=%d)", 912 | inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port), length); 913 | continue; 914 | } 915 | } 916 | 917 | // Is it handshake? 918 | if (*((uint32_t*)buffer) == WG_TYPE_HANDSHAKE) { 919 | log(LL_DEBUG, "Received WireGuard handshake from %s:%d to %s:%d (%d bytes, obfuscated=%s)", 920 | inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port), 921 | target_host, target_port, 922 | length, 923 | obfuscated ? "yes" : "no"); 924 | 925 | if (!client_entry) { 926 | client_entry = new_client_entry(&sender_addr, &forward_addr); 927 | if (!client_entry) { 928 | continue; 929 | } 930 | client_entry->version = version; 931 | if (version < OBFUSCATION_VERSION) { 932 | log(LL_WARN, "Client %s:%d uses old obfuscation version, downgrading from %d to %d", inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port), 933 | OBFUSCATION_VERSION, version); 934 | } 935 | } 936 | 937 | client_entry->handshake_direction = HANDSHAKE_DIRECTION_CLIENT_TO_SERVER; 938 | client_entry->last_handshake_request_time = now; 939 | } 940 | // Is it handshake response? 941 | else if (*((uint32_t*)buffer) == WG_TYPE_HANDSHAKE_RESP) { 942 | if (!client_entry) { 943 | log(LL_DEBUG, "Received WireGuard handshake response from %s:%d, but no connection entry found for this client", 944 | inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port)); 945 | continue; 946 | } 947 | 948 | log(LL_DEBUG, "Received WireGuard handshake response from %s:%d to %s:%d (%d bytes, obfuscated=%s)", 949 | inet_ntoa(client_entry->client_addr.sin_addr), ntohs(client_entry->client_addr.sin_port), 950 | target_host, target_port, 951 | length, obfuscated ? "yes" : "no"); 952 | 953 | // Check handshake timeout 954 | if (now - client_entry->last_handshake_request_time > HANDSHAKE_TIMEOUT) { 955 | log(LL_DEBUG, "Ignoring WireGuard handshake response, handshake timeout"); 956 | continue; 957 | } 958 | 959 | if (client_entry->handshake_direction != HANDSHAKE_DIRECTION_SERVER_TO_CLIENT) { 960 | log(LL_DEBUG, "Received handshake response from %s:%d to %s:%d, but the handshake direction is not set to server-to-client", 961 | inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port), 962 | target_host, target_port); 963 | continue;; 964 | } 965 | 966 | log(!client_entry->handshaked ? LL_INFO : LL_DEBUG, "Handshake established with %s:%d to %s:%d (reverse)", 967 | inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port), 968 | target_host, target_port); 969 | client_entry->handshaked = 1; 970 | client_entry->last_handshake_time = now; 971 | } 972 | // If it's not a handshake or handshake response, connection is not established yet 973 | else if (!client_entry || !client_entry->handshaked) { 974 | log(LL_DEBUG, "Ignoring data from %s:%d to %s:%d until the handshake is completed", 975 | inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port), 976 | target_host, target_port); 977 | continue; 978 | } 979 | 980 | if (!obfuscated) { 981 | // If the packet is not obfuscated, we need to encode it 982 | length = encode(buffer, length, xor_key, key_length, client_entry->version); 983 | if (length < 4) { 984 | log(LL_ERROR, "Failed to encode packet from %s:%d (too short, length=%d)", 985 | inet_ntoa(sender_addr.sin_addr), ntohs(sender_addr.sin_port), length); 986 | continue; 987 | } 988 | } 989 | 990 | if (verbose >= LL_TRACE) { 991 | if (!obfuscated) { 992 | trace("X->: "); 993 | } else { 994 | trace("O->: "); 995 | } 996 | for (int i = 0; i < length; ++i) { 997 | trace("%02X ", buffer[i]); 998 | } 999 | trace("\n"); 1000 | } 1001 | 1002 | sendto(client_entry->server_sock, buffer, length, 0, (struct sockaddr *)&forward_addr, sizeof(forward_addr)); 1003 | client_entry->last_activity_time = now; 1004 | } else { // if (event->data.fd == listen_sock) 1005 | /* *** Handle data from the server *** */ 1006 | #ifdef USE_EPOLL 1007 | client_entry_t *client_entry = event->data.ptr; 1008 | #else 1009 | client_entry_t *client_entry = find_by_server_sock(pollfds[e].fd); 1010 | #endif 1011 | int length = recv(client_entry->server_sock, buffer, BUFFER_SIZE, 0); 1012 | if (length < 0) { 1013 | serror("recv"); 1014 | continue; 1015 | } 1016 | if (length < 4) { 1017 | log(LL_DEBUG, "Received too short packet from %s:%d (%d bytes), ignoring", target_host, target_port, length); 1018 | continue; 1019 | } 1020 | 1021 | uint8_t obfuscated = is_obfuscated(buffer); 1022 | 1023 | if (verbose >= LL_TRACE) { 1024 | log(LL_TRACE, "Received %d bytes from %s:%d to %s:%d (obfuscated=%s)", 1025 | length, 1026 | target_host, target_port, 1027 | inet_ntoa(client_entry->client_addr.sin_addr), ntohs(client_entry->client_addr.sin_port), 1028 | obfuscated ? "yes" : "no"); 1029 | if (obfuscated) { 1030 | trace("<-X: "); 1031 | } else { 1032 | trace("<-O: "); 1033 | } 1034 | for (int i = 0; i < length; ++i) { 1035 | trace("%02X ", buffer[i]); 1036 | } 1037 | trace("\n"); 1038 | } 1039 | 1040 | if (obfuscated) { 1041 | // decode 1042 | length = decode(buffer, length, xor_key, key_length, &client_entry->version); 1043 | if (length < 4) { 1044 | log(LL_ERROR, "Failed to decode packet from %s:%d", target_host, target_port); 1045 | continue; 1046 | } 1047 | } 1048 | 1049 | // Is it handshake? 1050 | if (*((uint32_t*)buffer) == WG_TYPE_HANDSHAKE) { 1051 | log(LL_DEBUG, "Received WireGuard handshake from %s:%d to %s:%d (%d bytes, obfuscated=%s)", 1052 | target_host, target_port, 1053 | inet_ntoa(client_entry->client_addr.sin_addr), ntohs(client_entry->client_addr.sin_port), 1054 | length, 1055 | obfuscated ? "yes" : "no"); 1056 | 1057 | client_entry->handshake_direction = HANDSHAKE_DIRECTION_SERVER_TO_CLIENT; 1058 | client_entry->last_handshake_request_time = now; 1059 | } 1060 | // Is it handshake response? 1061 | else if (*((uint32_t*)buffer) == WG_TYPE_HANDSHAKE_RESP) { 1062 | log(LL_DEBUG, "Received WireGuard handshake response from %s:%d to %s:%d (%d bytes, obfuscated=%s)", 1063 | target_host, target_port, 1064 | inet_ntoa(client_entry->client_addr.sin_addr), ntohs(client_entry->client_addr.sin_port), 1065 | length, obfuscated ? "yes" : "no"); 1066 | 1067 | // Check handshake timeout 1068 | if (now - client_entry->last_handshake_request_time > HANDSHAKE_TIMEOUT) { 1069 | log(LL_DEBUG, "Ignoring WireGuard handshake response, handshake timeout"); 1070 | continue; 1071 | } 1072 | 1073 | if (client_entry->handshake_direction != HANDSHAKE_DIRECTION_CLIENT_TO_SERVER) { 1074 | log(LL_DEBUG, "Received handshake response from %s:%d to %s:%d, but the handshake direction is not set to client-to-server", 1075 | target_host, target_port, 1076 | inet_ntoa(client_entry->client_addr.sin_addr), ntohs(client_entry->client_addr.sin_port)); 1077 | continue; 1078 | } 1079 | 1080 | log(!client_entry->handshaked ? LL_INFO : LL_DEBUG, "Handshake established with %s:%d to %s:%d (direct)", 1081 | inet_ntoa(client_entry->client_addr.sin_addr), ntohs(client_entry->client_addr.sin_port), 1082 | target_host, target_port); 1083 | client_entry->handshaked = 1; 1084 | client_entry->last_handshake_time = now; 1085 | } 1086 | // If it's not a handshake or handshake response, connection is not established yet 1087 | else if (!client_entry->handshaked) { 1088 | log(LL_DEBUG, "Ignoring response from %s:%d to %s:%d until the handshake is completed", 1089 | target_host, target_port, 1090 | inet_ntoa(client_entry->client_addr.sin_addr), ntohs(client_entry->client_addr.sin_port)); 1091 | continue; 1092 | } 1093 | 1094 | if (!obfuscated) { 1095 | // If the packet is not obfuscated, we need to encode it 1096 | length = encode(buffer, length, xor_key, key_length, client_entry->version); 1097 | if (length < 4) { 1098 | log(LL_ERROR, "Failed to encode packet from %s:%d", target_host, target_port); 1099 | continue; 1100 | } 1101 | } 1102 | 1103 | if (verbose >= LL_TRACE) { 1104 | if (!obfuscated) { 1105 | trace("<-X: "); 1106 | } else { 1107 | trace("<-O: "); 1108 | } 1109 | for (int i = 0; i < length; ++i) { 1110 | trace("%02X ", buffer[i]); 1111 | } 1112 | trace("\n"); 1113 | } 1114 | 1115 | // Send the response back to the original client 1116 | sendto(listen_sock, buffer, length, 0, (struct sockaddr *)&client_entry->client_addr, sizeof(client_entry->client_addr)); 1117 | client_entry->last_activity_time = now; 1118 | } // if (event->data.fd != listen_sock) 1119 | } // for (int e = 0; e < events_n; e++) 1120 | 1121 | /* *** Cleanup old entries *** */ 1122 | if (now - last_cleanup_time >= CLEANUP_INTERVAL) { 1123 | client_entry_t *current_entry, *tmp; 1124 | // Iterate over all client entries 1125 | HASH_ITER(hh, conn_table, current_entry, tmp) { 1126 | // Check if the entry is idle for too long 1127 | if ( 1128 | ( 1129 | (now - current_entry->last_activity_time >= IDLE_TIMEOUT) 1130 | || (!current_entry->handshaked && (now - current_entry->last_handshake_request_time >= HANDSHAKE_TIMEOUT)) 1131 | ) && !current_entry->is_static // Do not remove static entries 1132 | ) { 1133 | log(LL_INFO, "Removing idle client %s:%d", inet_ntoa(current_entry->client_addr.sin_addr), ntohs(current_entry->client_addr.sin_port)); 1134 | #ifdef USE_EPOLL 1135 | epoll_ctl(epfd, EPOLL_CTL_DEL, current_entry->server_sock, NULL); 1136 | #endif 1137 | close(current_entry->server_sock); 1138 | HASH_DEL(conn_table, current_entry); 1139 | free(current_entry); 1140 | } 1141 | } 1142 | // Update the last cleanup time 1143 | last_cleanup_time = now; 1144 | } 1145 | } // while (1) 1146 | 1147 | // You should never reach this point, but just in case 1148 | return 0; 1149 | } 1150 | -------------------------------------------------------------------------------- /wg-obfuscator.conf: -------------------------------------------------------------------------------- 1 | # Instance name 2 | [main] 3 | 4 | # Uncomment to bind source socket to a specific interface 5 | # source-if = 0.0.0.0 6 | 7 | # Port to listen for the source client (real client or client obfuscator) 8 | source-lport = 13255 9 | 10 | # Host and port of the target to forward to (server obfuscator or real server) 11 | target = 10.13.1.100:13255 12 | 13 | # Obfuscation key, must be the same on both sides 14 | key = test 15 | 16 | # You can specify a static bindings for two-way mode (when the server is also a client) 17 | # This is useful when both WireGuard server and client have a public static IP 18 | # The format is comma-separated list of ::, 19 | # where is the IP of the client, is the UDP port of the client, 20 | # and is the local UDP port used by connections to the server, 21 | # e.g. UDP port to which the server should send packets. 22 | # Spaces are allowed around the commas. 23 | # 24 | # static-bindings = 1.2.3.4:12883:6670, 5.6.7.8:12083:6679 25 | 26 | # Verbosity level (0 - 4) 27 | # 0 - ERRORS (critical errors only) 28 | # 1 - WARNINGS (important messages: startup and shutdown messages) 29 | # 2 - INFO (informational messages: status messages, connection established, etc.) 30 | # 3 - DEBUG (detailed debug messages) 31 | # 4 - TRACE (very detailed debug messages, including packet dumps) 32 | verbose = 2 33 | 34 | # You can specify multiple instances 35 | # [second_server] 36 | # source-if = 0.0.0.0 37 | # source-lport = 13255 38 | # target = 10.13.1.100:13255 39 | # key = test 40 | # static-bindings = 1.2.3.4:12883:6670, 5.6.7.8:12083:6679 41 | # verbose = 2 42 | -------------------------------------------------------------------------------- /wg-obfuscator.h: -------------------------------------------------------------------------------- 1 | #ifndef _WG_OBFUSCATOR_H_ 2 | #define _WG_OBFUSCATOR_H_ 3 | 4 | // on Linux, use epoll for better performance 5 | #ifdef __linux__ 6 | #define USE_EPOLL 7 | #endif 8 | 9 | #include 10 | #include "uthash.h" 11 | 12 | #ifdef USE_EPOLL 13 | #include 14 | #define MAX_EVENTS 1024 15 | #else 16 | #include 17 | #endif 18 | 19 | #define WG_OBFUSCATOR_VERSION "1.1" 20 | #define WG_OBFUSCATOR_GIT_REPO "https://github.com/ClusterM/wg-obfuscator" 21 | 22 | // Logging levels 23 | #define LL_ERROR 0 24 | #define LL_WARN 1 25 | #define LL_INFO 2 26 | #define LL_DEBUG 3 27 | #define LL_TRACE 4 28 | 29 | // Main parameters 30 | // TODO: make these configurable via command line arguments or config file 31 | #define BUFFER_SIZE 8*1024 // size of the buffer for receiving data from the clients and server 32 | #define POLL_TIMEOUT 5000 // in milliseconds 33 | #define HANDSHAKE_TIMEOUT 5000 // in milliseconds 34 | #define MAX_CLIENTS 1024 // maximum number of clients 35 | #define CLEANUP_INTERVAL 15000 // in milliseconds 36 | #define IDLE_TIMEOUT 300000 // in milliseconds 37 | #define MAX_DUMMY_LENGTH_TOTAL 1024 // maximum length of a packet after dummy data extension 38 | #define MAX_DUMMY_LENGTH_HANDSHAKE 512 // maximum length of dummy data for handshake packets 39 | #define MAX_DUMMY_LENGTH_DATA 4 // maximum length of dummy data for data packets 40 | 41 | // WireGuard packet types 42 | #define WG_TYPE_HANDSHAKE 0x01 43 | #define WG_TYPE_HANDSHAKE_RESP 0x02 44 | #define WG_TYPE_COOKIE 0x03 45 | #define WG_TYPE_DATA 0x04 46 | 47 | // Handshake directions 48 | #define HANDSHAKE_DIRECTION_CLIENT_TO_SERVER 0 49 | #define HANDSHAKE_DIRECTION_SERVER_TO_CLIENT 1 50 | 51 | // Current obfuscation version 52 | #define OBFUSCATION_VERSION 1 53 | #define DEFAULT_INSTANCE_NAME "main" 54 | 55 | // Structure to hold client connection information 56 | typedef struct { 57 | struct sockaddr_in client_addr; // client address and port (key for the hash table) 58 | struct sockaddr_in our_addr; // our address and port on the server connection 59 | long last_activity_time; // last time we received data from/to this client 60 | long last_handshake_request_time; // last time we received a handshake request from/to this client 61 | long last_handshake_time; // last time we received a handshake response from/to this client 62 | int server_sock; // socket for the connection to the server 63 | uint8_t version; // obfuscation version 64 | uint8_t handshaked : 1; // 1 if the client has completed the handshake, 0 otherwise 65 | uint8_t handshake_direction : 1; // 1 if the handshake is from client to server, 0 if from server to client 66 | uint8_t is_static : 1; // 1 if this is a static binding entry, 0 otherwise 67 | UT_hash_handle hh; 68 | } client_entry_t; 69 | 70 | #endif 71 | -------------------------------------------------------------------------------- /wg-obfuscator.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=WireGuard Obfuscator 3 | After=network.target 4 | 5 | [Service] 6 | ExecStart=wg-obfuscator -c /etc/wg-obfuscator.conf 7 | StandardOutput=inherit 8 | StandardError=inherit 9 | Restart=always 10 | RestartSec=10 11 | User=root 12 | 13 | [Install] 14 | WantedBy=multi-user.target 15 | --------------------------------------------------------------------------------