├── LICENSE ├── README.md ├── cf_speedtest.js ├── go.mod ├── go.sum ├── main.go ├── script └── openwrt │ ├── CloudflareST │ ├── Country.mmdb │ ├── cf_RE.sh │ ├── config.yaml │ ├── ddns │ └── cf_ddns │ ├── msg │ ├── cf_push │ └── wxsend_jiang.sh │ └── start.sh ├── task ├── download.go ├── httping.go ├── ip.go └── tcping.go ├── trojan_workers └── _worker.js ├── utils ├── csv.go ├── csv_test.go ├── getcountry.go └── progress.go └── vless_workers └── _worker.js /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 | # Cloudflare 上建workers和pages节点及自动化优选IP的一揽子工具 2 | 3 | 4 | 5 | 优选工具使用CloudflareSpeedTest,用法如下: 6 | 7 | ``` cvs 8 | 9 | 10 | 参数: 11 | -n 200 12 | 延迟测速线程;越多延迟测速越快,性能弱的设备 (如路由器) 请勿太高;(默认 200 最多 1000) 13 | -t 4 14 | 延迟测速次数;单个 IP 延迟测速的次数;(默认 4 次) 15 | -dn 10 16 | 下载测速数量;延迟测速并排序后,从最低延迟起下载测速的数量;(默认 10 个) 17 | -dt 10 18 | 下载测速时间;单个 IP 下载测速最长时间,不能太短;(默认 10 秒) 19 | -tp 443 20 | 指定测速端口;延迟测速/下载测速时使用的端口;(默认 443 端口) 21 | -url https://cf.xiu2.xyz/url 22 | 指定测速地址;延迟测速(HTTPing)/下载测速时使用的地址,默认地址不保证可用性,建议自建; 23 | 24 | -httping 25 | 切换测速模式;延迟测速模式改为 HTTP 协议,所用测试地址为 [-url] 参数;(默认 TCPing) 26 | 注意:HTTPing 本质上也算一种 网络扫描 行为,因此如果你在服务器上面运行,需要降低并发(-n),否则可能会被一些严格的商家暂停服务。 27 | 如果你遇到 HTTPing 首次测速可用 IP 数量正常,后续测速越来越少甚至直接为 0,但停一段时间后又恢复了的情况,那么也可能是被 运营商、Cloudflare CDN 认为你在网络扫描而 触发临时限制机制,因此才会过一会儿就恢复了,建议降低并发(-n)减少这种情况的发生。 28 | -httping-code 200 29 | 有效状态代码;HTTPing 延迟测速时网页返回的有效 HTTP 状态码,仅限一个;(默认 200 301 302) 30 | -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD 31 | 匹配指定地区;地区名为当地机场三字码,英文逗号分隔,支持小写,支持 Cloudflare、AWS CloudFront,仅 HTTPing 模式可用;(默认 所有地区) 32 | 33 | -tl 200 34 | 平均延迟上限;只输出低于指定平均延迟的 IP,各上下限条件可搭配使用;(默认 9999 ms) 35 | -tll 40 36 | 平均延迟下限;只输出高于指定平均延迟的 IP;(默认 0 ms) 37 | -tlr 0.2 38 | 丢包几率上限;只输出低于/等于指定丢包率的 IP,范围 0.00~1.00,0 过滤掉任何丢包的 IP;(默认 1.00) 39 | -sl 5 40 | 下载速度下限;只输出高于指定下载速度的 IP,凑够指定数量 [-dn] 才会停止测速;(默认 0.00 MB/s) 41 | 42 | -p 10 43 | 显示结果数量;测速后直接显示指定数量的结果,为 0 时不显示结果直接退出;(默认 10 个) 44 | -f ip.txt 45 | IP段数据文件;如路径含有空格请加上引号;支持其他 CDN IP段;(默认 ip.txt) 46 | -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32 47 | 指定IP段数据;直接通过参数指定要测速的 IP 段数据,英文逗号分隔;(默认 空) 48 | -o result.csv 49 | 写入结果文件;如路径含有空格请加上引号;值为空时不写入文件 [-o ""];(默认 result.csv) 50 | 51 | -dd 52 | 禁用下载测速;禁用后测速结果会按延迟排序 (默认按下载速度排序);(默认 启用) 53 | -allip 54 | 测速全部的IP;对 IP 段中的每个 IP (仅支持 IPv4) 进行测速;(默认 每个 /24 段随机测速一个 IP) 55 | 56 | -c 57 | 按国家代码分类输出文件 58 | -cc 59 | 指定国家代码选择IP,仅支持 IPv4;(默认 所有国家) 60 | -v 61 | 打印程序版本 + 检查版本更新 62 | -h 63 | 打印帮助说明 64 | ``` 65 | 工具代码来自于: https://github.com/XIU2/CloudflareSpeedTest 66 | 我这个在此基础上做了功能增强修改。 67 | 68 | vless workers代码来自于: https://github.com/3Kmfi6HP/EDtunnel 69 | trojan workers代码来自于:https://github.com/ca110us/epeius 70 | 在原来代码基础上做了简单修改,统一了配置习惯。 71 | 72 | 73 | ## License 74 | 75 | The GPL-3.0 License. 76 | -------------------------------------------------------------------------------- /cf_speedtest.js: -------------------------------------------------------------------------------- 1 | export default { 2 | async fetch(request) { 3 | // 创建一个新的 URL 对象 4 | let url = new URL(request.url); 5 | let path = url.pathname.substring(1); 6 | let isSecure = url.protocol.startsWith("https"); 7 | let bytes; 8 | // 判断路径是否为空 9 | if (!path) { 10 | // 路径为空,将 bytes 赋值为 200MB 11 | bytes = 200000000; 12 | } else if (path === "locations") { 13 | let targetUrl = `http${isSecure ? 's' : ''}://speed.cloudflare.com/locations`; 14 | let cfRequest = new Request(targetUrl, request); 15 | let response = await fetch(cfRequest); 16 | return response; 17 | } else { 18 | // 其他路径,进行正常的处理 19 | const regex = /^(\d+)([a-z]?)$/i; 20 | const match = path.match(regex); 21 | if (!match) { 22 | // 路径格式不正确,返回错误 23 | return new Response("路径格式不正确", { 24 | status: 400, 25 | }); 26 | } 27 | 28 | const bytesStr = match[1]; 29 | const unit = match[2].toLowerCase(); 30 | 31 | // 转换单位 32 | bytes = parseInt(bytesStr, 10); 33 | if (unit === "k") { 34 | bytes *= 1000; 35 | } else if (unit === "m") { 36 | bytes *= 1000000; 37 | } else if (unit === "g") { 38 | bytes *= 1000000000; 39 | } 40 | } 41 | 42 | let targetUrl = `http${isSecure ? 's' : ''}://speed.cloudflare.com/__down?bytes=${bytes}`; 43 | let cfRequest = new Request(targetUrl, request); 44 | let response = await fetch(cfRequest); 45 | 46 | // 将测试结果反馈给用户 47 | return response; 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/XIU2/CloudflareSpeedTest 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/VividCortex/ewma v1.1.1 7 | github.com/cheggaaa/pb/v3 v3.0.4 8 | github.com/oschwald/maxminddb-golang v1.12.0 9 | golang.org/x/text v0.14.0 10 | ) 11 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/VividCortex/ewma v1.1.1 h1:MnEK4VOv6n0RSY4vtRe3h11qjxL3+t0B8yOL8iMXdcM= 2 | github.com/VividCortex/ewma v1.1.1/go.mod h1:2Tkkvm3sRDVXaiyucHiACn4cqf7DpdyLvmxzcbUokwA= 3 | github.com/cheggaaa/pb/v3 v3.0.4 h1:QZEPYOj2ix6d5oEg63fbHmpolrnNiwjUsk+h74Yt4bM= 4 | github.com/cheggaaa/pb/v3 v3.0.4/go.mod h1:7rgWxLrAUcFMkvJuv09+DYi7mMUYi8nO9iOWcvGJPfw= 5 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 7 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 8 | github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= 9 | github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= 10 | github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU= 11 | github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= 12 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= 13 | github.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW10= 14 | github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= 15 | github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54= 16 | github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= 17 | github.com/oschwald/maxminddb-golang v1.12.0 h1:9FnTOD0YOhP7DGxGsq4glzpGy5+w7pq50AS6wALUMYs= 18 | github.com/oschwald/maxminddb-golang v1.12.0/go.mod h1:q0Nob5lTCqyQ8WT6FYgS1L7PXKVVbgiymefNwIjPzgY= 19 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 20 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 21 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 22 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 23 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 24 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 25 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 26 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= 27 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 28 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 29 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 30 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 31 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 32 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 33 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 34 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 35 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 36 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 37 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 38 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 39 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 40 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 41 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 42 | golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 43 | golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 44 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 45 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 46 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 47 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 48 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 49 | golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= 50 | golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 51 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 52 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 53 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 54 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 55 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 56 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 57 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 58 | golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= 59 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 60 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 61 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 62 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 63 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 64 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 65 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 66 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 67 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 68 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 69 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 70 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "github.com/oschwald/maxminddb-golang" 7 | "io/ioutil" 8 | "net/http" 9 | "os" 10 | "runtime" 11 | "sort" 12 | "strings" 13 | "time" 14 | 15 | "github.com/XIU2/CloudflareSpeedTest/task" 16 | "github.com/XIU2/CloudflareSpeedTest/utils" 17 | ) 18 | 19 | var ( 20 | version, versionNew string 21 | BCountry bool = false 22 | CountryCodes string 23 | CountryList map[string]bool 24 | ) 25 | 26 | func init() { 27 | var printVersion bool 28 | var help = ` 29 | CloudflareSpeedTest ` + version + ` 30 | 测试 Cloudflare CDN 所有 IP 的延迟和速度,获取最快 IP (IPv4+IPv6)! 31 | https://github.com/XIU2/CloudflareSpeedTest 32 | 33 | 参数: 34 | -n 200 35 | 延迟测速线程;越多延迟测速越快,性能弱的设备 (如路由器) 请勿太高;(默认 200 最多 1000) 36 | -t 4 37 | 延迟测速次数;单个 IP 延迟测速的次数;(默认 4 次) 38 | -dn 10 39 | 下载测速数量;延迟测速并排序后,从最低延迟起下载测速的数量;(默认 10 个) 40 | -dt 10 41 | 下载测速时间;单个 IP 下载测速最长时间,不能太短;(默认 10 秒) 42 | -tp 443 43 | 指定测速端口;延迟测速/下载测速时使用的端口;(默认 443 端口) 44 | -url https://cf.xiu2.xyz/url 45 | 指定测速地址;延迟测速(HTTPing)/下载测速时使用的地址,默认地址不保证可用性,建议自建; 46 | 47 | -httping 48 | 切换测速模式;延迟测速模式改为 HTTP 协议,所用测试地址为 [-url] 参数;(默认 TCPing) 49 | -httping-code 200 50 | 有效状态代码;HTTPing 延迟测速时网页返回的有效 HTTP 状态码,仅限一个;(默认 200 301 302) 51 | -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD 52 | 匹配指定地区;地区名为当地机场三字码,英文逗号分隔,仅 HTTPing 模式可用;(默认 所有地区) 53 | 54 | -tl 200 55 | 平均延迟上限;只输出低于指定平均延迟的 IP,各上下限条件可搭配使用;(默认 9999 ms) 56 | -tll 40 57 | 平均延迟下限;只输出高于指定平均延迟的 IP;(默认 0 ms) 58 | -tlr 0.2 59 | 丢包几率上限;只输出低于/等于指定丢包率的 IP,范围 0.00~1.00,0 过滤掉任何丢包的 IP;(默认 1.00) 60 | -sl 5 61 | 下载速度下限;只输出高于指定下载速度的 IP,凑够指定数量 [-dn] 才会停止测速;(默认 0.00 MB/s) 62 | 63 | -p 10 64 | 显示结果数量;测速后直接显示指定数量的结果,为 0 时不显示结果直接退出;(默认 10 个) 65 | -f ip.txt 66 | IP段数据文件;如路径含有空格请加上引号;支持其他 CDN IP段;(默认 ip.txt) 67 | -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32 68 | 指定IP段数据;直接通过参数指定要测速的 IP 段数据,英文逗号分隔;(默认 空) 69 | -o result.csv 70 | 写入结果文件;如路径含有空格请加上引号;值为空时不写入文件 [-o ""];(默认 result.csv) 71 | 72 | -dd 73 | 禁用下载测速;禁用后测速结果会按延迟排序 (默认按下载速度排序);(默认 启用) 74 | -allip 75 | 测速全部的IP;对 IP 段中的每个 IP (仅支持 IPv4) 进行测速;(默认 每个 /24 段随机测速一个 IP) 76 | 77 | -c 78 | 显示国家信息,按国家分类输出并按速度排序。 79 | -cc 80 | 配合-cc使用,指定所需的国家ip,输入国家代码,多个用逗号分隔。如 US,JP 81 | -v 82 | 打印程序版本 + 检查版本更新 83 | -h 84 | 打印帮助说明 85 | ` 86 | var minDelay, maxDelay, downloadTime int 87 | var maxLossRate float64 88 | flag.IntVar(&task.Routines, "n", 200, "延迟测速线程") 89 | flag.IntVar(&task.PingTimes, "t", 4, "延迟测速次数") 90 | flag.IntVar(&task.TestCount, "dn", 10, "下载测速数量") 91 | flag.IntVar(&downloadTime, "dt", 10, "下载测速时间") 92 | flag.IntVar(&task.TCPPort, "tp", 443, "指定测速端口") 93 | flag.StringVar(&task.URL, "url", "https://cf.xiu2.xyz/url", "指定测速地址") 94 | 95 | flag.BoolVar(&task.Httping, "httping", false, "切换测速模式") 96 | flag.IntVar(&task.HttpingStatusCode, "httping-code", 0, "有效状态代码") 97 | flag.StringVar(&task.HttpingCFColo, "cfcolo", "", "匹配指定地区") 98 | 99 | flag.IntVar(&maxDelay, "tl", 9999, "平均延迟上限") 100 | flag.IntVar(&minDelay, "tll", 0, "平均延迟下限") 101 | flag.Float64Var(&maxLossRate, "tlr", 1, "丢包几率上限") 102 | flag.Float64Var(&task.MinSpeed, "sl", 0, "下载速度下限") 103 | 104 | flag.IntVar(&utils.PrintNum, "p", 10, "显示结果数量") 105 | flag.StringVar(&task.IPFile, "f", "ip.txt", "IP段数据文件") 106 | flag.StringVar(&task.IPText, "ip", "", "指定IP段数据") 107 | flag.StringVar(&utils.Output, "o", "result.csv", "输出结果文件") 108 | flag.StringVar(&CountryCodes, "cc", "", "指定国家代码,多个用逗号分隔") 109 | flag.BoolVar(&BCountry, "c", false, "按国家代码分类输出文件") 110 | flag.BoolVar(&task.Disable, "dd", false, "禁用下载测速") 111 | flag.BoolVar(&task.TestAll, "allip", false, "测速全部 IP") 112 | 113 | flag.BoolVar(&printVersion, "v", false, "打印程序版本") 114 | flag.Usage = func() { fmt.Print(help) } 115 | flag.Parse() 116 | 117 | if task.MinSpeed > 0 && time.Duration(maxDelay)*time.Millisecond == utils.InputMaxDelay { 118 | fmt.Println("[小提示] 在使用 [-sl] 参数时,建议搭配 [-tl] 参数,以避免因凑不够 [-dn] 数量而一直测速...") 119 | } 120 | utils.InputMaxDelay = time.Duration(maxDelay) * time.Millisecond 121 | utils.InputMinDelay = time.Duration(minDelay) * time.Millisecond 122 | utils.InputMaxLossRate = float32(maxLossRate) 123 | task.Timeout = time.Duration(downloadTime) * time.Second 124 | task.HttpingCFColomap = task.MapColoMap() 125 | 126 | if printVersion { 127 | println(version) 128 | fmt.Println("检查版本更新中...") 129 | checkUpdate() 130 | if versionNew != "" { 131 | fmt.Printf("*** 发现新版本 [%s]!请前往 [https://github.com/XIU2/CloudflareSpeedTest] 更新! ***", versionNew) 132 | } else { 133 | fmt.Println("当前为最新版本 [" + version + "]!") 134 | } 135 | os.Exit(0) 136 | } 137 | } 138 | 139 | func main() { 140 | task.InitRandSeed() // 置随机数种子 141 | 142 | if BCountry { 143 | fmt.Println("分国家测速模式") 144 | if CountryCodes != "" { 145 | codes := strings.Split(CountryCodes, ",") 146 | if len(codes) > 0 { 147 | CountryList = make(map[string]bool) 148 | for _, code := range codes { 149 | CountryList[code] = true 150 | } 151 | } 152 | } 153 | } 154 | fmt.Printf("# XIU2/CloudflareSpeedTest %s \n\n", version) 155 | 156 | // 开始延迟测速 + 过滤延迟/丢包 157 | pingData := task.NewPing().Run().FilterDelay().FilterLossRate() 158 | if BCountry { 159 | db, err := maxminddb.Open("Country.mmdb") 160 | if err != nil { 161 | fmt.Println(err) 162 | return 163 | } 164 | countryinfo := utils.NewCountryInfo(db) 165 | CountrypingData := pingData.FilterCountryV2(countryinfo, CountryList) 166 | countryinfo.Done() 167 | if CountrypingData == nil { 168 | return 169 | } 170 | //按国家代号排序,每个国家按延迟从小到大排序 171 | sort.Slice(CountrypingData, func(i, j int) bool { 172 | left := CountrypingData[i].Country + fmt.Sprintf("%d", CountrypingData[i].Delay) 173 | right := CountrypingData[j].Country + fmt.Sprintf("%d", CountrypingData[j].Delay) 174 | return left < right 175 | }) 176 | speedData := task.TestDownloadSpeedByCountry(CountrypingData) 177 | utils.ExportCsvByCountry(speedData) 178 | } else { 179 | // 开始下载测速 180 | speedData := task.TestDownloadSpeed(pingData) 181 | utils.ExportCsv(speedData) // 输出文件 182 | speedData.Print() // 打印结果 183 | } 184 | 185 | if versionNew != "" { 186 | fmt.Printf("\n*** 发现新版本 [%s]!请前往 [https://github.com/XIU2/CloudflareSpeedTest] 更新! ***\n", versionNew) 187 | } 188 | endPrint() 189 | } 190 | 191 | func endPrint() { 192 | if utils.NoPrintResult() { 193 | return 194 | } 195 | if runtime.GOOS == "windows" { // 如果是 Windows 系统,则需要按下 回车键 或 Ctrl+C 退出(避免通过双击运行时,测速完毕后直接关闭) 196 | fmt.Printf("按下 回车键 或 Ctrl+C 退出。") 197 | fmt.Scanln() 198 | } 199 | } 200 | 201 | // 检查更新 202 | func checkUpdate() { 203 | timeout := 10 * time.Second 204 | client := http.Client{Timeout: timeout} 205 | res, err := client.Get("https://api.xiu2.xyz/ver/cloudflarespeedtest.txt") 206 | if err != nil { 207 | return 208 | } 209 | // 读取资源数据 body: []byte 210 | body, err := ioutil.ReadAll(res.Body) 211 | if err != nil { 212 | return 213 | } 214 | // 关闭资源流 215 | defer res.Body.Close() 216 | if string(body) != version { 217 | versionNew = string(body) 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /script/openwrt/CloudflareST: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frankiejun/cvwt/371951127ae645f6c39e625b34be0d463c9068d0/script/openwrt/CloudflareST -------------------------------------------------------------------------------- /script/openwrt/Country.mmdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frankiejun/cvwt/371951127ae645f6c39e625b34be0d463c9068d0/script/openwrt/Country.mmdb -------------------------------------------------------------------------------- /script/openwrt/cf_RE.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ##用于openwrt安装jq和timeout,确保CloudflareSpeedTestDDNS运行正常。 3 | opkg update 4 | opkg install jq coreutils-timeout 5 | opkg install yq 6 | opkg list-installed | grep jq 7 | opkg list-installed | grep coreutils-timeout 8 | -------------------------------------------------------------------------------- /script/openwrt/config.yaml: -------------------------------------------------------------------------------- 1 | 2 | ##cloudflare配置 3 | cloudflare: 4 | #cloudflare账号邮箱 5 | - x_email: 6 | 7 | #域名(多个用逗号分隔) 8 | hostname: 9 | 10 | #空间ID 11 | zone_id: 12 | 13 | #Global API Key 14 | api_key: 15 | 16 | #配置多个账号或域名,注意字段使用空格对齐,符合yaml格式要求 17 | # - x_email: 18 | # 19 | # #域名(多个用逗号分隔) 20 | # hostname: 21 | # 22 | # #空间ID 23 | # zone_id: 24 | # 25 | # #Global API Key 26 | # api_key: 27 | 28 | ##openwrt科学上网插件配置 29 | #优选节点时是否自动停止科学上网服务 true: 自动停止 false: 不停止 默认为 true 30 | pause: 31 | true 32 | #填写openwrt使用的是哪个科学上网客户端,填写对应的“数字” 默认为 1 客户端为passwall 33 | # 1: passwall 2: passwall2 3: ShadowSocksR Plus+ 4: clash 5: openclash 6: bypass 34 | clien: 35 | 1 36 | #同一域名更新的ip数量(如果设置值大于实际搜出的ip数量,以实际ip数量为准) 37 | multip: 38 | 39 | #测速地址 40 | CFST_URL: 41 | 42 | #测速线程数量;越多测速越快,性能弱的设备 (如路由器) 请勿太高;(默认 200 最多 1000 ) 43 | CFST_N: 200 44 | #延迟测速次数;单个 IP 延迟测速次数,为 1 时将过滤丢包的IP,TCP协议;(默认 4 次 ) 45 | CFST_T: 1 46 | #下载测速数量;延迟测速并排序后,从最低延迟起下载测速的数量;(默认 10 个) 47 | CFST_DN: 10 48 | #平均延迟上限;只输出低于指定平均延迟的 IP,可与其他上限/下限搭配;(默认9999 ms 这里推荐配置250 ms) 49 | CFST_TL: 250 50 | #平均延迟下限;只输出高于指定平均延迟的 IP,可与其他上限/下限搭配、过滤假墙 IP;(默认 0 ms 这里推荐配置40) 51 | CFST_TLL: 40 52 | #下载速度下限;只输出高于指定下载速度的 IP,凑够指定数量 [-dn] 才会停止测速;(默认 0.00 MB/s 这里推荐5.00MB/s) 53 | CFST_SL: 5 54 | #是否按国家代码做分组筛选(是: true,否: false) 55 | CCFLAG: true 56 | #需要指定的国家代码,多个用逗号分隔(eg. US,JP) 57 | CCODE: 58 | #CF服务器对应端口 59 | CF_ADDR: 443 60 | 61 | #推送开关, 1:TG, 2:WX, 3.both. 62 | sendType: 63 | 3 64 | 65 | ##TG推送设置 66 | #(填写即为开启推送,未填写则为不开启) 67 | #TG机器人token 例如:123456789: ABCDEFG... 68 | telegramBotToken: 69 | 70 | telegramBotUserId: 71 | 72 | 73 | #微信推送, 通过https://sct.ftqq.com/r/13223 注册并登录server酱,取得sendKey 74 | sendKey: 75 | 76 | -------------------------------------------------------------------------------- /script/openwrt/ddns/cf_ddns: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #新功能,支持更新优选完毕后推送至TG,再也不怕脚本没有成功运行了。 3 | #使用脚本需要安装jq和timeout,新增openwrt专用cf_RE.sh文件,运行cf_RE.sh即可在openwrt安装jq和timeout两个扩展。 4 | #其他linux请自行安装jq和timeout。 5 | 6 | ipv4Regex="((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])" 7 | #默认关闭小云朵 8 | proxy="false" 9 | chkDnsArr=() 10 | delDnsArr=() 11 | excludeIp=() 12 | CheckDelCFDns() { 13 | listDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records?name=${CDNhostname}" 14 | excludeIp=() 15 | delDnsArr=() 16 | chkDnsArr=() 17 | res=$(curl -s -X GET "$listDnsApi" -H "X-Auth-Email:$x_email" -H "X-Auth-Key:$api_key" -H "Content-Type:application/json") 18 | total_ct=$(echo "$res" | jq -r ".result_info.total_count") 19 | 20 | #echo "multFlag: $multFlag" 21 | 22 | if ((total_ct > 1 || multFlag == 1)); then 23 | # echo "total_ct:$total_ct" 24 | for ((i = 0; i < total_ct; i++)); do 25 | record_id=$(echo "$res" | jq -r ".result[$i].id") 26 | ip=$(echo "$res" | jq -r ".result[$i].content") 27 | chkDnsArr+=("$record_id"":""$ip") 28 | #echo "$record_id"":""$ip" 29 | done 30 | fi 31 | } 32 | 33 | findRecInExcludeArr() { 34 | local rec=$1 35 | local sparr=() 36 | IFS=':' read -ra sparr <<<"$rec" 37 | # echo "findRecInExcludeArr():rec:$rec" 38 | for ip in "${excludeIp[@]}"; do 39 | #echo "left:${sparr[1]}|,right:$ip|" 40 | if [ "${sparr[1]}" == "$ip" ]; then 41 | return 0 42 | fi 43 | done 44 | 45 | return 1 46 | } 47 | 48 | FilterRec() { 49 | # echo "FilterRec()" 50 | delDnsArr=() 51 | for i in "${!chkDnsArr[@]}"; do 52 | findRecInExcludeArr "${chkDnsArr[$i]}" 53 | #不是排除之列,则加到删除队列 54 | if [ $? -eq 1 ]; then 55 | #echo "add to delarr" 56 | local sparr=() 57 | IFS=':' read -ra sparr <<<"${chkDnsArr[$i]}" 58 | delDnsArr+=(${sparr[0]}) 59 | fi 60 | 61 | done 62 | } 63 | 64 | RealDelDns() { 65 | delDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records" 66 | 67 | FilterRec 68 | for index in "${!delDnsArr[@]}"; do 69 | record_id=${delDnsArr[$index]} 70 | # 输出正在删除的记录 71 | #echo "正在删除第 $((index + 1)) 条 DNS 记录,记录 ID: $record_id" 72 | # 发出删除请求 73 | rt=$(curl -s -X DELETE "${delDnsApi}/$record_id" -H "Content-Type: application/json" -H "X-Auth-Email: $x_email" -H "X-Auth-Key: $api_key") 74 | succ=$(echo $rt | jq -r ".success") 75 | if [ "$succ" != "true" ]; then 76 | echo "删除dns记录失败,会可能引起后面更新问题,强制退出" 77 | exit 1 78 | fi 79 | 80 | done 81 | 82 | } 83 | 84 | InsertCF() { 85 | ipAddr=$1 86 | if [[ $ipAddr =~ $ipv4Regex ]]; then 87 | recordType="A" 88 | else 89 | recordType="AAAA" 90 | fi 91 | 92 | echo "新增$CDNhostname 的DNS记录" 93 | createDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records" 94 | res=$(curl -s -X POST "$createDnsApi" -H "X-Auth-Email:$x_email" -H "X-Auth-Key:$api_key" -H "Content-Type:application/json" --data "{\"type\":\"$recordType\",\"name\":\"$CDNhostname\",\"content\":\"$ipAddr\",\"proxied\":$proxy}") 95 | resSuccess=$(echo "$res" | jq -r ".success") 96 | 97 | if [[ "$resSuccess" = "true" ]]; then 98 | echo "$CDNhostname更新成功" 99 | return 0 100 | else 101 | code=$(echo "$res" | jq -r ".errors[0].code") 102 | #已有相同记录 103 | if [ $code -eq 81057 ]; then 104 | excludeIp+=($ipAddr) 105 | echo "已有[$ipAddr] IP记录不做更新" 106 | return 0 107 | else 108 | echo "$CDNhostname更新失败" 109 | return 1 110 | fi 111 | fi 112 | 113 | } 114 | 115 | UpInsetCF() { 116 | #开始DDNS 117 | ipAddr=$1 118 | if [[ $ipAddr =~ $ipv4Regex ]]; then 119 | recordType="A" 120 | else 121 | recordType="AAAA" 122 | fi 123 | 124 | listDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records?type=${recordType}&name=${CDNhostname}" 125 | createDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records" 126 | 127 | res=$(curl -s -X GET "$listDnsApi" -H "X-Auth-Email:$x_email" -H "X-Auth-Key:$api_key" -H "Content-Type:application/json") 128 | recordId=$(echo "$res" | jq -r ".result[0].id") 129 | recordIp=$(echo "$res" | jq -r ".result[0].content") 130 | 131 | echo "recordIp:$recordIp" 132 | if [[ $recordIp = "$ipAddr" ]]; then 133 | echo "更新失败,获取最快的IP与云端相同" 134 | excludeIp+=($ipAddr) 135 | resSuccess="false" 136 | elif [[ $recordId = "null" ]]; then 137 | res=$(curl -s -X POST "$createDnsApi" -H "X-Auth-Email:$x_email" -H "X-Auth-Key:$api_key" -H "Content-Type:application/json" --data "{\"type\":\"$recordType\",\"name\":\"$CDNhostname\",\"content\":\"$ipAddr\",\"proxied\":$proxy}") 138 | resSuccess=$(echo "$res" | jq -r ".success") 139 | else 140 | updateDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records/${recordId}" 141 | res=$(curl -s -X PUT "$updateDnsApi" -H "X-Auth-Email:$x_email" -H "X-Auth-Key:$api_key" -H "Content-Type:application/json" --data "{\"type\":\"$recordType\",\"name\":\"$CDNhostname\",\"content\":\"$ipAddr\",\"proxied\":$proxy}") 142 | resSuccess=$(echo "$res" | jq -r ".success") 143 | excludeIp+=($ipAddr) 144 | fi 145 | 146 | if [[ "$resSuccess" = "true" ]]; then 147 | echo "$CDNhostname更新成功" 148 | else 149 | echo "$CDNhostname更新失败" 150 | fi 151 | 152 | } 153 | 154 | #验证cf账号信息是否正确 155 | echo "cf_ddns():zone_id:$zone_id" 156 | echo "cf_ddns():api_key:$api_key" 157 | res=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${zone_id}" -H "X-Auth-Email:$x_email" -H "X-Auth-Key:$api_key" -H "Content-Type:application/json") 158 | resSuccess=$(echo "$res" | jq -r ".success") 159 | if [[ $resSuccess != "true" ]]; then 160 | pushmessage="登陆错误,检查cloudflare账号信息填写是否正确!" 161 | source cf_push 162 | exit 1 163 | fi 164 | echo "Cloudflare账号验证成功" 165 | 166 | if [ -z $multip ]; then 167 | multip=1 168 | multFlag=0 169 | else 170 | multFlag=1 171 | fi 172 | 173 | #开始循环 174 | echo "正在更新域名,请稍后..." 175 | x=0 176 | csvfile="" 177 | while [[ ${x} -lt $domain_num ]]; do 178 | CDNhostname=${domains[$x]} 179 | #获取优选后的ip地址 180 | 181 | if [ "$CCFLAG" = "true" ]; then 182 | CountryCode=${countryCodes[$x]} 183 | csvfile="$CountryCode"".csv" 184 | echo "csvfile:$csvfile" 185 | else 186 | csvfile="result.csv" 187 | fi 188 | 189 | #如果没有生成对应结果文件,跳过 190 | if [ ! -e $csvfile ]; then 191 | x=$((x + 1)) 192 | continue 193 | fi 194 | 195 | CheckDelCFDns 196 | 197 | lineNo=0 198 | ipcount=0 199 | while read -r line; do 200 | ((lineNo++)) 201 | if ((lineNo == 1)); then 202 | continue 203 | fi 204 | IFS=, read -ra fields <<<"$line" 205 | ipAddr=${fields[0]} 206 | 207 | ((ipcount++)) 208 | echo "开始更新第${ipcount}个---$ipAddr" 209 | if ((multFlag == 1)); then 210 | InsertCF $ipAddr 211 | else 212 | UpInsetCF $ipAddr 213 | fi 214 | 215 | if ((ipcount >= multip)); then 216 | break 217 | fi 218 | 219 | done <$csvfile 220 | 221 | RealDelDns 222 | echo "完成$csvfile的ip更新!" 223 | x=$((x + 1)) 224 | sleep 1s 225 | 226 | done >>informlog 227 | -------------------------------------------------------------------------------- /script/openwrt/msg/cf_push: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ##用于CloudflareSpeedTestDDNS执行情况推送。 3 | echo $pushmessage 4 | message_text=$pushmessage 5 | #解析模式,可选HTML或Markdown 6 | MODE='HTML' 7 | #api接口 8 | telegramBotToken=$(yq eval ".telegramBotToken" $configfile) 9 | telegramBotUserId=$(yq eval ".telegramBotUserId" $configfile) 10 | URL="https://api.telegram.org/bot${telegramBotToken}/sendMessage" 11 | if [[ -z ${telegramBotToken} ]]; then 12 | echo "未配置TG推送" 13 | else 14 | res=$(timeout 20s curl -s -X POST $URL -d chat_id=${telegramBotUserId} -d parse_mode=${MODE} -d text="${message_text}") 15 | if [ $? == 124 ]; then 16 | echo 'TG_api请求超时,请检查网络是否重启完成并是否能够访问TG' 17 | exit 1 18 | fi 19 | resSuccess=$(echo "$res" | jq -r ".ok") 20 | if [[ $resSuccess = "true" ]]; then 21 | echo "TG推送成功" 22 | else 23 | echo "TG推送失败,请检查TG机器人token和ID" 24 | fi 25 | fi 26 | -------------------------------------------------------------------------------- /script/openwrt/msg/wxsend_jiang.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | text='' 4 | 5 | while IFS= read -r line; do 6 | text+="$line" 7 | done <"./informlog" 8 | 9 | #for test. 10 | #configfile="./config.yaml" 11 | #sendKey=$(yq eval ".sendKey" $configfile) 12 | 13 | title="msg_from_cvwt" 14 | URL="https://sctapi.ftqq.com/$sendKey.send?" 15 | 16 | if [[ -z ${sendKey} ]]; then 17 | echo "未配置微信推送的sendKey, 关注【方糖】公众号获取sendKey" 18 | else 19 | res=$(timeout 20s curl -s -X POST $URL -d title=${title} -d desp="${text}") 20 | if [ $? == 124 ]; then 21 | echo "发送消息超时" 22 | exit 1 23 | fi 24 | 25 | #res:{"code":0,"message":"","data":{"pushid":"164999333","readkey":"SCTGLrDh4Zadf4k","error":"SUCCESS","errno":0}} 26 | err=$(echo "$res" | jq -r ".data.error") 27 | if [ "$err" == "SUCCESS" ]; then 28 | echo "微信推送成功" 29 | else 30 | echo "微信推送失败, error:$err" 31 | fi 32 | fi 33 | -------------------------------------------------------------------------------- /script/openwrt/start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if [ $# -lt 1 ]; then 4 | echo "start.sh config_file_path [ipfile]" 5 | exit 0 6 | fi 7 | 8 | configfile=$1 9 | ipfile=$2 10 | 11 | echo "configfile:$configfile, ipfile:$ipfile" 12 | 13 | ipzipfile="txt.zip" 14 | 15 | //for test 16 | rm -rf *.csv 17 | if [[ -e $ipzipfile ]]; then 18 | rm -rf $ipzipfile 19 | fi 20 | 21 | if [[ -e informlog ]]; then 22 | rm -rf informlog 23 | fi 24 | 25 | 26 | echo "0.读取配置文件" 27 | if [[ ! -e $configfile ]]; then 28 | echo "找不到$configfile配置文件!" 29 | exit 1 30 | fi 31 | 32 | pause=$(yq eval ".pause" $configfile) 33 | clien=$(yq eval ".clien" $configfile) 34 | multip=$(yq eval ".multip" $configfile) 35 | CFST_URL=$(yq eval ".CFST_URL" $configfile) 36 | CFST_N=$(yq eval ".CFST_N" $configfile) 37 | CFST_T=$(yq eval ".CFST_T" $configfile) 38 | CFST_DN=$(yq eval ".CFST_DN" $configfile) 39 | CFST_TL=$(yq eval ".CFST_TL" $configfile) 40 | CFST_TLL=$(yq eval ".CFST_TLL" $configfile) 41 | CFST_SL=$(yq eval ".CFST_SL" $configfile) 42 | CCFLAG=$(yq eval ".CCFLAG" $configfile) 43 | CCODE=$(yq eval ".CCODE" $configfile) 44 | CF_ADDR=$(yq eval ".CF_ADDR" $configfile) 45 | telegramBotToken=$(yq eval ".telegramBotToken" $configfile) 46 | telegramBotUserId=$(yq eval ".telegramBotUserId" $configfile) 47 | sendType=$(yq eval ".sendType" $configfile) 48 | sendKey=$(yq eval ".sendKey" $configfile) 49 | 50 | ChkHostnameAndCoutryCode() { 51 | IFS=, read -r -a domains <<<"$hostname" 52 | IFS=, read -r -a countryCodes <<<"$CCODE" 53 | 54 | domain_num=${#domains[@]} 55 | countryCode_num=${#countryCodes[@]} 56 | 57 | if [ ${#domains[@]} -eq 0 ]; then 58 | echo "hostname must be set in config file!" 59 | return 1 60 | fi 61 | 62 | #检查域名和国家代码是否一一对应 63 | if [ "$CCFLAG" = "true" ]; then 64 | echo "domain_num:$domain_num, countryCode_num:$countryCode_num" 65 | if [ $domain_num -ne $countryCode_num ]; then 66 | echo "The name and country code must correspond one to one!" 67 | return 1 68 | fi 69 | fi 70 | return 0 71 | } 72 | 73 | GetProxName() { 74 | c=$1 75 | if [ "$c" = "6" ]; then 76 | CLIEN=bypass 77 | elif [ "$c" = "5" ]; then 78 | CLIEN=openclash 79 | elif [ "$c" = "4" ]; then 80 | CLIEN=clash 81 | elif [ "$c" = "3" ]; then 82 | CLIEN=shadowsocksr 83 | elif [ "$c" = "2" ]; then 84 | CLIEN=passwall2 85 | else 86 | CLIEN=passwall 87 | fi 88 | echo $CLIEN 89 | } 90 | 91 | handle_err() { 92 | if [ "$pause" = "true" ] ; then 93 | echo "Restore background process." 94 | proxy=$(GetProxName $clien) 95 | /etc/init.d/$proxy start 96 | fi 97 | } 98 | 99 | #trap handle_err EXIT 100 | trap handle_err HUP INT TERM EXIT 101 | CLIEN=$(GetProxName $clien) 102 | ps -ef | grep $CLIEN | grep -v "grep" >/dev/null 103 | 104 | if [ $? = 1 ]; then 105 | /etc/init.d/$CLIEN start 106 | fi 107 | 108 | if [ -z $ipfile ]; then 109 | echo "1.Download ip file." 110 | for i in {1..3}; do 111 | wget -O $ipzipfile https://zip.baipiao.eu.org 112 | 113 | if [ $? != 0 ]; then 114 | echo "get ip file failed, try again" 115 | sleep 1 116 | continue 117 | else 118 | echo "downloaded." 119 | break 120 | fi 121 | done 122 | 123 | if [ -e $ipzipfile ]; then 124 | unzip -o $ipzipfile 125 | else 126 | echo "Can't download the ip zip file, Check whether the agent software is disabled." 127 | fi 128 | 129 | echo "2.Select the ip address of the desired port." 130 | port=$(yq eval ".CF_ADDR" $configfile) 131 | if [ -z $port ]; then 132 | port=443 133 | fi 134 | 135 | for file in $(find . -type f -name "*-[0-1]-$port.txt"); do 136 | echo "handling: $file" 137 | cat "$file" >>tmp.txt 138 | done 139 | 140 | if [ -e tmp.txt ]; then 141 | cat tmp.txt | sort -u >ip.txt 142 | rm -rf tmp.txt 143 | fi 144 | fi 145 | 146 | echo "Run scripts to test speed and update dns records." 147 | CFST_P=$CFST_DN 148 | #判断工作模式 149 | if [ "$IP_ADDR" = "ipv6" ]; then 150 | if [ ! -f "ipv6.txt" ]; then 151 | echo "当前工作模式为ipv6,但该目录下没有【ipv6.txt】,请配置【ipv6.txt】。下载地址:https://github.com/XIU2/CloudflareSpeedTest/releases" 152 | exit 2 153 | else 154 | echo "当前工作模式为ipv6" 155 | fi 156 | else 157 | echo "当前工作模式为ipv4" 158 | fi 159 | 160 | #读取配置文件中的客户端 161 | CLIEN=$(GetProxName $clien) 162 | 163 | #判断是否停止科学上网服务 164 | if [ "$pause" = "false" ]; then 165 | echo "按要求未停止科学上网服务" 166 | else 167 | /etc/init.d/$CLIEN stop 168 | echo "已停止$CLIEN" 169 | fi 170 | 171 | #判断是否配置测速地址 172 | if [[ "$CFST_URL" == http* ]]; then 173 | CFST_URL_R="-url $CFST_URL" 174 | else 175 | CFST_URL_R="" 176 | fi 177 | 178 | #判断是否使用国家代码来筛选 179 | if [[ "$CCFLAG" == "true" ]]; then 180 | USECC="-c " 181 | else 182 | USECC="" 183 | fi 184 | 185 | if [ ! -z "$CCODE" ]; then 186 | CCODE_IS="-cc $CCODE " 187 | else 188 | CCODE_IS="" 189 | fi 190 | 191 | if [ ! -z "$CF_ADDR" ]; then 192 | CF_ADDR=" -tp $CF_ADDR" 193 | else 194 | CF_ADDR=" -tp 443" 195 | fi 196 | 197 | if [ -z "$ipfile" ]; then 198 | ipflag="" 199 | else 200 | ipflag="-f " 201 | fi 202 | 203 | if [ "$IP_ADDR" = "ipv6" ]; then 204 | #开始优选IPv6 205 | ./CloudflareST $CFST_URL_R -t $CFST_T -n $CFST_N -dn $CFST_DN -tl $CFST_TL -tll $CFST_TLL -sl $CFST_SL -p $CFST_P $ipflag $ipfile $USECC $CCODE_IS 206 | echo "./CloudflareST $CFST_URL_R -t $CFST_T -n $CFST_N -dn $CFST_DN -tl $CFST_TL -tll $CFST_TLL -sl $CFST_SL -p $CFST_P $ipflag $ipfile $CF_ADDR $USECC $CCODE_IS" 207 | else 208 | #开始优选IPv4 209 | echo "./CloudflareST $CFST_URL_R -t $CFST_T -n $CFST_N -dn $CFST_DN -tl $CFST_TL -tll $CFST_TLL -sl $CFST_SL -p $CFST_P $ipflag $ipfile $CF_ADDR $USECC $CCODE_IS" 210 | ./CloudflareST $CFST_URL_R -t $CFST_T -n $CFST_N -dn $CFST_DN -tl $CFST_TL -tll $CFST_TLL -sl $CFST_SL -p $CFST_P $ipflag $ipfile $CF_ADDR $USECC $CCODE_IS 211 | fi 212 | echo "测速完毕" 213 | if [ "$pause" = "false" ]; then 214 | echo "按要求未重启科学上网服务" 215 | sleep 3s 216 | else 217 | /etc/init.d/$CLIEN restart 218 | echo "已重启$CLIEN" 219 | echo "为保证cloudflareAPI连接正常 将在3秒后开始更新域名解析" 220 | sleep 3s 221 | fi 222 | 223 | if yq eval 'has("cloudflare")' $configfile; then 224 | 225 | length=$(yq eval '.cloudflare | length' $configfile) 226 | 227 | echo "length:$length" 228 | for ((li = 0; li < $length; li++)); 229 | do 230 | echo "Configuration Group $((li + 1)):" 231 | x_email=$(yq eval ".cloudflare[$li].x_email" $configfile) 232 | echo "x_email: $x_email" 233 | hostname=$(yq eval ".cloudflare[$li].hostname" $configfile) 234 | echo "hostname: $hostname" 235 | zone_id=$(yq eval ".cloudflare[$li].zone_id" $configfile) 236 | #echo "zone_id:$zone_id" 237 | api_key=$(yq eval ".cloudflare[$li].api_key" $configfile) 238 | #echo "api_key:$api_key" 239 | ChkHostnameAndCoutryCode 240 | if [ $? -eq 1 ]; then 241 | echo "ChkHostnameAndCoutryCode() error!" 242 | exit 1 243 | fi 244 | 245 | source ./ddns/cf_ddns 246 | done 247 | 248 | fi 249 | 250 | #会生成一个名为informlog的临时文件作为推送的内容。 251 | pushmessage=$(cat informlog) 252 | echo $pushmessage 253 | 254 | if [ ! -z "$sendType" ]; then 255 | if [[ $sendType -eq 1 ]]; then 256 | source ./msg/cf_push 257 | elif [[ $sendType -eq 2 ]]; then 258 | source ./msg/wxsend_jiang.sh 259 | elif [[ $sendType -eq 3 ]]; then 260 | source ./msg/cf_push 261 | source ./msg/wxsend_jiang.sh 262 | else 263 | echo "$sendType is invalid type!" 264 | fi 265 | fi 266 | -------------------------------------------------------------------------------- /task/download.go: -------------------------------------------------------------------------------- 1 | package task 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "io" 7 | "net" 8 | "net/http" 9 | "sort" 10 | "strconv" 11 | "time" 12 | 13 | "github.com/XIU2/CloudflareSpeedTest/utils" 14 | 15 | "github.com/VividCortex/ewma" 16 | ) 17 | 18 | const ( 19 | bufferSize = 1024 20 | defaultURL = "https://cf.xiu2.xyz/url" 21 | defaultTimeout = 5 * time.Second 22 | defaultDisableDownload = false 23 | defaultTestNum = 10 24 | defaultMinSpeed float64 = 0.0 25 | ) 26 | 27 | var ( 28 | URL = defaultURL 29 | Timeout = defaultTimeout 30 | Disable = defaultDisableDownload 31 | 32 | TestCount = defaultTestNum 33 | MinSpeed = defaultMinSpeed 34 | ) 35 | 36 | func checkDownloadDefault() { 37 | if URL == "" { 38 | URL = defaultURL 39 | } 40 | if Timeout <= 0 { 41 | Timeout = defaultTimeout 42 | } 43 | if TestCount <= 0 { 44 | TestCount = defaultTestNum 45 | } 46 | if MinSpeed <= 0.0 { 47 | MinSpeed = defaultMinSpeed 48 | } 49 | } 50 | 51 | func TestDownloadSpeedByCountry(ipSet utils.PingDelaySet) (speedSet utils.DownloadSpeedSet) { 52 | checkDownloadDefault() 53 | if Disable { 54 | return utils.DownloadSpeedSet(ipSet) 55 | } 56 | if len(ipSet) <= 0 { // IP数组长度(IP数量) 大于 0 时才会继续下载测速 57 | fmt.Println("\n[信息] 延迟测速结果 IP 数量为 0,跳过下载测速。") 58 | return 59 | } 60 | //按国家代号划分分片 61 | countryMap := make(map[string]utils.PingDelaySet) 62 | for _, ip := range ipSet { 63 | country := ip.Country 64 | if _, ok := countryMap[country]; !ok { 65 | countryMap[country] = make(utils.PingDelaySet, 0) 66 | } 67 | countryMap[country] = append(countryMap[country], ip) 68 | } 69 | 70 | // 按照每个国家分批进行测速 71 | for country, countrySet := range countryMap { 72 | testNum := TestCount 73 | barCount := TestCount 74 | if len(countrySet) < TestCount || MinSpeed > 0 { // 如果IP数组长度(IP数量) 小于下载测速数量(-dn),则次数修正为IP数 75 | testNum = len(countrySet) 76 | } 77 | if testNum < barCount { 78 | barCount = testNum 79 | } 80 | 81 | fmt.Printf("\n[信息] 开始测速 %s 的 IP,数量:%d\n", country, len(countrySet)) 82 | bar_a := len(strconv.Itoa(len(countrySet))) 83 | bar_b := " " 84 | for i := 0; i < bar_a; i++ { 85 | bar_b += " " 86 | } 87 | bar := utils.NewBar(barCount, bar_b, "") 88 | countryspeedSet := make(utils.DownloadSpeedSet, 0) 89 | for i := 0; i < testNum; i++ { 90 | speed := downloadHandler(countrySet[i].IP) 91 | countrySet[i].DownloadSpeed = speed 92 | // 在每个 IP 下载测速后,以 [下载速度下限] 条件过滤结果 93 | if speed >= MinSpeed*1024*1024 { 94 | bar.Grow(1, "") 95 | countryspeedSet = append(countryspeedSet, countrySet[i]) // 高于下载速度下限时,添加到新数组中 96 | if len(countryspeedSet) == TestCount { // 凑够满足条件的 IP 时(下载测速数量 -dn),就跳出循环 97 | break 98 | } 99 | } 100 | } 101 | bar.Done() 102 | if len(countryspeedSet) == 0 { 103 | countryspeedSet = utils.DownloadSpeedSet(countrySet) 104 | } 105 | speedSet = append(speedSet, countryspeedSet...) 106 | } 107 | 108 | return 109 | } 110 | 111 | func TestDownloadSpeed(ipSet utils.PingDelaySet) (speedSet utils.DownloadSpeedSet) { 112 | checkDownloadDefault() 113 | if Disable { 114 | return utils.DownloadSpeedSet(ipSet) 115 | } 116 | if len(ipSet) <= 0 { // IP数组长度(IP数量) 大于 0 时才会继续下载测速 117 | fmt.Println("\n[信息] 延迟测速结果 IP 数量为 0,跳过下载测速。") 118 | return 119 | } 120 | testNum := TestCount 121 | if len(ipSet) < TestCount || MinSpeed > 0 { // 如果IP数组长度(IP数量) 小于下载测速数量(-dn),则次数修正为IP数 122 | testNum = len(ipSet) 123 | } 124 | if testNum < TestCount { 125 | TestCount = testNum 126 | } 127 | 128 | fmt.Printf("开始下载测速(下限:%.2f MB/s, 数量:%d, 队列:%d)\n", MinSpeed, TestCount, testNum) 129 | // 控制 下载测速进度条 与 延迟测速进度条 长度一致(强迫症) 130 | bar_a := len(strconv.Itoa(len(ipSet))) 131 | bar_b := " " 132 | for i := 0; i < bar_a; i++ { 133 | bar_b += " " 134 | } 135 | bar := utils.NewBar(TestCount, bar_b, "") 136 | for i := 0; i < testNum; i++ { 137 | speed := downloadHandler(ipSet[i].IP) 138 | ipSet[i].DownloadSpeed = speed 139 | // 在每个 IP 下载测速后,以 [下载速度下限] 条件过滤结果 140 | if speed >= MinSpeed*1024*1024 { 141 | bar.Grow(1, "") 142 | speedSet = append(speedSet, ipSet[i]) // 高于下载速度下限时,添加到新数组中 143 | if len(speedSet) == TestCount { // 凑够满足条件的 IP 时(下载测速数量 -dn),就跳出循环 144 | break 145 | } 146 | } 147 | } 148 | bar.Done() 149 | if len(speedSet) == 0 { // 没有符合速度限制的数据,返回所有测试数据 150 | speedSet = utils.DownloadSpeedSet(ipSet) 151 | } 152 | // 按速度排序 153 | sort.Sort(speedSet) 154 | return 155 | } 156 | 157 | func getDialContext(ip *net.IPAddr) func(ctx context.Context, network, address string) (net.Conn, error) { 158 | var fakeSourceAddr string 159 | if isIPv4(ip.String()) { 160 | fakeSourceAddr = fmt.Sprintf("%s:%d", ip.String(), TCPPort) 161 | } else { 162 | fakeSourceAddr = fmt.Sprintf("[%s]:%d", ip.String(), TCPPort) 163 | } 164 | return func(ctx context.Context, network, address string) (net.Conn, error) { 165 | return (&net.Dialer{}).DialContext(ctx, network, fakeSourceAddr) 166 | } 167 | } 168 | 169 | // return download Speed 170 | func downloadHandler(ip *net.IPAddr) float64 { 171 | client := &http.Client{ 172 | Transport: &http.Transport{DialContext: getDialContext(ip)}, 173 | Timeout: Timeout, 174 | CheckRedirect: func(req *http.Request, via []*http.Request) error { 175 | if len(via) > 10 { // 限制最多重定向 10 次 176 | return http.ErrUseLastResponse 177 | } 178 | if req.Header.Get("Referer") == defaultURL { // 当使用默认下载测速地址时,重定向不携带 Referer 179 | req.Header.Del("Referer") 180 | } 181 | return nil 182 | }, 183 | } 184 | req, err := http.NewRequest("GET", URL, nil) 185 | if err != nil { 186 | return 0.0 187 | } 188 | 189 | req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36") 190 | 191 | response, err := client.Do(req) 192 | if err != nil { 193 | return 0.0 194 | } 195 | defer response.Body.Close() 196 | if response.StatusCode != 200 { 197 | return 0.0 198 | } 199 | timeStart := time.Now() // 开始时间(当前) 200 | timeEnd := timeStart.Add(Timeout) // 加上下载测速时间得到的结束时间 201 | 202 | contentLength := response.ContentLength // 文件大小 203 | buffer := make([]byte, bufferSize) 204 | 205 | var ( 206 | contentRead int64 = 0 207 | timeSlice = Timeout / 100 208 | timeCounter = 1 209 | lastContentRead int64 = 0 210 | ) 211 | 212 | var nextTime = timeStart.Add(timeSlice * time.Duration(timeCounter)) 213 | e := ewma.NewMovingAverage() 214 | 215 | // 循环计算,如果文件下载完了(两者相等),则退出循环(终止测速) 216 | for contentLength != contentRead { 217 | currentTime := time.Now() 218 | if currentTime.After(nextTime) { 219 | timeCounter++ 220 | nextTime = timeStart.Add(timeSlice * time.Duration(timeCounter)) 221 | e.Add(float64(contentRead - lastContentRead)) 222 | lastContentRead = contentRead 223 | } 224 | // 如果超出下载测速时间,则退出循环(终止测速) 225 | if currentTime.After(timeEnd) { 226 | break 227 | } 228 | bufferRead, err := response.Body.Read(buffer) 229 | if err != nil { 230 | if err != io.EOF { // 如果文件下载过程中遇到报错(如 Timeout),且并不是因为文件下载完了,则退出循环(终止测速) 231 | break 232 | } else if contentLength == -1 { // 文件下载完成 且 文件大小未知,则退出循环(终止测速),例如:https://speed.cloudflare.com/__down?bytes=200000000 这样的,如果在 10 秒内就下载完成了,会导致测速结果明显偏低甚至显示为 0.00(下载速度太快时) 233 | break 234 | } 235 | // 获取上个时间片 236 | last_time_slice := timeStart.Add(timeSlice * time.Duration(timeCounter-1)) 237 | // 下载数据量 / (用当前时间 - 上个时间片/ 时间片) 238 | e.Add(float64(contentRead-lastContentRead) / (float64(currentTime.Sub(last_time_slice)) / float64(timeSlice))) 239 | } 240 | contentRead += int64(bufferRead) 241 | } 242 | return e.Value() / (Timeout.Seconds() / 120) 243 | } 244 | -------------------------------------------------------------------------------- /task/httping.go: -------------------------------------------------------------------------------- 1 | package task 2 | 3 | import ( 4 | //"crypto/tls" 5 | //"fmt" 6 | "io" 7 | "log" 8 | "net" 9 | "net/http" 10 | "regexp" 11 | "strings" 12 | "sync" 13 | "time" 14 | ) 15 | 16 | var ( 17 | Httping bool 18 | HttpingStatusCode int 19 | HttpingCFColo string 20 | HttpingCFColomap *sync.Map 21 | OutRegexp = regexp.MustCompile(`[A-Z]{3}`) 22 | ) 23 | 24 | // pingReceived pingTotalTime 25 | func (p *Ping) httping(ip *net.IPAddr) (int, time.Duration) { 26 | hc := http.Client{ 27 | Timeout: time.Second * 2, 28 | Transport: &http.Transport{ 29 | DialContext: getDialContext(ip), 30 | //TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // 跳过证书验证 31 | }, 32 | CheckRedirect: func(req *http.Request, via []*http.Request) error { 33 | return http.ErrUseLastResponse // 阻止重定向 34 | }, 35 | } 36 | 37 | // 先访问一次获得 HTTP 状态码 及 Cloudflare Colo 38 | { 39 | requ, err := http.NewRequest(http.MethodHead, URL, nil) 40 | if err != nil { 41 | return 0, 0 42 | } 43 | requ.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36") 44 | resp, err := hc.Do(requ) 45 | if err != nil { 46 | return 0, 0 47 | } 48 | defer resp.Body.Close() 49 | 50 | //fmt.Println("IP:", ip, "StatusCode:", resp.StatusCode, resp.Request.URL) 51 | // 如果未指定的 HTTP 状态码,或指定的状态码不合规,则默认只认为 200、301、302 才算 HTTPing 通过 52 | if HttpingStatusCode == 0 || HttpingStatusCode < 100 && HttpingStatusCode > 599 { 53 | if resp.StatusCode != 200 && resp.StatusCode != 301 && resp.StatusCode != 302 { 54 | return 0, 0 55 | } 56 | } else { 57 | if resp.StatusCode != HttpingStatusCode { 58 | return 0, 0 59 | } 60 | } 61 | 62 | io.Copy(io.Discard, resp.Body) 63 | 64 | // 只有指定了地区才匹配机场三字码 65 | if HttpingCFColo != "" { 66 | // 通过头部 Server 值判断是 Cloudflare 还是 AWS CloudFront 并设置 cfRay 为各自的机场三字码完整内容 67 | cfRay := func() string { 68 | if resp.Header.Get("Server") == "cloudflare" { 69 | return resp.Header.Get("CF-RAY") // 示例 cf-ray: 7bd32409eda7b020-SJC 70 | } 71 | return resp.Header.Get("x-amz-cf-pop") // 示例 X-Amz-Cf-Pop: SIN52-P1 72 | }() 73 | colo := p.getColo(cfRay) 74 | if colo == "" { // 没有匹配到三字码或不符合指定地区则直接结束该 IP 测试 75 | return 0, 0 76 | } 77 | } 78 | 79 | } 80 | 81 | // 循环测速计算延迟 82 | success := 0 83 | var delay time.Duration 84 | for i := 0; i < PingTimes; i++ { 85 | requ, err := http.NewRequest(http.MethodHead, URL, nil) 86 | if err != nil { 87 | log.Fatal("意外的错误,情报告:", err) 88 | return 0, 0 89 | } 90 | requ.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36") 91 | if i == PingTimes-1 { 92 | requ.Header.Set("Connection", "close") 93 | } 94 | startTime := time.Now() 95 | resp, err := hc.Do(requ) 96 | if err != nil { 97 | continue 98 | } 99 | success++ 100 | io.Copy(io.Discard, resp.Body) 101 | _ = resp.Body.Close() 102 | duration := time.Since(startTime) 103 | delay += duration 104 | 105 | } 106 | 107 | return success, delay 108 | 109 | } 110 | 111 | func MapColoMap() *sync.Map { 112 | if HttpingCFColo == "" { 113 | return nil 114 | } 115 | // 将参数指定的地区三字码转为大写并格式化 116 | colos := strings.Split(strings.ToUpper(HttpingCFColo), ",") 117 | colomap := &sync.Map{} 118 | for _, colo := range colos { 119 | colomap.Store(colo, colo) 120 | } 121 | return colomap 122 | } 123 | 124 | func (p *Ping) getColo(b string) string { 125 | if b == "" { 126 | return "" 127 | } 128 | // 正则匹配并返回 机场三字码 129 | out := OutRegexp.FindString(b) 130 | 131 | if HttpingCFColomap == nil { 132 | return out 133 | } 134 | // 匹配 机场三字码 是否为指定的地区 135 | _, ok := HttpingCFColomap.Load(out) 136 | if ok { 137 | return out 138 | } 139 | 140 | return "" 141 | } 142 | -------------------------------------------------------------------------------- /task/ip.go: -------------------------------------------------------------------------------- 1 | package task 2 | 3 | import ( 4 | "bufio" 5 | "log" 6 | "math/rand" 7 | "net" 8 | "os" 9 | "strconv" 10 | "strings" 11 | "time" 12 | ) 13 | 14 | const defaultInputFile = "ip.txt" 15 | 16 | var ( 17 | // TestAll test all ip 18 | TestAll = false 19 | // IPFile is the filename of IP Rangs 20 | IPFile = defaultInputFile 21 | IPText string 22 | ) 23 | 24 | func InitRandSeed() { 25 | rand.Seed(time.Now().UnixNano()) 26 | } 27 | 28 | func isIPv4(ip string) bool { 29 | return strings.Contains(ip, ".") 30 | } 31 | 32 | func randIPEndWith(num byte) byte { 33 | if num == 0 { // 对于 /32 这种单独的 IP 34 | return byte(0) 35 | } 36 | return byte(rand.Intn(int(num))) 37 | } 38 | 39 | type IPRanges struct { 40 | ips []*net.IPAddr 41 | mask string 42 | firstIP net.IP 43 | ipNet *net.IPNet 44 | } 45 | 46 | func newIPRanges() *IPRanges { 47 | return &IPRanges{ 48 | ips: make([]*net.IPAddr, 0), 49 | } 50 | } 51 | 52 | // 如果是单独 IP 则加上子网掩码,反之则获取子网掩码(r.mask) 53 | func (r *IPRanges) fixIP(ip string) string { 54 | // 如果不含有 '/' 则代表不是 IP 段,而是一个单独的 IP,因此需要加上 /32 /128 子网掩码 55 | if i := strings.IndexByte(ip, '/'); i < 0 { 56 | if isIPv4(ip) { 57 | r.mask = "/32" 58 | } else { 59 | r.mask = "/128" 60 | } 61 | ip += r.mask 62 | } else { 63 | r.mask = ip[i:] 64 | } 65 | return ip 66 | } 67 | 68 | // 解析 IP 段,获得 IP、IP 范围、子网掩码 69 | func (r *IPRanges) parseCIDR(ip string) { 70 | var err error 71 | if r.firstIP, r.ipNet, err = net.ParseCIDR(r.fixIP(ip)); err != nil { 72 | log.Fatalln("ParseCIDR err", err) 73 | } 74 | } 75 | 76 | func (r *IPRanges) appendIPv4(d byte) { 77 | r.appendIP(net.IPv4(r.firstIP[12], r.firstIP[13], r.firstIP[14], d)) 78 | } 79 | 80 | func (r *IPRanges) appendIP(ip net.IP) { 81 | r.ips = append(r.ips, &net.IPAddr{IP: ip}) 82 | } 83 | 84 | // 返回第四段 ip 的最小值及可用数目 85 | func (r *IPRanges) getIPRange() (minIP, hosts byte) { 86 | minIP = r.firstIP[15] & r.ipNet.Mask[3] // IP 第四段最小值 87 | 88 | // 根据子网掩码获取主机数量 89 | m := net.IPv4Mask(255, 255, 255, 255) 90 | for i, v := range r.ipNet.Mask { 91 | m[i] ^= v 92 | } 93 | total, _ := strconv.ParseInt(m.String(), 16, 32) // 总可用 IP 数 94 | if total > 255 { // 矫正 第四段 可用 IP 数 95 | hosts = 255 96 | return 97 | } 98 | hosts = byte(total) 99 | return 100 | } 101 | 102 | func (r *IPRanges) chooseIPv4() { 103 | if r.mask == "/32" { // 单个 IP 则无需随机,直接加入自身即可 104 | r.appendIP(r.firstIP) 105 | } else { 106 | minIP, hosts := r.getIPRange() // 返回第四段 IP 的最小值及可用数目 107 | for r.ipNet.Contains(r.firstIP) { // 只要该 IP 没有超出 IP 网段范围,就继续循环随机 108 | if TestAll { // 如果是测速全部 IP 109 | for i := 0; i <= int(hosts); i++ { // 遍历 IP 最后一段最小值到最大值 110 | r.appendIPv4(byte(i) + minIP) 111 | } 112 | } else { // 随机 IP 的最后一段 0.0.0.X 113 | r.appendIPv4(minIP + randIPEndWith(hosts)) 114 | } 115 | r.firstIP[14]++ // 0.0.(X+1).X 116 | if r.firstIP[14] == 0 { 117 | r.firstIP[13]++ // 0.(X+1).X.X 118 | if r.firstIP[13] == 0 { 119 | r.firstIP[12]++ // (X+1).X.X.X 120 | } 121 | } 122 | } 123 | } 124 | } 125 | 126 | func (r *IPRanges) chooseIPv6() { 127 | if r.mask == "/128" { // 单个 IP 则无需随机,直接加入自身即可 128 | r.appendIP(r.firstIP) 129 | } else { 130 | var tempIP uint8 // 临时变量,用于记录前一位的值 131 | for r.ipNet.Contains(r.firstIP) { // 只要该 IP 没有超出 IP 网段范围,就继续循环随机 132 | r.firstIP[15] = randIPEndWith(255) // 随机 IP 的最后一段 133 | r.firstIP[14] = randIPEndWith(255) // 随机 IP 的最后一段 134 | 135 | targetIP := make([]byte, len(r.firstIP)) 136 | copy(targetIP, r.firstIP) 137 | r.appendIP(targetIP) // 加入 IP 地址池 138 | 139 | for i := 13; i >= 0; i-- { // 从倒数第三位开始往前随机 140 | tempIP = r.firstIP[i] // 保存前一位的值 141 | r.firstIP[i] += randIPEndWith(255) // 随机 0~255,加到当前位上 142 | if r.firstIP[i] >= tempIP { // 如果当前位的值大于等于前一位的值,说明随机成功了,可以退出该循环 143 | break 144 | } 145 | } 146 | } 147 | } 148 | } 149 | 150 | func loadIPRanges() []*net.IPAddr { 151 | ranges := newIPRanges() 152 | if IPText != "" { // 从参数中获取 IP 段数据 153 | IPs := strings.Split(IPText, ",") // 以逗号分隔为数组并循环遍历 154 | for _, IP := range IPs { 155 | IP = strings.TrimSpace(IP) // 去除首尾的空白字符(空格、制表符、换行符等) 156 | if IP == "" { // 跳过空的(即开头、结尾或连续多个 ,, 的情况) 157 | continue 158 | } 159 | ranges.parseCIDR(IP) // 解析 IP 段,获得 IP、IP 范围、子网掩码 160 | if isIPv4(IP) { // 生成要测速的所有 IPv4 / IPv6 地址(单个/随机/全部) 161 | ranges.chooseIPv4() 162 | } else { 163 | ranges.chooseIPv6() 164 | } 165 | } 166 | } else { // 从文件中获取 IP 段数据 167 | if IPFile == "" { 168 | IPFile = defaultInputFile 169 | } 170 | file, err := os.Open(IPFile) 171 | if err != nil { 172 | log.Fatal(err) 173 | } 174 | defer file.Close() 175 | scanner := bufio.NewScanner(file) 176 | for scanner.Scan() { // 循环遍历文件每一行 177 | line := strings.TrimSpace(scanner.Text()) // 去除首尾的空白字符(空格、制表符、换行符等) 178 | if line == "" { // 跳过空行 179 | continue 180 | } 181 | ranges.parseCIDR(line) // 解析 IP 段,获得 IP、IP 范围、子网掩码 182 | if isIPv4(line) { // 生成要测速的所有 IPv4 / IPv6 地址(单个/随机/全部) 183 | ranges.chooseIPv4() 184 | } else { 185 | ranges.chooseIPv6() 186 | } 187 | } 188 | } 189 | return ranges.ips 190 | } 191 | -------------------------------------------------------------------------------- /task/tcping.go: -------------------------------------------------------------------------------- 1 | package task 2 | 3 | import ( 4 | "fmt" 5 | "net" 6 | "sort" 7 | "strconv" 8 | "sync" 9 | "time" 10 | 11 | "github.com/XIU2/CloudflareSpeedTest/utils" 12 | ) 13 | 14 | const ( 15 | tcpConnectTimeout = time.Second * 1 16 | maxRoutine = 1000 17 | defaultRoutines = 200 18 | defaultPort = 443 19 | defaultPingTimes = 4 20 | ) 21 | 22 | var ( 23 | Routines = defaultRoutines 24 | TCPPort int = defaultPort 25 | PingTimes int = defaultPingTimes 26 | ) 27 | 28 | type Ping struct { 29 | wg *sync.WaitGroup 30 | m *sync.Mutex 31 | ips []*net.IPAddr 32 | csv utils.PingDelaySet 33 | control chan bool 34 | bar *utils.Bar 35 | } 36 | 37 | func checkPingDefault() { 38 | if Routines <= 0 { 39 | Routines = defaultRoutines 40 | } 41 | if TCPPort <= 0 || TCPPort >= 65535 { 42 | TCPPort = defaultPort 43 | } 44 | if PingTimes <= 0 { 45 | PingTimes = defaultPingTimes 46 | } 47 | } 48 | 49 | func NewPing() *Ping { 50 | checkPingDefault() 51 | ips := loadIPRanges() 52 | return &Ping{ 53 | wg: &sync.WaitGroup{}, 54 | m: &sync.Mutex{}, 55 | ips: ips, 56 | csv: make(utils.PingDelaySet, 0), 57 | control: make(chan bool, Routines), 58 | bar: utils.NewBar(len(ips), "可用:", ""), 59 | } 60 | } 61 | 62 | func (p *Ping) Run() utils.PingDelaySet { 63 | if len(p.ips) == 0 { 64 | return p.csv 65 | } 66 | if Httping { 67 | fmt.Printf("开始延迟测速(模式:HTTP, 端口:%d, 范围:%v ~ %v ms, 丢包:%.2f)\n", TCPPort, utils.InputMinDelay.Milliseconds(), utils.InputMaxDelay.Milliseconds(), utils.InputMaxLossRate) 68 | } else { 69 | fmt.Printf("开始延迟测速(模式:TCP, 端口:%d, 范围:%v ~ %v ms, 丢包:%.2f)\n", TCPPort, utils.InputMinDelay.Milliseconds(), utils.InputMaxDelay.Milliseconds(), utils.InputMaxLossRate) 70 | } 71 | for _, ip := range p.ips { 72 | p.wg.Add(1) 73 | p.control <- false 74 | go p.start(ip) 75 | } 76 | p.wg.Wait() 77 | p.bar.Done() 78 | sort.Sort(p.csv) 79 | return p.csv 80 | } 81 | 82 | func (p *Ping) start(ip *net.IPAddr) { 83 | defer p.wg.Done() 84 | p.tcpingHandler(ip) 85 | <-p.control 86 | } 87 | 88 | // bool connectionSucceed float32 time 89 | func (p *Ping) tcping(ip *net.IPAddr) (bool, time.Duration) { 90 | startTime := time.Now() 91 | var fullAddress string 92 | if isIPv4(ip.String()) { 93 | fullAddress = fmt.Sprintf("%s:%d", ip.String(), TCPPort) 94 | } else { 95 | fullAddress = fmt.Sprintf("[%s]:%d", ip.String(), TCPPort) 96 | } 97 | conn, err := net.DialTimeout("tcp", fullAddress, tcpConnectTimeout) 98 | if err != nil { 99 | return false, 0 100 | } 101 | defer conn.Close() 102 | duration := time.Since(startTime) 103 | return true, duration 104 | 105 | } 106 | 107 | // pingReceived pingTotalTime 108 | func (p *Ping) checkConnection(ip *net.IPAddr) (recv int, totalDelay time.Duration) { 109 | if Httping { 110 | recv, totalDelay = p.httping(ip) 111 | return 112 | } 113 | for i := 0; i < PingTimes; i++ { 114 | if ok, delay := p.tcping(ip); ok { 115 | recv++ 116 | totalDelay += delay 117 | } 118 | } 119 | return 120 | } 121 | 122 | func (p *Ping) appendIPData(data *utils.PingData) { 123 | p.m.Lock() 124 | defer p.m.Unlock() 125 | p.csv = append(p.csv, utils.CloudflareIPData{ 126 | PingData: data, 127 | }) 128 | } 129 | 130 | // handle tcping 131 | func (p *Ping) tcpingHandler(ip *net.IPAddr) { 132 | recv, totalDlay := p.checkConnection(ip) 133 | nowAble := len(p.csv) 134 | if recv != 0 { 135 | nowAble++ 136 | } 137 | p.bar.Grow(1, strconv.Itoa(nowAble)) 138 | if recv == 0 { 139 | return 140 | } 141 | data := &utils.PingData{ 142 | IP: ip, 143 | Sended: PingTimes, 144 | Received: recv, 145 | Delay: totalDlay / time.Duration(recv), 146 | } 147 | p.appendIPData(data) 148 | } 149 | -------------------------------------------------------------------------------- /trojan_workers/_worker.js: -------------------------------------------------------------------------------- 1 | // src/worker.js 2 | import { connect } from "cloudflare:sockets"; 3 | let sha224Password = '7e89e622d89becc4299c2d74494b9fb15759f2b0ff47b20eeae867e2'; 4 | let pwd = 'abc123333' 5 | const proxyIPs = ["cdn.xn--b6gac.eu.org"]; //workers.cloudflare.cyou bestproxy.onecf.eu.org cdn-all.xn--b6gac.eu.org cdn.xn--b6gac.eu.org 6 | let proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)]; 7 | let defaultAddr='www.visa.com.sg' 8 | 9 | if (!isValidSHA224(sha224Password)) { 10 | throw new Error('sha224Password is not valid'); 11 | } 12 | 13 | function getprotocol() { 14 | let matter = ['t','r','o','j','a','n'] 15 | let result='' 16 | for (let i = 0; i < matter.length; i++) { 17 | result += matter[i]; 18 | } 19 | return result; 20 | } 21 | 22 | 23 | export default { 24 | /** 25 | * @param {import("@cloudflare/workers-types").Request} request 26 | * @param {{SHA224PASS: string, PROXYIP: string}} env 27 | * @param {import("@cloudflare/workers-types").ExecutionContext} ctx 28 | * @returns {Promise} 29 | */ 30 | async fetch(request, env, ctx) { 31 | try { 32 | proxyIP = env.PROXYIP || proxyIP; 33 | pwd = env.PASSWORD || pwd 34 | if ('PASSWORD' in env) { 35 | sha224Password = sha256.sha224(env.PASSWORD) 36 | } 37 | console.log('pass:'+sha224Password) 38 | const upgradeHeader = request.headers.get("Upgrade"); 39 | if (!upgradeHeader || upgradeHeader !== "websocket") { 40 | const url = new URL(request.url); 41 | switch (url.pathname) { 42 | case `/${pwd}`:{ 43 | const host = request.headers.get('Host'); 44 | if ( 'PROXYIP' in env) { 45 | return new Response(getprotocol() + `://` + pwd + `@${host}:443/?type=ws&host=${host}&security=tls#${host}`, { 46 | status: 200, 47 | headers: { 48 | "Content-Type": "text/plain;charset=utf-8", 49 | } 50 | }) 51 | }else{ 52 | return new Response(getprotocol() + `://` + pwd + `@${defaultAddr}:443/?type=ws&host=${host}&security=tls#${host}`, { 53 | status: 200, 54 | headers: { 55 | "Content-Type": "text/plain;charset=utf-8", 56 | } 57 | }) 58 | } 59 | 60 | }; 61 | default: 62 | return new Response("404 Not found", { status: 404 }); 63 | } 64 | } else { 65 | return await trojanOverWSHandler(request); 66 | } 67 | } catch (err) { 68 | let e = err; 69 | return new Response(e.toString()); 70 | } 71 | } 72 | }; 73 | 74 | async function trojanOverWSHandler(request) { 75 | const webSocketPair = new WebSocketPair(); 76 | const [client, webSocket] = Object.values(webSocketPair); 77 | webSocket.accept(); 78 | let address = ""; 79 | let portWithRandomLog = ""; 80 | const log = (info, event) => { 81 | console.log(`[${address}:${portWithRandomLog}] ${info}`, event || ""); 82 | }; 83 | const earlyDataHeader = request.headers.get("sec-websocket-protocol") || ""; 84 | const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log); 85 | let remoteSocketWapper = { 86 | value: null 87 | }; 88 | let udpStreamWrite = null; 89 | readableWebSocketStream.pipeTo(new WritableStream({ 90 | async write(chunk, controller) { 91 | if (udpStreamWrite) { 92 | return udpStreamWrite(chunk); 93 | } 94 | if (remoteSocketWapper.value) { 95 | const writer = remoteSocketWapper.value.writable.getWriter(); 96 | await writer.write(chunk); 97 | writer.releaseLock(); 98 | return; 99 | } 100 | const { 101 | hasError, 102 | message, 103 | portRemote = 443, 104 | addressRemote = "", 105 | rawClientData 106 | } = await parseTrojanHeader(chunk); 107 | address = addressRemote; 108 | portWithRandomLog = `${portRemote}--${Math.random()} tcp`; 109 | if (hasError) { 110 | throw new Error(message); 111 | return; 112 | } 113 | handleTCPOutBound(remoteSocketWapper, addressRemote, portRemote, rawClientData, webSocket, log); 114 | }, 115 | close() { 116 | log(`readableWebSocketStream is closed`); 117 | }, 118 | abort(reason) { 119 | log(`readableWebSocketStream is aborted`, JSON.stringify(reason)); 120 | } 121 | })).catch((err) => { 122 | log("readableWebSocketStream pipeTo error", err); 123 | }); 124 | return new Response(null, { 125 | status: 101, 126 | // @ts-ignore 127 | webSocket: client 128 | }); 129 | } 130 | 131 | async function parseTrojanHeader(buffer) { 132 | if (buffer.byteLength < 56) { 133 | return { 134 | hasError: true, 135 | message: "invalid data" 136 | }; 137 | } 138 | let crLfIndex = 56; 139 | if (new Uint8Array(buffer.slice(56, 57))[0] !== 0x0d || new Uint8Array(buffer.slice(57, 58))[0] !== 0x0a) { 140 | return { 141 | hasError: true, 142 | message: "invalid header format (missing CR LF)" 143 | }; 144 | } 145 | const password = new TextDecoder().decode(buffer.slice(0, crLfIndex)); 146 | if (password !== sha224Password) { 147 | return { 148 | hasError: true, 149 | message: "invalid password" 150 | }; 151 | } 152 | 153 | const socks5DataBuffer = buffer.slice(crLfIndex + 2); 154 | if (socks5DataBuffer.byteLength < 6) { 155 | return { 156 | hasError: true, 157 | message: "invalid SOCKS5 request data" 158 | }; 159 | } 160 | 161 | const view = new DataView(socks5DataBuffer); 162 | const cmd = view.getUint8(0); 163 | if (cmd !== 1) { 164 | return { 165 | hasError: true, 166 | message: "unsupported command, only TCP (CONNECT) is allowed" 167 | }; 168 | } 169 | 170 | const atype = view.getUint8(1); 171 | // 0x01: IPv4 address 172 | // 0x03: Domain name 173 | // 0x04: IPv6 address 174 | let addressLength = 0; 175 | let addressIndex = 2; 176 | let address = ""; 177 | switch (atype) { 178 | case 1: 179 | addressLength = 4; 180 | address = new Uint8Array( 181 | socks5DataBuffer.slice(addressIndex, addressIndex + addressLength) 182 | ).join("."); 183 | break; 184 | case 3: 185 | addressLength = new Uint8Array( 186 | socks5DataBuffer.slice(addressIndex, addressIndex + 1) 187 | )[0]; 188 | addressIndex += 1; 189 | address = new TextDecoder().decode( 190 | socks5DataBuffer.slice(addressIndex, addressIndex + addressLength) 191 | ); 192 | break; 193 | case 4: 194 | addressLength = 16; 195 | const dataView = new DataView(socks5DataBuffer.slice(addressIndex, addressIndex + addressLength)); 196 | const ipv6 = []; 197 | for (let i = 0; i < 8; i++) { 198 | ipv6.push(dataView.getUint16(i * 2).toString(16)); 199 | } 200 | address = ipv6.join(":"); 201 | break; 202 | default: 203 | return { 204 | hasError: true, 205 | message: `invalid addressType is ${atype}` 206 | }; 207 | } 208 | 209 | if (!address) { 210 | return { 211 | hasError: true, 212 | message: `address is empty, addressType is ${atype}` 213 | }; 214 | } 215 | 216 | const portIndex = addressIndex + addressLength; 217 | const portBuffer = socks5DataBuffer.slice(portIndex, portIndex + 2); 218 | const portRemote = new DataView(portBuffer).getUint16(0); 219 | return { 220 | hasError: false, 221 | addressRemote: address, 222 | portRemote, 223 | rawClientData: socks5DataBuffer.slice(portIndex + 4) 224 | }; 225 | } 226 | 227 | async function handleTCPOutBound(remoteSocket, addressRemote, portRemote, rawClientData, webSocket, log) { 228 | async function connectAndWrite(address, port) { 229 | const tcpSocket2 = connect({ 230 | hostname: address, 231 | port 232 | }); 233 | remoteSocket.value = tcpSocket2; 234 | log(`connected to ${address}:${port}`); 235 | const writer = tcpSocket2.writable.getWriter(); 236 | await writer.write(rawClientData); 237 | writer.releaseLock(); 238 | return tcpSocket2; 239 | } 240 | async function retry() { 241 | const tcpSocket2 = await connectAndWrite(proxyIP || addressRemote, portRemote); 242 | tcpSocket2.closed.catch((error) => { 243 | console.log("retry tcpSocket closed error", error); 244 | }).finally(() => { 245 | safeCloseWebSocket(webSocket); 246 | }); 247 | remoteSocketToWS(tcpSocket2, webSocket, null, log); 248 | } 249 | const tcpSocket = await connectAndWrite(addressRemote, portRemote); 250 | remoteSocketToWS(tcpSocket, webSocket, retry, log); 251 | } 252 | 253 | function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) { 254 | let readableStreamCancel = false; 255 | const stream = new ReadableStream({ 256 | start(controller) { 257 | webSocketServer.addEventListener("message", (event) => { 258 | if (readableStreamCancel) { 259 | return; 260 | } 261 | const message = event.data; 262 | controller.enqueue(message); 263 | }); 264 | webSocketServer.addEventListener("close", () => { 265 | safeCloseWebSocket(webSocketServer); 266 | if (readableStreamCancel) { 267 | return; 268 | } 269 | controller.close(); 270 | }); 271 | webSocketServer.addEventListener("error", (err) => { 272 | log("webSocketServer error"); 273 | controller.error(err); 274 | }); 275 | const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader); 276 | if (error) { 277 | controller.error(error); 278 | } else if (earlyData) { 279 | controller.enqueue(earlyData); 280 | } 281 | }, 282 | pull(controller) {}, 283 | cancel(reason) { 284 | if (readableStreamCancel) { 285 | return; 286 | } 287 | log(`readableStream was canceled, due to ${reason}`); 288 | readableStreamCancel = true; 289 | safeCloseWebSocket(webSocketServer); 290 | } 291 | }); 292 | return stream; 293 | } 294 | 295 | async function remoteSocketToWS(remoteSocket, webSocket, retry, log) { 296 | let hasIncomingData = false; 297 | await remoteSocket.readable.pipeTo( 298 | new WritableStream({ 299 | start() {}, 300 | /** 301 | * 302 | * @param {Uint8Array} chunk 303 | * @param {*} controller 304 | */ 305 | async write(chunk, controller) { 306 | hasIncomingData = true; 307 | if (webSocket.readyState !== WS_READY_STATE_OPEN) { 308 | controller.error( 309 | "webSocket connection is not open" 310 | ); 311 | } 312 | webSocket.send(chunk); 313 | }, 314 | close() { 315 | log(`remoteSocket.readable is closed, hasIncomingData: ${hasIncomingData}`); 316 | }, 317 | abort(reason) { 318 | console.error("remoteSocket.readable abort", reason); 319 | } 320 | }) 321 | ).catch((error) => { 322 | console.error( 323 | `remoteSocketToWS error:`, 324 | error.stack || error 325 | ); 326 | safeCloseWebSocket(webSocket); 327 | }); 328 | if (hasIncomingData === false && retry) { 329 | log(`retry`); 330 | retry(); 331 | } 332 | } 333 | 334 | function isValidSHA224(hash) { 335 | const sha224Regex = /^[0-9a-f]{56}$/i; 336 | return sha224Regex.test(hash); 337 | } 338 | 339 | function base64ToArrayBuffer(base64Str) { 340 | if (!base64Str) { 341 | return { error: null }; 342 | } 343 | try { 344 | base64Str = base64Str.replace(/-/g, "+").replace(/_/g, "/"); 345 | const decode = atob(base64Str); 346 | const arryBuffer = Uint8Array.from(decode, (c) => c.charCodeAt(0)); 347 | return { earlyData: arryBuffer.buffer, error: null }; 348 | } catch (error) { 349 | return { error }; 350 | } 351 | } 352 | 353 | let WS_READY_STATE_OPEN = 1; 354 | let WS_READY_STATE_CLOSING = 2; 355 | 356 | function safeCloseWebSocket(socket) { 357 | try { 358 | if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) { 359 | socket.close(); 360 | } 361 | } catch (error) { 362 | console.error("safeCloseWebSocket error", error); 363 | } 364 | } 365 | // export { 366 | // worker_default as 367 | // default 368 | // }; 369 | //# sourceMappingURL=worker.js.map 370 | 371 | 372 | /** 373 | * [js-sha256]{@link https://github.com/emn178/js-sha256} 374 | * 375 | * @version 0.11.0 376 | * @author Chen, Yi-Cyuan [emn178@gmail.com] 377 | * @copyright Chen, Yi-Cyuan 2014-2024 378 | * @license MIT 379 | */ 380 | /*jslint bitwise: true */ 381 | (function () { 382 | 'use strict'; 383 | 384 | var ERROR = 'input is invalid type'; 385 | var WINDOW = typeof window === 'object'; 386 | var root = WINDOW ? window : {}; 387 | if (root.JS_SHA256_NO_WINDOW) { 388 | WINDOW = false; 389 | } 390 | var WEB_WORKER = !WINDOW && typeof self === 'object'; 391 | var NODE_JS = !root.JS_SHA256_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; 392 | if (NODE_JS) { 393 | root = global; 394 | } else if (WEB_WORKER) { 395 | root = self; 396 | } 397 | var COMMON_JS = !root.JS_SHA256_NO_COMMON_JS && typeof module === 'object' && module.exports; 398 | var AMD = typeof define === 'function' && define.amd; 399 | var ARRAY_BUFFER = !root.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined'; 400 | var HEX_CHARS = '0123456789abcdef'.split(''); 401 | var EXTRA = [-2147483648, 8388608, 32768, 128]; 402 | var SHIFT = [24, 16, 8, 0]; 403 | var K = [ 404 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 405 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 406 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 407 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 408 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 409 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 410 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 411 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 412 | ]; 413 | var OUTPUT_TYPES = ['hex', 'array', 'digest', 'arrayBuffer']; 414 | 415 | var blocks = []; 416 | 417 | if (root.JS_SHA256_NO_NODE_JS || !Array.isArray) { 418 | Array.isArray = function (obj) { 419 | return Object.prototype.toString.call(obj) === '[object Array]'; 420 | }; 421 | } 422 | 423 | if (ARRAY_BUFFER && (root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { 424 | ArrayBuffer.isView = function (obj) { 425 | return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer; 426 | }; 427 | } 428 | 429 | var createOutputMethod = function (outputType, is224) { 430 | return function (message) { 431 | return new Sha256(is224, true).update(message)[outputType](); 432 | }; 433 | }; 434 | 435 | var createMethod = function (is224) { 436 | var method = createOutputMethod('hex', is224); 437 | if (NODE_JS) { 438 | method = nodeWrap(method, is224); 439 | } 440 | method.create = function () { 441 | return new Sha256(is224); 442 | }; 443 | method.update = function (message) { 444 | return method.create().update(message); 445 | }; 446 | for (var i = 0; i < OUTPUT_TYPES.length; ++i) { 447 | var type = OUTPUT_TYPES[i]; 448 | method[type] = createOutputMethod(type, is224); 449 | } 450 | return method; 451 | }; 452 | 453 | var nodeWrap = function (method, is224) { 454 | var crypto = require('crypto') 455 | var Buffer = require('buffer').Buffer; 456 | var algorithm = is224 ? 'sha224' : 'sha256'; 457 | var bufferFrom; 458 | if (Buffer.from && !root.JS_SHA256_NO_BUFFER_FROM) { 459 | bufferFrom = Buffer.from; 460 | } else { 461 | bufferFrom = function (message) { 462 | return new Buffer(message); 463 | }; 464 | } 465 | var nodeMethod = function (message) { 466 | if (typeof message === 'string') { 467 | return crypto.createHash(algorithm).update(message, 'utf8').digest('hex'); 468 | } else { 469 | if (message === null || message === undefined) { 470 | throw new Error(ERROR); 471 | } else if (message.constructor === ArrayBuffer) { 472 | message = new Uint8Array(message); 473 | } 474 | } 475 | if (Array.isArray(message) || ArrayBuffer.isView(message) || 476 | message.constructor === Buffer) { 477 | return crypto.createHash(algorithm).update(bufferFrom(message)).digest('hex'); 478 | } else { 479 | return method(message); 480 | } 481 | }; 482 | return nodeMethod; 483 | }; 484 | 485 | var createHmacOutputMethod = function (outputType, is224) { 486 | return function (key, message) { 487 | return new HmacSha256(key, is224, true).update(message)[outputType](); 488 | }; 489 | }; 490 | 491 | var createHmacMethod = function (is224) { 492 | var method = createHmacOutputMethod('hex', is224); 493 | method.create = function (key) { 494 | return new HmacSha256(key, is224); 495 | }; 496 | method.update = function (key, message) { 497 | return method.create(key).update(message); 498 | }; 499 | for (var i = 0; i < OUTPUT_TYPES.length; ++i) { 500 | var type = OUTPUT_TYPES[i]; 501 | method[type] = createHmacOutputMethod(type, is224); 502 | } 503 | return method; 504 | }; 505 | 506 | function Sha256(is224, sharedMemory) { 507 | if (sharedMemory) { 508 | blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = 509 | blocks[4] = blocks[5] = blocks[6] = blocks[7] = 510 | blocks[8] = blocks[9] = blocks[10] = blocks[11] = 511 | blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; 512 | this.blocks = blocks; 513 | } else { 514 | this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; 515 | } 516 | 517 | if (is224) { 518 | this.h0 = 0xc1059ed8; 519 | this.h1 = 0x367cd507; 520 | this.h2 = 0x3070dd17; 521 | this.h3 = 0xf70e5939; 522 | this.h4 = 0xffc00b31; 523 | this.h5 = 0x68581511; 524 | this.h6 = 0x64f98fa7; 525 | this.h7 = 0xbefa4fa4; 526 | } else { // 256 527 | this.h0 = 0x6a09e667; 528 | this.h1 = 0xbb67ae85; 529 | this.h2 = 0x3c6ef372; 530 | this.h3 = 0xa54ff53a; 531 | this.h4 = 0x510e527f; 532 | this.h5 = 0x9b05688c; 533 | this.h6 = 0x1f83d9ab; 534 | this.h7 = 0x5be0cd19; 535 | } 536 | 537 | this.block = this.start = this.bytes = this.hBytes = 0; 538 | this.finalized = this.hashed = false; 539 | this.first = true; 540 | this.is224 = is224; 541 | } 542 | 543 | Sha256.prototype.update = function (message) { 544 | if (this.finalized) { 545 | return; 546 | } 547 | var notString, type = typeof message; 548 | if (type !== 'string') { 549 | if (type === 'object') { 550 | if (message === null) { 551 | throw new Error(ERROR); 552 | } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { 553 | message = new Uint8Array(message); 554 | } else if (!Array.isArray(message)) { 555 | if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { 556 | throw new Error(ERROR); 557 | } 558 | } 559 | } else { 560 | throw new Error(ERROR); 561 | } 562 | notString = true; 563 | } 564 | var code, index = 0, i, length = message.length, blocks = this.blocks; 565 | while (index < length) { 566 | if (this.hashed) { 567 | this.hashed = false; 568 | blocks[0] = this.block; 569 | this.block = blocks[16] = blocks[1] = blocks[2] = blocks[3] = 570 | blocks[4] = blocks[5] = blocks[6] = blocks[7] = 571 | blocks[8] = blocks[9] = blocks[10] = blocks[11] = 572 | blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; 573 | } 574 | 575 | if (notString) { 576 | for (i = this.start; index < length && i < 64; ++index) { 577 | blocks[i >>> 2] |= message[index] << SHIFT[i++ & 3]; 578 | } 579 | } else { 580 | for (i = this.start; index < length && i < 64; ++index) { 581 | code = message.charCodeAt(index); 582 | if (code < 0x80) { 583 | blocks[i >>> 2] |= code << SHIFT[i++ & 3]; 584 | } else if (code < 0x800) { 585 | blocks[i >>> 2] |= (0xc0 | (code >>> 6)) << SHIFT[i++ & 3]; 586 | blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; 587 | } else if (code < 0xd800 || code >= 0xe000) { 588 | blocks[i >>> 2] |= (0xe0 | (code >>> 12)) << SHIFT[i++ & 3]; 589 | blocks[i >>> 2] |= (0x80 | ((code >>> 6) & 0x3f)) << SHIFT[i++ & 3]; 590 | blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; 591 | } else { 592 | code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); 593 | blocks[i >>> 2] |= (0xf0 | (code >>> 18)) << SHIFT[i++ & 3]; 594 | blocks[i >>> 2] |= (0x80 | ((code >>> 12) & 0x3f)) << SHIFT[i++ & 3]; 595 | blocks[i >>> 2] |= (0x80 | ((code >>> 6) & 0x3f)) << SHIFT[i++ & 3]; 596 | blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; 597 | } 598 | } 599 | } 600 | 601 | this.lastByteIndex = i; 602 | this.bytes += i - this.start; 603 | if (i >= 64) { 604 | this.block = blocks[16]; 605 | this.start = i - 64; 606 | this.hash(); 607 | this.hashed = true; 608 | } else { 609 | this.start = i; 610 | } 611 | } 612 | if (this.bytes > 4294967295) { 613 | this.hBytes += this.bytes / 4294967296 << 0; 614 | this.bytes = this.bytes % 4294967296; 615 | } 616 | return this; 617 | }; 618 | 619 | Sha256.prototype.finalize = function () { 620 | if (this.finalized) { 621 | return; 622 | } 623 | this.finalized = true; 624 | var blocks = this.blocks, i = this.lastByteIndex; 625 | blocks[16] = this.block; 626 | blocks[i >>> 2] |= EXTRA[i & 3]; 627 | this.block = blocks[16]; 628 | if (i >= 56) { 629 | if (!this.hashed) { 630 | this.hash(); 631 | } 632 | blocks[0] = this.block; 633 | blocks[16] = blocks[1] = blocks[2] = blocks[3] = 634 | blocks[4] = blocks[5] = blocks[6] = blocks[7] = 635 | blocks[8] = blocks[9] = blocks[10] = blocks[11] = 636 | blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; 637 | } 638 | blocks[14] = this.hBytes << 3 | this.bytes >>> 29; 639 | blocks[15] = this.bytes << 3; 640 | this.hash(); 641 | }; 642 | 643 | Sha256.prototype.hash = function () { 644 | var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, 645 | h = this.h7, blocks = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; 646 | 647 | for (j = 16; j < 64; ++j) { 648 | // rightrotate 649 | t1 = blocks[j - 15]; 650 | s0 = ((t1 >>> 7) | (t1 << 25)) ^ ((t1 >>> 18) | (t1 << 14)) ^ (t1 >>> 3); 651 | t1 = blocks[j - 2]; 652 | s1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10); 653 | blocks[j] = blocks[j - 16] + s0 + blocks[j - 7] + s1 << 0; 654 | } 655 | 656 | bc = b & c; 657 | for (j = 0; j < 64; j += 4) { 658 | if (this.first) { 659 | if (this.is224) { 660 | ab = 300032; 661 | t1 = blocks[0] - 1413257819; 662 | h = t1 - 150054599 << 0; 663 | d = t1 + 24177077 << 0; 664 | } else { 665 | ab = 704751109; 666 | t1 = blocks[0] - 210244248; 667 | h = t1 - 1521486534 << 0; 668 | d = t1 + 143694565 << 0; 669 | } 670 | this.first = false; 671 | } else { 672 | s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); 673 | s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); 674 | ab = a & b; 675 | maj = ab ^ (a & c) ^ bc; 676 | ch = (e & f) ^ (~e & g); 677 | t1 = h + s1 + ch + K[j] + blocks[j]; 678 | t2 = s0 + maj; 679 | h = d + t1 << 0; 680 | d = t1 + t2 << 0; 681 | } 682 | s0 = ((d >>> 2) | (d << 30)) ^ ((d >>> 13) | (d << 19)) ^ ((d >>> 22) | (d << 10)); 683 | s1 = ((h >>> 6) | (h << 26)) ^ ((h >>> 11) | (h << 21)) ^ ((h >>> 25) | (h << 7)); 684 | da = d & a; 685 | maj = da ^ (d & b) ^ ab; 686 | ch = (h & e) ^ (~h & f); 687 | t1 = g + s1 + ch + K[j + 1] + blocks[j + 1]; 688 | t2 = s0 + maj; 689 | g = c + t1 << 0; 690 | c = t1 + t2 << 0; 691 | s0 = ((c >>> 2) | (c << 30)) ^ ((c >>> 13) | (c << 19)) ^ ((c >>> 22) | (c << 10)); 692 | s1 = ((g >>> 6) | (g << 26)) ^ ((g >>> 11) | (g << 21)) ^ ((g >>> 25) | (g << 7)); 693 | cd = c & d; 694 | maj = cd ^ (c & a) ^ da; 695 | ch = (g & h) ^ (~g & e); 696 | t1 = f + s1 + ch + K[j + 2] + blocks[j + 2]; 697 | t2 = s0 + maj; 698 | f = b + t1 << 0; 699 | b = t1 + t2 << 0; 700 | s0 = ((b >>> 2) | (b << 30)) ^ ((b >>> 13) | (b << 19)) ^ ((b >>> 22) | (b << 10)); 701 | s1 = ((f >>> 6) | (f << 26)) ^ ((f >>> 11) | (f << 21)) ^ ((f >>> 25) | (f << 7)); 702 | bc = b & c; 703 | maj = bc ^ (b & d) ^ cd; 704 | ch = (f & g) ^ (~f & h); 705 | t1 = e + s1 + ch + K[j + 3] + blocks[j + 3]; 706 | t2 = s0 + maj; 707 | e = a + t1 << 0; 708 | a = t1 + t2 << 0; 709 | this.chromeBugWorkAround = true; 710 | } 711 | 712 | this.h0 = this.h0 + a << 0; 713 | this.h1 = this.h1 + b << 0; 714 | this.h2 = this.h2 + c << 0; 715 | this.h3 = this.h3 + d << 0; 716 | this.h4 = this.h4 + e << 0; 717 | this.h5 = this.h5 + f << 0; 718 | this.h6 = this.h6 + g << 0; 719 | this.h7 = this.h7 + h << 0; 720 | }; 721 | 722 | Sha256.prototype.hex = function () { 723 | this.finalize(); 724 | 725 | var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, 726 | h6 = this.h6, h7 = this.h7; 727 | 728 | var hex = HEX_CHARS[(h0 >>> 28) & 0x0F] + HEX_CHARS[(h0 >>> 24) & 0x0F] + 729 | HEX_CHARS[(h0 >>> 20) & 0x0F] + HEX_CHARS[(h0 >>> 16) & 0x0F] + 730 | HEX_CHARS[(h0 >>> 12) & 0x0F] + HEX_CHARS[(h0 >>> 8) & 0x0F] + 731 | HEX_CHARS[(h0 >>> 4) & 0x0F] + HEX_CHARS[h0 & 0x0F] + 732 | HEX_CHARS[(h1 >>> 28) & 0x0F] + HEX_CHARS[(h1 >>> 24) & 0x0F] + 733 | HEX_CHARS[(h1 >>> 20) & 0x0F] + HEX_CHARS[(h1 >>> 16) & 0x0F] + 734 | HEX_CHARS[(h1 >>> 12) & 0x0F] + HEX_CHARS[(h1 >>> 8) & 0x0F] + 735 | HEX_CHARS[(h1 >>> 4) & 0x0F] + HEX_CHARS[h1 & 0x0F] + 736 | HEX_CHARS[(h2 >>> 28) & 0x0F] + HEX_CHARS[(h2 >>> 24) & 0x0F] + 737 | HEX_CHARS[(h2 >>> 20) & 0x0F] + HEX_CHARS[(h2 >>> 16) & 0x0F] + 738 | HEX_CHARS[(h2 >>> 12) & 0x0F] + HEX_CHARS[(h2 >>> 8) & 0x0F] + 739 | HEX_CHARS[(h2 >>> 4) & 0x0F] + HEX_CHARS[h2 & 0x0F] + 740 | HEX_CHARS[(h3 >>> 28) & 0x0F] + HEX_CHARS[(h3 >>> 24) & 0x0F] + 741 | HEX_CHARS[(h3 >>> 20) & 0x0F] + HEX_CHARS[(h3 >>> 16) & 0x0F] + 742 | HEX_CHARS[(h3 >>> 12) & 0x0F] + HEX_CHARS[(h3 >>> 8) & 0x0F] + 743 | HEX_CHARS[(h3 >>> 4) & 0x0F] + HEX_CHARS[h3 & 0x0F] + 744 | HEX_CHARS[(h4 >>> 28) & 0x0F] + HEX_CHARS[(h4 >>> 24) & 0x0F] + 745 | HEX_CHARS[(h4 >>> 20) & 0x0F] + HEX_CHARS[(h4 >>> 16) & 0x0F] + 746 | HEX_CHARS[(h4 >>> 12) & 0x0F] + HEX_CHARS[(h4 >>> 8) & 0x0F] + 747 | HEX_CHARS[(h4 >>> 4) & 0x0F] + HEX_CHARS[h4 & 0x0F] + 748 | HEX_CHARS[(h5 >>> 28) & 0x0F] + HEX_CHARS[(h5 >>> 24) & 0x0F] + 749 | HEX_CHARS[(h5 >>> 20) & 0x0F] + HEX_CHARS[(h5 >>> 16) & 0x0F] + 750 | HEX_CHARS[(h5 >>> 12) & 0x0F] + HEX_CHARS[(h5 >>> 8) & 0x0F] + 751 | HEX_CHARS[(h5 >>> 4) & 0x0F] + HEX_CHARS[h5 & 0x0F] + 752 | HEX_CHARS[(h6 >>> 28) & 0x0F] + HEX_CHARS[(h6 >>> 24) & 0x0F] + 753 | HEX_CHARS[(h6 >>> 20) & 0x0F] + HEX_CHARS[(h6 >>> 16) & 0x0F] + 754 | HEX_CHARS[(h6 >>> 12) & 0x0F] + HEX_CHARS[(h6 >>> 8) & 0x0F] + 755 | HEX_CHARS[(h6 >>> 4) & 0x0F] + HEX_CHARS[h6 & 0x0F]; 756 | if (!this.is224) { 757 | hex += HEX_CHARS[(h7 >>> 28) & 0x0F] + HEX_CHARS[(h7 >>> 24) & 0x0F] + 758 | HEX_CHARS[(h7 >>> 20) & 0x0F] + HEX_CHARS[(h7 >>> 16) & 0x0F] + 759 | HEX_CHARS[(h7 >>> 12) & 0x0F] + HEX_CHARS[(h7 >>> 8) & 0x0F] + 760 | HEX_CHARS[(h7 >>> 4) & 0x0F] + HEX_CHARS[h7 & 0x0F]; 761 | } 762 | return hex; 763 | }; 764 | 765 | Sha256.prototype.toString = Sha256.prototype.hex; 766 | 767 | Sha256.prototype.digest = function () { 768 | this.finalize(); 769 | 770 | var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, 771 | h6 = this.h6, h7 = this.h7; 772 | 773 | var arr = [ 774 | (h0 >>> 24) & 0xFF, (h0 >>> 16) & 0xFF, (h0 >>> 8) & 0xFF, h0 & 0xFF, 775 | (h1 >>> 24) & 0xFF, (h1 >>> 16) & 0xFF, (h1 >>> 8) & 0xFF, h1 & 0xFF, 776 | (h2 >>> 24) & 0xFF, (h2 >>> 16) & 0xFF, (h2 >>> 8) & 0xFF, h2 & 0xFF, 777 | (h3 >>> 24) & 0xFF, (h3 >>> 16) & 0xFF, (h3 >>> 8) & 0xFF, h3 & 0xFF, 778 | (h4 >>> 24) & 0xFF, (h4 >>> 16) & 0xFF, (h4 >>> 8) & 0xFF, h4 & 0xFF, 779 | (h5 >>> 24) & 0xFF, (h5 >>> 16) & 0xFF, (h5 >>> 8) & 0xFF, h5 & 0xFF, 780 | (h6 >>> 24) & 0xFF, (h6 >>> 16) & 0xFF, (h6 >>> 8) & 0xFF, h6 & 0xFF 781 | ]; 782 | if (!this.is224) { 783 | arr.push((h7 >>> 24) & 0xFF, (h7 >>> 16) & 0xFF, (h7 >>> 8) & 0xFF, h7 & 0xFF); 784 | } 785 | return arr; 786 | }; 787 | 788 | Sha256.prototype.array = Sha256.prototype.digest; 789 | 790 | Sha256.prototype.arrayBuffer = function () { 791 | this.finalize(); 792 | 793 | var buffer = new ArrayBuffer(this.is224 ? 28 : 32); 794 | var dataView = new DataView(buffer); 795 | dataView.setUint32(0, this.h0); 796 | dataView.setUint32(4, this.h1); 797 | dataView.setUint32(8, this.h2); 798 | dataView.setUint32(12, this.h3); 799 | dataView.setUint32(16, this.h4); 800 | dataView.setUint32(20, this.h5); 801 | dataView.setUint32(24, this.h6); 802 | if (!this.is224) { 803 | dataView.setUint32(28, this.h7); 804 | } 805 | return buffer; 806 | }; 807 | 808 | function HmacSha256(key, is224, sharedMemory) { 809 | var i, type = typeof key; 810 | if (type === 'string') { 811 | var bytes = [], length = key.length, index = 0, code; 812 | for (i = 0; i < length; ++i) { 813 | code = key.charCodeAt(i); 814 | if (code < 0x80) { 815 | bytes[index++] = code; 816 | } else if (code < 0x800) { 817 | bytes[index++] = (0xc0 | (code >>> 6)); 818 | bytes[index++] = (0x80 | (code & 0x3f)); 819 | } else if (code < 0xd800 || code >= 0xe000) { 820 | bytes[index++] = (0xe0 | (code >>> 12)); 821 | bytes[index++] = (0x80 | ((code >>> 6) & 0x3f)); 822 | bytes[index++] = (0x80 | (code & 0x3f)); 823 | } else { 824 | code = 0x10000 + (((code & 0x3ff) << 10) | (key.charCodeAt(++i) & 0x3ff)); 825 | bytes[index++] = (0xf0 | (code >>> 18)); 826 | bytes[index++] = (0x80 | ((code >>> 12) & 0x3f)); 827 | bytes[index++] = (0x80 | ((code >>> 6) & 0x3f)); 828 | bytes[index++] = (0x80 | (code & 0x3f)); 829 | } 830 | } 831 | key = bytes; 832 | } else { 833 | if (type === 'object') { 834 | if (key === null) { 835 | throw new Error(ERROR); 836 | } else if (ARRAY_BUFFER && key.constructor === ArrayBuffer) { 837 | key = new Uint8Array(key); 838 | } else if (!Array.isArray(key)) { 839 | if (!ARRAY_BUFFER || !ArrayBuffer.isView(key)) { 840 | throw new Error(ERROR); 841 | } 842 | } 843 | } else { 844 | throw new Error(ERROR); 845 | } 846 | } 847 | 848 | if (key.length > 64) { 849 | key = (new Sha256(is224, true)).update(key).array(); 850 | } 851 | 852 | var oKeyPad = [], iKeyPad = []; 853 | for (i = 0; i < 64; ++i) { 854 | var b = key[i] || 0; 855 | oKeyPad[i] = 0x5c ^ b; 856 | iKeyPad[i] = 0x36 ^ b; 857 | } 858 | 859 | Sha256.call(this, is224, sharedMemory); 860 | 861 | this.update(iKeyPad); 862 | this.oKeyPad = oKeyPad; 863 | this.inner = true; 864 | this.sharedMemory = sharedMemory; 865 | } 866 | HmacSha256.prototype = new Sha256(); 867 | 868 | HmacSha256.prototype.finalize = function () { 869 | Sha256.prototype.finalize.call(this); 870 | if (this.inner) { 871 | this.inner = false; 872 | var innerHash = this.array(); 873 | Sha256.call(this, this.is224, this.sharedMemory); 874 | this.update(this.oKeyPad); 875 | this.update(innerHash); 876 | Sha256.prototype.finalize.call(this); 877 | } 878 | }; 879 | 880 | var exports = createMethod(); 881 | exports.sha256 = exports; 882 | exports.sha224 = createMethod(true); 883 | exports.sha256.hmac = createHmacMethod(); 884 | exports.sha224.hmac = createHmacMethod(true); 885 | 886 | if (COMMON_JS) { 887 | module.exports = exports; 888 | } else { 889 | root.sha256 = exports.sha256; 890 | root.sha224 = exports.sha224; 891 | if (AMD) { 892 | define(function () { 893 | return exports; 894 | }); 895 | } 896 | } 897 | })(); 898 | -------------------------------------------------------------------------------- /utils/csv.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "encoding/csv" 5 | "fmt" 6 | "golang.org/x/text/encoding/simplifiedchinese" 7 | "golang.org/x/text/transform" 8 | "log" 9 | "net" 10 | "os" 11 | "sort" 12 | "strconv" 13 | "time" 14 | ) 15 | 16 | const ( 17 | defaultOutput = "result.csv" 18 | maxDelay = 9999 * time.Millisecond 19 | minDelay = 0 * time.Millisecond 20 | maxLossRate float32 = 1.0 21 | ) 22 | 23 | var ( 24 | InputMaxDelay = maxDelay 25 | InputMinDelay = minDelay 26 | InputMaxLossRate = maxLossRate 27 | Output = defaultOutput 28 | PrintNum = 10 29 | ) 30 | 31 | // 是否打印测试结果 32 | func NoPrintResult() bool { 33 | return PrintNum == 0 34 | } 35 | 36 | // 是否输出到文件 37 | func noOutput() bool { 38 | return Output == "" || Output == " " 39 | } 40 | 41 | type PingData struct { 42 | IP *net.IPAddr 43 | Sended int 44 | Received int 45 | Delay time.Duration 46 | } 47 | 48 | type CloudflareIPData struct { 49 | *PingData 50 | lossRate float32 51 | DownloadSpeed float64 52 | Country string 53 | } 54 | 55 | // 计算丢包率 56 | func (cf *CloudflareIPData) getLossRate() float32 { 57 | if cf.lossRate == 0 { 58 | pingLost := cf.Sended - cf.Received 59 | cf.lossRate = float32(pingLost) / float32(cf.Sended) 60 | } 61 | return cf.lossRate 62 | } 63 | 64 | func (cf *CloudflareIPData) toString() []string { 65 | result := make([]string, 6) 66 | result[0] = cf.IP.String() 67 | result[1] = strconv.Itoa(cf.Sended) 68 | result[2] = strconv.Itoa(cf.Received) 69 | result[3] = strconv.FormatFloat(float64(cf.getLossRate()), 'f', 2, 32) 70 | result[4] = strconv.FormatFloat(cf.Delay.Seconds()*1000, 'f', 2, 32) 71 | result[5] = strconv.FormatFloat(cf.DownloadSpeed/1024/1024, 'f', 2, 32) 72 | return result 73 | } 74 | 75 | func WriteFile(filename string, data []CloudflareIPData) { 76 | fp, err := os.Create(filename) 77 | if err != nil { 78 | log.Fatalf("创建文件[%s]失败:%v", filename, err) 79 | return 80 | } 81 | defer fp.Close() 82 | w := csv.NewWriter(fp) //创建一个新的写入文件流 83 | _ = w.Write([]string{"IP 地址", "已发送", "已接收", "丢包率(%)", "延迟(ms)", "下载速度(Mbps)"}) 84 | _ = w.WriteAll(convertToString(data)) 85 | w.Flush() 86 | } 87 | 88 | func ExportCsvByCountry(data []CloudflareIPData) { 89 | theCC := "" 90 | datatmp := make([]CloudflareIPData, 0) 91 | for i, v := range data { 92 | if theCC == "" { 93 | theCC = v.Country 94 | } 95 | if v.Country != theCC { 96 | filename := theCC + ".csv" 97 | sort.Slice(datatmp, func(i, j int) bool { 98 | return datatmp[i].DownloadSpeed > datatmp[j].DownloadSpeed 99 | }) 100 | WriteFile(filename, datatmp) 101 | theCC = v.Country 102 | datatmp = datatmp[:0] 103 | } 104 | datatmp = append(datatmp, v) 105 | if i == len(data)-1 { 106 | filename := theCC + ".csv" 107 | sort.Slice(datatmp, func(i, j int) bool { 108 | return datatmp[i].DownloadSpeed > datatmp[j].DownloadSpeed 109 | }) 110 | WriteFile(filename, datatmp) 111 | } 112 | } 113 | } 114 | 115 | func ExportCsv(data []CloudflareIPData) { 116 | if noOutput() || len(data) == 0 { 117 | return 118 | } 119 | fp, err := os.Create(Output) 120 | if err != nil { 121 | log.Fatalf("创建文件[%s]失败:%v", Output, err) 122 | return 123 | } 124 | defer fp.Close() 125 | gbkEncoder := simplifiedchinese.GBK.NewEncoder() 126 | w := csv.NewWriter(transform.NewWriter(fp, gbkEncoder)) 127 | _ = w.Write([]string{"IP 地址", "已发送", "已接收", "丢包率", "平均延迟", "下载速度 (MB/s)"}) 128 | _ = w.WriteAll(convertToString(data)) 129 | w.Flush() 130 | } 131 | 132 | func convertToString(data []CloudflareIPData) [][]string { 133 | result := make([][]string, 0) 134 | for _, v := range data { 135 | result = append(result, v.toString()) 136 | } 137 | return result 138 | } 139 | 140 | // 延迟丢包排序 141 | type PingDelaySet []CloudflareIPData 142 | 143 | // 延迟条件过滤 144 | func (s PingDelaySet) FilterDelay() (data PingDelaySet) { 145 | if InputMaxDelay > maxDelay || InputMinDelay < minDelay { // 当输入的延迟条件不在默认范围内时,不进行过滤 146 | return s 147 | } 148 | if InputMaxDelay == maxDelay && InputMinDelay == minDelay { // 当输入的延迟条件为默认值时,不进行过滤 149 | return s 150 | } 151 | for _, v := range s { 152 | if v.Delay > InputMaxDelay { // 平均延迟上限,延迟大于条件最大值时,后面的数据都不满足条件,直接跳出循环 153 | break 154 | } 155 | if v.Delay < InputMinDelay { // 平均延迟下限,延迟小于条件最小值时,不满足条件,跳过 156 | continue 157 | } 158 | data = append(data, v) // 延迟满足条件时,添加到新数组中 159 | } 160 | return 161 | } 162 | 163 | // 丢包条件过滤 164 | func (s PingDelaySet) FilterLossRate() (data PingDelaySet) { 165 | if InputMaxLossRate >= maxLossRate { // 当输入的丢包条件为默认值时,不进行过滤 166 | return s 167 | } 168 | for _, v := range s { 169 | if v.getLossRate() > InputMaxLossRate { // 丢包几率上限 170 | break 171 | } 172 | data = append(data, v) // 丢包率满足条件时,添加到新数组中 173 | } 174 | return 175 | } 176 | 177 | func (s PingDelaySet) FilterCountryV2(info *CountryInfo, countrycodeList map[string]bool) (data PingDelaySet) { 178 | fmt.Printf("开始查询IP的国家代号...\n") 179 | bfilterCountry := false 180 | if len(countrycodeList) > 0 { 181 | bfilterCountry = true 182 | } 183 | for _, v := range s { 184 | v.Country = info.GetCountryV2(v.IP.IP.String()) 185 | if v.Country == "" { 186 | fmt.Printf("IP: %s 无法获取国家代号,已跳过\n", v.IP.IP.String()) 187 | continue 188 | } 189 | if bfilterCountry { 190 | if countrycodeList[v.Country] == true { 191 | data = append(data, v) 192 | } 193 | } else { 194 | data = append(data, v) 195 | } 196 | } 197 | return 198 | } 199 | 200 | func (s PingDelaySet) FilterCountryV3(info *CountryInfo) (data PingDelaySet) { 201 | fmt.Printf("开始查询IP的国家代号...\n") 202 | for _, v := range s { 203 | v.Country = info.GetCountryV2(v.IP.IP.String()) 204 | if v.Country == "" { 205 | data = append(data, v) 206 | } 207 | 208 | } 209 | return 210 | } 211 | 212 | func (s PingDelaySet) FilterCountryV1() (data PingDelaySet) { 213 | countrys := make([]IpResponse, 0) 214 | ips := make([]string, 0) 215 | querycount := 0 216 | fmt.Printf("开始查询IP的国家代号...\n") 217 | bar := NewBar(len(s), "已查:", "") 218 | for i, v := range s { 219 | if i > 0 && i%100 == 0 { 220 | countryCodeInfo := getCountryV1(ips) 221 | if countryCodeInfo == nil { 222 | fmt.Printf("[WARN] %s\n", "IP查询失败,请检查网络或API接口是否正常") 223 | continue 224 | } 225 | 226 | countrys = append(countrys, countryCodeInfo...) 227 | bar.Grow(100, strconv.Itoa(len(countrys))) 228 | ips = ips[:0] 229 | querycount++ 230 | if querycount >= 15 { 231 | time.Sleep(61 * time.Second) 232 | querycount = 0 233 | } 234 | } 235 | ip := v.IP.IP 236 | ips = append(ips, ip.String()) 237 | } 238 | 239 | if len(ips) > 0 { 240 | if querycount >= 15 { 241 | time.Sleep(61 * time.Second) 242 | } 243 | countryCodeInfo := getCountryV1(ips) 244 | countrys = append(countrys, countryCodeInfo...) 245 | bar.Grow(len(ips), strconv.Itoa(len(countrys))) 246 | } 247 | bar.Done() 248 | for i, v := range countrys { 249 | m := s[i] 250 | if v.Status == "fail" { 251 | m.Country = "" 252 | } else { 253 | m.Country = v.CountryCode 254 | } 255 | data = append(data, m) 256 | } 257 | return 258 | } 259 | 260 | func (s PingDelaySet) Len() int { 261 | return len(s) 262 | } 263 | func (s PingDelaySet) Less(i, j int) bool { 264 | iRate, jRate := s[i].getLossRate(), s[j].getLossRate() 265 | if iRate != jRate { 266 | return iRate < jRate 267 | } 268 | return s[i].Delay < s[j].Delay 269 | } 270 | func (s PingDelaySet) Swap(i, j int) { 271 | s[i], s[j] = s[j], s[i] 272 | } 273 | 274 | // 下载速度排序 275 | type DownloadSpeedSet []CloudflareIPData 276 | 277 | func (s DownloadSpeedSet) Len() int { 278 | return len(s) 279 | } 280 | func (s DownloadSpeedSet) Less(i, j int) bool { 281 | return s[i].DownloadSpeed > s[j].DownloadSpeed 282 | } 283 | func (s DownloadSpeedSet) Swap(i, j int) { 284 | s[i], s[j] = s[j], s[i] 285 | } 286 | 287 | func (s DownloadSpeedSet) Print() { 288 | if NoPrintResult() { 289 | return 290 | } 291 | if len(s) <= 0 { // IP数组长度(IP数量) 大于 0 时继续 292 | fmt.Println("\n[信息] 完整测速结果 IP 数量为 0,跳过输出结果。") 293 | return 294 | } 295 | dateString := convertToString(s) // 转为多维数组 [][]String 296 | if len(dateString) < PrintNum { // 如果IP数组长度(IP数量) 小于 打印次数,则次数改为IP数量 297 | PrintNum = len(dateString) 298 | } 299 | headFormat := "%-16s%-5s%-5s%-5s%-6s%-11s\n" 300 | dataFormat := "%-18s%-8s%-8s%-8s%-10s%-15s\n" 301 | for i := 0; i < PrintNum; i++ { // 如果要输出的 IP 中包含 IPv6,那么就需要调整一下间隔 302 | if len(dateString[i][0]) > 15 { 303 | headFormat = "%-40s%-5s%-5s%-5s%-6s%-11s\n" 304 | dataFormat = "%-42s%-8s%-8s%-8s%-10s%-15s\n" 305 | break 306 | } 307 | } 308 | fmt.Printf(headFormat, "IP 地址", "已发送", "已接收", "丢包率", "平均延迟", "下载速度 (MB/s)") 309 | for i := 0; i < PrintNum; i++ { 310 | fmt.Printf(dataFormat, dateString[i][0], dateString[i][1], dateString[i][2], dateString[i][3], dateString[i][4], dateString[i][5]) 311 | } 312 | if !noOutput() { 313 | fmt.Printf("\n完整测速结果已写入 %v 文件,可使用记事本/表格软件查看。\n", Output) 314 | } 315 | } 316 | 317 | func (s DownloadSpeedSet) PrintbyCountry() { 318 | if NoPrintResult() { 319 | return 320 | } 321 | } 322 | -------------------------------------------------------------------------------- /utils/csv_test.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | func TestPingDelaySet_FilterLossRate(t *testing.T) { 9 | tests := []struct { 10 | name string 11 | s PingDelaySet 12 | wantData PingDelaySet 13 | }{ 14 | // TODO: Add test cases. 15 | } 16 | for _, tt := range tests { 17 | t.Run(tt.name, func(t *testing.T) { 18 | if gotData := tt.s.FilterLossRate(); !reflect.DeepEqual(gotData, tt.wantData) { 19 | t.Errorf("FilterLossRate() = %v, want %v", gotData, tt.wantData) 20 | } 21 | }) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /utils/getcountry.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "github.com/oschwald/maxminddb-golang" 8 | "io" 9 | "net" 10 | "net/http" 11 | ) 12 | 13 | type IpResponse struct { 14 | Status string `json:"status"` 15 | CountryCode string `json:"countryCode"` 16 | } 17 | 18 | // 每分钟15次查询,每次最多100个ip 19 | func getCountryV1(ips []string) (coutryCodes []IpResponse) { 20 | jsonData, err := json.Marshal(ips) 21 | if err != nil { 22 | fmt.Println(err.Error()) 23 | return nil 24 | } 25 | 26 | resp, err := http.Post("http://ip-api.com/batch", "application/json", bytes.NewBuffer(jsonData)) 27 | if err != nil { 28 | fmt.Println(err.Error()) 29 | return nil 30 | } 31 | defer resp.Body.Close() 32 | 33 | body, _ := io.ReadAll(resp.Body) 34 | 35 | data := make([]IpResponse, 0) 36 | err = json.Unmarshal(body, &data) 37 | if err != nil { 38 | fmt.Println(err) 39 | return nil 40 | } 41 | 42 | for _, v := range data { 43 | coutryCodes = append(coutryCodes, v) 44 | } 45 | 46 | return 47 | } 48 | 49 | // 使用本地mmdb文件查国家代码 50 | type Country struct { 51 | GeoNameID uint `maxminddb:"geoname_id"` 52 | IsoCode string `maxminddb:"iso_code"` 53 | Names map[string]string `maxminddb:"names"` 54 | } 55 | 56 | type Record struct { 57 | C Country `maxminddb:"country"` 58 | } 59 | 60 | type CountryInfo struct { 61 | db *maxminddb.Reader 62 | } 63 | 64 | func NewCountryInfo(db *maxminddb.Reader) *CountryInfo { 65 | return &CountryInfo{ 66 | db: db, 67 | } 68 | } 69 | 70 | func (c *CountryInfo) GetCountryV2(ip string) string { 71 | 72 | ipinfo := net.ParseIP(ip) 73 | var record Record 74 | err := c.db.Lookup(ipinfo, &record) 75 | if err != nil { 76 | fmt.Println(err) 77 | return "" 78 | } 79 | 80 | return record.C.IsoCode 81 | } 82 | 83 | func (c *CountryInfo) Done() { 84 | defer c.db.Close() 85 | } 86 | -------------------------------------------------------------------------------- /utils/progress.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/cheggaaa/pb/v3" 7 | ) 8 | 9 | type Bar struct { 10 | pb *pb.ProgressBar 11 | } 12 | 13 | func NewBar(count int, MyStrStart, MyStrEnd string) *Bar { 14 | tmpl := fmt.Sprintf(`{{counters . }} {{ bar . "[" "-" (cycle . "↖" "↗" "↘" "↙" ) "_" "]"}} %s {{string . "MyStr" | green}} %s `, MyStrStart, MyStrEnd) 15 | bar := pb.ProgressBarTemplate(tmpl).Start(count) 16 | return &Bar{pb: bar} 17 | } 18 | 19 | func (b *Bar) Grow(num int, MyStrVal string) { 20 | b.pb.Set("MyStr", MyStrVal).Add(num) 21 | } 22 | 23 | func (b *Bar) Done() { 24 | b.pb.Finish() 25 | } 26 | -------------------------------------------------------------------------------- /vless_workers/_worker.js: -------------------------------------------------------------------------------- 1 | // @ts-ignore 2 | import { connect } from 'cloudflare:sockets'; 3 | 4 | // How to generate your own UUID: 5 | // [Windows] Press "Win + R", input cmd and run: Powershell -NoExit -Command "[guid]::NewGuid()" 6 | let userID = 'd342d11e-d424-4583-b36e-524ab1f0afa4'; 7 | 8 | const proxyIPs = ['cdn.xn--b6gac.eu.org', 'cdn-all.xn--b6gac.eu.org', 'workers.cloudflare.cyou']; 9 | 10 | // if you want to use ipv6 or single proxyIP, please add comment at this line and remove comment at the next line 11 | let proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)]; 12 | // use single proxyIP instead of random 13 | // let proxyIP = 'cdn.xn--b6gac.eu.org'; 14 | // ipv6 proxyIP example remove comment to use 15 | // let proxyIP = "[2a01:4f8:c2c:123f:64:5:6810:c55a]" 16 | 17 | let dohURL = 'https://sky.rethinkdns.com/1:-Pf_____9_8A_AMAIgE8kMABVDDmKOHTAKg='; // https://cloudflare-dns.com/dns-query or https://dns.google/dns-query 18 | 19 | if (!isValidUUID(userID)) { 20 | throw new Error('uuid is invalid'); 21 | } 22 | 23 | function getprotocol() { 24 | let matter = ['v','l','e','s','s'] 25 | let result='' 26 | for (let i = 0; i < 5; i++) { 27 | result += matter[i]; 28 | } 29 | return result; 30 | } 31 | 32 | 33 | export default { 34 | /** 35 | * @param {import("@cloudflare/workers-types").Request} request 36 | * @param {{UUID: string, PROXYIP: string, DNS_RESOLVER_URL: string, NODE_ID: int, API_HOST: string, API_TOKEN: string}} env 37 | * @param {import("@cloudflare/workers-types").ExecutionContext} ctx 38 | * @returns {Promise} 39 | */ 40 | async fetch(request, env, ctx) { 41 | // uuid_validator(request); 42 | try { 43 | userID = env.UUID || userID; 44 | proxyIP = env.PROXYIP || proxyIP; 45 | dohURL = env.DNS_RESOLVER_URL || dohURL; 46 | let userID_Path = userID; 47 | if (userID.includes(',')) { 48 | userID_Path = userID.split(',')[0]; 49 | } 50 | const upgradeHeader = request.headers.get('Upgrade'); 51 | if (!upgradeHeader || upgradeHeader !== 'websocket') { 52 | const url = new URL(request.url); 53 | switch (url.pathname.toLowerCase()) { 54 | case '/': 55 | const envKey = env.URL302 ? 'URL302' : (env.URL ? 'URL' : null); 56 | if (envKey) { 57 | const URLs = await ADD(env[envKey]); 58 | const URL = URLs[Math.floor(Math.random() * URLs.length)]; 59 | return envKey === 'URL302' ? Response.redirect(URL, 302) : fetch(new Request(URL, request)); 60 | } 61 | return new Response(JSON.stringify(request.cf, null, 4), { status: 200 }); 62 | case `/cf`: { 63 | return new Response(JSON.stringify(request.cf, null, 4), { 64 | status: 200, 65 | headers: { 66 | "Content-Type": "application/json;charset=utf-8", 67 | }, 68 | }); 69 | } 70 | case `/${userID_Path}`: { 71 | const bbbConfig = getbbbConfig(userID, request.headers.get('Host')); 72 | return new Response(`${bbbConfig}`, { 73 | status: 200, 74 | headers: { 75 | "Content-Type": "text/html; charset=utf-8", 76 | } 77 | }); 78 | }; 79 | case `/sub/${userID_Path}`: { 80 | const url = new URL(request.url); 81 | const searchParams = url.searchParams; 82 | const bbbSubConfig = createbbbSub(userID, request.headers.get('Host')); 83 | // Construct and return response object 84 | return new Response(btoa(bbbSubConfig), { 85 | status: 200, 86 | headers: { 87 | "Content-Type": "text/plain;charset=utf-8", 88 | } 89 | }); 90 | }; 91 | case `/bestip/${userID_Path}`: { 92 | const headers = request.headers; 93 | const url = `https://sub.xf.free.hr/auto?host=${request.headers.get('Host')}&uuid=${userID}&path=/`; 94 | const bestSubConfig = await fetch(url, { headers: headers }); 95 | return bestSubConfig; 96 | }; 97 | default: 98 | return new Response('Not found', { status: 404 }); 99 | // For any other path, reverse proxy to 'ramdom website' and return the original response, caching it in the process 100 | // const randomHostname = cn_hostnames[Math.floor(Math.random() * cn_hostnames.length)]; 101 | // const newHeaders = new Headers(request.headers); 102 | // newHeaders.set('cf-connecting-ip', '1.2.3.4'); 103 | // newHeaders.set('x-forwarded-for', '1.2.3.4'); 104 | // newHeaders.set('x-real-ip', '1.2.3.4'); 105 | // newHeaders.set('referer', 'https://www.google.com/search?q=edtunnel'); 106 | // // Use fetch to proxy the request to 15 different domains 107 | // const proxyUrl = 'https://' + randomHostname + url.pathname + url.search; 108 | // let modifiedRequest = new Request(proxyUrl, { 109 | // method: request.method, 110 | // headers: newHeaders, 111 | // body: request.body, 112 | // redirect: 'manual', 113 | // }); 114 | // const proxyResponse = await fetch(modifiedRequest, { redirect: 'manual' }); 115 | // // Check for 302 or 301 redirect status and return an error response 116 | // if ([301, 302].includes(proxyResponse.status)) { 117 | // return new Response(`Redirects to ${randomHostname} are not allowed.`, { 118 | // status: 403, 119 | // statusText: 'Forbidden', 120 | // }); 121 | // } 122 | //Return the response from the proxy server 123 | //return proxyResponse; 124 | } 125 | } else { 126 | return await bbbOverWSHandler(request); 127 | } 128 | } catch (err) { 129 | /** @type {Error} */ let e = err; 130 | return new Response(e.toString()); 131 | } 132 | }, 133 | }; 134 | 135 | export async function uuid_validator(request) { 136 | const hostname = request.headers.get('Host'); 137 | const currentDate = new Date(); 138 | 139 | const subdomain = hostname.split('.')[0]; 140 | const year = currentDate.getFullYear(); 141 | const month = String(currentDate.getMonth() + 1).padStart(2, '0'); 142 | const day = String(currentDate.getDate()).padStart(2, '0'); 143 | 144 | const formattedDate = `${year}-${month}-${day}`; 145 | 146 | // const daliy_sub = formattedDate + subdomain 147 | const hashHex = await hashHex_f(subdomain); 148 | // subdomain string contains timestamps utc and uuid string TODO. 149 | console.log(hashHex, subdomain, formattedDate); 150 | } 151 | 152 | export async function hashHex_f(string) { 153 | const encoder = new TextEncoder(); 154 | const data = encoder.encode(string); 155 | const hashBuffer = await crypto.subtle.digest('SHA-256', data); 156 | const hashArray = Array.from(new Uint8Array(hashBuffer)); 157 | const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join(''); 158 | return hashHex; 159 | } 160 | 161 | /** 162 | * Handles bbb over WebSocket requests by creating a WebSocket pair, accepting the WebSocket connection, and processing the bbb header. 163 | * @param {import("@cloudflare/workers-types").Request} request The incoming request object. 164 | * @returns {Promise} A Promise that resolves to a WebSocket response object. 165 | */ 166 | async function bbbOverWSHandler(request) { 167 | const webSocketPair = new WebSocketPair(); 168 | const [client, webSocket] = Object.values(webSocketPair); 169 | webSocket.accept(); 170 | 171 | let address = ''; 172 | let portWithRandomLog = ''; 173 | let currentDate = new Date(); 174 | const log = (/** @type {string} */ info, /** @type {string | undefined} */ event) => { 175 | console.log(`[${currentDate} ${address}:${portWithRandomLog}] ${info}`, event || ''); 176 | }; 177 | const earlyDataHeader = request.headers.get('sec-websocket-protocol') || ''; 178 | 179 | const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log); 180 | 181 | /** @type {{ value: import("@cloudflare/workers-types").Socket | null}}*/ 182 | let remoteSocketWapper = { 183 | value: null, 184 | }; 185 | let udpStreamWrite = null; 186 | let isDns = false; 187 | 188 | // ws --> remote 189 | readableWebSocketStream.pipeTo(new WritableStream({ 190 | async write(chunk, controller) { 191 | if (isDns && udpStreamWrite) { 192 | return udpStreamWrite(chunk); 193 | } 194 | if (remoteSocketWapper.value) { 195 | const writer = remoteSocketWapper.value.writable.getWriter() 196 | await writer.write(chunk); 197 | writer.releaseLock(); 198 | return; 199 | } 200 | 201 | const { 202 | hasError, 203 | message, 204 | portRemote = 443, 205 | addressRemote = '', 206 | rawDataIndex, 207 | bbbVersion = new Uint8Array([0, 0]), 208 | isUDP, 209 | } = processbbbHeader(chunk, userID); 210 | address = addressRemote; 211 | portWithRandomLog = `${portRemote} ${isUDP ? 'udp' : 'tcp'} `; 212 | if (hasError) { 213 | // controller.error(message); 214 | throw new Error(message); // cf seems has bug, controller.error will not end stream 215 | } 216 | 217 | // If UDP and not DNS port, close it 218 | if (isUDP && portRemote !== 53) { 219 | throw new Error('UDP proxy only enabled for DNS which is port 53'); 220 | // cf seems has bug, controller.error will not end stream 221 | } 222 | 223 | if (isUDP && portRemote === 53) { 224 | isDns = true; 225 | } 226 | 227 | // ["version", "������Ϣ���� N"] 228 | const bbbResponseHeader = new Uint8Array([bbbVersion[0], 0]); 229 | const rawClientData = chunk.slice(rawDataIndex); 230 | 231 | // TODO: support udp here when cf runtime has udp support 232 | if (isDns) { 233 | const { write } = await handleUDPOutBound(webSocket, bbbResponseHeader, log); 234 | udpStreamWrite = write; 235 | udpStreamWrite(rawClientData); 236 | return; 237 | } 238 | handleTCPOutBound(remoteSocketWapper, addressRemote, portRemote, rawClientData, webSocket, bbbResponseHeader, log); 239 | }, 240 | close() { 241 | log(`readableWebSocketStream is close`); 242 | }, 243 | abort(reason) { 244 | log(`readableWebSocketStream is abort`, JSON.stringify(reason)); 245 | }, 246 | })).catch((err) => { 247 | log('readableWebSocketStream pipeTo error', err); 248 | }); 249 | 250 | return new Response(null, { 251 | status: 101, 252 | // @ts-ignore 253 | webSocket: client, 254 | }); 255 | } 256 | 257 | /** 258 | * Handles outbound TCP connections. 259 | * 260 | * @param {any} remoteSocket 261 | * @param {string} addressRemote The remote address to connect to. 262 | * @param {number} portRemote The remote port to connect to. 263 | * @param {Uint8Array} rawClientData The raw client data to write. 264 | * @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket to pass the remote socket to. 265 | * @param {Uint8Array} bbbResponseHeader The bbb response header. 266 | * @param {function} log The logging function. 267 | * @returns {Promise} The remote socket. 268 | */ 269 | async function handleTCPOutBound(remoteSocket, addressRemote, portRemote, rawClientData, webSocket, bbbResponseHeader, log,) { 270 | 271 | /** 272 | * Connects to a given address and port and writes data to the socket. 273 | * @param {string} address The address to connect to. 274 | * @param {number} port The port to connect to. 275 | * @returns {Promise} A Promise that resolves to the connected socket. 276 | */ 277 | async function connectAndWrite(address, port) { 278 | /** @type {import("@cloudflare/workers-types").Socket} */ 279 | const tcpSocket = connect({ 280 | hostname: address, 281 | port: port, 282 | }); 283 | remoteSocket.value = tcpSocket; 284 | log(`connected to ${address}:${port}`); 285 | const writer = tcpSocket.writable.getWriter(); 286 | await writer.write(rawClientData); // first write, nomal is tls client hello 287 | writer.releaseLock(); 288 | return tcpSocket; 289 | } 290 | 291 | /** 292 | * Retries connecting to the remote address and port if the Cloudflare socket has no incoming data. 293 | * @returns {Promise} A Promise that resolves when the retry is complete. 294 | */ 295 | async function retry() { 296 | const tcpSocket = await connectAndWrite(proxyIP || addressRemote, portRemote) 297 | tcpSocket.closed.catch(error => { 298 | console.log('retry tcpSocket closed error', error); 299 | }).finally(() => { 300 | safeCloseWebSocket(webSocket); 301 | }) 302 | remoteSocketToWS(tcpSocket, webSocket, bbbResponseHeader, null, log); 303 | } 304 | 305 | const tcpSocket = await connectAndWrite(addressRemote, portRemote); 306 | 307 | // when remoteSocket is ready, pass to websocket 308 | // remote--> ws 309 | remoteSocketToWS(tcpSocket, webSocket, bbbResponseHeader, retry, log); 310 | } 311 | 312 | /** 313 | * Creates a readable stream from a WebSocket server, allowing for data to be read from the WebSocket. 314 | * @param {import("@cloudflare/workers-types").WebSocket} webSocketServer The WebSocket server to create the readable stream from. 315 | * @param {string} earlyDataHeader The header containing early data for WebSocket 0-RTT. 316 | * @param {(info: string)=> void} log The logging function. 317 | * @returns {ReadableStream} A readable stream that can be used to read data from the WebSocket. 318 | */ 319 | function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) { 320 | let readableStreamCancel = false; 321 | const stream = new ReadableStream({ 322 | start(controller) { 323 | webSocketServer.addEventListener('message', (event) => { 324 | const message = event.data; 325 | controller.enqueue(message); 326 | }); 327 | 328 | webSocketServer.addEventListener('close', () => { 329 | safeCloseWebSocket(webSocketServer); 330 | controller.close(); 331 | }); 332 | 333 | webSocketServer.addEventListener('error', (err) => { 334 | log('webSocketServer has error'); 335 | controller.error(err); 336 | }); 337 | const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader); 338 | if (error) { 339 | controller.error(error); 340 | } else if (earlyData) { 341 | controller.enqueue(earlyData); 342 | } 343 | }, 344 | 345 | pull(controller) { 346 | // if ws can stop read if stream is full, we can implement backpressure 347 | // https://streams.spec.whatwg.org/#example-rs-push-backpressure 348 | }, 349 | 350 | cancel(reason) { 351 | log(`ReadableStream was canceled, due to ${reason}`) 352 | readableStreamCancel = true; 353 | safeCloseWebSocket(webSocketServer); 354 | } 355 | }); 356 | 357 | return stream; 358 | } 359 | 360 | // https://xtls.github.io/development/protocols/bbb.html 361 | // https://github.com/zizifn/excalidraw-backup/blob/main/v2ray-protocol.excalidraw 362 | 363 | /** 364 | * Processes the bbb header buffer and returns an object with the relevant information. 365 | * @param {ArrayBuffer} bbbBuffer The bbb header buffer to process. 366 | * @param {string} userID The user ID to validate against the UUID in the bbb header. 367 | * @returns {{ 368 | * hasError: boolean, 369 | * message?: string, 370 | * addressRemote?: string, 371 | * addressType?: number, 372 | * portRemote?: number, 373 | * rawDataIndex?: number, 374 | * bbbVersion?: Uint8Array, 375 | * isUDP?: boolean 376 | * }} An object with the relevant information extracted from the bbb header buffer. 377 | */ 378 | function processbbbHeader(bbbBuffer, userID) { 379 | if (bbbBuffer.byteLength < 24) { 380 | return { 381 | hasError: true, 382 | message: 'invalid data', 383 | }; 384 | } 385 | 386 | const version = new Uint8Array(bbbBuffer.slice(0, 1)); 387 | let isValidUser = false; 388 | let isUDP = false; 389 | const slicedBuffer = new Uint8Array(bbbBuffer.slice(1, 17)); 390 | const slicedBufferString = stringify(slicedBuffer); 391 | // check if userID is valid uuid or uuids split by , and contains userID in it otherwise return error message to console 392 | const uuids = userID.includes(',') ? userID.split(",") : [userID]; 393 | // uuid_validator(hostName, slicedBufferString); 394 | 395 | 396 | // isValidUser = uuids.some(userUuid => slicedBufferString === userUuid.trim()); 397 | isValidUser = uuids.some(userUuid => slicedBufferString === userUuid.trim()) || uuids.length === 1 && slicedBufferString === uuids[0].trim(); 398 | 399 | console.log(`userID: ${slicedBufferString}`); 400 | 401 | if (!isValidUser) { 402 | return { 403 | hasError: true, 404 | message: 'invalid user', 405 | }; 406 | } 407 | 408 | const optLength = new Uint8Array(bbbBuffer.slice(17, 18))[0]; 409 | //skip opt for now 410 | 411 | const command = new Uint8Array( 412 | bbbBuffer.slice(18 + optLength, 18 + optLength + 1) 413 | )[0]; 414 | 415 | // 0x01 TCP 416 | // 0x02 UDP 417 | // 0x03 MUX 418 | if (command === 1) { 419 | isUDP = false; 420 | } else if (command === 2) { 421 | isUDP = true; 422 | } else { 423 | return { 424 | hasError: true, 425 | message: `command ${command} is not support, command 01-tcp,02-udp,03-mux`, 426 | }; 427 | } 428 | const portIndex = 18 + optLength + 1; 429 | const portBuffer = bbbBuffer.slice(portIndex, portIndex + 2); 430 | // port is big-Endian in raw data etc 80 == 0x005d 431 | const portRemote = new DataView(portBuffer).getUint16(0); 432 | 433 | let addressIndex = portIndex + 2; 434 | const addressBuffer = new Uint8Array( 435 | bbbBuffer.slice(addressIndex, addressIndex + 1) 436 | ); 437 | 438 | // 1--> ipv4 addressLength =4 439 | // 2--> domain name addressLength=addressBuffer[1] 440 | // 3--> ipv6 addressLength =16 441 | const addressType = addressBuffer[0]; 442 | let addressLength = 0; 443 | let addressValueIndex = addressIndex + 1; 444 | let addressValue = ''; 445 | switch (addressType) { 446 | case 1: 447 | addressLength = 4; 448 | addressValue = new Uint8Array( 449 | bbbBuffer.slice(addressValueIndex, addressValueIndex + addressLength) 450 | ).join('.'); 451 | break; 452 | case 2: 453 | addressLength = new Uint8Array( 454 | bbbBuffer.slice(addressValueIndex, addressValueIndex + 1) 455 | )[0]; 456 | addressValueIndex += 1; 457 | addressValue = new TextDecoder().decode( 458 | bbbBuffer.slice(addressValueIndex, addressValueIndex + addressLength) 459 | ); 460 | break; 461 | case 3: 462 | addressLength = 16; 463 | const dataView = new DataView( 464 | bbbBuffer.slice(addressValueIndex, addressValueIndex + addressLength) 465 | ); 466 | // 2001:0db8:85a3:0000:0000:8a2e:0370:7334 467 | const ipv6 = []; 468 | for (let i = 0; i < 8; i++) { 469 | ipv6.push(dataView.getUint16(i * 2).toString(16)); 470 | } 471 | addressValue = ipv6.join(':'); 472 | // seems no need add [] for ipv6 473 | break; 474 | default: 475 | return { 476 | hasError: true, 477 | message: `invild addressType is ${addressType}`, 478 | }; 479 | } 480 | if (!addressValue) { 481 | return { 482 | hasError: true, 483 | message: `addressValue is empty, addressType is ${addressType}`, 484 | }; 485 | } 486 | 487 | return { 488 | hasError: false, 489 | addressRemote: addressValue, 490 | addressType, 491 | portRemote, 492 | rawDataIndex: addressValueIndex + addressLength, 493 | bbbVersion: version, 494 | isUDP, 495 | }; 496 | } 497 | 498 | 499 | /** 500 | * Converts a remote socket to a WebSocket connection. 501 | * @param {import("@cloudflare/workers-types").Socket} remoteSocket The remote socket to convert. 502 | * @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket to connect to. 503 | * @param {ArrayBuffer | null} bbbResponseHeader The bbb response header. 504 | * @param {(() => Promise) | null} retry The function to retry the connection if it fails. 505 | * @param {(info: string) => void} log The logging function. 506 | * @returns {Promise} A Promise that resolves when the conversion is complete. 507 | */ 508 | async function remoteSocketToWS(remoteSocket, webSocket, bbbResponseHeader, retry, log) { 509 | // remote--> ws 510 | let remoteChunkCount = 0; 511 | let chunks = []; 512 | /** @type {ArrayBuffer | null} */ 513 | let bbbHeader = bbbResponseHeader; 514 | let hasIncomingData = false; // check if remoteSocket has incoming data 515 | await remoteSocket.readable 516 | .pipeTo( 517 | new WritableStream({ 518 | start() { 519 | }, 520 | /** 521 | * 522 | * @param {Uint8Array} chunk 523 | * @param {*} controller 524 | */ 525 | async write(chunk, controller) { 526 | hasIncomingData = true; 527 | remoteChunkCount++; 528 | if (webSocket.readyState !== WS_READY_STATE_OPEN) { 529 | controller.error( 530 | 'webSocket.readyState is not open, maybe close' 531 | ); 532 | } 533 | if (bbbHeader) { 534 | webSocket.send(await new Blob([bbbHeader, chunk]).arrayBuffer()); 535 | bbbHeader = null; 536 | } else { 537 | // console.log(`remoteSocketToWS send chunk ${chunk.byteLength}`); 538 | // seems no need rate limit this, CF seems fix this??.. 539 | // if (remoteChunkCount > 20000) { 540 | // // cf one package is 4096 byte(4kb), 4096 * 20000 = 80M 541 | // await delay(1); 542 | // } 543 | webSocket.send(chunk); 544 | } 545 | }, 546 | close() { 547 | log(`remoteConnection!.readable is close with hasIncomingData is ${hasIncomingData}`); 548 | // safeCloseWebSocket(webSocket); // no need server close websocket frist for some case will casue HTTP ERR_CONTENT_LENGTH_MISMATCH issue, client will send close event anyway. 549 | }, 550 | abort(reason) { 551 | console.error(`remoteConnection!.readable abort`, reason); 552 | }, 553 | }) 554 | ) 555 | .catch((error) => { 556 | console.error( 557 | `remoteSocketToWS has exception `, 558 | error.stack || error 559 | ); 560 | safeCloseWebSocket(webSocket); 561 | }); 562 | 563 | // seems is cf connect socket have error, 564 | // 1. Socket.closed will have error 565 | // 2. Socket.readable will be close without any data coming 566 | if (hasIncomingData === false && retry) { 567 | log(`retry`) 568 | retry(); 569 | } 570 | } 571 | 572 | /** 573 | * Decodes a base64 string into an ArrayBuffer. 574 | * @param {string} base64Str The base64 string to decode. 575 | * @returns {{earlyData: ArrayBuffer|null, error: Error|null}} An object containing the decoded ArrayBuffer or null if there was an error, and any error that occurred during decoding or null if there was no error. 576 | */ 577 | function base64ToArrayBuffer(base64Str) { 578 | if (!base64Str) { 579 | return { earlyData: null, error: null }; 580 | } 581 | try { 582 | // go use modified Base64 for URL rfc4648 which js atob not support 583 | base64Str = base64Str.replace(/-/g, '+').replace(/_/g, '/'); 584 | const decode = atob(base64Str); 585 | const arryBuffer = Uint8Array.from(decode, (c) => c.charCodeAt(0)); 586 | return { earlyData: arryBuffer.buffer, error: null }; 587 | } catch (error) { 588 | return { earlyData: null, error }; 589 | } 590 | } 591 | 592 | /** 593 | * Checks if a given string is a valid UUID. 594 | * Note: This is not a real UUID validation. 595 | * @param {string} uuid The string to validate as a UUID. 596 | * @returns {boolean} True if the string is a valid UUID, false otherwise. 597 | */ 598 | function isValidUUID(uuid) { 599 | const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; 600 | return uuidRegex.test(uuid); 601 | } 602 | 603 | const WS_READY_STATE_OPEN = 1; 604 | const WS_READY_STATE_CLOSING = 2; 605 | /** 606 | * Closes a WebSocket connection safely without throwing exceptions. 607 | * @param {import("@cloudflare/workers-types").WebSocket} socket The WebSocket connection to close. 608 | */ 609 | function safeCloseWebSocket(socket) { 610 | try { 611 | if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) { 612 | socket.close(); 613 | } 614 | } catch (error) { 615 | console.error('safeCloseWebSocket error', error); 616 | } 617 | } 618 | 619 | const byteToHex = []; 620 | 621 | for (let i = 0; i < 256; ++i) { 622 | byteToHex.push((i + 256).toString(16).slice(1)); 623 | } 624 | 625 | function unsafeStringify(arr, offset = 0) { 626 | return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); 627 | } 628 | 629 | function stringify(arr, offset = 0) { 630 | const uuid = unsafeStringify(arr, offset); 631 | if (!isValidUUID(uuid)) { 632 | throw TypeError("Stringified UUID is invalid"); 633 | } 634 | return uuid; 635 | } 636 | 637 | 638 | /** 639 | * Handles outbound UDP traffic by transforming the data into DNS queries and sending them over a WebSocket connection. 640 | * @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket connection to send the DNS queries over. 641 | * @param {ArrayBuffer} bbbResponseHeader The bbb response header. 642 | * @param {(string) => void} log The logging function. 643 | * @returns {{write: (chunk: Uint8Array) => void}} An object with a write method that accepts a Uint8Array chunk to write to the transform stream. 644 | */ 645 | async function handleUDPOutBound(webSocket, bbbResponseHeader, log) { 646 | 647 | let isbbbHeaderSent = false; 648 | const transformStream = new TransformStream({ 649 | start(controller) { 650 | 651 | }, 652 | transform(chunk, controller) { 653 | // udp message 2 byte is the the length of udp data 654 | // TODO: this should have bug, beacsue maybe udp chunk can be in two websocket message 655 | for (let index = 0; index < chunk.byteLength;) { 656 | const lengthBuffer = chunk.slice(index, index + 2); 657 | const udpPakcetLength = new DataView(lengthBuffer).getUint16(0); 658 | const udpData = new Uint8Array( 659 | chunk.slice(index + 2, index + 2 + udpPakcetLength) 660 | ); 661 | index = index + 2 + udpPakcetLength; 662 | controller.enqueue(udpData); 663 | } 664 | }, 665 | flush(controller) { 666 | } 667 | }); 668 | 669 | // only handle dns udp for now 670 | transformStream.readable.pipeTo(new WritableStream({ 671 | async write(chunk) { 672 | const resp = await fetch(dohURL, // dns server url 673 | { 674 | method: 'POST', 675 | headers: { 676 | 'content-type': 'application/dns-message', 677 | }, 678 | body: chunk, 679 | }) 680 | const dnsQueryResult = await resp.arrayBuffer(); 681 | const udpSize = dnsQueryResult.byteLength; 682 | // console.log([...new Uint8Array(dnsQueryResult)].map((x) => x.toString(16))); 683 | const udpSizeBuffer = new Uint8Array([(udpSize >> 8) & 0xff, udpSize & 0xff]); 684 | if (webSocket.readyState === WS_READY_STATE_OPEN) { 685 | log(`doh success and dns message length is ${udpSize}`); 686 | if (isbbbHeaderSent) { 687 | webSocket.send(await new Blob([udpSizeBuffer, dnsQueryResult]).arrayBuffer()); 688 | } else { 689 | webSocket.send(await new Blob([bbbResponseHeader, udpSizeBuffer, dnsQueryResult]).arrayBuffer()); 690 | isbbbHeaderSent = true; 691 | } 692 | } 693 | } 694 | })).catch((error) => { 695 | log('dns udp has error' + error) 696 | }); 697 | 698 | const writer = transformStream.writable.getWriter(); 699 | 700 | return { 701 | /** 702 | * 703 | * @param {Uint8Array} chunk 704 | */ 705 | write(chunk) { 706 | writer.write(chunk); 707 | } 708 | }; 709 | } 710 | 711 | /** 712 | * 713 | * @param {string} userID - single or comma separated userIDs 714 | * @param {string | null} hostName 715 | * @returns {string} 716 | */ 717 | function getbbbConfig(userIDs, hostName) { 718 | const commonUrlPart = `:443?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2048#${hostName}`; 719 | const hashSeparator = "################################################################"; 720 | 721 | // Split the userIDs into an array 722 | const userIDArray = userIDs.split(","); 723 | 724 | // Prepare output string for each userID 725 | const output = userIDArray.map((userID) => { 726 | const bbbMain = getprotocol()+'://' + userID + '@' + hostName + commonUrlPart; 727 | const bbbSec = getprotocol()+'://' + userID + '@' + proxyIP + commonUrlPart; 728 | return `

UUID: ${userID}

${hashSeparator}\nv2ray default ip 729 | --------------------------------------------------------------- 730 | ${bbbMain} 731 | 732 | --------------------------------------------------------------- 733 | v2ray with bestip 734 | --------------------------------------------------------------- 735 | ${bbbSec} 736 | 737 | ---------------------------------------------------------------`; 738 | }).join('\n'); 739 | const sublink = `https://${hostName}/sub/${userIDArray[0]}?format=clash` 740 | const subbestip = `https://${hostName}/bestip/${userIDArray[0]}`; 741 | const clash_link = `https://api.v1.mk/sub?target=clash&url=${encodeURIComponent(sublink)}&insert=false&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`; 742 | // Prepare header string 743 | const header = ` 744 |

ͼƬ���� 745 | Welcome! This function generates configuration for bbb protocol. If you found this useful, please check our GitHub project for more: 746 | ��ӭ���������� bbb Э������á���������������Ŀ�ܺ��ã���鿴���ǵ� GitHub ��Ŀ����һ��star�� 747 | EDtunnel - https://github.com/3Kmfi6HP/EDtunnel 748 | 749 | bbb �ڵ㶩������ 750 | Clash for Windows �ڵ㶩������ 751 | Clash �ڵ㶩������ 752 | ��ѡIP�Զ��ڵ㶩�� 753 | Clash��ѡIP�Զ� 754 | singbox��ѡIP�Զ� 755 | nekobox��ѡIP�Զ� 756 | v2rayNG��ѡIP�Զ�

`; 757 | 758 | // HTML Head with CSS and FontAwesome library 759 | const htmlHead = ` 760 | 761 | EDtunnel: bbb configuration 762 | 763 | 764 | 765 | 766 | 767 | 768 | 769 | 770 | 771 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 821 | 822 | 823 | 824 | 825 | `; 826 | 827 | // Join output with newlines, wrap inside and 828 | return ` 829 | 830 | ${htmlHead} 831 | 832 |
${header}
833 |
${output}
834 | 835 | 846 | `; 847 | } 848 | 849 | const portSet_http = new Set([80, 8080, 8880, 2052, 2086, 2095, 2082]); 850 | const portSet_https = new Set([443, 8443, 2053, 2096, 2087, 2083]); 851 | 852 | function createbbbSub(userID_Path, hostName) { 853 | const userIDArray = userID_Path.includes(',') ? userID_Path.split(',') : [userID_Path]; 854 | const commonUrlPart_http = `?encryption=none&security=none&fp=random&type=ws&host=${hostName}&path=%2F%3Fed%3D2048#`; 855 | const commonUrlPart_https = `?encryption=none&security=tls&sni=${hostName}&fp=random&type=ws&host=${hostName}&path=%2F%3Fed%3D2048#`; 856 | 857 | const output = userIDArray.flatMap((userID) => { 858 | const httpConfigurations = Array.from(portSet_http).flatMap((port) => { 859 | if (!hostName.includes('pages.dev')) { 860 | const urlPart = `${hostName}-HTTP-${port}`; 861 | const bbbMainHttp = getprotocol()+'://' + userID + '@' + hostName + ':' + port + commonUrlPart_http + urlPart; 862 | return proxyIPs.flatMap((proxyIP) => { 863 | const bbbSecHttp = getprotocol()+'://' + userID + '@' + proxyIP + ':' + port + commonUrlPart_http + urlPart + '-' + proxyIP + '-EDtunnel'; 864 | return [bbbMainHttp, bbbSecHttp]; 865 | }); 866 | } 867 | return []; 868 | }); 869 | 870 | const httpsConfigurations = Array.from(portSet_https).flatMap((port) => { 871 | const urlPart = `${hostName}-HTTPS-${port}`; 872 | const bbbMainHttps = getprotocol() + '://' + userID + '@' + hostName + ':' + port + commonUrlPart_https + urlPart; 873 | return proxyIPs.flatMap((proxyIP) => { 874 | const bbbSecHttps = getprotocol() + '://' + userID + '@' + proxyIP + ':' + port + commonUrlPart_https + urlPart + '-' + proxyIP + '-EDtunnel'; 875 | return [bbbMainHttps, bbbSecHttps]; 876 | }); 877 | }); 878 | 879 | return [...httpConfigurations, ...httpsConfigurations]; 880 | }); 881 | 882 | return output.join('\n'); 883 | } 884 | 885 | const cn_hostnames = [ 886 | 'weibo.com', // Weibo - A popular social media platform 887 | 'www.baidu.com', // Baidu - The largest search engine in China 888 | 'www.bing.com', 889 | 890 | ]; --------------------------------------------------------------------------------