├── .github └── workflows │ └── android_buildozer.yml ├── .gitignore ├── LICENSE ├── README.md ├── browser ├── OmegaOptions.bak └── gooreplacer.json ├── config.json ├── docs └── notes.md ├── main.py ├── poetry.lock ├── pyproject.toml ├── run.py ├── service.py ├── small_icon.png ├── src └── tls_fragment │ ├── __init__.py │ ├── cli.py │ ├── config.py │ ├── dns_extension.py │ ├── fake_desync.py │ ├── fragment.py │ ├── log.py │ ├── remote.py │ └── utils.py ├── tlsp.sh ├── tools ├── BUILD_WINDOWS.bat ├── UZA_MSEDGE.bat ├── build │ ├── README.md │ ├── build_android.dockerfile │ ├── build_android.sh │ ├── build_debian_8_docker.sh │ ├── build_ios.py │ ├── build_linux.sh │ ├── build_linux_amd64.dockerfile │ ├── build_macosx.py │ ├── build_windows.py │ ├── buildozer.spec │ ├── helloworld.linux.onefile.spec │ ├── helloworld.windows.onefile.spec │ ├── requirements.txt │ ├── requirements_build_android.txt │ ├── requirements_build_linux.txt │ ├── requirements_build_macosx.txt │ └── requirements_build_windows.txt ├── install.sh ├── run.sh └── test.bat └── tox.ini /.github/workflows/android_buildozer.yml: -------------------------------------------------------------------------------- 1 | name: Android Build 2 | on: 3 | push: 4 | branches: [ main ] 5 | paths: 6 | - 'src/tls_fragment' 7 | - 'main.py' 8 | workflow_dispatch: 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v4 16 | 17 | - name: Setup Java 18 | uses: actions/setup-java@v4 19 | with: 20 | distribution: temurin 21 | java-version: 17 22 | 23 | - name: Setup Python 24 | uses: actions/setup-python@v5 25 | with: 26 | python-version: '3.11' 27 | 28 | - name: Setup Gradle 29 | uses: gradle/actions/setup-gradle@v4 30 | 31 | - name: Install dependencies 32 | uses: awalsh128/cache-apt-pkgs-action@latest 33 | with: 34 | packages: autoconf automake build-essential ccache clang cmake gettext git libffi-dev libltdl-dev libssl-dev libtool openssl patch pkg-config unzip zip zlib1g-dev 35 | 36 | - name: Cache Buildozer 37 | uses: actions/cache@v4 38 | with: 39 | path: | 40 | ./build/android/.buildozer 41 | key: ${{ runner.os }}-buildozer-${{ hashFiles('tools/build/buildozer.spec') }} 42 | 43 | - name: Buildozer Build 44 | run: bash tools/build/build_android.sh 45 | 46 | - name: Upload artifacts 47 | uses: actions/upload-artifact@v4.6.2 48 | with: 49 | name: package 50 | path: build/android/bin/*.apk 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | DNS_cache.json 2 | TTL_cache.json 3 | dist 4 | /build 5 | proxy.exe.spec 6 | log.txt 7 | __pycache__ 8 | .vscode -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TLSFragment使用指南 2 | 3 | ## 交流群 4 | 5 | 可用discussions 6 | 7 | [matrix反馈群](https://matrix.to/#/!cCTXKjhvtagDMxlyLB:matrix.org?via=matrix.org&via=cutefunny.art)(本来就是公开的,现在多一个tlsp反馈群的功能) 8 | 9 | ## 安装 10 | 11 | 可以作为模块安装: 12 | ```shell 13 | python -m build --wheel --no-isolation 14 | python -m installer dist/*.whl 15 | ``` 16 | 17 | ## 运行 18 | 作为模块安装后可以直接运行 `tls_fragment`。(暂不支持) 19 | 20 | 或者将仓库克隆下来之后运行 `run.py`。 21 | 22 | ### TLSFragment原理 23 | 24 | #### TLSfrag 25 | 26 | 将TCP连接Client的第一个包(这个包一般来说是TLS ClientHello,一般应用层不会分片)在TLS层和TCP层分别进行分片,将sni拆入多个包以绕过gfw。 27 | 28 | #### FAKEdesync 29 | 30 | 利用ttl发送假包,扰乱gfw的DPI。 31 | 32 | 为了避免管理员/root权限的需要。 33 | 34 | + 在Windows上,使用`TransmitFile`函数(由于TransmitFIle被限制最多同时运行2个,性能较差) 35 | + 在linux上,使用管道 36 | 37 | 通过重传机制发送。 38 | 39 | ### 异步方式 40 | 41 | 使用`threading`(多线程),有一个`asyncio`协程版本目前废弃,原因是默认版本无法支持自代理DoH。 42 | 43 | ### 安装使用 44 | 45 | #### 运行 46 | 47 | ```bash 48 | git clone git@github.com:maoist2009/TlsFragment.git 49 | pip install -r requirements.txt 50 | python server.py 51 | ``` 52 | 53 | 也可以编译后开机自启动: 54 | 55 | ```bash 56 | BUILD_WINDOWS 57 | ``` 58 | 59 | 之后请为`/dist/proxy.exe`创建快捷方式,复制到`%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup` 60 | 61 | #### 浏览器使用 62 | 63 | 建议分流 64 | 65 | 安装`Proxy SwitchyOmega`和`Gooreplacer`,分别导入配置文件`OmegaOptions.bak`和`gooreplacer.json`(android请使用kiwi浏览器等) 66 | 67 | ### 配置方式 68 | 69 | #### 全局选项 70 | 71 | ##### 公共 72 | 73 | 74 | | 项名 | 简单解释 | 是否可以域名自定义 | 75 | | ------------------- | --------------------------- | ------------------ | 76 | | `output_data` | 是否输出包内容 | 否 | 77 | | `listen_PORT` | 代理运行端口 | 否 | 78 | | `DOH_PORT` | 代理使用DoH代理端口 | 否 | 79 | | `my_socket_timeout` | 接/发包超时时间 | 否 | 80 | | `doh_server` | doh服务器(请在 domains 里指定 ip) | 否 | 81 | | `DNS_log_every` | dns缓存频率 | 否 | 82 | | `TTL_log_every` | ttl缓存频率 | 否 | 83 | | `num_TCP_fragment` | 无sni段TCP分块数 | 是 | 84 | | `TCP_frag` | sni所在tcp层大致段分块长度 | 是 | 85 | | `method` | 操作方法,见下文模式 | 是 | 86 | | `IPtype` | dns查询ip默认类型(无则换) | 是 | 87 | 88 | ##### `TLSfrag`模式 89 | 90 | 91 | | 项名 | 简单解释 | 是否可以域名自定义 | 92 | | ------------------ | ------------------ | ------------------ | 93 | | `num_TLS_fragment` | 无sni段TLS分块数 | 是 | 94 | | `TLS_frag` | sni在tls层分块长度 | 是 | 95 | 96 | ##### `FAKEdesync`模式 97 | 98 | 99 | | 项名 | 简单解释 | 是否可以域名自定义 | 100 | | ----------------------- | ---------------------------------------- | ------------------ | 101 | | `FAKE_packet` | 发送的假包内容 | 是 | 102 | | `FAKE_ttl` | 假包使用的ttl,填`query`表示自动二分查询 | 是 | 103 | | `FAKE_ttl_auto_timeout` | cookie缓存时间 | 是 | 104 | | `FAKE_sleep` | 发送假包后改为真包的间隔时间 | 是 | 105 | 106 | 其中,域名自定义指的是在`domians.xxxx.com`下也有此配置项,且该处配置优先。 107 | 108 | #### `domains`下有其他项: 109 | 110 | 111 | | 项名 | 简单解释 | 112 | | ---------- | ------------------- | 113 | | `IP` | IP地址 | 114 | | `port` | 端口(不填默认443) | 115 | | `IPcache` | 是否缓存 | 116 | | `TTLcache` | 是否缓存IP对应TTL | 117 | 118 | ### 域名匹配规则 119 | 120 | 如果特定域名(若有多个取最长的,再有多个问python的sort)为sni的子串,则取。(使用AC自动机实现以应对巨大列表) 121 | 支持首尾匹配,实际上塞入AC自动机的是:`^www.domain.genshin.mihoyo.com$` 122 | 123 | ### IP查找 124 | 125 | 建议使用[HTTPS_IP_finder](https://github.com/maoist2009/HTTPS_IP_finder) 126 | 我本人也会维护已知的被ip封锁的网站。 127 | 128 | ### IP重定向 129 | 130 | 支持IP(段)重定向到ip,默认链式跳转,如果要求配置不链式,在结果ip字符串前添加`^`。 131 | -------------------------------------------------------------------------------- /browser/OmegaOptions.bak: -------------------------------------------------------------------------------- 1 | {"+auto switch":{"color":"#99dd99","defaultProfileName":"direct","name":"auto switch","profileType":"SwitchProfile","revision":"195b94b112e","rules":[{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.wikifunctions.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.mediawiki.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.cloudflare-dns.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.adminforge.de"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.nadeko.net"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.anoxinon.de"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.uptodown.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.google"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.freeweibo.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.fosstodon.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.smsactivate.s3.eu-central-1.amazonaws.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.android.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.readthedocs.io"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.sleazyfork.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.greasyfork.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.codesandbox.io"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.wikiquote.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.wikisource.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.indieweb.social"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.mov.im"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.stackblitz.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.bbc.co.uk"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.economist.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.conversations.im"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.611study.icu"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.xmpp.jp"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.cmx.im"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.cmlmuf.top"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.hack.chat"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.laborinfocn6.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.annas-archive.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.ci-ic.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.opkode.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.f-droid.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.protonvpn.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.archive.ph"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.lsepcn.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.patreon.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.conversejs.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.notion.site"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.go.dev"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.golang.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.chromium.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.cloudflare.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.bootstrapcdn.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.apkmirror.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.giscus.app"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.medium.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.suno.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.quoracdn.net"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.quora.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.onedrive.live.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.bbci.co.uk"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.bbc.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.huggingface.co"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.nyt.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.nytimes.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.freeflarum.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.thepiratebay.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.pornhub.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.archive.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.rutube.ru"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.youtu.be"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.pximg.net"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.vercel.app"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.nicovideo.jp"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.chrome.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.archive-it.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.croxy.network"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.proton.me"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.cookielaw.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.phncdn.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.docker.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.discord.gg"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.discordapp.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.discord.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.blogger.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.redd.it"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.redditmedia.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.redditstatic.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.reddit.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.receiveasmsonline.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.good.news"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.bsky.app"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.bsky.social"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.pscp.tv"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.matrix.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.pixiv.net"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.imgur.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.gravatar.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.twitch.tv"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.bit.ly"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.duckduckgo.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.cdn-telegram.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.githubusercontent.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.github.io"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.github.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.wikinews.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.wikipedia.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.wikimedia.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.instagram.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.dropbox.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.bu2021.xyz"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.cdninstagram.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.fbsbx.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.facebook.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.fbcdn.net"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.translate.goog"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.ggpht.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.telegram.me"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.t.me"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.v2ex.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.googleapis.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.x.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.twimg.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.twitter.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.withgoogle.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.telegram.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.youtube.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.ytimg.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.googlevideo.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.googleusercontent.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.google.com.hk"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.google.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.workers.dev"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.xcancel.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.geph.io"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.1lib.sk"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.odycdn.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.odysee.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.torproject.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.mastodon.social"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.freezhihu.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.z-library.sk"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.pages.dev"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.greatfire.org"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.gstatic.com"},"profileName":"proxy"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"*.githubassets.com"},"profileName":"direct"},{"condition":{"conditionType":"HostWildcardCondition","pattern":"fonts.gstatic.com"},"profileName":"direct"}]},"+fakesni":{"bypassList":[{"conditionType":"BypassCondition","pattern":"127.0.0.1"},{"conditionType":"BypassCondition","pattern":"[::1]"},{"conditionType":"BypassCondition","pattern":"localhost"}],"color":"#5b5","fallbackProxy":{"host":"127.0.0.1","port":2501,"scheme":"http"},"name":"fakesni","profileType":"FixedProfile","revision":"1939c5b6785"},"+proxy":{"bypassList":[{"conditionType":"BypassCondition","pattern":"127.0.0.1"},{"conditionType":"BypassCondition","pattern":"::1"},{"conditionType":"BypassCondition","pattern":"localhost"}],"color":"#99ccee","fallbackProxy":{"host":"127.0.0.1","port":2500,"scheme":"http"},"name":"proxy","profileType":"FixedProfile","revision":"192c3feb701"},"-addConditionsToBottom":false,"-confirmDeletion":true,"-downloadInterval":1440,"-enableQuickSwitch":false,"-monitorWebRequests":true,"-quickSwitchProfiles":[],"-refreshOnProfileChange":true,"-revertProxyChanges":true,"-showExternalProfile":true,"-showInspectMenu":true,"-startupProfileName":"","schemaVersion":2} -------------------------------------------------------------------------------- /browser/gooreplacer.json: -------------------------------------------------------------------------------- 1 | { 2 | "createBy": "http://liujiacai.net/gooreplacer/", 3 | "version": "3.13.0", 4 | "createAt": "2024/12/15 15:27:42", 5 | "redirect-rules": [ 6 | { 7 | "src": "cdn.jsdelivr.net", 8 | "kind": "wildcard", 9 | "dst": "gcore.jsdelivr.net", 10 | "enable": true 11 | }, 12 | { 13 | "src": "raw.githubusercontent.com", 14 | "kind": "wildcard", 15 | "dst": "raw.kkgithub.com", 16 | "enable": true 17 | }, 18 | { 19 | "src": "google.cn/m", 20 | "kind": "wildcard", 21 | "dst": "google.com.hk/m", 22 | "enable": true 23 | }, 24 | { 25 | "src": "abs-0.twimg.com", 26 | "kind": "wildcard", 27 | "dst": "abs.twimg.com", 28 | "enable": true 29 | } 30 | ], 31 | "cancel-rules": [], 32 | "request-headers": [], 33 | "response-headers": [] 34 | } -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "loglevel": "INFO", 3 | "port": 2500, 4 | "DOH_port": 2500, 5 | "num_tcp_pieces": 8, 6 | "num_tls_pieces": 8, 7 | "len_tcp_sni": 4, 8 | "len_tls_sni": 4, 9 | "send_interval": 0.01, 10 | "fake_packet": "GET / HTTP/1.1\r\nHost: www.baidu.com\r\n\r\n", 11 | "fake_ttl": "query", 12 | "fake_sleep": 0.2, 13 | "my_socket_timeout": 120, 14 | "FAKE_ttl_auto_timeout": 5, 15 | "doh_server": "https://cloudflare-dns.com/dns-query?dns=", 16 | "mode": "TLSfrag", 17 | "DNS_cache": true, 18 | "DNS_cache_update_interval": 2, 19 | "TTL_cache": true, 20 | "TTL_cache_update_interval": 2, 21 | "safety_check": false, 22 | "UDPfakeDNS": true, 23 | "BySNIfirst": false, 24 | "IPredirect": { 25 | "104.16.0.0/13": "104.21.57.162", 26 | "104.24.0.0/14": "^104.21.3.224", 27 | "172.64.0.0/13": "^104.21.3.225", 28 | "162.158.0.0/15": "^104.21.3.226", 29 | "2606:4700::/32": "^104.21.57.162", 30 | "2400:cb00::/32": "^104.21.3.224" 31 | }, 32 | "domains": { 33 | "streaming.mastodon.social": {}, 34 | "smsactivate.s3.eu-central-1.amazonaws.com": { 35 | "IP": "3.5.137.138" 36 | }, 37 | "disk.yandex.com": { 38 | "IP": "87.250.250.50", 39 | "mode": "FAKEdesync" 40 | }, 41 | "yandex.com": { 42 | "mode": "FAKEdesync" 43 | }, 44 | "inv.nadeko.net": { 45 | "IP": "186.105.142.141" 46 | }, 47 | "annas-archive.org": {}, 48 | "mastodon.social": { 49 | "IP": "199.232.89.91" 50 | }, 51 | "codesandbox.io": { 52 | "IP": "104.21.3.227" 53 | }, 54 | "stackblitz.com": { 55 | "IP": "13.32.27.56" 56 | }, 57 | "giscus.app": { 58 | "mode": "FAKEdesync" 59 | }, 60 | "bbc.com": { 61 | "IP": "146.75.36.81" 62 | }, 63 | "steampowered.com": { 64 | "IP": "23.202.181.157" 65 | }, 66 | "api.steampowered.com": { 67 | "IP": "184.85.112.102" 68 | }, 69 | "login.steampowered.com": { 70 | "IP": "23.199.145.239" 71 | }, 72 | "quora": { 73 | "IP": "104.21.3.225", 74 | "len_tls_sni": 3 75 | }, 76 | "copilot.microsoft.com": { 77 | "IP": "2.17.22.191" 78 | }, 79 | "onedrive.live.com": { 80 | "IP": "150.171.43.11", 81 | "mode": "FAKEdesync" 82 | }, 83 | "skyapi.onedrive.live.com": { 84 | "IP": "13.107.42.12", 85 | "mode": "FAKEdesync" 86 | }, 87 | "live.com": { 88 | "mode": "FAKEdesync" 89 | }, 90 | "vercel.app": { 91 | "mode": "FAKEdesync" 92 | }, 93 | "cloudflare.com": { 94 | "IP": "104.21.3.226" 95 | }, 96 | "cn.nytimes.com": {}, 97 | "nytimes.com": { 98 | "IP": "199.232.137.164" 99 | }, 100 | "purr.nytimes.com": {}, 101 | "et.nytimes.com": {}, 102 | "nyt.com": { 103 | "IP": "199.232.137.164" 104 | }, 105 | "pornhub.com": { 106 | "IP": "66.254.114.40" 107 | }, 108 | "help.pornhub.com": {}, 109 | "web.archive.org": { 110 | "IP": "207.241.237.3" 111 | }, 112 | "archive.org": { 113 | "IP": "207.241.225.120" 114 | }, 115 | "www.archive.org": { 116 | "IP": "207.241.225.120" 117 | }, 118 | ".archive.org": {}, 119 | "pages.dev": { 120 | "IP": "172.66.44.87" 121 | }, 122 | "reddit": { 123 | "IP": "146.75.37.140", 124 | "len_tls_sni": 3, 125 | "len_tcp_sni": 5 126 | }, 127 | "redd.it": { 128 | "IP": "151.101.45.140", 129 | "len_tls_sni": 3, 130 | "len_tcp_sni": 5 131 | }, 132 | "github.com": { 133 | "IP": "4.237.22.38", 134 | "len_tls_sni": 3, 135 | "len_tcp_sni": 5 136 | }, 137 | "gist.github.com": { 138 | "IP": "4.237.22.38", 139 | "len_tls_sni": 3, 140 | "len_tcp_sni": 5 141 | }, 142 | "api.github.com": { 143 | "IP": "4.237.22.34", 144 | "len_tls_sni": 3, 145 | "len_tcp_sni": 5 146 | }, 147 | "uploads.github.com": { 148 | "IP": "4.237.22.36", 149 | "len_tls_sni": 3, 150 | "len_tcp_sni": 5 151 | }, 152 | "alive.github.com": { 153 | "IP": "140.82.112.26", 154 | "len_tls_sni": 3, 155 | "len_tcp_sni": 5 156 | }, 157 | "github.io": { 158 | "IP": "151.101.21.147" 159 | }, 160 | "githubusercontent.com": { 161 | "IP": "151.101.24.133" 162 | }, 163 | "objects-origin.githubusercontent.com": { 164 | "IP": "140.82.113.22" 165 | }, 166 | "wikipedia.org": { 167 | "IP": "185.15.58.224" 168 | }, 169 | "upload.wikimedia.org": { 170 | "IP": "185.15.58.240" 171 | }, 172 | "wiktionary.org": { 173 | "IP": "185.15.59.224" 174 | }, 175 | "wikiversity.org": { 176 | "IP": "185.15.58.224" 177 | }, 178 | "wikivoyage.org": { 179 | "IP": "185.15.58.224" 180 | }, 181 | "wikisource.org": { 182 | "IP": "185.15.58.224" 183 | }, 184 | "wikinews.org": { 185 | "IP": "185.15.58.224" 186 | }, 187 | "wikidata.org": { 188 | "IP": "185.15.58.224" 189 | }, 190 | "species.wikimedia.org": { 191 | "IP": "185.15.58.224" 192 | }, 193 | "meta.wikimedia.org": { 194 | "IP": "185.15.58.224" 195 | }, 196 | "mediawiki.org": { 197 | "IP": "185.15.58.224" 198 | }, 199 | "wikifunctions.org": { 200 | "IP": "185.15.58.224" 201 | }, 202 | "pixiv": { 203 | "len_tls_sni": 3 204 | }, 205 | "chrome.com": { 206 | "IP": "35.190.247.145", 207 | "port": 1445, 208 | "safety_check": true 209 | }, 210 | "chromium.org": { 211 | "IP": "35.190.247.145", 212 | "port": 1445, 213 | "safety_check": true 214 | }, 215 | ".google$": { 216 | "IP": "35.190.247.150", 217 | "port": 1445, 218 | "safety_check": true 219 | }, 220 | "deepmind.google": {}, 221 | "google.com": { 222 | "IP": "35.190.247.145", 223 | "port": 1445, 224 | "safety_check": true 225 | }, 226 | "ai.dev": { 227 | "IP": "35.190.247.145", 228 | "port": 1445, 229 | "safety_check": true 230 | }, 231 | "google.dev": { 232 | "IP": "35.190.247.145", 233 | "port": 1445, 234 | "safety_check": true 235 | }, 236 | "android.com": { 237 | "IP": "35.190.247.145", 238 | "port": 1445, 239 | "safety_check": true 240 | }, 241 | "golang.org": { 242 | "IP": "35.190.247.145", 243 | "port": 1445, 244 | "safety_check": true 245 | }, 246 | "blogger.com": { 247 | "IP": "35.190.247.145", 248 | "port": 1445, 249 | "safety_check": true 250 | }, 251 | "gvt1.com": { 252 | "IP": "35.190.247.145", 253 | "port": 1445, 254 | "safety_check": true 255 | }, 256 | "googlevideo.com": { 257 | "IPtype": "ipv6" 258 | }, 259 | "googleusercontent.com": { 260 | "IP": "4.193.121.119", 261 | "port": 41620 262 | }, 263 | ".translate.goog": { 264 | "IP": "4.193.121.119", 265 | "port": 41620 266 | }, 267 | "ggpht.com": { 268 | "IP": "4.193.121.119", 269 | "port": 41620 270 | }, 271 | "gstatic.com": { 272 | "IP": "35.190.247.145", 273 | "port": 1445, 274 | "safety_check": true 275 | }, 276 | "googleapis.com": { 277 | "IP": "35.190.247.145", 278 | "port": 1445, 279 | "safety_check": true 280 | }, 281 | "youtube.com": { 282 | "IP": "35.190.247.145", 283 | "port": 1445, 284 | "safety_check": true 285 | }, 286 | "youtube-nocookie.com": { 287 | "IP": "35.190.247.145", 288 | "port": 1445, 289 | "safety_check": true 290 | }, 291 | "youtu.be": { 292 | "IP": "35.190.247.145", 293 | "port": 1445, 294 | "safety_check": true 295 | }, 296 | "ytimg.com": { 297 | "IP": "35.190.247.145", 298 | "port": 1445, 299 | "safety_check": true 300 | }, 301 | "facebook.com": { 302 | "IP": "157.240.229.35", 303 | "TLSfrag": 3, 304 | "TCPfrag": 5 305 | }, 306 | "www.instagram.com": { 307 | "IP": "2a03:2880:f276:e8:face:b00c:0:4420" 308 | }, 309 | "meta": { 310 | "len_tls_sni": 2, 311 | "len_tcp_sni": 3, 312 | "send_interval": 0.01 313 | }, 314 | "static.cdninstagram.com": { 315 | "IP": "2a03:2880:f276:d2:face:b00c:0:43fe" 316 | }, 317 | "static.xx.fbcdn.net": { 318 | "IP": "157.240.229.35", 319 | "len_tls_sni": 3, 320 | "len_tcp_sni": 5 321 | }, 322 | "fbcdn.net": { 323 | "IPtype": "ipv6" 324 | }, 325 | "fbsbx.com": { 326 | "IP": "2a03:2880:f115:83:face:b00c:0:25de", 327 | "len_tls_sni": 3, 328 | "len_tcp_sni": 5 329 | }, 330 | "dropbox.com": { 331 | "IP": "162.125.2.18" 332 | }, 333 | "www.dropbox.com": { 334 | "IP": "162.125.2.18" 335 | }, 336 | ".dropbox.com": {}, 337 | "telegram.org": { 338 | "IP": "149.154.161.145" 339 | }, 340 | "telegram.me": { 341 | "IP": "149.154.161.145" 342 | }, 343 | "t.me": { 344 | "IP": "149.154.161.145", 345 | "len_tls_sni": 1, 346 | "num_tcp_pieces": 3, 347 | "num_tls_pieces": 5, 348 | "len_tcp_sni": 2 349 | }, 350 | "medium": {}, 351 | "cdn-telegram.org": { 352 | "IPtype": "ipv4" 353 | }, 354 | "zws5.web.telegram.org": { 355 | "IP": "149.154.170.200" 356 | }, 357 | "zws5-1.web.telegram.org": { 358 | "IP": "149.154.170.200" 359 | }, 360 | "pluto.web.telegram.org": { 361 | "IP": "2001:b28:f23d:8007::805:532" 362 | }, 363 | "aurora.web.telegram.org": { 364 | "IP": "2001:b28:f23d:8007::805:532" 365 | }, 366 | "xcannel.com": { 367 | "IP": "198.98.60.34" 368 | }, 369 | "cdn.xcannel.com": { 370 | "IP": "129.80.246.62" 371 | }, 372 | "video.twimg.com": { 373 | "CDN": "Fastly: 2024/11/13: 151.101.40.158", 374 | "len_tcp_sni": 8, 375 | "IPcache": false 376 | }, 377 | "twimg.com": { 378 | "IP": "146.75.72.157", 379 | "len_tls_sni": 4 380 | }, 381 | "x.com": { 382 | "IP": "104.18.38.25", 383 | "len_tcp_sni": 5, 384 | "send_interval": 0.02, 385 | "len_tls_sni": 2 386 | }, 387 | "platform.twitter.com": { 388 | "IP": "146.75.120.157", 389 | "len_tls_sni": 4 390 | }, 391 | "twitter.com": { 392 | "IP": "104.18.38.25", 393 | "len_tls_sni": 4 394 | }, 395 | "video.pscp.tv": { 396 | "IP": "146.75.34.164", 397 | "len_tls_sni": 9, 398 | "IPcache": false 399 | }, 400 | "one.one.one.one": { 401 | "IP": "104.21.3.221", 402 | "len_tls_sni": 4 403 | }, 404 | "nav-edge.smartscreen.microsoft.com": { 405 | "IP": "0.0.0.0", 406 | "len_tls_sni": 4 407 | }, 408 | "cloudflare-dns.com": { 409 | "IP": "104.21.3.222", 410 | "len_tls_sni": 6 411 | }, 412 | "tracking.miui.com": { 413 | "method": "GFWlike" 414 | }, 415 | "bilibili.com": { 416 | "method": "DIRECT" 417 | } 418 | }, 419 | "pac_domains": [ 420 | "wikifunctions.org$", 421 | "mediawiki.org$", 422 | "ncdn.ec$", 423 | "cloudflare-dns.com$", 424 | "adminforge.de$", 425 | "nadeko.net$", 426 | "anoxinon.de$", 427 | "uptodown.com$", 428 | "google$", 429 | "freeweibo.com$", 430 | "fosstodon.org$", 431 | "smsactivate.s3.eu-central-1.amazonaws.com$", 432 | "android.com$", 433 | "readthedocs.io$", 434 | "sleazyfork.org$", 435 | "greasyfork.org$", 436 | "codesandbox.io$", 437 | "wikiquote.org$", 438 | "wikisource.org$", 439 | "indieweb.social$", 440 | "mov.im$", 441 | "stackblitz.com$", 442 | "bbc.co.uk$", 443 | "economist.com$", 444 | "conversations.im$", 445 | "611study.icu$", 446 | "xmpp.jp$", 447 | "cmx.im$", 448 | "cmlmuf.top$", 449 | "hack.chat$", 450 | "laborinfocn6.com$", 451 | "annas-archive.org$", 452 | "ci-ic.org$", 453 | "opkode.com$", 454 | "f-droid.org$", 455 | "protonvpn.com$", 456 | "archive.ph$", 457 | "lsepcn.com$", 458 | "patreon.com$", 459 | "conversejs.org$", 460 | "notion.site$", 461 | "go.dev$", 462 | "golang.org$", 463 | "chromium.org$", 464 | "cloudflare.com$", 465 | "bootstrapcdn.com$", 466 | "apkmirror.com$", 467 | "giscus.app$", 468 | "medium.com$", 469 | "suno.com$", 470 | "quoracdn.net$", 471 | "quora.com$", 472 | "onedrive.live.com$", 473 | "bbci.co.uk$", 474 | "bbc.com$", 475 | "huggingface.co$", 476 | "nyt.com$", 477 | "nytimes.com$", 478 | "freeflarum.com$", 479 | "thepiratebay.org$", 480 | "pornhub.com$", 481 | "archive.org$", 482 | "rutube.ru$", 483 | "youtu.be$", 484 | "pximg.net$", 485 | "vercel.app$", 486 | "nicovideo.jp$", 487 | "chrome.com$", 488 | "archive-it.org$", 489 | "croxy.network$", 490 | "proton.me$", 491 | "cookielaw.org$", 492 | "phncdn.com$", 493 | "docker.com$", 494 | "discord.gg$", 495 | "discordapp.com$", 496 | "discord.com$", 497 | "blogger.com$", 498 | "redd.it$", 499 | "redditmedia.com$", 500 | "redditstatic.com$", 501 | "reddit.com$", 502 | "receiveasmsonline.com$", 503 | "good.news$", 504 | "bsky.app$", 505 | "bsky.social$", 506 | "pscp.tv$", 507 | "matrix.org$", 508 | "pixiv.net$", 509 | "imgur.com$", 510 | "gravatar.com$", 511 | "twitch.tv$", 512 | "bit.ly$", 513 | "duckduckgo.com$", 514 | "cdn-telegram.org$", 515 | "githubusercontent.com$", 516 | "github.io$", 517 | "github.com$", 518 | "wikinews.org$", 519 | "wikipedia.org$", 520 | "wikimedia.org$", 521 | "instagram.com$", 522 | "dropbox.com$", 523 | "bu2021.xyz$", 524 | "cdninstagram.com$", 525 | "fbsbx.com$", 526 | "facebook.com$", 527 | "fbcdn.net$", 528 | "translate.goog$", 529 | "ggpht.com$", 530 | "telegram.me$", 531 | "t.me$", 532 | "v2ex.com$", 533 | "googleapis.com$", 534 | "x.com$", 535 | "twimg.com$", 536 | "twitter.com$", 537 | "withgoogle.com$", 538 | "telegram.org$", 539 | "youtube.com$", 540 | "ytimg.com$", 541 | "googlevideo.com$", 542 | "googleusercontent.com$", 543 | "google.com.hk$", 544 | "google.com$", 545 | "workers.dev$", 546 | "xcancel.com$", 547 | "geph.io$", 548 | "1lib.sk$", 549 | "odycdn.com$", 550 | "odysee.com$", 551 | "torproject.org$", 552 | "mastodon.social$", 553 | "freezhihu.org$", 554 | "z-library.sk$", 555 | "pages.dev$", 556 | "greatfire.org$", 557 | "gstatic.com$", 558 | "githubassets.com$" 559 | ] 560 | } -------------------------------------------------------------------------------- /docs/notes.md: -------------------------------------------------------------------------------- 1 | # Google available server 2 | 3 | `35.190.247.149:1445` 4 | 5 | # Google available mirrors 6 | 7 | `4.193.121.119:41620` 8 | `13.230.98.94:5128` 9 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from kivy.app import App 2 | from kivy.uix.boxlayout import BoxLayout 3 | from kivy.uix.button import Button 4 | from kivy.uix.textinput import TextInput 5 | from kivy.uix.popup import Popup 6 | from kivy.uix.label import Label 7 | from kivy.metrics import dp 8 | from kivy.utils import platform 9 | from jnius import autoclass 10 | from kivy.uix.checkbox import CheckBox 11 | import os 12 | import json 13 | 14 | 15 | class ProxyApp(App): 16 | def build(self): 17 | self.layout = BoxLayout(orientation='vertical', padding=dp(10), spacing=dp(5)) 18 | button_height = dp(32) # Use numeric value directly 19 | 20 | self.box_start = BoxLayout(orientation='horizontal', size_hint_y=None, height=button_height) 21 | self.start_button = Button( 22 | text='start proxy', 23 | size_hint_y=None, 24 | height=button_height 25 | ) 26 | self.start_button.bind(on_press=self.run_proxy_service) 27 | self.box_start.add_widget(self.start_button) 28 | 29 | self.proxy_running = False 30 | self.vpn_check_box_hint = Label(text='Global VPN') 31 | self.box_start.add_widget(self.vpn_check_box_hint) 32 | 33 | self.vpn_checkbox = CheckBox() 34 | self.box_start.add_widget(self.vpn_checkbox) 35 | self.layout.add_widget(self.box_start) 36 | 37 | self.delete_cache_box = BoxLayout(orientation='horizontal', size_hint_y=None, height=button_height) 38 | self.delete_DNS_cache_button = Button( 39 | text='delete DNS cache', 40 | size_hint_y=None, 41 | height=button_height 42 | ) 43 | self.delete_DNS_cache_button.bind(on_press=self.delete_DNS_cache) 44 | self.delete_cache_box.add_widget(self.delete_DNS_cache_button) 45 | 46 | self.delete_TTL_cache_button = Button( 47 | text='delete TTL cache', 48 | size_hint_y=None, 49 | height=button_height 50 | ) 51 | self.delete_TTL_cache_button.bind(on_press=self.delete_TTL_cache) 52 | self.delete_cache_box.add_widget(self.delete_TTL_cache_button) 53 | self.layout.add_widget(self.delete_cache_box) 54 | 55 | self.config_button_box = BoxLayout(orientation='horizontal', size_hint_y=None, height=button_height) 56 | self.edit_config_button = Button( 57 | text='Edit config', 58 | size_hint_y=None, 59 | height=button_height 60 | ) 61 | self.edit_config_button.bind(on_press=self.edit_config) 62 | self.config_button_box.add_widget(self.edit_config_button) 63 | 64 | self.save_config_button = Button( 65 | text='Save config', 66 | size_hint_y=None, 67 | height=button_height 68 | ) 69 | self.save_config_button.bind(on_press=self.save_config) 70 | self.save_config_button.disabled = True 71 | self.config_button_box.add_widget(self.save_config_button) 72 | self.layout.add_widget(self.config_button_box) 73 | 74 | self.config_input = TextInput( 75 | hint_text='Edit config.json', 76 | multiline=True, 77 | readonly=True, 78 | size_hint_y=1 79 | ) 80 | self.layout.add_widget(self.config_input) 81 | 82 | return self.layout 83 | 84 | def on_start(self): 85 | self.get_permit() 86 | self.load_config() 87 | 88 | def show_popup(self, title, message): 89 | """Utility function to show popups.""" 90 | popup = Popup(title=title, content=Label(text=message), size_hint=(None, None)) 91 | popup.open() 92 | 93 | def edit_config(self, instance): 94 | if self.config_input.readonly: 95 | self.config_input.readonly = False 96 | self.edit_config_button.text = 'Lock config' 97 | self.save_config_button.disabled = False 98 | else: 99 | self.config_input.readonly = True 100 | self.edit_config_button.text = 'Edit config' 101 | self.save_config_button.disabled = True 102 | 103 | def load_config(self): 104 | config_path = 'config.json' 105 | if os.path.exists(config_path): 106 | try: 107 | with open(config_path, 'r') as f: 108 | self.config_input.text = json.dumps(json.load(f), indent=4) 109 | except Exception as e: 110 | self.show_popup('Load config failed', f"Failed to load config: {e}") 111 | else: 112 | self.config_input.text = json.dumps(self.get_default_config(), indent=4) 113 | 114 | def start_proxy_service(self): 115 | """Start the Android service to run the proxy.""" 116 | from android import mActivity 117 | context = mActivity.getApplicationContext() 118 | SERVICE_NAME = str(context.getPackageName()) + '.ServiceProxyservice' 119 | 120 | self.service_target = autoclass(SERVICE_NAME) 121 | self.service_target.start(mActivity, 'icon', 'TlsFragment', 'ProxyRunning', '') 122 | self.show_popup('Start successfully', 'Proxy started successfully') 123 | 124 | return self.service_target 125 | 126 | def stop_proxy_service(self): 127 | from android import mActivity 128 | context = mActivity.getApplicationContext() 129 | SERVICE_NAME = str(context.getPackageName()) + '.ServiceProxyservice' 130 | Service = autoclass(SERVICE_NAME) 131 | Intent = autoclass('android.content.Intent') 132 | service_intent = Intent(mActivity, Service) 133 | mActivity.stopService(service_intent) 134 | 135 | def get_permit(self): 136 | from android.permissions import Permission, request_permissions 137 | 138 | def callback(permissions, results): 139 | granted_permissions = [perm for perm, res in zip(permissions, results) if res] 140 | denied_permissions = [perm for perm, res in zip(permissions, results) if not res] 141 | 142 | if denied_permissions: 143 | print('Denied permissions:', denied_permissions) 144 | elif granted_permissions: 145 | print('Got all permissions') 146 | else: 147 | self.show_popup('Lack of permissions', 'Please grant all permissions to use this app') 148 | 149 | requested_permissions = [ 150 | Permission.INTERNET, 151 | Permission.FOREGROUND_SERVICE, 152 | Permission.READ_EXTERNAL_STORAGE, 153 | Permission.SYSTEM_ALERT_WINDOW, 154 | ] 155 | request_permissions(requested_permissions, callback) 156 | 157 | def run_proxy_service(self, instance): 158 | if self.proxy_running: 159 | try: 160 | self.start_button.disabled = True 161 | self.start_button.text = 'Stopping' 162 | self.stop_proxy_service() 163 | self.start_button.text = 'start proxy' 164 | self.start_button.disabled = False 165 | self.vpn_checkbox.disabled = False 166 | self.config_button_box.disabled = False 167 | self.config_input.disabled = False 168 | self.delete_cache_box.disabled = False 169 | self.proxy_running = False 170 | except Exception as e: 171 | self.show_popup('Stop failed', 'Failed to stop proxy') 172 | self.start_button.text = 'stop proxy' 173 | self.start_button.disabled=False 174 | else: 175 | try: 176 | self.start_button.disabled = True 177 | self.start_button.text = 'starting' 178 | self.start_proxy_service() 179 | self.start_button.text = 'stop proxy' 180 | self.start_button.disabled = False 181 | self.vpn_checkbox.disabled = True 182 | self.config_button_box.disabled = True 183 | self.config_input.disabled = True 184 | self.delete_cache_box.disabled = True 185 | self.proxy_running = True 186 | except Exception as e: 187 | self.show_popup('Start failed', 'Failed to start proxy service') 188 | self.start_button.text = 'Start proxy' 189 | self.start_button.disabled=False 190 | 191 | def save_config(self, instance): 192 | try: 193 | config_data = json.loads(self.config_input.text) 194 | with open('config.json', 'w') as f: 195 | json.dump(config_data, f, indent=4) 196 | self.show_popup('Save config success', 'Config has been saved successfully') 197 | except json.JSONDecodeError: 198 | self.show_popup('Invalid JSON format', 'Please input valid JSON format') 199 | except Exception as e: 200 | self.show_popup('Save config failed', f"Failed to save config: {e}") 201 | 202 | def delete_DNS_cache(self, instance): 203 | try: 204 | if os.path.exists('DNS_cache.json'): 205 | os.remove('DNS_cache.json') 206 | self.show_popup('Delete DNS cache success', 'DNS_cache.json has been deleted successfully') 207 | except Exception as e: 208 | self.show_popup('Delete DNS cache failed', 'Failed to delete DNS_cache.json') 209 | 210 | def delete_TTL_cache(self, instance): 211 | try: 212 | if os.path.exists('TTL_cache.json'): 213 | os.remove('TTL_cache.json') 214 | self.show_popup('Delete TTL cache success', 'TTL_cache.json has been deleted successfully') 215 | except Exception as e: 216 | self.show_popup('Delete TTL cache failed', 'Failed to delete TTL_cache.json') 217 | 218 | if __name__ == '__main__': 219 | ProxyApp().run() 220 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "tls_fragment" 3 | version = "3.1.0" 4 | description = "tls fragment" 5 | readme = "README.md" 6 | authors = ["Maoist2009 "] 7 | license = "MIT" 8 | classifiers = [ 9 | "Operating System :: OS Independent", 10 | "Programming Language :: Python :: 3.11", 11 | ] 12 | 13 | [tool.poetry.dependencies] 14 | python = "^3.11" 15 | ahocorasick-python="^0.0.9" 16 | requests="^2.32.3" 17 | dnspython="^2.3.0" 18 | 19 | [tool.poetry.group.dev.dependencies] 20 | pylint = "^2.17.4" 21 | isort = "^5.12.0" 22 | pytest = "^7.3.1" 23 | tox = "^4.5.2" 24 | mkdocs = "^1.4.3" 25 | mkdocs-material = "^8.5.11" 26 | pytest-pylint = "^0.19.0" 27 | pre-commit = "^3.3.2" 28 | 29 | [build-system] 30 | requires = ["poetry-core"] 31 | build-backend = "poetry.core.masonry.api" 32 | [tool.pytest.ini_options] 33 | testpaths = "tests" 34 | python_files = "tests.py test_*.py *_tests.py" 35 | 36 | [tool.pylint.design] 37 | max-line-length = 120 38 | 39 | [tool.poetry.plugins.console_scripts] 40 | tls_fragment = "tls_fragment.cli:start_server" -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | from src.tls_fragment.cli import start_server 2 | 3 | if __name__ == '__main__': 4 | start_server() -------------------------------------------------------------------------------- /service.py: -------------------------------------------------------------------------------- 1 | # service/main.py 2 | from kivy.logger import Logger 3 | import os 4 | import threading 5 | from src.tls_fragment.cli import start_server, stop_server 6 | 7 | """启动代理服务器并保持服务运行""" 8 | Logger.info("Service: Starting proxy server") 9 | 10 | try: 11 | # 启动代理服务器(非阻塞模式) 12 | # 不再传递config参数 13 | Logger.info("Service: Proxy server started successfully") 14 | start_server(block=True) 15 | 16 | # # 保持主线程运行,防止服务被系统终止 17 | # Clock.schedule_interval(lambda dt: None, 1) 18 | 19 | except Exception as e: 20 | Logger.error(f"Service: Error starting server: {str(e)}") 21 | 22 | -------------------------------------------------------------------------------- /small_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maoist2009/TlsFragment/7bdcead8aee1718f9d6fc5ebd645331a3dd06f0e/small_icon.png -------------------------------------------------------------------------------- /src/tls_fragment/__init__.py: -------------------------------------------------------------------------------- 1 | """tls_fragment""" 2 | __version__ = '0.1.0' 3 | -------------------------------------------------------------------------------- /src/tls_fragment/cli.py: -------------------------------------------------------------------------------- 1 | from .log import logger 2 | from pathlib import Path 3 | import socket 4 | import threading 5 | import time 6 | from . import remote, fake_desync, fragment, utils 7 | from .config import config 8 | from .remote import match_domain 9 | import json 10 | 11 | my_socket_timeout = 120 # default for google is ~21 sec , recommend 60 sec unless you have low ram and need close soon 12 | 13 | datapath = Path() 14 | 15 | domain_settings = { 16 | "null": { 17 | "IP": "127.0.0.1", 18 | "TCP_frag": 114514, 19 | "TCP_sleep": 0.001, 20 | "TLS_frag": 114514, 21 | "num_TCP_fragment": 37, 22 | "num_TLS_fragment": 37, 23 | } 24 | } 25 | 26 | 27 | TTL_cache = {} # TTL for each IP 28 | 29 | lock_TTL_cache = threading.Lock() 30 | pacfile = "function genshin(){}" 31 | 32 | ThreadtoWork = False 33 | proxy_thread = None 34 | 35 | class ThreadedServer(object): 36 | def __init__(self, host, port): 37 | self.host = host 38 | self.port = port 39 | self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 40 | self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 41 | self.sock.bind((self.host, self.port)) 42 | 43 | def listen(self,block=True): 44 | global ThreadtoWork, proxy_thread 45 | self.sock.listen( 46 | 128 47 | ) # up to 128 concurrent unaccepted socket queued , the more is refused untill accepting those. 48 | 49 | proxy_thread = threading.Thread(target=self.accept_connections, args=()) 50 | proxy_thread.start() 51 | if block: 52 | try: 53 | # 主程序逻辑 54 | while True: 55 | time.sleep(1) # 主线程的其他操作 56 | except KeyboardInterrupt: 57 | # 捕获 Ctrl+C 58 | logger.warning("\nServer shutting down.") 59 | finally: 60 | ThreadtoWork = False 61 | self.sock.close() 62 | else: 63 | return self 64 | 65 | def accept_connections(self): 66 | try: 67 | global ThreadtoWork 68 | while ThreadtoWork: 69 | client_sock, _ = self.sock.accept() 70 | client_sock.settimeout(my_socket_timeout) 71 | 72 | time.sleep(0.01) # avoid server crash on flooding request 73 | thread_up = threading.Thread( 74 | target=self.my_upstream, args=(client_sock,) 75 | ) 76 | thread_up.daemon = True # avoid memory leak by telling os its belong to main program , its not a separate program , so gc collect it when thread finish 77 | thread_up.start() 78 | self.sock.close() 79 | except Exception as e: 80 | logger.warning(f"Server error: {repr(e)}") 81 | 82 | def handle_client_request(self, client_socket): 83 | try: 84 | # 协议嗅探(兼容原有逻辑) 85 | initial_data = client_socket.recv(5, socket.MSG_PEEK) 86 | if not initial_data: 87 | client_socket.close() 88 | return None 89 | 90 | # 协议分流判断 91 | if initial_data[0] == 0x05: # SOCKS5协议 92 | return self._handle_socks5(client_socket) 93 | else: # HTTP协议处理 94 | return self._handle_http_protocol(client_socket) 95 | 96 | except Exception as e: 97 | logger.error(f"协议检测异常: {repr(e)}") 98 | client_socket.close() 99 | return None 100 | 101 | def _handle_socks5(self, client_socket): 102 | """处理SOCKS5协议连接,保持与原有返回格式一致""" 103 | try: 104 | # 认证协商阶段 105 | client_socket.recv(2) # 已经通过peek确认版本 106 | nmethods = client_socket.recv(1)[0] 107 | client_socket.recv(nmethods) # 读取方法列表 108 | client_socket.sendall(b"\x05\x00") # 选择无认证 109 | 110 | # 请求解析阶段 111 | header = client_socket.recv(3) 112 | while header[0]!=0x05: 113 | logger.debug("right 1, %s",str(header)) 114 | header=header[1:]+client_sock.recv(1) 115 | logger.debug("socks5 header: %s",header) 116 | if len(header) != 3 or header[0] != 0x05: 117 | raise ValueError("Invalid SOCKS5 header") 118 | 119 | _, cmd, _ = header 120 | 121 | if cmd not in {0x01, 0x05}: # 只支持CONNECT和UDP(over TCP)命令 122 | client_socket.sendall(b"\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00") 123 | client_socket.close() 124 | raise ValueError(f"Not supported socks command, {cmd}") 125 | 126 | # 目标地址解析(复用原有DNS逻辑) 127 | server_name, server_port = utils.parse_socks5_address(client_socket) 128 | 129 | logger.info("%s:%d",server_name,server_port) 130 | 131 | # 建立连接(完全复用原有逻辑) 132 | try: 133 | if cmd==0x01: 134 | remote_obj = remote.Remote(server_name, server_port, 6) 135 | elif cmd==0x05: 136 | remote_obj = remote.Remote(server_name, server_port, 17) 137 | 138 | client_socket.sendall( 139 | b"\x05\x00\x00\x01" + socket.inet_aton("0.0.0.0") + b"\x00\x00" 140 | ) 141 | return remote_obj 142 | except Exception as e: 143 | logger.info(f"连接失败: {repr(e)}") 144 | client_socket.sendall(b"\x05\x04\x00\x01\x00\x00\x00\x00\x00\x00") 145 | client_socket.close() 146 | return server_name if utils.is_ip_address(server_name) else None 147 | 148 | except Exception as e: 149 | logger.info(f"SOCKS5处理错误: {repr(e)}") 150 | client_socket.close() 151 | return None 152 | 153 | def _handle_http_protocol(self, client_socket): 154 | """原有HTTP处理逻辑完整保留""" 155 | data = client_socket.recv(16384) 156 | 157 | # 原有CONNECT处理 158 | if data.startswith(b"CONNECT "): 159 | server_name, server_port = self.extract_servername_and_port(data) 160 | logger.info(f"CONNECT {server_name}:{server_port}") 161 | 162 | try: 163 | remote_obj = remote.Remote(server_name, server_port) 164 | client_socket.sendall( 165 | b"HTTP/1.1 200 Connection established\r\nProxy-agent: MyProxy/1.0\r\n\r\n" 166 | ) 167 | return remote_obj 168 | except Exception as e: 169 | logger.info(f"连接失败: {repr(e)}") 170 | client_socket.sendall( 171 | b"HTTP/1.1 502 Bad Gateway\r\nProxy-agent: MyProxy/1.0\r\n\r\n" 172 | ) 173 | client_socket.close() 174 | return server_name if utils.is_ip_address(server_name) else None 175 | 176 | # 原有PAC文件处理 177 | elif b"/proxy.pac" in data.splitlines()[0]: 178 | response = f"HTTP/1.1 200 OK\r\nContent-Type: application/x-ns-proxy-autoconfig\r\nContent-Length: {len(pacfile)}\r\n\r\n{pacfile}" 179 | client_socket.sendall(response.encode()) 180 | client_socket.close() 181 | return None 182 | 183 | # 原有HTTP重定向逻辑 184 | elif data.startswith((b'GET ', b'PUT ', b'DELETE ', b'POST ', b'HEAD ', b'OPTIONS ')): 185 | q_line = data.decode().split("\r\n")[0].split() 186 | q_method, q_url = q_line[0], q_line[1] 187 | https_url = q_url.replace("http://", "https://", 1) 188 | logger.info(f"重定向 {q_method} 到 HTTPS: {https_url}") 189 | response = f"HTTP/1.1 302 Found\r\nLocation: {https_url}\r\nProxy-agent: MyProxy/1.0\r\n\r\n" 190 | client_socket.sendall(response.encode()) 191 | client_socket.close() 192 | return None 193 | 194 | # 原有错误处理 195 | else: 196 | logger.info(f"未知请求: {data[:10]}") 197 | client_socket.sendall( 198 | b"HTTP/1.1 400 Bad Request\r\nProxy-agent: MyProxy/1.0\r\n\r\n" 199 | ) 200 | client_socket.close() 201 | return None 202 | 203 | def my_upstream(self, client_sock): 204 | first_flag = True 205 | backend_sock = self.handle_client_request(client_sock) 206 | if backend_sock == None: 207 | client_sock.close() 208 | raise Exception("backend not found") 209 | 210 | global ThreadtoWork 211 | while ThreadtoWork: 212 | try: 213 | if first_flag is True: 214 | first_flag = False 215 | 216 | time.sleep( 217 | 0.1 218 | ) # speed control + waiting for packet to fully recieve 219 | data = client_sock.recv(16384) 220 | 221 | try: 222 | extractedsni = utils.extract_sni(data) 223 | if config["BySNIfirst"] and str(extractedsni,encoding="ASCII") != backend_sock.domain: 224 | port, protocol=backend_sock.port,backend_sock.protocol 225 | logger.info(f"replace backendsock: {extractedsni} {port} {protocol}") 226 | new_backend_sock=remote.Remote(str(extractedsni,encoding="ASCII"),port,protocol) 227 | backend_sock=new_backend_sock 228 | except: 229 | pass 230 | 231 | try: 232 | backend_sock.connect() 233 | except: 234 | raise Exception("backend connect fail") 235 | 236 | 237 | if backend_sock.policy.get("safety_check") is True and data.startswith((b'GET ', b'PUT ', b'DELETE ', b'POST ', b'HEAD ', b'OPTIONS ')): 238 | logger.warning("HTTP protocol detected, will redirect to https") 239 | # 如果是http协议,重定向到https,要从data中提取url 240 | q_line = data.decode().split("\r\n")[0].split() 241 | q_method, q_url = q_line[0], q_line[1] 242 | https_url = q_url.replace("http://", "https://", 1) 243 | logger.info(f"重定向 {q_method} 到 HTTPS: {https_url}") 244 | response = f"HTTP/1.1 302 Found\r\nLocation: {https_url}\r\nProxy-agent: MyProxy/1.0\r\n\r\n" 245 | client_sock.sendall(response.encode()) 246 | client_sock.close() 247 | backend_sock.close() 248 | 249 | try: 250 | backend_sock.sni = extractedsni 251 | if str(backend_sock.sni)!=str(backend_sock.domain): 252 | backend_sock.policy = {**backend_sock.policy, **match_domain(str(backend_sock.sni))} 253 | except: 254 | backend_sock.send(data) 255 | return 256 | 257 | if data: 258 | thread_down = threading.Thread( 259 | target=self.my_downstream, 260 | args=(backend_sock, client_sock), 261 | ) 262 | thread_down.daemon = True 263 | thread_down.start() 264 | # backend_sock.sendall(data) 265 | 266 | mode = backend_sock.policy.get('mode') 267 | if mode == "TLSfrag": 268 | fragment.send_fraggmed_tls_data(backend_sock, data) 269 | elif mode == "FAKEdesync": 270 | fake_desync.send_data_with_fake(backend_sock,data) 271 | elif mode == "DIRECT": 272 | backend_sock.send(data) 273 | elif mode == "GFWlike": 274 | backend_sock.close() 275 | client_sock.close() 276 | return False 277 | 278 | else: 279 | raise Exception("cli syn close") 280 | 281 | else: 282 | data = client_sock.recv(16384) 283 | if data: 284 | backend_sock.send(data) 285 | else: 286 | raise Exception("cli pipe close") 287 | 288 | except Exception as e: 289 | logger.info(f"upstream : {repr(e)} from {backend_sock.domain}") 290 | time.sleep(2) # wait two second for another thread to flush 291 | client_sock.close() 292 | backend_sock.close() 293 | return False 294 | 295 | client_sock.close() 296 | backend_sock.close() 297 | 298 | def my_downstream(self, backend_sock: remote.Remote, client_sock: socket.socket): 299 | this_ip = backend_sock.sock.getpeername()[0] 300 | 301 | first_flag = True 302 | global ThreadtoWork 303 | while ThreadtoWork: 304 | try: 305 | if first_flag is True: 306 | first_flag = False 307 | data = backend_sock.recv(16384) 308 | if backend_sock.policy.get("safety_check")==True: 309 | try: 310 | if utils.detect_tls_version_by_keyshare(data) < 0: 311 | logger.warning("Not a TLS 1.3 connection and will close") 312 | backend_sock.close() 313 | client_sock.close() 314 | raise ValueError("Not a TLS 1.3 connection") 315 | except: 316 | pass 317 | if data: 318 | client_sock.sendall(data) 319 | else: 320 | raise Exception("backend pipe close at first") 321 | 322 | else: 323 | data = backend_sock.recv(16384) 324 | if data: 325 | client_sock.sendall(data) 326 | else: 327 | raise Exception("backend pipe close") 328 | 329 | except Exception as e: 330 | logger.info(f"downstream : {repr(e)} from {backend_sock.domain}") 331 | time.sleep(2) # wait two second for another thread to flush 332 | backend_sock.close() 333 | client_sock.close() 334 | return False 335 | 336 | client_sock.close() 337 | backend_sock.close() 338 | 339 | def extract_servername_and_port(self, data): 340 | host_and_port = str(data).split()[1] 341 | try: 342 | host, port = host_and_port.split(":") 343 | except: 344 | # ipv6 345 | if host_and_port.find("[") != -1: 346 | host, port = host_and_port.split("]:") 347 | host = host[1:] 348 | else: 349 | idx = 0 350 | for _ in range(6): 351 | idx = host_and_port.find(":", idx + 1) 352 | host = host_and_port[:idx] 353 | port = host_and_port[idx + 1 :] 354 | return (host, int(port)) 355 | 356 | 357 | # http114=b"" 358 | 359 | 360 | serverHandle = None 361 | 362 | 363 | def generate_PAC(): 364 | global pacfile 365 | pacfile = """class TrieNode { 366 | constructor(value){ 367 | this.value = value; 368 | this.num=1; 369 | this.deep=0; 370 | this.son=[]; 371 | this.isEnd=false; 372 | } 373 | findNode(value){ 374 | for(let i=0;i Resolved {server_name} to {resolved_ip}") 53 | return resolved_ip 54 | logger.error(f"online DNS --> Error DNS query: {ans.status_code} {ans.reason}") 55 | except Exception as e: 56 | logger.error(f"online DNS --> Error DNS query: {repr(e)}") 57 | raise Exception("online DNS --> Error DNS query") 58 | 59 | -------------------------------------------------------------------------------- /src/tls_fragment/fake_desync.py: -------------------------------------------------------------------------------- 1 | import socket 2 | from .utils import set_ttl 3 | from .log import logger 4 | from . import remote 5 | import time 6 | 7 | logger = logger.getChild("fake_desync") 8 | 9 | try: 10 | import platform 11 | system = platform.system() 12 | if system == "Windows": 13 | 14 | import ctypes 15 | from ctypes import wintypes 16 | 17 | # 加载 mswsock.dll 库 18 | mswsock = ctypes.WinDLL("mswsock") 19 | # 加载 ws2_32.dll 库 20 | ws2_32 = ctypes.windll.ws2_32 21 | # 加载 kernel32.dll 库 22 | kernel32 = ctypes.windll.kernel32 23 | msvcrt = ctypes.cdll.msvcrt 24 | 25 | class _DUMMYSTRUCTNAME(ctypes.Structure): 26 | _fields_ = [ 27 | ("Offset", wintypes.DWORD), 28 | ("OffsetHigh", wintypes.DWORD), 29 | ] 30 | 31 | # 定义 TransmitFile 函数的参数类型 32 | class _DUMMYUNIONNAME(ctypes.Union): 33 | _fields_ = [ 34 | ("Pointer", ctypes.POINTER(ctypes.c_void_p)), 35 | ("DUMMYSTRUCTNAME", _DUMMYSTRUCTNAME), 36 | ] 37 | 38 | # class OVERLAPPED(ctypes.Structure): 39 | # _fields_ = [ 40 | # ("Internal", wintypes.ULONG), 41 | # ("InternalHigh", wintypes.ULONG), 42 | # ("DUMMYUNIONNAME", _DUMMYUNIONNAME), 43 | # ("hEvent", wintypes.HANDLE), 44 | # ] 45 | 46 | class OVERLAPPED(ctypes.Structure): 47 | _fields_ = [ 48 | ("Internal", ctypes.c_void_p), 49 | ("InternalHigh", ctypes.c_void_p), 50 | ("Offset", ctypes.c_ulong), 51 | ("OffsetHigh", ctypes.c_ulong), 52 | ("hEvent", ctypes.c_void_p), 53 | ] 54 | 55 | # import pywintypes 56 | mswsock.TransmitFile.argtypes = [ 57 | wintypes.HANDLE, # 套接字句柄 58 | wintypes.HANDLE, # 文件句柄 59 | wintypes.DWORD, # 要发送的字节数 60 | wintypes.DWORD, # 每次发送的字节数 61 | ctypes.POINTER(OVERLAPPED), # 重叠结构指针 62 | ctypes.POINTER(ctypes.c_void_p), # 传输缓冲区指针 63 | wintypes.DWORD, # 保留参数 64 | ] 65 | # 定义 TransmitFile 函数的返回值类型 66 | mswsock.TransmitFile.restype = wintypes.BOOL 67 | # ws2_32.WSASocketW.argtypes = [ 68 | # wintypes.INT, wintypes.INT, wintypes.INT, 69 | # wintypes.DWORD,wintypes.DWORD, wintypes.DWORD 70 | # ] 71 | # ws2_32.WSASocketW.restype = ctypes.c_uint 72 | 73 | kernel32.CreateFileA.argtypes = [ 74 | wintypes.LPCSTR, 75 | wintypes.DWORD, 76 | wintypes.DWORD, 77 | wintypes.LPVOID, 78 | wintypes.DWORD, 79 | wintypes.DWORD, 80 | wintypes.LPVOID, 81 | ] 82 | kernel32.CreateFileA.restype = wintypes.HANDLE 83 | kernel32.WriteFile.argtypes = [ 84 | wintypes.HANDLE, 85 | wintypes.LPVOID, 86 | wintypes.DWORD, 87 | ctypes.POINTER(wintypes.DWORD), 88 | wintypes.LPVOID, 89 | ] 90 | kernel32.WriteFile.restype = wintypes.BOOL 91 | kernel32.SetFilePointer.argtypes = [ 92 | wintypes.HANDLE, 93 | ctypes.c_long, 94 | wintypes.LONG, 95 | wintypes.DWORD, 96 | ] 97 | kernel32.SetFilePointer.restype = ctypes.c_long 98 | kernel32.SetEndOfFile.argtypes = [wintypes.HANDLE] 99 | kernel32.SetEndOfFile.restype = wintypes.BOOL 100 | kernel32.CloseHandle.argtypes = [wintypes.HANDLE] 101 | kernel32.CloseHandle.restype = wintypes.BOOL 102 | msvcrt._get_osfhandle.argtypes = [wintypes.INT] 103 | msvcrt._get_osfhandle.restype = wintypes.HANDLE 104 | # kernel32._get_osfhandle.argtypes = [wintypes.INT] 105 | # kernel32._get_osfhandle.restype = wintypes.HANDLE 106 | pass 107 | elif system in {"Linux", "Darwin", "Android"}: 108 | import ctypes 109 | 110 | # 加载 libc 库 111 | 112 | try: 113 | libc = ctypes.CDLL("libc.so.6") 114 | except: 115 | libc = ctypes.CDLL("/system/lib64/libc.so") 116 | 117 | class iovec(ctypes.Structure): 118 | _fields_ = [("iov_base", ctypes.c_void_p), ("iov_len", ctypes.c_size_t)] 119 | 120 | # 定义 splice 函数的参数类型和返回类型 121 | libc.splice.argtypes = [ 122 | ctypes.c_int, # int fd_in 123 | ctypes.c_longlong, # loff_t *off_in 124 | ctypes.c_int, # int fd_out 125 | ctypes.c_longlong, # loff_t *off_out 126 | ctypes.c_size_t, # size_t len 127 | ctypes.c_uint, # unsigned int flags 128 | ] 129 | libc.splice.restype = ctypes.c_ssize_t 130 | 131 | # 定义 vmsplice 函数的参数类型和返回类型 132 | libc.vmsplice.argtypes = [ 133 | ctypes.c_int, # int fd 134 | ctypes.POINTER(iovec), # struct iovec *iov 135 | ctypes.c_size_t, # size_t nr_segs 136 | ctypes.c_uint, # unsigned int flags 137 | ] 138 | libc.vmsplice.restype = ctypes.c_ssize_t 139 | 140 | libc.mmap.argtypes = [ 141 | ctypes.c_void_p, # void *addr 142 | ctypes.c_size_t, # size_t length 143 | ctypes.c_int, # int prot 144 | ctypes.c_int, # int flags 145 | ctypes.c_int, # int fd 146 | ctypes.c_size_t, # off_t offset 147 | ] 148 | libc.mmap.restype = ctypes.c_void_p 149 | 150 | libc.memcpy.argtypes = [ 151 | ctypes.c_void_p, # void *dest 152 | ctypes.c_void_p, # const void *src 153 | ctypes.c_size_t, # size_t n 154 | ] 155 | libc.memcpy.restype = ctypes.c_void_p 156 | libc.close.argtypes = [ctypes.c_int] 157 | libc.close.restype = ctypes.c_int 158 | 159 | libc.munmap.argtypes = [ 160 | ctypes.c_void_p, # void *addr 161 | ctypes.c_size_t, # size_t length 162 | ] 163 | libc.munmap.restype = ctypes.c_int 164 | 165 | libc.pipe.argtypes = [ctypes.POINTER(ctypes.c_int)] 166 | libc.pipe.restype = ctypes.c_int 167 | 168 | pass 169 | except Exception as e: 170 | logger.warning(repr(e)) 171 | 172 | 173 | def send_fake_data( 174 | data_len, fake_data, fake_ttl, real_data, default_ttl, sock, FAKE_sleep 175 | ): 176 | import platform 177 | system = platform.system() 178 | logger.info(system) 179 | if system == "Windows": 180 | logger.warning( 181 | "Desync on Windows may cause Error! Make sure other programs are not using the TransmitFile. " 182 | ) 183 | """ 184 | BOOL TransmitFile( 185 | SOCKET hSocket, 186 | HANDLE hFile, 187 | DWORD nNumberOfBytesToWrite, 188 | DWORD nNumberOfBytesPerSend, 189 | LPOVERLAPPED lpOverlapped, 190 | LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers, 191 | DWORD dwReserved 192 | ); 193 | """ 194 | import tempfile, uuid 195 | 196 | file_path = f"{tempfile.gettempdir()}\\{uuid.uuid4()}.txt" 197 | try: 198 | sock_file_descriptor = sock.fileno() 199 | logger.info("sock file discriptor: %s", sock_file_descriptor) 200 | file_handle = kernel32.CreateFileA( 201 | bytes(file_path, encoding="utf-8"), 202 | wintypes.DWORD(0x40000000 | 0x80000000), # GENERIC_READ | GENERIC_WRITE 203 | wintypes.DWORD( 204 | 0x00000001 | 0x00000002 205 | ), # FILE_SHARE_READ | FILE_SHARE_WRITE 206 | None, 207 | wintypes.DWORD(2), # CREATE_ALWAYS 208 | # 0, 209 | 0x00000100, # FILE_FLAG_DELETE_ON_CLOSE 210 | None, 211 | ) 212 | 213 | if file_handle == -1: 214 | raise Exception( 215 | "Create file failed, Error code:", kernel32.GetLastError() 216 | ) 217 | logger.info(f"Create file success {file_handle}") 218 | try: 219 | ov = OVERLAPPED() 220 | ov.hEvent = kernel32.CreateEventA(None, True, False, None) 221 | if ov.hEvent <= 0: 222 | raise Exception( 223 | "Failed to create event. Error code:", kernel32.GetLastError() 224 | ) 225 | logger.info(f"Create event success {ov.hEvent}") 226 | 227 | kernel32.SetFilePointer(file_handle, 0, 0, 0) 228 | kernel32.WriteFile( 229 | file_handle, 230 | fake_data, 231 | data_len, 232 | ctypes.byref(wintypes.DWORD(0)), 233 | None, 234 | ) 235 | kernel32.SetEndOfFile(file_handle) 236 | set_ttl(sock, fake_ttl) 237 | kernel32.SetFilePointer(file_handle, 0, 0, 0) 238 | 239 | logger.debug(f"{fake_data} {real_data} {data_len}") 240 | 241 | # 调用 TransmitFile 函数 242 | result = mswsock.TransmitFile( 243 | sock_file_descriptor, 244 | file_handle, 245 | wintypes.DWORD(data_len), 246 | wintypes.DWORD(data_len), 247 | ov, 248 | None, 249 | 32 | 4, # TF_USE_KERNEL_APC | TF_WRITE_BEHIND 250 | ) 251 | 252 | if FAKE_sleep < 0.1: 253 | logger.warning("Too short sleep time on Windows, set to 0.1") 254 | FAKE_sleep = 0.1 255 | 256 | logger.info("sleep for: %d", FAKE_sleep) 257 | time.sleep(FAKE_sleep) 258 | kernel32.SetFilePointer(file_handle, 0, 0, 0) 259 | kernel32.WriteFile( 260 | file_handle, 261 | real_data, 262 | data_len, 263 | ctypes.byref(wintypes.DWORD(0)), 264 | None, 265 | ) 266 | kernel32.SetEndOfFile(file_handle) 267 | kernel32.SetFilePointer(file_handle, 0, 0, 0) 268 | set_ttl(sock, default_ttl) 269 | 270 | val = kernel32.WaitForSingleObject(ov.hEvent, wintypes.DWORD(5000)) 271 | 272 | if val == 0: 273 | logger.info(f"TransmitFile call was successful. {result}") 274 | else: 275 | raise Exception( 276 | "TransmitFile call failed (on waiting for event). Error code:", 277 | kernel32.GetLastError(), 278 | ws2_32.WSAGetLastError(), 279 | ) 280 | return True 281 | except: 282 | raise Exception( 283 | "TransmitFile call failed. Error code:", kernel32.GetLastError() 284 | ) 285 | finally: 286 | kernel32.CloseHandle(file_handle) 287 | kernel32.CloseHandle(ov.hEvent) 288 | import os 289 | os.remove(file_path) 290 | except Exception as e: 291 | raise e 292 | elif system in {"Linux", "Darwin", "Android"}: 293 | try: 294 | sock_file_descriptor = sock.fileno() 295 | logger.info(f"sock file discriptor: {sock_file_descriptor}") 296 | fds = (ctypes.c_int * 2)() 297 | if libc.pipe(fds) < 0: 298 | raise Exception("pipe creation failed") 299 | logger.info("pipe creation success %d %d", fds[0], fds[1]) 300 | p = libc.mmap( 301 | 0, ((data_len - 1) // 4 + 1) * 4, 0x1 | 0x2, 0x2 | 0x20, 0, 0 302 | ) # PROT_WRITE | PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS 303 | if p == ctypes.c_void_p(-1): 304 | raise Exception("mmap failed") 305 | logger.info("mmap success %s", p) 306 | libc.memcpy(p, fake_data, data_len) 307 | set_ttl(sock, fake_ttl) 308 | vec = iovec(p, data_len) 309 | len = libc.vmsplice(fds[1], ctypes.byref(vec), 1, 2) # SPLICE_F_GIFT 310 | if len < 0: 311 | raise Exception("vmsplice failed") 312 | logger.info("vmsplice success %d", len) 313 | len = libc.splice(fds[0], 0, sock_file_descriptor, 0, data_len, 0) 314 | if len < 0: 315 | raise Exception("splice failed") 316 | logger.info("splice success %d", len) 317 | logger.info(f"sleep for: {FAKE_sleep}") 318 | time.sleep(FAKE_sleep) 319 | libc.memcpy(p, real_data, data_len) 320 | set_ttl(sock, default_ttl) 321 | return True 322 | except Exception as e: 323 | raise e 324 | finally: 325 | libc.munmap(p, ((data_len - 1) // 4 + 1) * 4) 326 | libc.close(fds[0]) 327 | libc.close(fds[1]) 328 | else: 329 | raise Exception("unknown os") 330 | 331 | 332 | def send_data_with_fake(sock: remote.Remote, data): 333 | logger.info("To send: %d Bytes. ", len(data)) # check os 334 | # if windows, use TransmitFile 335 | default_ttl = sock.sock.getsockopt(socket.IPPROTO_IP, socket.IP_TTL) 336 | try: 337 | fake_data = sock.policy.get("fake_packet") 338 | fake_ttl = int(sock.policy.get("fake_ttl")) 339 | except: 340 | raise Exception("FAKE_packet or FAKE_ttl not set in settings.json") 341 | 342 | data_len = len(fake_data) 343 | FAKE_sleep = sock.policy.get("fake_sleep") 344 | if send_fake_data( 345 | data_len, 346 | fake_data, 347 | fake_ttl, 348 | data[0:data_len], 349 | default_ttl, 350 | sock.sock, 351 | FAKE_sleep, 352 | ): 353 | logger.info("Fake data sent.") 354 | else: 355 | raise Exception("Failed to send fake data.") 356 | 357 | data = data[data_len:] 358 | sni=sock.sni 359 | if sni==None: 360 | sock.send(data) 361 | return 362 | 363 | position = data.find(sni) 364 | logger.debug(f"{sni} {position}") 365 | if position == -1: 366 | sock.send(data) 367 | return 368 | sni_len = len(sni) 369 | 370 | sock.send(data[0:position]) 371 | data=data[position:] 372 | 373 | if sock.policy.get("len_tcp_sni") >= sni_len: 374 | sock.policy["len_tcp_sni"]=sni_len/2 375 | logger.info("len_tcp_sni too big, set to %d",sock.policy.get("len_tcp_sni")) 376 | 377 | if send_fake_data( 378 | sock.policy.get("len_tcp_sni"), 379 | fake_data, 380 | fake_ttl, 381 | sni[0:sock.policy.get("len_tcp_sni")], 382 | default_ttl, 383 | sock.sock, 384 | FAKE_sleep, 385 | ): 386 | logger.info("Fake sni sent.") 387 | else: 388 | raise Exception("Failed to send fake SNI.") 389 | 390 | data=data[sock.policy.get("len_tcp_sni"):] 391 | 392 | sock.send(data) 393 | -------------------------------------------------------------------------------- /src/tls_fragment/fragment.py: -------------------------------------------------------------------------------- 1 | """ 2 | tls data fragment. 3 | """ 4 | 5 | import random 6 | from .log import logger 7 | from . import remote 8 | import time 9 | 10 | 11 | logger = logger.getChild("fragment") 12 | 13 | def fragment_content(data: str, num: int) -> list: 14 | """ 15 | frag into num pieces 16 | """ 17 | data_length = len(data) 18 | fragmented_content = [] 19 | if len(data) > 1: 20 | dividing_points = random.sample( 21 | range(1, data_length), min(num, data_length - 1) 22 | ) 23 | else: 24 | fragmented_content.append(data) 25 | return 26 | dividing_points.append(0) 27 | dividing_points.append(data_length) 28 | dividing_points.sort() 29 | for i in range(len(dividing_points) - 1): 30 | fragmented_content.append(data[dividing_points[i]:dividing_points[i + 1]]) 31 | return fragmented_content 32 | 33 | 34 | def fragment_pattern(data, pattern, len_sni: int, num_pieces: int): 35 | """ 36 | fragment pattern into at least num parts. 37 | the first part of the pattern contains in 38 | fragmented_data[0] 39 | """ 40 | fragmented_data = [] 41 | position = data.find(pattern) 42 | logger.debug(f"{pattern} {position}") 43 | if position == -1: 44 | return fragment_content(data, 2 * num_pieces) 45 | 46 | print(position) 47 | pattern_length = len(pattern) 48 | data_length = len(data) 49 | 50 | fragmented_data.extend(fragment_content(data[0:position], num_pieces)) 51 | 52 | l = len(fragmented_data) 53 | 54 | if len_sni >= len(pattern) / 2: 55 | len_sni = int(len(pattern) / 2) 56 | logger.info("len_sni was too big so it has been set to %d", len_sni) 57 | 58 | num = int(pattern_length / len_sni) 59 | 60 | if num * len_sni < pattern_length: 61 | num += 1 62 | 63 | for i in range(num): 64 | fragmented_data.append( 65 | data[position + i * len_sni:position + (i + 1) * len_sni] 66 | ) 67 | 68 | r = len(fragmented_data) 69 | 70 | fragmented_data.extend( 71 | fragment_content(data[position + num * len_sni:], num_pieces) 72 | ) 73 | return fragmented_data, l, r 74 | 75 | def send_fraggmed_tls_data(sock: remote.Remote, data): 76 | """send fragged tls data""" 77 | sni = sock.sni 78 | 79 | logger.info("To send: %d Bytes.", len(data)) 80 | if sni is None: 81 | sock.send(data) 82 | return 83 | 84 | logger.debug(f"Sending: {data}") 85 | base_header = data[:3] 86 | record = data[5:] 87 | 88 | fragmented_tls_data, l, r = fragment_pattern( 89 | record, sni, sock.policy["len_tls_sni"], sock.policy["num_tls_pieces"] 90 | ) 91 | tcp_data = b"" 92 | for i, _ in enumerate(fragmented_tls_data): 93 | tmp = fragmented_tls_data[i] = ( 94 | base_header 95 | + int.to_bytes(len(fragmented_tls_data[i]), byteorder="big", length=2) 96 | + fragmented_tls_data[i] 97 | ) 98 | tcp_data += tmp 99 | logger.debug("Adding frag: %d bytes.", len(tmp)) 100 | logger.debug(f"Adding frag: {tmp}") 101 | 102 | logger.info("TLS fraged: %d Bytes.", len(tcp_data)) 103 | logger.debug(f"TLS fraged: {tcp_data}") 104 | 105 | lenl = 0 106 | for i in range(0,l): 107 | lenl += len(fragmented_tls_data[i]) 108 | lenr = lenl 109 | for i in range(l, r): 110 | lenr += len(fragmented_tls_data[i]) 111 | 112 | fragmented_tcp_data, l, r = fragment_pattern( 113 | tcp_data, 114 | tcp_data[lenl:lenr], 115 | sock.policy["len_tcp_sni"], 116 | sock.policy["num_tcp_pieces"], 117 | ) 118 | 119 | for packet in fragmented_tcp_data: 120 | sock.send(packet) 121 | logger.debug( 122 | "TCP send: %d bytes. And 'll sleep for %d seconds.", 123 | len(packet), 124 | sock.policy["send_interval"], 125 | ) 126 | logger.debug(f"TCP send: {packet}") 127 | 128 | time.sleep(sock.policy["send_interval"]) 129 | 130 | logger.info(f"----------finish------------ {sni}") 131 | -------------------------------------------------------------------------------- /src/tls_fragment/log.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from .config import config 3 | 4 | logging.basicConfig( 5 | format="%(asctime)s %(levelname)-8s %(name)s: %(message)s", 6 | datefmt="%Y-%m-%d %H:%M:%S", 7 | ) 8 | logger = logging.getLogger("tls_fragmenter") 9 | logger.setLevel(config["loglevel"]) 10 | -------------------------------------------------------------------------------- /src/tls_fragment/remote.py: -------------------------------------------------------------------------------- 1 | """ 2 | site 3 | """ 4 | 5 | from .log import logger 6 | from .config import ( 7 | domain_policies, 8 | config, 9 | default_policy, 10 | ipv4_map, 11 | ipv6_map, 12 | DNS_cache, 13 | TTL_cache, 14 | write_DNS_cache, 15 | write_TTL_cache 16 | ) 17 | 18 | from .dns_extension import MyDoh 19 | import socket 20 | import threading 21 | from . import utils 22 | 23 | logger = logger.getChild("remote") 24 | 25 | resolver = MyDoh(proxy=f'http://127.0.0.1:{config["DOH_port"]}', url=config["doh_server"]) 26 | cnt_upd_TTL_cache = 0 27 | lock_TTL_cache = threading.Lock() 28 | cnt_upd_DNS_cache = 0 29 | lock_DNS_cache = threading.Lock() 30 | 31 | 32 | def redirect(ip): 33 | if ':' in ip: 34 | mapped_ip = ipv6_map.search(utils.ip_to_binary_prefix(ip)) 35 | else: 36 | mapped_ip = ipv4_map.search(utils.ip_to_binary_prefix(ip)) 37 | if mapped_ip is None: 38 | return ip 39 | logger.info(f"IP redirect {ip} to {mapped_ip}") 40 | if mapped_ip[0] == "^": 41 | return mapped_ip[1:] 42 | if ip == mapped_ip: 43 | return mapped_ip 44 | return redirect(mapped_ip) 45 | 46 | def match_domain(domain): 47 | matched_domains = domain_policies.search("^" + domain + "$") 48 | if matched_domains: 49 | import copy 50 | return copy.deepcopy( 51 | config["domains"].get(sorted(matched_domains, key=len, reverse=True)[0]) 52 | ) 53 | else: 54 | return {} 55 | 56 | 57 | class Remote: 58 | policy: dict 59 | domain: str 60 | address: str 61 | sock: socket.socket 62 | port: int 63 | protocl: int 64 | # 6 tcp 17 udp 65 | 66 | def __init__(self, domain: str, port=443, protocol=6): 67 | self.domain = domain 68 | self.policy = match_domain(domain) 69 | self.policy = {**default_policy, **self.policy} 70 | self.policy.setdefault("port", port) 71 | self.protocol = protocol 72 | import ipaddress 73 | 74 | try: 75 | ipaddress.IPv4Address(self.domain) 76 | self.policy["IP"] = self.domain 77 | except: 78 | try: 79 | ipaddress.IPv6Address(self.domain) 80 | self.policy["IP"] = self.domain 81 | except: 82 | pass 83 | 84 | if self.policy.get("IP") is None: 85 | if DNS_cache.get(self.domain) is not None: 86 | self.address = DNS_cache[self.domain] 87 | logger.info("DNS cache for %s is %s", self.domain, self.address) 88 | else: 89 | if self.policy.get("IPtype") == "ipv6": 90 | try: 91 | self.address = resolver.resolve(self.domain, "AAAA") 92 | except: 93 | self.address = resolver.resolve(self.domain, "A") 94 | else: 95 | try: 96 | self.address = resolver.resolve(self.domain, "A") 97 | except: 98 | self.address = resolver.resolve(self.domain, "AAAA") 99 | if self.address: 100 | global cnt_upd_DNS_cache, lock_DNS_cache 101 | lock_DNS_cache.acquire() 102 | DNS_cache[self.domain] = self.address 103 | cnt_upd_DNS_cache += 1 104 | if cnt_upd_DNS_cache >= config["DNS_cache_update_interval"]: 105 | cnt_upd_DNS_cache = 0 106 | write_DNS_cache() 107 | lock_DNS_cache.release() 108 | logger.info(f"DNS cache for {self.domain} to {self.address}") 109 | else: 110 | self.address = self.policy["IP"] 111 | self.address = redirect(self.address) 112 | self.port = self.policy["port"] 113 | 114 | logger.info("%s %d", self.address, self.port) 115 | # res["IP"]="127.0.0.1" 116 | 117 | if self.policy["fake_ttl"] == "query" and self.policy["mode"] == "FAKEdesync": 118 | logger.info(f'FAKE TTL for {self.address} is {self.policy.get("fake_ttl")}') 119 | if TTL_cache.get(self.address) != None: 120 | self.policy["fake_ttl"] = TTL_cache[self.address] - 1 121 | logger.info( 122 | "FAKE TTL for %s is %d", self.address, self.policy.get("fake_ttl") 123 | ) 124 | else: 125 | logger.info("%s %d", self.address, self.policy.get("port")) 126 | val = utils.get_ttl(self.address, self.policy.get("port")) 127 | if val == -1: 128 | raise Exception("ERROR get ttl") 129 | global cnt_upd_TTL_cache, lock_TTL_cache 130 | lock_TTL_cache.acquire() 131 | TTL_cache[self.address] = val 132 | cnt_upd_TTL_cache += 1 133 | if cnt_upd_TTL_cache >= config["TTL_cache_update_interval"]: 134 | cnt_upd_TTL_cache = 0 135 | write_TTL_cache() 136 | lock_TTL_cache.release() 137 | self.policy["fake_ttl"] = val - 1 138 | logger.info( 139 | "FAKE TTL for %s is %d", self.address, self.policy.get("fake_ttl") 140 | ) 141 | 142 | logger.info(f"{domain} --> {self.policy}") 143 | 144 | iptype = socket.AF_INET6 if ":" in self.address else socket.AF_INET 145 | 146 | if self.protocol == 6: 147 | socktype = socket.SOCK_STREAM 148 | self.sock = socket.socket(iptype, socktype) 149 | elif self.protocol == 17: 150 | socktype = socket.SOCK_DGRAM 151 | self.sock = socket.socket(iptype, socktype) 152 | else: 153 | raise ValueError("Unknown sock type", self.protocol) 154 | 155 | if self.protocol == 6: 156 | self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 157 | self.sock.settimeout(config["my_socket_timeout"]) 158 | 159 | def connect(self): 160 | if self.protocol == 6: 161 | self.sock.connect((self.address, self.port)) 162 | elif self.protocol == 17: 163 | pass 164 | 165 | def send(self, data): 166 | if self.protocol == 6: 167 | self.sock.sendall(data) 168 | elif self.protocol == 17: 169 | data = data[3:] 170 | address, port, offset = utils.parse_socks5_address_from_data(data) 171 | data = data[offset:] 172 | logger.info(f"send to {address}:{port}") 173 | logger.debug(data) 174 | self.sock.sendto(data,(address, port)) 175 | 176 | def recv(self, size): 177 | if self.protocol == 6: 178 | return self.sock.recv(size) 179 | elif self.protocol == 17: 180 | data, address = self.sock.recvfrom(size) 181 | logger.info(f"receive from {address[0]}:{address[1]}") 182 | logger.debug(b"\x00\x00\x00"+utils.build_socks5_address(address[0],address[1])+data) 183 | return b"\x00\x00\x00"+utils.build_socks5_address(address[0],address[1])+data 184 | 185 | 186 | def close(self): 187 | if self.protocol == 6: 188 | self.sock.close() 189 | elif self.protocol == 17: 190 | pass 191 | -------------------------------------------------------------------------------- /src/tls_fragment/utils.py: -------------------------------------------------------------------------------- 1 | import ipaddress 2 | import socket 3 | import struct 4 | 5 | 6 | def ip_to_binary_prefix(ip_or_network): 7 | try: 8 | network = ipaddress.ip_network(ip_or_network, strict=False) 9 | network_address = network.network_address 10 | prefix_length = network.prefixlen 11 | if isinstance(network_address, ipaddress.IPv4Address): 12 | binary_network = bin(int(network_address))[2:].zfill(32) 13 | elif isinstance(network_address, ipaddress.IPv6Address): 14 | binary_network = bin(int(network_address))[2:].zfill(128) 15 | binary_prefix = binary_network[:prefix_length] 16 | return binary_prefix 17 | except ValueError: 18 | try: 19 | ip = ipaddress.ip_address(ip_or_network) 20 | if isinstance(ip, ipaddress.IPv4Address): 21 | binary_ip = bin(int(ip))[2:].zfill(32) 22 | binary_prefix = binary_ip[:32] 23 | elif isinstance(ip, ipaddress.IPv6Address): 24 | binary_ip = bin(int(ip))[2:].zfill(128) 25 | binary_prefix = binary_ip[:128] 26 | return binary_prefix 27 | except ValueError: 28 | raise ValueError(f"输入的 {ip_or_network} 不是有效的 IP 地址或网络") 29 | 30 | 31 | def set_ttl(sock, ttl): 32 | if sock.family == socket.AF_INET6: 33 | sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_UNICAST_HOPS, ttl) 34 | else: 35 | sock.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, ttl) 36 | 37 | 38 | def check_ttl(ip, port, ttl): 39 | try: 40 | if ':' in ip: 41 | sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) 42 | else: 43 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 44 | set_ttl(sock, ttl) 45 | sock.settimeout(0.5) 46 | sock.connect((ip, port)) 47 | sock.send(b"0") 48 | sock.close() 49 | return True 50 | except Exception as e: 51 | from .log import logger 52 | logger = logger.getChild("utils") 53 | logger.warning(f'check_ttl error: {repr(e)}') 54 | return False 55 | finally: 56 | sock.close() 57 | 58 | 59 | def get_ttl(ip, port): 60 | from .log import logger 61 | logger = logger.getChild("utils") 62 | l = 1 63 | r = 128 64 | ans = -1 65 | while l <= r: 66 | mid = (l + r) // 2 67 | val = check_ttl(ip, port, mid) 68 | logger.debug("%d %d %d %d %d", l, r, mid, ans, val) 69 | if val: 70 | ans = mid 71 | r = mid - 1 72 | else: 73 | l = mid + 1 74 | 75 | logger.info("get_ttl %s %d %d", ip, port, ans) 76 | return ans 77 | 78 | 79 | def is_ip_address(s): 80 | try: 81 | ipaddress.ip_address(s) 82 | return True 83 | except ValueError: 84 | return False 85 | 86 | 87 | def extract_sni(data): 88 | """ 89 | extract sni 90 | data: the tls data. 91 | """ 92 | # 解析TLS记录 93 | content_type, _, _, length = struct.unpack(">BBBH", data[:5]) 94 | if content_type != 0x16: # 0x16表示TLS Handshake 95 | raise ValueError("Not a TLS Handshake message") 96 | handshake_data = data[5 : 5 + length] 97 | 98 | # 解析握手消息头 99 | handshake_type, tmp, length = struct.unpack(">BBH", handshake_data[:4]) 100 | length = tmp * 64 + length 101 | if handshake_type != 0x01: # 0x01表示Client Hello 102 | raise ValueError("Not a Client Hello message") 103 | client_hello_data = handshake_data[4 : 4 + length] 104 | 105 | # 解析Client Hello消息 106 | _, _, _, session_id_length = struct.unpack(">BB32sB", client_hello_data[:35]) 107 | cipher_suites_length = struct.unpack( 108 | ">H", client_hello_data[35 + session_id_length : 35 + session_id_length + 2] 109 | )[0] 110 | compression_methods_length = struct.unpack( 111 | ">B", 112 | client_hello_data[ 113 | 35 114 | + session_id_length 115 | + 2 116 | + cipher_suites_length : 35 117 | + session_id_length 118 | + 2 119 | + cipher_suites_length 120 | + 1 121 | ], 122 | )[0] 123 | 124 | # 定位扩展部分 125 | extensions_offset = ( 126 | 35 127 | + session_id_length 128 | + 2 129 | + cipher_suites_length 130 | + 1 131 | + compression_methods_length 132 | ) 133 | extensions_length = struct.unpack( 134 | ">H", client_hello_data[extensions_offset : extensions_offset + 2] 135 | )[0] 136 | extensions_data = client_hello_data[ 137 | extensions_offset + 2 : extensions_offset + 2 + extensions_length 138 | ] 139 | 140 | offset = 0 141 | while offset < extensions_length: 142 | extension_type, extension_length = struct.unpack( 143 | ">HH", extensions_data[offset : offset + 4] 144 | ) 145 | if extension_type == 0x0000: # SNI扩展的类型是0x0000 146 | sni_extension = extensions_data[offset + 4 : offset + 4 + extension_length] 147 | # 解析SNI扩展 148 | list_length = struct.unpack(">H", sni_extension[:2])[0] 149 | if list_length != 0: 150 | name_type, name_length = struct.unpack(">BH", sni_extension[2:5]) 151 | if name_type == 0: # 域名类型 152 | sni = sni_extension[5 : 5 + name_length] 153 | return sni 154 | offset += 4 + extension_length 155 | return None 156 | 157 | def parse_extensions(data): 158 | extensions = {} 159 | offset = 0 160 | try: 161 | while offset < len(data): 162 | if offset + 4 > len(data): 163 | break 164 | # 解析扩展类型 165 | ext_type = struct.unpack('>H', data[offset:offset + 2])[0] 166 | # 解析扩展长度 167 | ext_length = struct.unpack('>H', data[offset + 2:offset + 4])[0] 168 | if offset + 4 + ext_length > len(data): 169 | break 170 | # 解析扩展数据 171 | ext_data = data[offset + 4:offset + 4 + ext_length] 172 | extensions[ext_type] = ext_data 173 | offset += 4 + ext_length 174 | except struct.error as e: 175 | raise e 176 | return extensions 177 | 178 | 179 | def detect_tls_version_by_keyshare(server_hello): 180 | # 解析TLS记录层 181 | if len(server_hello) < 5: 182 | return 0 183 | content_type, _, _, record_length = struct.unpack('>BBBH', server_hello[:5]) 184 | if content_type != 0x16: # 0x16表示TLS Handshake 185 | return 0 186 | handshake_data = server_hello[5:5 + record_length] 187 | 188 | # 解析握手消息头 189 | if len(handshake_data) < 4: 190 | return 0 191 | handshake_type, _, handshake_length = struct.unpack('>BBH', handshake_data[:4]) 192 | if handshake_type != 0x02: # 0x02表示Server Hello 193 | return 0 194 | 195 | # 跳过前面固定长度的字段(消息类型、长度、版本、随机数) 196 | offset = 4 + 2 + 32 197 | # 解析会话 ID 长度 198 | session_id_length = struct.unpack('>B', handshake_data[offset:offset + 1])[0] 199 | offset += 1 + session_id_length 200 | # 跳过密码套件和压缩方法 201 | offset += 2 + 1 202 | # 扩展字段起始位置 203 | extensions_start = offset 204 | 205 | # 解析扩展字段的总长度 206 | if extensions_start + 2 > len(handshake_data): 207 | return 0 208 | extensions_length = struct.unpack('>H', handshake_data[extensions_start:extensions_start + 2])[0] 209 | # 检查扩展字段数据是否完整 210 | if extensions_start + 2 + extensions_length > len(handshake_data): 211 | return 0 212 | # 提取扩展字段的数据 213 | extensions_data = handshake_data[extensions_start + 2:extensions_start + 2 + extensions_length] 214 | # 解析扩展字段 215 | extensions = parse_extensions(extensions_data) 216 | 217 | # 定义key_share扩展类型 218 | key_share_ext_type = 0x0033 219 | # 检查是否存在key_share扩展 220 | try: 221 | has_key_share_ext = key_share_ext_type in extensions 222 | 223 | if has_key_share_ext: 224 | return 1 225 | return -1 226 | except: 227 | return 0 228 | 229 | def is_udp_dns_query(data): 230 | if len(data) < 12: 231 | return False 232 | flags = data[2:4] # 取出第3和第4字节 233 | qr = flags[0] >> 7 # 取出QR位 234 | return qr == 0 # QR位为0表示查询 235 | 236 | def fake_udp_dns_query(data): 237 | import dns.message 238 | import dns.rrset 239 | import dns.rdatatype 240 | 241 | try: 242 | # 解析DNS查询 243 | dns_query = dns.message.from_wire(query) 244 | except Exception as e: 245 | print(f"Failed to parse DNS query: {e}") 246 | return None # 返回None表示解析失败 247 | 248 | # 创建DNS响应 249 | response = dns.message.make_response(dns_query) 250 | 251 | # 检查查询类型 252 | for question in dns_query.question: 253 | if question.rdtype == dns.rdatatype.A: 254 | # A记录返回127.0.0.1 255 | a_record = dns.rrset.from_text(question.name, 3600, dns.rdatatype.A, "127.0.0.1") 256 | response.answer.append(a_record) 257 | elif question.rdtype == dns.rdatatype.AAAA: 258 | # AAAA记录返回::1 259 | aaaa_record = dns.rrset.from_text(question.name, 3600, dns.rdatatype.AAAA, "::1") 260 | response.answer.append(aaaa_record) 261 | else: 262 | # 其他记录返回未找到 263 | response.set_rcode(dns.rcode.NXDOMAIN) 264 | return response 265 | 266 | return response.to_wire() 267 | 268 | def parse_socks5_address(sock): 269 | """SOCKS5地址解析""" 270 | atyp=sock.recv(1)[0] 271 | if atyp == 0x01: # IPv4 272 | server_ip = socket.inet_ntop(socket.AF_INET, sock.recv(4)) 273 | return server_ip, int.from_bytes(sock.recv(2), "big") 274 | elif atyp == 0x03: # 域名 275 | domain_len = ord(sock.recv(1)) 276 | server_name = sock.recv(domain_len).decode() 277 | port = int.from_bytes(sock.recv(2), "big") 278 | return server_name, port 279 | elif atyp == 0x04: # IPv6 280 | server_ip = socket.inet_ntop(socket.AF_INET6, sock.recv(16)) 281 | return server_ip, int.from_bytes(sock.recv(2), "big") 282 | raise ValueError("Invalid address type") 283 | 284 | def parse_socks5_address_from_data(data): 285 | """SOCKS5 address parsing with error handling""" 286 | offset = 0 287 | atyp = data[offset:offset+1][0] 288 | offset += 1 289 | 290 | if atyp == 0x01: # IPv4 291 | if len(data) < offset + 6: # 4 bytes for IP + 2 bytes for port 292 | raise ValueError("Data too short for IPv4 address") 293 | server_ip = socket.inet_ntop(socket.AF_INET, data[offset:offset + 4]) 294 | offset += 4 295 | port = int.from_bytes(data[offset:offset + 2], "big") 296 | offset += 2 297 | return server_ip, port, offset 298 | elif atyp == 0x03: # Domain name 299 | if len(data) < offset + 1: # At least 1 byte for domain length 300 | raise ValueError("Data too short for domain length") 301 | domain_len = data[offset] 302 | offset += 1 303 | if len(data) < offset + domain_len + 2: # domain + 2 bytes for port 304 | raise ValueError("Data too short for domain address") 305 | server_name = data[offset:offset + domain_len].decode() 306 | offset += domain_len 307 | port = int.from_bytes(data[offset:offset + 2], "big") 308 | offset += 2 309 | return server_name, port, offset 310 | elif atyp == 0x04: # IPv6 311 | if len(data) < offset + 18: # 16 bytes for IP + 2 bytes for port 312 | raise ValueError("Data too short for IPv6 address") 313 | server_ip = socket.inet_ntop(socket.AF_INET6, data[offset:offset + 16]) 314 | offset += 16 315 | port = int.from_bytes(data[offset:offset + 2], "big") 316 | offset += 2 317 | return server_ip, port, offset 318 | raise ValueError("Invalid address type") 319 | 320 | def build_socks5_address(ip, port): 321 | """根据 IP 和端口构造 SOCKS5 地址""" 322 | # 解析 IP 地址 323 | try: 324 | packed_ip = socket.inet_pton(socket.AF_INET, ip) # IPv4 325 | atyp = 0x01 # 地址类型为 IPv4 326 | except socket.error: 327 | try: 328 | packed_ip = socket.inet_pton(socket.AF_INET6, ip) # IPv6 329 | atyp = 0x04 # 地址类型为 IPv6 330 | except socket.error: 331 | # 如果都无法解析,抛出异常 332 | raise ValueError("Invalid IP address format") 333 | 334 | # 构造 SOCKS5 地址 335 | if atyp == 0x01: # IPv4 336 | return bytes([atyp]) + packed_ip + port.to_bytes(2, 'big') 337 | elif atyp == 0x04: # IPv6 338 | return bytes([atyp]) + packed_ip + port.to_bytes(2, 'big') 339 | -------------------------------------------------------------------------------- /tlsp.sh: -------------------------------------------------------------------------------- 1 | cd tlsp 2 | python server_threading.py 3 | 4 | -------------------------------------------------------------------------------- /tools/BUILD_WINDOWS.bat: -------------------------------------------------------------------------------- 1 | cd .. 2 | pip install -r requirements.txt 3 | pyinstaller -F run.py -n proxy.exe --noconsole 4 | copy /Y config.json dist\config.json 5 | pause -------------------------------------------------------------------------------- /tools/UZA_MSEDGE.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | taskkill /f /t /im msedge.exe 3 | start "" "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --ignore-certificate-errors -------------------------------------------------------------------------------- /tools/build/README.md: -------------------------------------------------------------------------------- 1 | The Scripts in this directory are used by Github Actions to build your packages. 2 | These scripts can also be used to build your local builds. 3 | 4 | Here is how to use these scripts to build your local packages using these scripts. 5 | 6 | 7 | - Build for linux 8 | 9 | - To build on your linux distro:: 10 | 11 | /bin/bash tools/build/build_linux.sh 12 | 13 | - To build using docker:: 14 | 15 | - Install Docker[https://docs.docker.com/engine/install/]. 16 | 17 | Run the following commands form this applications root dir. 18 | 19 | docker build . -t local -f tools/build/build_linux_amd64.dockerfile 20 | docker run -i -v $PWD:/srv -w/srv local /bin/bash ./tools/build/build_debian_8_docker.sh 21 | 22 | 23 | - Build for Windows 24 | - WIP 25 | - Build for android 26 | - WIP 27 | - Build for ios 28 | - WIP 29 | - Build for rpi 30 | -WIP -------------------------------------------------------------------------------- /tools/build/build_android.dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:11 2 | 3 | RUN : \ 4 | && apt-get update \ 5 | \ 6 | # Buildozer \ 7 | && apt-get install -y --no-install-recommends autoconf automake build-essential \ 8 | ccache cmake openjdk-17-jdk gettext git libffi-dev libltdl-dev libssl-dev \ 9 | libtool patch pkg-config unzip zip zlib1g-dev \ 10 | \ 11 | # Python 3.8 \ 12 | && apt-get -yq install wget build-essential libreadline-dev \ 13 | libncursesw5-dev libssl-dev libsqlite3-dev tk-dev \ 14 | libgdbm-dev libc6-dev libbz2-dev libffi-dev zlib1g-dev \ 15 | && ( \ 16 | cd /tmp \ 17 | && wget https://www.python.org/ftp/python/3.8.12/Python-3.8.12.tgz \ 18 | -O Python-3.8.12.tgz \ 19 | && tar xzf Python-3.8.12.tgz \ 20 | && rm Python-3.8.12.tgz \ 21 | && ( \ 22 | cd Python-3.8.12 \ 23 | && ./configure --prefix=/usr --enable-optimizations --enable-shared \ 24 | && make install -j $(nproc) \ 25 | && ldconfig \ 26 | ) \ 27 | && rm -rf Python-3.8.12 \ 28 | ) \ 29 | \ 30 | # Cleanup \ 31 | && apt-get clean \ 32 | && rm -rf /var/lib/apt/lists/* 33 | 34 | RUN echo "#################################################" 35 | RUN echo "Copy the GitHub repo to the Docker container" 36 | RUN echo "COPY . ${env_workspace_directory}" 37 | COPY . ${env_workspace_directory} 38 | -------------------------------------------------------------------------------- /tools/build/build_android.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -eux pipefail 3 | 4 | ROOT=$(realpath $(dirname "$0")/../..) 5 | 6 | [[ -d "$ROOT"/build/android ]] || mkdir -p "$ROOT"/build/android 7 | 8 | # chown -R root build/android 9 | 10 | ( 11 | cd "$ROOT"/build/android 12 | export HOME="$PWD" 13 | # export GRADLE_USER_HOME="$PWD"/.gradle 14 | export ANDROID_USER_HOME="$PWD"/.android 15 | 16 | # python3 -m venv venv 17 | # source venv/bin/activate 18 | 19 | pip install --upgrade pip 20 | # python3 -m pip install --force-reinstall -r "$ROOT"/tools/build/requirements.txt 21 | pip install --force-reinstall -r "$ROOT"/tools/build/requirements_build_android.txt 22 | 23 | # Remove APK if exists 24 | rm -rf bin 25 | 26 | # Build 27 | ( 28 | cp "$ROOT"/tools/build/buildozer.spec . 29 | yes| buildozer android debug 30 | ) 31 | ) 32 | 33 | # change permissions to allow cache copying 34 | # find build/android -type d -exec chmod 755 {} \; 35 | # find build/android -type f -exec chmod 644 {} \; 36 | 37 | # sanity check 38 | PACKAGE="$ROOT"/build/android/bin/ 39 | 40 | if ls "$PACKAGE"; then 41 | echo Successfully built. 42 | else 43 | echo Error: "$PACKAGE" doesn\'t exist >&2; exit 1; 44 | fi 45 | -------------------------------------------------------------------------------- /tools/build/build_debian_8_docker.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euxo pipefail 3 | 4 | # Debian 8 has outdated certificates 5 | export GIT_SSL_NO_VERIFY=1 6 | 7 | # Old git fails with "unable to look up current user in the passwd file: no such user" 8 | export GIT_COMMITTER_NAME="Jenkins" 9 | export GIT_COMMITTER_EMAIL="ci@test.com" 10 | 11 | # Build 12 | xvfb-run -s "-screen 0 1280x1024x24" /bin/bash tools/build/build_linux.sh 13 | 14 | # Rename executable 15 | mv build/linux/dist/helloworld.run \ 16 | build/linux/dist/helloworld-linux-x86_64.run 17 | -------------------------------------------------------------------------------- /tools/build/build_ios.py: -------------------------------------------------------------------------------- 1 | '''Build for Android 2 | ''' -------------------------------------------------------------------------------- /tools/build/build_linux.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euxo pipefail 3 | 4 | ROOT=$(realpath $(dirname "$0")/../..) 5 | 6 | [[ -d "$ROOT"/build/linux ]] \ 7 | || mkdir -p "$ROOT"/build/linux 8 | 9 | ( 10 | cd "$ROOT"/build/linux 11 | export HOME="$PWD" 12 | 13 | python3 -m venv venv 14 | source venv/bin/activate 15 | 16 | python3 -m pip install --upgrade pip 17 | python3 -m pip install -r "$ROOT"/tools/build/requirements.txt \ 18 | -r "$ROOT"/tools/build/requirements_build_linux.txt 19 | 20 | # remove PyInstaller's dist directory if exists 21 | rm -rf dist 22 | 23 | python3 -m PyInstaller --clean "$ROOT"/tools/build/helloworld.linux.onefile.spec 24 | ) 25 | 26 | # sanity check 27 | PACKAGE="$ROOT"/build/linux/dist/helloworld.run 28 | [[ -f "$PACKAGE" ]] \ 29 | || { echo Error: "$PACKAGE" doesn\'t exist >&2; exit 1; } 30 | 31 | echo Successfully built "$PACKAGE" 32 | -------------------------------------------------------------------------------- /tools/build/build_linux_amd64.dockerfile: -------------------------------------------------------------------------------- 1 | FROM debian:8 2 | 3 | RUN : \ 4 | && echo "deb http://archive.debian.org/debian jessie main" > /etc/apt/sources.list \ 5 | && echo "deb http://archive.debian.org/debian-security jessie/updates main" >> /etc/apt/sources.list \ 6 | # Add jessie-backports, needed for newer libssl for python \ 7 | && echo "deb http://archive.debian.org/debian jessie-backports main" >> /etc/apt/sources.list \ 8 | && echo "Acquire::Check-Valid-Until \"false\";" > /etc/apt/apt.conf \ 9 | \ 10 | # Update \ 11 | && apt-get update \ 12 | \ 13 | # Python 3.8 \ 14 | && apt-get -yq install --force-yes wget build-essential libreadline-gplv2-dev \ 15 | libncursesw5-dev libssl1.0.0=1.0.2\* libssl-dev=1.0.2\* \ 16 | libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev \ 17 | libffi-dev zlib1g-dev \ 18 | && ( \ 19 | cd /tmp \ 20 | && wget --no-check-certificate https://www.python.org/ftp/python/3.8.12/Python-3.8.12.tgz \ 21 | -O Python-3.8.12.tgz \ 22 | && tar xzf Python-3.8.12.tgz \ 23 | && rm Python-3.8.12.tgz \ 24 | && ( \ 25 | cd Python-3.8.12 \ 26 | && ./configure --prefix=/usr --enable-optimizations --enable-shared \ 27 | && make install -j $(nproc) \ 28 | && ldconfig \ 29 | ) \ 30 | && rm -rf Python-3.8.12 \ 31 | ) \ 32 | \ 33 | # Other stuff \ 34 | && apt-get -yq --force-yes install \ 35 | git \ 36 | # For headless rendering \ 37 | xvfb \ 38 | # For Kivy \ 39 | libmtdev1 \ 40 | \ 41 | # Hacking libgl: replacing libgl1-mesa-glx -> libgl1-mesa-swx11 \ 42 | && apt-get -yq --force-yes install mesa-common-dev \ 43 | && dpkg -r --force-depends libgl1-mesa-glx libgl1-mesa-dev \ 44 | && ( \ 45 | cd /tmp \ 46 | && apt-get download libgl1-mesa-swx11 libgl1-mesa-swx11-dev libosmesa6 \ 47 | && dpkg -i *.deb \ 48 | ) \ 49 | \ 50 | # Cleanup \ 51 | && apt-get clean \ 52 | && rm -rf /var/lib/apt/lists/* 53 | -------------------------------------------------------------------------------- /tools/build/build_macosx.py: -------------------------------------------------------------------------------- 1 | '''Build for osx 2 | ''' 3 | 4 | import os 5 | import sys 6 | import shutil 7 | 8 | script_dir = os.path.dirname(__file__) 9 | root_app_dir = os.path.abspath(script_dir + '/../..') 10 | os.chdir(root_app_dir) 11 | 12 | BUILD_DIR = root_app_dir + '/build' 13 | 14 | try: 15 | os.makedirs(BUILD_DIR) 16 | except FileExistsError: 17 | pass 18 | 19 | try: 20 | os.remove(f'{BUILD_DIR}/buildozer.spec') 21 | except (FileExistsError, FileNotFoundError): 22 | pass 23 | 24 | shutil.copy('tools/build/buildozer.spec', f'{BUILD_DIR}/buildozer.spec') 25 | shutil.copy('tools/build/requirements.txt', f'{BUILD_DIR}/') 26 | shutil.copy('tools/build/requirements_build_macosx.txt', f'{BUILD_DIR}/') 27 | os.chdir(BUILD_DIR) 28 | 29 | commands = [ 30 | f'{sys.executable} -m venv ./venv', 31 | f'./venv/bin/python -m pip install docopts', 32 | f'./venv/bin/python -m pip install -r requirements_build_macosx.txt', 33 | './venv/bin/buildozer -v osx debug'] 34 | 35 | import subprocess 36 | for cmd in commands: 37 | print(f'cmd: {cmd}') 38 | subprocess.run(cmd.split(' ')) -------------------------------------------------------------------------------- /tools/build/build_windows.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import shutil 4 | 5 | script_dir = os.path.dirname(__file__) 6 | root_app_dir = os.path.abspath(script_dir + '/../..') 7 | os.chdir(root_app_dir) 8 | 9 | BUILD_DIR = root_app_dir + '/build/windows' 10 | 11 | try: 12 | os.makedirs(BUILD_DIR) 13 | except FileExistsError: 14 | pass 15 | 16 | commands = f''' 17 | python -m venv venv 18 | venv\\Scripts\\activate.bat 19 | 20 | python -m pip install --upgrade pip 21 | python -m pip install -r {script_dir}/requirements.txt -r {script_dir}/requirements_build_windows.txt 22 | 23 | echo Remove PyInstaller's dist directory if exists. 24 | rm -rf dist 25 | 26 | python -m PyInstaller --clean {script_dir}/helloworld.windows.onefile.spec 27 | ''' 28 | 29 | import subprocess 30 | for cmd in commands.split('\n'): 31 | if cmd in ('', '\n'): 32 | continue 33 | print(f'running cmd : {cmd}') 34 | subprocess.run(cmd.split(' ')) 35 | 36 | 37 | 38 | # sanity check 39 | package = f'{root_app_dir}/dist/helloworld.exe' 40 | 41 | 42 | if os.path.exists(package): 43 | print(f"Successfully built {package}") 44 | #include_arch(arch.arch) 45 | #include_version(version.version) 46 | else: 47 | subprocess.run(['tree']) 48 | raise('Failed to build package...') -------------------------------------------------------------------------------- /tools/build/buildozer.spec: -------------------------------------------------------------------------------- 1 | [app] 2 | # (str) Title of your application 3 | title = TLSFragment 4 | 5 | # (str) Package name 6 | package.name = tlsfragment 7 | 8 | # (str) Package domain 9 | package.domain = org.maoist2009 10 | 11 | # (str) Source code where the main.py live 12 | source.dir = ../.. 13 | 14 | # (list) Source files to include (let empty to include all the files) 15 | source.include_exts = py,png,jpg,kv,atlas,json 16 | 17 | # (list) List of inclusions using pattern matching 18 | # source.include_patterns = src,config.json,main.py 19 | 20 | # (list) Source files to exclude (let empty to not exclude anything) 21 | #source.exclude_exts = spec 22 | 23 | # (list) List of directory to exclude (let empty to not exclude anything) 24 | source.exclude_dirs = test, tools, docs, browser 25 | 26 | # (list) List of exclusions using pattern matching 27 | # Do not prefix with './' 28 | #source.exclude_patterns = license,images/*/*.jpg 29 | 30 | # (str) Application versioning (method 1) 31 | version = 0.1 32 | 33 | # (str) Application versioning (method 2) 34 | # version.regex = __version__ = ['"](.*)['"] 35 | # version.filename = %(source.dir)s/main.py 36 | 37 | # (list) Application requirements 38 | # comma separated e.g. requirements = sqlite3,kivy 39 | requirements = python3,kivy,ahocorasick-python,requests,dnspython,pyjnius,https://github.com/kvdroid/Kvdroid/archive/refs/heads/master.zip 40 | 41 | # (str) Custom source folders for requirements 42 | # Sets custom source for any requirements with recipes 43 | # requirements.source.kivy = ../../kivy 44 | 45 | # (str) Presplash of the application 46 | #presplash.filename = %(source.dir)s/data/presplash.png 47 | 48 | # (str) Icon of the application 49 | icon.filename = %(source.dir)s/small_icon.png 50 | 51 | # (list) Supported orientations 52 | # Valid options are: landscape, portrait, portrait-reverse or landscape-reverse 53 | orientation = portrait 54 | 55 | # (list) List of service to declare 56 | services = Proxyservice:service.py:foreground:sticky 57 | 58 | # 59 | # OSX Specific 60 | # 61 | 62 | # 63 | # author = © Copyright Info 64 | 65 | # change the major version of python used by the app 66 | osx.python_version = 3 67 | 68 | # Kivy version to use 69 | osx.kivy_version = 2.2.0 70 | 71 | # 72 | # Android specific 73 | # 74 | 75 | # (bool) Indicate if the application should be fullscreen or not 76 | fullscreen = 0 77 | 78 | # (string) Presplash background color (for android toolchain) 79 | # Supported formats are: #RRGGBB #AARRGGBB or one of the following names: 80 | # red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray, 81 | # darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy, 82 | # olive, purple, silver, teal. 83 | android.presplash_color = #39C5BB 84 | 85 | # (string) Presplash animation using Lottie format. 86 | # see https://lottiefiles.com/ for examples and https://airbnb.design/lottie/ 87 | # for general documentation. 88 | # Lottie files can be created using various tools, like Adobe After Effect or Synfig. 89 | #android.presplash_lottie = "path/to/lottie/file.json" 90 | 91 | # (str) Adaptive icon of the application (used if Android API level is 26+ at runtime) 92 | #icon.adaptive_foreground.filename = %(source.dir)s/data/icon_fg.png 93 | #icon.adaptive_background.filename = %(source.dir)s/data/icon_bg.png 94 | 95 | # (list) Permissions 96 | # (See https://python-for-android.readthedocs.io/en/latest/buildoptions/#build-options-1 for all the supported syntaxes and properties) 97 | android.permissions = INTERNET, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, FOREGROUND_SERVICE, SYSTEM_ALERT_WINDOW, REQUEST_IGNORE_BATTERY_OPTIMIZATIONS 98 | 99 | # (list) features (adds uses-feature -tags to manifest) 100 | #android.features = android.hardware.usb.host 101 | 102 | # (int) Target Android API, should be as high as possible. 103 | #android.api = 31 104 | 105 | # (int) Minimum API your APK / AAB will support. 106 | #android.minapi = 21 107 | 108 | # (int) Android SDK version to use 109 | #android.sdk = 20 110 | 111 | # (str) Android NDK version to use 112 | android.ndk = 25b 113 | 114 | # (int) Android NDK API to use. This is the minimum API your app will support, it should usually match android.minapi. 115 | #android.ndk_api = 21 116 | 117 | # (str) Android NDK directory (if empty, it will be automatically downloaded.) 118 | #android.ndk_path = 119 | 120 | # (str) Android SDK directory (if empty, it will be automatically downloaded.) 121 | #android.sdk_path = 122 | 123 | # (str) ANT directory (if empty, it will be automatically downloaded.) 124 | #android.ant_path = 125 | 126 | # (bool) If True, then skip trying to update the Android sdk 127 | # This can be useful to avoid excess Internet downloads or save time 128 | # when an update is due and you just want to test/build your package 129 | # android.skip_update = False 130 | 131 | # (bool) If True, then automatically accept SDK license 132 | # agreements. This is intended for automation only. If set to False, 133 | # the default, you will be shown the license when first running 134 | # buildozer. 135 | # android.accept_sdk_license = False 136 | 137 | # (str) Android entry point, default is ok for Kivy-based app 138 | #android.entrypoint = org.kivy.android.PythonActivity 139 | 140 | # (str) Full name including package path of the Java class that implements Android Activity 141 | # use that parameter together with android.entrypoint to set custom Java class instead of PythonActivity 142 | #android.activity_class_name = org.kivy.android.PythonActivity 143 | 144 | # (str) Extra xml to write directly inside the element of AndroidManifest.xml 145 | # use that parameter to provide a filename from where to load your custom XML code 146 | #android.extra_manifest_xml = ./src/android/extra_manifest.xml 147 | 148 | # (str) Extra xml to write directly inside the tag of AndroidManifest.xml 149 | # use that parameter to provide a filename from where to load your custom XML arguments: 150 | #android.extra_manifest_application_arguments = ./src/android/extra_manifest_application_arguments.xml 151 | 152 | # (str) Full name including package path of the Java class that implements Python Service 153 | # use that parameter to set custom Java class which extends PythonService 154 | #android.service_class_name = org.kivy.android.PythonService 155 | 156 | # (str) Android app theme, default is ok for Kivy-based app 157 | # android.apptheme = "@android:style/Theme.NoTitleBar" 158 | 159 | # (list) Pattern to whitelist for the whole project 160 | #android.whitelist = 161 | 162 | # (bool) If True, your application will be listed as a home app (launcher app) 163 | # android.home_app = False 164 | 165 | # (str) Path to a custom whitelist file 166 | #android.whitelist_src = 167 | 168 | # (str) Path to a custom blacklist file 169 | #android.blacklist_src = 170 | 171 | # (list) List of Java .jar files to add to the libs so that pyjnius can access 172 | # their classes. Don't add jars that you do not need, since extra jars can slow 173 | # down the build process. Allows wildcards matching, for example: 174 | # OUYA-ODK/libs/*.jar 175 | #android.add_jars = foo.jar,bar.jar,path/to/more/*.jar 176 | 177 | # (list) List of Java files to add to the android project (can be java or a 178 | # directory containing the files) 179 | #android.add_src = 180 | 181 | # (list) Android AAR archives to add 182 | #android.add_aars = 183 | 184 | # (list) Put these files or directories in the apk assets directory. 185 | # Either form may be used, and assets need not be in 'source.include_exts'. 186 | # 1) android.add_assets = source_asset_relative_path 187 | # 2) android.add_assets = source_asset_path:destination_asset_relative_path 188 | #android.add_assets = 189 | 190 | # (list) Put these files or directories in the apk res directory. 191 | # The option may be used in three ways, the value may contain one or zero ':' 192 | # Some examples: 193 | # 1) A file to add to resources, legal resource names contain ['a-z','0-9','_'] 194 | # android.add_resources = my_icons/all-inclusive.png:drawable/all_inclusive.png 195 | # 2) A directory, here 'legal_icons' must contain resources of one kind 196 | # android.add_resources = legal_icons:drawable 197 | # 3) A directory, here 'legal_resources' must contain one or more directories, 198 | # each of a resource kind: drawable, xml, etc... 199 | # android.add_resources = legal_resources 200 | #android.add_resources = 201 | 202 | # (list) Gradle dependencies to add 203 | #android.gradle_dependencies = 204 | 205 | # (bool) Enable AndroidX support. Enable when 'android.gradle_dependencies' 206 | # contains an 'androidx' package, or any package from Kotlin source. 207 | # android.enable_androidx requires android.api >= 28 208 | #android.enable_androidx = True 209 | 210 | # (list) add java compile options 211 | # this can for example be necessary when importing certain java libraries using the 'android.gradle_dependencies' option 212 | # see https://developer.android.com/studio/write/java8-support for further information 213 | # android.add_compile_options = "sourceCompatibility = 1.8", "targetCompatibility = 1.8" 214 | 215 | # (list) Gradle repositories to add {can be necessary for some android.gradle_dependencies} 216 | # please enclose in double quotes 217 | # e.g. android.gradle_repositories = "maven { url 'https://kotlin.bintray.com/ktor' }" 218 | #android.add_gradle_repositories = 219 | 220 | # (list) packaging options to add 221 | # see https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.PackagingOptions.html 222 | # can be necessary to solve conflicts in gradle_dependencies 223 | # please enclose in double quotes 224 | # e.g. android.add_packaging_options = "exclude 'META-INF/common.kotlin_module'", "exclude 'META-INF/*.kotlin_module'" 225 | #android.add_packaging_options = 226 | 227 | # (list) Java classes to add as activities to the manifest. 228 | #android.add_activities = com.example.ExampleActivity 229 | 230 | # (str) OUYA Console category. Should be one of GAME or APP 231 | # If you leave this blank, OUYA support will not be enabled 232 | #android.ouya.category = GAME 233 | 234 | # (str) Filename of OUYA Console icon. It must be a 732x412 png image. 235 | #android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png 236 | 237 | # (str) XML file to include as an intent filters in tag 238 | #android.manifest.intent_filters = 239 | 240 | # (list) Copy these files to src/main/res/xml/ (used for example with intent-filters) 241 | #android.res_xml = PATH_TO_FILE, 242 | 243 | # (str) launchMode to set for the main activity 244 | #android.manifest.launch_mode = standard 245 | 246 | # (str) screenOrientation to set for the main activity. 247 | # Valid values can be found at https://developer.android.com/guide/topics/manifest/activity-element 248 | #android.manifest.orientation = fullSensor 249 | 250 | # (list) Android additional libraries to copy into libs/armeabi 251 | #android.add_libs_armeabi = libs/android/*.so 252 | #android.add_libs_armeabi_v7a = libs/android-v7/*.so 253 | #android.add_libs_arm64_v8a = libs/android-v8/*.so 254 | #android.add_libs_x86 = libs/android-x86/*.so 255 | #android.add_libs_mips = libs/android-mips/*.so 256 | 257 | # (bool) Indicate whether the screen should stay on 258 | # Don't forget to add the WAKE_LOCK permission if you set this to True 259 | #android.wakelock = False 260 | 261 | # (list) Android application meta-data to set (key=value format) 262 | #android.meta_data = 263 | 264 | # (list) Android library project to add (will be added in the 265 | # project.properties automatically.) 266 | #android.library_references = 267 | 268 | # (list) Android shared libraries which will be added to AndroidManifest.xml using tag 269 | #android.uses_library = 270 | 271 | # (str) Android logcat filters to use 272 | #android.logcat_filters = *:S python:D 273 | 274 | # (bool) Android logcat only display log for activity's pid 275 | #android.logcat_pid_only = False 276 | 277 | # (str) Android additional adb arguments 278 | #android.adb_args = -H host.docker.internal 279 | 280 | # (bool) Copy library instead of making a libpymodules.so 281 | #android.copy_libs = 1 282 | 283 | # (list) The Android archs to build for, choices: armeabi-v7a, arm64-v8a, x86, x86_64 284 | # In past, was `android.arch` as we weren't supporting builds for multiple archs at the same time. 285 | android.archs = arm64-v8a, armeabi-v7a 286 | 287 | # (int) overrides automatic versionCode computation (used in build.gradle) 288 | # this is not the same as app version and should only be edited if you know what you're doing 289 | # android.numeric_version = 1 290 | 291 | # (bool) enables Android auto backup feature (Android API >=23) 292 | android.allow_backup = True 293 | 294 | # (str) XML file for custom backup rules (see official auto backup documentation) 295 | # android.backup_rules = 296 | 297 | # (str) If you need to insert variables into your AndroidManifest.xml file, 298 | # you can do so with the manifestPlaceholders property. 299 | # This property takes a map of key-value pairs. (via a string) 300 | # Usage example : android.manifest_placeholders = [myCustomUrl:\"org.kivy.customurl\"] 301 | # android.manifest_placeholders = [:] 302 | 303 | # (bool) Skip byte compile for .py files 304 | # android.no-byte-compile-python = False 305 | 306 | # (str) The format used to package the app for release mode (aab or apk or aar). 307 | # android.release_artifact = aab 308 | 309 | # (str) The format used to package the app for debug mode (apk or aar). 310 | # android.debug_artifact = apk 311 | 312 | # 313 | # Python for android (p4a) specific 314 | # 315 | 316 | # (str) python-for-android URL to use for checkout 317 | #p4a.url = 318 | 319 | # (str) python-for-android fork to use in case if p4a.url is not specified, defaults to upstream (kivy) 320 | #p4a.fork = kivy 321 | 322 | # (str) python-for-android branch to use, defaults to master 323 | #p4a.branch = master 324 | 325 | # (str) python-for-android specific commit to use, defaults to HEAD, must be within p4a.branch 326 | #p4a.commit = HEAD 327 | 328 | # (str) python-for-android git clone directory (if empty, it will be automatically cloned from github) 329 | #p4a.source_dir = 330 | 331 | # (str) The directory in which python-for-android should look for your own build recipes (if any) 332 | #p4a.local_recipes = 333 | 334 | # (str) Filename to the hook for p4a 335 | #p4a.hook = 336 | 337 | # (str) Bootstrap to use for android builds 338 | # p4a.bootstrap = sdl2 339 | 340 | # (int) port number to specify an explicit --port= p4a argument (eg for bootstrap flask) 341 | #p4a.port = 342 | 343 | # Control passing the --use-setup-py vs --ignore-setup-py to p4a 344 | # "in the future" --use-setup-py is going to be the default behaviour in p4a, right now it is not 345 | # Setting this to false will pass --ignore-setup-py, true will pass --use-setup-py 346 | # NOTE: this is general setuptools integration, having pyproject.toml is enough, no need to generate 347 | # setup.py if you're using Poetry, but you need to add "toml" to source.include_exts. 348 | #p4a.setup_py = false 349 | 350 | # (str) extra command line arguments to pass when invoking pythonforandroid.toolchain 351 | #p4a.extra_args = 352 | 353 | 354 | 355 | # 356 | # iOS specific 357 | # 358 | 359 | # (str) Path to a custom kivy-ios folder 360 | #ios.kivy_ios_dir = ../kivy-ios 361 | # Alternately, specify the URL and branch of a git checkout: 362 | ios.kivy_ios_url = https://github.com/kivy/kivy-ios 363 | ios.kivy_ios_branch = master 364 | 365 | # Another platform dependency: ios-deploy 366 | # Uncomment to use a custom checkout 367 | #ios.ios_deploy_dir = ../ios_deploy 368 | # Or specify URL and branch 369 | ios.ios_deploy_url = https://github.com/phonegap/ios-deploy 370 | ios.ios_deploy_branch = 1.12.2 371 | 372 | # (bool) Whether or not to sign the code 373 | ios.codesign.allowed = false 374 | 375 | # (str) Name of the certificate to use for signing the debug version 376 | # Get a list of available identities: buildozer ios list_identities 377 | #ios.codesign.debug = "iPhone Developer: ()" 378 | 379 | # (str) The development team to use for signing the debug version 380 | #ios.codesign.development_team.debug = 381 | 382 | # (str) Name of the certificate to use for signing the release version 383 | #ios.codesign.release = %(ios.codesign.debug)s 384 | 385 | # (str) The development team to use for signing the release version 386 | #ios.codesign.development_team.release = 387 | 388 | # (str) URL pointing to .ipa file to be installed 389 | # This option should be defined along with `display_image_url` and `full_size_image_url` options. 390 | #ios.manifest.app_url = 391 | 392 | # (str) URL pointing to an icon (57x57px) to be displayed during download 393 | # This option should be defined along with `app_url` and `full_size_image_url` options. 394 | #ios.manifest.display_image_url = 395 | 396 | # (str) URL pointing to a large icon (512x512px) to be used by iTunes 397 | # This option should be defined along with `app_url` and `display_image_url` options. 398 | #ios.manifest.full_size_image_url = 399 | 400 | 401 | [buildozer] 402 | 403 | # (int) Log level (0 = error only, 1 = info, 2 = debug (with command output)) 404 | log_level = 2 405 | 406 | # (int) Display warning if buildozer is run as root (0 = False, 1 = True) 407 | warn_on_root = 1 408 | 409 | # (str) Path to build artifact storage, absolute or relative to spec file 410 | # build_dir = ./.buildozer 411 | 412 | # (str) Path to build output (i.e. .apk, .aab, .ipa) storage 413 | # bin_dir = ./bin 414 | 415 | # ----------------------------------------------------------------------------- 416 | # List as sections 417 | # 418 | # You can define all the "list" as [section:key]. 419 | # Each line will be considered as a option to the list. 420 | # Let's take [app] / source.exclude_patterns. 421 | # Instead of doing: 422 | # 423 | #[app] 424 | #source.exclude_patterns = license,data/audio/*.wav,data/images/original/* 425 | # 426 | # This can be translated into: 427 | # 428 | #[app:source.exclude_patterns] 429 | #license 430 | #data/audio/*.wav 431 | #data/images/original/* 432 | # 433 | 434 | # ----------------------------------------------------------------------------- 435 | # Profiles 436 | # 437 | # You can extend section / key with a profile 438 | # For example, you want to deploy a demo version of your application without 439 | # HD content. You could first change the title to add "(demo)" in the name 440 | # and extend the excluded directories to remove the HD content. 441 | # 442 | #[app@demo] 443 | #title = My Application (demo) 444 | # 445 | #[app:source.exclude_patterns@demo] 446 | #images/hd/* 447 | # 448 | # Then, invoke the command line with the "demo" profile: 449 | # 450 | #buildozer --profile demo android debug 451 | -------------------------------------------------------------------------------- /tools/build/helloworld.linux.onefile.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python ; coding: utf-8 -*- 2 | 3 | block_cipher = None 4 | 5 | a = Analysis(['../../helloworld/main.py'], 6 | pathex=['.'], 7 | binaries=[], 8 | datas=[], 9 | hiddenimports=[], 10 | hookspath=[], 11 | runtime_hooks=[], 12 | excludes=[], 13 | win_no_prefer_redirects=False, 14 | win_private_assemblies=False, 15 | cipher=block_cipher, 16 | noarchive=False) 17 | 18 | # Remove libstdc++, as it might not be compatible with the target system 19 | a.binaries = [(name, path, type) for (name, path, type) in a.binaries 20 | if not name.startswith("libstdc++.so")] 21 | 22 | pyz = PYZ(a.pure, a.zipped_data, 23 | cipher=block_cipher) 24 | 25 | exe = EXE(pyz, 26 | Tree('helloworld' if os.path.exists('helloworld') else '../../helloworld'), 27 | a.scripts, 28 | a.binaries, 29 | a.zipfiles, 30 | a.datas, 31 | [], 32 | name='helloworld.run', 33 | debug=False, 34 | bootloader_ignore_signals=False, 35 | strip=False, 36 | upx=True, 37 | upx_exclude=[], 38 | runtime_tmpdir=None, 39 | console=False, 40 | disable_windowed_traceback=False, 41 | target_arch=None, 42 | codesign_identity=None, 43 | entitlements_file=None) 44 | -------------------------------------------------------------------------------- /tools/build/helloworld.windows.onefile.spec: -------------------------------------------------------------------------------- 1 | # -*- mode: python ; coding: utf-8 -*- 2 | 3 | from kivy_deps import sdl2, glew 4 | 5 | block_cipher = None 6 | 7 | a = Analysis(['..\\..\\helloworld\\main.py'], 8 | pathex=['.'], 9 | binaries=[], 10 | datas=[], 11 | hiddenimports=[], 12 | hookspath=[], 13 | runtime_hooks=[], 14 | excludes=[], 15 | win_no_prefer_redirects=False, 16 | win_private_assemblies=False, 17 | cipher=block_cipher, 18 | noarchive=False) 19 | 20 | pyz = PYZ(a.pure, a.zipped_data, 21 | cipher=block_cipher) 22 | 23 | exe = EXE(pyz, 24 | Tree('helloworld' if os.path.exists('helloworld') else '..\\..\\helloworld'), 25 | a.scripts, 26 | a.binaries, 27 | a.zipfiles, 28 | a.datas, 29 | *[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)], 30 | [], 31 | name='helloworld', 32 | debug=False, 33 | bootloader_ignore_signals=False, 34 | strip=False, 35 | upx=True, 36 | upx_exclude=[], 37 | runtime_tmpdir=None, 38 | # icon='..\\..\\helloworld\\data\\icon.ico', 39 | console=False) 40 | -------------------------------------------------------------------------------- /tools/build/requirements.txt: -------------------------------------------------------------------------------- 1 | kivy==2.2.0 2 | ahocorasick-python==0.0.9 3 | requests==2.32.3 4 | dnspython==2.3.0 -------------------------------------------------------------------------------- /tools/build/requirements_build_android.txt: -------------------------------------------------------------------------------- 1 | cython==0.29.33 2 | git+https://github.com/kivy/buildozer.git@master -------------------------------------------------------------------------------- /tools/build/requirements_build_linux.txt: -------------------------------------------------------------------------------- 1 | PyInstaller==5.13.1 2 | #cython==0.29.33 3 | -------------------------------------------------------------------------------- /tools/build/requirements_build_macosx.txt: -------------------------------------------------------------------------------- 1 | 2 | sh==2.0.4 3 | setuptools==68.2.2 4 | git+https://github.com/kivy/buildozer.git@820a4480ec4c9bf8a95ba77ba7b3b85dfc2e0130 5 | -------------------------------------------------------------------------------- /tools/build/requirements_build_windows.txt: -------------------------------------------------------------------------------- 1 | PyInstaller==5.13.1 2 | #cython==0.29.33 3 | -------------------------------------------------------------------------------- /tools/install.sh: -------------------------------------------------------------------------------- 1 | cd .. 2 | pip install -r requirements.txt -------------------------------------------------------------------------------- /tools/run.sh: -------------------------------------------------------------------------------- 1 | cd .. 2 | python run.py -------------------------------------------------------------------------------- /tools/test.bat: -------------------------------------------------------------------------------- 1 | cd .. 2 | taskkill /f /t /im python.exe 3 | python run.py 4 | cd tools -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | isolated_build = True 3 | envlist = 4 | py311 5 | isort 6 | pylint 7 | 8 | [testenv] 9 | deps = 10 | poetry 11 | commands = 12 | poetry install -v 13 | poetry run pytest tests 14 | 15 | [testenv:isort] 16 | deps = 17 | isort 18 | changedir = {toxinidir} 19 | commands = 20 | isort . --check-only --diff 21 | 22 | [testenv:pylint] 23 | changedir = {toxinidir} 24 | commands = 25 | poetry install -v 26 | poetry run pylint tests src 27 | --------------------------------------------------------------------------------