Repository: frankiejun/cvwt Branch: main Commit: b81de9743d05 Files: 26 Total size: 180.2 KB Directory structure: gitextract_yd9geek9/ ├── 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 │ │ ├── wxpush.sh │ │ └── wxsend_jiang.sh │ ├── start-v2.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 ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # Cloudflare 上建 workers 和 pages 节点及自动化优选 IP 的一揽子工具 优选工具使用 CloudflareSpeedTest,用法如下: ```cvs 参数: -n 200 延迟测速线程;越多延迟测速越快,性能弱的设备 (如路由器) 请勿太高;(默认 200 最多 1000) -t 4 延迟测速次数;单个 IP 延迟测速的次数;(默认 4 次) -dn 10 下载测速数量;延迟测速并排序后,从最低延迟起下载测速的数量;(默认 10 个) -dt 10 下载测速时间;单个 IP 下载测速最长时间,不能太短;(默认 10 秒) -tp 443 指定测速端口;延迟测速/下载测速时使用的端口;(默认 443 端口) -url https://cf.xiu2.xyz/url 指定测速地址;延迟测速(HTTPing)/下载测速时使用的地址,默认地址不保证可用性,建议自建; -httping 切换测速模式;延迟测速模式改为 HTTP 协议,所用测试地址为 [-url] 参数;(默认 TCPing) 注意:HTTPing 本质上也算一种 网络扫描 行为,因此如果你在服务器上面运行,需要降低并发(-n),否则可能会被一些严格的商家暂停服务。 如果你遇到 HTTPing 首次测速可用 IP 数量正常,后续测速越来越少甚至直接为 0,但停一段时间后又恢复了的情况,那么也可能是被 运营商、Cloudflare CDN 认为你在网络扫描而 触发临时限制机制,因此才会过一会儿就恢复了,建议降低并发(-n)减少这种情况的发生。 -httping-code 200 有效状态代码;HTTPing 延迟测速时网页返回的有效 HTTP 状态码,仅限一个;(默认 200 301 302) -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD 匹配指定地区;地区名为当地机场三字码,英文逗号分隔,支持小写,支持 Cloudflare、AWS CloudFront,仅 HTTPing 模式可用;(默认 所有地区) -tl 200 平均延迟上限;只输出低于指定平均延迟的 IP,各上下限条件可搭配使用;(默认 9999 ms) -tll 40 平均延迟下限;只输出高于指定平均延迟的 IP;(默认 0 ms) -tlr 0.2 丢包几率上限;只输出低于/等于指定丢包率的 IP,范围 0.00~1.00,0 过滤掉任何丢包的 IP;(默认 1.00) -sl 5 下载速度下限;只输出高于指定下载速度的 IP,凑够指定数量 [-dn] 才会停止测速;(默认 0.00 MB/s) -p 10 显示结果数量;测速后直接显示指定数量的结果,为 0 时不显示结果直接退出;(默认 10 个) -f ip.txt IP段数据文件;如路径含有空格请加上引号;支持其他 CDN IP段;(默认 ip.txt) -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32 指定IP段数据;直接通过参数指定要测速的 IP 段数据,英文逗号分隔;(默认 空) -o result.csv 写入结果文件;如路径含有空格请加上引号;值为空时不写入文件 [-o ""];(默认 result.csv) -dd 禁用下载测速;禁用后测速结果会按延迟排序 (默认按下载速度排序);(默认 启用) -allip 测速全部的IP;对 IP 段中的每个 IP (仅支持 IPv4) 进行测速;(默认 每个 /24 段随机测速一个 IP) -c 按国家代码分类输出文件 -cc 指定国家代码选择IP,仅支持 IPv4;(默认 所有国家) -v 打印程序版本 + 检查版本更新 -h 打印帮助说明 ``` ## workers 变量说明 | 变量 | 是否必须 | 例子 | 说明 | | -------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | `UUID` | No | `12345678-1234-1234-1234-123456789012` | 唯一标识 | | `PROXYIP` | No | `1.1.1.1` or `cdn.xn--b6gac.eu.org` or with port `1.1.1.1:9443` or `[2a01:4f8:c2c:123f:64:5:6810:c55a]:443` or use multiple proxyIPs `1.1.1.1:80,2.2.2.2:443,example.com:443` | ProxyIP 格式 | | `SOCKS5` | No | `1.1.1.1:1080` or `user:pass@host:port` | SOCKS5 代理 | | `SOCKS5_RELAY` | No | `true` or `false` | true 时所有流量走代理 | ## 鸣谢 [IU2](https://github.com/XIU2/CloudflareSpeedTest), [6Kmfi6HP](https://github.com/6Kmfi6HP/EDtunnel), [ca110us](https://github.com/ca110us/epeius), [CM](https://github.com/cmliu/CF-Workers-SpeedTestURL) ## License The GPL-3.0 License. ================================================ FILE: cf_speedtest.js ================================================ export default { async fetch(request) { const url = new URL(request.url); const path = url.pathname.substring(1); let bytes = 100000000; // Default 100MB if (path) { const match = path.match(/^(\d+)([a-z]{0,2})$/i); if (!match) { return new Response("路径格式不正确", { status: 400 }); } const size = parseInt(match[1], 10); const unit = match[2].toLowerCase(); const multipliers = { 'k': 1000, 'kb': 1000, 'm': 1000000, 'mb': 1000000, 'g': 1000000000, 'gb': 1000000000 }; bytes = size * (multipliers[unit] || 1); } const targetUrl = `https://speed.cloudflare.com/__down?bytes=${bytes}`; const headers = new Headers(request.headers); headers.set('referer', 'https://speed.cloudflare.com/'); return fetch(new Request(targetUrl, { method: request.method, headers: headers, body: request.body })); } }; ================================================ FILE: go.mod ================================================ module github.com/XIU2/CloudflareSpeedTest go 1.14 require ( github.com/VividCortex/ewma v1.1.1 github.com/cheggaaa/pb/v3 v3.0.4 github.com/oschwald/maxminddb-golang v1.12.0 golang.org/x/text v0.14.0 ) ================================================ FILE: go.sum ================================================ github.com/VividCortex/ewma v1.1.1 h1:MnEK4VOv6n0RSY4vtRe3h11qjxL3+t0B8yOL8iMXdcM= github.com/VividCortex/ewma v1.1.1/go.mod h1:2Tkkvm3sRDVXaiyucHiACn4cqf7DpdyLvmxzcbUokwA= github.com/cheggaaa/pb/v3 v3.0.4 h1:QZEPYOj2ix6d5oEg63fbHmpolrnNiwjUsk+h74Yt4bM= github.com/cheggaaa/pb/v3 v3.0.4/go.mod h1:7rgWxLrAUcFMkvJuv09+DYi7mMUYi8nO9iOWcvGJPfw= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= github.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW10= github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54= github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/oschwald/maxminddb-golang v1.12.0 h1:9FnTOD0YOhP7DGxGsq4glzpGy5+w7pq50AS6wALUMYs= github.com/oschwald/maxminddb-golang v1.12.0/go.mod h1:q0Nob5lTCqyQ8WT6FYgS1L7PXKVVbgiymefNwIjPzgY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191128015809-6d18c012aee9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ================================================ FILE: main.go ================================================ package main import ( "flag" "fmt" "github.com/oschwald/maxminddb-golang" "io/ioutil" "net/http" "os" "runtime" "sort" "strings" "time" "github.com/XIU2/CloudflareSpeedTest/task" "github.com/XIU2/CloudflareSpeedTest/utils" ) var ( version, versionNew string BCountry bool = false CountryCodes string CountryList map[string]bool ) func init() { var printVersion bool var help = ` CloudflareSpeedTest ` + version + ` 测试 Cloudflare CDN 所有 IP 的延迟和速度,获取最快 IP (IPv4+IPv6)! https://github.com/XIU2/CloudflareSpeedTest 参数: -n 200 延迟测速线程;越多延迟测速越快,性能弱的设备 (如路由器) 请勿太高;(默认 200 最多 1000) -t 4 延迟测速次数;单个 IP 延迟测速的次数;(默认 4 次) -dn 10 下载测速数量;延迟测速并排序后,从最低延迟起下载测速的数量;(默认 10 个) -dt 10 下载测速时间;单个 IP 下载测速最长时间,不能太短;(默认 10 秒) -tp 443 指定测速端口;延迟测速/下载测速时使用的端口;(默认 443 端口) -url https://cf.xiu2.xyz/url 指定测速地址;延迟测速(HTTPing)/下载测速时使用的地址,默认地址不保证可用性,建议自建; -httping 切换测速模式;延迟测速模式改为 HTTP 协议,所用测试地址为 [-url] 参数;(默认 TCPing) -httping-code 200 有效状态代码;HTTPing 延迟测速时网页返回的有效 HTTP 状态码,仅限一个;(默认 200 301 302) -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD 匹配指定地区;地区名为当地机场三字码,英文逗号分隔,仅 HTTPing 模式可用;(默认 所有地区) -tl 200 平均延迟上限;只输出低于指定平均延迟的 IP,各上下限条件可搭配使用;(默认 9999 ms) -tll 40 平均延迟下限;只输出高于指定平均延迟的 IP;(默认 0 ms) -tlr 0.2 丢包几率上限;只输出低于/等于指定丢包率的 IP,范围 0.00~1.00,0 过滤掉任何丢包的 IP;(默认 1.00) -sl 5 下载速度下限;只输出高于指定下载速度的 IP,凑够指定数量 [-dn] 才会停止测速;(默认 0.00 MB/s) -p 10 显示结果数量;测速后直接显示指定数量的结果,为 0 时不显示结果直接退出;(默认 10 个) -f ip.txt IP段数据文件;如路径含有空格请加上引号;支持其他 CDN IP段;(默认 ip.txt) -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32 指定IP段数据;直接通过参数指定要测速的 IP 段数据,英文逗号分隔;(默认 空) -o result.csv 写入结果文件;如路径含有空格请加上引号;值为空时不写入文件 [-o ""];(默认 result.csv) -dd 禁用下载测速;禁用后测速结果会按延迟排序 (默认按下载速度排序);(默认 启用) -allip 测速全部的IP;对 IP 段中的每个 IP (仅支持 IPv4) 进行测速;(默认 每个 /24 段随机测速一个 IP) -c 显示国家信息,按国家分类输出并按速度排序。 -cc 配合-cc使用,指定所需的国家ip,输入国家代码,多个用逗号分隔。如 US,JP -v 打印程序版本 + 检查版本更新 -h 打印帮助说明 ` var minDelay, maxDelay, downloadTime int var maxLossRate float64 flag.IntVar(&task.Routines, "n", 200, "延迟测速线程") flag.IntVar(&task.PingTimes, "t", 4, "延迟测速次数") flag.IntVar(&task.TestCount, "dn", 10, "下载测速数量") flag.IntVar(&downloadTime, "dt", 10, "下载测速时间") flag.IntVar(&task.TCPPort, "tp", 443, "指定测速端口") flag.StringVar(&task.URL, "url", "https://cf.xiu2.xyz/url", "指定测速地址") flag.BoolVar(&task.Httping, "httping", false, "切换测速模式") flag.IntVar(&task.HttpingStatusCode, "httping-code", 0, "有效状态代码") flag.StringVar(&task.HttpingCFColo, "cfcolo", "", "匹配指定地区") flag.IntVar(&maxDelay, "tl", 9999, "平均延迟上限") flag.IntVar(&minDelay, "tll", 0, "平均延迟下限") flag.Float64Var(&maxLossRate, "tlr", 1, "丢包几率上限") flag.Float64Var(&task.MinSpeed, "sl", 0, "下载速度下限") flag.IntVar(&utils.PrintNum, "p", 10, "显示结果数量") flag.StringVar(&task.IPFile, "f", "ip.txt", "IP段数据文件") flag.StringVar(&task.IPText, "ip", "", "指定IP段数据") flag.StringVar(&utils.Output, "o", "result.csv", "输出结果文件") flag.StringVar(&CountryCodes, "cc", "", "指定国家代码,多个用逗号分隔") flag.BoolVar(&BCountry, "c", false, "按国家代码分类输出文件") flag.BoolVar(&task.Disable, "dd", false, "禁用下载测速") flag.BoolVar(&task.TestAll, "allip", false, "测速全部 IP") flag.BoolVar(&printVersion, "v", false, "打印程序版本") flag.Usage = func() { fmt.Print(help) } flag.Parse() if task.MinSpeed > 0 && time.Duration(maxDelay)*time.Millisecond == utils.InputMaxDelay { fmt.Println("[小提示] 在使用 [-sl] 参数时,建议搭配 [-tl] 参数,以避免因凑不够 [-dn] 数量而一直测速...") } utils.InputMaxDelay = time.Duration(maxDelay) * time.Millisecond utils.InputMinDelay = time.Duration(minDelay) * time.Millisecond utils.InputMaxLossRate = float32(maxLossRate) task.Timeout = time.Duration(downloadTime) * time.Second task.HttpingCFColomap = task.MapColoMap() if printVersion { println(version) fmt.Println("检查版本更新中...") checkUpdate() if versionNew != "" { fmt.Printf("*** 发现新版本 [%s]!请前往 [https://github.com/XIU2/CloudflareSpeedTest] 更新! ***", versionNew) } else { fmt.Println("当前为最新版本 [" + version + "]!") } os.Exit(0) } } func main() { task.InitRandSeed() // 置随机数种子 if BCountry { fmt.Println("分国家测速模式") if CountryCodes != "" { codes := strings.Split(CountryCodes, ",") if len(codes) > 0 { CountryList = make(map[string]bool) for _, code := range codes { CountryList[code] = true } } } } fmt.Printf("# XIU2/CloudflareSpeedTest %s \n\n", version) // 开始延迟测速 + 过滤延迟/丢包 pingData := task.NewPing().Run().FilterDelay().FilterLossRate() if BCountry { db, err := maxminddb.Open("Country.mmdb") if err != nil { fmt.Println(err) return } countryinfo := utils.NewCountryInfo(db) CountrypingData := pingData.FilterCountryV2(countryinfo, CountryList) countryinfo.Done() if CountrypingData == nil { return } //按国家代号排序,每个国家按延迟从小到大排序 sort.Slice(CountrypingData, func(i, j int) bool { left := CountrypingData[i].Country + fmt.Sprintf("%d", CountrypingData[i].Delay) right := CountrypingData[j].Country + fmt.Sprintf("%d", CountrypingData[j].Delay) return left < right }) speedData := task.TestDownloadSpeedByCountry(CountrypingData) utils.ExportCsvByCountry(speedData) } else { // 开始下载测速 speedData := task.TestDownloadSpeed(pingData) utils.ExportCsv(speedData) // 输出文件 speedData.Print() // 打印结果 } if versionNew != "" { fmt.Printf("\n*** 发现新版本 [%s]!请前往 [https://github.com/XIU2/CloudflareSpeedTest] 更新! ***\n", versionNew) } endPrint() } func endPrint() { if utils.NoPrintResult() { return } if runtime.GOOS == "windows" { // 如果是 Windows 系统,则需要按下 回车键 或 Ctrl+C 退出(避免通过双击运行时,测速完毕后直接关闭) fmt.Printf("按下 回车键 或 Ctrl+C 退出。") fmt.Scanln() } } // 检查更新 func checkUpdate() { timeout := 10 * time.Second client := http.Client{Timeout: timeout} res, err := client.Get("https://api.xiu2.xyz/ver/cloudflarespeedtest.txt") if err != nil { return } // 读取资源数据 body: []byte body, err := ioutil.ReadAll(res.Body) if err != nil { return } // 关闭资源流 defer res.Body.Close() if string(body) != version { versionNew = string(body) } } ================================================ FILE: script/openwrt/cf_RE.sh ================================================ #!/bin/bash ##用于openwrt安装jq和timeout,确保CloudflareSpeedTestDDNS运行正常。 opkg update opkg install jq coreutils-timeout opkg install yq opkg list-installed | grep jq opkg list-installed | grep coreutils-timeout ================================================ FILE: script/openwrt/config.yaml ================================================ ##cloudflare配置 cloudflare: #cloudflare账号邮箱 - x_email: #域名(多个用逗号分隔) hostname: #空间ID zone_id: #Global API Key api_key: #配置多个账号或域名,注意字段使用空格对齐,符合yaml格式要求 # - x_email: # # #域名(多个用逗号分隔) # hostname: # # #空间ID # zone_id: # # #Global API Key # api_key: ##openwrt科学上网插件配置 #优选节点时是否自动停止科学上网服务 true: 自动停止 false: 不停止 默认为 true pause: true #填写openwrt使用的是哪个科学上网客户端,填写对应的“数字” 默认为 1 客户端为passwall # 1: passwall 2: passwall2 3: ShadowSocksR Plus+ 4: clash 5: openclash 6: bypass clien: 1 #同一域名更新的ip数量(如果设置值大于实际搜出的ip数量,以实际ip数量为准) multip: #测速地址 CFST_URL: #测速线程数量;越多测速越快,性能弱的设备 (如路由器) 请勿太高;(默认 200 最多 1000 ) CFST_N: 200 #延迟测速次数;单个 IP 延迟测速次数,为 1 时将过滤丢包的IP,TCP协议;(默认 4 次 ) CFST_T: 1 #下载测速数量;延迟测速并排序后,从最低延迟起下载测速的数量;(默认 10 个) CFST_DN: 10 #平均延迟上限;只输出低于指定平均延迟的 IP,可与其他上限/下限搭配;(默认9999 ms 这里推荐配置250 ms) CFST_TL: 250 #平均延迟下限;只输出高于指定平均延迟的 IP,可与其他上限/下限搭配、过滤假墙 IP;(默认 0 ms 这里推荐配置40) CFST_TLL: 40 #下载速度下限;只输出高于指定下载速度的 IP,凑够指定数量 [-dn] 才会停止测速;(默认 0.00 MB/s 这里推荐5.00MB/s) CFST_SL: 5 #是否按国家代码做分组筛选(是: true,否: false) CCFLAG: true #需要指定的国家代码,多个用逗号分隔(eg. US,JP) CCODE: #CF服务器对应端口 CF_ADDR: 443 #推送开关, 1:TG, 2:WX, 3.both. sendType: 3 ##TG推送设置 #(填写即为开启推送,未填写则为不开启) #TG机器人token 例如:123456789: ABCDEFG... telegramBotToken: telegramBotUserId: #微信推送, 通过https://sct.ftqq.com/r/13223 注册并登录server酱,取得sendKey sendKey: #微信推送api wxpushAPI: wxToken: ================================================ FILE: script/openwrt/ddns/cf_ddns ================================================ #!/bin/bash #新功能,支持更新优选完毕后推送至TG,再也不怕脚本没有成功运行了。 #使用脚本需要安装jq和timeout,新增openwrt专用cf_RE.sh文件,运行cf_RE.sh即可在openwrt安装jq和timeout两个扩展。 #其他linux请自行安装jq和timeout。 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])" #默认关闭小云朵 proxy="false" chkDnsArr=() delDnsArr=() excludeIp=() CheckDelCFDns() { listDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records?name=${CDNhostname}" excludeIp=() delDnsArr=() chkDnsArr=() res=$(curl -s -X GET "$listDnsApi" -H "X-Auth-Email:$x_email" -H "X-Auth-Key:$api_key" -H "Content-Type:application/json") total_ct=$(echo "$res" | jq -r ".result_info.total_count") #echo "multFlag: $multFlag" if ((total_ct > 1 || multFlag == 1)); then # echo "total_ct:$total_ct" for ((i = 0; i < total_ct; i++)); do record_id=$(echo "$res" | jq -r ".result[$i].id") ip=$(echo "$res" | jq -r ".result[$i].content") chkDnsArr+=("$record_id"":""$ip") #echo "$record_id"":""$ip" done fi } findRecInExcludeArr() { local rec=$1 local sparr=() IFS=':' read -ra sparr <<<"$rec" # echo "findRecInExcludeArr():rec:$rec" for ip in "${excludeIp[@]}"; do #echo "left:${sparr[1]}|,right:$ip|" if [ "${sparr[1]}" == "$ip" ]; then return 0 fi done return 1 } FilterRec() { # echo "FilterRec()" delDnsArr=() for i in "${!chkDnsArr[@]}"; do findRecInExcludeArr "${chkDnsArr[$i]}" #不是排除之列,则加到删除队列 if [ $? -eq 1 ]; then #echo "add to delarr" local sparr=() IFS=':' read -ra sparr <<<"${chkDnsArr[$i]}" delDnsArr+=(${sparr[0]}) fi done } RealDelDns() { delDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records" FilterRec for index in "${!delDnsArr[@]}"; do record_id=${delDnsArr[$index]} # 输出正在删除的记录 #echo "正在删除第 $((index + 1)) 条 DNS 记录,记录 ID: $record_id" # 发出删除请求 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") succ=$(echo $rt | jq -r ".success") if [ "$succ" != "true" ]; then echo "删除dns记录失败,会可能引起后面更新问题,强制退出" exit 1 fi done } InsertCF() { ipAddr=$1 if [[ $ipAddr =~ $ipv4Regex ]]; then recordType="A" else recordType="AAAA" fi echo "新增$CDNhostname 的DNS记录" createDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records" 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}") resSuccess=$(echo "$res" | jq -r ".success") if [[ "$resSuccess" = "true" ]]; then echo "$CDNhostname更新成功" return 0 else code=$(echo "$res" | jq -r ".errors[0].code") #已有相同记录 if [ $code -eq 81057 ]; then excludeIp+=($ipAddr) echo "已有[$ipAddr] IP记录不做更新" return 0 else echo "$CDNhostname更新失败" return 1 fi fi } UpInsetCF() { #开始DDNS ipAddr=$1 if [[ $ipAddr =~ $ipv4Regex ]]; then recordType="A" else recordType="AAAA" fi listDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records?type=${recordType}&name=${CDNhostname}" createDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records" res=$(curl -s -X GET "$listDnsApi" -H "X-Auth-Email:$x_email" -H "X-Auth-Key:$api_key" -H "Content-Type:application/json") recordId=$(echo "$res" | jq -r ".result[0].id") recordIp=$(echo "$res" | jq -r ".result[0].content") echo "recordIp:$recordIp" if [[ $recordIp = "$ipAddr" ]]; then echo "更新失败,获取最快的IP与云端相同" excludeIp+=($ipAddr) resSuccess="false" elif [[ $recordId = "null" ]]; then 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}") resSuccess=$(echo "$res" | jq -r ".success") else updateDnsApi="https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records/${recordId}" 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}") resSuccess=$(echo "$res" | jq -r ".success") excludeIp+=($ipAddr) fi if [[ "$resSuccess" = "true" ]]; then echo "$CDNhostname更新成功" else echo "$CDNhostname更新失败" fi } #验证cf账号信息是否正确 echo "cf_ddns():zone_id:$zone_id" echo "cf_ddns():api_key:$api_key" 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") resSuccess=$(echo "$res" | jq -r ".success") if [[ $resSuccess != "true" ]]; then pushmessage="登陆错误,检查cloudflare账号信息填写是否正确!" source ./msg/cf_push exit 1 fi echo "Cloudflare账号验证成功" if [ -z $multip ]; then multip=1 multFlag=0 else multFlag=1 fi #开始循环 echo "正在更新域名,请稍后..." x=0 csvfile="" while [[ ${x} -lt $domain_num ]]; do CDNhostname=${domains[$x]} #获取优选后的ip地址 if [ "$CCFLAG" = "true" ]; then CountryCode=${countryCodes[$x]} csvfile="$CountryCode"".csv" echo "csvfile:$csvfile" else csvfile="result.csv" fi #如果没有生成对应结果文件,跳过 if [ ! -e $csvfile ]; then x=$((x + 1)) continue fi CheckDelCFDns lineNo=0 ipcount=0 while read -r line; do ((lineNo++)) if ((lineNo == 1)); then continue fi IFS=, read -ra fields <<<"$line" ipAddr=${fields[0]} ((ipcount++)) echo "开始更新第${ipcount}个---$ipAddr" if ((multFlag == 1)); then InsertCF $ipAddr else UpInsetCF $ipAddr fi if ((ipcount >= multip)); then break fi done <$csvfile RealDelDns echo "完成$csvfile的ip更新!" x=$((x + 1)) sleep 1s done >>informlog ================================================ FILE: script/openwrt/msg/cf_push ================================================ #!/bin/bash ##用于CloudflareSpeedTestDDNS执行情况推送。 echo $pushmessage message_text=$pushmessage #解析模式,可选HTML或Markdown MODE='HTML' #api接口 telegramBotToken=$(yq eval ".telegramBotToken" $configfile) telegramBotUserId=$(yq eval ".telegramBotUserId" $configfile) URL="https://api.telegram.org/bot${telegramBotToken}/sendMessage" if [[ -z ${telegramBotToken} ]]; then echo "未配置TG推送" else res=$(timeout 20s curl -s -X POST $URL -d chat_id=${telegramBotUserId} -d parse_mode=${MODE} -d text="${message_text}") if [ $? == 124 ]; then echo 'TG_api请求超时,请检查网络是否重启完成并是否能够访问TG' exit 1 fi resSuccess=$(echo "$res" | jq -r ".ok") if [[ $resSuccess = "true" ]]; then echo "TG推送成功" else echo "TG推送失败,请检查TG机器人token和ID" fi fi ================================================ FILE: script/openwrt/msg/wxpush.sh ================================================ #!/bin/bash text='' while IFS= read -r line; do text+="$line" done <"./informlog" title="msg_from_cvwt" token="$wxToken" if [[ -z ${wxpushAPI} ]]; then echo "未配置微信推送API!!!" else URL="$wxpushAPI" echo "URL:$URL" res=$(timeout 20s curl -s -X POST $URL \ -d title=${title} --data-urlencode content="${text}" -d token="$token") if [ $? == 124 ]; then echo "发送消息超时" exit 1 fi # 检查返回结果是否包含成功关键词 if echo "$res" | grep -q -E "Successfully"; then echo "微信推送成功" echo "res:$res" else echo "微信推送失败, 返回结果: $res" fi fi ================================================ FILE: script/openwrt/msg/wxsend_jiang.sh ================================================ #!/bin/bash text='' while IFS= read -r line; do text+="$line" done <"./informlog" #for test. #configfile="./config.yaml" #sendKey=$(yq eval ".sendKey" $configfile) title="msg_from_cvwt" URL="https://sctapi.ftqq.com/$sendKey.send?" if [[ -z ${sendKey} ]]; then echo "未配置微信推送的sendKey, 关注【方糖】公众号获取sendKey" else res=$(timeout 20s curl -s -X POST $URL -d title=${title} -d desp="${text}") if [ $? == 124 ]; then echo "发送消息超时" exit 1 fi #res:{"code":0,"message":"","data":{"pushid":"164999333","readkey":"SCTGLrDh4Zadf4k","error":"SUCCESS","errno":0}} err=$(echo "$res" | jq -r ".data.error") if [ "$err" == "SUCCESS" ]; then echo "微信推送成功" else echo "微信推送失败, error:$err" fi fi ================================================ FILE: script/openwrt/start-v2.sh ================================================ #!/bin/bash if [ $# -lt 1 ]; then echo "start.sh config_file_path [ipfile]" exit 0 fi configfile=$1 ipfile=$2 echo "configfile:$configfile, ipfile:$ipfile" ipzipfile="ip.zip" #or test rm -rf *.csv if [[ -e $ipzipfile ]]; then rm -rf $ipzipfile fi if [[ -e informlog ]]; then rm -rf informlog fi echo "0.读取配置文件" if [[ ! -e $configfile ]]; then echo "找不到$configfile配置文件!" exit 1 fi pause=$(yq eval ".pause" $configfile) clien=$(yq eval ".clien" $configfile) multip=$(yq eval ".multip" $configfile) CFST_URL=$(yq eval ".CFST_URL" $configfile) CFST_N=$(yq eval ".CFST_N" $configfile) CFST_T=$(yq eval ".CFST_T" $configfile) CFST_DN=$(yq eval ".CFST_DN" $configfile) CFST_TL=$(yq eval ".CFST_TL" $configfile) CFST_TLL=$(yq eval ".CFST_TLL" $configfile) CFST_SL=$(yq eval ".CFST_SL" $configfile) CCFLAG=$(yq eval ".CCFLAG" $configfile) CCODE=$(yq eval ".CCODE" $configfile) CF_ADDR=$(yq eval ".CF_ADDR" $configfile) telegramBotToken=$(yq eval ".telegramBotToken" $configfile) telegramBotUserId=$(yq eval ".telegramBotUserId" $configfile) sendType=$(yq eval ".sendType" $configfile) sendKey=$(yq eval ".sendKey" $configfile) wxpushAPI=$(yq eval ".wxpushAPI" $configfile) wxToken=$(yq eval ".wxToken" $configfile) ChkHostnameAndCoutryCode() { IFS=, read -r -a domains <<<"$hostname" IFS=, read -r -a countryCodes <<<"$CCODE" domain_num=${#domains[@]} countryCode_num=${#countryCodes[@]} if [ ${#domains[@]} -eq 0 ]; then echo "hostname must be set in config file!" return 1 fi #检查域名和国家代码是否一一对应 if [ "$CCFLAG" = "true" ]; then echo "domain_num:$domain_num, countryCode_num:$countryCode_num" if [ $domain_num -ne $countryCode_num ]; then echo "The name and country code must correspond one to one!" return 1 fi fi return 0 } GetProxName() { c=$1 if [ "$c" = "6" ]; then CLIEN=bypass elif [ "$c" = "5" ]; then CLIEN=openclash elif [ "$c" = "4" ]; then CLIEN=clash elif [ "$c" = "3" ]; then CLIEN=shadowsocksr elif [ "$c" = "2" ]; then CLIEN=passwall2 else CLIEN=passwall fi echo $CLIEN } handle_err() { if [ "$pause" = "true" ] ; then echo "Restore background process." proxy=$(GetProxName $clien) /etc/init.d/$proxy stop /etc/init.d/$proxy start fi } #trap handle_err EXIT trap handle_err HUP INT TERM EXIT CLIEN=$(GetProxName $clien) ps -ef | grep $CLIEN | grep -v "grep" >/dev/null if [ $? = 1 ]; then /etc/init.d/$CLIEN start fi if [ -z $ipfile ]; then echo "1.Download ip file." for i in {1..3}; do wget -O $ipzipfile https://zip.cm.edu.kg if [ $? != 0 ]; then echo "get ip file failed, try again" sleep 1 continue else echo "downloaded." break fi done if [ -e $ipzipfile ]; then unzip -o $ipzipfile else echo "Can't download the ip zip file, Check whether the agent software is disabled." fi # echo "2.Select the ip address of the desired port." # port=$(yq eval ".CF_ADDR" $configfile) # if [ -z $port ]; then # port=443 # fi # ip_file="./$port/ALL.txt" # # for file in $(find . -type f -name "*-[0-1]-$port.txt"); do # # echo "handling: $file" # # cat "$file" >>tmp.txt # # done # if [ -e "$ip_file" ]; then # cat "$ip_file" | sort -u >ip.txt # fi fi echo "Run scripts to test speed and update dns records." CFST_P=$CFST_DN #判断工作模式 if [ "$IP_ADDR" = "ipv6" ]; then if [ ! -f "ipv6.txt" ]; then echo "当前工作模式为ipv6,但该目录下没有【ipv6.txt】,请配置【ipv6.txt】。下载地址:https://github.com/XIU2/CloudflareSpeedTest/releases" exit 2 else echo "当前工作模式为ipv6" fi else echo "当前工作模式为ipv4" fi #读取配置文件中的客户端 CLIEN=$(GetProxName $clien) #判断是否停止科学上网服务 if [ "$pause" = "false" ]; then echo "按要求未停止科学上网服务" else /etc/init.d/$CLIEN stop echo "已停止$CLIEN" fi #判断是否配置测速地址 if [[ "$CFST_URL" == http* ]]; then CFST_URL_R="-url $CFST_URL" else CFST_URL_R="" fi #判断是否使用国家代码来筛选 if [[ "$CCFLAG" == "true" ]]; then USECC="-c " else USECC="" fi if [ ! -z "$CCODE" ]; then CCODE_IS="-cc $CCODE " else CCODE_IS="" fi if [ ! -z "$CF_ADDR" ]; then CF_ADDR=" -tp $CF_ADDR" else CF_ADDR=" -tp 443" fi # 定义测速函数 run_speedtest() { local ip_file=$1 local output=$2 local cmd_args="$CFST_URL_R -t $CFST_T -n $CFST_N -dn $CFST_DN -tl $CFST_TL -tll $CFST_TLL -sl $CFST_SL -p $CFST_P" if [ ! -z "$ip_file" ]; then cmd_args="$cmd_args -f $ip_file" fi if [ ! -z "$output" ]; then cmd_args="$cmd_args -o $output" fi if [ "$IP_ADDR" != "ipv6" ] && [ ! -z "$CF_ADDR" ]; then cmd_args="$cmd_args $CF_ADDR" fi if [ ! -z "$USECC" ] && [ ! -z "$CCODE_IS" ]; then cmd_args="$cmd_args $USECC $CCODE_IS" fi echo "./CloudflareST $cmd_args" ./CloudflareST $cmd_args } if [ -z "$ipfile" ]; then ipflag="" port=$(yq eval ".CF_ADDR" $configfile) if [ -z $port ]; then port=443 fi if [ ! -z "$CCODE" ]; then # 如果配置了CCODE,按逗号分割为数组,循环每个国家代码进行测速 IFS=',' read -ra cc_arr <<< "$CCODE" echo "国家代码列表: ${cc_arr[*]}" CCODE_IS="" USECC="" for cc in "${cc_arr[@]}"; do cc=$(echo $cc | xargs) # 去除可能的空格 echo "处理国家代码: $cc" ipfile_path="./$port/${cc}.txt" output_file="${cc}.csv" if [ -f "$ipfile_path" ]; then echo "找到IP文件: $ipfile_path" run_speedtest "$ipfile_path" "$output_file" else echo "警告: IP文件 $ipfile_path 不存在,跳过此国家代码" fi done else run_speedtest "$ipfile" "result.csv" fi else # 使用用户指定的IP文件进行测速 run_speedtest "$ipfile" "result.csv" fi echo "测速完毕" if [ "$pause" = "false" ]; then echo "按要求未重启科学上网服务" sleep 3s else /etc/init.d/$CLIEN restart echo "已重启$CLIEN" echo "为保证cloudflareAPI连接正常 将在3秒后开始更新域名解析" sleep 3s fi if yq eval 'has("cloudflare")' $configfile; then length=$(yq eval '.cloudflare | length' $configfile) echo "length:$length" for ((li = 0; li < $length; li++)); do echo "Configuration Group $((li + 1)):" x_email=$(yq eval ".cloudflare[$li].x_email" $configfile) echo "x_email: $x_email" hostname=$(yq eval ".cloudflare[$li].hostname" $configfile) echo "hostname: $hostname" zone_id=$(yq eval ".cloudflare[$li].zone_id" $configfile) #echo "zone_id:$zone_id" api_key=$(yq eval ".cloudflare[$li].api_key" $configfile) #echo "api_key:$api_key" ChkHostnameAndCoutryCode if [ $? -eq 1 ]; then echo "ChkHostnameAndCoutryCode() error!" exit 1 fi source ./ddns/cf_ddns done fi #会生成一个名为informlog的临时文件作为推送的内容。 pushmessage=$(cat informlog) echo $pushmessage if [ ! -z "$sendType" ]; then if [[ $sendType -eq 1 ]]; then source ./msg/cf_push elif [[ $sendType -eq 2 ]]; then source ./msg/wxsend_jiang.sh source ./msg/wxpush.sh elif [[ $sendType -eq 3 ]]; then source ./msg/cf_push source ./msg/wxsend_jiang.sh source ./msg/wxpush.sh else echo "$sendType is invalid type!" fi fi ================================================ FILE: script/openwrt/start.sh ================================================ #!/bin/bash if [ $# -lt 1 ]; then echo "start.sh config_file_path [ipfile]" exit 0 fi configfile=$1 ipfile=$2 echo "configfile:$configfile, ipfile:$ipfile" ipzipfile="ip.zip" //for test rm -rf *.csv if [[ -e $ipzipfile ]]; then rm -rf $ipzipfile fi if [[ -e informlog ]]; then rm -rf informlog fi echo "0.读取配置文件" if [[ ! -e $configfile ]]; then echo "找不到$configfile配置文件!" exit 1 fi pause=$(yq eval ".pause" $configfile) clien=$(yq eval ".clien" $configfile) multip=$(yq eval ".multip" $configfile) CFST_URL=$(yq eval ".CFST_URL" $configfile) CFST_N=$(yq eval ".CFST_N" $configfile) CFST_T=$(yq eval ".CFST_T" $configfile) CFST_DN=$(yq eval ".CFST_DN" $configfile) CFST_TL=$(yq eval ".CFST_TL" $configfile) CFST_TLL=$(yq eval ".CFST_TLL" $configfile) CFST_SL=$(yq eval ".CFST_SL" $configfile) CCFLAG=$(yq eval ".CCFLAG" $configfile) CCODE=$(yq eval ".CCODE" $configfile) CF_ADDR=$(yq eval ".CF_ADDR" $configfile) telegramBotToken=$(yq eval ".telegramBotToken" $configfile) telegramBotUserId=$(yq eval ".telegramBotUserId" $configfile) sendType=$(yq eval ".sendType" $configfile) sendKey=$(yq eval ".sendKey" $configfile) wxpushAPI=$(yq eval ".wxpushAPI" $configfile) wxToken=$(yq eval ".wxToken" $configfile) ChkHostnameAndCoutryCode() { IFS=, read -r -a domains <<<"$hostname" IFS=, read -r -a countryCodes <<<"$CCODE" domain_num=${#domains[@]} countryCode_num=${#countryCodes[@]} if [ ${#domains[@]} -eq 0 ]; then echo "hostname must be set in config file!" return 1 fi #检查域名和国家代码是否一一对应 if [ "$CCFLAG" = "true" ]; then echo "domain_num:$domain_num, countryCode_num:$countryCode_num" if [ $domain_num -ne $countryCode_num ]; then echo "The name and country code must correspond one to one!" return 1 fi fi return 0 } GetProxName() { c=$1 if [ "$c" = "6" ]; then CLIEN=bypass elif [ "$c" = "5" ]; then CLIEN=openclash elif [ "$c" = "4" ]; then CLIEN=clash elif [ "$c" = "3" ]; then CLIEN=shadowsocksr elif [ "$c" = "2" ]; then CLIEN=passwall2 else CLIEN=passwall fi echo $CLIEN } handle_err() { if [ "$pause" = "true" ] ; then echo "Restore background process." proxy=$(GetProxName $clien) /etc/init.d/$proxy start fi } #trap handle_err EXIT trap handle_err HUP INT TERM EXIT CLIEN=$(GetProxName $clien) ps -ef | grep $CLIEN | grep -v "grep" >/dev/null if [ $? = 1 ]; then /etc/init.d/$CLIEN start fi if [ -z $ipfile ]; then echo "1.Download ip file." for i in {1..3}; do wget -O $ipzipfile https://zip.cm.edu.kg if [ $? != 0 ]; then echo "get ip file failed, try again" sleep 1 continue else echo "downloaded." break fi done if [ -e $ipzipfile ]; then unzip -o $ipzipfile else echo "Can't download the ip zip file, Check whether the agent software is disabled." fi echo "2.Select the ip address of the desired port." port=$(yq eval ".CF_ADDR" $configfile) if [ -z $port ]; then port=443 fi ip_file="./$port/ALL.txt" # for file in $(find . -type f -name "*-[0-1]-$port.txt"); do # echo "handling: $file" # cat "$file" >>tmp.txt # done if [ -e "$ip_file" ]; then cat "$ip_file" | sort -u >ip.txt fi fi echo "Run scripts to test speed and update dns records." CFST_P=$CFST_DN #判断工作模式 if [ "$IP_ADDR" = "ipv6" ]; then if [ ! -f "ipv6.txt" ]; then echo "当前工作模式为ipv6,但该目录下没有【ipv6.txt】,请配置【ipv6.txt】。下载地址:https://github.com/XIU2/CloudflareSpeedTest/releases" exit 2 else echo "当前工作模式为ipv6" fi else echo "当前工作模式为ipv4" fi #读取配置文件中的客户端 CLIEN=$(GetProxName $clien) #判断是否停止科学上网服务 if [ "$pause" = "false" ]; then echo "按要求未停止科学上网服务" else /etc/init.d/$CLIEN stop echo "已停止$CLIEN" fi #判断是否配置测速地址 if [[ "$CFST_URL" == http* ]]; then CFST_URL_R="-url $CFST_URL" else CFST_URL_R="" fi #判断是否使用国家代码来筛选 if [[ "$CCFLAG" == "true" ]]; then USECC="-c " else USECC="" fi if [ ! -z "$CCODE" ]; then CCODE_IS="-cc $CCODE " else CCODE_IS="" fi if [ ! -z "$CF_ADDR" ]; then CF_ADDR=" -tp $CF_ADDR" else CF_ADDR=" -tp 443" fi if [ -z "$ipfile" ]; then ipflag="" else ipflag="-f " fi if [ "$IP_ADDR" = "ipv6" ]; then #开始优选IPv6 ./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 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" else #开始优选IPv4 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" ./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 fi echo "测速完毕" if [ "$pause" = "false" ]; then echo "按要求未重启科学上网服务" sleep 3s else /etc/init.d/$CLIEN restart echo "已重启$CLIEN" echo "为保证cloudflareAPI连接正常 将在3秒后开始更新域名解析" sleep 3s fi if yq eval 'has("cloudflare")' $configfile; then length=$(yq eval '.cloudflare | length' $configfile) echo "length:$length" for ((li = 0; li < $length; li++)); do echo "Configuration Group $((li + 1)):" x_email=$(yq eval ".cloudflare[$li].x_email" $configfile) echo "x_email: $x_email" hostname=$(yq eval ".cloudflare[$li].hostname" $configfile) echo "hostname: $hostname" zone_id=$(yq eval ".cloudflare[$li].zone_id" $configfile) #echo "zone_id:$zone_id" api_key=$(yq eval ".cloudflare[$li].api_key" $configfile) #echo "api_key:$api_key" ChkHostnameAndCoutryCode if [ $? -eq 1 ]; then echo "ChkHostnameAndCoutryCode() error!" exit 1 fi source ./ddns/cf_ddns done fi #会生成一个名为informlog的临时文件作为推送的内容。 pushmessage=$(cat informlog) echo $pushmessage if [ ! -z "$sendType" ]; then if [[ $sendType -eq 1 ]]; then source ./msg/cf_push elif [[ $sendType -eq 2 ]]; then source ./msg/wxsend_jiang.sh source ./msg/wxpush.sh elif [[ $sendType -eq 3 ]]; then source ./msg/cf_push source ./msg/wxsend_jiang.sh source ./msg/wxpush.sh else echo "$sendType is invalid type!" fi fi ================================================ FILE: task/download.go ================================================ package task import ( "context" "fmt" "io" "net" "net/http" "sort" "strconv" "time" "github.com/XIU2/CloudflareSpeedTest/utils" "github.com/VividCortex/ewma" ) const ( bufferSize = 1024 defaultURL = "https://cf.xiu2.xyz/url" defaultTimeout = 5 * time.Second defaultDisableDownload = false defaultTestNum = 10 defaultMinSpeed float64 = 0.0 ) var ( URL = defaultURL Timeout = defaultTimeout Disable = defaultDisableDownload TestCount = defaultTestNum MinSpeed = defaultMinSpeed ) func checkDownloadDefault() { if URL == "" { URL = defaultURL } if Timeout <= 0 { Timeout = defaultTimeout } if TestCount <= 0 { TestCount = defaultTestNum } if MinSpeed <= 0.0 { MinSpeed = defaultMinSpeed } } func TestDownloadSpeedByCountry(ipSet utils.PingDelaySet) (speedSet utils.DownloadSpeedSet) { checkDownloadDefault() if Disable { return utils.DownloadSpeedSet(ipSet) } if len(ipSet) <= 0 { // IP数组长度(IP数量) 大于 0 时才会继续下载测速 fmt.Println("\n[信息] 延迟测速结果 IP 数量为 0,跳过下载测速。") return } //按国家代号划分分片 countryMap := make(map[string]utils.PingDelaySet) for _, ip := range ipSet { country := ip.Country if _, ok := countryMap[country]; !ok { countryMap[country] = make(utils.PingDelaySet, 0) } countryMap[country] = append(countryMap[country], ip) } // 按照每个国家分批进行测速 for country, countrySet := range countryMap { testNum := TestCount barCount := TestCount if len(countrySet) < TestCount || MinSpeed > 0 { // 如果IP数组长度(IP数量) 小于下载测速数量(-dn),则次数修正为IP数 testNum = len(countrySet) } if testNum < barCount { barCount = testNum } fmt.Printf("\n[信息] 开始测速 %s 的 IP,数量:%d\n", country, len(countrySet)) bar_a := len(strconv.Itoa(len(countrySet))) bar_b := " " for i := 0; i < bar_a; i++ { bar_b += " " } bar := utils.NewBar(barCount, bar_b, "") countryspeedSet := make(utils.DownloadSpeedSet, 0) for i := 0; i < testNum; i++ { speed := downloadHandler(countrySet[i].IP) countrySet[i].DownloadSpeed = speed // 在每个 IP 下载测速后,以 [下载速度下限] 条件过滤结果 if speed >= MinSpeed*1024*1024 { bar.Grow(1, "") countryspeedSet = append(countryspeedSet, countrySet[i]) // 高于下载速度下限时,添加到新数组中 if len(countryspeedSet) == TestCount { // 凑够满足条件的 IP 时(下载测速数量 -dn),就跳出循环 break } } } bar.Done() if len(countryspeedSet) == 0 { countryspeedSet = utils.DownloadSpeedSet(countrySet) } speedSet = append(speedSet, countryspeedSet...) } return } func TestDownloadSpeed(ipSet utils.PingDelaySet) (speedSet utils.DownloadSpeedSet) { checkDownloadDefault() if Disable { return utils.DownloadSpeedSet(ipSet) } if len(ipSet) <= 0 { // IP数组长度(IP数量) 大于 0 时才会继续下载测速 fmt.Println("\n[信息] 延迟测速结果 IP 数量为 0,跳过下载测速。") return } testNum := TestCount if len(ipSet) < TestCount || MinSpeed > 0 { // 如果IP数组长度(IP数量) 小于下载测速数量(-dn),则次数修正为IP数 testNum = len(ipSet) } if testNum < TestCount { TestCount = testNum } fmt.Printf("开始下载测速(下限:%.2f MB/s, 数量:%d, 队列:%d)\n", MinSpeed, TestCount, testNum) // 控制 下载测速进度条 与 延迟测速进度条 长度一致(强迫症) bar_a := len(strconv.Itoa(len(ipSet))) bar_b := " " for i := 0; i < bar_a; i++ { bar_b += " " } bar := utils.NewBar(TestCount, bar_b, "") for i := 0; i < testNum; i++ { speed := downloadHandler(ipSet[i].IP) ipSet[i].DownloadSpeed = speed // 在每个 IP 下载测速后,以 [下载速度下限] 条件过滤结果 if speed >= MinSpeed*1024*1024 { bar.Grow(1, "") speedSet = append(speedSet, ipSet[i]) // 高于下载速度下限时,添加到新数组中 if len(speedSet) == TestCount { // 凑够满足条件的 IP 时(下载测速数量 -dn),就跳出循环 break } } } bar.Done() if len(speedSet) == 0 { // 没有符合速度限制的数据,返回所有测试数据 speedSet = utils.DownloadSpeedSet(ipSet) } // 按速度排序 sort.Sort(speedSet) return } func getDialContext(ip *net.IPAddr) func(ctx context.Context, network, address string) (net.Conn, error) { var fakeSourceAddr string if isIPv4(ip.String()) { fakeSourceAddr = fmt.Sprintf("%s:%d", ip.String(), TCPPort) } else { fakeSourceAddr = fmt.Sprintf("[%s]:%d", ip.String(), TCPPort) } return func(ctx context.Context, network, address string) (net.Conn, error) { return (&net.Dialer{}).DialContext(ctx, network, fakeSourceAddr) } } // return download Speed func downloadHandler(ip *net.IPAddr) float64 { client := &http.Client{ Transport: &http.Transport{DialContext: getDialContext(ip)}, Timeout: Timeout, CheckRedirect: func(req *http.Request, via []*http.Request) error { if len(via) > 10 { // 限制最多重定向 10 次 return http.ErrUseLastResponse } if req.Header.Get("Referer") == defaultURL { // 当使用默认下载测速地址时,重定向不携带 Referer req.Header.Del("Referer") } return nil }, } req, err := http.NewRequest("GET", URL, nil) if err != nil { return 0.0 } 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") response, err := client.Do(req) if err != nil { return 0.0 } defer response.Body.Close() if response.StatusCode != 200 { return 0.0 } timeStart := time.Now() // 开始时间(当前) timeEnd := timeStart.Add(Timeout) // 加上下载测速时间得到的结束时间 contentLength := response.ContentLength // 文件大小 buffer := make([]byte, bufferSize) var ( contentRead int64 = 0 timeSlice = Timeout / 100 timeCounter = 1 lastContentRead int64 = 0 ) var nextTime = timeStart.Add(timeSlice * time.Duration(timeCounter)) e := ewma.NewMovingAverage() // 循环计算,如果文件下载完了(两者相等),则退出循环(终止测速) for contentLength != contentRead { currentTime := time.Now() if currentTime.After(nextTime) { timeCounter++ nextTime = timeStart.Add(timeSlice * time.Duration(timeCounter)) e.Add(float64(contentRead - lastContentRead)) lastContentRead = contentRead } // 如果超出下载测速时间,则退出循环(终止测速) if currentTime.After(timeEnd) { break } bufferRead, err := response.Body.Read(buffer) if err != nil { if err != io.EOF { // 如果文件下载过程中遇到报错(如 Timeout),且并不是因为文件下载完了,则退出循环(终止测速) break } else if contentLength == -1 { // 文件下载完成 且 文件大小未知,则退出循环(终止测速),例如:https://speed.cloudflare.com/__down?bytes=200000000 这样的,如果在 10 秒内就下载完成了,会导致测速结果明显偏低甚至显示为 0.00(下载速度太快时) break } // 获取上个时间片 last_time_slice := timeStart.Add(timeSlice * time.Duration(timeCounter-1)) // 下载数据量 / (用当前时间 - 上个时间片/ 时间片) e.Add(float64(contentRead-lastContentRead) / (float64(currentTime.Sub(last_time_slice)) / float64(timeSlice))) } contentRead += int64(bufferRead) } return e.Value() / (Timeout.Seconds() / 120) } ================================================ FILE: task/httping.go ================================================ package task import ( //"crypto/tls" //"fmt" "io" "log" "net" "net/http" "regexp" "strings" "sync" "time" ) var ( Httping bool HttpingStatusCode int HttpingCFColo string HttpingCFColomap *sync.Map OutRegexp = regexp.MustCompile(`[A-Z]{3}`) ) // pingReceived pingTotalTime func (p *Ping) httping(ip *net.IPAddr) (int, time.Duration) { hc := http.Client{ Timeout: time.Second * 2, Transport: &http.Transport{ DialContext: getDialContext(ip), //TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // 跳过证书验证 }, CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse // 阻止重定向 }, } // 先访问一次获得 HTTP 状态码 及 Cloudflare Colo { requ, err := http.NewRequest(http.MethodHead, URL, nil) if err != nil { return 0, 0 } 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") resp, err := hc.Do(requ) if err != nil { return 0, 0 } defer resp.Body.Close() //fmt.Println("IP:", ip, "StatusCode:", resp.StatusCode, resp.Request.URL) // 如果未指定的 HTTP 状态码,或指定的状态码不合规,则默认只认为 200、301、302 才算 HTTPing 通过 if HttpingStatusCode == 0 || HttpingStatusCode < 100 && HttpingStatusCode > 599 { if resp.StatusCode != 200 && resp.StatusCode != 301 && resp.StatusCode != 302 { return 0, 0 } } else { if resp.StatusCode != HttpingStatusCode { return 0, 0 } } io.Copy(io.Discard, resp.Body) // 只有指定了地区才匹配机场三字码 if HttpingCFColo != "" { // 通过头部 Server 值判断是 Cloudflare 还是 AWS CloudFront 并设置 cfRay 为各自的机场三字码完整内容 cfRay := func() string { if resp.Header.Get("Server") == "cloudflare" { return resp.Header.Get("CF-RAY") // 示例 cf-ray: 7bd32409eda7b020-SJC } return resp.Header.Get("x-amz-cf-pop") // 示例 X-Amz-Cf-Pop: SIN52-P1 }() colo := p.getColo(cfRay) if colo == "" { // 没有匹配到三字码或不符合指定地区则直接结束该 IP 测试 return 0, 0 } } } // 循环测速计算延迟 success := 0 var delay time.Duration for i := 0; i < PingTimes; i++ { requ, err := http.NewRequest(http.MethodHead, URL, nil) if err != nil { log.Fatal("意外的错误,情报告:", err) return 0, 0 } 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") if i == PingTimes-1 { requ.Header.Set("Connection", "close") } startTime := time.Now() resp, err := hc.Do(requ) if err != nil { continue } success++ io.Copy(io.Discard, resp.Body) _ = resp.Body.Close() duration := time.Since(startTime) delay += duration } return success, delay } func MapColoMap() *sync.Map { if HttpingCFColo == "" { return nil } // 将参数指定的地区三字码转为大写并格式化 colos := strings.Split(strings.ToUpper(HttpingCFColo), ",") colomap := &sync.Map{} for _, colo := range colos { colomap.Store(colo, colo) } return colomap } func (p *Ping) getColo(b string) string { if b == "" { return "" } // 正则匹配并返回 机场三字码 out := OutRegexp.FindString(b) if HttpingCFColomap == nil { return out } // 匹配 机场三字码 是否为指定的地区 _, ok := HttpingCFColomap.Load(out) if ok { return out } return "" } ================================================ FILE: task/ip.go ================================================ package task import ( "bufio" "log" "math/rand" "net" "os" "strconv" "strings" "time" ) const defaultInputFile = "ip.txt" var ( // TestAll test all ip TestAll = false // IPFile is the filename of IP Rangs IPFile = defaultInputFile IPText string ) func InitRandSeed() { rand.Seed(time.Now().UnixNano()) } func isIPv4(ip string) bool { return strings.Contains(ip, ".") } func randIPEndWith(num byte) byte { if num == 0 { // 对于 /32 这种单独的 IP return byte(0) } return byte(rand.Intn(int(num))) } type IPRanges struct { ips []*net.IPAddr mask string firstIP net.IP ipNet *net.IPNet } func newIPRanges() *IPRanges { return &IPRanges{ ips: make([]*net.IPAddr, 0), } } // 如果是单独 IP 则加上子网掩码,反之则获取子网掩码(r.mask) func (r *IPRanges) fixIP(ip string) string { // 如果不含有 '/' 则代表不是 IP 段,而是一个单独的 IP,因此需要加上 /32 /128 子网掩码 if i := strings.IndexByte(ip, '/'); i < 0 { if isIPv4(ip) { r.mask = "/32" } else { r.mask = "/128" } ip += r.mask } else { r.mask = ip[i:] } return ip } // 解析 IP 段,获得 IP、IP 范围、子网掩码 func (r *IPRanges) parseCIDR(ip string) { var err error if r.firstIP, r.ipNet, err = net.ParseCIDR(r.fixIP(ip)); err != nil { log.Fatalln("ParseCIDR err", err) } } func (r *IPRanges) appendIPv4(d byte) { r.appendIP(net.IPv4(r.firstIP[12], r.firstIP[13], r.firstIP[14], d)) } func (r *IPRanges) appendIP(ip net.IP) { r.ips = append(r.ips, &net.IPAddr{IP: ip}) } // 返回第四段 ip 的最小值及可用数目 func (r *IPRanges) getIPRange() (minIP, hosts byte) { minIP = r.firstIP[15] & r.ipNet.Mask[3] // IP 第四段最小值 // 根据子网掩码获取主机数量 m := net.IPv4Mask(255, 255, 255, 255) for i, v := range r.ipNet.Mask { m[i] ^= v } total, _ := strconv.ParseInt(m.String(), 16, 32) // 总可用 IP 数 if total > 255 { // 矫正 第四段 可用 IP 数 hosts = 255 return } hosts = byte(total) return } func (r *IPRanges) chooseIPv4() { if r.mask == "/32" { // 单个 IP 则无需随机,直接加入自身即可 r.appendIP(r.firstIP) } else { minIP, hosts := r.getIPRange() // 返回第四段 IP 的最小值及可用数目 for r.ipNet.Contains(r.firstIP) { // 只要该 IP 没有超出 IP 网段范围,就继续循环随机 if TestAll { // 如果是测速全部 IP for i := 0; i <= int(hosts); i++ { // 遍历 IP 最后一段最小值到最大值 r.appendIPv4(byte(i) + minIP) } } else { // 随机 IP 的最后一段 0.0.0.X r.appendIPv4(minIP + randIPEndWith(hosts)) } r.firstIP[14]++ // 0.0.(X+1).X if r.firstIP[14] == 0 { r.firstIP[13]++ // 0.(X+1).X.X if r.firstIP[13] == 0 { r.firstIP[12]++ // (X+1).X.X.X } } } } } func (r *IPRanges) chooseIPv6() { if r.mask == "/128" { // 单个 IP 则无需随机,直接加入自身即可 r.appendIP(r.firstIP) } else { var tempIP uint8 // 临时变量,用于记录前一位的值 for r.ipNet.Contains(r.firstIP) { // 只要该 IP 没有超出 IP 网段范围,就继续循环随机 r.firstIP[15] = randIPEndWith(255) // 随机 IP 的最后一段 r.firstIP[14] = randIPEndWith(255) // 随机 IP 的最后一段 targetIP := make([]byte, len(r.firstIP)) copy(targetIP, r.firstIP) r.appendIP(targetIP) // 加入 IP 地址池 for i := 13; i >= 0; i-- { // 从倒数第三位开始往前随机 tempIP = r.firstIP[i] // 保存前一位的值 r.firstIP[i] += randIPEndWith(255) // 随机 0~255,加到当前位上 if r.firstIP[i] >= tempIP { // 如果当前位的值大于等于前一位的值,说明随机成功了,可以退出该循环 break } } } } } func loadIPRanges() []*net.IPAddr { ranges := newIPRanges() if IPText != "" { // 从参数中获取 IP 段数据 IPs := strings.Split(IPText, ",") // 以逗号分隔为数组并循环遍历 for _, IP := range IPs { IP = strings.TrimSpace(IP) // 去除首尾的空白字符(空格、制表符、换行符等) if IP == "" { // 跳过空的(即开头、结尾或连续多个 ,, 的情况) continue } ranges.parseCIDR(IP) // 解析 IP 段,获得 IP、IP 范围、子网掩码 if isIPv4(IP) { // 生成要测速的所有 IPv4 / IPv6 地址(单个/随机/全部) ranges.chooseIPv4() } else { ranges.chooseIPv6() } } } else { // 从文件中获取 IP 段数据 if IPFile == "" { IPFile = defaultInputFile } file, err := os.Open(IPFile) if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { // 循环遍历文件每一行 line := strings.TrimSpace(scanner.Text()) // 去除首尾的空白字符(空格、制表符、换行符等) if line == "" { // 跳过空行 continue } ranges.parseCIDR(line) // 解析 IP 段,获得 IP、IP 范围、子网掩码 if isIPv4(line) { // 生成要测速的所有 IPv4 / IPv6 地址(单个/随机/全部) ranges.chooseIPv4() } else { ranges.chooseIPv6() } } } return ranges.ips } ================================================ FILE: task/tcping.go ================================================ package task import ( "fmt" "net" "sort" "strconv" "sync" "time" "github.com/XIU2/CloudflareSpeedTest/utils" ) const ( tcpConnectTimeout = time.Second * 1 maxRoutine = 1000 defaultRoutines = 200 defaultPort = 443 defaultPingTimes = 4 ) var ( Routines = defaultRoutines TCPPort int = defaultPort PingTimes int = defaultPingTimes ) type Ping struct { wg *sync.WaitGroup m *sync.Mutex ips []*net.IPAddr csv utils.PingDelaySet control chan bool bar *utils.Bar } func checkPingDefault() { if Routines <= 0 { Routines = defaultRoutines } if TCPPort <= 0 || TCPPort >= 65535 { TCPPort = defaultPort } if PingTimes <= 0 { PingTimes = defaultPingTimes } } func NewPing() *Ping { checkPingDefault() ips := loadIPRanges() return &Ping{ wg: &sync.WaitGroup{}, m: &sync.Mutex{}, ips: ips, csv: make(utils.PingDelaySet, 0), control: make(chan bool, Routines), bar: utils.NewBar(len(ips), "可用:", ""), } } func (p *Ping) Run() utils.PingDelaySet { if len(p.ips) == 0 { return p.csv } if Httping { fmt.Printf("开始延迟测速(模式:HTTP, 端口:%d, 范围:%v ~ %v ms, 丢包:%.2f)\n", TCPPort, utils.InputMinDelay.Milliseconds(), utils.InputMaxDelay.Milliseconds(), utils.InputMaxLossRate) } else { fmt.Printf("开始延迟测速(模式:TCP, 端口:%d, 范围:%v ~ %v ms, 丢包:%.2f)\n", TCPPort, utils.InputMinDelay.Milliseconds(), utils.InputMaxDelay.Milliseconds(), utils.InputMaxLossRate) } for _, ip := range p.ips { p.wg.Add(1) p.control <- false go p.start(ip) } p.wg.Wait() p.bar.Done() sort.Sort(p.csv) return p.csv } func (p *Ping) start(ip *net.IPAddr) { defer p.wg.Done() p.tcpingHandler(ip) <-p.control } // bool connectionSucceed float32 time func (p *Ping) tcping(ip *net.IPAddr) (bool, time.Duration) { startTime := time.Now() var fullAddress string if isIPv4(ip.String()) { fullAddress = fmt.Sprintf("%s:%d", ip.String(), TCPPort) } else { fullAddress = fmt.Sprintf("[%s]:%d", ip.String(), TCPPort) } conn, err := net.DialTimeout("tcp", fullAddress, tcpConnectTimeout) if err != nil { return false, 0 } defer conn.Close() duration := time.Since(startTime) return true, duration } // pingReceived pingTotalTime func (p *Ping) checkConnection(ip *net.IPAddr) (recv int, totalDelay time.Duration) { if Httping { recv, totalDelay = p.httping(ip) return } for i := 0; i < PingTimes; i++ { if ok, delay := p.tcping(ip); ok { recv++ totalDelay += delay } } return } func (p *Ping) appendIPData(data *utils.PingData) { p.m.Lock() defer p.m.Unlock() p.csv = append(p.csv, utils.CloudflareIPData{ PingData: data, }) } // handle tcping func (p *Ping) tcpingHandler(ip *net.IPAddr) { recv, totalDlay := p.checkConnection(ip) nowAble := len(p.csv) if recv != 0 { nowAble++ } p.bar.Grow(1, strconv.Itoa(nowAble)) if recv == 0 { return } data := &utils.PingData{ IP: ip, Sended: PingTimes, Received: recv, Delay: totalDlay / time.Duration(recv), } p.appendIPData(data) } ================================================ FILE: trojan_workers/_worker.js ================================================ // src/worker.js import { connect } from "cloudflare:sockets"; let sha224Password = '7e89e622d89becc4299c2d74494b9fb15759f2b0ff47b20eeae867e2'; let pwd = 'abc123333' 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 let proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)]; let defaultAddr='www.visa.com.sg' if (!isValidSHA224(sha224Password)) { throw new Error('sha224Password is not valid'); } function getprotocol() { let matter = ['t','r','o','j','a','n'] let result='' for (let i = 0; i < matter.length; i++) { result += matter[i]; } return result; } export default { /** * @param {import("@cloudflare/workers-types").Request} request * @param {{SHA224PASS: string, PROXYIP: string}} env * @param {import("@cloudflare/workers-types").ExecutionContext} ctx * @returns {Promise} */ async fetch(request, env, ctx) { try { proxyIP = env.PROXYIP || proxyIP; pwd = env.PASSWORD || pwd if ('PASSWORD' in env) { sha224Password = sha256.sha224(env.PASSWORD) } console.log('pass:'+sha224Password) const upgradeHeader = request.headers.get("Upgrade"); if (!upgradeHeader || upgradeHeader !== "websocket") { const url = new URL(request.url); switch (url.pathname) { case `/${pwd}`:{ const host = request.headers.get('Host'); if ( 'PROXYIP' in env) { return new Response(getprotocol() + `://` + pwd + `@${host}:443/?type=ws&host=${host}&security=tls#${host}`, { status: 200, headers: { "Content-Type": "text/plain;charset=utf-8", } }) }else{ return new Response(getprotocol() + `://` + pwd + `@${defaultAddr}:443/?type=ws&host=${host}&security=tls#${host}`, { status: 200, headers: { "Content-Type": "text/plain;charset=utf-8", } }) } }; default: return new Response("404 Not found", { status: 404 }); } } else { return await trojanOverWSHandler(request); } } catch (err) { let e = err; return new Response(e.toString()); } } }; async function trojanOverWSHandler(request) { const webSocketPair = new WebSocketPair(); const [client, webSocket] = Object.values(webSocketPair); webSocket.accept(); let address = ""; let portWithRandomLog = ""; const log = (info, event) => { console.log(`[${address}:${portWithRandomLog}] ${info}`, event || ""); }; const earlyDataHeader = request.headers.get("sec-websocket-protocol") || ""; const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log); let remoteSocketWapper = { value: null }; let udpStreamWrite = null; readableWebSocketStream.pipeTo(new WritableStream({ async write(chunk, controller) { if (udpStreamWrite) { return udpStreamWrite(chunk); } if (remoteSocketWapper.value) { const writer = remoteSocketWapper.value.writable.getWriter(); await writer.write(chunk); writer.releaseLock(); return; } const { hasError, message, portRemote = 443, addressRemote = "", rawClientData } = await parseTrojanHeader(chunk); address = addressRemote; portWithRandomLog = `${portRemote}--${Math.random()} tcp`; if (hasError) { throw new Error(message); return; } handleTCPOutBound(remoteSocketWapper, addressRemote, portRemote, rawClientData, webSocket, log); }, close() { log(`readableWebSocketStream is closed`); }, abort(reason) { log(`readableWebSocketStream is aborted`, JSON.stringify(reason)); } })).catch((err) => { log("readableWebSocketStream pipeTo error", err); }); return new Response(null, { status: 101, // @ts-ignore webSocket: client }); } async function parseTrojanHeader(buffer) { if (buffer.byteLength < 56) { return { hasError: true, message: "invalid data" }; } let crLfIndex = 56; if (new Uint8Array(buffer.slice(56, 57))[0] !== 0x0d || new Uint8Array(buffer.slice(57, 58))[0] !== 0x0a) { return { hasError: true, message: "invalid header format (missing CR LF)" }; } const password = new TextDecoder().decode(buffer.slice(0, crLfIndex)); if (password !== sha224Password) { return { hasError: true, message: "invalid password" }; } const socks5DataBuffer = buffer.slice(crLfIndex + 2); if (socks5DataBuffer.byteLength < 6) { return { hasError: true, message: "invalid SOCKS5 request data" }; } const view = new DataView(socks5DataBuffer); const cmd = view.getUint8(0); if (cmd !== 1) { return { hasError: true, message: "unsupported command, only TCP (CONNECT) is allowed" }; } const atype = view.getUint8(1); // 0x01: IPv4 address // 0x03: Domain name // 0x04: IPv6 address let addressLength = 0; let addressIndex = 2; let address = ""; switch (atype) { case 1: addressLength = 4; address = new Uint8Array( socks5DataBuffer.slice(addressIndex, addressIndex + addressLength) ).join("."); break; case 3: addressLength = new Uint8Array( socks5DataBuffer.slice(addressIndex, addressIndex + 1) )[0]; addressIndex += 1; address = new TextDecoder().decode( socks5DataBuffer.slice(addressIndex, addressIndex + addressLength) ); break; case 4: addressLength = 16; const dataView = new DataView(socks5DataBuffer.slice(addressIndex, addressIndex + addressLength)); const ipv6 = []; for (let i = 0; i < 8; i++) { ipv6.push(dataView.getUint16(i * 2).toString(16)); } address = ipv6.join(":"); break; default: return { hasError: true, message: `invalid addressType is ${atype}` }; } if (!address) { return { hasError: true, message: `address is empty, addressType is ${atype}` }; } const portIndex = addressIndex + addressLength; const portBuffer = socks5DataBuffer.slice(portIndex, portIndex + 2); const portRemote = new DataView(portBuffer).getUint16(0); return { hasError: false, addressRemote: address, portRemote, rawClientData: socks5DataBuffer.slice(portIndex + 4) }; } async function handleTCPOutBound(remoteSocket, addressRemote, portRemote, rawClientData, webSocket, log) { async function connectAndWrite(address, port) { const tcpSocket2 = connect({ hostname: address, port }); remoteSocket.value = tcpSocket2; log(`connected to ${address}:${port}`); const writer = tcpSocket2.writable.getWriter(); await writer.write(rawClientData); writer.releaseLock(); return tcpSocket2; } async function retry() { const tcpSocket2 = await connectAndWrite(proxyIP || addressRemote, portRemote); tcpSocket2.closed.catch((error) => { console.log("retry tcpSocket closed error", error); }).finally(() => { safeCloseWebSocket(webSocket); }); remoteSocketToWS(tcpSocket2, webSocket, null, log); } const tcpSocket = await connectAndWrite(addressRemote, portRemote); remoteSocketToWS(tcpSocket, webSocket, retry, log); } function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) { let readableStreamCancel = false; const stream = new ReadableStream({ start(controller) { webSocketServer.addEventListener("message", (event) => { if (readableStreamCancel) { return; } const message = event.data; controller.enqueue(message); }); webSocketServer.addEventListener("close", () => { safeCloseWebSocket(webSocketServer); if (readableStreamCancel) { return; } controller.close(); }); webSocketServer.addEventListener("error", (err) => { log("webSocketServer error"); controller.error(err); }); const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader); if (error) { controller.error(error); } else if (earlyData) { controller.enqueue(earlyData); } }, pull(controller) {}, cancel(reason) { if (readableStreamCancel) { return; } log(`readableStream was canceled, due to ${reason}`); readableStreamCancel = true; safeCloseWebSocket(webSocketServer); } }); return stream; } async function remoteSocketToWS(remoteSocket, webSocket, retry, log) { let hasIncomingData = false; await remoteSocket.readable.pipeTo( new WritableStream({ start() {}, /** * * @param {Uint8Array} chunk * @param {*} controller */ async write(chunk, controller) { hasIncomingData = true; if (webSocket.readyState !== WS_READY_STATE_OPEN) { controller.error( "webSocket connection is not open" ); } webSocket.send(chunk); }, close() { log(`remoteSocket.readable is closed, hasIncomingData: ${hasIncomingData}`); }, abort(reason) { console.error("remoteSocket.readable abort", reason); } }) ).catch((error) => { console.error( `remoteSocketToWS error:`, error.stack || error ); safeCloseWebSocket(webSocket); }); if (hasIncomingData === false && retry) { log(`retry`); retry(); } } function isValidSHA224(hash) { const sha224Regex = /^[0-9a-f]{56}$/i; return sha224Regex.test(hash); } function base64ToArrayBuffer(base64Str) { if (!base64Str) { return { error: null }; } try { base64Str = base64Str.replace(/-/g, "+").replace(/_/g, "/"); const decode = atob(base64Str); const arryBuffer = Uint8Array.from(decode, (c) => c.charCodeAt(0)); return { earlyData: arryBuffer.buffer, error: null }; } catch (error) { return { error }; } } let WS_READY_STATE_OPEN = 1; let WS_READY_STATE_CLOSING = 2; function safeCloseWebSocket(socket) { try { if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) { socket.close(); } } catch (error) { console.error("safeCloseWebSocket error", error); } } // export { // worker_default as // default // }; //# sourceMappingURL=worker.js.map /** * [js-sha256]{@link https://github.com/emn178/js-sha256} * * @version 0.11.0 * @author Chen, Yi-Cyuan [emn178@gmail.com] * @copyright Chen, Yi-Cyuan 2014-2024 * @license MIT */ /*jslint bitwise: true */ (function () { 'use strict'; var ERROR = 'input is invalid type'; var WINDOW = typeof window === 'object'; var root = WINDOW ? window : {}; if (root.JS_SHA256_NO_WINDOW) { WINDOW = false; } var WEB_WORKER = !WINDOW && typeof self === 'object'; var NODE_JS = !root.JS_SHA256_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; if (NODE_JS) { root = global; } else if (WEB_WORKER) { root = self; } var COMMON_JS = !root.JS_SHA256_NO_COMMON_JS && typeof module === 'object' && module.exports; var AMD = typeof define === 'function' && define.amd; var ARRAY_BUFFER = !root.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined'; var HEX_CHARS = '0123456789abcdef'.split(''); var EXTRA = [-2147483648, 8388608, 32768, 128]; var SHIFT = [24, 16, 8, 0]; var K = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; var OUTPUT_TYPES = ['hex', 'array', 'digest', 'arrayBuffer']; var blocks = []; if (root.JS_SHA256_NO_NODE_JS || !Array.isArray) { Array.isArray = function (obj) { return Object.prototype.toString.call(obj) === '[object Array]'; }; } if (ARRAY_BUFFER && (root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { ArrayBuffer.isView = function (obj) { return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer; }; } var createOutputMethod = function (outputType, is224) { return function (message) { return new Sha256(is224, true).update(message)[outputType](); }; }; var createMethod = function (is224) { var method = createOutputMethod('hex', is224); if (NODE_JS) { method = nodeWrap(method, is224); } method.create = function () { return new Sha256(is224); }; method.update = function (message) { return method.create().update(message); }; for (var i = 0; i < OUTPUT_TYPES.length; ++i) { var type = OUTPUT_TYPES[i]; method[type] = createOutputMethod(type, is224); } return method; }; var nodeWrap = function (method, is224) { var crypto = require('crypto') var Buffer = require('buffer').Buffer; var algorithm = is224 ? 'sha224' : 'sha256'; var bufferFrom; if (Buffer.from && !root.JS_SHA256_NO_BUFFER_FROM) { bufferFrom = Buffer.from; } else { bufferFrom = function (message) { return new Buffer(message); }; } var nodeMethod = function (message) { if (typeof message === 'string') { return crypto.createHash(algorithm).update(message, 'utf8').digest('hex'); } else { if (message === null || message === undefined) { throw new Error(ERROR); } else if (message.constructor === ArrayBuffer) { message = new Uint8Array(message); } } if (Array.isArray(message) || ArrayBuffer.isView(message) || message.constructor === Buffer) { return crypto.createHash(algorithm).update(bufferFrom(message)).digest('hex'); } else { return method(message); } }; return nodeMethod; }; var createHmacOutputMethod = function (outputType, is224) { return function (key, message) { return new HmacSha256(key, is224, true).update(message)[outputType](); }; }; var createHmacMethod = function (is224) { var method = createHmacOutputMethod('hex', is224); method.create = function (key) { return new HmacSha256(key, is224); }; method.update = function (key, message) { return method.create(key).update(message); }; for (var i = 0; i < OUTPUT_TYPES.length; ++i) { var type = OUTPUT_TYPES[i]; method[type] = createHmacOutputMethod(type, is224); } return method; }; function Sha256(is224, sharedMemory) { if (sharedMemory) { blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; this.blocks = blocks; } else { this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; } if (is224) { this.h0 = 0xc1059ed8; this.h1 = 0x367cd507; this.h2 = 0x3070dd17; this.h3 = 0xf70e5939; this.h4 = 0xffc00b31; this.h5 = 0x68581511; this.h6 = 0x64f98fa7; this.h7 = 0xbefa4fa4; } else { // 256 this.h0 = 0x6a09e667; this.h1 = 0xbb67ae85; this.h2 = 0x3c6ef372; this.h3 = 0xa54ff53a; this.h4 = 0x510e527f; this.h5 = 0x9b05688c; this.h6 = 0x1f83d9ab; this.h7 = 0x5be0cd19; } this.block = this.start = this.bytes = this.hBytes = 0; this.finalized = this.hashed = false; this.first = true; this.is224 = is224; } Sha256.prototype.update = function (message) { if (this.finalized) { return; } var notString, type = typeof message; if (type !== 'string') { if (type === 'object') { if (message === null) { throw new Error(ERROR); } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { message = new Uint8Array(message); } else if (!Array.isArray(message)) { if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { throw new Error(ERROR); } } } else { throw new Error(ERROR); } notString = true; } var code, index = 0, i, length = message.length, blocks = this.blocks; while (index < length) { if (this.hashed) { this.hashed = false; blocks[0] = this.block; this.block = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; } if (notString) { for (i = this.start; index < length && i < 64; ++index) { blocks[i >>> 2] |= message[index] << SHIFT[i++ & 3]; } } else { for (i = this.start; index < length && i < 64; ++index) { code = message.charCodeAt(index); if (code < 0x80) { blocks[i >>> 2] |= code << SHIFT[i++ & 3]; } else if (code < 0x800) { blocks[i >>> 2] |= (0xc0 | (code >>> 6)) << SHIFT[i++ & 3]; blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else if (code < 0xd800 || code >= 0xe000) { blocks[i >>> 2] |= (0xe0 | (code >>> 12)) << SHIFT[i++ & 3]; blocks[i >>> 2] |= (0x80 | ((code >>> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else { code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); blocks[i >>> 2] |= (0xf0 | (code >>> 18)) << SHIFT[i++ & 3]; blocks[i >>> 2] |= (0x80 | ((code >>> 12) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >>> 2] |= (0x80 | ((code >>> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } } } this.lastByteIndex = i; this.bytes += i - this.start; if (i >= 64) { this.block = blocks[16]; this.start = i - 64; this.hash(); this.hashed = true; } else { this.start = i; } } if (this.bytes > 4294967295) { this.hBytes += this.bytes / 4294967296 << 0; this.bytes = this.bytes % 4294967296; } return this; }; Sha256.prototype.finalize = function () { if (this.finalized) { return; } this.finalized = true; var blocks = this.blocks, i = this.lastByteIndex; blocks[16] = this.block; blocks[i >>> 2] |= EXTRA[i & 3]; this.block = blocks[16]; if (i >= 56) { if (!this.hashed) { this.hash(); } blocks[0] = this.block; blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; } blocks[14] = this.hBytes << 3 | this.bytes >>> 29; blocks[15] = this.bytes << 3; this.hash(); }; Sha256.prototype.hash = function () { var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; for (j = 16; j < 64; ++j) { // rightrotate t1 = blocks[j - 15]; s0 = ((t1 >>> 7) | (t1 << 25)) ^ ((t1 >>> 18) | (t1 << 14)) ^ (t1 >>> 3); t1 = blocks[j - 2]; s1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10); blocks[j] = blocks[j - 16] + s0 + blocks[j - 7] + s1 << 0; } bc = b & c; for (j = 0; j < 64; j += 4) { if (this.first) { if (this.is224) { ab = 300032; t1 = blocks[0] - 1413257819; h = t1 - 150054599 << 0; d = t1 + 24177077 << 0; } else { ab = 704751109; t1 = blocks[0] - 210244248; h = t1 - 1521486534 << 0; d = t1 + 143694565 << 0; } this.first = false; } else { s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10)); s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7)); ab = a & b; maj = ab ^ (a & c) ^ bc; ch = (e & f) ^ (~e & g); t1 = h + s1 + ch + K[j] + blocks[j]; t2 = s0 + maj; h = d + t1 << 0; d = t1 + t2 << 0; } s0 = ((d >>> 2) | (d << 30)) ^ ((d >>> 13) | (d << 19)) ^ ((d >>> 22) | (d << 10)); s1 = ((h >>> 6) | (h << 26)) ^ ((h >>> 11) | (h << 21)) ^ ((h >>> 25) | (h << 7)); da = d & a; maj = da ^ (d & b) ^ ab; ch = (h & e) ^ (~h & f); t1 = g + s1 + ch + K[j + 1] + blocks[j + 1]; t2 = s0 + maj; g = c + t1 << 0; c = t1 + t2 << 0; s0 = ((c >>> 2) | (c << 30)) ^ ((c >>> 13) | (c << 19)) ^ ((c >>> 22) | (c << 10)); s1 = ((g >>> 6) | (g << 26)) ^ ((g >>> 11) | (g << 21)) ^ ((g >>> 25) | (g << 7)); cd = c & d; maj = cd ^ (c & a) ^ da; ch = (g & h) ^ (~g & e); t1 = f + s1 + ch + K[j + 2] + blocks[j + 2]; t2 = s0 + maj; f = b + t1 << 0; b = t1 + t2 << 0; s0 = ((b >>> 2) | (b << 30)) ^ ((b >>> 13) | (b << 19)) ^ ((b >>> 22) | (b << 10)); s1 = ((f >>> 6) | (f << 26)) ^ ((f >>> 11) | (f << 21)) ^ ((f >>> 25) | (f << 7)); bc = b & c; maj = bc ^ (b & d) ^ cd; ch = (f & g) ^ (~f & h); t1 = e + s1 + ch + K[j + 3] + blocks[j + 3]; t2 = s0 + maj; e = a + t1 << 0; a = t1 + t2 << 0; this.chromeBugWorkAround = true; } this.h0 = this.h0 + a << 0; this.h1 = this.h1 + b << 0; this.h2 = this.h2 + c << 0; this.h3 = this.h3 + d << 0; this.h4 = this.h4 + e << 0; this.h5 = this.h5 + f << 0; this.h6 = this.h6 + g << 0; this.h7 = this.h7 + h << 0; }; Sha256.prototype.hex = function () { this.finalize(); var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; var hex = HEX_CHARS[(h0 >>> 28) & 0x0F] + HEX_CHARS[(h0 >>> 24) & 0x0F] + HEX_CHARS[(h0 >>> 20) & 0x0F] + HEX_CHARS[(h0 >>> 16) & 0x0F] + HEX_CHARS[(h0 >>> 12) & 0x0F] + HEX_CHARS[(h0 >>> 8) & 0x0F] + HEX_CHARS[(h0 >>> 4) & 0x0F] + HEX_CHARS[h0 & 0x0F] + HEX_CHARS[(h1 >>> 28) & 0x0F] + HEX_CHARS[(h1 >>> 24) & 0x0F] + HEX_CHARS[(h1 >>> 20) & 0x0F] + HEX_CHARS[(h1 >>> 16) & 0x0F] + HEX_CHARS[(h1 >>> 12) & 0x0F] + HEX_CHARS[(h1 >>> 8) & 0x0F] + HEX_CHARS[(h1 >>> 4) & 0x0F] + HEX_CHARS[h1 & 0x0F] + HEX_CHARS[(h2 >>> 28) & 0x0F] + HEX_CHARS[(h2 >>> 24) & 0x0F] + HEX_CHARS[(h2 >>> 20) & 0x0F] + HEX_CHARS[(h2 >>> 16) & 0x0F] + HEX_CHARS[(h2 >>> 12) & 0x0F] + HEX_CHARS[(h2 >>> 8) & 0x0F] + HEX_CHARS[(h2 >>> 4) & 0x0F] + HEX_CHARS[h2 & 0x0F] + HEX_CHARS[(h3 >>> 28) & 0x0F] + HEX_CHARS[(h3 >>> 24) & 0x0F] + HEX_CHARS[(h3 >>> 20) & 0x0F] + HEX_CHARS[(h3 >>> 16) & 0x0F] + HEX_CHARS[(h3 >>> 12) & 0x0F] + HEX_CHARS[(h3 >>> 8) & 0x0F] + HEX_CHARS[(h3 >>> 4) & 0x0F] + HEX_CHARS[h3 & 0x0F] + HEX_CHARS[(h4 >>> 28) & 0x0F] + HEX_CHARS[(h4 >>> 24) & 0x0F] + HEX_CHARS[(h4 >>> 20) & 0x0F] + HEX_CHARS[(h4 >>> 16) & 0x0F] + HEX_CHARS[(h4 >>> 12) & 0x0F] + HEX_CHARS[(h4 >>> 8) & 0x0F] + HEX_CHARS[(h4 >>> 4) & 0x0F] + HEX_CHARS[h4 & 0x0F] + HEX_CHARS[(h5 >>> 28) & 0x0F] + HEX_CHARS[(h5 >>> 24) & 0x0F] + HEX_CHARS[(h5 >>> 20) & 0x0F] + HEX_CHARS[(h5 >>> 16) & 0x0F] + HEX_CHARS[(h5 >>> 12) & 0x0F] + HEX_CHARS[(h5 >>> 8) & 0x0F] + HEX_CHARS[(h5 >>> 4) & 0x0F] + HEX_CHARS[h5 & 0x0F] + HEX_CHARS[(h6 >>> 28) & 0x0F] + HEX_CHARS[(h6 >>> 24) & 0x0F] + HEX_CHARS[(h6 >>> 20) & 0x0F] + HEX_CHARS[(h6 >>> 16) & 0x0F] + HEX_CHARS[(h6 >>> 12) & 0x0F] + HEX_CHARS[(h6 >>> 8) & 0x0F] + HEX_CHARS[(h6 >>> 4) & 0x0F] + HEX_CHARS[h6 & 0x0F]; if (!this.is224) { hex += HEX_CHARS[(h7 >>> 28) & 0x0F] + HEX_CHARS[(h7 >>> 24) & 0x0F] + HEX_CHARS[(h7 >>> 20) & 0x0F] + HEX_CHARS[(h7 >>> 16) & 0x0F] + HEX_CHARS[(h7 >>> 12) & 0x0F] + HEX_CHARS[(h7 >>> 8) & 0x0F] + HEX_CHARS[(h7 >>> 4) & 0x0F] + HEX_CHARS[h7 & 0x0F]; } return hex; }; Sha256.prototype.toString = Sha256.prototype.hex; Sha256.prototype.digest = function () { this.finalize(); var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; var arr = [ (h0 >>> 24) & 0xFF, (h0 >>> 16) & 0xFF, (h0 >>> 8) & 0xFF, h0 & 0xFF, (h1 >>> 24) & 0xFF, (h1 >>> 16) & 0xFF, (h1 >>> 8) & 0xFF, h1 & 0xFF, (h2 >>> 24) & 0xFF, (h2 >>> 16) & 0xFF, (h2 >>> 8) & 0xFF, h2 & 0xFF, (h3 >>> 24) & 0xFF, (h3 >>> 16) & 0xFF, (h3 >>> 8) & 0xFF, h3 & 0xFF, (h4 >>> 24) & 0xFF, (h4 >>> 16) & 0xFF, (h4 >>> 8) & 0xFF, h4 & 0xFF, (h5 >>> 24) & 0xFF, (h5 >>> 16) & 0xFF, (h5 >>> 8) & 0xFF, h5 & 0xFF, (h6 >>> 24) & 0xFF, (h6 >>> 16) & 0xFF, (h6 >>> 8) & 0xFF, h6 & 0xFF ]; if (!this.is224) { arr.push((h7 >>> 24) & 0xFF, (h7 >>> 16) & 0xFF, (h7 >>> 8) & 0xFF, h7 & 0xFF); } return arr; }; Sha256.prototype.array = Sha256.prototype.digest; Sha256.prototype.arrayBuffer = function () { this.finalize(); var buffer = new ArrayBuffer(this.is224 ? 28 : 32); var dataView = new DataView(buffer); dataView.setUint32(0, this.h0); dataView.setUint32(4, this.h1); dataView.setUint32(8, this.h2); dataView.setUint32(12, this.h3); dataView.setUint32(16, this.h4); dataView.setUint32(20, this.h5); dataView.setUint32(24, this.h6); if (!this.is224) { dataView.setUint32(28, this.h7); } return buffer; }; function HmacSha256(key, is224, sharedMemory) { var i, type = typeof key; if (type === 'string') { var bytes = [], length = key.length, index = 0, code; for (i = 0; i < length; ++i) { code = key.charCodeAt(i); if (code < 0x80) { bytes[index++] = code; } else if (code < 0x800) { bytes[index++] = (0xc0 | (code >>> 6)); bytes[index++] = (0x80 | (code & 0x3f)); } else if (code < 0xd800 || code >= 0xe000) { bytes[index++] = (0xe0 | (code >>> 12)); bytes[index++] = (0x80 | ((code >>> 6) & 0x3f)); bytes[index++] = (0x80 | (code & 0x3f)); } else { code = 0x10000 + (((code & 0x3ff) << 10) | (key.charCodeAt(++i) & 0x3ff)); bytes[index++] = (0xf0 | (code >>> 18)); bytes[index++] = (0x80 | ((code >>> 12) & 0x3f)); bytes[index++] = (0x80 | ((code >>> 6) & 0x3f)); bytes[index++] = (0x80 | (code & 0x3f)); } } key = bytes; } else { if (type === 'object') { if (key === null) { throw new Error(ERROR); } else if (ARRAY_BUFFER && key.constructor === ArrayBuffer) { key = new Uint8Array(key); } else if (!Array.isArray(key)) { if (!ARRAY_BUFFER || !ArrayBuffer.isView(key)) { throw new Error(ERROR); } } } else { throw new Error(ERROR); } } if (key.length > 64) { key = (new Sha256(is224, true)).update(key).array(); } var oKeyPad = [], iKeyPad = []; for (i = 0; i < 64; ++i) { var b = key[i] || 0; oKeyPad[i] = 0x5c ^ b; iKeyPad[i] = 0x36 ^ b; } Sha256.call(this, is224, sharedMemory); this.update(iKeyPad); this.oKeyPad = oKeyPad; this.inner = true; this.sharedMemory = sharedMemory; } HmacSha256.prototype = new Sha256(); HmacSha256.prototype.finalize = function () { Sha256.prototype.finalize.call(this); if (this.inner) { this.inner = false; var innerHash = this.array(); Sha256.call(this, this.is224, this.sharedMemory); this.update(this.oKeyPad); this.update(innerHash); Sha256.prototype.finalize.call(this); } }; var exports = createMethod(); exports.sha256 = exports; exports.sha224 = createMethod(true); exports.sha256.hmac = createHmacMethod(); exports.sha224.hmac = createHmacMethod(true); if (COMMON_JS) { module.exports = exports; } else { root.sha256 = exports.sha256; root.sha224 = exports.sha224; if (AMD) { define(function () { return exports; }); } } })(); ================================================ FILE: utils/csv.go ================================================ package utils import ( "encoding/csv" "fmt" "golang.org/x/text/encoding/simplifiedchinese" "golang.org/x/text/transform" "log" "net" "os" "sort" "strconv" "time" ) const ( defaultOutput = "result.csv" maxDelay = 9999 * time.Millisecond minDelay = 0 * time.Millisecond maxLossRate float32 = 1.0 ) var ( InputMaxDelay = maxDelay InputMinDelay = minDelay InputMaxLossRate = maxLossRate Output = defaultOutput PrintNum = 10 ) // 是否打印测试结果 func NoPrintResult() bool { return PrintNum == 0 } // 是否输出到文件 func noOutput() bool { return Output == "" || Output == " " } type PingData struct { IP *net.IPAddr Sended int Received int Delay time.Duration } type CloudflareIPData struct { *PingData lossRate float32 DownloadSpeed float64 Country string } // 计算丢包率 func (cf *CloudflareIPData) getLossRate() float32 { if cf.lossRate == 0 { pingLost := cf.Sended - cf.Received cf.lossRate = float32(pingLost) / float32(cf.Sended) } return cf.lossRate } func (cf *CloudflareIPData) toString() []string { result := make([]string, 6) result[0] = cf.IP.String() result[1] = strconv.Itoa(cf.Sended) result[2] = strconv.Itoa(cf.Received) result[3] = strconv.FormatFloat(float64(cf.getLossRate()), 'f', 2, 32) result[4] = strconv.FormatFloat(cf.Delay.Seconds()*1000, 'f', 2, 32) result[5] = strconv.FormatFloat(cf.DownloadSpeed/1024/1024, 'f', 2, 32) return result } func WriteFile(filename string, data []CloudflareIPData) { fp, err := os.Create(filename) if err != nil { log.Fatalf("创建文件[%s]失败:%v", filename, err) return } defer fp.Close() w := csv.NewWriter(fp) //创建一个新的写入文件流 _ = w.Write([]string{"IP 地址", "已发送", "已接收", "丢包率(%)", "延迟(ms)", "下载速度(Mbps)"}) _ = w.WriteAll(convertToString(data)) w.Flush() } func ExportCsvByCountry(data []CloudflareIPData) { theCC := "" datatmp := make([]CloudflareIPData, 0) for i, v := range data { if theCC == "" { theCC = v.Country } if v.Country != theCC { filename := theCC + ".csv" sort.Slice(datatmp, func(i, j int) bool { return datatmp[i].DownloadSpeed > datatmp[j].DownloadSpeed }) WriteFile(filename, datatmp) theCC = v.Country datatmp = datatmp[:0] } datatmp = append(datatmp, v) if i == len(data)-1 { filename := theCC + ".csv" sort.Slice(datatmp, func(i, j int) bool { return datatmp[i].DownloadSpeed > datatmp[j].DownloadSpeed }) WriteFile(filename, datatmp) } } } func ExportCsv(data []CloudflareIPData) { if noOutput() || len(data) == 0 { return } fp, err := os.Create(Output) if err != nil { log.Fatalf("创建文件[%s]失败:%v", Output, err) return } defer fp.Close() gbkEncoder := simplifiedchinese.GBK.NewEncoder() w := csv.NewWriter(transform.NewWriter(fp, gbkEncoder)) _ = w.Write([]string{"IP 地址", "已发送", "已接收", "丢包率", "平均延迟", "下载速度 (MB/s)"}) _ = w.WriteAll(convertToString(data)) w.Flush() } func convertToString(data []CloudflareIPData) [][]string { result := make([][]string, 0) for _, v := range data { result = append(result, v.toString()) } return result } // 延迟丢包排序 type PingDelaySet []CloudflareIPData // 延迟条件过滤 func (s PingDelaySet) FilterDelay() (data PingDelaySet) { if InputMaxDelay > maxDelay || InputMinDelay < minDelay { // 当输入的延迟条件不在默认范围内时,不进行过滤 return s } if InputMaxDelay == maxDelay && InputMinDelay == minDelay { // 当输入的延迟条件为默认值时,不进行过滤 return s } for _, v := range s { if v.Delay > InputMaxDelay { // 平均延迟上限,延迟大于条件最大值时,后面的数据都不满足条件,直接跳出循环 break } if v.Delay < InputMinDelay { // 平均延迟下限,延迟小于条件最小值时,不满足条件,跳过 continue } data = append(data, v) // 延迟满足条件时,添加到新数组中 } return } // 丢包条件过滤 func (s PingDelaySet) FilterLossRate() (data PingDelaySet) { if InputMaxLossRate >= maxLossRate { // 当输入的丢包条件为默认值时,不进行过滤 return s } for _, v := range s { if v.getLossRate() > InputMaxLossRate { // 丢包几率上限 break } data = append(data, v) // 丢包率满足条件时,添加到新数组中 } return } func (s PingDelaySet) FilterCountryV2(info *CountryInfo, countrycodeList map[string]bool) (data PingDelaySet) { fmt.Printf("开始查询IP的国家代号...\n") bfilterCountry := false if len(countrycodeList) > 0 { bfilterCountry = true } for _, v := range s { v.Country = info.GetCountryV2(v.IP.IP.String()) if v.Country == "" { fmt.Printf("IP: %s 无法获取国家代号,已跳过\n", v.IP.IP.String()) continue } if bfilterCountry { if countrycodeList[v.Country] == true { data = append(data, v) } } else { data = append(data, v) } } return } func (s PingDelaySet) FilterCountryV3(info *CountryInfo) (data PingDelaySet) { fmt.Printf("开始查询IP的国家代号...\n") for _, v := range s { v.Country = info.GetCountryV2(v.IP.IP.String()) if v.Country == "" { data = append(data, v) } } return } func (s PingDelaySet) FilterCountryV1() (data PingDelaySet) { countrys := make([]IpResponse, 0) ips := make([]string, 0) querycount := 0 fmt.Printf("开始查询IP的国家代号...\n") bar := NewBar(len(s), "已查:", "") for i, v := range s { if i > 0 && i%100 == 0 { countryCodeInfo := getCountryV1(ips) if countryCodeInfo == nil { fmt.Printf("[WARN] %s\n", "IP查询失败,请检查网络或API接口是否正常") continue } countrys = append(countrys, countryCodeInfo...) bar.Grow(100, strconv.Itoa(len(countrys))) ips = ips[:0] querycount++ if querycount >= 15 { time.Sleep(61 * time.Second) querycount = 0 } } ip := v.IP.IP ips = append(ips, ip.String()) } if len(ips) > 0 { if querycount >= 15 { time.Sleep(61 * time.Second) } countryCodeInfo := getCountryV1(ips) countrys = append(countrys, countryCodeInfo...) bar.Grow(len(ips), strconv.Itoa(len(countrys))) } bar.Done() for i, v := range countrys { m := s[i] if v.Status == "fail" { m.Country = "" } else { m.Country = v.CountryCode } data = append(data, m) } return } func (s PingDelaySet) Len() int { return len(s) } func (s PingDelaySet) Less(i, j int) bool { iRate, jRate := s[i].getLossRate(), s[j].getLossRate() if iRate != jRate { return iRate < jRate } return s[i].Delay < s[j].Delay } func (s PingDelaySet) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // 下载速度排序 type DownloadSpeedSet []CloudflareIPData func (s DownloadSpeedSet) Len() int { return len(s) } func (s DownloadSpeedSet) Less(i, j int) bool { return s[i].DownloadSpeed > s[j].DownloadSpeed } func (s DownloadSpeedSet) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s DownloadSpeedSet) Print() { if NoPrintResult() { return } if len(s) <= 0 { // IP数组长度(IP数量) 大于 0 时继续 fmt.Println("\n[信息] 完整测速结果 IP 数量为 0,跳过输出结果。") return } dateString := convertToString(s) // 转为多维数组 [][]String if len(dateString) < PrintNum { // 如果IP数组长度(IP数量) 小于 打印次数,则次数改为IP数量 PrintNum = len(dateString) } headFormat := "%-16s%-5s%-5s%-5s%-6s%-11s\n" dataFormat := "%-18s%-8s%-8s%-8s%-10s%-15s\n" for i := 0; i < PrintNum; i++ { // 如果要输出的 IP 中包含 IPv6,那么就需要调整一下间隔 if len(dateString[i][0]) > 15 { headFormat = "%-40s%-5s%-5s%-5s%-6s%-11s\n" dataFormat = "%-42s%-8s%-8s%-8s%-10s%-15s\n" break } } fmt.Printf(headFormat, "IP 地址", "已发送", "已接收", "丢包率", "平均延迟", "下载速度 (MB/s)") for i := 0; i < PrintNum; i++ { fmt.Printf(dataFormat, dateString[i][0], dateString[i][1], dateString[i][2], dateString[i][3], dateString[i][4], dateString[i][5]) } if !noOutput() { fmt.Printf("\n完整测速结果已写入 %v 文件,可使用记事本/表格软件查看。\n", Output) } } func (s DownloadSpeedSet) PrintbyCountry() { if NoPrintResult() { return } } ================================================ FILE: utils/csv_test.go ================================================ package utils import ( "reflect" "testing" ) func TestPingDelaySet_FilterLossRate(t *testing.T) { tests := []struct { name string s PingDelaySet wantData PingDelaySet }{ // TODO: Add test cases. } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if gotData := tt.s.FilterLossRate(); !reflect.DeepEqual(gotData, tt.wantData) { t.Errorf("FilterLossRate() = %v, want %v", gotData, tt.wantData) } }) } } ================================================ FILE: utils/getcountry.go ================================================ package utils import ( "bytes" "encoding/json" "fmt" "github.com/oschwald/maxminddb-golang" "io" "net" "net/http" ) type IpResponse struct { Status string `json:"status"` CountryCode string `json:"countryCode"` } // 每分钟15次查询,每次最多100个ip func getCountryV1(ips []string) (coutryCodes []IpResponse) { jsonData, err := json.Marshal(ips) if err != nil { fmt.Println(err.Error()) return nil } resp, err := http.Post("http://ip-api.com/batch", "application/json", bytes.NewBuffer(jsonData)) if err != nil { fmt.Println(err.Error()) return nil } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) data := make([]IpResponse, 0) err = json.Unmarshal(body, &data) if err != nil { fmt.Println(err) return nil } for _, v := range data { coutryCodes = append(coutryCodes, v) } return } // 使用本地mmdb文件查国家代码 type Country struct { GeoNameID uint `maxminddb:"geoname_id"` IsoCode string `maxminddb:"iso_code"` Names map[string]string `maxminddb:"names"` } type Record struct { C Country `maxminddb:"country"` } type CountryInfo struct { db *maxminddb.Reader } func NewCountryInfo(db *maxminddb.Reader) *CountryInfo { return &CountryInfo{ db: db, } } func (c *CountryInfo) GetCountryV2(ip string) string { ipinfo := net.ParseIP(ip) var record Record err := c.db.Lookup(ipinfo, &record) if err != nil { fmt.Println(err) return "" } return record.C.IsoCode } func (c *CountryInfo) Done() { defer c.db.Close() } ================================================ FILE: utils/progress.go ================================================ package utils import ( "fmt" "github.com/cheggaaa/pb/v3" ) type Bar struct { pb *pb.ProgressBar } func NewBar(count int, MyStrStart, MyStrEnd string) *Bar { tmpl := fmt.Sprintf(`{{counters . }} {{ bar . "[" "-" (cycle . "↖" "↗" "↘" "↙" ) "_" "]"}} %s {{string . "MyStr" | green}} %s `, MyStrStart, MyStrEnd) bar := pb.ProgressBarTemplate(tmpl).Start(count) return &Bar{pb: bar} } func (b *Bar) Grow(num int, MyStrVal string) { b.pb.Set("MyStr", MyStrVal).Add(num) } func (b *Bar) Done() { b.pb.Finish() } ================================================ FILE: vless_workers/_worker.js ================================================ // @ts-ignore import { connect } from 'cloudflare:sockets'; // How to generate your own UUID: // [Windows] Press "Win + R", input cmd and run: Powershell -NoExit -Command "[guid]::NewGuid()" let userID = 'd342d11e-d424-4583-b36e-524ab1f0afa4'; const proxyIPs = ['cdn.xn--b6gac.eu.org:443', 'cdn-all.xn--b6gac.eu.org:443']; // if you want to use ipv6 or single proxyIP, please add comment at this line and remove comment at the next line let proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)]; // how to make sure the proxyIP with port is valid? // go to https://proxyip.edtunnel.best/ , input your proxyIP:proxyPort, and click "Check" button // if the port is valid, value "Proxy IP" is true, otherwise false and the value "Origin" must be 443 let proxyPort = proxyIP.includes(':') ? proxyIP.split(':')[1] : '443'; // use single proxyip instead of random // let proxyIP = 'cdn.xn--b6gac.eu.org'; // ipv6 proxyIP example remove comment to use // let proxyIP = "[2a01:4f8:c2c:123f:64:5:6810:c55a]" // Example: user:pass@host:port or host:port let socks5Address = ''; // socks5Relay is true, will proxy all traffic to socks5Address, otherwise socks5Address only be used for cloudflare ips let socks5Relay = false; if (!isValidUUID(userID)) { throw new Error('uuid is not valid'); } let parsedSocks5Address = {}; let enableSocks = false; export default { /** * @param {import("@cloudflare/workers-types").Request} request * @param {{UUID: string, PROXYIP: string, SOCKS5: string, SOCKS5_RELAY: string}} env * @param {import("@cloudflare/workers-types").ExecutionContext} _ctx * @returns {Promise} */ async fetch(request, env, _ctx) { try { const { UUID, PROXYIP, SOCKS5, SOCKS5_RELAY } = env; userID = UUID || userID; socks5Address = SOCKS5 || socks5Address; socks5Relay = SOCKS5_RELAY || socks5Relay; if (PROXYIP) { // Split PROXYIP into an array of proxy addresses const proxyAddresses = PROXYIP.split(',').map(addr => addr.trim()); // Randomly select one proxy address const selectedProxy = proxyAddresses[Math.floor(Math.random() * proxyAddresses.length)]; [proxyIP, proxyPort = '443'] = selectedProxy.split(':'); } else { proxyPort = proxyIP.includes(':') ? proxyIP.split(':')[1] : '443'; proxyIP = proxyIP.split(':')[0]; } console.log('ProxyIP:', proxyIP); console.log('ProxyPort:', proxyPort); if (socks5Address) { try { // Split SOCKS5 into an array of addresses const socks5Addresses = socks5Address.split(',').map(addr => addr.trim()); // Randomly select one SOCKS5 address const selectedSocks5 = socks5Addresses[Math.floor(Math.random() * socks5Addresses.length)]; parsedSocks5Address = socks5AddressParser(selectedSocks5); enableSocks = true; } catch (err) { console.log(err.toString()); enableSocks = false; } } const userID_Path = userID.includes(',') ? userID.split(',')[0] : userID; const url = new URL(request.url); const host = request.headers.get('Host'); if (request.headers.get('Upgrade') !== 'websocket') { switch (url.pathname) { case '/cf': return new Response(JSON.stringify(request.cf, null, 4), { status: 200, headers: { "Content-Type": "application/json;charset=utf-8" }, }); case `/${userID_Path}`: return new Response(getConfig(userID, host), { status: 200, headers: { "Content-Type": "text/html; charset=utf-8" }, }); case `/sub/${userID_Path}`: return new Response(btoa(GenSub(userID, host)), { status: 200, headers: { "Content-Type": "text/plain;charset=utf-8" }, }); case `/bestip/${userID_Path}`: return fetch(`https://sub.xf.free.hr/auto?host=${host}&uuid=${userID}&path=/`, { headers: request.headers }); default: return handleDefaultPath(url, request); } } else { return await ProtocolOverWSHandler(request); } } catch (err) { return new Response(err.toString()); } }, }; async function handleDefaultPath(url, request) { const randomHostname = hostnames[Math.floor(Math.random() * hostnames.length)]; const newHeaders = new Headers(request.headers); newHeaders.set('cf-connecting-ip', '1.2.3.4'); newHeaders.set('x-forwarded-for', '1.2.3.4'); newHeaders.set('x-real-ip', '1.2.3.4'); newHeaders.set('referer', 'https://www.google.com/search?q=edtunnel'); const proxyUrl = 'https://' + randomHostname + url.pathname + url.search; const modifiedRequest = new Request(proxyUrl, { method: request.method, headers: newHeaders, body: request.body, redirect: 'manual', }); const proxyResponse = await fetch(modifiedRequest, { redirect: 'manual' }); if ([301, 302].includes(proxyResponse.status)) { return new Response(`Redirects to ${randomHostname} are not allowed.`, { status: 403, statusText: 'Forbidden', }); } return proxyResponse; } /** * Handles protocol over WebSocket requests by creating a WebSocket pair, accepting the WebSocket connection, and processing the protocol header. * @param {import("@cloudflare/workers-types").Request} request The incoming request object. * @returns {Promise} A Promise that resolves to a WebSocket response object. */ async function ProtocolOverWSHandler(request) { /** @type {import("@cloudflare/workers-types").WebSocket[]} */ // @ts-ignore const webSocketPair = new WebSocketPair(); const [client, webSocket] = Object.values(webSocketPair); webSocket.accept(); let address = ''; let portWithRandomLog = ''; const log = (/** @type {string} */ info, /** @type {string | undefined} */ event) => { console.log(`[${address}:${portWithRandomLog}] ${info}`, event || ''); }; const earlyDataHeader = request.headers.get('sec-websocket-protocol') || ''; const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log); /** @type {{ value: import("@cloudflare/workers-types").Socket | null}}*/ let remoteSocketWapper = { value: null, }; let isDns = false; // ws --> remote readableWebSocketStream.pipeTo(new WritableStream({ async write(chunk, controller) { if (isDns) { return await handleDNSQuery(chunk, webSocket, null, log); } if (remoteSocketWapper.value) { const writer = remoteSocketWapper.value.writable.getWriter() await writer.write(chunk); writer.releaseLock(); return; } const { hasError, message, addressType, portRemote = 443, addressRemote = '', rawDataIndex, ProtocolVersion = new Uint8Array([0, 0]), isUDP, } = processProtocolHeader(chunk, userID); address = addressRemote; portWithRandomLog = `${portRemote}--${Math.random()} ${isUDP ? 'udp ' : 'tcp ' } `; if (hasError) { // controller.error(message); throw new Error(message); // cf seems has bug, controller.error will not end stream } // Handle UDP connections for DNS (port 53) only if (isUDP) { if (portRemote === 53) { isDns = true; } else { throw new Error('UDP proxy is only enabled for DNS (port 53)'); } return; // Early return after setting isDns or throwing error } // ["version", "附加信息长度 N"] const ProtocolResponseHeader = new Uint8Array([ProtocolVersion[0], 0]); const rawClientData = chunk.slice(rawDataIndex); if (isDns) { return handleDNSQuery(rawClientData, webSocket, ProtocolResponseHeader, log); } handleTCPOutBound(remoteSocketWapper, addressType, addressRemote, portRemote, rawClientData, webSocket, ProtocolResponseHeader, log); }, close() { log(`readableWebSocketStream is close`); }, abort(reason) { log(`readableWebSocketStream is abort`, JSON.stringify(reason)); }, })).catch((err) => { log('readableWebSocketStream pipeTo error', err); }); return new Response(null, { status: 101, // @ts-ignore webSocket: client, }); } /** * Handles outbound TCP connections. * * @param {any} remoteSocket * @param {string} addressRemote The remote address to connect to. * @param {number} portRemote The remote port to connect to. * @param {Uint8Array} rawClientData The raw client data to write. * @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket to pass the remote socket to. * @param {Uint8Array} protocolResponseHeader The protocol response header. * @param {function} log The logging function. * @returns {Promise} The remote socket. */ async function handleTCPOutBound(remoteSocket, addressType, addressRemote, portRemote, rawClientData, webSocket, ProtocolResponseHeader, log,) { async function connectAndWrite(address, port, socks = false) { /** @type {import("@cloudflare/workers-types").Socket} */ let tcpSocket; if (socks5Relay) { tcpSocket = await socks5Connect(addressType, address, port, log) } else { tcpSocket = socks ? await socks5Connect(addressType, address, port, log) : connect({ hostname: address, port: port, }); } remoteSocket.value = tcpSocket; log(`connected to ${address}:${port}`); const writer = tcpSocket.writable.getWriter(); await writer.write(rawClientData); // first write, normal is tls client hello writer.releaseLock(); return tcpSocket; } // if the cf connect tcp socket have no incoming data, we retry to redirect ip async function retry() { if (enableSocks) { tcpSocket = await connectAndWrite(addressRemote, portRemote, true); } else { tcpSocket = await connectAndWrite(proxyIP || addressRemote, proxyPort || portRemote, false); } // no matter retry success or not, close websocket tcpSocket.closed.catch(error => { console.log('retry tcpSocket closed error', error); }).finally(() => { safeCloseWebSocket(webSocket); }) remoteSocketToWS(tcpSocket, webSocket, ProtocolResponseHeader, null, log); } let tcpSocket = await connectAndWrite(addressRemote, portRemote); // when remoteSocket is ready, pass to websocket // remote--> ws remoteSocketToWS(tcpSocket, webSocket, ProtocolResponseHeader, retry, log); } /** * Creates a readable stream from a WebSocket server, allowing for data to be read from the WebSocket. * @param {import("@cloudflare/workers-types").WebSocket} webSocketServer The WebSocket server to create the readable stream from. * @param {string} earlyDataHeader The header containing early data for WebSocket 0-RTT. * @param {(info: string)=> void} log The logging function. * @returns {ReadableStream} A readable stream that can be used to read data from the WebSocket. */ function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) { let readableStreamCancel = false; const stream = new ReadableStream({ start(controller) { webSocketServer.addEventListener('message', (event) => { const message = event.data; controller.enqueue(message); }); webSocketServer.addEventListener('close', () => { safeCloseWebSocket(webSocketServer); controller.close(); }); webSocketServer.addEventListener('error', (err) => { log('webSocketServer has error'); controller.error(err); }); const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader); if (error) { controller.error(error); } else if (earlyData) { controller.enqueue(earlyData); } }, pull(_controller) { // if ws can stop read if stream is full, we can implement backpressure // https://streams.spec.whatwg.org/#example-rs-push-backpressure }, cancel(reason) { log(`ReadableStream was canceled, due to ${reason}`) readableStreamCancel = true; safeCloseWebSocket(webSocketServer); } }); return stream; } // https://xtls.github.io/development/protocols/protocol.html // https://github.com/zizifn/excalidraw-backup/blob/main/v2ray-protocol.excalidraw /** * Processes the protocol header buffer and returns an object with the relevant information. * @param {ArrayBuffer} protocolBuffer The protocol header buffer to process. * @param {string} userID The user ID to validate against the UUID in the protocol header. * @returns {{ * hasError: boolean, * message?: string, * addressRemote?: string, * addressType?: number, * portRemote?: number, * rawDataIndex?: number, * protocolVersion?: Uint8Array, * isUDP?: boolean * }} An object with the relevant information extracted from the protocol header buffer. */ function processProtocolHeader(protocolBuffer, userID) { if (protocolBuffer.byteLength < 24) { return { hasError: true, message: 'invalid data' }; } const dataView = new DataView(protocolBuffer); const version = dataView.getUint8(0); const slicedBufferString = stringify(new Uint8Array(protocolBuffer.slice(1, 17))); const uuids = userID.includes(',') ? userID.split(",") : [userID]; const isValidUser = uuids.some(uuid => slicedBufferString === uuid.trim()) || (uuids.length === 1 && slicedBufferString === uuids[0].trim()); console.log(`userID: ${slicedBufferString}`); if (!isValidUser) { return { hasError: true, message: 'invalid user' }; } const optLength = dataView.getUint8(17); const command = dataView.getUint8(18 + optLength); if (command !== 1 && command !== 2) { return { hasError: true, message: `command ${command} is not supported, command 01-tcp,02-udp,03-mux` }; } const portIndex = 18 + optLength + 1; const portRemote = dataView.getUint16(portIndex); const addressType = dataView.getUint8(portIndex + 2); let addressValue, addressLength, addressValueIndex; switch (addressType) { case 1: addressLength = 4; addressValueIndex = portIndex + 3; addressValue = new Uint8Array(protocolBuffer.slice(addressValueIndex, addressValueIndex + addressLength)).join('.'); break; case 2: addressLength = dataView.getUint8(portIndex + 3); addressValueIndex = portIndex + 4; addressValue = new TextDecoder().decode(protocolBuffer.slice(addressValueIndex, addressValueIndex + addressLength)); break; case 3: addressLength = 16; addressValueIndex = portIndex + 3; addressValue = Array.from({ length: 8 }, (_, i) => dataView.getUint16(addressValueIndex + i * 2).toString(16)).join(':'); break; default: return { hasError: true, message: `invalid addressType: ${addressType}` }; } if (!addressValue) { return { hasError: true, message: `addressValue is empty, addressType is ${addressType}` }; } return { hasError: false, addressRemote: addressValue, addressType, portRemote, rawDataIndex: addressValueIndex + addressLength, protocolVersion: new Uint8Array([version]), isUDP: command === 2 }; } /** * Converts a remote socket to a WebSocket connection. * @param {import("@cloudflare/workers-types").Socket} remoteSocket The remote socket to convert. * @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket to connect to. * @param {ArrayBuffer | null} protocolResponseHeader The protocol response header. * @param {(() => Promise) | null} retry The function to retry the connection if it fails. * @param {(info: string) => void} log The logging function. * @returns {Promise} A Promise that resolves when the conversion is complete. */ async function remoteSocketToWS(remoteSocket, webSocket, protocolResponseHeader, retry, log) { let hasIncomingData = false; try { await remoteSocket.readable.pipeTo( new WritableStream({ async write(chunk) { if (webSocket.readyState !== WS_READY_STATE_OPEN) { throw new Error('WebSocket is not open'); } hasIncomingData = true; if (protocolResponseHeader) { webSocket.send(await new Blob([protocolResponseHeader, chunk]).arrayBuffer()); protocolResponseHeader = null; } else { webSocket.send(chunk); } }, close() { log(`Remote connection readable closed. Had incoming data: ${hasIncomingData}`); }, abort(reason) { console.error(`Remote connection readable aborted:`, reason); }, }) ); } catch (error) { console.error(`remoteSocketToWS error:`, error.stack || error); safeCloseWebSocket(webSocket); } if (!hasIncomingData && retry) { log(`No incoming data, retrying`); await retry(); } /** } * Decodes a base64 string into an ArrayBuffer. * @param {string} base64Str The base64 string to decode. * @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. */ function base64ToArrayBuffer(base64Str) { if (!base64Str) { return { earlyData: null, error: null }; } try { // Convert modified Base64 for URL (RFC 4648) to standard Base64 base64Str = base64Str.replace(/-/g, '+').replace(/_/g, '/'); // Decode Base64 string const binaryStr = atob(base64Str); // Convert binary string to ArrayBuffer const buffer = new ArrayBuffer(binaryStr.length); const view = new Uint8Array(buffer); for (let i = 0; i < binaryStr.length; i++) { view[i] = binaryStr.charCodeAt(i); } return { earlyData: buffer, error: null }; } catch (error) { return { earlyData: null, error }; } } /** * Checks if a given string is a valid UUID. * @param {string} uuid The string to validate as a UUID. * @returns {boolean} True if the string is a valid UUID, false otherwise. */ function isValidUUID(uuid) { // More precise UUID regex pattern const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; return uuidRegex.test(uuid); } const WS_READY_STATE_OPEN = 1; const WS_READY_STATE_CLOSING = 2; /** * Closes a WebSocket connection safely without throwing exceptions. * @param {import("@cloudflare/workers-types").WebSocket} socket The WebSocket connection to close. */ function safeCloseWebSocket(socket) { try { if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) { socket.close(); } } catch (error) { console.error('safeCloseWebSocket error:', error); } } const byteToHex = Array.from({ length: 256 }, (_, i) => (i + 0x100).toString(16).slice(1)); function unsafeStringify(arr, offset = 0) { return [ byteToHex[arr[offset]], 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]] ].join('').toLowerCase(); } function stringify(arr, offset = 0) { const uuid = unsafeStringify(arr, offset); if (!isValidUUID(uuid)) { throw new TypeError("Stringified UUID is invalid"); } return uuid; } /** * Handles outbound UDP traffic by transforming the data into DNS queries and sending them over a WebSocket connection. * @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket connection to send the DNS queries over. * @param {ArrayBuffer} protocolResponseHeader The protocol response header. * @param {(string) => void} log The logging function. * @returns {{write: (chunk: Uint8Array) => void}} An object with a write method that accepts a Uint8Array chunk to write to the transform stream. */ async function handleUDPOutBound(webSocket, protocolResponseHeader, log) { let isprotocolHeaderSent = false; const transformStream = new TransformStream({ start(_controller) { }, transform(chunk, controller) { // udp message 2 byte is the the length of udp data // TODO: this should have bug, beacsue maybe udp chunk can be in two websocket message for (let index = 0; index < chunk.byteLength;) { const lengthBuffer = chunk.slice(index, index + 2); const udpPakcetLength = new DataView(lengthBuffer).getUint16(0); const udpData = new Uint8Array( chunk.slice(index + 2, index + 2 + udpPakcetLength) ); index = index + 2 + udpPakcetLength; controller.enqueue(udpData); } }, flush(_controller) { } }); // only handle dns udp for now transformStream.readable.pipeTo(new WritableStream({ async write(chunk) { const resp = await fetch(dohURL, // dns server url { method: 'POST', headers: { 'content-type': 'application/dns-message', }, body: chunk, }) const dnsQueryResult = await resp.arrayBuffer(); const udpSize = dnsQueryResult.byteLength; // console.log([...new Uint8Array(dnsQueryResult)].map((x) => x.toString(16))); const udpSizeBuffer = new Uint8Array([(udpSize >> 8) & 0xff, udpSize & 0xff]); if (webSocket.readyState === WS_READY_STATE_OPEN) { log(`doh success and dns message length is ${udpSize}`); if (isprotocolHeaderSent) { webSocket.send(await new Blob([udpSizeBuffer, dnsQueryResult]).arrayBuffer()); } else { webSocket.send(await new Blob([protocolResponseHeader, udpSizeBuffer, dnsQueryResult]).arrayBuffer()); isprotocolHeaderSent = true; } } } })).catch((error) => { log('dns udp has error' + error) }); const writer = transformStream.writable.getWriter(); return { /** * * @param {Uint8Array} chunk */ write(chunk) { writer.write(chunk); } }; } /** * * @param {ArrayBuffer} udpChunk * @param {import("@cloudflare/workers-types").WebSocket} webSocket * @param {ArrayBuffer} protocolResponseHeader * @param {(string)=> void} log */ async function handleDNSQuery(udpChunk, webSocket, protocolResponseHeader, log) { // no matter which DNS server client send, we alwasy use hard code one. // beacsue someof DNS server is not support DNS over TCP try { const dnsServer = '8.8.4.4'; // change to 1.1.1.1 after cf fix connect own ip bug const dnsPort = 53; /** @type {ArrayBuffer | null} */ let vlessHeader = protocolResponseHeader; /** @type {import("@cloudflare/workers-types").Socket} */ const tcpSocket = connect({ hostname: dnsServer, port: dnsPort, }); log(`connected to ${dnsServer}:${dnsPort}`); const writer = tcpSocket.writable.getWriter(); await writer.write(udpChunk); writer.releaseLock(); await tcpSocket.readable.pipeTo(new WritableStream({ async write(chunk) { if (webSocket.readyState === WS_READY_STATE_OPEN) { if (vlessHeader) { webSocket.send(await new Blob([vlessHeader, chunk]).arrayBuffer()); vlessHeader = null; } else { webSocket.send(chunk); } } }, close() { log(`dns server(${dnsServer}) tcp is close`); }, abort(reason) { console.error(`dns server(${dnsServer}) tcp is abort`, reason); }, })); } catch (error) { console.error( `handleDNSQuery have exception, error: ${error.message}` ); } } /** * * @param {number} addressType * @param {string} addressRemote * @param {number} portRemote * @param {function} log The logging function. */ async function socks5Connect(addressType, addressRemote, portRemote, log) { const { username, password, hostname, port } = parsedSocks5Address; // Connect to the SOCKS server const socket = connect({ hostname, port, }); // Request head format (Worker -> Socks Server): // +----+----------+----------+ // |VER | NMETHODS | METHODS | // +----+----------+----------+ // | 1 | 1 | 1 to 255 | // +----+----------+----------+ // https://en.wikipedia.org/wiki/SOCKS#SOCKS5 // For METHODS: // 0x00 NO AUTHENTICATION REQUIRED // 0x02 USERNAME/PASSWORD https://datatracker.ietf.org/doc/html/rfc1929 const socksGreeting = new Uint8Array([5, 2, 0, 2]); const writer = socket.writable.getWriter(); await writer.write(socksGreeting); log('sent socks greeting'); const reader = socket.readable.getReader(); const encoder = new TextEncoder(); let res = (await reader.read()).value; // Response format (Socks Server -> Worker): // +----+--------+ // |VER | METHOD | // +----+--------+ // | 1 | 1 | // +----+--------+ if (res[0] !== 0x05) { log(`socks server version error: ${res[0]} expected: 5`); return; } if (res[1] === 0xff) { log("no acceptable methods"); return; } // if return 0x0502 if (res[1] === 0x02) { log("socks server needs auth"); if (!username || !password) { log("please provide username/password"); return; } // +----+------+----------+------+----------+ // |VER | ULEN | UNAME | PLEN | PASSWD | // +----+------+----------+------+----------+ // | 1 | 1 | 1 to 255 | 1 | 1 to 255 | // +----+------+----------+------+----------+ const authRequest = new Uint8Array([ 1, username.length, ...encoder.encode(username), password.length, ...encoder.encode(password) ]); await writer.write(authRequest); res = (await reader.read()).value; // expected 0x0100 if (res[0] !== 0x01 || res[1] !== 0x00) { log("fail to auth socks server"); return; } } // Request data format (Worker -> Socks Server): // +----+-----+-------+------+----------+----------+ // |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT | // +----+-----+-------+------+----------+----------+ // | 1 | 1 | X'00' | 1 | Variable | 2 | // +----+-----+-------+------+----------+----------+ // ATYP: address type of following address // 0x01: IPv4 address // 0x03: Domain name // 0x04: IPv6 address // DST.ADDR: desired destination address // DST.PORT: desired destination port in network octet order // addressType // 1--> ipv4 addressLength =4 // 2--> domain name // 3--> ipv6 addressLength =16 let DSTADDR; // DSTADDR = ATYP + DST.ADDR switch (addressType) { case 1: DSTADDR = new Uint8Array( [1, ...addressRemote.split('.').map(Number)] ); break; case 2: DSTADDR = new Uint8Array( [3, addressRemote.length, ...encoder.encode(addressRemote)] ); break; case 3: DSTADDR = new Uint8Array( [4, ...addressRemote.split(':').flatMap(x => [parseInt(x.slice(0, 2), 16), parseInt(x.slice(2), 16)])] ); break; default: log(`invild addressType is ${addressType}`); return; } const socksRequest = new Uint8Array([5, 1, 0, ...DSTADDR, portRemote >> 8, portRemote & 0xff]); await writer.write(socksRequest); log('sent socks request'); res = (await reader.read()).value; // Response format (Socks Server -> Worker): // +----+-----+-------+------+----------+----------+ // |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT | // +----+-----+-------+------+----------+----------+ // | 1 | 1 | X'00' | 1 | Variable | 2 | // +----+-----+-------+------+----------+----------+ if (res[1] === 0x00) { log("socks connection opened"); } else { log("fail to open socks connection"); return; } writer.releaseLock(); reader.releaseLock(); return socket; } /** * * @param {string} address */ function socks5AddressParser(address) { let [latter, former] = address.split("@").reverse(); let username, password, hostname, port; if (former) { const formers = former.split(":"); if (formers.length !== 2) { throw new Error('Invalid SOCKS address format'); } [username, password] = formers; } const latters = latter.split(":"); port = Number(latters.pop()); if (isNaN(port)) { throw new Error('Invalid SOCKS address format'); } hostname = latters.join(":"); const regex = /^\[.*\]$/; if (hostname.includes(":") && !regex.test(hostname)) { throw new Error('Invalid SOCKS address format'); } return { username, password, hostname, port, } } async function parseTrojanHeader(buffer) { if (buffer.byteLength < 58) { return { hasError: true, message: "Invalid data length" }; } const view = new DataView(buffer); if (view.getUint8(56) !== 0x0d || view.getUint8(57) !== 0x0a) { return { hasError: true, message: "Invalid header format (missing CR LF)" }; } const password = new TextDecoder().decode(buffer.slice(0, 56)); if (password !== Sha256.sha224(userID)) { return { hasError: true, message: "Invalid password" }; } const socks5Data = new DataView(buffer, 58); if (socks5Data.byteLength < 6) { return { hasError: true, message: "Invalid SOCKS5 request data" }; } if (socks5Data.getUint8(0) !== 1) { return { hasError: true, message: "Unsupported command, only TCP (CONNECT) is allowed" }; } const atype = socks5Data.getUint8(1); let address; let addressEnd; switch (atype) { case 1: // IPv4 address = Array.from(new Uint8Array(socks5Data.buffer, socks5Data.byteOffset + 2, 4)).join('.'); addressEnd = 6; break; case 3: // Domain name const domainLength = socks5Data.getUint8(2); address = new TextDecoder().decode(socks5Data.buffer.slice(socks5Data.byteOffset + 3, socks5Data.byteOffset + 3 + domainLength)); addressEnd = 3 + domainLength; break; case 4: // IPv6 address = Array.from(new Uint8Array(socks5Data.buffer, socks5Data.byteOffset + 2, 16)) .map(x => x.toString(16).padStart(2, '0')) .join(':') .replace(/(:0)+:/, '::'); addressEnd = 18; break; default: return { hasError: true, message: `Invalid address type: ${atype}` }; } const port = socks5Data.getUint16(addressEnd); return { hasError: false, address, port, data: buffer.slice(58 + addressEnd + 2) }; } const VlessCmd = { TCP: 1, UDP: 2, MUX: 3, }; const VlessAddrType = { IPv4: 1, // 4-bytes DomainName: 2, // The first byte indicates the length of the following domain name IPv6: 3, // 16-bytes }; /** * Generate a vless request header. * @param {number} command - The command to execute (see VlessCmd). * @param {number} destType - The type of destination address (see VlessAddrType). * @param {string} destAddr - The destination address. * @param {number} destPort - The destination port. * @param {string} uuid - The UUID of the request. * @returns {Uint8Array} - The vless request header as a Uint8Array. * @throws {Error} - If the address type is unknown. */ function makeVlessReqHeader(command, destType, destAddr, destPort, uuid) { /** @type {number} */ let addressFieldLength; /** @type {Uint8Array | undefined} */ let addressEncoded; switch (destType) { case VlessAddrType.IPv4: addressFieldLength = 4; break; case VlessAddrType.DomainName: addressEncoded = new TextEncoder().encode(destAddr); addressFieldLength = addressEncoded.length + 1; break; case VlessAddrType.IPv6: addressFieldLength = 16; break; default: throw new Error(`Unknown address type: ${destType}`); } const uuidString = uuid.replace(/-/g, ''); const uuidOffset = 1; const vlessHeader = new Uint8Array(22 + addressFieldLength); // Protocol Version = 0 vlessHeader[0] = 0x00; for (let i = 0; i < uuidString.length; i += 2) { vlessHeader[uuidOffset + i / 2] = parseInt(uuidString.substr(i, 2), 16); } // Additional Information Length M = 0 vlessHeader[17] = 0x00; // Instruction vlessHeader[18] = command; // Port, 2-byte big-endian vlessHeader[19] = destPort >> 8; vlessHeader[20] = destPort & 0xFF; // Address Type // 1--> ipv4 addressLength =4 // 2--> domain name addressLength=addressBuffer[1] // 3--> ipv6 addressLength =16 vlessHeader[21] = destType; // Address switch (destType) { case VlessAddrType.IPv4: const octetsIPv4 = destAddr.split('.'); for (let i = 0; i < 4; i++) { vlessHeader[22 + i] = parseInt(octetsIPv4[i]); } break; case VlessAddrType.DomainName: vlessHeader[22] = addressEncoded.length; vlessHeader.set(addressEncoded, 23); break; case VlessAddrType.IPv6: const groupsIPv6 = ipv6.split(':'); for (let i = 0; i < 8; i++) { const hexGroup = parseInt(groupsIPv6[i], 16); vlessHeader[i * 2 + 22] = hexGroup >> 8; vlessHeader[i * 2 + 23] = hexGroup & 0xFF; } break; default: throw new Error(`Unknown address type: ${destType}`); } return vlessHeader; } /** * Checks if the provided VLESS configuration is valid for the given address and stream settings. * @param {string} address - The address to check against. * @param {Object} streamSettings - The stream settings to check. * @throws {Error} If the outbound stream method is not 'ws'. * @throws {Error} If the security layer is not 'none' or 'tls'. * @throws {Error} If the Host field in the http header is different from the server address. * @throws {Error} If the SNI is different from the server address. */ function checkVlessConfig(address, streamSettings) { if (streamSettings.network !== 'ws') { throw new Error(`Unsupported outbound stream method: ${streamSettings.network}, has to be ws (Websocket)`); } if (streamSettings.security !== 'tls' && streamSettings.security !== 'none') { throw new Error(`Usupported security layer: ${streamSettings.network}, has to be none or tls.`); } if (streamSettings.wsSettings && streamSettings.wsSettings.headers && streamSettings.wsSettings.headers.Host !== address) { throw new Error(`The Host field in the http header is different from the server address, this is unsupported due to Cloudflare API restrictions`); } if (streamSettings.tlsSettings && streamSettings.tlsSettings.serverName !== address) { throw new Error(`The SNI is different from the server address, this is unsupported due to Cloudflare API restrictions`); } } /** * Parses a VLESS URL string into its components. * @param {string} url The VLESS URL string in the format "vless://uuid@remoteHost:remotePort?queryParams#descriptiveText". * @returns {{ * protocol: string, * uuid: string, * remoteHost: string, * remotePort: number, * descriptiveText: string, * queryParams: Object * }} An object containing the parsed components of the VLESS URL string. * @throws {Error} If the URL string is in an invalid format. */ function parseVlessString(url) { const regex = /^(.+):\/\/(.+?)@(.+?):(\d+)(\?[^#]*)?(#.*)?$/; const match = url.match(regex); if (!match) { throw new Error('Invalid URL format'); } const [, protocol, uuid, remoteHost, remotePort, query, descriptiveText] = match; const json = { protocol, uuid, remoteHost, remotePort: parseInt(remotePort), descriptiveText: descriptiveText ? descriptiveText.substring(1) : '', queryParams: {} }; if (query) { const queryFields = query.substring(1).split('&'); queryFields.forEach(field => { const [key, value] = field.split('='); json.queryParams[key] = value; }); } return json; } const at = 'QA=='; const pt = 'dmxlc3M='; const ed = 'RUR0dW5uZWw='; /** * * @param {string} userID - single or comma separated userIDs * @param {string | null} hostName * @returns {string} */ function getConfig(userIDs, hostName) { const commonUrlPart = `?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2048#${hostName}`; // Split the userIDs into an array const userIDArray = userIDs.split(","); // Prepare output string for each userID const sublink = `https://${hostName}/sub/${userIDArray[0]}?format=clash` const subbestip = `https://${hostName}/bestip/${userIDArray[0]}`; const clash_link = `https://url.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`; // HTML Head with CSS and FontAwesome library const htmlHead = ` EDtunnel: Configuration `; const header = `

EDtunnel: Protocol Configuration

Welcome! This function generates configuration for the vless protocol. If you found this useful, please check our GitHub project:

EDtunnel - https://github.com/6Kmfi6HP/EDtunnel

Options Explained:

  • VLESS Subscription: Direct link for VLESS protocol configuration. Suitable for clients supporting VLESS.
  • Clash Subscription: Opens the Clash client with pre-configured settings. Best for Clash users on mobile devices.
  • Clash Link: A web link to convert the VLESS config to Clash format. Useful for manual import or troubleshooting.
  • Best IP Subscription: Provides a curated list of optimal server IPs for many different countries.

Choose the option that best fits your client and needs. For most users, the VLESS or Clash Subscription will be the easiest to use.

`; const configOutput = userIDArray.map((userID) => { const protocolMain = atob(pt) + '://' + userID + atob(at) + hostName + ":443" + commonUrlPart; const protocolSec = atob(pt) + '://' + userID + atob(at) + proxyIP + ":" + proxyPort + commonUrlPart; return `

UUID: ${userID}

Default IP Configuration

${protocolMain}

Best IP Configuration

${protocolSec}
`; }).join(''); return ` ${htmlHead} ${header} ${configOutput} `; } const HttpPort = new Set([80, 8080, 8880, 2052, 2086, 2095, 2082]); const HttpsPort = new Set([443, 8443, 2053, 2096, 2087, 2083]); function GenSub(userID_path, hostname) { const userIDArray = userID_path.includes(',') ? userID_path.split(',') : [userID_path]; const randomPath = () => '/' + Math.random().toString(36).substring(2, 15) + '?ed=2048'; const commonUrlPartHttp = `?encryption=none&security=none&fp=random&type=ws&host=${hostname}&path=${encodeURIComponent(randomPath())}#`; const commonUrlPartHttps = `?encryption=none&security=tls&sni=${hostname}&fp=random&type=ws&host=${hostname}&path=%2F%3Fed%3D2048#`; const result = userIDArray.flatMap((userID) => { const PartHttp = Array.from(HttpPort).flatMap((port) => { if (!hostname.includes('pages.dev')) { const urlPart = `${hostname}-HTTP-${port}`; const mainProtocolHttp = atob(pt) + '://' + userID + atob(at) + hostname + ':' + port + commonUrlPartHttp + urlPart; return proxyIPs.flatMap((proxyIP) => { const secondaryProtocolHttp = atob(pt) + '://' + userID + atob(at) + proxyIP.split(':')[0] + ':' + proxyPort + commonUrlPartHttp + urlPart + '-' + proxyIP + '-' + atob(ed); return [mainProtocolHttp, secondaryProtocolHttp]; }); } return []; }); const PartHttps = Array.from(HttpsPort).flatMap((port) => { const urlPart = `${hostname}-HTTPS-${port}`; const mainProtocolHttps = atob(pt) + '://' + userID + atob(at) + hostname + ':' + port + commonUrlPartHttps + urlPart; return proxyIPs.flatMap((proxyIP) => { const secondaryProtocolHttps = atob(pt) + '://' + userID + atob(at) + proxyIP.split(':')[0] + ':' + proxyPort + commonUrlPartHttps + urlPart + '-' + proxyIP + '-' + atob(ed); return [mainProtocolHttps, secondaryProtocolHttps]; }); }); return [...PartHttp, ...PartHttps]; }); return result.join('\n'); } const hostnames = [ 'weibo.com', // Weibo - A popular social media platform 'www.baidu.com', // Baidu - The largest search engine in China 'www.qq.com', // QQ - A widely used instant messaging platform 'www.taobao.com', // Taobao - An e-commerce website owned by Alibaba Group 'www.jd.com', // JD.com - One of the largest online retailers in China 'www.sina.com.cn', // Sina - A Chinese online media company 'www.sohu.com', // Sohu - A Chinese internet service provider 'www.tmall.com', // Tmall - An online retail platform owned by Alibaba Group 'www.163.com', // NetEase Mail - One of the major email providers in China 'www.zhihu.com', // Zhihu - A popular question-and-answer website 'www.youku.com', // Youku - A Chinese video sharing platform 'www.xinhuanet.com', // Xinhua News Agency - Official news agency of China 'www.douban.com', // Douban - A Chinese social networking service 'www.meituan.com', // Meituan - A Chinese group buying website for local services 'www.toutiao.com', // Toutiao - A news and information content platform 'www.ifeng.com', // iFeng - A popular news website in China 'www.autohome.com.cn', // Autohome - A leading Chinese automobile online platform 'www.360.cn', // 360 - A Chinese internet security company 'www.douyin.com', // Douyin - A Chinese short video platform 'www.kuaidi100.com', // Kuaidi100 - A Chinese express delivery tracking service 'www.wechat.com', // WeChat - A popular messaging and social media app 'www.csdn.net', // CSDN - A Chinese technology community website 'www.imgo.tv', // ImgoTV - A Chinese live streaming platform 'www.aliyun.com', // Alibaba Cloud - A Chinese cloud computing company 'www.eyny.com', // Eyny - A Chinese multimedia resource-sharing website 'www.mgtv.com', // MGTV - A Chinese online video platform 'www.xunlei.com', // Xunlei - A Chinese download manager and torrent client 'www.hao123.com', // Hao123 - A Chinese web directory service 'www.bilibili.com', // Bilibili - A Chinese video sharing and streaming platform 'www.youth.cn', // Youth.cn - A China Youth Daily news portal 'www.hupu.com', // Hupu - A Chinese sports community and forum 'www.youzu.com', // Youzu Interactive - A Chinese game developer and publisher 'www.panda.tv', // Panda TV - A Chinese live streaming platform 'www.tudou.com', // Tudou - A Chinese video-sharing website 'www.zol.com.cn', // ZOL - A Chinese electronics and gadgets website 'www.toutiao.io', // Toutiao - A news and information app 'www.tiktok.com', // TikTok - A Chinese short-form video app 'www.netease.com', // NetEase - A Chinese internet technology company 'www.cnki.net', // CNKI - China National Knowledge Infrastructure, an information aggregator 'www.zhibo8.cc', // Zhibo8 - A website providing live sports streams 'www.zhangzishi.cc', // Zhangzishi - Personal website of Zhang Zishi, a public intellectual in China 'www.xueqiu.com', // Xueqiu - A Chinese online social platform for investors and traders 'www.qqgongyi.com', // QQ Gongyi - Tencent's charitable foundation platform 'www.ximalaya.com', // Ximalaya - A Chinese online audio platform 'www.dianping.com', // Dianping - A Chinese online platform for finding and reviewing local businesses 'www.suning.com', // Suning - A leading Chinese online retailer 'www.zhaopin.com', // Zhaopin - A Chinese job recruitment platform 'www.jianshu.com', // Jianshu - A Chinese online writing platform 'www.mafengwo.cn', // Mafengwo - A Chinese travel information sharing platform 'www.51cto.com', // 51CTO - A Chinese IT technical community website 'www.qidian.com', // Qidian - A Chinese web novel platform 'www.ctrip.com', // Ctrip - A Chinese travel services provider 'www.pconline.com.cn', // PConline - A Chinese technology news and review website 'www.cnzz.com', // CNZZ - A Chinese web analytics service provider 'www.telegraph.co.uk', // The Telegraph - A British newspaper website 'www.ynet.com', // Ynet - A Chinese news portal 'www.ted.com', // TED - A platform for ideas worth spreading 'www.renren.com', // Renren - A Chinese social networking service 'www.pptv.com', // PPTV - A Chinese online video streaming platform 'www.liepin.com', // Liepin - A Chinese online recruitment website 'www.881903.com', // 881903 - A Hong Kong radio station website 'www.aipai.com', // Aipai - A Chinese online video sharing platform 'www.ttpaihang.com', // Ttpaihang - A Chinese celebrity popularity ranking website 'www.quyaoya.com', // Quyaoya - A Chinese online ticketing platform 'www.91.com', // 91.com - A Chinese software download website 'www.dianyou.cn', // Dianyou - A Chinese game information website 'www.tmtpost.com', // TMTPost - A Chinese technology media platform 'www.douban.com', // Douban - A Chinese social networking service 'www.guancha.cn', // Guancha - A Chinese news and commentary website 'www.so.com', // So.com - A Chinese search engine 'www.58.com', // 58.com - A Chinese classified advertising website 'www.cnblogs.com', // Cnblogs - A Chinese technology blog community 'www.cntv.cn', // CCTV - China Central Television official website 'www.secoo.com', // Secoo - A Chinese luxury e-commerce platform ];