├── .github ├── FUNDING.yml └── workflows │ ├── Benchmark.yml │ ├── Deploy.yml │ ├── Documentation.yml │ ├── Tests.yml │ ├── iOS.yml │ ├── tvOS.yml │ ├── visionOS.yml │ └── watchOS.yml ├── .gitignore ├── .mailmap ├── Benchmarks └── Memory │ └── Dockerfile ├── LICENSE ├── NOTICE ├── Package.swift ├── README.md ├── Scripts ├── Package └── TestAll ├── Snippets └── FirewallUsage.swift └── Sources ├── FirewallPrefabricator ├── Array (ext).swift ├── IP.Firewall.Image (ext).swift ├── JSONDecodable (ext).swift └── Main.swift ├── FirewallTests ├── Bisection.swift └── Roundtripping.swift ├── Firewalls ├── IP.AS.Metadata.swift ├── IP.AS.swift ├── IP.ASN.swift ├── IP.Claimant.swift ├── IP.Firewall.Image.swift ├── IP.Firewall.swift ├── IP.Table.SortedArray.IntervalError.swift ├── IP.Table.SortedArray.swift └── IP.Table.swift ├── IP ├── IP.Address.swift ├── IP.Block.swift ├── IP.V4.swift ├── IP.V6.swift ├── IP.swift └── docs.docc │ └── IP.md ├── IPTests ├── Mapping.swift ├── Masking.swift └── Parsing.swift ├── IP_BSON ├── IP.Address (ext).swift ├── IP.V4 (ext).swift └── IP.V6 (ext).swift ├── IP_NIOCore ├── IP.V4 (ext).swift ├── IP.V6 (ext).swift └── docs.docc │ └── IP_NIOCore.md ├── IPinfo ├── IPinfo.ASN.swift ├── IPinfo.ASNRange.swift ├── IPinfo.Address.swift ├── IPinfo.CountryRange.swift ├── IPinfo.swift └── ISO.Country (ext).swift └── Whitelists ├── GitHubWhitelist.swift ├── IP.AnyCIDR.swift ├── IP.Block (ext).swift ├── IP.Claims.swift └── SearchbotWhitelist.swift /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [tayloraswift] 2 | -------------------------------------------------------------------------------- /.github/workflows/Benchmark.yml: -------------------------------------------------------------------------------- 1 | name: benchmark 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | linux: 11 | runs-on: ubuntu-24.04 12 | name: memory consumption 13 | steps: 14 | - name: Checkout repository 15 | uses: actions/checkout@v3 16 | 17 | - name: Build environment 18 | run: | 19 | docker build -f Benchmarks/Memory/Dockerfile -t benchmark . 20 | 21 | - name: Build test application 22 | run: | 23 | docker run --rm -v=$PWD:/swift -w=/swift \ 24 | benchmark \ 25 | swift build -c release --product FirewallUsage 26 | 27 | - name: Build firewall 28 | run: | 29 | docker run --rm -v=$PWD:/swift -w=/swift \ 30 | -e IPINFO_TOKEN=${{ secrets.IPINFO_TOKEN }} \ 31 | benchmark \ 32 | Scripts/Package 33 | 34 | - name: Run test application (300MB memory limit) 35 | run: | 36 | docker run --rm -v=$PWD:/swift -w=/swift \ 37 | --memory-swap 300m \ 38 | --memory 300m \ 39 | -e LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2 \ 40 | benchmark \ 41 | .build/release/FirewallUsage 66.249.66.169 42 | 43 | - name: Run test application (200MB memory limit) 44 | run: | 45 | docker run --rm -v=$PWD:/swift -w=/swift \ 46 | --memory-swap 200m \ 47 | --memory 200m \ 48 | -e LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2 \ 49 | benchmark \ 50 | .build/release/FirewallUsage 66.249.66.169 51 | 52 | - name: Run test application (160MB memory limit) 53 | run: | 54 | docker run --rm -v=$PWD:/swift -w=/swift \ 55 | --memory-swap 160m \ 56 | --memory 160m \ 57 | -e LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2 \ 58 | benchmark \ 59 | .build/release/FirewallUsage 66.249.66.169 60 | -------------------------------------------------------------------------------- /.github/workflows/Deploy.yml: -------------------------------------------------------------------------------- 1 | name: deploy 2 | 3 | on: 4 | # Enable manual deployment 5 | workflow_dispatch: 6 | # This runs on the 37th minute of every hour, which is a random number we choose to 7 | # avoid peak minutes around :00 and :30 8 | schedule: 9 | - cron: "37 * * * *" 10 | 11 | jobs: 12 | linux: 13 | runs-on: ubuntu-24.04 14 | name: Ubuntu 24.04 15 | steps: 16 | - name: Setup AWS CLI 17 | uses: aws-actions/configure-aws-credentials@v1 18 | with: 19 | aws-secret-access-key: ${{ secrets.AWS_S3_ACCESS_SECRET }} 20 | aws-access-key-id: ${{ vars.AWS_S3_ACCESS_KEY }} 21 | aws-region: us-east-1 22 | 23 | - name: Install Swift 24 | uses: tayloraswift/swift-install-action@master 25 | with: 26 | swift-prefix: "swift-6.0.3-release/ubuntu2404/swift-6.0.3-RELEASE" 27 | swift-id: "swift-6.0.3-RELEASE-ubuntu24.04" 28 | 29 | - name: Checkout repository 30 | uses: actions/checkout@v3 31 | 32 | - name: Build products 33 | env: 34 | IPINFO_TOKEN: ${{ secrets.IPINFO_TOKEN }} 35 | run: Scripts/Package 36 | 37 | - name: Test firewall 38 | run: swift run -c release FirewallUsage 98.223.208.128 39 | 40 | - name: Upload firewall 41 | run: | 42 | aws s3 cp firewall.bson.gz s3://swiftinit/ip/firewall.bson.gz \ 43 | --content-encoding gzip \ 44 | --content-type application/bson 45 | -------------------------------------------------------------------------------- /.github/workflows/Documentation.yml: -------------------------------------------------------------------------------- 1 | # This workflow validates the package’s documentation. Because documentation building involves 2 | # compiling the package, this also checks that the package itself compiles successfully on each 3 | # supported platform. 4 | name: documentation 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | linux: 14 | runs-on: ubuntu-24.04 15 | name: Ubuntu 24.04 16 | 17 | steps: 18 | - name: Install Swift 19 | uses: tayloraswift/swift-install-action@master 20 | with: 21 | swift-prefix: "swift-6.0.3-release/ubuntu2404/swift-6.0.3-RELEASE" 22 | swift-id: "swift-6.0.3-RELEASE-ubuntu24.04" 23 | 24 | - name: Install Unidoc 25 | uses: tayloraswift/swift-unidoc-action@master 26 | 27 | # This clobbers everything in the current directory! 28 | - name: Checkout repository 29 | uses: actions/checkout@v3 30 | 31 | - name: Validate documentation 32 | run: | 33 | unidoc compile \ 34 | --swift-toolchain $SWIFT_INSTALLATION \ 35 | --ci fail-on-errors \ 36 | --project-path . 37 | 38 | macos: 39 | runs-on: macos-15 40 | name: macOS 41 | steps: 42 | - name: Install Unidoc 43 | uses: tayloraswift/swift-unidoc-action@master 44 | 45 | - name: Checkout repository 46 | uses: actions/checkout@v3 47 | 48 | - name: Validate documentation 49 | run: | 50 | unidoc compile \ 51 | --ci fail-on-errors \ 52 | --project-path . 53 | -------------------------------------------------------------------------------- /.github/workflows/Tests.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | linux: 11 | runs-on: ubuntu-24.04 12 | name: Ubuntu 24.04 13 | steps: 14 | - name: Install Swift 15 | uses: tayloraswift/swift-install-action@master 16 | with: 17 | swift-prefix: "swift-6.0.3-release/ubuntu2404/swift-6.0.3-RELEASE" 18 | swift-id: "swift-6.0.3-RELEASE-ubuntu24.04" 19 | 20 | - name: Checkout repository 21 | uses: actions/checkout@v3 22 | 23 | - name: Run tests 24 | run: Scripts/TestAll 25 | 26 | macos: 27 | runs-on: macos-15 28 | name: macOS 29 | steps: 30 | - name: Checkout repository 31 | uses: actions/checkout@v3 32 | 33 | - name: Run tests 34 | run: Scripts/TestAll 35 | -------------------------------------------------------------------------------- /.github/workflows/iOS.yml: -------------------------------------------------------------------------------- 1 | name: iOS 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | uses: tayloraswift/swift-device-action/.github/workflows/build.yml@master 12 | with: 13 | xcode-scheme: 'swift-ip-Package' 14 | destination: ${{ github.workflow }} 15 | -------------------------------------------------------------------------------- /.github/workflows/tvOS.yml: -------------------------------------------------------------------------------- 1 | name: tvOS 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | uses: tayloraswift/swift-device-action/.github/workflows/build.yml@master 12 | with: 13 | xcode-scheme: 'swift-ip-Package' 14 | destination: ${{ github.workflow }} 15 | -------------------------------------------------------------------------------- /.github/workflows/visionOS.yml: -------------------------------------------------------------------------------- 1 | name: visionOS 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | uses: tayloraswift/swift-device-action/.github/workflows/build.yml@master 12 | with: 13 | xcode-scheme: 'swift-ip-Package' 14 | destination: ${{ github.workflow }} 15 | -------------------------------------------------------------------------------- /.github/workflows/watchOS.yml: -------------------------------------------------------------------------------- 1 | name: watchOS 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | uses: tayloraswift/swift-device-action/.github/workflows/build.yml@master 12 | with: 13 | xcode-scheme: 'swift-ip-Package' 14 | destination: ${{ github.workflow }} 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .ssgc 2 | .build 3 | .build.ssgc 4 | 5 | *.json 6 | *.json.gz 7 | *.bson 8 | *.bson.gz 9 | 10 | Package.resolved 11 | -------------------------------------------------------------------------------- /.mailmap: -------------------------------------------------------------------------------- 1 | Dianna 2 | -------------------------------------------------------------------------------- /Benchmarks/Memory/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM swift:6.0.3-noble 2 | 3 | RUN apt update 4 | RUN apt -y install libjemalloc2 curl gzip 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2024 191 | Dianna Ma (@taylorswift, @tayloraswift) 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | the `swift-ip` package was created by dianna ma (@taylorswift). 2 | 3 | you are welcome to contribute to this project at: 4 | 5 | https://github.com/tayloraswift/swift-ip 6 | 7 | we do not maintain any other mirrors of this repository, and such 8 | forks of this repository may not carry the most up-to-date code. 9 | 10 | contributors: 11 | 12 | 1. dianna ma (@taylorswift, 2024) 13 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:6.0 2 | import PackageDescription 3 | 4 | let package:Package = .init( 5 | name: "swift-ip", 6 | platforms: [.macOS(.v15), .iOS(.v18), .tvOS(.v18), .visionOS(.v2), .watchOS(.v11)], 7 | products: [ 8 | .library(name: "Firewalls", targets: ["Firewalls"]), 9 | 10 | .library(name: "IP", targets: ["IP"]), 11 | .library(name: "IP_BSON", targets: ["IP_BSON"]), 12 | .library(name: "IP_NIOCore", targets: ["IP_NIOCore"]), 13 | 14 | .library(name: "IPinfo", targets: ["IPinfo"]), 15 | ], 16 | dependencies: [ 17 | .package(url: "https://github.com/tayloraswift/swift-bson", from: "1.0.0"), 18 | .package(url: "https://github.com/tayloraswift/swift-json", from: "1.1.2"), 19 | 20 | .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"), 21 | .package(url: "https://github.com/apple/swift-nio", from: "2.75.0"), 22 | ], 23 | targets: [ 24 | .executableTarget(name: "FirewallPrefabricator", 25 | dependencies: [ 26 | .target(name: "IPinfo"), 27 | .target(name: "Whitelists"), 28 | .product(name: "ArgumentParser", package: "swift-argument-parser"), 29 | ]), 30 | 31 | .target(name: "Firewalls", 32 | dependencies: [ 33 | .target(name: "IP"), 34 | .target(name: "IP_BSON"), 35 | .product(name: "BSON_ISO", package: "swift-bson"), 36 | ]), 37 | 38 | .target(name: "IP"), 39 | 40 | .target(name: "IP_BSON", 41 | dependencies: [ 42 | .target(name: "IP"), 43 | .product(name: "BSON", package: "swift-bson"), 44 | ]), 45 | 46 | .target(name: "IP_NIOCore", 47 | dependencies: [ 48 | .target(name: "IP"), 49 | .product(name: "NIOCore", package: "swift-nio"), 50 | ]), 51 | 52 | .target(name: "IPinfo", 53 | dependencies: [ 54 | .target(name: "Firewalls"), 55 | .product(name: "JSON", package: "swift-json"), 56 | ]), 57 | 58 | .target(name: "Whitelists", 59 | dependencies: [ 60 | .target(name: "Firewalls"), 61 | .product(name: "JSON", package: "swift-json"), 62 | ]), 63 | 64 | .testTarget(name: "FirewallTests", dependencies: ["Firewalls"]), 65 | .testTarget(name: "IPTests", dependencies: ["IP"]), 66 | ]) 67 | 68 | for target:PackageDescription.Target in package.targets 69 | { 70 | { 71 | var settings:[PackageDescription.SwiftSetting] = $0 ?? [] 72 | 73 | settings.append(.enableUpcomingFeature("ExistentialAny")) 74 | settings.append(.enableExperimentalFeature("StrictConcurrency")) 75 | 76 | $0 = settings 77 | } (&target.swiftSettings) 78 | } 79 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | ***`ip`*** 4 | 5 | [![Tests](https://github.com/tayloraswift/swift-ip/actions/workflows/Tests.yml/badge.svg)](https://github.com/tayloraswift/swift-ip/actions/workflows/Tests.yml) 6 | [![Deploy](https://github.com/tayloraswift/swift-ip/actions/workflows/Deploy.yml/badge.svg)](https://github.com/tayloraswift/swift-ip/actions/workflows/Deploy.yml) 7 | [![Documentation](https://github.com/tayloraswift/swift-ip/actions/workflows/Documentation.yml/badge.svg)](https://github.com/tayloraswift/swift-ip/actions/workflows/Documentation.yml) 8 | 9 |
10 | 11 | The ***swift-ip*** library is a portable, Foundation-free library for working with IP addresses. It provides tools for parsing and formatting IP addresses, data structures for performing efficient IP address lookups, and shims for compatibility with types from other libraries such as SwiftNIO. 12 | 13 | One of the goals of this library is to allow other libraries to exchange strongly-typed values with zero overhead without falling back to raw integer representations or linking against large frameworks. 14 | 15 |
16 | 17 | [documentation](https://swiftinit.org/docs/swift-ip/ip) · 18 | [license](LICENSE) 19 | 20 |
21 | 22 | 23 | ## Requirements 24 | 25 | The swift-ip library requires Swift 6.0 or later. This is because [`IP.V6`](https://swiftinit.org/docs/swift-ip/ip/ip/v6) uses [`UInt128`](https://swiftinit.org/docs/swift/swift/uint128). 26 | 27 | 28 | | Platform | Status | 29 | | -------- | ------ | 30 | | 🐧 Linux | [![Tests](https://github.com/tayloraswift/swift-ip/actions/workflows/Tests.yml/badge.svg)](https://github.com/tayloraswift/swift-ip/actions/workflows/Tests.yml) | 31 | | 🍏 Darwin | [![Tests](https://github.com/tayloraswift/swift-ip/actions/workflows/Tests.yml/badge.svg)](https://github.com/tayloraswift/swift-ip/actions/workflows/Tests.yml) | 32 | | 🍏 Darwin (iOS) | [![iOS](https://github.com/tayloraswift/swift-ip/actions/workflows/iOS.yml/badge.svg)](https://github.com/tayloraswift/swift-ip/actions/workflows/iOS.yml) | 33 | | 🍏 Darwin (tvOS) | [![tvOS](https://github.com/tayloraswift/swift-ip/actions/workflows/tvOS.yml/badge.svg)](https://github.com/tayloraswift/swift-ip/actions/workflows/tvOS.yml) | 34 | | 🍏 Darwin (visionOS) | [![visionOS](https://github.com/tayloraswift/swift-ip/actions/workflows/visionOS.yml/badge.svg)](https://github.com/tayloraswift/swift-ip/actions/workflows/visionOS.yml) | 35 | | 🍏 Darwin (watchOS) | [![watchOS](https://github.com/tayloraswift/swift-ip/actions/workflows/watchOS.yml/badge.svg)](https://github.com/tayloraswift/swift-ip/actions/workflows/watchOS.yml) | 36 | 37 | 38 | [Check deployment minimums](https://swiftinit.org/docs/swift-ip#ss:platform-requirements) 39 | 40 | 41 | ## Why use swift-ip? 42 | 43 | The IP address types defined by the `Network` framework are Darwin-only, which precludes their use in server-side code. 44 | 45 | The swift-nio library provides a multi-platform [`SocketAddress`](https://swiftinit.org/docs/swift-nio/niocore/socketaddress) type, but it is heap-allocated and reference-counted, and requires linking against the entire `NIOCore` module. This makes it unsuitable as a high-performance currency type for purposes such as firewall implementations or metrics collection. 46 | 47 | 48 | ## Who is using swift-ip? 49 | 50 | The [Swiftinit](https://swiftinit.org) documentation index currently uses the swift-ip library to verify clients (such as Googlebot and GitHub Webhooks) and combat abuse. 51 | 52 | 53 | ## License 54 | 55 | The swift-ip library is Apache 2.0 licensed. 56 | -------------------------------------------------------------------------------- /Scripts/Package: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | swift --version 5 | 6 | swift build -c release \ 7 | --explicit-target-dependency-import-check=error \ 8 | --target FirewallPrefabricator 9 | 10 | # If JSON files are not present, download them from ipinfo.io 11 | for file in asn country ; do 12 | if [ ! -f $file.json ]; then 13 | if [ -z "$IPINFO_TOKEN" ]; then 14 | echo "error: IPINFO_TOKEN is not set" 15 | exit 1 16 | fi 17 | 18 | # Must follow redirects to get the actual file 19 | curl -L https://ipinfo.io/data/free/$file.json.gz?token=$IPINFO_TOKEN -o $file.json.gz 20 | gzip -d $file.json.gz 21 | else 22 | echo "Using existing $file.json" 23 | fi 24 | done 25 | 26 | if [ ! -f googlebot.json ]; then 27 | curl -L https://developers.google.com/static/search/apis/ipranges/googlebot.json \ 28 | -o googlebot.json 29 | else 30 | echo "Using existing googlebot.json" 31 | fi 32 | 33 | if [ ! -f bingbot.json ]; then 34 | curl -L https://www.bing.com/toolbox/bingbot.json \ 35 | -o bingbot.json 36 | else 37 | echo "Using existing bingbot.json" 38 | fi 39 | 40 | if [ ! -f github.json ]; then 41 | curl -L https://api.github.com/meta \ 42 | -o github.json 43 | else 44 | echo "Using existing github.json" 45 | fi 46 | 47 | 48 | swift run -c release FirewallPrefabricator \ 49 | --country country.json \ 50 | --asn asn.json \ 51 | --googlebot googlebot.json \ 52 | --bingbot bingbot.json \ 53 | --github github.json \ 54 | --output firewall.bson \ 55 | 56 | gzip -kf9 firewall.bson 57 | -------------------------------------------------------------------------------- /Scripts/TestAll: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | swift --version 5 | 6 | swift build -c release \ 7 | --explicit-target-dependency-import-check=error \ 8 | --build-tests 9 | 10 | swift test -c release \ 11 | --explicit-target-dependency-import-check=error \ 12 | --skip-build 13 | -------------------------------------------------------------------------------- /Snippets/FirewallUsage.swift: -------------------------------------------------------------------------------- 1 | #if canImport(FoundationEssentials) 2 | import FoundationEssentials 3 | #else 4 | import Foundation 5 | #endif 6 | 7 | import BSON 8 | import Firewalls 9 | import IP 10 | import ISO 11 | 12 | guard CommandLine.arguments.count == 2 13 | else 14 | { 15 | fatalError("Usage: \(CommandLine.arguments[0]) ") 16 | } 17 | 18 | let ip:IP.V6 19 | 20 | if let ipv4:IP.V4 = .init(CommandLine.arguments[1]) 21 | { 22 | ip = .init(v4: ipv4) 23 | } 24 | else if let ipv6:IP.V6 = .init(CommandLine.arguments[1]) 25 | { 26 | ip = ipv6 27 | } 28 | else 29 | { 30 | fatalError("Invalid IP address") 31 | } 32 | 33 | // snippet.LOAD_FIREWALL 34 | let data:Data = try .init(contentsOf: URL.init(fileURLWithPath: "firewall.bson")) 35 | let bson:BSON.Document = .init(bytes: [UInt8].init(data)[...]) 36 | 37 | let firewall:IP.Firewall = .load(from: try IP.Firewall.Image.init(bson: bson)) 38 | 39 | // snippet.LOOKUP_COUNTRY 40 | let country:ISO.Country? = firewall.country[v6: ip] 41 | // snippet.end 42 | if let country:ISO.Country 43 | { 44 | print("Country: \(country)") 45 | } 46 | 47 | // snippet.LOOKUP_ASN 48 | let (system, claimant):(IP.AS?, IP.Claimant?) = firewall.lookup(v6: ip) 49 | // snippet.end 50 | if let system:IP.AS 51 | { 52 | print(""" 53 | ASN: \(system.number) 54 | AS: \(system.domain) (\(system.name)) 55 | """) 56 | } 57 | 58 | if let claimant:IP.Claimant 59 | { 60 | print(""" 61 | Claimant: \(claimant) 62 | """) 63 | } 64 | -------------------------------------------------------------------------------- /Sources/FirewallPrefabricator/Array (ext).swift: -------------------------------------------------------------------------------- 1 | import JSON 2 | 3 | extension Array where Element:JSONDecodable 4 | { 5 | static func splitting(_ file:String, where delimiter:(Character) -> Bool) throws -> Self 6 | { 7 | var i:String.Index = file.startIndex 8 | var elements:Self = [] 9 | 10 | while let j:String.Index = file[i...].firstIndex(where: delimiter) 11 | { 12 | let json:JSON = .init(utf8: [UInt8].init(file[i ..< j].utf8)[...]) 13 | elements.append(try json.decode()) 14 | i = file.index(after: j) 15 | } 16 | if i != file.endIndex 17 | { 18 | // JSON is missing trailing newline 19 | let json:JSON = .init(utf8: [UInt8].init(file[i...].utf8)[...]) 20 | elements.append(try json.decode()) 21 | } 22 | 23 | return elements 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Sources/FirewallPrefabricator/IP.Firewall.Image (ext).swift: -------------------------------------------------------------------------------- 1 | import IP 2 | import IPinfo 3 | import ISO 4 | 5 | extension IP.Firewall.Image 6 | { 7 | static func build(from ranges:[IPinfo.ASNRange]) throws -> Self 8 | { 9 | var v4:[(IP.ASN, ip:ClosedRange)] 10 | var v6:[(IP.ASN, ip:ClosedRange)] 11 | 12 | let table:[IP.ASN: IP.AS] 13 | 14 | (as: table, v4: v4, v6: v6) = ranges.reduce(into: ([:], [], [])) 15 | { 16 | $0.as[$1.asn] = .init(number: $1.asn, domain: $1.domain, name: $1.name) 17 | 18 | if let first:IP.V4 = $1.first.v4, 19 | let last:IP.V4 = $1.last.v4 20 | { 21 | $0.v4.append(($1.asn, first ... last)) 22 | } 23 | else 24 | { 25 | $0.v6.append(($1.asn, $1.first ... $1.last)) 26 | } 27 | } 28 | 29 | v4.sort { $0.ip.lowerBound < $1.ip.lowerBound } 30 | v6.sort { $0.ip.lowerBound < $1.ip.lowerBound } 31 | 32 | var image:Self = .init(autonomousSystems: table.values.sorted { $0.number < $1.number }) 33 | try image.colorByASN(v4: v4, v6: v6) 34 | 35 | return image 36 | } 37 | 38 | mutating 39 | func colorByCountry(from ranges:[IPinfo.CountryRange]) throws 40 | { 41 | var v4:[(ISO.Country, ip:ClosedRange)] 42 | var v6:[(ISO.Country, ip:ClosedRange)] 43 | 44 | (v4: v4, v6: v6) = ranges.reduce(into: ([], [])) 45 | { 46 | if let first:IP.V4 = $1.first.v4, 47 | let last:IP.V4 = $1.last.v4 48 | { 49 | $0.v4.append(($1.country, first ... last)) 50 | } 51 | else 52 | { 53 | $0.v6.append(($1.country, $1.first ... $1.last)) 54 | } 55 | } 56 | 57 | v4.sort { $0.ip.lowerBound < $1.ip.lowerBound } 58 | v6.sort { $0.ip.lowerBound < $1.ip.lowerBound } 59 | 60 | try self.colorByCountry(v4: v4, v6: v6) 61 | } 62 | 63 | mutating 64 | func colorByClaimant(_ claims:[IP.Claims]) throws 65 | { 66 | var v4:[(IP.Claimant, ip:ClosedRange)] 67 | var v6:[(IP.Claimant, ip:ClosedRange)] 68 | 69 | (v4: v4, v6: v6) = claims.reduce(into: ([], [])) 70 | { 71 | for range:ClosedRange in $1.v4 72 | { 73 | $0.v4.append(($1.id, range)) 74 | } 75 | for range:ClosedRange in $1.v6 76 | { 77 | $0.v6.append(($1.id, range)) 78 | } 79 | } 80 | 81 | v4.sort { $0.ip.lowerBound < $1.ip.lowerBound } 82 | v6.sort { $0.ip.lowerBound < $1.ip.lowerBound } 83 | 84 | try self.colorByClaimant(v4: v4, v6: v6) 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /Sources/FirewallPrefabricator/JSONDecodable (ext).swift: -------------------------------------------------------------------------------- 1 | import JSON 2 | 3 | extension JSONDecodable 4 | { 5 | static func decode(parsing file:String) throws -> Self 6 | { 7 | let json:JSON = .init(utf8: [UInt8].init(file.utf8)[...]) 8 | return try json.decode() 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Sources/FirewallPrefabricator/Main.swift: -------------------------------------------------------------------------------- 1 | #if canImport(FoundationEssentials) 2 | import FoundationEssentials 3 | #else 4 | import Foundation 5 | #endif 6 | 7 | import ArgumentParser 8 | import BSON 9 | import Firewalls 10 | import IP 11 | import IPinfo 12 | import ISO 13 | import Whitelists 14 | 15 | @main 16 | struct Main:ParsableCommand 17 | { 18 | @Option( 19 | name: [.customLong("googlebot")], 20 | help: "Googlebot JSON file") 21 | var googlebot:String 22 | 23 | @Option( 24 | name: [.customLong("bingbot")], 25 | help: "Bingbot JSON file") 26 | var bingbot:String 27 | 28 | @Option( 29 | name: [.customLong("github")], 30 | help: "GitHub Metadata JSON file") 31 | var github:String 32 | 33 | @Option( 34 | name: [.customLong("country")], 35 | help: "IPinfo Countries JSON file") 36 | var country:String 37 | 38 | @Option( 39 | name: [.customLong("asn")], 40 | help: "IPinfo Autonomous Systems JSON file") 41 | var asn:String 42 | 43 | @Option( 44 | name: [.customLong("output"), .customShort("o")], 45 | help: "Output BSON file") 46 | var output:String 47 | } 48 | extension Main 49 | { 50 | func run() throws 51 | { 52 | var image:IP.Firewall.Image = try .build(from: try .splitting(try .init( 53 | contentsOf: URL.init(fileURLWithPath: self.asn), 54 | encoding: .utf8), 55 | where: \.isNewline)) 56 | 57 | try image.colorByCountry(from: try .splitting(try .init( 58 | contentsOf: URL.init(fileURLWithPath: self.country), 59 | encoding: .utf8), 60 | where: \.isNewline)) 61 | 62 | let googlebot:SearchbotWhitelist = try .decode(parsing: try .init( 63 | contentsOf: URL.init(fileURLWithPath: self.googlebot), 64 | encoding: .utf8)) 65 | 66 | let bingbot:SearchbotWhitelist = try .decode(parsing: try .init( 67 | contentsOf: URL.init(fileURLWithPath: self.bingbot), 68 | encoding: .utf8)) 69 | 70 | let github:GitHubWhitelist = try .decode(parsing: try .init( 71 | contentsOf: URL.init(fileURLWithPath: self.github), 72 | encoding: .utf8)) 73 | 74 | var claims:[IP.Claims] = [] 75 | 76 | googlebot.add(to: &claims, as: .google_common) 77 | bingbot.add(to: &claims, as: .microsoft_bingbot) 78 | github.add(to: &claims) 79 | 80 | try image.colorByClaimant(claims) 81 | 82 | let bson:BSON.Document = .init(encoding: image) 83 | 84 | print("Successfully built firewall image (\(bson.bytes.count / 1_000) KB)") 85 | 86 | try Data.init(bson.bytes).write(to: URL.init(fileURLWithPath: self.output)) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /Sources/FirewallTests/Bisection.swift: -------------------------------------------------------------------------------- 1 | import Firewalls 2 | import IP 3 | import ISO 4 | import Testing 5 | 6 | @Suite 7 | struct Bisection 8 | { 9 | @Test(arguments: [ 10 | [10 ... 19, 0 ... 9], 11 | [0 ... 10, 10 ... 10], 12 | [0 ... 10, 5 ... 10], 13 | [0 ... 10, 0 ... 10], 14 | [5 ... 15, 0 ... 10], 15 | ]) 16 | static func validation(_ ranges:[ClosedRange]) throws 17 | { 18 | var image:IP.Firewall.Image = .init(autonomousSystems: []) 19 | 20 | #expect(throws: (any Error).self) 21 | { 22 | try image.colorByCountry(v4: ranges.map { (.US, $0) }, v6: []) 23 | } 24 | } 25 | 26 | @Test 27 | static func bisection() throws 28 | { 29 | let empty:IP.Firewall = .load(from: .init(autonomousSystems: [])) 30 | 31 | #expect(empty.lookup(v6: 0) == (nil, nil)) 32 | 33 | var image:IP.Firewall.Image = .init(autonomousSystems: []) 34 | try image.colorByCountry( 35 | v4: [ 36 | (.US, 1 ... 10), 37 | (.GB, 11 ... 20), 38 | (.IL, 22 ... 30), 39 | ], 40 | v6: [ 41 | (.UA, 11 ... 20), 42 | ]) 43 | 44 | let firewall:IP.Firewall = .load(from: image) 45 | 46 | #expect(firewall.country[v6: 0] == nil) 47 | #expect(firewall.country[v6: 1] == nil) 48 | #expect(firewall.country[v6: 10] == nil) 49 | #expect(firewall.country[v6: 11] == .UA) 50 | #expect(firewall.country[v6: 19] == .UA) 51 | #expect(firewall.country[v6: 20] == .UA) 52 | #expect(firewall.country[v6: 21] == nil) 53 | 54 | #expect(firewall.country[v4: 0] == nil) 55 | #expect(firewall.country[v4: 1] == .US) 56 | #expect(firewall.country[v4: 9] == .US) 57 | #expect(firewall.country[v4: 10] == .US) 58 | #expect(firewall.country[v4: 11] == .GB) 59 | #expect(firewall.country[v4: 19] == .GB) 60 | #expect(firewall.country[v4: 20] == .GB) 61 | #expect(firewall.country[v4: 21] == nil) 62 | #expect(firewall.country[v4: 22] == .IL) 63 | #expect(firewall.country[v4: 30] == .IL) 64 | #expect(firewall.country[v4: 31] == nil) 65 | 66 | #expect(firewall.country[v6: .init(v4: 0)] == nil) 67 | #expect(firewall.country[v6: .init(v4: 1)] == .US) 68 | #expect(firewall.country[v6: .init(v4: 9)] == .US) 69 | #expect(firewall.country[v6: .init(v4: 10)] == .US) 70 | #expect(firewall.country[v6: .init(v4: 11)] == .GB) 71 | #expect(firewall.country[v6: .init(v4: 19)] == .GB) 72 | #expect(firewall.country[v6: .init(v4: 20)] == .GB) 73 | #expect(firewall.country[v6: .init(v4: 21)] == nil) 74 | #expect(firewall.country[v6: .init(v4: 22)] == .IL) 75 | #expect(firewall.country[v6: .init(v4: 30)] == .IL) 76 | #expect(firewall.country[v6: .init(v4: 31)] == nil) 77 | } 78 | 79 | @Test 80 | static func cidr() throws 81 | { 82 | let blocks:[IP.Block] = [ 83 | 0xAAAA_AAAA_AAAA_AAAA_0000_0000_0000_0000 / 64, 84 | 0xBBBB_BBBB_BBBB_BBBB_B000_0000_0000_0000 / 68, 85 | 0xCCCC_CCCC_CCCC_CCCC_CC00_0000_0000_0000 / 72, 86 | 0xDDDD_DDDD_DDDD_DDDD_DDD0_0000_0000_0000 / 76, 87 | 0xEEEE_EEEE_EEEE_EEEE_EEEE_0000_0000_0000 / 80, 88 | ] 89 | 90 | var image:IP.Firewall.Image = .init(autonomousSystems: []) 91 | try image.colorByCountry(v4: [], v6: blocks.map { (.US, $0.range) }) 92 | 93 | let firewall:IP.Firewall = .load(from: image) 94 | 95 | #expect(firewall.country[v6: 0xAAAA_AAAA_AAAA_AAA9_FFFF_FFFF_FFFF_FFFF] == nil) 96 | #expect(firewall.country[v6: 0xAAAA_AAAA_AAAA_AAAA_0000_0000_0000_0000] != nil) 97 | #expect(firewall.country[v6: 0xAAAA_AAAA_AAAA_AAAA_0000_0000_0000_0001] != nil) 98 | #expect(firewall.country[v6: 0xAAAA_AAAA_AAAA_AAAA_FFFF_FFFF_FFFF_FFFF] != nil) 99 | #expect(firewall.country[v6: 0xAAAA_AAAA_AAAA_AAAB_0000_0000_0000_0000] == nil) 100 | 101 | #expect(firewall.country[v6: 0xBBBB_BBBB_BBBB_BBBB_AFFF_FFFF_FFFF_FFFF] == nil) 102 | #expect(firewall.country[v6: 0xBBBB_BBBB_BBBB_BBBB_B000_0000_0000_0000] != nil) 103 | #expect(firewall.country[v6: 0xBBBB_BBBB_BBBB_BBBB_B000_0000_0000_0001] != nil) 104 | #expect(firewall.country[v6: 0xBBBB_BBBB_BBBB_BBBB_BFFF_FFFF_FFFF_FFFF] != nil) 105 | #expect(firewall.country[v6: 0xBBBB_BBBB_BBBB_BBBB_C000_0000_0000_0000] == nil) 106 | 107 | #expect(firewall.country[v6: 0xCCCC_CCCC_CCCC_CCCC_CBFF_FFFF_FFFF_FFFF] == nil) 108 | #expect(firewall.country[v6: 0xCCCC_CCCC_CCCC_CCCC_CC00_0000_0000_0000] != nil) 109 | #expect(firewall.country[v6: 0xCCCC_CCCC_CCCC_CCCC_CC00_0000_0000_0001] != nil) 110 | #expect(firewall.country[v6: 0xCCCC_CCCC_CCCC_CCCC_CCFF_FFFF_FFFF_FFFF] != nil) 111 | #expect(firewall.country[v6: 0xCCCC_CCCC_CCCC_CCCC_CD00_0000_0000_0000] == nil) 112 | 113 | #expect(firewall.country[v6: 0xDDDD_DDDD_DDDD_DDDD_DDCF_FFFF_FFFF_FFFF] == nil) 114 | #expect(firewall.country[v6: 0xDDDD_DDDD_DDDD_DDDD_DDD0_0000_0000_0000] != nil) 115 | #expect(firewall.country[v6: 0xDDDD_DDDD_DDDD_DDDD_DDD0_0000_0000_0001] != nil) 116 | #expect(firewall.country[v6: 0xDDDD_DDDD_DDDD_DDDD_DDDF_FFFF_FFFF_FFFF] != nil) 117 | #expect(firewall.country[v6: 0xDDDD_DDDD_DDDD_DDDD_DDE0_0000_0000_0000] == nil) 118 | 119 | #expect(firewall.country[v6: 0xEEEE_EEEE_EEEE_EEEE_EEED_FFFF_FFFF_FFFF] == nil) 120 | #expect(firewall.country[v6: 0xEEEE_EEEE_EEEE_EEEE_EEEE_0000_0000_0000] != nil) 121 | #expect(firewall.country[v6: 0xEEEE_EEEE_EEEE_EEEE_EEEE_0000_0000_0001] != nil) 122 | #expect(firewall.country[v6: 0xEEEE_EEEE_EEEE_EEEE_EEEE_FFFF_FFFF_FFFF] != nil) 123 | #expect(firewall.country[v6: 0xEEEE_EEEE_EEEE_EEEE_EEEF_0000_0000_0000] == nil) 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /Sources/FirewallTests/Roundtripping.swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import IP 3 | import Testing 4 | 5 | @Suite 6 | struct Roundtripping 7 | { 8 | /// This checks that the integer transform we use to preserve sorting behavior is sound. 9 | @Test(arguments: [ 10 | 0, 11 | 1, 12 | 0x7FFF_FFFE, 13 | 0x7FFF_FFFF, 14 | 0x8000_0000, 15 | 0x8000_0001, 16 | 0xFFFF_FFFE, 17 | 0xFFFF_FFFF, 18 | ] as [IP.ASN]) 19 | static func asn(_ asn:IP.ASN) throws 20 | { 21 | let expected:IP.AS = .init(number: asn, domain: "", name: "") 22 | 23 | let encoded:BSON.Document = .init(encoding: expected) 24 | let decoded:IP.AS = try .init(bson: encoded) 25 | 26 | #expect(decoded.number == expected.number) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Sources/Firewalls/IP.AS.Metadata.swift: -------------------------------------------------------------------------------- 1 | import IP 2 | 3 | extension IP.AS 4 | { 5 | /// The human-readable ``name`` and associated ``domain`` of an Autonomous System. 6 | @frozen public 7 | struct Metadata:Equatable, Sendable 8 | { 9 | /// A web domain associated with the Autonomous System. 10 | public 11 | let domain:String 12 | /// A human-readable name for the Autonomous System. 13 | public 14 | let name:String 15 | 16 | @inlinable public 17 | init(domain:String, name:String) 18 | { 19 | self.domain = domain 20 | self.name = name 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Sources/Firewalls/IP.AS.swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import IP 3 | import IP_BSON 4 | 5 | extension IP 6 | { 7 | /// Describes an 8 | /// [Autonomous System](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) (AS). 9 | @frozen public 10 | struct AS:Hashable, Equatable, Sendable 11 | { 12 | public 13 | let number:ASN 14 | public 15 | var domain:String 16 | public 17 | var name:String 18 | 19 | @inlinable public 20 | init(number:ASN, domain:String, name:String) 21 | { 22 | self.number = number 23 | self.domain = domain 24 | self.name = name 25 | } 26 | } 27 | } 28 | extension IP.AS 29 | { 30 | @inlinable public 31 | init(number:IP.ASN, metadata:Metadata) 32 | { 33 | self.init(number: number, domain: metadata.domain, name: metadata.name) 34 | } 35 | 36 | @inlinable public 37 | var metadata:Metadata { .init(domain: self.domain, name: self.name) } 38 | } 39 | extension IP.AS 40 | { 41 | @frozen public 42 | enum CodingKey:String, Sendable 43 | { 44 | case number = "I" 45 | case domain = "D" 46 | case name = "N" 47 | } 48 | } 49 | extension IP.AS:BSONDocumentEncodable 50 | { 51 | public 52 | func encode(to bson:inout BSON.DocumentEncoder) 53 | { 54 | bson[.number] = self.number 55 | bson[.domain] = self.domain 56 | bson[.name] = self.name 57 | } 58 | } 59 | extension IP.AS:BSONDocumentDecodable 60 | { 61 | public 62 | init(bson:BSON.DocumentDecoder) throws 63 | { 64 | self.init( 65 | number: try bson[.number].decode(), 66 | domain: try bson[.domain].decode(), 67 | name: try bson[.name].decode()) 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Sources/Firewalls/IP.ASN.swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import IP 3 | 4 | extension IP 5 | { 6 | /// An [Autonomous System](https://en.wikipedia.org/wiki/Autonomous_system_(Internet)) 7 | /// Number (ASN). 8 | @frozen public 9 | struct ASN:Equatable, Hashable, Sendable 10 | { 11 | public 12 | let value:UInt32 13 | 14 | @inlinable public 15 | init(value:UInt32) 16 | { 17 | self.value = value 18 | } 19 | } 20 | } 21 | extension IP.ASN:ExpressibleByIntegerLiteral 22 | { 23 | @inlinable public 24 | init(integerLiteral:UInt32) { self.init(value: integerLiteral) } 25 | } 26 | extension IP.ASN:Comparable 27 | { 28 | @inlinable public 29 | static func < (a:Self, b:Self) -> Bool { a.value < b.value } 30 | } 31 | extension IP.ASN:CustomStringConvertible 32 | { 33 | @inlinable public 34 | var description:String { "\(value)" } 35 | } 36 | extension IP.ASN:LosslessStringConvertible 37 | { 38 | @inlinable public 39 | init?(_ string:some StringProtocol) 40 | { 41 | guard 42 | let value:UInt32 = .init(string) 43 | else 44 | { 45 | return nil 46 | } 47 | 48 | self.init(value: value) 49 | } 50 | } 51 | extension IP.ASN:BSON.BinaryPackable 52 | { 53 | @inlinable public 54 | static func get(_ storage:UInt32) -> Self { .init(value: .get(storage)) } 55 | 56 | @inlinable public 57 | consuming func set() -> UInt32 { self.value.set() } 58 | } 59 | extension IP.ASN:BSONEncodable 60 | { 61 | /// Encodes the ASN as a signed BSON ``Int32``, by mapping the range of the ``UInt32`` 62 | /// value to the range of an ``Int32``. 63 | /// 64 | /// The transformation effectively shifts the encoded values by ``Int32.min``. This ensures 65 | /// the correct database sort behavior, but also means that the numeric values observable in 66 | /// BSON dumps are nonsensical. 67 | @inlinable public 68 | func encode(to field:inout BSON.FieldEncoder) 69 | { 70 | // 0 - x = Int32.min 71 | // UInt32.max - x = Int32.max 72 | (Int32.init(bitPattern: self.value) &+ Int32.min).encode(to: &field) 73 | } 74 | } 75 | extension IP.ASN:BSONDecodable 76 | { 77 | @inlinable public 78 | init(bson:BSON.AnyValue) throws 79 | { 80 | self.init(value: UInt32.init(bitPattern: try Int32.init(bson: bson) &- Int32.min)) 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Sources/Firewalls/IP.Claimant.swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import IP 3 | 4 | extension IP 5 | { 6 | @frozen public 7 | enum Claimant:String, BSONEncodable, BSONDecodable, Sendable 8 | { 9 | case github_actions 10 | case github_webhook 11 | case github_other 12 | 13 | /// Google’s “common” crawlers. This used to just be Googlebot, but has since been 14 | /// co-opted for [Gemini AI](https://gemini.google.com/) training as well. 15 | case google_common 16 | /// Google’s “special” crawlers, such as AdsBot. 17 | case google_special 18 | 19 | /// Microsoft’s Bingbot. Microsoft claims that Bingbot is not used for AI training. 20 | case microsoft_bingbot 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Sources/Firewalls/IP.Firewall.Image.swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import BSON_ISO 3 | import IP 4 | import ISO 5 | 6 | extension IP.Firewall 7 | { 8 | /// The data used to construct ``IP.Firewall``. 9 | @frozen public 10 | struct Image:Sendable 11 | { 12 | @usableFromInline 13 | var autonomousSystems:[IP.AS] 14 | @usableFromInline 15 | var asn:IP.Table 16 | @usableFromInline 17 | var country:IP.Table 18 | @usableFromInline 19 | var claimant:IP.Table 20 | @usableFromInline 21 | var claimants:[IP.Claimant] 22 | 23 | @inlinable public 24 | init(autonomousSystems:[IP.AS] = []) 25 | { 26 | self.autonomousSystems = autonomousSystems 27 | self.asn = .init() 28 | self.country = .init() 29 | self.claimant = .init() 30 | self.claimants = [] 31 | } 32 | } 33 | } 34 | extension IP.Firewall.Image 35 | { 36 | public mutating 37 | func colorByASN( 38 | v4:[(IP.ASN, ip:ClosedRange)], 39 | v6:[(IP.ASN, ip:ClosedRange)]) throws 40 | { 41 | var v4Ranges:BSON.BinaryArray> = .init(count: v4.count) 42 | var v4Colors:BSON.BinaryArray = .init(count: v4.count) 43 | 44 | for (i, (asn, ip)):(Int, (IP.ASN, ClosedRange)) in zip( 45 | v4Ranges.indices, 46 | v4) 47 | { 48 | v4Ranges[i] = ip 49 | v4Colors[i] = asn 50 | } 51 | 52 | var v6Ranges:BSON.BinaryArray> = .init(count: v6.count) 53 | var v6Colors:BSON.BinaryArray = .init(count: v6.count) 54 | 55 | for (i, (asn, ip)):(Int, (IP.ASN, ClosedRange)) in zip( 56 | v6Ranges.indices, 57 | v6) 58 | { 59 | v6Ranges[i] = ip 60 | v6Colors[i] = asn 61 | } 62 | 63 | self.asn = .init( 64 | v4: try .init(checking: v4Ranges, colors: v4Colors), 65 | v6: try .init(checking: v6Ranges, colors: v6Colors)) 66 | } 67 | 68 | public mutating 69 | func colorByCountry( 70 | v4:[(ISO.Country, ip:ClosedRange)], 71 | v6:[(ISO.Country, ip:ClosedRange)]) throws 72 | { 73 | var v4Ranges:BSON.BinaryArray> = .init(count: v4.count) 74 | var v4Colors:BSON.BinaryArray = .init(count: v4.count) 75 | 76 | for (i, (country, ip)):(Int, (ISO.Country, ClosedRange)) in zip( 77 | v4Ranges.indices, 78 | v4) 79 | { 80 | v4Ranges[i] = ip 81 | v4Colors[i] = country 82 | } 83 | 84 | var v6Ranges:BSON.BinaryArray> = .init(count: v6.count) 85 | var v6Colors:BSON.BinaryArray = .init(count: v6.count) 86 | 87 | for (i, (country, ip)):(Int, (ISO.Country, ClosedRange)) in zip( 88 | v6Ranges.indices, 89 | v6) 90 | { 91 | v6Ranges[i] = ip 92 | v6Colors[i] = country 93 | } 94 | 95 | self.country = .init( 96 | v4: try .init(checking: v4Ranges, colors: v4Colors), 97 | v6: try .init(checking: v6Ranges, colors: v6Colors)) 98 | } 99 | 100 | public mutating 101 | func colorByClaimant( 102 | v4:[(IP.Claimant, ip:ClosedRange)], 103 | v6:[(IP.Claimant, ip:ClosedRange)]) throws 104 | { 105 | var claimantIndices:[IP.Claimant: Int] = [:] 106 | 107 | for (j, claimant):(Int, IP.Claimant) in zip(self.claimants.indices, self.claimants) 108 | { 109 | claimantIndices[claimant] = j 110 | } 111 | 112 | func index(_ claimant:IP.Claimant) -> Int32 113 | { 114 | let j:Int = 115 | { 116 | if let j:Int = $0 117 | { 118 | return j 119 | } 120 | else 121 | { 122 | let j:Int = self.claimants.endIndex 123 | self.claimants.append(claimant) 124 | return j 125 | } 126 | } (&claimantIndices[claimant]) 127 | return Int32.init(j) 128 | } 129 | 130 | var v4Ranges:BSON.BinaryArray> = .init(count: v4.count) 131 | var v4Claims:BSON.BinaryArray = .init(count: v4.count) 132 | 133 | for (i, (claimant, ip)):(Int, (IP.Claimant, ClosedRange)) in zip( 134 | v4Ranges.indices, 135 | v4) 136 | { 137 | v4Ranges[i] = ip 138 | v4Claims[i] = index(claimant) 139 | } 140 | 141 | var v6Ranges:BSON.BinaryArray> = .init(count: v6.count) 142 | var v6Claims:BSON.BinaryArray = .init(count: v6.count) 143 | 144 | for (i, (claimant, ip)):(Int, (IP.Claimant, ClosedRange)) in zip( 145 | v6Ranges.indices, 146 | v6) 147 | { 148 | v6Ranges[i] = ip 149 | v6Claims[i] = index(claimant) 150 | } 151 | 152 | self.claimant = .init( 153 | v4: try .init(checking: v4Ranges, colors: v4Claims), 154 | v6: try .init(checking: v6Ranges, colors: v6Claims)) 155 | } 156 | } 157 | extension IP.Firewall.Image 158 | { 159 | @frozen public 160 | enum CodingKey:String, Sendable 161 | { 162 | case autonomousSystems 163 | 164 | case asn_v4_ranges 165 | case asn_v4_colors 166 | case asn_v6_ranges 167 | case asn_v6_colors 168 | 169 | case country_v4_ranges 170 | case country_v4_colors 171 | case country_v6_ranges 172 | case country_v6_colors 173 | 174 | case claimant_v4_ranges 175 | case claimant_v4_colors 176 | case claimant_v6_ranges 177 | case claimant_v6_colors 178 | 179 | case claimants 180 | } 181 | } 182 | extension IP.Firewall.Image:BSONDocumentEncodable 183 | { 184 | public 185 | func encode(to bson:inout BSON.DocumentEncoder) 186 | { 187 | bson[.autonomousSystems] = self.autonomousSystems 188 | 189 | bson[.asn_v4_ranges] = self.asn.v4.ranges 190 | bson[.asn_v4_colors] = self.asn.v4.colors 191 | bson[.asn_v6_ranges] = self.asn.v6.ranges 192 | bson[.asn_v6_colors] = self.asn.v6.colors 193 | 194 | bson[.country_v4_ranges] = self.country.v4.ranges 195 | bson[.country_v4_colors] = self.country.v4.colors 196 | bson[.country_v6_ranges] = self.country.v6.ranges 197 | bson[.country_v6_colors] = self.country.v6.colors 198 | 199 | bson[.claimant_v4_ranges] = self.claimant.v4.ranges 200 | bson[.claimant_v4_colors] = self.claimant.v4.colors 201 | bson[.claimant_v6_ranges] = self.claimant.v6.ranges 202 | bson[.claimant_v6_colors] = self.claimant.v6.colors 203 | 204 | bson[.claimants] = self.claimants 205 | } 206 | } 207 | extension IP.Firewall.Image:BSONDocumentDecodable 208 | { 209 | public 210 | init(bson:BSON.DocumentDecoder) throws 211 | { 212 | self.init(autonomousSystems: try bson[.autonomousSystems].decode()) 213 | 214 | self.asn = .init( 215 | v4: try .init( 216 | checking: bson[.asn_v4_ranges].decode(), 217 | colors: bson[.asn_v4_colors].decode()), 218 | v6: try .init( 219 | checking: bson[.asn_v6_ranges].decode(), 220 | colors: bson[.asn_v6_colors].decode())) 221 | 222 | self.country = .init( 223 | v4: try .init( 224 | checking: bson[.country_v4_ranges].decode(), 225 | colors: bson[.country_v4_colors].decode()), 226 | v6: try .init( 227 | checking: bson[.country_v6_ranges].decode(), 228 | colors: bson[.country_v6_colors].decode())) 229 | 230 | self.claimant = .init( 231 | v4: try .init( 232 | checking: bson[.claimant_v4_ranges].decode(), 233 | colors: bson[.claimant_v4_colors].decode()), 234 | v6: try .init( 235 | checking: bson[.claimant_v6_ranges].decode(), 236 | colors: bson[.claimant_v6_colors].decode())) 237 | 238 | self.claimants = try bson[.claimants].decode() 239 | } 240 | } 241 | -------------------------------------------------------------------------------- /Sources/Firewalls/IP.Firewall.swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import BSON_ISO 3 | import IP 4 | import ISO 5 | 6 | extension IP 7 | { 8 | @frozen public 9 | struct Firewall:Sendable 10 | { 11 | private 12 | let autonomousSystems:[ASN: AS.Metadata] 13 | 14 | public 15 | let asn:Table 16 | public 17 | let country:Table 18 | 19 | private 20 | let claimant:Table 21 | private 22 | let claimants:[Claimant] 23 | private 24 | let loopback:Claimant? 25 | 26 | init( 27 | autonomousSystems:[ASN: AS.Metadata], 28 | asn:Table, 29 | country:Table, 30 | claimant:Table, 31 | claimants:[Claimant], 32 | loopback:Claimant?) 33 | { 34 | self.autonomousSystems = autonomousSystems 35 | self.asn = asn 36 | self.country = country 37 | self.claimant = claimant 38 | self.claimants = claimants 39 | self.loopback = loopback 40 | } 41 | } 42 | } 43 | extension IP.Firewall 44 | { 45 | public 46 | static func load(from image:Image, loopback:IP.Claimant? = nil) -> Self 47 | { 48 | let autonomousSystems:[IP.ASN: IP.AS.Metadata] = image.autonomousSystems.reduce( 49 | into: [:]) 50 | { 51 | $0[$1.number] = $1.metadata 52 | } 53 | 54 | return .init(autonomousSystems: autonomousSystems, 55 | asn: image.asn, 56 | country: image.country, 57 | claimant: image.claimant, 58 | claimants: image.claimants, 59 | loopback: loopback) 60 | } 61 | 62 | public 63 | func lookup(v4 ip:IP.V4) -> (IP.AS?, IP.Claimant?) 64 | { 65 | let asn:IP.ASN? = self.asn[v4: ip] 66 | let claimant:Int32? = self.claimant[v4: ip] 67 | return self.symbolicate(asn: asn, 68 | claimant: claimant, 69 | loopback: IP.Block.loopback.contains(ip)) 70 | } 71 | public 72 | func lookup(v6 ip:IP.V6) -> (IP.AS?, IP.Claimant?) 73 | { 74 | let asn:IP.ASN? = self.asn[v6: ip] 75 | let claimant:Int32? = self.claimant[v6: ip] 76 | return self.symbolicate(asn: asn, 77 | claimant: claimant, 78 | loopback: IP.Block.loopback.contains(ip)) 79 | } 80 | 81 | private 82 | func symbolicate(asn:IP.ASN?, 83 | claimant:Int32?, 84 | loopback:Bool) -> (IP.AS?, IP.Claimant?) 85 | { 86 | let autonomousSystem:IP.AS? 87 | if let asn:IP.ASN, 88 | let metadata:IP.AS.Metadata = self.autonomousSystems[asn] 89 | { 90 | autonomousSystem = .init(number: asn, metadata: metadata) 91 | } 92 | else 93 | { 94 | autonomousSystem = nil 95 | } 96 | 97 | let claimant:IP.Claimant? = claimant.map { self.claimants[Int.init($0)] } 98 | 99 | return (autonomousSystem, claimant ?? (loopback ? self.loopback : nil)) 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /Sources/Firewalls/IP.Table.SortedArray.IntervalError.swift: -------------------------------------------------------------------------------- 1 | import IP 2 | 3 | extension IP.Table.SortedArray where Bound:Sendable 4 | { 5 | enum IntervalError:Error 6 | { 7 | case nonmonotonic(ClosedRange, ClosedRange) 8 | } 9 | } 10 | extension IP.Table.SortedArray.IntervalError:CustomStringConvertible 11 | { 12 | var description:String 13 | { 14 | switch self 15 | { 16 | case .nonmonotonic(let a, let b): "Nonmonotonic intervals (\(a), \(b))" 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Sources/Firewalls/IP.Table.SortedArray.swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import IP 3 | 4 | extension IP.Table 5 | { 6 | @frozen @usableFromInline 7 | struct SortedArray where Bound:Comparable, Bound:BSON.BinaryPackable 8 | { 9 | @usableFromInline 10 | let ranges:BSON.BinaryArray> 11 | @usableFromInline 12 | let colors:BSON.BinaryArray 13 | 14 | @inlinable 15 | init() 16 | { 17 | self.ranges = [] 18 | self.colors = [] 19 | } 20 | 21 | init( 22 | unchecked ranges:BSON.BinaryArray>, 23 | colors:BSON.BinaryArray) 24 | { 25 | self.ranges = ranges 26 | self.colors = colors 27 | } 28 | } 29 | } 30 | extension IP.Table.SortedArray where Bound:Sendable 31 | { 32 | init( 33 | checking ranges:BSON.BinaryArray>, 34 | colors:BSON.BinaryArray) throws 35 | { 36 | guard ranges.count == colors.count 37 | else 38 | { 39 | fatalError("unimplemented") 40 | } 41 | 42 | var last:ClosedRange? 43 | 44 | for range:ClosedRange in ranges 45 | { 46 | if let last:ClosedRange 47 | { 48 | if last.upperBound >= range.lowerBound 49 | { 50 | throw IntervalError.nonmonotonic(last, range) 51 | } 52 | } 53 | 54 | last = range 55 | } 56 | 57 | self.init(unchecked: ranges, colors: colors) 58 | } 59 | } 60 | extension IP.Table.SortedArray:Sendable where Color:Sendable 61 | { 62 | } 63 | extension IP.Table.SortedArray 64 | { 65 | @inlinable 66 | func color(containing ip:Bound) -> Color? 67 | { 68 | let index:Int = self.index(containing: ip) 69 | if index == self.ranges.endIndex 70 | { 71 | return nil 72 | } 73 | 74 | let range:ClosedRange = self.ranges[index] 75 | // We already know that `ip <= range.upperBound` 76 | if ip < range.lowerBound 77 | { 78 | return nil 79 | } 80 | else 81 | { 82 | return self.colors[index] 83 | } 84 | } 85 | 86 | @inlinable 87 | func index(containing ip:Bound) -> Int 88 | { 89 | var n:Int = self.ranges.count 90 | var l:Int = self.ranges.startIndex 91 | 92 | while n > 0 93 | { 94 | let half:Int = n / 2 95 | let mid:Int = self.ranges.index(l, offsetBy: half) 96 | 97 | if ip <= self.ranges[mid].upperBound 98 | { 99 | n = half 100 | } 101 | else 102 | { 103 | l = self.ranges.index(after: mid) 104 | n -= half + 1 105 | } 106 | } 107 | 108 | return l 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /Sources/Firewalls/IP.Table.swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import IP 3 | import IP_BSON 4 | 5 | extension IP 6 | { 7 | /// A data structure for efficient IP address lookups. 8 | /// 9 | /// IP mappings can be quite large, so you should always ensure the machine you are using 10 | /// them on has enough memory to store them. 11 | @frozen public 12 | struct Table where Color:BSON.BinaryPackable 13 | { 14 | @usableFromInline 15 | var v4:SortedArray 16 | @usableFromInline 17 | var v6:SortedArray 18 | 19 | /// Constructs a mapping from lists of IP ranges and associated colors. 20 | /// 21 | /// The address ranges must be non-overlapping and sorted in ascending order. If not, 22 | /// the initializer will throw an error. 23 | /// 24 | /// This does not perform any IPv6 to IPv4 normalization, which means IPv6-mapped IPv4 25 | /// addresses in the `v6` list will never match any queries. 26 | @inlinable 27 | init( 28 | v4:SortedArray = .init(), 29 | v6:SortedArray = .init()) 30 | { 31 | self.v4 = v4 32 | self.v6 = v6 33 | } 34 | } 35 | } 36 | extension IP.Table:Sendable where Color:Sendable 37 | { 38 | } 39 | extension IP.Table 40 | { 41 | /// Performs a bisection search to look up the color associated with the given IP address, 42 | /// using the IPv4 subtable only. 43 | /// 44 | /// > Complexity: 45 | /// *O*(log *n*), where *n* is the number of ranges in the IPv4 subtable. 46 | @inlinable public 47 | subscript(v4 ip:IP.V4) -> Color? 48 | { 49 | self.v4.color(containing: ip) 50 | } 51 | 52 | /// Performs a bisection search to look up the color associated with the given IP address. 53 | /// If the IP address is an IPv6-mapped IPv4 address, the subscript will use the IPv4 54 | /// subtable, otherwise it will use the IPv6 subtable. 55 | /// 56 | /// > Complexity: 57 | /// *O*(log *n*), where *n* is the number of ranges in the corresponding subtable. 58 | @inlinable public 59 | subscript(v6 ip:IP.V6) -> Color? 60 | { 61 | if let v4:IP.V4 = ip.v4 62 | { 63 | self[v4: v4] 64 | } 65 | else 66 | { 67 | self.v6.color(containing: ip) 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Sources/IP/IP.Address.swift: -------------------------------------------------------------------------------- 1 | extension IP 2 | { 3 | /// Abstracts over ``IP.V4`` and ``IP.V6`` addresses. 4 | /// 5 | /// We recommend normalizing all addresses to ``IP.V6`` when possible. However some 6 | /// applications may derive a performance or security benefit from supporting ``IP.V4`` 7 | /// addresses only, so this protocol enables generic code to support both. 8 | public 9 | protocol Address:LosslessStringConvertible, Comparable, Equatable, Hashable, Sendable 10 | { 11 | /// The raw storage type for the IP address. 12 | associatedtype Storage:FixedWidthInteger, UnsignedInteger, BitwiseCopyable 13 | 14 | /// The raw storage, which is the numeric address value in big-endian byte order. 15 | var storage:Storage { get } 16 | 17 | /// Initializes an IP address from raw storage. 18 | init(storage:Storage) 19 | 20 | /// Parses an IP address from a string. 21 | init?(_ string:some StringProtocol) 22 | } 23 | } 24 | extension IP.Address 25 | { 26 | /// Initializes an IP address from a logical value. 27 | /// 28 | /// For IPv4, the high byte of the ``UInt32`` will become the first octet. 29 | /// 30 | /// For IPv6, the high bits of the ``UInt128`` will appear in the high bits of the first 31 | /// hextet. 32 | @inlinable public 33 | init(value:Storage) 34 | { 35 | self.init(storage: value.bigEndian) 36 | } 37 | 38 | /// The logical value of the address. 39 | /// 40 | /// For IPv4, the high byte of the ``UInt32`` is the first octet. 41 | /// 42 | /// For IPv6, the high bits of the ``UInt128`` come from the high bits of the first hextet. 43 | @inlinable public 44 | var value:Storage { .init(bigEndian: self.storage) } 45 | } 46 | extension IP.Address where Self:ExpressibleByIntegerLiteral, Self.IntegerLiteralType == Storage 47 | { 48 | @inlinable public 49 | init(integerLiteral:Storage) { self.init(value: integerLiteral) } 50 | } 51 | extension IP.Address where Self:Comparable 52 | { 53 | /// Compares two IP addresses by their logical ``value``. 54 | @inlinable public 55 | static func < (a:Self, b:Self) -> Bool { a.value < b.value } 56 | } 57 | extension IP.Address 58 | { 59 | /// The bit width of the IP address type. 60 | @inlinable 61 | static var bitWidth:UInt8 { .init(Storage.bitWidth) } 62 | 63 | /// Returns a storage mask where the corresponding logical high `bits` are all 1. 64 | /// The returned mask itself is in big-endian byte order. 65 | @inlinable 66 | static func storageMask(ones bits:UInt8) -> Storage 67 | { 68 | let ones:Storage = ~0 69 | let mask:Storage = ones << (Self.bitWidth - bits) 70 | return mask.bigEndian 71 | } 72 | 73 | /// Replaces all bits in the IP address except for the leading number of `bits` with 0. 74 | @inlinable public 75 | func zeroMasked(to bits:UInt8) -> Self 76 | { 77 | .init(storage: self.storage & Self.storageMask(ones: bits)) 78 | } 79 | 80 | /// Replaces all bits in the IP address except for the leading number of `bits` with 1. 81 | @inlinable public 82 | func onesMasked(to bits:UInt8) -> Self 83 | { 84 | .init(storage: self.storage | ~Self.storageMask(ones: bits)) 85 | } 86 | 87 | /// Creates a CIDR block by masking this IP address to the specified number of bits. 88 | /// The meaning of the slash (`/`) operator follows CIDR notation. 89 | @inlinable public 90 | static func / (self:Self, bits:UInt8) -> IP.Block 91 | { 92 | .init(base: self.zeroMasked(to: bits), bits: bits) 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Sources/IP/IP.Block.swift: -------------------------------------------------------------------------------- 1 | extension IP 2 | { 3 | /// A representation of a CIDR block. 4 | /// 5 | /// Create a CIDR block using the ``Address./(_:_:)`` operator. 6 | /// 7 | /// This type wastes a lot of padding, as it stores the prefix length alongside the base 8 | /// mask, so it is only suitable as a formatter, parser, or interface type. 9 | /// 10 | /// Data structures should mask the base addresses using ``Address.zeroMasked(to:)`` and 11 | /// perform lookups against the masked values. 12 | @frozen public 13 | struct Block:Equatable, Hashable, Sendable where Base:Address 14 | { 15 | public 16 | var base:Base 17 | public 18 | var bits:UInt8 19 | 20 | @inlinable 21 | init(base:Base, bits:UInt8) 22 | { 23 | self.base = base 24 | self.bits = bits 25 | } 26 | } 27 | } 28 | extension IP.Block 29 | { 30 | /// Converts the IPv4 base address to an IPv6 address and adds 96 to the prefix length. 31 | @inlinable public 32 | init(v4:IP.Block) 33 | { 34 | self.init(base: .init(v4: v4.base), bits: v4.bits + 96) 35 | } 36 | 37 | /// Returns the IPv6 loopback mask, `::1/128`. 38 | @inlinable public 39 | static var loopback:IP.Block { .init(base: .localhost, bits: 128) } 40 | } 41 | extension IP.Block 42 | { 43 | /// Returns the IPv4 loopback mask, `127.0.0.0/8`. 44 | @inlinable public 45 | static var loopback:IP.Block { .init(base: .localhost, bits: 8) } 46 | } 47 | extension IP.Block 48 | { 49 | @inlinable public 50 | func contains(_ ip:Base) -> Bool { self.base == ip.zeroMasked(to: self.bits) } 51 | 52 | @inlinable public 53 | var range:ClosedRange { self.base ... self.base.onesMasked(to: self.bits) } 54 | } 55 | extension IP.Block:CustomStringConvertible 56 | { 57 | /// Formats the block as a string in CIDR notation. 58 | @inlinable public 59 | var description:String { "\(self.base)/\(self.bits)" } 60 | } 61 | extension IP.Block:LosslessStringConvertible 62 | { 63 | /// Parses a CIDR block from a string in CIDR notation. 64 | @inlinable public 65 | init?(_ string:some StringProtocol) 66 | { 67 | guard 68 | let slash:String.Index = string.lastIndex(of: "/"), 69 | let base:Base = .init(string[.. IP.Block``, which models the entire 35 | /// loopback range. 36 | @inlinable public 37 | static var localhost:Self { .init(value: 0x7F_00_00_01) } 38 | } 39 | extension IP.V4:CustomStringConvertible 40 | { 41 | /// Formats the address as a string in dotted-decimal notation. 42 | @inlinable public 43 | var description:String 44 | { 45 | withUnsafeBytes(of: self.storage) { "\($0[0]).\($0[1]).\($0[2]).\($0[3])" } 46 | } 47 | } 48 | extension IP.V4:LosslessStringConvertible 49 | { 50 | /// Parses an IPv4 address from a string in dotted-decimal notation. 51 | @inlinable public 52 | init?(_ description:some StringProtocol) 53 | { 54 | guard 55 | var b:String.Index = description.firstIndex(of: "."), 56 | let a:UInt8 = .init(description[..) -> Self? 101 | { 102 | bytes.count == MemoryLayout.size ? .copy(buffer: bytes) : nil 103 | } 104 | 105 | @inlinable 106 | static func copy(buffer:some RandomAccessCollection) -> Self 107 | { 108 | precondition(buffer.count == MemoryLayout.size) 109 | 110 | return withUnsafeTemporaryAllocation( 111 | byteCount: MemoryLayout.size, 112 | alignment: MemoryLayout.alignment) 113 | { 114 | $0.copyBytes(from: buffer) 115 | return .init(storage: $0.load(as: UInt128.self)) 116 | } 117 | } 118 | } 119 | extension IP.V6 120 | { 121 | /// Returns the all-zeros address, `::`. 122 | @inlinable public 123 | static var zero:Self { .init(storage: 0) } 124 | 125 | /// Returns the all-ones address, `ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff`. 126 | @inlinable public 127 | static var ones:Self { .init(storage: ~0) } 128 | 129 | /// Returns the loopback address, `::1`. There is only one loopback address in IPv6. 130 | @inlinable public 131 | static var localhost:Self { .init(value: 1) } 132 | } 133 | extension IP.V6:RandomAccessCollection 134 | { 135 | /// Always 0. 136 | @inlinable public 137 | var startIndex:Int { 0 } 138 | 139 | /// Always 8, the number of 16-bit words in an IPv6 address. 140 | @inlinable public 141 | var endIndex:Int { 8 } 142 | 143 | /// Returns the *i*th word of the address, in **platform** byte order. 144 | @inlinable public 145 | subscript(i:Int) -> UInt16 146 | { 147 | get 148 | { 149 | precondition(self.indices ~= i, "index out of range") 150 | 151 | return withUnsafeBytes(of: self) 152 | { 153 | let words:UnsafeBufferPointer = $0.bindMemory(to: UInt16.self) 154 | return .init(bigEndian: words[i]) 155 | } 156 | } 157 | set(word) 158 | { 159 | precondition(self.indices ~= i, "index out of range") 160 | 161 | withUnsafeMutableBytes(of: &self) 162 | { 163 | let words:UnsafeMutableBufferPointer = $0.bindMemory(to: UInt16.self) 164 | words[i] = word.bigEndian 165 | } 166 | } 167 | } 168 | } 169 | extension IP.V6:CustomStringConvertible 170 | { 171 | /// Formats the address as a string in colon-hexadecimal notation. This formatter does not 172 | /// collapse zeros. 173 | @inlinable public 174 | var description:String 175 | { 176 | self.lazy.map { String.init($0, radix: 16) }.joined(separator: ":") 177 | } 178 | } 179 | extension IP.V6:LosslessStringConvertible 180 | { 181 | /// Parses an IPv6 address from a string in colon-hexadecimal notation. This parser accepts 182 | /// both full and collapsed forms. 183 | @inlinable public 184 | init?(_ string:some StringProtocol) 185 | { 186 | self = .zero 187 | 188 | var i:String.Index = string.startIndex 189 | var z:Int = 0 190 | for w:Int in 0 ..< 8 191 | { 192 | guard 193 | let j:String.Index = string[i...].firstIndex(of: ":") 194 | else 195 | { 196 | guard w == 7, 197 | let word:UInt16 = .init(string[i...], radix: 16) 198 | else 199 | { 200 | return nil 201 | } 202 | 203 | self[w] = word 204 | return 205 | } 206 | 207 | guard i < j 208 | else 209 | { 210 | break 211 | } 212 | 213 | guard 214 | let word:UInt16 = .init(string[i ..< j], radix: 16) 215 | else 216 | { 217 | return nil 218 | } 219 | 220 | self[w] = word 221 | i = string.index(after: j) 222 | z = w + 1 223 | } 224 | 225 | var k:String.Index = string.indices.last ?? i 226 | for w:Int in (z ..< 8).reversed() 227 | { 228 | guard 229 | let j:String.Index = string[i ... k].lastIndex(of: ":") 230 | else 231 | { 232 | return nil 233 | } 234 | 235 | guard j < k 236 | else 237 | { 238 | break 239 | } 240 | 241 | guard 242 | let word:UInt16 = .init(string[string.index(after: j) ... k], radix: 16) 243 | else 244 | { 245 | return nil 246 | } 247 | 248 | self[w] = word 249 | 250 | guard i < j 251 | else 252 | { 253 | break 254 | } 255 | 256 | k = string.index(before: j) 257 | } 258 | } 259 | } 260 | -------------------------------------------------------------------------------- /Sources/IP/IP.swift: -------------------------------------------------------------------------------- 1 | /// The namespace for IP types. 2 | @frozen public 3 | enum IP 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /Sources/IP/docs.docc/IP.md: -------------------------------------------------------------------------------- 1 | # ``/IP`` 2 | 3 | This Foundation-free module provides tools for parsing and formatting IP addresses, and data structures for performing efficient IP address lookups. 4 | 5 | 6 | ## Topics 7 | 8 | ### Namespaces 9 | 10 | - ``IP`` 11 | 12 | ### Address types 13 | 14 | - ``IP.Address`` 15 | - ``IP.V4`` 16 | - ``IP.V6`` 17 | - ``IP.Block`` 18 | -------------------------------------------------------------------------------- /Sources/IPTests/Mapping.swift: -------------------------------------------------------------------------------- 1 | import IP 2 | import Testing 3 | 4 | @Test 5 | func Mapping() throws 6 | { 7 | let v4:IP.V4 = try #require(.init("1.2.3.4")) 8 | let v6:IP.V6 = .init(v4: v4) 9 | 10 | #expect(v6 == .init(0, 0, 0, 0, 0, 0xffff, 0x0102, 0x0304)) 11 | #expect(v6 == .init(value: 0xff_ff_01_02_03_04)) 12 | #expect(v6.v4 == v4) 13 | } 14 | -------------------------------------------------------------------------------- /Sources/IPTests/Masking.swift: -------------------------------------------------------------------------------- 1 | import IP 2 | import Testing 3 | 4 | @Suite 5 | struct Masking 6 | { 7 | private 8 | let ip:IP.V6 = .init( 9 | 0x0123, 10 | 0x2345, 11 | 0x3456, 12 | 0x4567, 13 | 0x5678, 14 | 0x6789, 15 | 0x789a, 16 | 0x89ab) 17 | 18 | @Test 19 | func zero() throws 20 | { 21 | #expect(self.ip.zeroMasked(to: 0) == .zero) 22 | #expect(self.ip.zeroMasked(to: 1) == .init( 23 | 0x0000, 0, 0, 0, 0, 0, 0, 0)) 24 | 25 | #expect(self.ip.zeroMasked(to: 8) == .init( 26 | 0x0100, 0, 0, 0, 0, 0, 0, 0)) 27 | 28 | #expect(self.ip.zeroMasked(to: 16) == .init( 29 | 0x0123, 0, 0, 0, 0, 0, 0, 0)) 30 | 31 | #expect(self.ip.zeroMasked(to: 32) == .init( 32 | 0x0123, 0x2345, 0, 0, 0, 0, 0, 0)) 33 | 34 | #expect(self.ip.zeroMasked(to: 60) == .init( 35 | 0x0123, 0x2345, 0x3456, 0x4560, 0, 0, 0, 0)) 36 | 37 | #expect(self.ip.zeroMasked(to: 64) == .init( 38 | 0x0123, 0x2345, 0x3456, 0x4567, 0, 0, 0, 0)) 39 | 40 | #expect(self.ip.zeroMasked(to: 68) == .init( 41 | 0x0123, 0x2345, 0x3456, 0x4567, 0x5000, 0, 0, 0)) 42 | 43 | #expect(self.ip.zeroMasked(to: 96) == .init( 44 | 0x0123, 0x2345, 0x3456, 0x4567, 0x5678, 0x6789, 0, 0)) 45 | 46 | #expect(self.ip.zeroMasked(to: 112) == .init( 47 | 0x0123, 0x2345, 0x3456, 0x4567, 0x5678, 0x6789, 0x789a, 0)) 48 | 49 | #expect(self.ip.zeroMasked(to: 120) == .init( 50 | 0x0123, 0x2345, 0x3456, 0x4567, 0x5678, 0x6789, 0x789a, 0x8900)) 51 | 52 | #expect(self.ip.zeroMasked(to: 127) == .init( 53 | 0x0123, 0x2345, 0x3456, 0x4567, 0x5678, 0x6789, 0x789a, 0x89aa)) 54 | 55 | #expect(self.ip.zeroMasked(to: 128) == self.ip) 56 | } 57 | 58 | @Test 59 | func ones() throws 60 | { 61 | #expect(self.ip.onesMasked(to: 0) == .ones) 62 | #expect(self.ip.onesMasked(to: 1) == .init( 63 | 0x7fff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)) 64 | 65 | #expect(self.ip.onesMasked(to: 8) == .init( 66 | 0x01ff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)) 67 | 68 | #expect(self.ip.onesMasked(to: 16) == .init( 69 | 0x0123, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)) 70 | 71 | #expect(self.ip.onesMasked(to: 32) == .init( 72 | 0x0123, 0x2345, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)) 73 | 74 | #expect(self.ip.onesMasked(to: 60) == .init( 75 | 0x0123, 0x2345, 0x3456, 0x456f, 0xffff, 0xffff, 0xffff, 0xffff)) 76 | 77 | #expect(self.ip.onesMasked(to: 64) == .init( 78 | 0x0123, 0x2345, 0x3456, 0x4567, 0xffff, 0xffff, 0xffff, 0xffff)) 79 | 80 | #expect(self.ip.onesMasked(to: 68) == .init( 81 | 0x0123, 0x2345, 0x3456, 0x4567, 0x5fff, 0xffff, 0xffff, 0xffff)) 82 | 83 | #expect(self.ip.onesMasked(to: 96) == .init( 84 | 0x0123, 0x2345, 0x3456, 0x4567, 0x5678, 0x6789, 0xffff, 0xffff)) 85 | 86 | #expect(self.ip.onesMasked(to: 112) == .init( 87 | 0x0123, 0x2345, 0x3456, 0x4567, 0x5678, 0x6789, 0x789a, 0xffff)) 88 | 89 | #expect(self.ip.onesMasked(to: 120) == .init( 90 | 0x0123, 0x2345, 0x3456, 0x4567, 0x5678, 0x6789, 0x789a, 0x89ff)) 91 | 92 | #expect(self.ip.onesMasked(to: 127) == .init( 93 | 0x0123, 0x2345, 0x3456, 0x4567, 0x5678, 0x6789, 0x789a, 0x89ab)) 94 | 95 | #expect(self.ip.onesMasked(to: 128) == self.ip) 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Sources/IPTests/Parsing.swift: -------------------------------------------------------------------------------- 1 | import IP 2 | import Testing 3 | 4 | @Suite 5 | struct Parsing 6 | { 7 | @Test 8 | static func localhost4() throws 9 | { 10 | #expect(try #require(IP.V4.init("127.0.0.1")) == .localhost) 11 | } 12 | 13 | @Test 14 | static func localhost6() throws 15 | { 16 | #expect(try #require(IP.V6.init("::1")) == .localhost) 17 | } 18 | 19 | @Test 20 | static func zero() throws 21 | { 22 | #expect(try #require(IP.V6.init("::")) == .zero) 23 | } 24 | 25 | @Test 26 | static func ones() throws 27 | { 28 | #expect(try #require(IP.V6.init("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")) == .ones) 29 | } 30 | 31 | @Test 32 | static func prefix16() throws 33 | { 34 | let expected:IP.V6 = .init(0xabcd, 0, 0, 0, 0, 0, 0, 0) 35 | #expect(try #require(IP.V6.init("abcd::")) == expected) 36 | } 37 | 38 | @Test 39 | static func prefix32() throws 40 | { 41 | let expected:IP.V6 = .init(0xabcd, 0x1234, 0, 0, 0, 0, 0, 0) 42 | #expect(try #require(IP.V6.init("abcd:1234::")) == expected) 43 | } 44 | 45 | @Test 46 | static func prefix32_16() throws 47 | { 48 | let expected:IP.V6 = .init(0xabcd, 0x1234, 0, 0, 0, 0, 0, 0xcdef) 49 | #expect(try #require(IP.V6.init("abcd:1234::cdef")) == expected) 50 | } 51 | 52 | @Test 53 | static func prefix32_32() throws 54 | { 55 | let expected:IP.V6 = .init(0xabcd, 0x1234, 0, 0, 0, 0, 0x5678, 0xcdef) 56 | #expect(try #require(IP.V6.init("abcd:1234::5678:cdef")) == expected) 57 | } 58 | 59 | @Test 60 | static func prefix16_32() throws 61 | { 62 | let expected:IP.V6 = .init(0xabcd, 0, 0, 0, 0, 0, 0x5678, 0xcdef) 63 | #expect(try #require(IP.V6.init("abcd::5678:cdef")) == expected) 64 | } 65 | 66 | @Test 67 | static func suffix32() throws 68 | { 69 | let expected:IP.V6 = .init(0, 0, 0, 0, 0, 0, 0x5678, 0xcdef) 70 | #expect(try #require(IP.V6.init("::5678:cdef")) == expected) 71 | } 72 | 73 | @Test 74 | static func suffix16() throws 75 | { 76 | let expected:IP.V6 = .init(0, 0, 0, 0, 0, 0, 0, 0xcdef) 77 | #expect(try #require(IP.V6.init("::cdef")) == expected) 78 | } 79 | 80 | @Test 81 | static func roundtripping4() throws 82 | { 83 | let expected:IP.V4 = .init(value: 0x01_02_03_04) 84 | #expect(try #require(.init("1.2.3.4")) == expected) 85 | #expect(try #require(.init("\(expected)")) == expected) 86 | } 87 | 88 | @Test 89 | static func roundtripping6() throws 90 | { 91 | let expected:IP.V6 = .init( 92 | 0x0123, 93 | 0x2345, 94 | 0x3456, 95 | 0x4567, 96 | 0x5678, 97 | 0x6789, 98 | 0x789a, 99 | 0x89ab) 100 | 101 | let actual:IP.V6 = try #require(.init("0123:2345:3456:4567:5678:6789:789a:89ab")) 102 | let again:IP.V6 = try #require(.init("\(actual)")) 103 | 104 | #expect(expected == actual) 105 | #expect(expected == again) 106 | 107 | #expect(actual.value == 0x0123_2345_3456_4567_5678_6789_789a_89ab) 108 | #expect(actual.v4 == nil) 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /Sources/IP_BSON/IP.Address (ext).swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import IP 3 | 4 | extension IP.Address where Self:BSON.BinaryPackable, Storage:BSON.BinaryPackable 5 | { 6 | @inlinable public 7 | static func get(_ storage:Storage) -> Self { .init(storage: storage) } 8 | 9 | @inlinable public 10 | func set() -> Storage { self.storage } 11 | } 12 | -------------------------------------------------------------------------------- /Sources/IP_BSON/IP.V4 (ext).swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import IP 3 | 4 | extension IP.V4:BSON.BinaryPackable 5 | { 6 | } 7 | -------------------------------------------------------------------------------- /Sources/IP_BSON/IP.V6 (ext).swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import IP 3 | 4 | extension IP.V6:BSONBinaryEncodable 5 | { 6 | /// Encodes the IPv6 address as a BSON binary array of ``BSON.BinarySubtype/generic`` 7 | /// subtype. 8 | @inlinable public 9 | func encode(to bson:inout BSON.BinaryEncoder) 10 | { 11 | withUnsafeBytes(of: self) { bson += $0 } 12 | } 13 | } 14 | extension IP.V6:BSONBinaryDecodable 15 | { 16 | /// Decodes an IPv6 address from a BSON binary array of ``BSON.BinarySubtype/generic`` 17 | /// subtype. 18 | @inlinable public 19 | init(bson:BSON.BinaryDecoder) throws 20 | { 21 | try bson.subtype.expect(.generic) 22 | 23 | if let ip:IP.V6 = .copy(from: bson.bytes) 24 | { 25 | self = ip 26 | } 27 | else 28 | { 29 | throw BSON.BinaryShapeError.init(invalid: bson.bytes.count, expected: .size(16)) 30 | } 31 | } 32 | } 33 | 34 | extension IP.V6:BSON.BinaryPackable 35 | { 36 | } 37 | -------------------------------------------------------------------------------- /Sources/IP_NIOCore/IP.V4 (ext).swift: -------------------------------------------------------------------------------- 1 | #if canImport(Darwin) 2 | import CNIODarwin 3 | #else 4 | import CNIOLinux 5 | #endif 6 | 7 | import IP 8 | import NIOCore 9 | 10 | extension IP.V4 11 | { 12 | /// Creates an IPv4 address from an ``SocketAddress/IPv4Address``. 13 | @inlinable public 14 | init(_ ip:SocketAddress.IPv4Address) 15 | { 16 | self.init(storage: ip.address.sin_addr.s_addr) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Sources/IP_NIOCore/IP.V6 (ext).swift: -------------------------------------------------------------------------------- 1 | #if canImport(Darwin) 2 | import CNIODarwin 3 | #else 4 | import CNIOLinux 5 | #endif 6 | 7 | import IP 8 | import NIOCore 9 | 10 | extension IP.V6 11 | { 12 | /// Creates an IPv6 address from an ``SocketAddress/IPv4Address`` by mapping it to IPv6. 13 | @inlinable public 14 | init(_ ip:SocketAddress.IPv4Address) 15 | { 16 | self.init(v4: .init(ip)) 17 | } 18 | 19 | /// Creates an IPv6 address from an ``SocketAddress/IPv6Address``. 20 | @inlinable public 21 | init(_ ip:SocketAddress.IPv6Address) 22 | { 23 | #if canImport(Darwin) 24 | self.init(storage: ip.address.sin6_addr.__u6_addr.__u6_addr32) 25 | #else 26 | self.init(storage: ip.address.sin6_addr.__in6_u.__u6_addr32) 27 | #endif 28 | } 29 | 30 | /// Creates an IPv6 address from a ``SocketAddress``. IPv4 addresses are mapped to IPv6. 31 | /// Returns nil if the address is not an IP address. 32 | @inlinable public 33 | init?(_ address:SocketAddress) 34 | { 35 | switch address 36 | { 37 | case .v4(let ip): self.init(ip) 38 | case .v6(let ip): self.init(ip) 39 | case .unixDomainSocket: return nil 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Sources/IP_NIOCore/docs.docc/IP_NIOCore.md: -------------------------------------------------------------------------------- 1 | # ``/IP_NIOCore`` 2 | 3 | This module provides shims for compatibility with SwiftNIO’s ``SocketAddress/IPv4Address`` and ``SocketAddress/IPv6Address`` types. 4 | 5 | The two native ``SocketAddress`` types are reference counted and resilient, which makes them unsuitable for performance-sensitive applications. By contrast, this library’s ``IP.V4`` and ``IP.V6`` types are inline value types that can be passed around with zero overhead. 6 | -------------------------------------------------------------------------------- /Sources/IPinfo/IPinfo.ASN.swift: -------------------------------------------------------------------------------- 1 | import Firewalls 2 | import IP 3 | import JSON 4 | 5 | extension IPinfo 6 | { 7 | /// A helper type for parsing and formatting an ASN with the `AS` prefix. If the string is 8 | /// empty, the ASN is the null ASN, `0`. 9 | struct ASN 10 | { 11 | let parsed:IP.ASN 12 | } 13 | } 14 | extension IPinfo.ASN:CustomStringConvertible 15 | { 16 | var description:String { self.parsed == 0 ? "" : "AS\(self.parsed)" } 17 | } 18 | extension IPinfo.ASN:LosslessStringConvertible 19 | { 20 | init?(_ string:String) 21 | { 22 | if string.isEmpty 23 | { 24 | self.init(parsed: 0) 25 | return 26 | } 27 | 28 | guard 29 | let i:String.Index = string.index(string.startIndex, 30 | offsetBy: 2, 31 | limitedBy: string.endIndex), 32 | case "AS" = string[..) 48 | { 49 | json[.start_ip] = IPinfo.Address.init(parsed: self.first) 50 | json[.end_ip] = IPinfo.Address.init(parsed: self.last) 51 | json[.asn] = IPinfo.ASN.init(parsed: self.asn) 52 | json[.name] = self.name 53 | json[.domain] = self.domain 54 | } 55 | } 56 | extension IPinfo.ASNRange:JSONObjectDecodable 57 | { 58 | public 59 | init(json:JSON.ObjectDecoder) throws 60 | { 61 | self.init( 62 | first: try json[.start_ip].decode(as: IPinfo.Address.self, with: \.parsed), 63 | last: try json[.end_ip].decode(as: IPinfo.Address.self, with: \.parsed), 64 | asn: try json[.asn].decode(as: IPinfo.ASN.self, with: \.parsed), 65 | name: try json[.name].decode(), 66 | domain: try json[.domain].decode()) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Sources/IPinfo/IPinfo.Address.swift: -------------------------------------------------------------------------------- 1 | import IP 2 | import JSON 3 | 4 | extension IPinfo 5 | { 6 | /// A helper type for parsing and formatting addresses that can be either IPv4 or IPv6. 7 | struct Address 8 | { 9 | let parsed:IP.V6 10 | } 11 | } 12 | extension IPinfo.Address:CustomStringConvertible 13 | { 14 | var description:String { self.parsed.v4?.description ?? self.parsed.description } 15 | } 16 | extension IPinfo.Address:LosslessStringConvertible 17 | { 18 | init?(_ string:String) 19 | { 20 | if let v4:IP.V4 = .init(string) 21 | { 22 | self.init(parsed: .init(v4: v4)) 23 | } 24 | else if 25 | let v6:IP.V6 = .init(string) 26 | { 27 | self.init(parsed: v6) 28 | } 29 | else 30 | { 31 | return nil 32 | } 33 | } 34 | } 35 | extension IPinfo.Address:JSONStringDecodable, JSONStringEncodable 36 | { 37 | } 38 | -------------------------------------------------------------------------------- /Sources/IPinfo/IPinfo.CountryRange.swift: -------------------------------------------------------------------------------- 1 | import IP 2 | import ISO 3 | import JSON 4 | 5 | extension IPinfo 6 | { 7 | @frozen public 8 | struct CountryRange 9 | { 10 | public 11 | let first:IP.V6 12 | public 13 | let last:IP.V6 14 | public 15 | let country:ISO.Country 16 | 17 | @inlinable public 18 | init(first:IP.V6, last:IP.V6, country:ISO.Country) 19 | { 20 | self.first = first 21 | self.last = last 22 | self.country = country 23 | } 24 | } 25 | } 26 | extension IPinfo.CountryRange 27 | { 28 | @frozen public 29 | enum CodingKey:String, Sendable 30 | { 31 | case start_ip 32 | case end_ip 33 | case country 34 | 35 | @available(*, unavailable) case country_name 36 | @available(*, unavailable) case continent 37 | @available(*, unavailable) case continent_name 38 | } 39 | } 40 | extension IPinfo.CountryRange:JSONObjectEncodable 41 | { 42 | public 43 | func encode(to json:inout JSON.ObjectEncoder) 44 | { 45 | json[.start_ip] = IPinfo.Address.init(parsed: self.first) 46 | json[.end_ip] = IPinfo.Address.init(parsed: self.last) 47 | json[.country] = self.country 48 | } 49 | } 50 | extension IPinfo.CountryRange:JSONObjectDecodable 51 | { 52 | public 53 | init(json:JSON.ObjectDecoder) throws 54 | { 55 | self.init( 56 | first: try json[.start_ip].decode(as: IPinfo.Address.self, with: \.parsed), 57 | last: try json[.end_ip].decode(as: IPinfo.Address.self, with: \.parsed), 58 | country: try json[.country].decode()) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Sources/IPinfo/IPinfo.swift: -------------------------------------------------------------------------------- 1 | /// The namespace for IPinfo types. 2 | /// 3 | /// [IPinfo](https://ipinfo.io) is a brand name and therefore this type is spelled `IPinfo` and 4 | /// not `IPInfo` or `IP.Info`. 5 | @frozen public 6 | enum IPinfo 7 | { 8 | } 9 | -------------------------------------------------------------------------------- /Sources/IPinfo/ISO.Country (ext).swift: -------------------------------------------------------------------------------- 1 | import ISO 2 | import JSON 3 | 4 | extension ISO.Country:@retroactive JSONStringDecodable, @retroactive JSONStringEncodable 5 | { 6 | } 7 | -------------------------------------------------------------------------------- /Sources/Whitelists/GitHubWhitelist.swift: -------------------------------------------------------------------------------- 1 | import IP 2 | import JSON 3 | 4 | @frozen public 5 | struct GitHubWhitelist 6 | { 7 | var hooks:[IP.AnyCIDR] 8 | var web:[IP.AnyCIDR] 9 | var api:[IP.AnyCIDR] 10 | var git:[IP.AnyCIDR] 11 | var importer:[IP.AnyCIDR] 12 | var importerGitHubEnterprise:[IP.AnyCIDR] 13 | var packages:[IP.AnyCIDR] 14 | var pages:[IP.AnyCIDR] 15 | var actions:[IP.AnyCIDR] 16 | var actionsMacOS:[IP.AnyCIDR] 17 | var dependabot:[IP.AnyCIDR] 18 | 19 | init(hooks:[IP.AnyCIDR], 20 | web:[IP.AnyCIDR], 21 | api:[IP.AnyCIDR], 22 | git:[IP.AnyCIDR], 23 | importer:[IP.AnyCIDR], 24 | importerGitHubEnterprise:[IP.AnyCIDR], 25 | packages:[IP.AnyCIDR], 26 | pages:[IP.AnyCIDR], 27 | actions:[IP.AnyCIDR], 28 | actionsMacOS:[IP.AnyCIDR], 29 | dependabot:[IP.AnyCIDR]) 30 | { 31 | self.hooks = hooks 32 | self.web = web 33 | self.api = api 34 | self.git = git 35 | self.importer = importer 36 | self.importerGitHubEnterprise = importerGitHubEnterprise 37 | self.packages = packages 38 | self.pages = pages 39 | self.actions = actions 40 | self.actionsMacOS = actionsMacOS 41 | self.dependabot = dependabot 42 | } 43 | } 44 | extension GitHubWhitelist 45 | { 46 | public 47 | func add(to claims:inout [IP.Claims]) 48 | { 49 | // var actions:IP.Claims = .init(id: .github_actions) 50 | var webhook:IP.Claims = .init(id: .github_webhook) 51 | // var other:IP.Claims = .init(id: .github_other) 52 | 53 | // GitHub seems to use subsets of the GitHub Actions address space for its other 54 | // services, which creates overlapping ranges. Some of the addresses are also claimed 55 | // by Bingbot, I guess because Microsoft owns GitHub. 56 | 57 | // actions.extend(with: whitelist.actions) 58 | // actions.extend(with: whitelist.actionsMacOS) 59 | 60 | webhook.extend(with: self.hooks) 61 | 62 | // These also overlap with Bingbot... 63 | 64 | // other.extend(with: whitelist.web) 65 | // other.extend(with: whitelist.api) 66 | // other.extend(with: whitelist.git) 67 | // other.extend(with: whitelist.importer) 68 | // other.extend(with: whitelist.importerGitHubEnterprise) 69 | // other.extend(with: whitelist.packages) 70 | // other.extend(with: whitelist.pages) 71 | // other.extend(with: whitelist.dependabot) 72 | 73 | // claims.append(actions) 74 | claims.append(webhook) 75 | // claims.append(other) 76 | } 77 | } 78 | extension GitHubWhitelist 79 | { 80 | @frozen public 81 | enum CodingKey:String, Sendable 82 | { 83 | case hooks 84 | case web 85 | case api 86 | case git 87 | case github_enterprise_importer 88 | case packages 89 | case pages 90 | case importer 91 | case actions 92 | case actions_macos 93 | case dependabot 94 | } 95 | } 96 | extension GitHubWhitelist:JSONObjectDecodable 97 | { 98 | public 99 | init(json:JSON.ObjectDecoder) throws 100 | { 101 | self.init(hooks: try json[.hooks]?.decode() ?? [], 102 | web: try json[.web]?.decode() ?? [], 103 | api: try json[.api]?.decode() ?? [], 104 | git: try json[.git]?.decode() ?? [], 105 | importer: try json[.importer]?.decode() ?? [], 106 | importerGitHubEnterprise: try json[.github_enterprise_importer]?.decode() ?? [], 107 | packages: try json[.packages]?.decode() ?? [], 108 | pages: try json[.pages]?.decode() ?? [], 109 | actions: try json[.actions]?.decode() ?? [], 110 | actionsMacOS: try json[.actions_macos]?.decode() ?? [], 111 | dependabot: try json[.dependabot]?.decode() ?? []) 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /Sources/Whitelists/IP.AnyCIDR.swift: -------------------------------------------------------------------------------- 1 | import IP 2 | import JSON 3 | 4 | extension IP 5 | { 6 | /// A helper type to represent a CIDR block that can be either IPv4 or IPv6. 7 | @frozen @usableFromInline 8 | enum AnyCIDR 9 | { 10 | case v4(Block) 11 | case v6(Block) 12 | } 13 | } 14 | extension IP.AnyCIDR:CustomStringConvertible 15 | { 16 | @usableFromInline 17 | var description:String 18 | { 19 | switch self 20 | { 21 | case .v4(let block): block.description 22 | case .v6(let block): block.description 23 | } 24 | } 25 | } 26 | extension IP.AnyCIDR:LosslessStringConvertible 27 | { 28 | @usableFromInline 29 | init?(_ string:some StringProtocol) 30 | { 31 | if let block:IP.Block = .init(string) 32 | { 33 | self = .v4(block) 34 | } 35 | else if 36 | let block:IP.Block = .init(string) 37 | { 38 | self = .v6(block) 39 | } 40 | else 41 | { 42 | return nil 43 | } 44 | } 45 | } 46 | extension IP.AnyCIDR:JSONStringDecodable, JSONStringEncodable 47 | { 48 | } 49 | -------------------------------------------------------------------------------- /Sources/Whitelists/IP.Block (ext).swift: -------------------------------------------------------------------------------- 1 | import IP 2 | import JSON 3 | 4 | extension IP.Block:JSONStringDecodable 5 | { 6 | } 7 | -------------------------------------------------------------------------------- /Sources/Whitelists/IP.Claims.swift: -------------------------------------------------------------------------------- 1 | import BSON 2 | import Firewalls 3 | import IP 4 | 5 | extension IP 6 | { 7 | @frozen public 8 | struct Claims:Identifiable, Sendable 9 | { 10 | public 11 | let id:IP.Claimant 12 | 13 | public 14 | var v4:[ClosedRange] 15 | public 16 | var v6:[ClosedRange] 17 | 18 | init(id:IP.Claimant, v4:[ClosedRange] = [], v6:[ClosedRange] = []) 19 | { 20 | self.id = id 21 | self.v4 = v4 22 | self.v6 = v6 23 | } 24 | } 25 | } 26 | extension IP.Claims 27 | { 28 | mutating 29 | func extend(with blocks:[IP.AnyCIDR]) 30 | { 31 | for block:IP.AnyCIDR in blocks 32 | { 33 | switch block 34 | { 35 | case .v4(let block): self.v4.append(block.range) 36 | case .v6(let block): self.v6.append(block.range) 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Sources/Whitelists/SearchbotWhitelist.swift: -------------------------------------------------------------------------------- 1 | import IP 2 | import Firewalls 3 | import JSON 4 | 5 | /// The common whitelist API format shared between 6 | /// [Googlebot](https://developers.google.com/static/search/apis/ipranges/googlebot.json) and 7 | /// [Bingbot](https://www.bing.com/toolbox/bingbot.json). 8 | @frozen public 9 | struct SearchbotWhitelist 10 | { 11 | let blocks:[IP.AnyCIDR] 12 | 13 | init(blocks:[IP.AnyCIDR]) 14 | { 15 | self.blocks = blocks 16 | } 17 | } 18 | extension SearchbotWhitelist 19 | { 20 | public 21 | func add(to claims:inout [IP.Claims], as id:IP.Claimant) 22 | { 23 | var crawler:IP.Claims = .init(id: id) 24 | crawler.extend(with: self.blocks) 25 | claims.append(crawler) 26 | } 27 | } 28 | extension SearchbotWhitelist:JSONObjectDecodable 29 | { 30 | @frozen public 31 | enum CodingKey:String, Sendable 32 | { 33 | case prefixes 34 | enum Prefix:String, Sendable 35 | { 36 | case ipv4Prefix 37 | case ipv6Prefix 38 | } 39 | } 40 | 41 | public 42 | init(json:JSON.ObjectDecoder) throws 43 | { 44 | let blocks:[IP.AnyCIDR] = try json[.prefixes].decode(as: JSON.Array.self) 45 | { 46 | try $0.map 47 | { 48 | let object:JSON.ObjectDecoder = try $0.decode() 49 | let prefix:JSON.FieldDecoder = try object.single() 50 | 51 | switch prefix.key 52 | { 53 | case .ipv4Prefix: return .v4(try prefix.decode()) 54 | case .ipv6Prefix: return .v6(try prefix.decode()) 55 | } 56 | } 57 | } 58 | 59 | self.init(blocks: blocks) 60 | } 61 | } 62 | --------------------------------------------------------------------------------