├── .github └── workflows │ ├── build.yml │ └── build_release.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── hyperspeed.sh └── src ├── client.rs ├── clients ├── base.rs ├── http.rs ├── mod.rs └── tcp_speedtest_net.rs ├── lib.rs ├── server.rs ├── servers ├── base.rs ├── http.rs └── mod.rs └── utils.rs /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | on: push 3 | 4 | env: 5 | CARGO_TERM_COLOR: always 6 | 7 | jobs: 8 | build-linux: 9 | runs-on: ubuntu-latest 10 | env: 11 | RUST_BACKTRACE: full 12 | 13 | strategy: 14 | matrix: 15 | target: 16 | - x86_64-unknown-linux-musl 17 | - aarch64-unknown-linux-musl 18 | 19 | steps: 20 | - uses: actions/checkout@v2 21 | 22 | - name: Install Rust 23 | uses: actions-rs/toolchain@v1 24 | with: 25 | target: ${{ matrix.target }} 26 | toolchain: nightly 27 | default: true 28 | override: true 29 | 30 | - name: Install cross 31 | run: cargo install cross 32 | 33 | - name: Build ${{ matrix.target }} 34 | timeout-minutes: 15 35 | run: | 36 | mkdir -p ./build/release 37 | export RUSTFLAGS="-C link-arg=-lgcc -Clink-arg=-static-libgcc" 38 | cross build --target ${{ matrix.target }} -r -Z build-std=std,panic_abort -Z build-std-features=panic_immediate_abort 39 | cp ./target/${{ matrix.target }}/release/bimc ./build/release/bimc-${{ matrix.target }} 40 | cp ./target/${{ matrix.target }}/release/bim ./build/release/bim-${{ matrix.target }} 41 | 42 | - name: UPX 43 | uses: crazy-max/ghaction-upx@v2 44 | with: 45 | version: latest 46 | files: | 47 | ./build/release/bimc-${{ matrix.target }} 48 | ./build/release/bim-${{ matrix.target }} 49 | args: --best --lzma 50 | 51 | - name: sha256 52 | run: | 53 | cd ./build/release 54 | shasum -a 256 bimc-${{ matrix.target }} > bimc-${{ matrix.target }}.sha256 55 | shasum -a 256 bim-${{ matrix.target }} > bim-${{ matrix.target }}.sha256 56 | 57 | - name: Upload Artifact 58 | uses: actions/upload-artifact@v3 59 | with: 60 | name: bim 61 | path: build/release/* 62 | 63 | build-windows: 64 | runs-on: windows-latest 65 | env: 66 | RUST_BACKTRACE: full 67 | 68 | steps: 69 | - uses: actions/checkout@v2 70 | 71 | - name: Install Rust 72 | uses: actions-rs/toolchain@v1 73 | with: 74 | profile: minimal 75 | toolchain: nightly 76 | default: true 77 | override: true 78 | 79 | - name: Build 80 | timeout-minutes: 15 81 | run: | 82 | cargo build -r 83 | mkdir -p ./build/release 84 | cp ./target/release/bimc.exe ./build/release/bimc.exe 85 | cp ./target/release/bim.exe ./build/release/bim.exe 86 | cd ./build/release 87 | Get-FileHash bimc.exe | Format-List > bimc.exe.sha256 88 | Get-FileHash bim.exe | Format-List > bim.exe.sha256 89 | 90 | - name: Upload Artifact 91 | uses: actions/upload-artifact@v3 92 | with: 93 | name: bim 94 | path: build/release/* 95 | 96 | build-macos: 97 | runs-on: macos-latest 98 | env: 99 | RUST_BACKTRACE: full 100 | 101 | steps: 102 | - uses: actions/checkout@v2 103 | 104 | - name: Install Rust 105 | uses: actions-rs/toolchain@v1 106 | with: 107 | profile: minimal 108 | toolchain: nightly 109 | default: true 110 | override: true 111 | 112 | - name: Build 113 | timeout-minutes: 120 114 | run: | 115 | cargo build -r 116 | mkdir -p ./build/release 117 | cp ./target/release/bim ./build/release/bim-macos 118 | cp ./target/release/bimc ./build/release/bimc-macos 119 | cd ./build/release 120 | shasum -a 256 bim-macos > bim-macos.sha256 121 | shasum -a 256 bimc-macos > bimc-macos.sha256 122 | 123 | - name: Upload Artifact 124 | uses: actions/upload-artifact@v3 125 | with: 126 | name: bim 127 | path: build/release/* 128 | -------------------------------------------------------------------------------- /.github/workflows/build_release.yml: -------------------------------------------------------------------------------- 1 | name: Build Releases 2 | on: 3 | push: 4 | tags: 5 | - v* 6 | 7 | env: 8 | CARGO_TERM_COLOR: always 9 | 10 | jobs: 11 | build-linux: 12 | runs-on: ubuntu-latest 13 | env: 14 | RUST_BACKTRACE: full 15 | 16 | strategy: 17 | matrix: 18 | target: 19 | - x86_64-unknown-linux-musl 20 | - aarch64-unknown-linux-musl 21 | 22 | steps: 23 | - uses: actions/checkout@v2 24 | 25 | - name: Install Rust 26 | uses: actions-rs/toolchain@v1 27 | with: 28 | target: ${{ matrix.target }} 29 | toolchain: nightly 30 | default: true 31 | override: true 32 | 33 | - name: Install cross 34 | run: cargo install cross 35 | 36 | - name: Build ${{ matrix.target }} 37 | timeout-minutes: 15 38 | run: | 39 | mkdir -p ./build/release 40 | export RUSTFLAGS="-C link-arg=-lgcc -Clink-arg=-static-libgcc" 41 | cross build --target ${{ matrix.target }} -r -Z build-std=std,panic_abort -Z build-std-features=panic_immediate_abort 42 | cp ./target/${{ matrix.target }}/release/bimc ./build/release/bimc-${{ matrix.target }} 43 | cp ./target/${{ matrix.target }}/release/bim ./build/release/bim-${{ matrix.target }} 44 | 45 | - name: UPX 46 | uses: crazy-max/ghaction-upx@v2 47 | with: 48 | version: latest 49 | files: | 50 | ./build/release/bimc-${{ matrix.target }} 51 | ./build/release/bim-${{ matrix.target }} 52 | args: --best --lzma 53 | 54 | - name: sha256 55 | run: | 56 | cd ./build/release 57 | shasum -a 256 bimc-${{ matrix.target }} > bimc-${{ matrix.target }}.sha256 58 | shasum -a 256 bim-${{ matrix.target }} > bim-${{ matrix.target }}.sha256 59 | 60 | - name: Upload Github Assets 61 | uses: softprops/action-gh-release@v1 62 | env: 63 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 64 | with: 65 | files: build/release/* 66 | prerelease: ${{ contains(github.ref, '-') }} 67 | 68 | build-windows: 69 | runs-on: windows-latest 70 | env: 71 | RUST_BACKTRACE: full 72 | 73 | steps: 74 | - uses: actions/checkout@v2 75 | 76 | - name: Install Rust 77 | uses: actions-rs/toolchain@v1 78 | with: 79 | profile: minimal 80 | toolchain: nightly 81 | default: true 82 | override: true 83 | 84 | - name: Build 85 | timeout-minutes: 15 86 | run: | 87 | cargo build -r 88 | mkdir -p ./build/release 89 | cp ./target/release/bimc.exe ./build/release/bimc.exe 90 | cp ./target/release/bim.exe ./build/release/bim.exe 91 | cd ./build/release 92 | Get-FileHash bimc.exe | Format-List > bimc.exe.sha256 93 | Get-FileHash bim.exe | Format-List > bim.exe.sha256 94 | 95 | - name: Upload Github Assets 96 | uses: softprops/action-gh-release@v1 97 | env: 98 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 99 | with: 100 | files: build/release/* 101 | prerelease: ${{ contains(github.ref, '-') }} 102 | 103 | build-macos: 104 | runs-on: macos-latest 105 | env: 106 | RUST_BACKTRACE: full 107 | 108 | steps: 109 | - uses: actions/checkout@v2 110 | 111 | - name: Install Rust 112 | uses: actions-rs/toolchain@v1 113 | with: 114 | profile: minimal 115 | toolchain: nightly 116 | default: true 117 | override: true 118 | 119 | - name: Build 120 | timeout-minutes: 120 121 | run: | 122 | cargo build -r 123 | mkdir -p ./build/release 124 | cp ./target/release/bim ./build/release/bim-macos 125 | cp ./target/release/bimc ./build/release/bimc-macos 126 | cd ./build/release 127 | shasum -a 256 bim-macos > bim-macos.sha256 128 | shasum -a 256 bimc-macos > bimc-macos.sha256 129 | 130 | - name: Upload Github Assets 131 | uses: softprops/action-gh-release@v1 132 | env: 133 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 134 | with: 135 | files: build/release/* 136 | prerelease: ${{ contains(github.ref, '-') }} 137 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | 13 | # Added by cargo 14 | 15 | /target 16 | bimc 17 | venv 18 | .vscode 19 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bim-core" 3 | version = "0.17.0" 4 | edition = "2021" 5 | description = "Client core for bench.im." 6 | license = "GPL-2.0-only" 7 | 8 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 9 | 10 | [[bin]] 11 | name = "bim" 12 | path = "src/server.rs" 13 | 14 | [[bin]] 15 | name = "bimc" 16 | path = "src/client.rs" 17 | 18 | [dependencies] 19 | url = "2" 20 | getopts = "0.2" 21 | webpki-roots = "0.22" 22 | rustls = "0.20" 23 | tiny_http = "0.11" 24 | unicode-width = "0.1" 25 | serde = { version = "1.0", features = ["derive"] } 26 | 27 | log = "0.4" 28 | env_logger = "0.9" 29 | 30 | [profile.release] 31 | opt-level = 'z' 32 | strip = true 33 | lto = true 34 | codegen-units = 1 35 | panic = "abort" 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bim-core 2 | Client core for bench.im 3 | -------------------------------------------------------------------------------- /hyperspeed.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | RED='\033[0;31m' 4 | GREEN='\033[0;32m' 5 | YELLOW='\033[0;33m' 6 | PURPLE="\033[0;35m" 7 | CYAN='\033[0;36m' 8 | ENDC='\033[0m' 9 | 10 | check_wget() { 11 | if [ ! -e '/usr/bin/wget' ]; then 12 | echo "请先安装 wget" && exit 1 13 | fi 14 | } 15 | 16 | check_bimc() { 17 | if [ ! -e './bimc' ]; then 18 | echo "正在获取组件" 19 | arch=$(uname -m) 20 | wget --no-check-certificate -qO bimc https://bench.im/bimc-$arch > /dev/null 2>&1 21 | chmod +x bimc 22 | fi 23 | } 24 | 25 | print_info() { 26 | echo "——————————————————————————— HyperSpeed —————————————————————————————" 27 | echo " bash <(wget -qO- https://bench.im/hyperspeed)" 28 | echo " 项目修改自: https://github.com/zq/superspeed/" 29 | echo " 脚本更新: 2023/4/13 | 组件更新: 2023/11/1 | 组件版本: 0.17.0" 30 | echo "————————————————————————————————————————————————————————————————————" 31 | } 32 | 33 | get_options() { 34 | echo -e " 测速类型: ${GREEN}1.${ENDC} 三网测速 ${GREEN}2.${ENDC} 取消测速 ${GREEN}0.${ENDC} 港澳台日韩" 35 | echo -e " ${GREEN}3.${ENDC} 电信节点 ${GREEN}4.${ENDC} 联通节点 ${GREEN}5.${ENDC} 移动节点" 36 | echo -e " ${GREEN}6.${ENDC} 教育网IPv4 ${GREEN}7.${ENDC} 教育网IPv6 ${GREEN}8.${ENDC} 三网IPv6" 37 | while :; do read -p " 请选择测速类型(默认: 1): " selection 38 | if [[ "$selection" == "" ]]; then 39 | selection=1 40 | break 41 | elif [[ ! $selection =~ ^[0-8]$ ]]; then 42 | echo -e " ${RED}输入错误${ENDC}, 请输入正确的数字!" 43 | else 44 | break 45 | fi 46 | done 47 | while :; do read -p " 启用八线程测速[y/N](默认: N): " multi 48 | if [[ "$multi" == "y" ]]; then 49 | thread=" -m" 50 | break 51 | else 52 | thread="" 53 | break 54 | fi 55 | done 56 | } 57 | 58 | speed_test(){ 59 | local nodeLocation=$1 60 | local nodeISP=$2 61 | local extra=$3 62 | local dl=$(echo "$4"| base64 -d) 63 | local ul=$(echo "$5"| base64 -d) 64 | local name=$(./bimc -n "$nodeLocation") 65 | 66 | output=$(./bimc $dl $ul$thread $extra) 67 | local upload="$(echo "$output" | cut -n -d ',' -f1)" 68 | local uploadStatus="$(echo "$output" | cut -n -d ',' -f2)" 69 | local download="$(echo "$output" | cut -n -d ',' -f3)" 70 | local downloadStatus="$(echo "$output" | cut -n -d ',' -f4)" 71 | local latency="$(echo "$output" | cut -n -d ',' -f5)" 72 | local jitter="$(echo "$output" | cut -n -d ',' -f6)" 73 | 74 | result="${YELLOW}${nodeISP}|${GREEN}${name}${CYAN}↑${upload}${YELLOW}${uploadStatus}${CYAN} ↓${download}${YELLOW}${downloadStatus}${CYAN} ↕ ${GREEN}${latency}${CYAN} ϟ ${GREEN}${jitter}${ENDC}" 75 | if [ $uploadStatus = "正常" ] && [ $downloadStatus = "正常" ]; then 76 | printf "$result\n" 77 | else 78 | failed+=("$result") 79 | fi 80 | } 81 | 82 | run_test() { 83 | [[ ${selection} == 2 ]] && exit 1 84 | 85 | echo "————————————————————————————————————————————————————————————————————" 86 | echo "测速服务器信息 ↑ 上传/Mbps ↓ 下载/Mbps ↕ 延迟/ms ϟ 抖动/ms" 87 | echo "————————————————————————————————————————————————————————————————————" 88 | start=$(date +%s) 89 | failed=( ) 90 | 91 | if [[ ${selection} == 1 ]] || [[ ${selection} == 3 ]]; then 92 | speed_test '上海' '电信' '' 'aHR0cDovL3NwZWVkdGVzdDEub25saW5lLnNoLmNuOjgwODAvZG93bmxvYWQK' 'aHR0cDovL3NwZWVkdGVzdDEub25saW5lLnNoLmNuOjgwODAvdXBsb2FkCg==' 93 | speed_test '江苏镇江5G' '电信' '' 'aHR0cDovLzVnemhlbmppYW5nLnNwZWVkdGVzdC5qc2luZm8ubmV0OjgwODAvZG93bmxvYWQ=' 'aHR0cDovLzVnemhlbmppYW5nLnNwZWVkdGVzdC5qc2luZm8ubmV0OjgwODAvdXBsb2Fk' 94 | speed_test '江苏南京5G' '电信' '' 'aHR0cDovLzVnbmFuamluZy5zcGVlZHRlc3QuanNpbmZvLm5ldDo4MDgwL2Rvd25sb2FkCg==' 'aHR0cDovLzVnbmFuamluZy5zcGVlZHRlc3QuanNpbmZvLm5ldDo4MDgwL3VwbG9hZAo=' 95 | speed_test '安徽合肥5G' '电信' '' 'aHR0cDovL3NwZWVkdGVzdDEuYWgxNjMuY29tOjgwODAvZG93bmxvYWQ=' 'aHR0cDovL3NwZWVkdGVzdDEuYWgxNjMuY29tOjgwODAvdXBsb2Fk' 96 | speed_test '天津5G' '电信' '' 'aHR0cDovL3N5LnRqdGVsZS5jb206ODA4MC9kb3dubG9hZA==' 'aHR0cDovL3N5LnRqdGVsZS5jb206ODA4MC91cGxvYWQ=' 97 | speed_test '天津' '电信' '' 'aHR0cDovL3RqcmF0ZS50anRlbGUuY29tOjgwODAvZG93bmxvYWQ=' 'aHR0cDovL3RqcmF0ZS50anRlbGUuY29tOjgwODAvdXBsb2Fk' 98 | speed_test '四川成都' '电信' '' 'aHR0cDovL3NwZWVkdGVzdDEuc2MuMTg5LmNuOjgwODAvZG93bmxvYWQ=' 'aHR0cDovL3NwZWVkdGVzdDEuc2MuMTg5LmNuOjgwODAvdXBsb2Fk' 99 | speed_test '甘肃兰州' '电信' '' 'aHR0cDovL3NwZWVkLmJhamlhbmp1bi5jb206ODA4MC9kb3dubG9hZA==' 'aHR0cDovL3NwZWVkLmJhamlhbmp1bi5jb206ODA4MC91cGxvYWQ=' 100 | fi 101 | 102 | if [[ ${selection} == 1 ]] || [[ ${selection} == 4 ]]; then 103 | speed_test '上海5G' '联通' '' 'aHR0cDovLzVnLnNodW5pY29tdGVzdC5jb206ODA4MC9kb3dubG9hZAo=' 'aHR0cDovLzVnLnNodW5pY29tdGVzdC5jb206ODA4MC91cGxvYWQK' 104 | speed_test '江苏无锡' '联通' '' 'aHR0cHM6Ly9zcGVlZHRlc3QyLm5pdXRrLmNvbTo4MDgwL2Rvd25sb2Fk' 'aHR0cHM6Ly9zcGVlZHRlc3QyLm5pdXRrLmNvbTo4MDgwL3VwbG9hZA==' 105 | speed_test '江西南昌' '联通' '' 'aHR0cDovL3NwZWVkdGVzdC5qeHVuaWNvbS5jb206ODA4MC9kb3dubG9hZA==' 'aHR0cDovL3NwZWVkdGVzdC5qeHVuaWNvbS5jb206ODA4MC91cGxvYWQ=' 106 | speed_test '河南郑州5G' '联通' '' 'aHR0cDovLzVndGVzdC5zaGFuZ2R1LmNvbTo4MDgwL2Rvd25sb2Fk' 'aHR0cDovLzVndGVzdC5zaGFuZ2R1LmNvbTo4MDgwL3VwbG9hZA==' 107 | speed_test '湖南长沙5G' '联通' '' 'aHR0cDovL3NwZWVkdGVzdDAxLmhuMTY1LmNvbTo4MDgwL2Rvd25sb2Fk' 'aHR0cDovL3NwZWVkdGVzdDAxLmhuMTY1LmNvbTo4MDgwL3VwbG9hZA==' 108 | speed_test '辽宁沈阳' '联通' '' 'aHR0cDovL3VuaWNvbXNwZWVkdGVzdC5jb206ODA4MC9kb3dubG9hZAo=' 'aHR0cDovL3VuaWNvbXNwZWVkdGVzdC5jb206ODA4MC91cGxvYWQK' 109 | speed_test '福建福州' '联通' '' 'aHR0cDovL3VwbG9hZDEudGVzdHNwZWVkLmNkbjE2LmNvbTo4MDgwL2Rvd25sb2Fk' 'aHR0cDovL3VwbG9hZDEudGVzdHNwZWVkLmNkbjE2LmNvbTo4MDgwL3VwbG9hZA==' 110 | fi 111 | 112 | if [[ ${selection} == 1 ]] || [[ ${selection} == 5 ]]; then 113 | speed_test '北京' '移动' '' 'aHR0cDovLzIxMS4xMzYuMzAuMTE0OjkwMDAvc3BlZWQvMjAwMDAwMC5kYXRhCg==' 'aHR0cDovLzIxMS4xMzYuMzAuMTE0OjkwMDAvc3BlZWQvMjAwMDAwLmRhdGEK' 114 | speed_test '浙江杭州5G' '移动' '' 'aHR0cDovL3NwZWVkdGVzdC4xMzlwbGF5LmNvbTo4MDgwL2Rvd25sb2Fk' 'aHR0cDovL3NwZWVkdGVzdC4xMzlwbGF5LmNvbTo4MDgwL3VwbG9hZA==' 115 | speed_test '陕西西安5G' '移动' '' 'aHR0cDovL3NwZWVkdGVzdC5vbmUtcHVuY2gud2luOjgwODAvZG93bmxvYWQ=' 'aHR0cDovL3NwZWVkdGVzdC5vbmUtcHVuY2gud2luOjgwODAvdXBsb2Fk' 116 | speed_test '四川成都' '移动' '' 'aHR0cDovL3NwZWVkdGVzdDEuc2MuY2hpbmFtb2JpbGUuY29tOjgwODAvZG93bmxvYWQ=' 'aHR0cDovL3NwZWVkdGVzdDEuc2MuY2hpbmFtb2JpbGUuY29tOjgwODAvdXBsb2Fk' 117 | speed_test '甘肃兰州' '移动' '' 'aHR0cDovL3NwZWVkdGVzdDEuZ3MuY2hpbmFtb2JpbGUuY29tOjgwODAvZG93bmxvYWQ=' 'aHR0cDovL3NwZWVkdGVzdDEuZ3MuY2hpbmFtb2JpbGUuY29tOjgwODAvdXBsb2Fk' 118 | fi 119 | 120 | if [[ ${selection} == 6 ]]; then 121 | speed_test '中国科技大学' '合肥' '' 'aHR0cHM6Ly90ZXN0LnVzdGMuZWR1LmNuL2JhY2tlbmQvZ2FyYmFnZS5waHAK' 'aHR0cHM6Ly90ZXN0LnVzdGMuZWR1LmNuL2JhY2tlbmQvZW1wdHkucGhwCg==' 122 | speed_test '东北大学' '沈阳' '' 'aHR0cHM6Ly9pcHR2LnRzaW5naHVhLmVkdS5jbi9zdC9nYXJiYWdlLnBocAo=' 'aHR0cHM6Ly9pcHR2LnRzaW5naHVhLmVkdS5jbi9zdC9lbXB0eS5waHAK' 123 | speed_test '上海交通大学' '上海' '' 'aHR0cHM6Ly93c3VzLnNqdHUuZWR1LmNuL3NwZWVkdGVzdC9iYWNrZW5kL2dhcmJhZ2UucGhwCg==' 'aHR0cHM6Ly93c3VzLnNqdHUuZWR1LmNuL3NwZWVkdGVzdC9iYWNrZW5kL2VtcHR5LnBocAo=' 124 | fi 125 | 126 | if [[ ${selection} == 7 ]]; then 127 | speed_test '中国科技大学' '合肥' '-6' 'aHR0cHM6Ly90ZXN0Ni51c3RjLmVkdS5jbi9iYWNrZW5kL2dhcmJhZ2UucGhwCg==' 'aHR0cHM6Ly90ZXN0Ni51c3RjLmVkdS5jbi9iYWNrZW5kL2VtcHR5LnBocAo=' 128 | speed_test '东北大学' '沈阳' '-6' 'aHR0cHM6Ly9pcHR2LnRzaW5naHVhLmVkdS5jbi9zdC9nYXJiYWdlLnBocAo=' 'aHR0cHM6Ly9pcHR2LnRzaW5naHVhLmVkdS5jbi9zdC9lbXB0eS5waHAK' 129 | speed_test '上海交通大学' '上海' '-6' 'aHR0cHM6Ly93c3VzLnNqdHUuZWR1LmNuL3NwZWVkdGVzdC9iYWNrZW5kL2dhcmJhZ2UucGhwCg==' 'aHR0cHM6Ly93c3VzLnNqdHUuZWR1LmNuL3NwZWVkdGVzdC9iYWNrZW5kL2VtcHR5LnBocAo=' 130 | fi 131 | 132 | if [[ ${selection} == 8 ]]; then 133 | speed_test '甘肃兰州' '电信' '-6' 'aHR0cDovL3NwZWVkLmJhamlhbmp1bi5jb206ODA4MC9kb3dubG9hZA==' 'aHR0cDovL3NwZWVkLmJhamlhbmp1bi5jb206ODA4MC91cGxvYWQ=' 134 | speed_test '上海5G' '联通' '-6' 'aHR0cDovLzVnLnNodW5pY29tdGVzdC5jb206ODA4MC9kb3dubG9hZAo=' 'aHR0cDovLzVnLnNodW5pY29tdGVzdC5jb206ODA4MC91cGxvYWQK' 135 | fi 136 | 137 | if [[ ${selection} == 0 ]]; then 138 | speed_test '环电宽频' '香港' '' 'aHR0cDovL29va2xhLWhpZGMuaGdjb25haXIuaGdjLmNvbS5oazo4MDgwL2Rvd25sb2FkCg==' 'aHR0cDovL29va2xhLWhpZGMuaGdjb25haXIuaGdjLmNvbS5oazo4MDgwL3VwbG9hZAo=' 139 | speed_test '澳门电讯' '澳门' '' 'aHR0cDovL3NwZWVkdGVzdDUubWFjYXUuY3RtLm5ldDo4MDgwL2Rvd25sb2FkCg==' 'aHR0cDovL3NwZWVkdGVzdDUubWFjYXUuY3RtLm5ldDo4MDgwL3VwbG9hZAo=' 140 | speed_test '中华电信' '台北' '' 'aHR0cDovL3RwMS5jaHRtLmhpbmV0Lm5ldDo4MDgwL2Rvd25sb2FkCg==' 'aHR0cDovL3RwMS5jaHRtLmhpbmV0Lm5ldDo4MDgwL3VwbG9hZAo=' 141 | speed_test '乐天移动' '东京' '' 'aHR0cDovL29va2xhLm1ic3BlZWQubmV0OjgwODAvZG93bmxvYWQK' 'aHR0cDovL29va2xhLm1ic3BlZWQubmV0OjgwODAvdXBsb2FkCg==' 142 | speed_test 'Kdatacenter ' '首尔' '' 'aHR0cDovL3NwZWVkdGVzdC5rZGF0YWNlbnRlci5jb206ODA4MC9kb3dubG9hZAo=' 'aHR0cDovL3NwZWVkdGVzdC5rZGF0YWNlbnRlci5jb206ODA4MC91cGxvYWQK' 143 | fi 144 | 145 | end=$(date +%s) 146 | 147 | if [ ${#failed[@]} -ne 0 ]; then 148 | echo "--------------------------------------------------------------------" 149 | for value in "${failed[@]}" 150 | do 151 | printf "$value\n" 152 | done 153 | fi 154 | 155 | echo "————————————————————————————————————————————————————————————————————" 156 | 157 | if [[ "$thread" == "" ]]; then 158 | echo -ne " 单线程" 159 | else 160 | echo -ne " 八线程" 161 | fi 162 | 163 | time=$(( $end - $start )) 164 | if [[ $time -gt 60 ]]; then 165 | min=$(expr $time / 60) 166 | sec=$(expr $time % 60) 167 | echo -e "测试完成, 本次测速耗时: ${min} 分 ${sec} 秒" 168 | else 169 | echo -e "测试完成, 本次测速耗时: ${time} 秒" 170 | fi 171 | echo -ne " 当前时间: " 172 | echo $(TZ=Asia/Shanghai date --rfc-3339=seconds) 173 | } 174 | 175 | run_all() { 176 | check_wget; 177 | check_bimc; 178 | clear; 179 | print_info; 180 | get_options; 181 | run_test; 182 | rm -rf bimc; 183 | } 184 | 185 | LANG=C 186 | run_all 187 | -------------------------------------------------------------------------------- /src/client.rs: -------------------------------------------------------------------------------- 1 | use getopts::Options; 2 | use std::env; 3 | 4 | use bim_core::clients::{Client, HTTPClient, SpeedtestNetTcpClient}; 5 | use bim_core::utils::{justify_name, SpeedTestResult}; 6 | 7 | fn print_usage(program: &str, opts: Options) { 8 | let brief = format!("Usage: {} DOWNLOAD_URL UPLOAD_URL [options]", program); 9 | print!("{}", opts.usage(&brief)); 10 | } 11 | 12 | fn get_client( 13 | client_name: &str, 14 | download_url: String, 15 | upload_url: String, 16 | ipv6: bool, 17 | threads: u8, 18 | ) -> Option> { 19 | match client_name { 20 | "http" => HTTPClient::build(download_url, upload_url, ipv6, threads), 21 | "tcp" => SpeedtestNetTcpClient::build(upload_url, ipv6, threads), 22 | _ => None, 23 | } 24 | } 25 | 26 | fn main() { 27 | let args: Vec = env::args().collect(); 28 | let program = args[0].clone(); 29 | 30 | let mut opts = Options::new(); 31 | opts.optopt("c", "client", "set test client", "NAME"); 32 | opts.optflagopt("m", "multi", "enable multi threads", "NUM"); 33 | opts.optflag("6", "ipv6", "enable ipv6"); 34 | opts.optflag("n", "name", "print justified name"); 35 | opts.optflag("h", "help", "print this help menu"); 36 | let matches = match opts.parse(&args[1..]) { 37 | Ok(m) => m, 38 | Err(f) => { 39 | println!("{}\n", f.to_string()); 40 | print_usage(&program, opts); 41 | return; 42 | } 43 | }; 44 | 45 | if matches.opt_present("h") { 46 | print_usage(&program, opts); 47 | return; 48 | } 49 | 50 | let (dl, ul) = match matches.free.as_slice() { 51 | [first, second, ..] => (Some(first), Some(second)), 52 | _ => { 53 | print_usage(&program, opts); 54 | return; 55 | } 56 | }; 57 | 58 | if matches.opt_present("n") { 59 | if let Some(name) = dl { 60 | print!("{}", justify_name(name, 12, true)); 61 | } else { 62 | print_usage(&program, opts); 63 | } 64 | return; 65 | } 66 | 67 | if ul.is_none() { 68 | print_usage(&program, opts); 69 | return; 70 | } 71 | 72 | let download_url = dl.unwrap().clone(); 73 | let upload_url = ul.unwrap().clone(); 74 | let ipv6 = matches.opt_present("6"); 75 | 76 | let theads = matches 77 | .opt_str("m") 78 | .and_then(|value| value.parse().ok()) 79 | .unwrap_or(1); 80 | 81 | #[cfg(debug_assertions)] 82 | env_logger::init(); 83 | 84 | let client_name = matches.opt_str("c").unwrap_or("http".to_string()); 85 | let r = match get_client(&client_name, download_url, upload_url, ipv6, theads) { 86 | Some(mut client) => { 87 | let _ = (*client).run(); 88 | client.result() 89 | } 90 | None => SpeedTestResult::build(0.0, "失败".to_string(), 0.0, "失败".to_string(), 0.0, 0.0), 91 | }; 92 | 93 | println!("{}", r.text()); 94 | } 95 | -------------------------------------------------------------------------------- /src/clients/base.rs: -------------------------------------------------------------------------------- 1 | use std::io::{Read, Write}; 2 | use std::net::{SocketAddr, TcpStream, ToSocketAddrs}; 3 | use std::sync::{Arc, Barrier, RwLock}; 4 | use std::thread; 5 | use std::time::{Duration, Instant}; 6 | 7 | #[cfg(debug_assertions)] 8 | use log::debug; 9 | 10 | use rustls::{OwnedTrustAnchor, RootCertStore}; 11 | use url::Url; 12 | 13 | use crate::utils::SpeedTestResult; 14 | 15 | pub trait GenericStream: Read + Write {} 16 | 17 | impl GenericStream for T {} 18 | 19 | pub fn get_address(url: &Url, ipv6: bool) -> Option { 20 | let host = url.host_str()?; 21 | let port = url.port_or_known_default()?; 22 | 23 | let host_port = format!("{host}:{port}"); 24 | let addresses = host_port.to_socket_addrs().ok()?; 25 | 26 | addresses 27 | .into_iter() 28 | .find(|addr| (addr.is_ipv6() && ipv6) || (addr.is_ipv4() && !ipv6)) 29 | } 30 | 31 | pub fn make_connection(address: &SocketAddr, url: &Url) -> Result, String> { 32 | let ssl = if url.scheme() == "https" { true } else { false }; 33 | let mut retry = 3; 34 | 35 | let mut root_store = RootCertStore::empty(); 36 | root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map( 37 | |ta| { 38 | OwnedTrustAnchor::from_subject_spki_name_constraints( 39 | ta.subject, 40 | ta.spki, 41 | ta.name_constraints, 42 | ) 43 | }, 44 | )); 45 | 46 | let config = rustls::ClientConfig::builder() 47 | .with_safe_defaults() 48 | .with_root_certificates(root_store) 49 | .with_no_client_auth(); 50 | 51 | let server_name = url.host_str().unwrap().try_into().unwrap(); 52 | let conn = rustls::ClientConnection::new(Arc::new(config), server_name).unwrap(); 53 | 54 | while retry > 0 { 55 | if let Ok(stream) = TcpStream::connect_timeout(&address, Duration::from_micros(1_000_000)) { 56 | #[cfg(debug_assertions)] 57 | debug!("TCP connected"); 58 | 59 | let _r = stream.set_write_timeout(Some(Duration::from_secs(3))); 60 | let _r = stream.set_read_timeout(Some(Duration::from_secs(3))); 61 | if !ssl { 62 | return Ok(Box::new(stream)); 63 | } 64 | 65 | let tls = rustls::StreamOwned::new(conn, stream); 66 | 67 | #[cfg(debug_assertions)] 68 | debug!("SSL connected"); 69 | 70 | return Ok(Box::new(tls)); 71 | } 72 | 73 | retry -= 1; 74 | } 75 | 76 | Err(String::from("连接失败")) 77 | } 78 | 79 | pub fn request_tcp_ping(address: &SocketAddr) -> u128 { 80 | let now = Instant::now(); 81 | let r = TcpStream::connect_timeout(&address, Duration::from_micros(1_000_000)); 82 | let used = now.elapsed().as_micros(); 83 | match r { 84 | Ok(_) => used, 85 | Err(_e) => { 86 | #[cfg(debug_assertions)] 87 | debug!("Ping {_e}"); 88 | 89 | 0 90 | } 91 | } 92 | } 93 | 94 | pub struct LoadCounter { 95 | counter: RwLock, 96 | stater: Barrier, 97 | ender: RwLock, 98 | results: RwLock>, 99 | } 100 | 101 | impl LoadCounter { 102 | pub fn new(threads: u8) -> Self { 103 | Self { 104 | counter: RwLock::new(0), 105 | stater: Barrier::new((threads + 1) as usize), 106 | ender: RwLock::new(false), 107 | results: RwLock::new(vec![]), 108 | } 109 | } 110 | 111 | pub fn wait(&self) { 112 | self.stater.wait(); 113 | } 114 | 115 | pub fn end(&self) { 116 | let mut e = self.ender.write().unwrap(); 117 | *e = true; 118 | } 119 | 120 | pub fn is_end(&self) -> bool { 121 | let e = self.ender.read().unwrap(); 122 | *e 123 | } 124 | 125 | pub fn increase(&self, count: u64) { 126 | let mut c = self.counter.write().unwrap(); 127 | *c += count; 128 | } 129 | 130 | pub fn count(&self, time_passed: u128) { 131 | let c = { *self.counter.read().unwrap() }; 132 | 133 | let mut results = self.results.write().unwrap(); 134 | results.push((c, time_passed)); 135 | } 136 | 137 | pub fn speed(&self) -> f64 { 138 | let (c18, t18) = self.results.read().unwrap()[17]; 139 | let (c28, t28) = self.results.read().unwrap()[27]; 140 | 141 | ((c28 - c18) * 8) as f64 / (t28 - t18) as f64 142 | } 143 | 144 | pub fn status(&self) -> String { 145 | let mut stop = 0; 146 | let mut last = 0; 147 | let results = self.results.read().unwrap().to_vec(); 148 | 149 | #[cfg(debug_assertions)] 150 | debug!("Results {results:?}"); 151 | 152 | for (num, _) in results { 153 | if num == last { 154 | stop += 1; 155 | } 156 | last = num; 157 | } 158 | 159 | if stop < 6 { 160 | String::from("正常") 161 | } else { 162 | String::from("断流") 163 | } 164 | } 165 | } 166 | 167 | pub trait Client { 168 | fn result(&self) -> SpeedTestResult; 169 | 170 | fn ping(&mut self) -> bool; 171 | 172 | fn upload(&mut self) -> bool; 173 | 174 | fn download(&mut self) -> bool; 175 | 176 | fn run(&mut self) -> bool { 177 | let r = self.ping(); 178 | if r { 179 | thread::sleep(Duration::from_secs(2)); 180 | self.upload(); 181 | thread::sleep(Duration::from_secs(3)); 182 | self.download(); 183 | return true; 184 | } 185 | false 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /src/clients/http.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use std::net::SocketAddr; 3 | use std::sync::Arc; 4 | use std::thread; 5 | use std::time::{Duration, Instant}; 6 | 7 | #[cfg(debug_assertions)] 8 | use log::debug; 9 | 10 | use url::Url; 11 | 12 | use crate::clients::base::{get_address, make_connection, request_tcp_ping, Client, LoadCounter}; 13 | use crate::utils::SpeedTestResult; 14 | 15 | use std::io::{Read, Write}; 16 | use std::time::SystemTime; 17 | 18 | pub struct HTTPClient { 19 | download_url: Url, 20 | upload_url: Url, 21 | threads: u8, 22 | 23 | address: SocketAddr, 24 | 25 | upload: f64, 26 | upload_status: String, 27 | download: f64, 28 | download_status: String, 29 | latency: f64, 30 | jitter: f64, 31 | } 32 | 33 | impl HTTPClient { 34 | pub fn build( 35 | download_url: String, 36 | upload_url: String, 37 | ipv6: bool, 38 | threads: u8, 39 | ) -> Option> { 40 | let download_url = Url::parse(&download_url).ok()?; 41 | let upload_url = Url::parse(&upload_url).ok()?; 42 | 43 | let address = get_address(&download_url, ipv6)?; 44 | 45 | #[cfg(debug_assertions)] 46 | debug!("IP address {address}"); 47 | 48 | let r = "取消".to_owned(); 49 | Some(Box::new(Self { 50 | download_url, 51 | upload_url, 52 | threads, 53 | address, 54 | upload: 0.0, 55 | upload_status: r.clone(), 56 | download: 0.0, 57 | download_status: r.clone(), 58 | latency: 0.0, 59 | jitter: 0.0, 60 | })) 61 | } 62 | 63 | fn run_load(&mut self, load: u8) -> Result> { 64 | let url = match load { 65 | 0 => self.upload_url.clone(), 66 | _ => self.download_url.clone(), 67 | }; 68 | let counter = Arc::new(LoadCounter::new(self.threads)); 69 | let mut tasks = vec![]; 70 | 71 | for _ in 0..self.threads { 72 | let a = self.address.clone(); 73 | let u = url.clone(); 74 | let c = counter.clone(); 75 | 76 | let task = thread::spawn(move || { 77 | match load { 78 | 0 => request_http_upload(a, u, c), 79 | _ => request_http_download(a, u, c), 80 | }; 81 | }); 82 | tasks.push(task); 83 | thread::sleep(Duration::from_millis(250)); 84 | } 85 | 86 | let mut time_passed = 0; 87 | counter.wait(); 88 | 89 | let now = Instant::now(); 90 | while time_passed < 14_000_000 { 91 | thread::sleep(Duration::from_millis(500)); 92 | time_passed = now.elapsed().as_micros(); 93 | 94 | counter.count(time_passed); 95 | } 96 | 97 | counter.end(); 98 | for task in tasks { 99 | let _ = task.join(); 100 | } 101 | 102 | match load { 103 | 0 => { 104 | self.upload = counter.speed(); 105 | self.upload_status = counter.status(); 106 | } 107 | _ => { 108 | self.download = counter.speed(); 109 | self.download_status = counter.status(); 110 | } 111 | } 112 | 113 | Ok(true) 114 | } 115 | } 116 | 117 | impl Client for HTTPClient { 118 | fn ping(&mut self) -> bool { 119 | let mut count = 0; 120 | let mut pings = [0u128; 6]; 121 | let mut ping_min = 10000000; 122 | 123 | while count < 6 { 124 | let ping = request_tcp_ping(&self.address); 125 | if ping > 0 { 126 | if ping < ping_min { 127 | ping_min = ping 128 | } 129 | pings[count] = ping; 130 | } 131 | thread::sleep(Duration::from_millis(1000)); 132 | count += 1; 133 | } 134 | 135 | if pings == [0, 0, 0, 0, 0, 0] { 136 | self.latency = 0.0; 137 | self.jitter = 0.0; 138 | return false; 139 | } 140 | 141 | let mut jitter_all = 0; 142 | for p in pings { 143 | if p > 0 { 144 | jitter_all += p - ping_min; 145 | } 146 | } 147 | 148 | self.latency = ping_min as f64 / 1_000.0; 149 | self.jitter = jitter_all as f64 / 5_000.0; 150 | 151 | #[cfg(debug_assertions)] 152 | debug!("Ping {} ms", self.latency); 153 | 154 | #[cfg(debug_assertions)] 155 | debug!("Jitter {} ms", self.jitter); 156 | 157 | true 158 | } 159 | 160 | fn download(&mut self) -> bool { 161 | match self.run_load(1) { 162 | Ok(_) => true, 163 | Err(_) => false, 164 | } 165 | } 166 | 167 | fn upload(&mut self) -> bool { 168 | match self.run_load(0) { 169 | Ok(_) => true, 170 | Err(_) => false, 171 | } 172 | } 173 | 174 | fn result(&self) -> SpeedTestResult { 175 | SpeedTestResult::build( 176 | self.upload, 177 | self.upload_status.clone(), 178 | self.download, 179 | self.download_status.clone(), 180 | self.latency, 181 | self.jitter, 182 | ) 183 | } 184 | } 185 | 186 | fn request_http_download(address: SocketAddr, url: Url, counter: Arc) { 187 | let chunk_count = 50; 188 | let data_size = chunk_count * 1024 * 1024 as u64; 189 | let mut data_counter; 190 | let mut buffer = [0; 65536]; 191 | 192 | let host_port = format!( 193 | "{}:{}", 194 | url.host_str().unwrap(), 195 | url.port_or_known_default().unwrap() 196 | ); 197 | let path_str = url.path(); 198 | 199 | let mut stream = match make_connection(&address, &url) { 200 | Ok(s) => s, 201 | Err(_) => { 202 | counter.wait(); 203 | return; 204 | } 205 | }; 206 | 207 | counter.wait(); 208 | 209 | 'request: while !counter.is_end() { 210 | let now = SystemTime::now() 211 | .duration_since(SystemTime::UNIX_EPOCH) 212 | .unwrap() 213 | .as_millis(); 214 | let path_query = format!( 215 | "{}?cors=true&r={}&ckSize={}&size={}", 216 | path_str, now, chunk_count, data_size 217 | ); 218 | 219 | #[cfg(debug_assertions)] 220 | debug!("Download {path_query}"); 221 | 222 | let request_head = format!( 223 | "GET {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: bim/1.0\r\n\r\n", 224 | path_query, host_port, 225 | ) 226 | .into_bytes(); 227 | 228 | match stream.write_all(&request_head) { 229 | Ok(_) => { 230 | if let Ok(size) = stream.read(&mut buffer) { 231 | #[cfg(debug_assertions)] 232 | debug!("Download Status: {size}"); 233 | 234 | if size > 0 { 235 | let count = size as u64; 236 | data_counter = count; 237 | counter.increase(count); 238 | } else { 239 | break 'request; 240 | } 241 | } else { 242 | break 'request; 243 | } 244 | } 245 | Err(_e) => { 246 | #[cfg(debug_assertions)] 247 | debug!("Download Error: {}", _e); 248 | 249 | break 'request; 250 | } 251 | } 252 | 253 | while data_counter < data_size && !counter.is_end() { 254 | match stream.read(&mut buffer) { 255 | Ok(size) => { 256 | let count = size as u64; 257 | data_counter += count; 258 | counter.increase(count); 259 | } 260 | Err(_e) => { 261 | #[cfg(debug_assertions)] 262 | debug!("Download Error: {}", _e); 263 | 264 | break 'request; 265 | } 266 | } 267 | } 268 | } 269 | } 270 | 271 | fn request_http_upload(address: SocketAddr, url: Url, counter: Arc) { 272 | let chunk_count = 50; 273 | let data_size = chunk_count * 1024 * 1024 as u64; 274 | let mut data_counter; 275 | 276 | let host_port = format!( 277 | "{}:{}", 278 | url.host_str().unwrap(), 279 | url.port_or_known_default().unwrap() 280 | ); 281 | let url_path = url.path(); 282 | let request_chunk = "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz-=" 283 | .repeat(1024) 284 | .into_bytes(); 285 | 286 | let mut stream = match make_connection(&address, &url) { 287 | Ok(s) => s, 288 | Err(_) => { 289 | counter.wait(); 290 | return; 291 | } 292 | }; 293 | 294 | counter.wait(); 295 | 296 | 'request: while !counter.is_end() { 297 | let now = SystemTime::now() 298 | .duration_since(SystemTime::UNIX_EPOCH) 299 | .unwrap() 300 | .as_millis(); 301 | let path_query = format!("{}?r={}", url_path, now); 302 | 303 | #[cfg(debug_assertions)] 304 | debug!("Upload {path_query} size {data_size}"); 305 | 306 | let request_head = format!( 307 | "POST {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: bim/1.0\r\nContent-Length: {}\r\n\r\n", 308 | path_query, host_port, data_size 309 | ) 310 | .into_bytes(); 311 | 312 | match stream.write_all(&request_head) { 313 | Ok(_) => { 314 | let length = request_head.len() as u64; 315 | data_counter = length; 316 | counter.increase(length); 317 | } 318 | Err(_e) => { 319 | #[cfg(debug_assertions)] 320 | debug!("Upload Error: {}", _e); 321 | 322 | break 'request; 323 | } 324 | } 325 | 326 | while data_counter < data_size && !counter.is_end() { 327 | match stream.write(&request_chunk) { 328 | Ok(size) => { 329 | let count = size as u64; 330 | data_counter += size as u64; 331 | counter.increase(count); 332 | } 333 | Err(_e) => { 334 | #[cfg(debug_assertions)] 335 | debug!("Upload Error: {}", _e); 336 | 337 | break 'request; 338 | } 339 | } 340 | } 341 | } 342 | } 343 | -------------------------------------------------------------------------------- /src/clients/mod.rs: -------------------------------------------------------------------------------- 1 | mod base; 2 | mod http; 3 | mod tcp_speedtest_net; 4 | 5 | pub use base::Client; 6 | pub use http::HTTPClient; 7 | pub use tcp_speedtest_net::SpeedtestNetTcpClient; 8 | -------------------------------------------------------------------------------- /src/clients/tcp_speedtest_net.rs: -------------------------------------------------------------------------------- 1 | use std::error::Error; 2 | use std::net::SocketAddr; 3 | use std::sync::Arc; 4 | use std::thread; 5 | use std::time::{Duration, Instant}; 6 | 7 | #[cfg(debug_assertions)] 8 | use log::debug; 9 | 10 | use url::Url; 11 | 12 | use crate::clients::base::{get_address, make_connection, request_tcp_ping, Client, LoadCounter}; 13 | use crate::utils::SpeedTestResult; 14 | 15 | use std::io::{Read, Write}; 16 | 17 | pub struct SpeedtestNetTcpClient { 18 | threads: u8, 19 | 20 | address: SocketAddr, 21 | 22 | upload: f64, 23 | upload_status: String, 24 | download: f64, 25 | download_status: String, 26 | latency: f64, 27 | jitter: f64, 28 | } 29 | 30 | impl SpeedtestNetTcpClient { 31 | pub fn build(url: String, ipv6: bool, threads: u8) -> Option> { 32 | let url = Url::parse(&url).ok()?; 33 | 34 | let address = get_address(&url, ipv6)?; 35 | 36 | #[cfg(debug_assertions)] 37 | debug!("IP address {address}"); 38 | 39 | let r = "取消".to_owned(); 40 | Some(Box::new(Self { 41 | threads, 42 | address, 43 | upload: 0.0, 44 | upload_status: r.clone(), 45 | download: 0.0, 46 | download_status: r.clone(), 47 | latency: 0.0, 48 | jitter: 0.0, 49 | })) 50 | } 51 | 52 | fn run_load(&mut self, load: u8) -> Result> { 53 | let counter = Arc::new(LoadCounter::new(self.threads)); 54 | let mut tasks = vec![]; 55 | 56 | for _ in 0..self.threads { 57 | let a = self.address.clone(); 58 | let c = counter.clone(); 59 | 60 | let task = thread::spawn(move || { 61 | match load { 62 | 0 => request_tcp_upload(a, c), 63 | _ => request_tcp_download(a, c), 64 | }; 65 | }); 66 | tasks.push(task); 67 | thread::sleep(Duration::from_millis(250)); 68 | } 69 | 70 | let mut time_passed = 0; 71 | 72 | counter.wait(); 73 | 74 | let now = Instant::now(); 75 | while time_passed < 14_000_000 { 76 | thread::sleep(Duration::from_millis(500)); 77 | time_passed = now.elapsed().as_micros(); 78 | 79 | counter.count(time_passed); 80 | } 81 | 82 | counter.end(); 83 | for task in tasks { 84 | let _ = task.join(); 85 | } 86 | 87 | match load { 88 | 0 => { 89 | self.upload = counter.speed(); 90 | self.upload_status = counter.status(); 91 | } 92 | _ => { 93 | self.download = counter.speed(); 94 | self.download_status = counter.status(); 95 | } 96 | } 97 | 98 | Ok(true) 99 | } 100 | } 101 | 102 | impl Client for SpeedtestNetTcpClient { 103 | fn ping(&mut self) -> bool { 104 | let mut count = 0; 105 | let mut pings = [0u128; 6]; 106 | let mut ping_min = 10000000; 107 | 108 | while count < 6 { 109 | let ping = request_tcp_ping(&self.address); 110 | if ping > 0 { 111 | if ping < ping_min { 112 | ping_min = ping 113 | } 114 | pings[count] = ping; 115 | } 116 | thread::sleep(Duration::from_millis(1000)); 117 | count += 1; 118 | } 119 | 120 | if pings == [0, 0, 0, 0, 0, 0] { 121 | self.latency = 0.0; 122 | self.jitter = 0.0; 123 | return false; 124 | } 125 | 126 | let mut jitter_all = 0; 127 | for p in pings { 128 | if p > 0 { 129 | jitter_all += p - ping_min; 130 | } 131 | } 132 | 133 | self.latency = ping_min as f64 / 1_000.0; 134 | self.jitter = jitter_all as f64 / 5_000.0; 135 | 136 | #[cfg(debug_assertions)] 137 | debug!("Ping {} ms", self.latency); 138 | 139 | #[cfg(debug_assertions)] 140 | debug!("Jitter {} ms", self.jitter); 141 | 142 | true 143 | } 144 | 145 | fn download(&mut self) -> bool { 146 | match self.run_load(1) { 147 | Ok(_) => true, 148 | Err(_) => false, 149 | } 150 | } 151 | 152 | fn upload(&mut self) -> bool { 153 | match self.run_load(0) { 154 | Ok(_) => true, 155 | Err(_) => false, 156 | } 157 | } 158 | 159 | fn result(&self) -> SpeedTestResult { 160 | SpeedTestResult::build( 161 | self.upload, 162 | self.upload_status.clone(), 163 | self.download, 164 | self.download_status.clone(), 165 | self.latency, 166 | self.jitter, 167 | ) 168 | } 169 | } 170 | 171 | fn request_tcp_download(address: SocketAddr, counter: Arc) { 172 | let data_size = 15 * 1024 * 1024 * 1024 as u128; 173 | let mut buffer = [0; 65536]; 174 | 175 | let url = Url::parse("http://bench.im").unwrap(); 176 | let mut stream = match make_connection(&address, &url) { 177 | Ok(s) => s, 178 | Err(_) => { 179 | counter.wait(); 180 | return; 181 | } 182 | }; 183 | 184 | counter.wait(); 185 | 186 | #[cfg(debug_assertions)] 187 | debug!("Download Start"); 188 | 189 | let request = format!("DOWNLOAD {data_size}\n").into_bytes(); 190 | match stream.write_all(&request) { 191 | Ok(_) => { 192 | if let Ok(size) = stream.read(&mut buffer) { 193 | #[cfg(debug_assertions)] 194 | debug!("Download Status: {size}"); 195 | 196 | if size == 0 { 197 | #[cfg(debug_assertions)] 198 | debug!("Download Error: Start failed"); 199 | return; 200 | } 201 | 202 | let count = size as u64; 203 | counter.increase(count); 204 | } else { 205 | return; 206 | } 207 | } 208 | Err(_e) => { 209 | #[cfg(debug_assertions)] 210 | debug!("Download Error: {}", _e); 211 | return; 212 | } 213 | } 214 | 215 | while !counter.is_end() { 216 | match stream.read(&mut buffer) { 217 | Ok(size) => { 218 | let count = size as u64; 219 | counter.increase(count); 220 | } 221 | Err(_e) => { 222 | #[cfg(debug_assertions)] 223 | debug!("Download Error: {}", _e); 224 | return; 225 | } 226 | } 227 | } 228 | } 229 | 230 | fn request_tcp_upload(address: SocketAddr, counter: Arc) { 231 | let data_size = 15 * 1024 * 1024 * 1024 as u128; 232 | let request_chunk = "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz-=" 233 | .repeat(1024) 234 | .into_bytes(); 235 | 236 | let url = Url::parse("http://bench.im").unwrap(); 237 | 238 | let mut stream = match make_connection(&address, &url) { 239 | Ok(s) => s, 240 | Err(_) => { 241 | counter.wait(); 242 | return; 243 | } 244 | }; 245 | 246 | counter.wait(); 247 | 248 | #[cfg(debug_assertions)] 249 | debug!("Upload Start"); 250 | 251 | let request = format!("UPLOAD {data_size} 0\n").into_bytes(); 252 | match stream.write_all(&request) { 253 | Ok(_) => { 254 | let count = request.len() as u64; 255 | counter.increase(count); 256 | } 257 | Err(_e) => { 258 | #[cfg(debug_assertions)] 259 | debug!("Upload Error: {}", _e); 260 | return; 261 | } 262 | } 263 | 264 | while !counter.is_end() { 265 | match stream.write(&request_chunk) { 266 | Ok(size) => { 267 | let count = size as u64; 268 | counter.increase(count); 269 | } 270 | Err(_e) => { 271 | #[cfg(debug_assertions)] 272 | debug!("Upload Error: {}", _e); 273 | return; 274 | } 275 | } 276 | } 277 | } 278 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | pub mod clients; 2 | pub mod servers; 3 | pub mod utils; 4 | -------------------------------------------------------------------------------- /src/server.rs: -------------------------------------------------------------------------------- 1 | use getopts::Options; 2 | use std::env; 3 | 4 | use bim_core::servers::{HTTPServer, Server}; 5 | 6 | fn print_usage(program: &str, opts: Options) { 7 | let brief = format!("Usage: {} HOST:PORT [options]", program); 8 | print!("{}", opts.usage(&brief)); 9 | } 10 | 11 | fn get_server(server_name: &str, address: &str) -> Option> { 12 | match server_name { 13 | "http" => Some(Box::new(HTTPServer::build(address.to_string()).unwrap())), 14 | _ => None, 15 | } 16 | } 17 | 18 | fn main() { 19 | let args: Vec = env::args().collect(); 20 | let program = args[0].clone(); 21 | 22 | let mut opts = Options::new(); 23 | opts.optopt("s", "server", "set test server", "NAME"); 24 | opts.optflag("h", "help", "print this help menu"); 25 | let matches = match opts.parse(&args[1..]) { 26 | Ok(m) => m, 27 | Err(f) => { 28 | println!("{}\n", f.to_string()); 29 | print_usage(&program, opts); 30 | return; 31 | } 32 | }; 33 | 34 | if matches.opt_present("h") { 35 | print_usage(&program, opts); 36 | return; 37 | } 38 | 39 | let address = if !matches.free.is_empty() { 40 | matches.free.get(0).unwrap() 41 | } else { 42 | print_usage(&program, opts); 43 | return; 44 | }; 45 | 46 | #[cfg(debug_assertions)] 47 | env_logger::init(); 48 | 49 | let server_name = matches.opt_str("s").unwrap_or("http".to_string()); 50 | if let Some(mut server) = get_server(&server_name, address) { 51 | println!("Running {server_name} server on: {address}"); 52 | let _ = (*server).run(); 53 | } else { 54 | println!("{server_name} client not found or invalid params.") 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/servers/base.rs: -------------------------------------------------------------------------------- 1 | pub trait Server { 2 | fn run(&mut self) -> bool; 3 | } 4 | -------------------------------------------------------------------------------- /src/servers/http.rs: -------------------------------------------------------------------------------- 1 | use std::net::ToSocketAddrs; 2 | use std::sync::Arc; 3 | use std::thread; 4 | 5 | #[cfg(debug_assertions)] 6 | use log::debug; 7 | 8 | use tiny_http::Method; 9 | 10 | use crate::servers::Server; 11 | 12 | pub struct HTTPServer { 13 | address: String, 14 | } 15 | 16 | impl HTTPServer { 17 | pub fn build(address: String) -> Option { 18 | let _ = match address.to_socket_addrs() { 19 | Ok(_) => {} 20 | Err(_) => return None, 21 | }; 22 | 23 | return Some(Self { address }); 24 | } 25 | } 26 | 27 | impl Server for HTTPServer { 28 | fn run(&mut self) -> bool { 29 | let server = match tiny_http::Server::http(&self.address) { 30 | Ok(s) => Arc::new(s), 31 | Err(_e) => { 32 | #[cfg(debug_assertions)] 33 | debug!("Start Failed {_e}"); 34 | 35 | return false; 36 | } 37 | }; 38 | 39 | let data = Arc::new( 40 | "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz-=" 41 | .repeat(1024) 42 | .into_bytes(), 43 | ); 44 | 45 | let mut guards = Vec::with_capacity(8); 46 | 47 | for _ in 0..8 { 48 | let server = server.clone(); 49 | let data = data.clone(); 50 | 51 | let guard = thread::spawn(move || loop { 52 | let request = server.recv().unwrap(); 53 | let method = request.method().clone(); 54 | let mut writer = request.into_writer(); 55 | let data = data.as_ref(); 56 | 57 | match method { 58 | Method::Get => { 59 | let mut counter = 0; 60 | let head = "HTTP/1.1 200\r\n\r\n".as_bytes(); 61 | let _ = writer.write_all(head); 62 | 63 | while counter < 50 * 1024 * 1024 { 64 | let _ = writer.write_all(data); 65 | counter += 65536; 66 | } 67 | } 68 | Method::Post => { 69 | let head = "HTTP/1.1 200\r\n\r\n".as_bytes(); 70 | let _ = writer.write_all(head); 71 | } 72 | _ => { 73 | let head = "HTTP/1.1 500\r\n\r\n".as_bytes(); 74 | let _ = writer.write_all(head); 75 | } 76 | } 77 | }); 78 | 79 | guards.push(guard); 80 | } 81 | 82 | for p in guards { 83 | let _ = p.join(); 84 | } 85 | true 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/servers/mod.rs: -------------------------------------------------------------------------------- 1 | mod base; 2 | mod http; 3 | 4 | pub use base::Server; 5 | pub use http::HTTPServer; 6 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | use serde::{Deserialize, Serialize}; 4 | use unicode_width::UnicodeWidthStr; 5 | 6 | pub fn justify_name(name: &str, length: u8, left_right: bool) -> String { 7 | let mut justified_name = String::from(name); 8 | let width = UnicodeWidthStr::width(name); 9 | 10 | if width < length as usize { 11 | let space_count = length as usize - width; 12 | let spaces = " ".repeat(space_count as usize); 13 | if left_right { 14 | justified_name += spaces.as_str(); 15 | } else { 16 | justified_name = spaces + &justified_name; 17 | } 18 | } 19 | justified_name 20 | } 21 | 22 | #[derive(Serialize, Deserialize)] 23 | pub struct SpeedTestResult { 24 | #[serde(serialize_with = "serialize_f64")] 25 | upload: f64, 26 | upload_status: String, 27 | #[serde(serialize_with = "serialize_f64")] 28 | download: f64, 29 | download_status: String, 30 | #[serde(serialize_with = "serialize_f64")] 31 | latency: f64, 32 | #[serde(serialize_with = "serialize_f64")] 33 | jitter: f64, 34 | } 35 | 36 | fn serialize_f64(x: &f64, serializer: S) -> Result 37 | where 38 | S: serde::Serializer, 39 | { 40 | let s = format!("{:.1}", x); 41 | serializer.serialize_str(&s) 42 | } 43 | 44 | impl SpeedTestResult { 45 | pub fn build( 46 | upload: f64, 47 | upload_status: String, 48 | download: f64, 49 | download_status: String, 50 | latency: f64, 51 | jitter: f64, 52 | ) -> SpeedTestResult { 53 | return SpeedTestResult { 54 | upload, 55 | upload_status, 56 | download, 57 | download_status, 58 | latency, 59 | jitter, 60 | }; 61 | } 62 | 63 | pub fn text(&self) -> String { 64 | let upload = justify_name(&format!("{:.1}", &self.upload), 9, false); 65 | let upload_status = justify_name(&self.upload_status, 5, false); 66 | let download = justify_name(&format!("{:.1}", &self.download), 9, false); 67 | let download_status = justify_name(&self.download_status, 5, false); 68 | let latency = justify_name(&format!("{:.1}", &self.latency), 7, false); 69 | let jitter = justify_name(&format!("{:.1}", &self.jitter), 7, false); 70 | 71 | format!("{upload},{upload_status},{download},{download_status},{latency},{jitter}") 72 | } 73 | } 74 | 75 | impl fmt::Display for SpeedTestResult { 76 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 77 | write!( 78 | f, 79 | "Upload {:.1}Mbps {}, Download: {:.1}Mbps {}, Latency {:.1}, Jitter {:.1}", 80 | self.upload, 81 | self.upload_status, 82 | self.download, 83 | self.download_status, 84 | self.latency, 85 | self.jitter 86 | ) 87 | } 88 | } 89 | --------------------------------------------------------------------------------