[
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Cloudflare 上建 workers 和 pages 节点及自动化优选 IP 的一揽子工具\n\n优选工具使用 CloudflareSpeedTest，用法如下：\n\n```cvs\n\n\n参数：\n    -n 200\n        延迟测速线程；越多延迟测速越快，性能弱的设备 (如路由器) 请勿太高；(默认 200 最多 1000)\n    -t 4\n        延迟测速次数；单个 IP 延迟测速的次数；(默认 4 次)\n    -dn 10\n        下载测速数量；延迟测速并排序后，从最低延迟起下载测速的数量；(默认 10 个)\n    -dt 10\n        下载测速时间；单个 IP 下载测速最长时间，不能太短；(默认 10 秒)\n    -tp 443\n        指定测速端口；延迟测速/下载测速时使用的端口；(默认 443 端口)\n    -url https://cf.xiu2.xyz/url\n        指定测速地址；延迟测速(HTTPing)/下载测速时使用的地址，默认地址不保证可用性，建议自建；\n\n    -httping\n        切换测速模式；延迟测速模式改为 HTTP 协议，所用测试地址为 [-url] 参数；(默认 TCPing)\n        注意：HTTPing 本质上也算一种 网络扫描 行为，因此如果你在服务器上面运行，需要降低并发(-n)，否则可能会被一些严格的商家暂停服务。\n        如果你遇到 HTTPing 首次测速可用 IP 数量正常，后续测速越来越少甚至直接为 0，但停一段时间后又恢复了的情况，那么也可能是被 运营商、Cloudflare CDN 认为你在网络扫描而 触发临时限制机制，因此才会过一会儿就恢复了，建议降低并发(-n)减少这种情况的发生。\n    -httping-code 200\n        有效状态代码；HTTPing 延迟测速时网页返回的有效 HTTP 状态码，仅限一个；(默认 200 301 302)\n    -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD\n        匹配指定地区；地区名为当地机场三字码，英文逗号分隔，支持小写，支持 Cloudflare、AWS CloudFront，仅 HTTPing 模式可用；(默认 所有地区)\n\n    -tl 200\n        平均延迟上限；只输出低于指定平均延迟的 IP，各上下限条件可搭配使用；(默认 9999 ms)\n    -tll 40\n        平均延迟下限；只输出高于指定平均延迟的 IP；(默认 0 ms)\n    -tlr 0.2\n        丢包几率上限；只输出低于/等于指定丢包率的 IP，范围 0.00~1.00，0 过滤掉任何丢包的 IP；(默认 1.00)\n    -sl 5\n        下载速度下限；只输出高于指定下载速度的 IP，凑够指定数量 [-dn] 才会停止测速；(默认 0.00 MB/s)\n\n    -p 10\n        显示结果数量；测速后直接显示指定数量的结果，为 0 时不显示结果直接退出；(默认 10 个)\n    -f ip.txt\n        IP段数据文件；如路径含有空格请加上引号；支持其他 CDN IP段；(默认 ip.txt)\n    -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32\n        指定IP段数据；直接通过参数指定要测速的 IP 段数据，英文逗号分隔；(默认 空)\n    -o result.csv\n        写入结果文件；如路径含有空格请加上引号；值为空时不写入文件 [-o \"\"]；(默认 result.csv)\n\n    -dd\n        禁用下载测速；禁用后测速结果会按延迟排序 (默认按下载速度排序)；(默认 启用)\n    -allip\n        测速全部的IP；对 IP 段中的每个 IP (仅支持 IPv4) 进行测速；(默认 每个 /24 段随机测速一个 IP)\n\n    -c\n        按国家代码分类输出文件\n    -cc\n        指定国家代码选择IP，仅支持 IPv4；(默认 所有国家)\n    -v\n        打印程序版本 + 检查版本更新\n    -h\n        打印帮助说明\n```\n\n## workers 变量说明\n\n| 变量           | 是否必须 | 例子                                                                                                                                                                          | 说明                  |\n| -------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |\n| `UUID`         | No       | `12345678-1234-1234-1234-123456789012`                                                                                                                                        | 唯一标识              |\n| `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 格式          |\n| `SOCKS5`       | No       | `1.1.1.1:1080` or `user:pass@host:port`                                                                                                                                       | SOCKS5 代理           |\n| `SOCKS5_RELAY` | No       | `true` or `false`                                                                                                                                                             | true 时所有流量走代理 |\n\n## 鸣谢\n\n[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)   \n\n\n## License\n\nThe GPL-3.0 License.\n"
  },
  {
    "path": "cf_speedtest.js",
    "content": "export default {\n  async fetch(request) {\n    const url = new URL(request.url);\n    const path = url.pathname.substring(1);\n\n    let bytes = 100000000; // Default 100MB\n    if (path) {\n      const match = path.match(/^(\\d+)([a-z]{0,2})$/i);\n      if (!match) {\n        return new Response(\"路径格式不正确\", { status: 400 });\n      }\n\n      const size = parseInt(match[1], 10);\n      const unit = match[2].toLowerCase();\n      const multipliers = {\n        'k': 1000, 'kb': 1000,\n        'm': 1000000, 'mb': 1000000,\n        'g': 1000000000, 'gb': 1000000000\n      };\n      bytes = size * (multipliers[unit] || 1);\n    }\n\n    const targetUrl = `https://speed.cloudflare.com/__down?bytes=${bytes}`;\n    const headers = new Headers(request.headers);\n    headers.set('referer', 'https://speed.cloudflare.com/');\n\n    return fetch(new Request(targetUrl, {\n      method: request.method,\n      headers: headers,\n      body: request.body\n    }));\n  }\n};\n\n\n"
  },
  {
    "path": "go.mod",
    "content": "module github.com/XIU2/CloudflareSpeedTest\n\ngo 1.14\n\nrequire (\n\tgithub.com/VividCortex/ewma v1.1.1\n\tgithub.com/cheggaaa/pb/v3 v3.0.4\n\tgithub.com/oschwald/maxminddb-golang v1.12.0\n\tgolang.org/x/text v0.14.0\n)\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/VividCortex/ewma v1.1.1 h1:MnEK4VOv6n0RSY4vtRe3h11qjxL3+t0B8yOL8iMXdcM=\ngithub.com/VividCortex/ewma v1.1.1/go.mod h1:2Tkkvm3sRDVXaiyucHiACn4cqf7DpdyLvmxzcbUokwA=\ngithub.com/cheggaaa/pb/v3 v3.0.4 h1:QZEPYOj2ix6d5oEg63fbHmpolrnNiwjUsk+h74Yt4bM=\ngithub.com/cheggaaa/pb/v3 v3.0.4/go.mod h1:7rgWxLrAUcFMkvJuv09+DYi7mMUYi8nO9iOWcvGJPfw=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys=\ngithub.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=\ngithub.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU=\ngithub.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=\ngithub.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=\ngithub.com/mattn/go-isatty v0.0.10 h1:qxFzApOv4WsAL965uUPIsXzAKCZxN2p9UqdhFS4ZW10=\ngithub.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=\ngithub.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54=\ngithub.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=\ngithub.com/oschwald/maxminddb-golang v1.12.0 h1:9FnTOD0YOhP7DGxGsq4glzpGy5+w7pq50AS6wALUMYs=\ngithub.com/oschwald/maxminddb-golang v1.12.0/go.mod h1:q0Nob5lTCqyQ8WT6FYgS1L7PXKVVbgiymefNwIjPzgY=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=\ngithub.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=\ngithub.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=\ngithub.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=\ngithub.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=\ngithub.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=\ngolang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\ngolang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=\ngolang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=\ngolang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=\ngolang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=\ngolang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=\ngolang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=\ngolang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=\ngolang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20191128015809-6d18c012aee9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA=\ngolang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=\ngolang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=\ngolang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=\ngolang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\ngolang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=\ngolang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=\ngolang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=\ngolang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=\ngolang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=\ngolang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=\ngolang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=\ngolang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=\ngolang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=\ngolang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "main.go",
    "content": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com/oschwald/maxminddb-golang\"\n\t\"io/ioutil\"\n\t\"net/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/XIU2/CloudflareSpeedTest/task\"\n\t\"github.com/XIU2/CloudflareSpeedTest/utils\"\n)\n\nvar (\n\tversion, versionNew string\n\tBCountry            bool = false\n\tCountryCodes        string\n\tCountryList         map[string]bool\n)\n\nfunc init() {\n\tvar printVersion bool\n\tvar help = `\nCloudflareSpeedTest ` + version + `\n测试 Cloudflare CDN 所有 IP 的延迟和速度，获取最快 IP (IPv4+IPv6)！\nhttps://github.com/XIU2/CloudflareSpeedTest\n\n参数：\n    -n 200\n        延迟测速线程；越多延迟测速越快，性能弱的设备 (如路由器) 请勿太高；(默认 200 最多 1000)\n    -t 4\n        延迟测速次数；单个 IP 延迟测速的次数；(默认 4 次)\n    -dn 10\n        下载测速数量；延迟测速并排序后，从最低延迟起下载测速的数量；(默认 10 个)\n    -dt 10\n        下载测速时间；单个 IP 下载测速最长时间，不能太短；(默认 10 秒)\n    -tp 443\n        指定测速端口；延迟测速/下载测速时使用的端口；(默认 443 端口)\n    -url https://cf.xiu2.xyz/url\n        指定测速地址；延迟测速(HTTPing)/下载测速时使用的地址，默认地址不保证可用性，建议自建；\n\n    -httping\n        切换测速模式；延迟测速模式改为 HTTP 协议，所用测试地址为 [-url] 参数；(默认 TCPing)\n    -httping-code 200\n        有效状态代码；HTTPing 延迟测速时网页返回的有效 HTTP 状态码，仅限一个；(默认 200 301 302)\n    -cfcolo HKG,KHH,NRT,LAX,SEA,SJC,FRA,MAD\n        匹配指定地区；地区名为当地机场三字码，英文逗号分隔，仅 HTTPing 模式可用；(默认 所有地区)\n\n    -tl 200\n        平均延迟上限；只输出低于指定平均延迟的 IP，各上下限条件可搭配使用；(默认 9999 ms)\n    -tll 40\n        平均延迟下限；只输出高于指定平均延迟的 IP；(默认 0 ms)\n    -tlr 0.2\n        丢包几率上限；只输出低于/等于指定丢包率的 IP，范围 0.00~1.00，0 过滤掉任何丢包的 IP；(默认 1.00)\n    -sl 5\n        下载速度下限；只输出高于指定下载速度的 IP，凑够指定数量 [-dn] 才会停止测速；(默认 0.00 MB/s)\n\n    -p 10\n        显示结果数量；测速后直接显示指定数量的结果，为 0 时不显示结果直接退出；(默认 10 个)\n    -f ip.txt\n        IP段数据文件；如路径含有空格请加上引号；支持其他 CDN IP段；(默认 ip.txt)\n    -ip 1.1.1.1,2.2.2.2/24,2606:4700::/32\n        指定IP段数据；直接通过参数指定要测速的 IP 段数据，英文逗号分隔；(默认 空)\n    -o result.csv\n        写入结果文件；如路径含有空格请加上引号；值为空时不写入文件 [-o \"\"]；(默认 result.csv)\n\n    -dd\n        禁用下载测速；禁用后测速结果会按延迟排序 (默认按下载速度排序)；(默认 启用)\n    -allip\n        测速全部的IP；对 IP 段中的每个 IP (仅支持 IPv4) 进行测速；(默认 每个 /24 段随机测速一个 IP)\n    \n    -c\n        显示国家信息，按国家分类输出并按速度排序。\n    -cc \n \t\t配合-cc使用，指定所需的国家ip，输入国家代码，多个用逗号分隔。如 US,JP\n    -v\n        打印程序版本 + 检查版本更新\n    -h\n        打印帮助说明\n`\n\tvar minDelay, maxDelay, downloadTime int\n\tvar maxLossRate float64\n\tflag.IntVar(&task.Routines, \"n\", 200, \"延迟测速线程\")\n\tflag.IntVar(&task.PingTimes, \"t\", 4, \"延迟测速次数\")\n\tflag.IntVar(&task.TestCount, \"dn\", 10, \"下载测速数量\")\n\tflag.IntVar(&downloadTime, \"dt\", 10, \"下载测速时间\")\n\tflag.IntVar(&task.TCPPort, \"tp\", 443, \"指定测速端口\")\n\tflag.StringVar(&task.URL, \"url\", \"https://cf.xiu2.xyz/url\", \"指定测速地址\")\n\n\tflag.BoolVar(&task.Httping, \"httping\", false, \"切换测速模式\")\n\tflag.IntVar(&task.HttpingStatusCode, \"httping-code\", 0, \"有效状态代码\")\n\tflag.StringVar(&task.HttpingCFColo, \"cfcolo\", \"\", \"匹配指定地区\")\n\n\tflag.IntVar(&maxDelay, \"tl\", 9999, \"平均延迟上限\")\n\tflag.IntVar(&minDelay, \"tll\", 0, \"平均延迟下限\")\n\tflag.Float64Var(&maxLossRate, \"tlr\", 1, \"丢包几率上限\")\n\tflag.Float64Var(&task.MinSpeed, \"sl\", 0, \"下载速度下限\")\n\n\tflag.IntVar(&utils.PrintNum, \"p\", 10, \"显示结果数量\")\n\tflag.StringVar(&task.IPFile, \"f\", \"ip.txt\", \"IP段数据文件\")\n\tflag.StringVar(&task.IPText, \"ip\", \"\", \"指定IP段数据\")\n\tflag.StringVar(&utils.Output, \"o\", \"result.csv\", \"输出结果文件\")\n\tflag.StringVar(&CountryCodes, \"cc\", \"\", \"指定国家代码，多个用逗号分隔\")\n\tflag.BoolVar(&BCountry, \"c\", false, \"按国家代码分类输出文件\")\n\tflag.BoolVar(&task.Disable, \"dd\", false, \"禁用下载测速\")\n\tflag.BoolVar(&task.TestAll, \"allip\", false, \"测速全部 IP\")\n\n\tflag.BoolVar(&printVersion, \"v\", false, \"打印程序版本\")\n\tflag.Usage = func() { fmt.Print(help) }\n\tflag.Parse()\n\n\tif task.MinSpeed > 0 && time.Duration(maxDelay)*time.Millisecond == utils.InputMaxDelay {\n\t\tfmt.Println(\"[小提示] 在使用 [-sl] 参数时，建议搭配 [-tl] 参数，以避免因凑不够 [-dn] 数量而一直测速...\")\n\t}\n\tutils.InputMaxDelay = time.Duration(maxDelay) * time.Millisecond\n\tutils.InputMinDelay = time.Duration(minDelay) * time.Millisecond\n\tutils.InputMaxLossRate = float32(maxLossRate)\n\ttask.Timeout = time.Duration(downloadTime) * time.Second\n\ttask.HttpingCFColomap = task.MapColoMap()\n\n\tif printVersion {\n\t\tprintln(version)\n\t\tfmt.Println(\"检查版本更新中...\")\n\t\tcheckUpdate()\n\t\tif versionNew != \"\" {\n\t\t\tfmt.Printf(\"*** 发现新版本 [%s]！请前往 [https://github.com/XIU2/CloudflareSpeedTest] 更新！ ***\", versionNew)\n\t\t} else {\n\t\t\tfmt.Println(\"当前为最新版本 [\" + version + \"]！\")\n\t\t}\n\t\tos.Exit(0)\n\t}\n}\n\nfunc main() {\n\ttask.InitRandSeed() // 置随机数种子\n\n\tif BCountry {\n\t\tfmt.Println(\"分国家测速模式\")\n\t\tif CountryCodes != \"\" {\n\t\t\tcodes := strings.Split(CountryCodes, \",\")\n\t\t\tif len(codes) > 0 {\n\t\t\t\tCountryList = make(map[string]bool)\n\t\t\t\tfor _, code := range codes {\n\t\t\t\t\tCountryList[code] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"# XIU2/CloudflareSpeedTest %s \\n\\n\", version)\n\n\t// 开始延迟测速 + 过滤延迟/丢包\n\tpingData := task.NewPing().Run().FilterDelay().FilterLossRate()\n\tif BCountry {\n\t\tdb, err := maxminddb.Open(\"Country.mmdb\")\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn\n\t\t}\n\t\tcountryinfo := utils.NewCountryInfo(db)\n\t\tCountrypingData := pingData.FilterCountryV2(countryinfo, CountryList)\n\t\tcountryinfo.Done()\n\t\tif CountrypingData == nil {\n\t\t\treturn\n\t\t}\n\t\t//按国家代号排序,每个国家按延迟从小到大排序\n\t\tsort.Slice(CountrypingData, func(i, j int) bool {\n\t\t\tleft := CountrypingData[i].Country + fmt.Sprintf(\"%d\", CountrypingData[i].Delay)\n\t\t\tright := CountrypingData[j].Country + fmt.Sprintf(\"%d\", CountrypingData[j].Delay)\n\t\t\treturn left < right\n\t\t})\n\t\tspeedData := task.TestDownloadSpeedByCountry(CountrypingData)\n\t\tutils.ExportCsvByCountry(speedData)\n\t} else {\n\t\t// 开始下载测速\n\t\tspeedData := task.TestDownloadSpeed(pingData)\n\t\tutils.ExportCsv(speedData) // 输出文件\n\t\tspeedData.Print()          // 打印结果\n\t}\n\n\tif versionNew != \"\" {\n\t\tfmt.Printf(\"\\n*** 发现新版本 [%s]！请前往 [https://github.com/XIU2/CloudflareSpeedTest] 更新！ ***\\n\", versionNew)\n\t}\n\tendPrint()\n}\n\nfunc endPrint() {\n\tif utils.NoPrintResult() {\n\t\treturn\n\t}\n\tif runtime.GOOS == \"windows\" { // 如果是 Windows 系统，则需要按下 回车键 或 Ctrl+C 退出（避免通过双击运行时，测速完毕后直接关闭）\n\t\tfmt.Printf(\"按下 回车键 或 Ctrl+C 退出。\")\n\t\tfmt.Scanln()\n\t}\n}\n\n// 检查更新\nfunc checkUpdate() {\n\ttimeout := 10 * time.Second\n\tclient := http.Client{Timeout: timeout}\n\tres, err := client.Get(\"https://api.xiu2.xyz/ver/cloudflarespeedtest.txt\")\n\tif err != nil {\n\t\treturn\n\t}\n\t// 读取资源数据 body: []byte\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\t// 关闭资源流\n\tdefer res.Body.Close()\n\tif string(body) != version {\n\t\tversionNew = string(body)\n\t}\n}\n"
  },
  {
    "path": "script/openwrt/cf_RE.sh",
    "content": "#!/bin/bash\n##用于openwrt安装jq和timeout，确保CloudflareSpeedTestDDNS运行正常。\nopkg update\nopkg install jq coreutils-timeout\nopkg install yq\nopkg list-installed | grep jq\nopkg list-installed | grep coreutils-timeout\n"
  },
  {
    "path": "script/openwrt/config.yaml",
    "content": "\n##cloudflare配置\ncloudflare:\n#cloudflare账号邮箱\n - x_email:  \n\n   #域名(多个用逗号分隔)\n   hostname: \n   \n   #空间ID\n   zone_id:\n   \n   #Global API Key\n   api_key: \n\n#配置多个账号或域名,注意字段使用空格对齐，符合yaml格式要求 \n# - x_email:  \n#\n#   #域名(多个用逗号分隔)\n#   hostname: \n#   \n#   #空间ID\n#   zone_id:\n#   \n#   #Global API Key\n#   api_key: \n\n##openwrt科学上网插件配置\n#优选节点时是否自动停止科学上网服务 true: 自动停止 false: 不停止 默认为 true\npause: \n  true\n#填写openwrt使用的是哪个科学上网客户端，填写对应的“数字”  默认为 1  客户端为passwall\n# 1: passwall 2: passwall2 3: ShadowSocksR Plus+ 4: clash 5: openclash 6: bypass\nclien: \n  1\n#同一域名更新的ip数量(如果设置值大于实际搜出的ip数量，以实际ip数量为准)\nmultip:\n\n#测速地址  \nCFST_URL: \n  \n#测速线程数量；越多测速越快，性能弱的设备 (如路由器) 请勿太高；(默认 200 最多 1000 )\nCFST_N: 200\n#延迟测速次数；单个 IP 延迟测速次数，为 1 时将过滤丢包的IP，TCP协议；(默认 4 次 )\nCFST_T: 1\n#下载测速数量；延迟测速并排序后，从最低延迟起下载测速的数量；(默认 10 个)\nCFST_DN: 10\n#平均延迟上限；只输出低于指定平均延迟的 IP，可与其他上限/下限搭配；(默认9999 ms 这里推荐配置250 ms)\nCFST_TL: 250\n#平均延迟下限；只输出高于指定平均延迟的 IP，可与其他上限/下限搭配、过滤假墙 IP；(默认 0 ms 这里推荐配置40)\nCFST_TLL: 40\n#下载速度下限；只输出高于指定下载速度的 IP，凑够指定数量 [-dn] 才会停止测速；(默认 0.00 MB/s 这里推荐5.00MB/s)\nCFST_SL: 5\n#是否按国家代码做分组筛选(是: true,否: false)\nCCFLAG: true\n#需要指定的国家代码,多个用逗号分隔(eg. US,JP)\nCCODE: \n#CF服务器对应端口\nCF_ADDR: 443\n\n#推送开关, 1:TG, 2:WX, 3.both.\nsendType:\n   3\n\n##TG推送设置\n#（填写即为开启推送，未填写则为不开启）\n#TG机器人token 例如：123456789: ABCDEFG...\ntelegramBotToken:  \n  \ntelegramBotUserId: \n  \n \n#微信推送, 通过https://sct.ftqq.com/r/13223 注册并登录server酱，取得sendKey\nsendKey:\n\n#微信推送api\nwxpushAPI:\n\nwxToken:\n\n"
  },
  {
    "path": "script/openwrt/ddns/cf_ddns",
    "content": "#!/bin/bash\n#新功能，支持更新优选完毕后推送至TG，再也不怕脚本没有成功运行了。\n#使用脚本需要安装jq和timeout，新增openwrt专用cf_RE.sh文件，运行cf_RE.sh即可在openwrt安装jq和timeout两个扩展。\n#其他linux请自行安装jq和timeout。\n\nipv4Regex=\"((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])\"\n#默认关闭小云朵\nproxy=\"false\"\nchkDnsArr=()\ndelDnsArr=()\nexcludeIp=()\nCheckDelCFDns() {\n  listDnsApi=\"https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records?name=${CDNhostname}\"\n  excludeIp=()\n  delDnsArr=()\n  chkDnsArr=()\n  res=$(curl -s -X GET \"$listDnsApi\" -H \"X-Auth-Email:$x_email\" -H \"X-Auth-Key:$api_key\" -H \"Content-Type:application/json\")\n  total_ct=$(echo \"$res\" | jq -r \".result_info.total_count\")\n\n  #echo \"multFlag: $multFlag\"\n\n  if ((total_ct > 1 || multFlag == 1)); then\n    # echo \"total_ct:$total_ct\"\n    for ((i = 0; i < total_ct; i++)); do\n      record_id=$(echo \"$res\" | jq -r \".result[$i].id\")\n      ip=$(echo \"$res\" | jq -r \".result[$i].content\")\n      chkDnsArr+=(\"$record_id\"\":\"\"$ip\")\n      #echo \"$record_id\"\":\"\"$ip\"\n    done\n  fi\n}\n\nfindRecInExcludeArr() {\n  local rec=$1\n  local sparr=()\n  IFS=':' read -ra sparr <<<\"$rec\"\n  # echo \"findRecInExcludeArr():rec:$rec\"\n  for ip in \"${excludeIp[@]}\"; do\n    #echo \"left:${sparr[1]}|,right:$ip|\"\n    if [ \"${sparr[1]}\" == \"$ip\" ]; then\n      return 0\n    fi\n  done\n\n  return 1\n}\n\nFilterRec() {\n  # echo \"FilterRec()\"\n  delDnsArr=()\n  for i in \"${!chkDnsArr[@]}\"; do\n    findRecInExcludeArr \"${chkDnsArr[$i]}\"\n    #不是排除之列，则加到删除队列\n    if [ $? -eq 1 ]; then\n      #echo \"add to delarr\"\n      local sparr=()\n      IFS=':' read -ra sparr <<<\"${chkDnsArr[$i]}\"\n      delDnsArr+=(${sparr[0]})\n    fi\n\n  done\n}\n\nRealDelDns() {\n  delDnsApi=\"https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records\"\n\n  FilterRec\n  for index in \"${!delDnsArr[@]}\"; do\n    record_id=${delDnsArr[$index]}\n    # 输出正在删除的记录\n    #echo \"正在删除第 $((index + 1)) 条 DNS 记录，记录 ID: $record_id\"\n    # 发出删除请求\n    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\")\n    succ=$(echo $rt | jq -r \".success\")\n    if [ \"$succ\" != \"true\" ]; then\n      echo \"删除dns记录失败,会可能引起后面更新问题，强制退出\"\n      exit 1\n    fi\n\n  done\n\n}\n\nInsertCF() {\n  ipAddr=$1\n  if [[ $ipAddr =~ $ipv4Regex ]]; then\n    recordType=\"A\"\n  else\n    recordType=\"AAAA\"\n  fi\n\n  echo \"新增$CDNhostname 的DNS记录\"\n  createDnsApi=\"https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records\"\n  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}\")\n  resSuccess=$(echo \"$res\" | jq -r \".success\")\n\n  if [[ \"$resSuccess\" = \"true\" ]]; then\n    echo \"$CDNhostname更新成功\"\n    return 0\n  else\n    code=$(echo \"$res\" | jq -r \".errors[0].code\")\n    #已有相同记录\n    if [ $code -eq 81057 ]; then\n      excludeIp+=($ipAddr)\n      echo \"已有[$ipAddr] IP记录不做更新\"\n      return 0\n    else\n      echo \"$CDNhostname更新失败\"\n      return 1\n    fi\n  fi\n\n}\n\nUpInsetCF() {\n  #开始DDNS\n  ipAddr=$1\n  if [[ $ipAddr =~ $ipv4Regex ]]; then\n    recordType=\"A\"\n  else\n    recordType=\"AAAA\"\n  fi\n\n  listDnsApi=\"https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records?type=${recordType}&name=${CDNhostname}\"\n  createDnsApi=\"https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records\"\n\n  res=$(curl -s -X GET \"$listDnsApi\" -H \"X-Auth-Email:$x_email\" -H \"X-Auth-Key:$api_key\" -H \"Content-Type:application/json\")\n  recordId=$(echo \"$res\" | jq -r \".result[0].id\")\n  recordIp=$(echo \"$res\" | jq -r \".result[0].content\")\n\n  echo \"recordIp:$recordIp\"\n  if [[ $recordIp = \"$ipAddr\" ]]; then\n    echo \"更新失败，获取最快的IP与云端相同\"\n    excludeIp+=($ipAddr)\n    resSuccess=\"false\"\n  elif [[ $recordId = \"null\" ]]; then\n    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}\")\n    resSuccess=$(echo \"$res\" | jq -r \".success\")\n  else\n    updateDnsApi=\"https://api.cloudflare.com/client/v4/zones/${zone_id}/dns_records/${recordId}\"\n    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}\")\n    resSuccess=$(echo \"$res\" | jq -r \".success\")\n    excludeIp+=($ipAddr)\n  fi\n\n  if [[ \"$resSuccess\" = \"true\" ]]; then\n    echo \"$CDNhostname更新成功\"\n  else\n    echo \"$CDNhostname更新失败\"\n  fi\n\n}\n\n#验证cf账号信息是否正确\necho \"cf_ddns():zone_id:$zone_id\"\necho \"cf_ddns():api_key:$api_key\"\nres=$(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\")\nresSuccess=$(echo \"$res\" | jq -r \".success\")\nif [[ $resSuccess != \"true\" ]]; then\n  pushmessage=\"登陆错误,检查cloudflare账号信息填写是否正确！\"\n  source ./msg/cf_push\n  exit 1\nfi\necho \"Cloudflare账号验证成功\"\n\nif [ -z $multip ]; then\n  multip=1\n  multFlag=0\nelse\n  multFlag=1\nfi\n\n#开始循环\necho \"正在更新域名，请稍后...\"\nx=0\ncsvfile=\"\"\nwhile [[ ${x} -lt $domain_num ]]; do\n  CDNhostname=${domains[$x]}\n  #获取优选后的ip地址\n\n  if [ \"$CCFLAG\" = \"true\" ]; then\n    CountryCode=${countryCodes[$x]}\n    csvfile=\"$CountryCode\"\".csv\"\n    echo \"csvfile:$csvfile\"\n  else\n    csvfile=\"result.csv\"\n  fi\n\n  #如果没有生成对应结果文件，跳过\n  if [ ! -e $csvfile ]; then\n    x=$((x + 1))\n    continue\n  fi\n\n  CheckDelCFDns\n\n  lineNo=0\n  ipcount=0\n  while read -r line; do\n    ((lineNo++))\n    if ((lineNo == 1)); then\n      continue\n    fi\n    IFS=, read -ra fields <<<\"$line\"\n    ipAddr=${fields[0]}\n\n    ((ipcount++))\n    echo \"开始更新第${ipcount}个---$ipAddr\"\n    if ((multFlag == 1)); then\n      InsertCF $ipAddr\n    else\n      UpInsetCF $ipAddr\n    fi\n\n    if ((ipcount >= multip)); then\n      break\n    fi\n\n  done <$csvfile\n\n  RealDelDns\n  echo \"完成$csvfile的ip更新!\"\n  x=$((x + 1))\n  sleep 1s\n\ndone >>informlog\n"
  },
  {
    "path": "script/openwrt/msg/cf_push",
    "content": "#!/bin/bash\n##用于CloudflareSpeedTestDDNS执行情况推送。\necho $pushmessage\nmessage_text=$pushmessage\n#解析模式，可选HTML或Markdown\nMODE='HTML'\n#api接口\ntelegramBotToken=$(yq eval \".telegramBotToken\" $configfile)\ntelegramBotUserId=$(yq eval \".telegramBotUserId\" $configfile)\nURL=\"https://api.telegram.org/bot${telegramBotToken}/sendMessage\"\nif [[ -z ${telegramBotToken} ]]; then\n  echo \"未配置TG推送\"\nelse\n  res=$(timeout 20s curl -s -X POST $URL -d chat_id=${telegramBotUserId} -d parse_mode=${MODE} -d text=\"${message_text}\")\n  if [ $? == 124 ]; then\n    echo 'TG_api请求超时,请检查网络是否重启完成并是否能够访问TG'\n    exit 1\n  fi\n  resSuccess=$(echo \"$res\" | jq -r \".ok\")\n  if [[ $resSuccess = \"true\" ]]; then\n    echo \"TG推送成功\"\n  else\n    echo \"TG推送失败，请检查TG机器人token和ID\"\n  fi\nfi\n"
  },
  {
    "path": "script/openwrt/msg/wxpush.sh",
    "content": "#!/bin/bash\n\ntext=''\n\nwhile IFS= read -r line; do\n  text+=\"$line\"\ndone <\"./informlog\"\n\ntitle=\"msg_from_cvwt\"\ntoken=\"$wxToken\"\n\nif [[ -z ${wxpushAPI} ]]; then\n  echo \"未配置微信推送API!!!\"\nelse\n  URL=\"$wxpushAPI\"\n  echo \"URL:$URL\"\n  res=$(timeout 20s curl -s -X POST $URL \\\n  -d title=${title} --data-urlencode content=\"${text}\" -d token=\"$token\")\n\n  if [ $? == 124 ]; then\n    echo \"发送消息超时\"\n    exit 1\n  fi\n\n # 检查返回结果是否包含成功关键词\n  if echo \"$res\" | grep -q -E \"Successfully\"; then\n    echo \"微信推送成功\"\n    echo \"res:$res\"\n  else\n    echo \"微信推送失败, 返回结果: $res\"\n  fi\n\nfi\n"
  },
  {
    "path": "script/openwrt/msg/wxsend_jiang.sh",
    "content": "#!/bin/bash\n\ntext=''\n\nwhile IFS= read -r line; do\n  text+=\"$line\"\ndone <\"./informlog\"\n\n#for test.\n#configfile=\"./config.yaml\"\n#sendKey=$(yq eval \".sendKey\" $configfile)\n\ntitle=\"msg_from_cvwt\"\nURL=\"https://sctapi.ftqq.com/$sendKey.send?\"\n\nif [[ -z ${sendKey} ]]; then\n  echo \"未配置微信推送的sendKey, 关注【方糖】公众号获取sendKey\"\nelse\n  res=$(timeout 20s curl -s -X POST $URL -d title=${title} -d desp=\"${text}\")\n  if [ $? == 124 ]; then\n    echo \"发送消息超时\"\n    exit 1\n  fi\n\n  #res:{\"code\":0,\"message\":\"\",\"data\":{\"pushid\":\"164999333\",\"readkey\":\"SCTGLrDh4Zadf4k\",\"error\":\"SUCCESS\",\"errno\":0}}\n  err=$(echo \"$res\" | jq -r \".data.error\")\n  if [ \"$err\" == \"SUCCESS\" ]; then\n    echo \"微信推送成功\"\n  else\n    echo \"微信推送失败, error:$err\"\n  fi\nfi\n"
  },
  {
    "path": "script/openwrt/start-v2.sh",
    "content": "#!/bin/bash\n\nif [ $# -lt 1 ]; then\n  echo \"start.sh config_file_path [ipfile]\"\n  exit 0\nfi\n\nconfigfile=$1\nipfile=$2\n\necho \"configfile:$configfile, ipfile:$ipfile\"\n\nipzipfile=\"ip.zip\"\n\n#or test\nrm -rf *.csv\nif [[ -e $ipzipfile ]]; then\n  rm -rf $ipzipfile\nfi\n\nif [[ -e informlog ]]; then\n  rm -rf informlog\nfi\n\n\necho \"0.读取配置文件\"\nif [[ ! -e $configfile ]]; then\n  echo \"找不到$configfile配置文件!\"\n  exit 1\nfi\n\npause=$(yq eval \".pause\" $configfile)\nclien=$(yq eval \".clien\" $configfile)\nmultip=$(yq eval \".multip\" $configfile)\nCFST_URL=$(yq eval \".CFST_URL\" $configfile)\nCFST_N=$(yq eval \".CFST_N\" $configfile)\nCFST_T=$(yq eval \".CFST_T\" $configfile)\nCFST_DN=$(yq eval \".CFST_DN\" $configfile)\nCFST_TL=$(yq eval \".CFST_TL\" $configfile)\nCFST_TLL=$(yq eval \".CFST_TLL\" $configfile)\nCFST_SL=$(yq eval \".CFST_SL\" $configfile)\nCCFLAG=$(yq eval \".CCFLAG\" $configfile)\nCCODE=$(yq eval \".CCODE\" $configfile)\nCF_ADDR=$(yq eval \".CF_ADDR\" $configfile)\ntelegramBotToken=$(yq eval \".telegramBotToken\" $configfile)\ntelegramBotUserId=$(yq eval \".telegramBotUserId\" $configfile)\nsendType=$(yq eval \".sendType\" $configfile)\nsendKey=$(yq eval \".sendKey\" $configfile)\nwxpushAPI=$(yq eval \".wxpushAPI\" $configfile)\nwxToken=$(yq eval \".wxToken\" $configfile)\n\nChkHostnameAndCoutryCode() {\n  IFS=, read -r -a domains <<<\"$hostname\"\n  IFS=, read -r -a countryCodes <<<\"$CCODE\"\n\n  domain_num=${#domains[@]}\n  countryCode_num=${#countryCodes[@]}\n\n  if [ ${#domains[@]} -eq 0 ]; then\n    echo \"hostname must be set in config file!\"\n    return 1\n  fi\n\n  #检查域名和国家代码是否一一对应\n  if [ \"$CCFLAG\" = \"true\" ]; then\n    echo \"domain_num:$domain_num, countryCode_num:$countryCode_num\"\n    if [ $domain_num -ne $countryCode_num ]; then\n      echo \"The name and country code must correspond one to one!\"\n      return 1\n    fi\n  fi\n  return 0\n}\n\nGetProxName() {\n  c=$1\n  if [ \"$c\" = \"6\" ]; then\n    CLIEN=bypass\n  elif [ \"$c\" = \"5\" ]; then\n    CLIEN=openclash\n  elif [ \"$c\" = \"4\" ]; then\n    CLIEN=clash\n  elif [ \"$c\" = \"3\" ]; then\n    CLIEN=shadowsocksr\n  elif [ \"$c\" = \"2\" ]; then\n    CLIEN=passwall2\n  else\n    CLIEN=passwall\n  fi\n  echo $CLIEN\n}\n\nhandle_err() {\n  if [ \"$pause\" = \"true\" ] ; then\n    echo \"Restore background process.\"\n    proxy=$(GetProxName $clien)\n    /etc/init.d/$proxy stop\n    /etc/init.d/$proxy start\n  fi\n}\n\n#trap handle_err EXIT\ntrap handle_err HUP INT TERM EXIT\nCLIEN=$(GetProxName $clien)\nps -ef | grep $CLIEN | grep -v \"grep\" >/dev/null\n\nif [ $? = 1 ]; then\n  /etc/init.d/$CLIEN start\nfi\n\nif [ -z $ipfile ]; then\n  echo \"1.Download ip file.\"\n  for i in {1..3}; do\n    wget -O $ipzipfile https://zip.cm.edu.kg\n\n    if [ $? != 0 ]; then\n      echo \"get ip file failed, try again\"\n      sleep 1\n      continue\n    else\n      echo \"downloaded.\"\n      break\n    fi\n  done\n\n  if [ -e $ipzipfile ]; then\n    unzip -o $ipzipfile\n  else\n    echo \"Can't download the ip zip file, Check whether the agent software is disabled.\"\n  fi\n\n  # echo \"2.Select the ip address of the desired port.\"\n#   port=$(yq eval \".CF_ADDR\" $configfile)\n#   if [ -z $port ]; then\n#     port=443\n#   fi\n\n#   ip_file=\"./$port/ALL.txt\"\n#   # for file in $(find . -type f -name \"*-[0-1]-$port.txt\"); do\n#   #   echo \"handling: $file\"\n#   #   cat \"$file\" >>tmp.txt\n#   # done\n\n#   if [ -e \"$ip_file\" ]; then\n#     cat \"$ip_file\" | sort -u >ip.txt\n#   fi\nfi\n\necho \"Run scripts to test speed and update dns records.\"\nCFST_P=$CFST_DN\n#判断工作模式\nif [ \"$IP_ADDR\" = \"ipv6\" ]; then\n  if [ ! -f \"ipv6.txt\" ]; then\n    echo \"当前工作模式为ipv6，但该目录下没有【ipv6.txt】，请配置【ipv6.txt】。下载地址：https://github.com/XIU2/CloudflareSpeedTest/releases\"\n    exit 2\n  else\n    echo \"当前工作模式为ipv6\"\n  fi\nelse\n  echo \"当前工作模式为ipv4\"\nfi\n\n#读取配置文件中的客户端\nCLIEN=$(GetProxName $clien)\n\n#判断是否停止科学上网服务\nif [ \"$pause\" = \"false\" ]; then\n  echo \"按要求未停止科学上网服务\"\nelse\n  /etc/init.d/$CLIEN stop\n  echo \"已停止$CLIEN\"\nfi\n\n#判断是否配置测速地址\nif [[ \"$CFST_URL\" == http* ]]; then\n  CFST_URL_R=\"-url $CFST_URL\"\nelse\n  CFST_URL_R=\"\"\nfi\n\n#判断是否使用国家代码来筛选\nif [[ \"$CCFLAG\" == \"true\" ]]; then\n  USECC=\"-c \"\nelse\n  USECC=\"\"\nfi\n\nif [ ! -z \"$CCODE\" ]; then\n  CCODE_IS=\"-cc $CCODE \"\nelse\n  CCODE_IS=\"\"\nfi\n\nif [ ! -z \"$CF_ADDR\" ]; then\n  CF_ADDR=\" -tp $CF_ADDR\"\nelse\n  CF_ADDR=\" -tp 443\"\nfi\n\n# 定义测速函数\nrun_speedtest() {\n  local ip_file=$1\n  local output=$2\n  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\"\n  \n  if [ ! -z \"$ip_file\" ]; then\n    cmd_args=\"$cmd_args -f $ip_file\"\n  fi\n  \n  if [ ! -z \"$output\" ]; then\n    cmd_args=\"$cmd_args -o $output\"\n  fi\n  \n  if [ \"$IP_ADDR\" != \"ipv6\" ] && [ ! -z \"$CF_ADDR\" ]; then\n    cmd_args=\"$cmd_args $CF_ADDR\"\n  fi\n  \n  if [ ! -z \"$USECC\" ] && [ ! -z \"$CCODE_IS\" ]; then\n    cmd_args=\"$cmd_args $USECC $CCODE_IS\"\n  fi\n  \n  echo \"./CloudflareST $cmd_args\"\n  ./CloudflareST $cmd_args\n}\n\nif [ -z \"$ipfile\" ]; then\n  ipflag=\"\"\n  port=$(yq eval \".CF_ADDR\" $configfile)\n  if [ -z $port ]; then\n    port=443\n  fi\n  \n  if [ ! -z \"$CCODE\" ]; then\n    # 如果配置了CCODE，按逗号分割为数组，循环每个国家代码进行测速\n    IFS=',' read -ra cc_arr <<< \"$CCODE\"\n    echo \"国家代码列表: ${cc_arr[*]}\"\n    CCODE_IS=\"\"\n    USECC=\"\"\n    for cc in \"${cc_arr[@]}\"; do\n      cc=$(echo $cc | xargs)  # 去除可能的空格\n      echo \"处理国家代码: $cc\"\n      ipfile_path=\"./$port/${cc}.txt\"\n      output_file=\"${cc}.csv\"\n      \n      if [ -f \"$ipfile_path\" ]; then\n        echo \"找到IP文件: $ipfile_path\"\n        run_speedtest \"$ipfile_path\" \"$output_file\"\n      else\n        echo \"警告: IP文件 $ipfile_path 不存在，跳过此国家代码\"\n      fi\n    done\n  else\n    run_speedtest \"$ipfile\" \"result.csv\"\n  fi\nelse\n  # 使用用户指定的IP文件进行测速\n  run_speedtest \"$ipfile\" \"result.csv\"\nfi\n\n\n\necho \"测速完毕\"\nif [ \"$pause\" = \"false\" ]; then\n  echo \"按要求未重启科学上网服务\"\n  sleep 3s\nelse\n  /etc/init.d/$CLIEN restart\n  echo \"已重启$CLIEN\"\n  echo \"为保证cloudflareAPI连接正常 将在3秒后开始更新域名解析\"\n  sleep 3s\nfi\n\nif yq eval 'has(\"cloudflare\")' $configfile; then\n\n  length=$(yq eval '.cloudflare | length' $configfile)\n\n  echo \"length:$length\"\n  for ((li = 0; li < $length; li++)); \n  do\n    echo \"Configuration Group $((li + 1)):\"\n    x_email=$(yq eval \".cloudflare[$li].x_email\" $configfile)\n    echo \"x_email: $x_email\"\n    hostname=$(yq eval \".cloudflare[$li].hostname\" $configfile)\n    echo \"hostname: $hostname\"\n    zone_id=$(yq eval \".cloudflare[$li].zone_id\" $configfile)\n    #echo \"zone_id:$zone_id\"\n    api_key=$(yq eval \".cloudflare[$li].api_key\" $configfile)\n    #echo \"api_key:$api_key\"\n    ChkHostnameAndCoutryCode\n    if [ $? -eq 1 ]; then\n      echo \"ChkHostnameAndCoutryCode() error!\"\n      exit 1\n    fi\n\n    source ./ddns/cf_ddns\n  done\n\nfi\n\n#会生成一个名为informlog的临时文件作为推送的内容。\npushmessage=$(cat informlog)\necho $pushmessage\n\nif [ ! -z \"$sendType\" ]; then\n  if [[ $sendType -eq 1 ]]; then\n    source ./msg/cf_push\n  elif [[ $sendType -eq 2 ]]; then\n    source ./msg/wxsend_jiang.sh\n    source ./msg/wxpush.sh\n  elif [[ $sendType -eq 3 ]]; then\n    source ./msg/cf_push\n    source ./msg/wxsend_jiang.sh\n    source ./msg/wxpush.sh\n  else\n    echo \"$sendType is invalid type!\"\n  fi\nfi\n"
  },
  {
    "path": "script/openwrt/start.sh",
    "content": "#!/bin/bash\n\nif [ $# -lt 1 ]; then\n  echo \"start.sh config_file_path [ipfile]\"\n  exit 0\nfi\n\nconfigfile=$1\nipfile=$2\n\necho \"configfile:$configfile, ipfile:$ipfile\"\n\nipzipfile=\"ip.zip\"\n\n//for test\nrm -rf *.csv\nif [[ -e $ipzipfile ]]; then\n  rm -rf $ipzipfile\nfi\n\nif [[ -e informlog ]]; then\n  rm -rf informlog\nfi\n\n\necho \"0.读取配置文件\"\nif [[ ! -e $configfile ]]; then\n  echo \"找不到$configfile配置文件!\"\n  exit 1\nfi\n\npause=$(yq eval \".pause\" $configfile)\nclien=$(yq eval \".clien\" $configfile)\nmultip=$(yq eval \".multip\" $configfile)\nCFST_URL=$(yq eval \".CFST_URL\" $configfile)\nCFST_N=$(yq eval \".CFST_N\" $configfile)\nCFST_T=$(yq eval \".CFST_T\" $configfile)\nCFST_DN=$(yq eval \".CFST_DN\" $configfile)\nCFST_TL=$(yq eval \".CFST_TL\" $configfile)\nCFST_TLL=$(yq eval \".CFST_TLL\" $configfile)\nCFST_SL=$(yq eval \".CFST_SL\" $configfile)\nCCFLAG=$(yq eval \".CCFLAG\" $configfile)\nCCODE=$(yq eval \".CCODE\" $configfile)\nCF_ADDR=$(yq eval \".CF_ADDR\" $configfile)\ntelegramBotToken=$(yq eval \".telegramBotToken\" $configfile)\ntelegramBotUserId=$(yq eval \".telegramBotUserId\" $configfile)\nsendType=$(yq eval \".sendType\" $configfile)\nsendKey=$(yq eval \".sendKey\" $configfile)\nwxpushAPI=$(yq eval \".wxpushAPI\" $configfile)\nwxToken=$(yq eval \".wxToken\" $configfile)\n\nChkHostnameAndCoutryCode() {\n  IFS=, read -r -a domains <<<\"$hostname\"\n  IFS=, read -r -a countryCodes <<<\"$CCODE\"\n\n  domain_num=${#domains[@]}\n  countryCode_num=${#countryCodes[@]}\n\n  if [ ${#domains[@]} -eq 0 ]; then\n    echo \"hostname must be set in config file!\"\n    return 1\n  fi\n\n  #检查域名和国家代码是否一一对应\n  if [ \"$CCFLAG\" = \"true\" ]; then\n    echo \"domain_num:$domain_num, countryCode_num:$countryCode_num\"\n    if [ $domain_num -ne $countryCode_num ]; then\n      echo \"The name and country code must correspond one to one!\"\n      return 1\n    fi\n  fi\n  return 0\n}\n\nGetProxName() {\n  c=$1\n  if [ \"$c\" = \"6\" ]; then\n    CLIEN=bypass\n  elif [ \"$c\" = \"5\" ]; then\n    CLIEN=openclash\n  elif [ \"$c\" = \"4\" ]; then\n    CLIEN=clash\n  elif [ \"$c\" = \"3\" ]; then\n    CLIEN=shadowsocksr\n  elif [ \"$c\" = \"2\" ]; then\n    CLIEN=passwall2\n  else\n    CLIEN=passwall\n  fi\n  echo $CLIEN\n}\n\nhandle_err() {\n  if [ \"$pause\" = \"true\" ] ; then\n    echo \"Restore background process.\"\n    proxy=$(GetProxName $clien)\n    /etc/init.d/$proxy start\n  fi\n}\n\n#trap handle_err EXIT\ntrap handle_err HUP INT TERM EXIT\nCLIEN=$(GetProxName $clien)\nps -ef | grep $CLIEN | grep -v \"grep\" >/dev/null\n\nif [ $? = 1 ]; then\n  /etc/init.d/$CLIEN start\nfi\n\nif [ -z $ipfile ]; then\n  echo \"1.Download ip file.\"\n  for i in {1..3}; do\n    wget -O $ipzipfile https://zip.cm.edu.kg\n\n    if [ $? != 0 ]; then\n      echo \"get ip file failed, try again\"\n      sleep 1\n      continue\n    else\n      echo \"downloaded.\"\n      break\n    fi\n  done\n\n  if [ -e $ipzipfile ]; then\n    unzip -o $ipzipfile\n  else\n    echo \"Can't download the ip zip file, Check whether the agent software is disabled.\"\n  fi\n\n  echo \"2.Select the ip address of the desired port.\"\n  port=$(yq eval \".CF_ADDR\" $configfile)\n  if [ -z $port ]; then\n    port=443\n  fi\n\n  ip_file=\"./$port/ALL.txt\"\n  # for file in $(find . -type f -name \"*-[0-1]-$port.txt\"); do\n  #   echo \"handling: $file\"\n  #   cat \"$file\" >>tmp.txt\n  # done\n\n  if [ -e \"$ip_file\" ]; then\n    cat \"$ip_file\" | sort -u >ip.txt\n  fi\nfi\n\necho \"Run scripts to test speed and update dns records.\"\nCFST_P=$CFST_DN\n#判断工作模式\nif [ \"$IP_ADDR\" = \"ipv6\" ]; then\n  if [ ! -f \"ipv6.txt\" ]; then\n    echo \"当前工作模式为ipv6，但该目录下没有【ipv6.txt】，请配置【ipv6.txt】。下载地址：https://github.com/XIU2/CloudflareSpeedTest/releases\"\n    exit 2\n  else\n    echo \"当前工作模式为ipv6\"\n  fi\nelse\n  echo \"当前工作模式为ipv4\"\nfi\n\n#读取配置文件中的客户端\nCLIEN=$(GetProxName $clien)\n\n#判断是否停止科学上网服务\nif [ \"$pause\" = \"false\" ]; then\n  echo \"按要求未停止科学上网服务\"\nelse\n  /etc/init.d/$CLIEN stop\n  echo \"已停止$CLIEN\"\nfi\n\n#判断是否配置测速地址\nif [[ \"$CFST_URL\" == http* ]]; then\n  CFST_URL_R=\"-url $CFST_URL\"\nelse\n  CFST_URL_R=\"\"\nfi\n\n#判断是否使用国家代码来筛选\nif [[ \"$CCFLAG\" == \"true\" ]]; then\n  USECC=\"-c \"\nelse\n  USECC=\"\"\nfi\n\nif [ ! -z \"$CCODE\" ]; then\n  CCODE_IS=\"-cc $CCODE \"\nelse\n  CCODE_IS=\"\"\nfi\n\nif [ ! -z \"$CF_ADDR\" ]; then\n  CF_ADDR=\" -tp $CF_ADDR\"\nelse\n  CF_ADDR=\" -tp 443\"\nfi\n\nif [ -z \"$ipfile\" ]; then\n  ipflag=\"\"\nelse\n  ipflag=\"-f \"\nfi\n\nif [ \"$IP_ADDR\" = \"ipv6\" ]; then\n  #开始优选IPv6\n  ./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\n  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\"\nelse\n  #开始优选IPv4\n  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\"\n  ./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\nfi\necho \"测速完毕\"\nif [ \"$pause\" = \"false\" ]; then\n  echo \"按要求未重启科学上网服务\"\n  sleep 3s\nelse\n  /etc/init.d/$CLIEN restart\n  echo \"已重启$CLIEN\"\n  echo \"为保证cloudflareAPI连接正常 将在3秒后开始更新域名解析\"\n  sleep 3s\nfi\n\nif yq eval 'has(\"cloudflare\")' $configfile; then\n\n  length=$(yq eval '.cloudflare | length' $configfile)\n\n  echo \"length:$length\"\n  for ((li = 0; li < $length; li++)); \n  do\n    echo \"Configuration Group $((li + 1)):\"\n    x_email=$(yq eval \".cloudflare[$li].x_email\" $configfile)\n    echo \"x_email: $x_email\"\n    hostname=$(yq eval \".cloudflare[$li].hostname\" $configfile)\n    echo \"hostname: $hostname\"\n    zone_id=$(yq eval \".cloudflare[$li].zone_id\" $configfile)\n    #echo \"zone_id:$zone_id\"\n    api_key=$(yq eval \".cloudflare[$li].api_key\" $configfile)\n    #echo \"api_key:$api_key\"\n    ChkHostnameAndCoutryCode\n    if [ $? -eq 1 ]; then\n      echo \"ChkHostnameAndCoutryCode() error!\"\n      exit 1\n    fi\n\n    source ./ddns/cf_ddns\n  done\n\nfi\n\n#会生成一个名为informlog的临时文件作为推送的内容。\npushmessage=$(cat informlog)\necho $pushmessage\n\nif [ ! -z \"$sendType\" ]; then\n  if [[ $sendType -eq 1 ]]; then\n    source ./msg/cf_push\n  elif [[ $sendType -eq 2 ]]; then\n    source ./msg/wxsend_jiang.sh\n    source ./msg/wxpush.sh\n  elif [[ $sendType -eq 3 ]]; then\n    source ./msg/cf_push\n    source ./msg/wxsend_jiang.sh\n    source ./msg/wxpush.sh\n  else\n    echo \"$sendType is invalid type!\"\n  fi\nfi\n\n"
  },
  {
    "path": "task/download.go",
    "content": "package task\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"sort\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/XIU2/CloudflareSpeedTest/utils\"\n\n\t\"github.com/VividCortex/ewma\"\n)\n\nconst (\n\tbufferSize                     = 1024\n\tdefaultURL                     = \"https://cf.xiu2.xyz/url\"\n\tdefaultTimeout                 = 5 * time.Second\n\tdefaultDisableDownload         = false\n\tdefaultTestNum                 = 10\n\tdefaultMinSpeed        float64 = 0.0\n)\n\nvar (\n\tURL     = defaultURL\n\tTimeout = defaultTimeout\n\tDisable = defaultDisableDownload\n\n\tTestCount = defaultTestNum\n\tMinSpeed  = defaultMinSpeed\n)\n\nfunc checkDownloadDefault() {\n\tif URL == \"\" {\n\t\tURL = defaultURL\n\t}\n\tif Timeout <= 0 {\n\t\tTimeout = defaultTimeout\n\t}\n\tif TestCount <= 0 {\n\t\tTestCount = defaultTestNum\n\t}\n\tif MinSpeed <= 0.0 {\n\t\tMinSpeed = defaultMinSpeed\n\t}\n}\n\nfunc TestDownloadSpeedByCountry(ipSet utils.PingDelaySet) (speedSet utils.DownloadSpeedSet) {\n\tcheckDownloadDefault()\n\tif Disable {\n\t\treturn utils.DownloadSpeedSet(ipSet)\n\t}\n\tif len(ipSet) <= 0 { // IP数组长度(IP数量) 大于 0 时才会继续下载测速\n\t\tfmt.Println(\"\\n[信息] 延迟测速结果 IP 数量为 0，跳过下载测速。\")\n\t\treturn\n\t}\n\t//按国家代号划分分片\n\tcountryMap := make(map[string]utils.PingDelaySet)\n\tfor _, ip := range ipSet {\n\t\tcountry := ip.Country\n\t\tif _, ok := countryMap[country]; !ok {\n\t\t\tcountryMap[country] = make(utils.PingDelaySet, 0)\n\t\t}\n\t\tcountryMap[country] = append(countryMap[country], ip)\n\t}\n\n\t// 按照每个国家分批进行测速\n\tfor country, countrySet := range countryMap {\n\t\ttestNum := TestCount\n\t\tbarCount := TestCount\n\t\tif len(countrySet) < TestCount || MinSpeed > 0 { // 如果IP数组长度(IP数量) 小于下载测速数量（-dn），则次数修正为IP数\n\t\t\ttestNum = len(countrySet)\n\t\t}\n\t\tif testNum < barCount {\n\t\t\tbarCount = testNum\n\t\t}\n\n\t\tfmt.Printf(\"\\n[信息] 开始测速 %s 的 IP，数量：%d\\n\", country, len(countrySet))\n\t\tbar_a := len(strconv.Itoa(len(countrySet)))\n\t\tbar_b := \"     \"\n\t\tfor i := 0; i < bar_a; i++ {\n\t\t\tbar_b += \" \"\n\t\t}\n\t\tbar := utils.NewBar(barCount, bar_b, \"\")\n\t\tcountryspeedSet := make(utils.DownloadSpeedSet, 0)\n\t\tfor i := 0; i < testNum; i++ {\n\t\t\tspeed := downloadHandler(countrySet[i].IP)\n\t\t\tcountrySet[i].DownloadSpeed = speed\n\t\t\t// 在每个 IP 下载测速后，以 [下载速度下限] 条件过滤结果\n\t\t\tif speed >= MinSpeed*1024*1024 {\n\t\t\t\tbar.Grow(1, \"\")\n\t\t\t\tcountryspeedSet = append(countryspeedSet, countrySet[i]) // 高于下载速度下限时，添加到新数组中\n\t\t\t\tif len(countryspeedSet) == TestCount {                   // 凑够满足条件的 IP 时（下载测速数量 -dn），就跳出循环\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbar.Done()\n\t\tif len(countryspeedSet) == 0 {\n\t\t\tcountryspeedSet = utils.DownloadSpeedSet(countrySet)\n\t\t}\n\t\tspeedSet = append(speedSet, countryspeedSet...)\n\t}\n\n\treturn\n}\n\nfunc TestDownloadSpeed(ipSet utils.PingDelaySet) (speedSet utils.DownloadSpeedSet) {\n\tcheckDownloadDefault()\n\tif Disable {\n\t\treturn utils.DownloadSpeedSet(ipSet)\n\t}\n\tif len(ipSet) <= 0 { // IP数组长度(IP数量) 大于 0 时才会继续下载测速\n\t\tfmt.Println(\"\\n[信息] 延迟测速结果 IP 数量为 0，跳过下载测速。\")\n\t\treturn\n\t}\n\ttestNum := TestCount\n\tif len(ipSet) < TestCount || MinSpeed > 0 { // 如果IP数组长度(IP数量) 小于下载测速数量（-dn），则次数修正为IP数\n\t\ttestNum = len(ipSet)\n\t}\n\tif testNum < TestCount {\n\t\tTestCount = testNum\n\t}\n\n\tfmt.Printf(\"开始下载测速（下限：%.2f MB/s, 数量：%d, 队列：%d）\\n\", MinSpeed, TestCount, testNum)\n\t// 控制 下载测速进度条 与 延迟测速进度条 长度一致（强迫症）\n\tbar_a := len(strconv.Itoa(len(ipSet)))\n\tbar_b := \"     \"\n\tfor i := 0; i < bar_a; i++ {\n\t\tbar_b += \" \"\n\t}\n\tbar := utils.NewBar(TestCount, bar_b, \"\")\n\tfor i := 0; i < testNum; i++ {\n\t\tspeed := downloadHandler(ipSet[i].IP)\n\t\tipSet[i].DownloadSpeed = speed\n\t\t// 在每个 IP 下载测速后，以 [下载速度下限] 条件过滤结果\n\t\tif speed >= MinSpeed*1024*1024 {\n\t\t\tbar.Grow(1, \"\")\n\t\t\tspeedSet = append(speedSet, ipSet[i]) // 高于下载速度下限时，添加到新数组中\n\t\t\tif len(speedSet) == TestCount {       // 凑够满足条件的 IP 时（下载测速数量 -dn），就跳出循环\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tbar.Done()\n\tif len(speedSet) == 0 { // 没有符合速度限制的数据，返回所有测试数据\n\t\tspeedSet = utils.DownloadSpeedSet(ipSet)\n\t}\n\t// 按速度排序\n\tsort.Sort(speedSet)\n\treturn\n}\n\nfunc getDialContext(ip *net.IPAddr) func(ctx context.Context, network, address string) (net.Conn, error) {\n\tvar fakeSourceAddr string\n\tif isIPv4(ip.String()) {\n\t\tfakeSourceAddr = fmt.Sprintf(\"%s:%d\", ip.String(), TCPPort)\n\t} else {\n\t\tfakeSourceAddr = fmt.Sprintf(\"[%s]:%d\", ip.String(), TCPPort)\n\t}\n\treturn func(ctx context.Context, network, address string) (net.Conn, error) {\n\t\treturn (&net.Dialer{}).DialContext(ctx, network, fakeSourceAddr)\n\t}\n}\n\n// return download Speed\nfunc downloadHandler(ip *net.IPAddr) float64 {\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{DialContext: getDialContext(ip)},\n\t\tTimeout:   Timeout,\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\tif len(via) > 10 { // 限制最多重定向 10 次\n\t\t\t\treturn http.ErrUseLastResponse\n\t\t\t}\n\t\t\tif req.Header.Get(\"Referer\") == defaultURL { // 当使用默认下载测速地址时，重定向不携带 Referer\n\t\t\t\treq.Header.Del(\"Referer\")\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\treq, err := http.NewRequest(\"GET\", URL, nil)\n\tif err != nil {\n\t\treturn 0.0\n\t}\n\n\treq.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\")\n\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\treturn 0.0\n\t}\n\tdefer response.Body.Close()\n\tif response.StatusCode != 200 {\n\t\treturn 0.0\n\t}\n\ttimeStart := time.Now()           // 开始时间（当前）\n\ttimeEnd := timeStart.Add(Timeout) // 加上下载测速时间得到的结束时间\n\n\tcontentLength := response.ContentLength // 文件大小\n\tbuffer := make([]byte, bufferSize)\n\n\tvar (\n\t\tcontentRead     int64 = 0\n\t\ttimeSlice             = Timeout / 100\n\t\ttimeCounter           = 1\n\t\tlastContentRead int64 = 0\n\t)\n\n\tvar nextTime = timeStart.Add(timeSlice * time.Duration(timeCounter))\n\te := ewma.NewMovingAverage()\n\n\t// 循环计算，如果文件下载完了（两者相等），则退出循环（终止测速）\n\tfor contentLength != contentRead {\n\t\tcurrentTime := time.Now()\n\t\tif currentTime.After(nextTime) {\n\t\t\ttimeCounter++\n\t\t\tnextTime = timeStart.Add(timeSlice * time.Duration(timeCounter))\n\t\t\te.Add(float64(contentRead - lastContentRead))\n\t\t\tlastContentRead = contentRead\n\t\t}\n\t\t// 如果超出下载测速时间，则退出循环（终止测速）\n\t\tif currentTime.After(timeEnd) {\n\t\t\tbreak\n\t\t}\n\t\tbufferRead, err := response.Body.Read(buffer)\n\t\tif err != nil {\n\t\t\tif err != io.EOF { // 如果文件下载过程中遇到报错（如 Timeout），且并不是因为文件下载完了，则退出循环（终止测速）\n\t\t\t\tbreak\n\t\t\t} else if contentLength == -1 { // 文件下载完成 且 文件大小未知，则退出循环（终止测速），例如：https://speed.cloudflare.com/__down?bytes=200000000 这样的，如果在 10 秒内就下载完成了，会导致测速结果明显偏低甚至显示为 0.00（下载速度太快时）\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// 获取上个时间片\n\t\t\tlast_time_slice := timeStart.Add(timeSlice * time.Duration(timeCounter-1))\n\t\t\t// 下载数据量 / (用当前时间 - 上个时间片/ 时间片)\n\t\t\te.Add(float64(contentRead-lastContentRead) / (float64(currentTime.Sub(last_time_slice)) / float64(timeSlice)))\n\t\t}\n\t\tcontentRead += int64(bufferRead)\n\t}\n\treturn e.Value() / (Timeout.Seconds() / 120)\n}\n"
  },
  {
    "path": "task/httping.go",
    "content": "package task\n\nimport (\n\t//\"crypto/tls\"\n\t//\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"net/http\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar (\n\tHttping           bool\n\tHttpingStatusCode int\n\tHttpingCFColo     string\n\tHttpingCFColomap  *sync.Map\n\tOutRegexp         = regexp.MustCompile(`[A-Z]{3}`)\n)\n\n// pingReceived pingTotalTime\nfunc (p *Ping) httping(ip *net.IPAddr) (int, time.Duration) {\n\thc := http.Client{\n\t\tTimeout: time.Second * 2,\n\t\tTransport: &http.Transport{\n\t\t\tDialContext: getDialContext(ip),\n\t\t\t//TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // 跳过证书验证\n\t\t},\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse // 阻止重定向\n\t\t},\n\t}\n\n\t// 先访问一次获得 HTTP 状态码 及 Cloudflare Colo\n\t{\n\t\trequ, err := http.NewRequest(http.MethodHead, URL, nil)\n\t\tif err != nil {\n\t\t\treturn 0, 0\n\t\t}\n\t\trequ.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\")\n\t\tresp, err := hc.Do(requ)\n\t\tif err != nil {\n\t\t\treturn 0, 0\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\t//fmt.Println(\"IP:\", ip, \"StatusCode:\", resp.StatusCode, resp.Request.URL)\n\t\t// 如果未指定的 HTTP 状态码，或指定的状态码不合规，则默认只认为 200、301、302 才算 HTTPing 通过\n\t\tif HttpingStatusCode == 0 || HttpingStatusCode < 100 && HttpingStatusCode > 599 {\n\t\t\tif resp.StatusCode != 200 && resp.StatusCode != 301 && resp.StatusCode != 302 {\n\t\t\t\treturn 0, 0\n\t\t\t}\n\t\t} else {\n\t\t\tif resp.StatusCode != HttpingStatusCode {\n\t\t\t\treturn 0, 0\n\t\t\t}\n\t\t}\n\n\t\tio.Copy(io.Discard, resp.Body)\n\n\t\t// 只有指定了地区才匹配机场三字码\n\t\tif HttpingCFColo != \"\" {\n\t\t\t// 通过头部 Server 值判断是 Cloudflare 还是 AWS CloudFront 并设置 cfRay 为各自的机场三字码完整内容\n\t\t\tcfRay := func() string {\n\t\t\t\tif resp.Header.Get(\"Server\") == \"cloudflare\" {\n\t\t\t\t\treturn resp.Header.Get(\"CF-RAY\") // 示例 cf-ray: 7bd32409eda7b020-SJC\n\t\t\t\t}\n\t\t\t\treturn resp.Header.Get(\"x-amz-cf-pop\") // 示例 X-Amz-Cf-Pop: SIN52-P1\n\t\t\t}()\n\t\t\tcolo := p.getColo(cfRay)\n\t\t\tif colo == \"\" { // 没有匹配到三字码或不符合指定地区则直接结束该 IP 测试\n\t\t\t\treturn 0, 0\n\t\t\t}\n\t\t}\n\n\t}\n\n\t// 循环测速计算延迟\n\tsuccess := 0\n\tvar delay time.Duration\n\tfor i := 0; i < PingTimes; i++ {\n\t\trequ, err := http.NewRequest(http.MethodHead, URL, nil)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"意外的错误，情报告：\", err)\n\t\t\treturn 0, 0\n\t\t}\n\t\trequ.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\")\n\t\tif i == PingTimes-1 {\n\t\t\trequ.Header.Set(\"Connection\", \"close\")\n\t\t}\n\t\tstartTime := time.Now()\n\t\tresp, err := hc.Do(requ)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tsuccess++\n\t\tio.Copy(io.Discard, resp.Body)\n\t\t_ = resp.Body.Close()\n\t\tduration := time.Since(startTime)\n\t\tdelay += duration\n\n\t}\n\n\treturn success, delay\n\n}\n\nfunc MapColoMap() *sync.Map {\n\tif HttpingCFColo == \"\" {\n\t\treturn nil\n\t}\n\t// 将参数指定的地区三字码转为大写并格式化\n\tcolos := strings.Split(strings.ToUpper(HttpingCFColo), \",\")\n\tcolomap := &sync.Map{}\n\tfor _, colo := range colos {\n\t\tcolomap.Store(colo, colo)\n\t}\n\treturn colomap\n}\n\nfunc (p *Ping) getColo(b string) string {\n\tif b == \"\" {\n\t\treturn \"\"\n\t}\n\t// 正则匹配并返回 机场三字码\n\tout := OutRegexp.FindString(b)\n\n\tif HttpingCFColomap == nil {\n\t\treturn out\n\t}\n\t// 匹配 机场三字码 是否为指定的地区\n\t_, ok := HttpingCFColomap.Load(out)\n\tif ok {\n\t\treturn out\n\t}\n\n\treturn \"\"\n}\n"
  },
  {
    "path": "task/ip.go",
    "content": "package task\n\nimport (\n\t\"bufio\"\n\t\"log\"\n\t\"math/rand\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst defaultInputFile = \"ip.txt\"\n\nvar (\n\t// TestAll test all ip\n\tTestAll = false\n\t// IPFile is the filename of IP Rangs\n\tIPFile = defaultInputFile\n\tIPText string\n)\n\nfunc InitRandSeed() {\n\trand.Seed(time.Now().UnixNano())\n}\n\nfunc isIPv4(ip string) bool {\n\treturn strings.Contains(ip, \".\")\n}\n\nfunc randIPEndWith(num byte) byte {\n\tif num == 0 { // 对于 /32 这种单独的 IP\n\t\treturn byte(0)\n\t}\n\treturn byte(rand.Intn(int(num)))\n}\n\ntype IPRanges struct {\n\tips     []*net.IPAddr\n\tmask    string\n\tfirstIP net.IP\n\tipNet   *net.IPNet\n}\n\nfunc newIPRanges() *IPRanges {\n\treturn &IPRanges{\n\t\tips: make([]*net.IPAddr, 0),\n\t}\n}\n\n// 如果是单独 IP 则加上子网掩码，反之则获取子网掩码(r.mask)\nfunc (r *IPRanges) fixIP(ip string) string {\n\t// 如果不含有 '/' 则代表不是 IP 段，而是一个单独的 IP，因此需要加上 /32 /128 子网掩码\n\tif i := strings.IndexByte(ip, '/'); i < 0 {\n\t\tif isIPv4(ip) {\n\t\t\tr.mask = \"/32\"\n\t\t} else {\n\t\t\tr.mask = \"/128\"\n\t\t}\n\t\tip += r.mask\n\t} else {\n\t\tr.mask = ip[i:]\n\t}\n\treturn ip\n}\n\n// 解析 IP 段，获得 IP、IP 范围、子网掩码\nfunc (r *IPRanges) parseCIDR(ip string) {\n\tvar err error\n\tif r.firstIP, r.ipNet, err = net.ParseCIDR(r.fixIP(ip)); err != nil {\n\t\tlog.Fatalln(\"ParseCIDR err\", err)\n\t}\n}\n\nfunc (r *IPRanges) appendIPv4(d byte) {\n\tr.appendIP(net.IPv4(r.firstIP[12], r.firstIP[13], r.firstIP[14], d))\n}\n\nfunc (r *IPRanges) appendIP(ip net.IP) {\n\tr.ips = append(r.ips, &net.IPAddr{IP: ip})\n}\n\n// 返回第四段 ip 的最小值及可用数目\nfunc (r *IPRanges) getIPRange() (minIP, hosts byte) {\n\tminIP = r.firstIP[15] & r.ipNet.Mask[3] // IP 第四段最小值\n\n\t// 根据子网掩码获取主机数量\n\tm := net.IPv4Mask(255, 255, 255, 255)\n\tfor i, v := range r.ipNet.Mask {\n\t\tm[i] ^= v\n\t}\n\ttotal, _ := strconv.ParseInt(m.String(), 16, 32) // 总可用 IP 数\n\tif total > 255 {                                 // 矫正 第四段 可用 IP 数\n\t\thosts = 255\n\t\treturn\n\t}\n\thosts = byte(total)\n\treturn\n}\n\nfunc (r *IPRanges) chooseIPv4() {\n\tif r.mask == \"/32\" { // 单个 IP 则无需随机，直接加入自身即可\n\t\tr.appendIP(r.firstIP)\n\t} else {\n\t\tminIP, hosts := r.getIPRange()    // 返回第四段 IP 的最小值及可用数目\n\t\tfor r.ipNet.Contains(r.firstIP) { // 只要该 IP 没有超出 IP 网段范围，就继续循环随机\n\t\t\tif TestAll { // 如果是测速全部 IP\n\t\t\t\tfor i := 0; i <= int(hosts); i++ { // 遍历 IP 最后一段最小值到最大值\n\t\t\t\t\tr.appendIPv4(byte(i) + minIP)\n\t\t\t\t}\n\t\t\t} else { // 随机 IP 的最后一段 0.0.0.X\n\t\t\t\tr.appendIPv4(minIP + randIPEndWith(hosts))\n\t\t\t}\n\t\t\tr.firstIP[14]++ // 0.0.(X+1).X\n\t\t\tif r.firstIP[14] == 0 {\n\t\t\t\tr.firstIP[13]++ // 0.(X+1).X.X\n\t\t\t\tif r.firstIP[13] == 0 {\n\t\t\t\t\tr.firstIP[12]++ // (X+1).X.X.X\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (r *IPRanges) chooseIPv6() {\n\tif r.mask == \"/128\" { // 单个 IP 则无需随机，直接加入自身即可\n\t\tr.appendIP(r.firstIP)\n\t} else {\n\t\tvar tempIP uint8                  // 临时变量，用于记录前一位的值\n\t\tfor r.ipNet.Contains(r.firstIP) { // 只要该 IP 没有超出 IP 网段范围，就继续循环随机\n\t\t\tr.firstIP[15] = randIPEndWith(255) // 随机 IP 的最后一段\n\t\t\tr.firstIP[14] = randIPEndWith(255) // 随机 IP 的最后一段\n\n\t\t\ttargetIP := make([]byte, len(r.firstIP))\n\t\t\tcopy(targetIP, r.firstIP)\n\t\t\tr.appendIP(targetIP) // 加入 IP 地址池\n\n\t\t\tfor i := 13; i >= 0; i-- { // 从倒数第三位开始往前随机\n\t\t\t\ttempIP = r.firstIP[i]              // 保存前一位的值\n\t\t\t\tr.firstIP[i] += randIPEndWith(255) // 随机 0~255，加到当前位上\n\t\t\t\tif r.firstIP[i] >= tempIP {        // 如果当前位的值大于等于前一位的值，说明随机成功了，可以退出该循环\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc loadIPRanges() []*net.IPAddr {\n\tranges := newIPRanges()\n\tif IPText != \"\" { // 从参数中获取 IP 段数据\n\t\tIPs := strings.Split(IPText, \",\") // 以逗号分隔为数组并循环遍历\n\t\tfor _, IP := range IPs {\n\t\t\tIP = strings.TrimSpace(IP) // 去除首尾的空白字符（空格、制表符、换行符等）\n\t\t\tif IP == \"\" {              // 跳过空的（即开头、结尾或连续多个 ,, 的情况）\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tranges.parseCIDR(IP) // 解析 IP 段，获得 IP、IP 范围、子网掩码\n\t\t\tif isIPv4(IP) {      // 生成要测速的所有 IPv4 / IPv6 地址（单个/随机/全部）\n\t\t\t\tranges.chooseIPv4()\n\t\t\t} else {\n\t\t\t\tranges.chooseIPv6()\n\t\t\t}\n\t\t}\n\t} else { // 从文件中获取 IP 段数据\n\t\tif IPFile == \"\" {\n\t\t\tIPFile = defaultInputFile\n\t\t}\n\t\tfile, err := os.Open(IPFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer file.Close()\n\t\tscanner := bufio.NewScanner(file)\n\t\tfor scanner.Scan() { // 循环遍历文件每一行\n\t\t\tline := strings.TrimSpace(scanner.Text()) // 去除首尾的空白字符（空格、制表符、换行符等）\n\t\t\tif line == \"\" {                           // 跳过空行\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tranges.parseCIDR(line) // 解析 IP 段，获得 IP、IP 范围、子网掩码\n\t\t\tif isIPv4(line) {      // 生成要测速的所有 IPv4 / IPv6 地址（单个/随机/全部）\n\t\t\t\tranges.chooseIPv4()\n\t\t\t} else {\n\t\t\t\tranges.chooseIPv6()\n\t\t\t}\n\t\t}\n\t}\n\treturn ranges.ips\n}\n"
  },
  {
    "path": "task/tcping.go",
    "content": "package task\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"sort\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/XIU2/CloudflareSpeedTest/utils\"\n)\n\nconst (\n\ttcpConnectTimeout = time.Second * 1\n\tmaxRoutine        = 1000\n\tdefaultRoutines   = 200\n\tdefaultPort       = 443\n\tdefaultPingTimes  = 4\n)\n\nvar (\n\tRoutines      = defaultRoutines\n\tTCPPort   int = defaultPort\n\tPingTimes int = defaultPingTimes\n)\n\ntype Ping struct {\n\twg      *sync.WaitGroup\n\tm       *sync.Mutex\n\tips     []*net.IPAddr\n\tcsv     utils.PingDelaySet\n\tcontrol chan bool\n\tbar     *utils.Bar\n}\n\nfunc checkPingDefault() {\n\tif Routines <= 0 {\n\t\tRoutines = defaultRoutines\n\t}\n\tif TCPPort <= 0 || TCPPort >= 65535 {\n\t\tTCPPort = defaultPort\n\t}\n\tif PingTimes <= 0 {\n\t\tPingTimes = defaultPingTimes\n\t}\n}\n\nfunc NewPing() *Ping {\n\tcheckPingDefault()\n\tips := loadIPRanges()\n\treturn &Ping{\n\t\twg:      &sync.WaitGroup{},\n\t\tm:       &sync.Mutex{},\n\t\tips:     ips,\n\t\tcsv:     make(utils.PingDelaySet, 0),\n\t\tcontrol: make(chan bool, Routines),\n\t\tbar:     utils.NewBar(len(ips), \"可用:\", \"\"),\n\t}\n}\n\nfunc (p *Ping) Run() utils.PingDelaySet {\n\tif len(p.ips) == 0 {\n\t\treturn p.csv\n\t}\n\tif Httping {\n\t\tfmt.Printf(\"开始延迟测速（模式：HTTP, 端口：%d, 范围：%v ~ %v ms, 丢包：%.2f)\\n\", TCPPort, utils.InputMinDelay.Milliseconds(), utils.InputMaxDelay.Milliseconds(), utils.InputMaxLossRate)\n\t} else {\n\t\tfmt.Printf(\"开始延迟测速（模式：TCP, 端口：%d, 范围：%v ~ %v ms, 丢包：%.2f)\\n\", TCPPort, utils.InputMinDelay.Milliseconds(), utils.InputMaxDelay.Milliseconds(), utils.InputMaxLossRate)\n\t}\n\tfor _, ip := range p.ips {\n\t\tp.wg.Add(1)\n\t\tp.control <- false\n\t\tgo p.start(ip)\n\t}\n\tp.wg.Wait()\n\tp.bar.Done()\n\tsort.Sort(p.csv)\n\treturn p.csv\n}\n\nfunc (p *Ping) start(ip *net.IPAddr) {\n\tdefer p.wg.Done()\n\tp.tcpingHandler(ip)\n\t<-p.control\n}\n\n// bool connectionSucceed float32 time\nfunc (p *Ping) tcping(ip *net.IPAddr) (bool, time.Duration) {\n\tstartTime := time.Now()\n\tvar fullAddress string\n\tif isIPv4(ip.String()) {\n\t\tfullAddress = fmt.Sprintf(\"%s:%d\", ip.String(), TCPPort)\n\t} else {\n\t\tfullAddress = fmt.Sprintf(\"[%s]:%d\", ip.String(), TCPPort)\n\t}\n\tconn, err := net.DialTimeout(\"tcp\", fullAddress, tcpConnectTimeout)\n\tif err != nil {\n\t\treturn false, 0\n\t}\n\tdefer conn.Close()\n\tduration := time.Since(startTime)\n\treturn true, duration\n\n}\n\n// pingReceived pingTotalTime\nfunc (p *Ping) checkConnection(ip *net.IPAddr) (recv int, totalDelay time.Duration) {\n\tif Httping {\n\t\trecv, totalDelay = p.httping(ip)\n\t\treturn\n\t}\n\tfor i := 0; i < PingTimes; i++ {\n\t\tif ok, delay := p.tcping(ip); ok {\n\t\t\trecv++\n\t\t\ttotalDelay += delay\n\t\t}\n\t}\n\treturn\n}\n\nfunc (p *Ping) appendIPData(data *utils.PingData) {\n\tp.m.Lock()\n\tdefer p.m.Unlock()\n\tp.csv = append(p.csv, utils.CloudflareIPData{\n\t\tPingData: data,\n\t})\n}\n\n// handle tcping\nfunc (p *Ping) tcpingHandler(ip *net.IPAddr) {\n\trecv, totalDlay := p.checkConnection(ip)\n\tnowAble := len(p.csv)\n\tif recv != 0 {\n\t\tnowAble++\n\t}\n\tp.bar.Grow(1, strconv.Itoa(nowAble))\n\tif recv == 0 {\n\t\treturn\n\t}\n\tdata := &utils.PingData{\n\t\tIP:       ip,\n\t\tSended:   PingTimes,\n\t\tReceived: recv,\n\t\tDelay:    totalDlay / time.Duration(recv),\n\t}\n\tp.appendIPData(data)\n}\n"
  },
  {
    "path": "trojan_workers/_worker.js",
    "content": "// src/worker.js\nimport { connect } from \"cloudflare:sockets\";\nlet sha224Password = '7e89e622d89becc4299c2d74494b9fb15759f2b0ff47b20eeae867e2';\nlet pwd = 'abc123333'\nconst proxyIPs = [\"cdn.xn--b6gac.eu.org\"]; //workers.cloudflare.cyou bestproxy.onecf.eu.org cdn-all.xn--b6gac.eu.org cdn.xn--b6gac.eu.org\nlet proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)];\nlet defaultAddr='www.visa.com.sg'\n\nif (!isValidSHA224(sha224Password)) {\n    throw new Error('sha224Password is not valid');\n}\n   \nfunction getprotocol() {\n\tlet matter = ['t','r','o','j','a','n']\n\tlet result=''\n\tfor (let i = 0; i < matter.length; i++) {\n\t  result += matter[i];\n\t}\n\treturn result;\n  }\n\n\n  export default  {\n    /**\n     * @param {import(\"@cloudflare/workers-types\").Request} request\n     * @param {{SHA224PASS: string, PROXYIP: string}} env\n     * @param {import(\"@cloudflare/workers-types\").ExecutionContext} ctx\n     * @returns {Promise<Response>}\n     */\n    async fetch(request, env, ctx) {\n        try {\n            proxyIP = env.PROXYIP || proxyIP;\n            pwd  = env.PASSWORD || pwd\n            if ('PASSWORD' in env) {\n                sha224Password = sha256.sha224(env.PASSWORD)\n             }\n            console.log('pass:'+sha224Password)\n            const upgradeHeader = request.headers.get(\"Upgrade\");\n            if (!upgradeHeader || upgradeHeader !== \"websocket\") {\n                const url = new URL(request.url);\n                switch (url.pathname) {\n                    case `/${pwd}`:{\n                        const host = request.headers.get('Host');\n                        if ( 'PROXYIP' in env) {\n                          return new Response(getprotocol() + `://` + pwd + `@${host}:443/?type=ws&host=${host}&security=tls#${host}`, {\n                            status: 200,\n                            headers: {\n                                \"Content-Type\": \"text/plain;charset=utf-8\",\n                            }\n                        })\n                        }else{\n                          return new Response(getprotocol() + `://` + pwd + `@${defaultAddr}:443/?type=ws&host=${host}&security=tls#${host}`, {\n                            status: 200,\n                            headers: {\n                                \"Content-Type\": \"text/plain;charset=utf-8\",\n                            }\n                        })\n                        }\n                       \n                      };\n                    default:\n                        return new Response(\"404 Not found\", { status: 404 });\n                }\n            } else {\n                return await trojanOverWSHandler(request);\n            }\n        } catch (err) {\n            let e = err;\n            return new Response(e.toString());\n        }\n    }\n};\n\nasync function trojanOverWSHandler(request) {\n    const webSocketPair = new WebSocketPair();\n    const [client, webSocket] = Object.values(webSocketPair);\n    webSocket.accept();\n    let address = \"\";\n    let portWithRandomLog = \"\";\n    const log = (info, event) => {\n        console.log(`[${address}:${portWithRandomLog}] ${info}`, event || \"\");\n    };\n    const earlyDataHeader = request.headers.get(\"sec-websocket-protocol\") || \"\";\n    const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);\n    let remoteSocketWapper = {\n        value: null\n    };\n    let udpStreamWrite = null;\n    readableWebSocketStream.pipeTo(new WritableStream({\n        async write(chunk, controller) {\n            if (udpStreamWrite) {\n                return udpStreamWrite(chunk);\n            }\n            if (remoteSocketWapper.value) {\n                const writer = remoteSocketWapper.value.writable.getWriter();\n                await writer.write(chunk);\n                writer.releaseLock();\n                return;\n            }\n            const {\n                hasError,\n                message,\n                portRemote = 443,\n                addressRemote = \"\",\n                rawClientData\n            } = await parseTrojanHeader(chunk);\n            address = addressRemote;\n            portWithRandomLog = `${portRemote}--${Math.random()} tcp`;\n            if (hasError) {\n                throw new Error(message);\n                return;\n            }\n            handleTCPOutBound(remoteSocketWapper, addressRemote, portRemote, rawClientData, webSocket, log);\n        },\n        close() {\n            log(`readableWebSocketStream is closed`);\n        },\n        abort(reason) {\n            log(`readableWebSocketStream is aborted`, JSON.stringify(reason));\n        }\n    })).catch((err) => {\n        log(\"readableWebSocketStream pipeTo error\", err);\n    });\n    return new Response(null, {\n        status: 101,\n        // @ts-ignore\n        webSocket: client\n    });\n}\n\nasync function parseTrojanHeader(buffer) {\n    if (buffer.byteLength < 56) {\n        return {\n            hasError: true,\n            message: \"invalid data\"\n        };\n    }\n    let crLfIndex = 56;\n    if (new Uint8Array(buffer.slice(56, 57))[0] !== 0x0d || new Uint8Array(buffer.slice(57, 58))[0] !== 0x0a) {\n        return {\n            hasError: true,\n            message: \"invalid header format (missing CR LF)\"\n        };\n    }\n    const password = new TextDecoder().decode(buffer.slice(0, crLfIndex));\n    if (password !== sha224Password) {\n        return {\n            hasError: true,\n            message: \"invalid password\"\n        };\n    }\n\n    const socks5DataBuffer = buffer.slice(crLfIndex + 2);\n    if (socks5DataBuffer.byteLength < 6) {\n        return {\n            hasError: true,\n            message: \"invalid SOCKS5 request data\"\n        };\n    }\n\n    const view = new DataView(socks5DataBuffer);\n    const cmd = view.getUint8(0);\n    if (cmd !== 1) {\n        return {\n            hasError: true,\n            message: \"unsupported command, only TCP (CONNECT) is allowed\"\n        };\n    }\n\n    const atype = view.getUint8(1);\n    // 0x01: IPv4 address\n    // 0x03: Domain name\n    // 0x04: IPv6 address\n    let addressLength = 0;\n    let addressIndex = 2;\n    let address = \"\";\n    switch (atype) {\n        case 1:\n            addressLength = 4;\n            address = new Uint8Array(\n              socks5DataBuffer.slice(addressIndex, addressIndex + addressLength)\n            ).join(\".\");\n            break;\n        case 3:\n            addressLength = new Uint8Array(\n              socks5DataBuffer.slice(addressIndex, addressIndex + 1)\n            )[0];\n            addressIndex += 1;\n            address = new TextDecoder().decode(\n              socks5DataBuffer.slice(addressIndex, addressIndex + addressLength)\n            );\n            break;\n        case 4:\n            addressLength = 16;\n            const dataView = new DataView(socks5DataBuffer.slice(addressIndex, addressIndex + addressLength));\n            const ipv6 = [];\n            for (let i = 0; i < 8; i++) {\n                ipv6.push(dataView.getUint16(i * 2).toString(16));\n            }\n            address = ipv6.join(\":\");\n            break;\n        default:\n            return {\n                hasError: true,\n                message: `invalid addressType is ${atype}`\n            };\n    }\n\n    if (!address) {\n        return {\n            hasError: true,\n            message: `address is empty, addressType is ${atype}`\n        };\n    }\n\n    const portIndex = addressIndex + addressLength;\n    const portBuffer = socks5DataBuffer.slice(portIndex, portIndex + 2);\n    const portRemote = new DataView(portBuffer).getUint16(0);\n    return {\n        hasError: false,\n        addressRemote: address,\n        portRemote,\n        rawClientData: socks5DataBuffer.slice(portIndex + 4)\n    };\n}\n\nasync function handleTCPOutBound(remoteSocket, addressRemote, portRemote, rawClientData, webSocket, log) {\n    async function connectAndWrite(address, port) {\n        const tcpSocket2 = connect({\n            hostname: address,\n            port\n        });\n        remoteSocket.value = tcpSocket2;\n        log(`connected to ${address}:${port}`);\n        const writer = tcpSocket2.writable.getWriter();\n        await writer.write(rawClientData);\n        writer.releaseLock();\n        return tcpSocket2;\n    }\n    async function retry() {\n        const tcpSocket2 = await connectAndWrite(proxyIP || addressRemote, portRemote);\n        tcpSocket2.closed.catch((error) => {\n            console.log(\"retry tcpSocket closed error\", error);\n        }).finally(() => {\n            safeCloseWebSocket(webSocket);\n        });\n        remoteSocketToWS(tcpSocket2, webSocket, null, log);\n    }\n    const tcpSocket = await connectAndWrite(addressRemote, portRemote);\n    remoteSocketToWS(tcpSocket, webSocket, retry, log);\n}\n\nfunction makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) {\n    let readableStreamCancel = false;\n    const stream = new ReadableStream({\n        start(controller) {\n            webSocketServer.addEventListener(\"message\", (event) => {\n                if (readableStreamCancel) {\n                    return;\n                }\n                const message = event.data;\n                controller.enqueue(message);\n            });\n            webSocketServer.addEventListener(\"close\", () => {\n                safeCloseWebSocket(webSocketServer);\n                if (readableStreamCancel) {\n                    return;\n                }\n                controller.close();\n            });\n            webSocketServer.addEventListener(\"error\", (err) => {\n                log(\"webSocketServer error\");\n                controller.error(err);\n            });\n            const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader);\n            if (error) {\n                controller.error(error);\n            } else if (earlyData) {\n                controller.enqueue(earlyData);\n            }\n        },\n        pull(controller) {},\n        cancel(reason) {\n            if (readableStreamCancel) {\n                return;\n            }\n            log(`readableStream was canceled, due to ${reason}`);\n            readableStreamCancel = true;\n            safeCloseWebSocket(webSocketServer);\n        }\n    });\n    return stream;\n}\n\nasync function remoteSocketToWS(remoteSocket, webSocket, retry, log) {\n    let hasIncomingData = false;\n    await remoteSocket.readable.pipeTo(\n        new WritableStream({\n            start() {},\n            /**\n             *\n             * @param {Uint8Array} chunk\n             * @param {*} controller\n             */\n            async write(chunk, controller) {\n                hasIncomingData = true;\n                if (webSocket.readyState !== WS_READY_STATE_OPEN) {\n                    controller.error(\n                        \"webSocket connection is not open\"\n                    );\n                }\n                webSocket.send(chunk);\n            },\n            close() {\n                log(`remoteSocket.readable is closed, hasIncomingData: ${hasIncomingData}`);\n            },\n            abort(reason) {\n                console.error(\"remoteSocket.readable abort\", reason);\n            }\n        })\n    ).catch((error) => {\n        console.error(\n            `remoteSocketToWS error:`,\n            error.stack || error\n        );\n        safeCloseWebSocket(webSocket);\n    });\n    if (hasIncomingData === false && retry) {\n        log(`retry`);\n        retry();\n    }\n}\n\nfunction isValidSHA224(hash) {\n    const sha224Regex = /^[0-9a-f]{56}$/i;\n    return sha224Regex.test(hash);\n}\n\nfunction base64ToArrayBuffer(base64Str) {\n    if (!base64Str) {\n        return { error: null };\n    }\n    try {\n        base64Str = base64Str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n        const decode = atob(base64Str);\n        const arryBuffer = Uint8Array.from(decode, (c) => c.charCodeAt(0));\n        return { earlyData: arryBuffer.buffer, error: null };\n    } catch (error) {\n        return { error };\n    }\n}\n\nlet WS_READY_STATE_OPEN = 1;\nlet WS_READY_STATE_CLOSING = 2;\n\nfunction safeCloseWebSocket(socket) {\n    try {\n        if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) {\n            socket.close();\n        }\n    } catch (error) {\n        console.error(\"safeCloseWebSocket error\", error);\n    }\n}\n// export {\n//     worker_default as\n//     default\n// };\n//# sourceMappingURL=worker.js.map\n\n\n/**\n * [js-sha256]{@link https://github.com/emn178/js-sha256}\n *\n * @version 0.11.0\n * @author Chen, Yi-Cyuan [emn178@gmail.com]\n * @copyright Chen, Yi-Cyuan 2014-2024\n * @license MIT\n */\n/*jslint bitwise: true */\n(function () {\n    'use strict';\n  \n    var ERROR = 'input is invalid type';\n    var WINDOW = typeof window === 'object';\n    var root = WINDOW ? window : {};\n    if (root.JS_SHA256_NO_WINDOW) {\n      WINDOW = false;\n    }\n    var WEB_WORKER = !WINDOW && typeof self === 'object';\n    var NODE_JS = !root.JS_SHA256_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;\n    if (NODE_JS) {\n      root = global;\n    } else if (WEB_WORKER) {\n      root = self;\n    }\n    var COMMON_JS = !root.JS_SHA256_NO_COMMON_JS && typeof module === 'object' && module.exports;\n    var AMD = typeof define === 'function' && define.amd;\n    var ARRAY_BUFFER = !root.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';\n    var HEX_CHARS = '0123456789abcdef'.split('');\n    var EXTRA = [-2147483648, 8388608, 32768, 128];\n    var SHIFT = [24, 16, 8, 0];\n    var K = [\n      0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n      0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n      0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n      0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n      0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n      0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n      0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n      0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n    ];\n    var OUTPUT_TYPES = ['hex', 'array', 'digest', 'arrayBuffer'];\n  \n    var blocks = [];\n  \n    if (root.JS_SHA256_NO_NODE_JS || !Array.isArray) {\n      Array.isArray = function (obj) {\n        return Object.prototype.toString.call(obj) === '[object Array]';\n      };\n    }\n  \n    if (ARRAY_BUFFER && (root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {\n      ArrayBuffer.isView = function (obj) {\n        return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;\n      };\n    }\n  \n    var createOutputMethod = function (outputType, is224) {\n      return function (message) {\n        return new Sha256(is224, true).update(message)[outputType]();\n      };\n    };\n  \n    var createMethod = function (is224) {\n      var method = createOutputMethod('hex', is224);\n      if (NODE_JS) {\n        method = nodeWrap(method, is224);\n      }\n      method.create = function () {\n        return new Sha256(is224);\n      };\n      method.update = function (message) {\n        return method.create().update(message);\n      };\n      for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n        var type = OUTPUT_TYPES[i];\n        method[type] = createOutputMethod(type, is224);\n      }\n      return method;\n    };\n  \n    var nodeWrap = function (method, is224) {\n      var crypto = require('crypto')\n      var Buffer = require('buffer').Buffer;\n      var algorithm = is224 ? 'sha224' : 'sha256';\n      var bufferFrom;\n      if (Buffer.from && !root.JS_SHA256_NO_BUFFER_FROM) {\n        bufferFrom = Buffer.from;\n      } else {\n        bufferFrom = function (message) {\n          return new Buffer(message);\n        };\n      }\n      var nodeMethod = function (message) {\n        if (typeof message === 'string') {\n          return crypto.createHash(algorithm).update(message, 'utf8').digest('hex');\n        } else {\n          if (message === null || message === undefined) {\n            throw new Error(ERROR);\n          } else if (message.constructor === ArrayBuffer) {\n            message = new Uint8Array(message);\n          }\n        }\n        if (Array.isArray(message) || ArrayBuffer.isView(message) ||\n          message.constructor === Buffer) {\n          return crypto.createHash(algorithm).update(bufferFrom(message)).digest('hex');\n        } else {\n          return method(message);\n        }\n      };\n      return nodeMethod;\n    };\n  \n    var createHmacOutputMethod = function (outputType, is224) {\n      return function (key, message) {\n        return new HmacSha256(key, is224, true).update(message)[outputType]();\n      };\n    };\n  \n    var createHmacMethod = function (is224) {\n      var method = createHmacOutputMethod('hex', is224);\n      method.create = function (key) {\n        return new HmacSha256(key, is224);\n      };\n      method.update = function (key, message) {\n        return method.create(key).update(message);\n      };\n      for (var i = 0; i < OUTPUT_TYPES.length; ++i) {\n        var type = OUTPUT_TYPES[i];\n        method[type] = createHmacOutputMethod(type, is224);\n      }\n      return method;\n    };\n  \n    function Sha256(is224, sharedMemory) {\n      if (sharedMemory) {\n        blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] =\n          blocks[4] = blocks[5] = blocks[6] = blocks[7] =\n          blocks[8] = blocks[9] = blocks[10] = blocks[11] =\n          blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;\n        this.blocks = blocks;\n      } else {\n        this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];\n      }\n  \n      if (is224) {\n        this.h0 = 0xc1059ed8;\n        this.h1 = 0x367cd507;\n        this.h2 = 0x3070dd17;\n        this.h3 = 0xf70e5939;\n        this.h4 = 0xffc00b31;\n        this.h5 = 0x68581511;\n        this.h6 = 0x64f98fa7;\n        this.h7 = 0xbefa4fa4;\n      } else { // 256\n        this.h0 = 0x6a09e667;\n        this.h1 = 0xbb67ae85;\n        this.h2 = 0x3c6ef372;\n        this.h3 = 0xa54ff53a;\n        this.h4 = 0x510e527f;\n        this.h5 = 0x9b05688c;\n        this.h6 = 0x1f83d9ab;\n        this.h7 = 0x5be0cd19;\n      }\n  \n      this.block = this.start = this.bytes = this.hBytes = 0;\n      this.finalized = this.hashed = false;\n      this.first = true;\n      this.is224 = is224;\n    }\n  \n    Sha256.prototype.update = function (message) {\n      if (this.finalized) {\n        return;\n      }\n      var notString, type = typeof message;\n      if (type !== 'string') {\n        if (type === 'object') {\n          if (message === null) {\n            throw new Error(ERROR);\n          } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {\n            message = new Uint8Array(message);\n          } else if (!Array.isArray(message)) {\n            if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {\n              throw new Error(ERROR);\n            }\n          }\n        } else {\n          throw new Error(ERROR);\n        }\n        notString = true;\n      }\n      var code, index = 0, i, length = message.length, blocks = this.blocks;\n      while (index < length) {\n        if (this.hashed) {\n          this.hashed = false;\n          blocks[0] = this.block;\n          this.block = blocks[16] = blocks[1] = blocks[2] = blocks[3] =\n            blocks[4] = blocks[5] = blocks[6] = blocks[7] =\n            blocks[8] = blocks[9] = blocks[10] = blocks[11] =\n            blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;\n        }\n  \n        if (notString) {\n          for (i = this.start; index < length && i < 64; ++index) {\n            blocks[i >>> 2] |= message[index] << SHIFT[i++ & 3];\n          }\n        } else {\n          for (i = this.start; index < length && i < 64; ++index) {\n            code = message.charCodeAt(index);\n            if (code < 0x80) {\n              blocks[i >>> 2] |= code << SHIFT[i++ & 3];\n            } else if (code < 0x800) {\n              blocks[i >>> 2] |= (0xc0 | (code >>> 6)) << SHIFT[i++ & 3];\n              blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n            } else if (code < 0xd800 || code >= 0xe000) {\n              blocks[i >>> 2] |= (0xe0 | (code >>> 12)) << SHIFT[i++ & 3];\n              blocks[i >>> 2] |= (0x80 | ((code >>> 6) & 0x3f)) << SHIFT[i++ & 3];\n              blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n            } else {\n              code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));\n              blocks[i >>> 2] |= (0xf0 | (code >>> 18)) << SHIFT[i++ & 3];\n              blocks[i >>> 2] |= (0x80 | ((code >>> 12) & 0x3f)) << SHIFT[i++ & 3];\n              blocks[i >>> 2] |= (0x80 | ((code >>> 6) & 0x3f)) << SHIFT[i++ & 3];\n              blocks[i >>> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];\n            }\n          }\n        }\n  \n        this.lastByteIndex = i;\n        this.bytes += i - this.start;\n        if (i >= 64) {\n          this.block = blocks[16];\n          this.start = i - 64;\n          this.hash();\n          this.hashed = true;\n        } else {\n          this.start = i;\n        }\n      }\n      if (this.bytes > 4294967295) {\n        this.hBytes += this.bytes / 4294967296 << 0;\n        this.bytes = this.bytes % 4294967296;\n      }\n      return this;\n    };\n  \n    Sha256.prototype.finalize = function () {\n      if (this.finalized) {\n        return;\n      }\n      this.finalized = true;\n      var blocks = this.blocks, i = this.lastByteIndex;\n      blocks[16] = this.block;\n      blocks[i >>> 2] |= EXTRA[i & 3];\n      this.block = blocks[16];\n      if (i >= 56) {\n        if (!this.hashed) {\n          this.hash();\n        }\n        blocks[0] = this.block;\n        blocks[16] = blocks[1] = blocks[2] = blocks[3] =\n          blocks[4] = blocks[5] = blocks[6] = blocks[7] =\n          blocks[8] = blocks[9] = blocks[10] = blocks[11] =\n          blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;\n      }\n      blocks[14] = this.hBytes << 3 | this.bytes >>> 29;\n      blocks[15] = this.bytes << 3;\n      this.hash();\n    };\n  \n    Sha256.prototype.hash = function () {\n      var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6,\n        h = this.h7, blocks = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc;\n  \n      for (j = 16; j < 64; ++j) {\n        // rightrotate\n        t1 = blocks[j - 15];\n        s0 = ((t1 >>> 7) | (t1 << 25)) ^ ((t1 >>> 18) | (t1 << 14)) ^ (t1 >>> 3);\n        t1 = blocks[j - 2];\n        s1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10);\n        blocks[j] = blocks[j - 16] + s0 + blocks[j - 7] + s1 << 0;\n      }\n  \n      bc = b & c;\n      for (j = 0; j < 64; j += 4) {\n        if (this.first) {\n          if (this.is224) {\n            ab = 300032;\n            t1 = blocks[0] - 1413257819;\n            h = t1 - 150054599 << 0;\n            d = t1 + 24177077 << 0;\n          } else {\n            ab = 704751109;\n            t1 = blocks[0] - 210244248;\n            h = t1 - 1521486534 << 0;\n            d = t1 + 143694565 << 0;\n          }\n          this.first = false;\n        } else {\n          s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));\n          s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));\n          ab = a & b;\n          maj = ab ^ (a & c) ^ bc;\n          ch = (e & f) ^ (~e & g);\n          t1 = h + s1 + ch + K[j] + blocks[j];\n          t2 = s0 + maj;\n          h = d + t1 << 0;\n          d = t1 + t2 << 0;\n        }\n        s0 = ((d >>> 2) | (d << 30)) ^ ((d >>> 13) | (d << 19)) ^ ((d >>> 22) | (d << 10));\n        s1 = ((h >>> 6) | (h << 26)) ^ ((h >>> 11) | (h << 21)) ^ ((h >>> 25) | (h << 7));\n        da = d & a;\n        maj = da ^ (d & b) ^ ab;\n        ch = (h & e) ^ (~h & f);\n        t1 = g + s1 + ch + K[j + 1] + blocks[j + 1];\n        t2 = s0 + maj;\n        g = c + t1 << 0;\n        c = t1 + t2 << 0;\n        s0 = ((c >>> 2) | (c << 30)) ^ ((c >>> 13) | (c << 19)) ^ ((c >>> 22) | (c << 10));\n        s1 = ((g >>> 6) | (g << 26)) ^ ((g >>> 11) | (g << 21)) ^ ((g >>> 25) | (g << 7));\n        cd = c & d;\n        maj = cd ^ (c & a) ^ da;\n        ch = (g & h) ^ (~g & e);\n        t1 = f + s1 + ch + K[j + 2] + blocks[j + 2];\n        t2 = s0 + maj;\n        f = b + t1 << 0;\n        b = t1 + t2 << 0;\n        s0 = ((b >>> 2) | (b << 30)) ^ ((b >>> 13) | (b << 19)) ^ ((b >>> 22) | (b << 10));\n        s1 = ((f >>> 6) | (f << 26)) ^ ((f >>> 11) | (f << 21)) ^ ((f >>> 25) | (f << 7));\n        bc = b & c;\n        maj = bc ^ (b & d) ^ cd;\n        ch = (f & g) ^ (~f & h);\n        t1 = e + s1 + ch + K[j + 3] + blocks[j + 3];\n        t2 = s0 + maj;\n        e = a + t1 << 0;\n        a = t1 + t2 << 0;\n        this.chromeBugWorkAround = true;\n      }\n  \n      this.h0 = this.h0 + a << 0;\n      this.h1 = this.h1 + b << 0;\n      this.h2 = this.h2 + c << 0;\n      this.h3 = this.h3 + d << 0;\n      this.h4 = this.h4 + e << 0;\n      this.h5 = this.h5 + f << 0;\n      this.h6 = this.h6 + g << 0;\n      this.h7 = this.h7 + h << 0;\n    };\n  \n    Sha256.prototype.hex = function () {\n      this.finalize();\n  \n      var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5,\n        h6 = this.h6, h7 = this.h7;\n  \n      var hex = HEX_CHARS[(h0 >>> 28) & 0x0F] + HEX_CHARS[(h0 >>> 24) & 0x0F] +\n        HEX_CHARS[(h0 >>> 20) & 0x0F] + HEX_CHARS[(h0 >>> 16) & 0x0F] +\n        HEX_CHARS[(h0 >>> 12) & 0x0F] + HEX_CHARS[(h0 >>> 8) & 0x0F] +\n        HEX_CHARS[(h0 >>> 4) & 0x0F] + HEX_CHARS[h0 & 0x0F] +\n        HEX_CHARS[(h1 >>> 28) & 0x0F] + HEX_CHARS[(h1 >>> 24) & 0x0F] +\n        HEX_CHARS[(h1 >>> 20) & 0x0F] + HEX_CHARS[(h1 >>> 16) & 0x0F] +\n        HEX_CHARS[(h1 >>> 12) & 0x0F] + HEX_CHARS[(h1 >>> 8) & 0x0F] +\n        HEX_CHARS[(h1 >>> 4) & 0x0F] + HEX_CHARS[h1 & 0x0F] +\n        HEX_CHARS[(h2 >>> 28) & 0x0F] + HEX_CHARS[(h2 >>> 24) & 0x0F] +\n        HEX_CHARS[(h2 >>> 20) & 0x0F] + HEX_CHARS[(h2 >>> 16) & 0x0F] +\n        HEX_CHARS[(h2 >>> 12) & 0x0F] + HEX_CHARS[(h2 >>> 8) & 0x0F] +\n        HEX_CHARS[(h2 >>> 4) & 0x0F] + HEX_CHARS[h2 & 0x0F] +\n        HEX_CHARS[(h3 >>> 28) & 0x0F] + HEX_CHARS[(h3 >>> 24) & 0x0F] +\n        HEX_CHARS[(h3 >>> 20) & 0x0F] + HEX_CHARS[(h3 >>> 16) & 0x0F] +\n        HEX_CHARS[(h3 >>> 12) & 0x0F] + HEX_CHARS[(h3 >>> 8) & 0x0F] +\n        HEX_CHARS[(h3 >>> 4) & 0x0F] + HEX_CHARS[h3 & 0x0F] +\n        HEX_CHARS[(h4 >>> 28) & 0x0F] + HEX_CHARS[(h4 >>> 24) & 0x0F] +\n        HEX_CHARS[(h4 >>> 20) & 0x0F] + HEX_CHARS[(h4 >>> 16) & 0x0F] +\n        HEX_CHARS[(h4 >>> 12) & 0x0F] + HEX_CHARS[(h4 >>> 8) & 0x0F] +\n        HEX_CHARS[(h4 >>> 4) & 0x0F] + HEX_CHARS[h4 & 0x0F] +\n        HEX_CHARS[(h5 >>> 28) & 0x0F] + HEX_CHARS[(h5 >>> 24) & 0x0F] +\n        HEX_CHARS[(h5 >>> 20) & 0x0F] + HEX_CHARS[(h5 >>> 16) & 0x0F] +\n        HEX_CHARS[(h5 >>> 12) & 0x0F] + HEX_CHARS[(h5 >>> 8) & 0x0F] +\n        HEX_CHARS[(h5 >>> 4) & 0x0F] + HEX_CHARS[h5 & 0x0F] +\n        HEX_CHARS[(h6 >>> 28) & 0x0F] + HEX_CHARS[(h6 >>> 24) & 0x0F] +\n        HEX_CHARS[(h6 >>> 20) & 0x0F] + HEX_CHARS[(h6 >>> 16) & 0x0F] +\n        HEX_CHARS[(h6 >>> 12) & 0x0F] + HEX_CHARS[(h6 >>> 8) & 0x0F] +\n        HEX_CHARS[(h6 >>> 4) & 0x0F] + HEX_CHARS[h6 & 0x0F];\n      if (!this.is224) {\n        hex += HEX_CHARS[(h7 >>> 28) & 0x0F] + HEX_CHARS[(h7 >>> 24) & 0x0F] +\n          HEX_CHARS[(h7 >>> 20) & 0x0F] + HEX_CHARS[(h7 >>> 16) & 0x0F] +\n          HEX_CHARS[(h7 >>> 12) & 0x0F] + HEX_CHARS[(h7 >>> 8) & 0x0F] +\n          HEX_CHARS[(h7 >>> 4) & 0x0F] + HEX_CHARS[h7 & 0x0F];\n      }\n      return hex;\n    };\n  \n    Sha256.prototype.toString = Sha256.prototype.hex;\n  \n    Sha256.prototype.digest = function () {\n      this.finalize();\n  \n      var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5,\n        h6 = this.h6, h7 = this.h7;\n  \n      var arr = [\n        (h0 >>> 24) & 0xFF, (h0 >>> 16) & 0xFF, (h0 >>> 8) & 0xFF, h0 & 0xFF,\n        (h1 >>> 24) & 0xFF, (h1 >>> 16) & 0xFF, (h1 >>> 8) & 0xFF, h1 & 0xFF,\n        (h2 >>> 24) & 0xFF, (h2 >>> 16) & 0xFF, (h2 >>> 8) & 0xFF, h2 & 0xFF,\n        (h3 >>> 24) & 0xFF, (h3 >>> 16) & 0xFF, (h3 >>> 8) & 0xFF, h3 & 0xFF,\n        (h4 >>> 24) & 0xFF, (h4 >>> 16) & 0xFF, (h4 >>> 8) & 0xFF, h4 & 0xFF,\n        (h5 >>> 24) & 0xFF, (h5 >>> 16) & 0xFF, (h5 >>> 8) & 0xFF, h5 & 0xFF,\n        (h6 >>> 24) & 0xFF, (h6 >>> 16) & 0xFF, (h6 >>> 8) & 0xFF, h6 & 0xFF\n      ];\n      if (!this.is224) {\n        arr.push((h7 >>> 24) & 0xFF, (h7 >>> 16) & 0xFF, (h7 >>> 8) & 0xFF, h7 & 0xFF);\n      }\n      return arr;\n    };\n  \n    Sha256.prototype.array = Sha256.prototype.digest;\n  \n    Sha256.prototype.arrayBuffer = function () {\n      this.finalize();\n  \n      var buffer = new ArrayBuffer(this.is224 ? 28 : 32);\n      var dataView = new DataView(buffer);\n      dataView.setUint32(0, this.h0);\n      dataView.setUint32(4, this.h1);\n      dataView.setUint32(8, this.h2);\n      dataView.setUint32(12, this.h3);\n      dataView.setUint32(16, this.h4);\n      dataView.setUint32(20, this.h5);\n      dataView.setUint32(24, this.h6);\n      if (!this.is224) {\n        dataView.setUint32(28, this.h7);\n      }\n      return buffer;\n    };\n  \n    function HmacSha256(key, is224, sharedMemory) {\n      var i, type = typeof key;\n      if (type === 'string') {\n        var bytes = [], length = key.length, index = 0, code;\n        for (i = 0; i < length; ++i) {\n          code = key.charCodeAt(i);\n          if (code < 0x80) {\n            bytes[index++] = code;\n          } else if (code < 0x800) {\n            bytes[index++] = (0xc0 | (code >>> 6));\n            bytes[index++] = (0x80 | (code & 0x3f));\n          } else if (code < 0xd800 || code >= 0xe000) {\n            bytes[index++] = (0xe0 | (code >>> 12));\n            bytes[index++] = (0x80 | ((code >>> 6) & 0x3f));\n            bytes[index++] = (0x80 | (code & 0x3f));\n          } else {\n            code = 0x10000 + (((code & 0x3ff) << 10) | (key.charCodeAt(++i) & 0x3ff));\n            bytes[index++] = (0xf0 | (code >>> 18));\n            bytes[index++] = (0x80 | ((code >>> 12) & 0x3f));\n            bytes[index++] = (0x80 | ((code >>> 6) & 0x3f));\n            bytes[index++] = (0x80 | (code & 0x3f));\n          }\n        }\n        key = bytes;\n      } else {\n        if (type === 'object') {\n          if (key === null) {\n            throw new Error(ERROR);\n          } else if (ARRAY_BUFFER && key.constructor === ArrayBuffer) {\n            key = new Uint8Array(key);\n          } else if (!Array.isArray(key)) {\n            if (!ARRAY_BUFFER || !ArrayBuffer.isView(key)) {\n              throw new Error(ERROR);\n            }\n          }\n        } else {\n          throw new Error(ERROR);\n        }\n      }\n  \n      if (key.length > 64) {\n        key = (new Sha256(is224, true)).update(key).array();\n      }\n  \n      var oKeyPad = [], iKeyPad = [];\n      for (i = 0; i < 64; ++i) {\n        var b = key[i] || 0;\n        oKeyPad[i] = 0x5c ^ b;\n        iKeyPad[i] = 0x36 ^ b;\n      }\n  \n      Sha256.call(this, is224, sharedMemory);\n  \n      this.update(iKeyPad);\n      this.oKeyPad = oKeyPad;\n      this.inner = true;\n      this.sharedMemory = sharedMemory;\n    }\n    HmacSha256.prototype = new Sha256();\n  \n    HmacSha256.prototype.finalize = function () {\n      Sha256.prototype.finalize.call(this);\n      if (this.inner) {\n        this.inner = false;\n        var innerHash = this.array();\n        Sha256.call(this, this.is224, this.sharedMemory);\n        this.update(this.oKeyPad);\n        this.update(innerHash);\n        Sha256.prototype.finalize.call(this);\n      }\n    };\n  \n    var exports = createMethod();\n    exports.sha256 = exports;\n    exports.sha224 = createMethod(true);\n    exports.sha256.hmac = createHmacMethod();\n    exports.sha224.hmac = createHmacMethod(true);\n  \n    if (COMMON_JS) {\n      module.exports = exports;\n    } else {\n      root.sha256 = exports.sha256;\n      root.sha224 = exports.sha224;\n      if (AMD) {\n        define(function () {\n          return exports;\n        });\n      }\n    }\n  })();\n"
  },
  {
    "path": "utils/csv.go",
    "content": "package utils\n\nimport (\n\t\"encoding/csv\"\n\t\"fmt\"\n\t\"golang.org/x/text/encoding/simplifiedchinese\"\n\t\"golang.org/x/text/transform\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"time\"\n)\n\nconst (\n\tdefaultOutput         = \"result.csv\"\n\tmaxDelay              = 9999 * time.Millisecond\n\tminDelay              = 0 * time.Millisecond\n\tmaxLossRate   float32 = 1.0\n)\n\nvar (\n\tInputMaxDelay    = maxDelay\n\tInputMinDelay    = minDelay\n\tInputMaxLossRate = maxLossRate\n\tOutput           = defaultOutput\n\tPrintNum         = 10\n)\n\n// 是否打印测试结果\nfunc NoPrintResult() bool {\n\treturn PrintNum == 0\n}\n\n// 是否输出到文件\nfunc noOutput() bool {\n\treturn Output == \"\" || Output == \" \"\n}\n\ntype PingData struct {\n\tIP       *net.IPAddr\n\tSended   int\n\tReceived int\n\tDelay    time.Duration\n}\n\ntype CloudflareIPData struct {\n\t*PingData\n\tlossRate      float32\n\tDownloadSpeed float64\n\tCountry       string\n}\n\n// 计算丢包率\nfunc (cf *CloudflareIPData) getLossRate() float32 {\n\tif cf.lossRate == 0 {\n\t\tpingLost := cf.Sended - cf.Received\n\t\tcf.lossRate = float32(pingLost) / float32(cf.Sended)\n\t}\n\treturn cf.lossRate\n}\n\nfunc (cf *CloudflareIPData) toString() []string {\n\tresult := make([]string, 6)\n\tresult[0] = cf.IP.String()\n\tresult[1] = strconv.Itoa(cf.Sended)\n\tresult[2] = strconv.Itoa(cf.Received)\n\tresult[3] = strconv.FormatFloat(float64(cf.getLossRate()), 'f', 2, 32)\n\tresult[4] = strconv.FormatFloat(cf.Delay.Seconds()*1000, 'f', 2, 32)\n\tresult[5] = strconv.FormatFloat(cf.DownloadSpeed/1024/1024, 'f', 2, 32)\n\treturn result\n}\n\nfunc WriteFile(filename string, data []CloudflareIPData) {\n\tfp, err := os.Create(filename)\n\tif err != nil {\n\t\tlog.Fatalf(\"创建文件[%s]失败：%v\", filename, err)\n\t\treturn\n\t}\n\tdefer fp.Close()\n\tw := csv.NewWriter(fp) //创建一个新的写入文件流\n\t_ = w.Write([]string{\"IP 地址\", \"已发送\", \"已接收\", \"丢包率(%)\", \"延迟(ms)\", \"下载速度(Mbps)\"})\n\t_ = w.WriteAll(convertToString(data))\n\tw.Flush()\n}\n\nfunc ExportCsvByCountry(data []CloudflareIPData) {\n\ttheCC := \"\"\n\tdatatmp := make([]CloudflareIPData, 0)\n\tfor i, v := range data {\n\t\tif theCC == \"\" {\n\t\t\ttheCC = v.Country\n\t\t}\n\t\tif v.Country != theCC {\n\t\t\tfilename := theCC + \".csv\"\n\t\t\tsort.Slice(datatmp, func(i, j int) bool {\n\t\t\t\treturn datatmp[i].DownloadSpeed > datatmp[j].DownloadSpeed\n\t\t\t})\n\t\t\tWriteFile(filename, datatmp)\n\t\t\ttheCC = v.Country\n\t\t\tdatatmp = datatmp[:0]\n\t\t}\n\t\tdatatmp = append(datatmp, v)\n\t\tif i == len(data)-1 {\n\t\t\tfilename := theCC + \".csv\"\n\t\t\tsort.Slice(datatmp, func(i, j int) bool {\n\t\t\t\treturn datatmp[i].DownloadSpeed > datatmp[j].DownloadSpeed\n\t\t\t})\n\t\t\tWriteFile(filename, datatmp)\n\t\t}\n\t}\n}\n\nfunc ExportCsv(data []CloudflareIPData) {\n\tif noOutput() || len(data) == 0 {\n\t\treturn\n\t}\n\tfp, err := os.Create(Output)\n\tif err != nil {\n\t\tlog.Fatalf(\"创建文件[%s]失败：%v\", Output, err)\n\t\treturn\n\t}\n\tdefer fp.Close()\n\tgbkEncoder := simplifiedchinese.GBK.NewEncoder()\n\tw := csv.NewWriter(transform.NewWriter(fp, gbkEncoder))\n\t_ = w.Write([]string{\"IP 地址\", \"已发送\", \"已接收\", \"丢包率\", \"平均延迟\", \"下载速度 (MB/s)\"})\n\t_ = w.WriteAll(convertToString(data))\n\tw.Flush()\n}\n\nfunc convertToString(data []CloudflareIPData) [][]string {\n\tresult := make([][]string, 0)\n\tfor _, v := range data {\n\t\tresult = append(result, v.toString())\n\t}\n\treturn result\n}\n\n// 延迟丢包排序\ntype PingDelaySet []CloudflareIPData\n\n// 延迟条件过滤\nfunc (s PingDelaySet) FilterDelay() (data PingDelaySet) {\n\tif InputMaxDelay > maxDelay || InputMinDelay < minDelay { // 当输入的延迟条件不在默认范围内时，不进行过滤\n\t\treturn s\n\t}\n\tif InputMaxDelay == maxDelay && InputMinDelay == minDelay { // 当输入的延迟条件为默认值时，不进行过滤\n\t\treturn s\n\t}\n\tfor _, v := range s {\n\t\tif v.Delay > InputMaxDelay { // 平均延迟上限，延迟大于条件最大值时，后面的数据都不满足条件，直接跳出循环\n\t\t\tbreak\n\t\t}\n\t\tif v.Delay < InputMinDelay { // 平均延迟下限，延迟小于条件最小值时，不满足条件，跳过\n\t\t\tcontinue\n\t\t}\n\t\tdata = append(data, v) // 延迟满足条件时，添加到新数组中\n\t}\n\treturn\n}\n\n// 丢包条件过滤\nfunc (s PingDelaySet) FilterLossRate() (data PingDelaySet) {\n\tif InputMaxLossRate >= maxLossRate { // 当输入的丢包条件为默认值时，不进行过滤\n\t\treturn s\n\t}\n\tfor _, v := range s {\n\t\tif v.getLossRate() > InputMaxLossRate { // 丢包几率上限\n\t\t\tbreak\n\t\t}\n\t\tdata = append(data, v) // 丢包率满足条件时，添加到新数组中\n\t}\n\treturn\n}\n\nfunc (s PingDelaySet) FilterCountryV2(info *CountryInfo, countrycodeList map[string]bool) (data PingDelaySet) {\n\tfmt.Printf(\"开始查询IP的国家代号...\\n\")\n\tbfilterCountry := false\n\tif len(countrycodeList) > 0 {\n\t\tbfilterCountry = true\n\t}\n\tfor _, v := range s {\n\t\tv.Country = info.GetCountryV2(v.IP.IP.String())\n\t\tif v.Country == \"\" {\n\t\t\tfmt.Printf(\"IP: %s 无法获取国家代号，已跳过\\n\", v.IP.IP.String())\n\t\t\tcontinue\n\t\t}\n\t\tif bfilterCountry {\n\t\t\tif countrycodeList[v.Country] == true {\n\t\t\t\tdata = append(data, v)\n\t\t\t}\n\t\t} else {\n\t\t\tdata = append(data, v)\n\t\t}\n\t}\n\treturn\n}\n\nfunc (s PingDelaySet) FilterCountryV3(info *CountryInfo) (data PingDelaySet) {\n\tfmt.Printf(\"开始查询IP的国家代号...\\n\")\n\tfor _, v := range s {\n\t\tv.Country = info.GetCountryV2(v.IP.IP.String())\n\t\tif v.Country == \"\" {\n\t\t\tdata = append(data, v)\n\t\t}\n\n\t}\n\treturn\n}\n\nfunc (s PingDelaySet) FilterCountryV1() (data PingDelaySet) {\n\tcountrys := make([]IpResponse, 0)\n\tips := make([]string, 0)\n\tquerycount := 0\n\tfmt.Printf(\"开始查询IP的国家代号...\\n\")\n\tbar := NewBar(len(s), \"已查:\", \"\")\n\tfor i, v := range s {\n\t\tif i > 0 && i%100 == 0 {\n\t\t\tcountryCodeInfo := getCountryV1(ips)\n\t\t\tif countryCodeInfo == nil {\n\t\t\t\tfmt.Printf(\"[WARN] %s\\n\", \"IP查询失败，请检查网络或API接口是否正常\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcountrys = append(countrys, countryCodeInfo...)\n\t\t\tbar.Grow(100, strconv.Itoa(len(countrys)))\n\t\t\tips = ips[:0]\n\t\t\tquerycount++\n\t\t\tif querycount >= 15 {\n\t\t\t\ttime.Sleep(61 * time.Second)\n\t\t\t\tquerycount = 0\n\t\t\t}\n\t\t}\n\t\tip := v.IP.IP\n\t\tips = append(ips, ip.String())\n\t}\n\n\tif len(ips) > 0 {\n\t\tif querycount >= 15 {\n\t\t\ttime.Sleep(61 * time.Second)\n\t\t}\n\t\tcountryCodeInfo := getCountryV1(ips)\n\t\tcountrys = append(countrys, countryCodeInfo...)\n\t\tbar.Grow(len(ips), strconv.Itoa(len(countrys)))\n\t}\n\tbar.Done()\n\tfor i, v := range countrys {\n\t\tm := s[i]\n\t\tif v.Status == \"fail\" {\n\t\t\tm.Country = \"\"\n\t\t} else {\n\t\t\tm.Country = v.CountryCode\n\t\t}\n\t\tdata = append(data, m)\n\t}\n\treturn\n}\n\nfunc (s PingDelaySet) Len() int {\n\treturn len(s)\n}\nfunc (s PingDelaySet) Less(i, j int) bool {\n\tiRate, jRate := s[i].getLossRate(), s[j].getLossRate()\n\tif iRate != jRate {\n\t\treturn iRate < jRate\n\t}\n\treturn s[i].Delay < s[j].Delay\n}\nfunc (s PingDelaySet) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\n// 下载速度排序\ntype DownloadSpeedSet []CloudflareIPData\n\nfunc (s DownloadSpeedSet) Len() int {\n\treturn len(s)\n}\nfunc (s DownloadSpeedSet) Less(i, j int) bool {\n\treturn s[i].DownloadSpeed > s[j].DownloadSpeed\n}\nfunc (s DownloadSpeedSet) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc (s DownloadSpeedSet) Print() {\n\tif NoPrintResult() {\n\t\treturn\n\t}\n\tif len(s) <= 0 { // IP数组长度(IP数量) 大于 0 时继续\n\t\tfmt.Println(\"\\n[信息] 完整测速结果 IP 数量为 0，跳过输出结果。\")\n\t\treturn\n\t}\n\tdateString := convertToString(s) // 转为多维数组 [][]String\n\tif len(dateString) < PrintNum {  // 如果IP数组长度(IP数量) 小于  打印次数，则次数改为IP数量\n\t\tPrintNum = len(dateString)\n\t}\n\theadFormat := \"%-16s%-5s%-5s%-5s%-6s%-11s\\n\"\n\tdataFormat := \"%-18s%-8s%-8s%-8s%-10s%-15s\\n\"\n\tfor i := 0; i < PrintNum; i++ { // 如果要输出的 IP 中包含 IPv6，那么就需要调整一下间隔\n\t\tif len(dateString[i][0]) > 15 {\n\t\t\theadFormat = \"%-40s%-5s%-5s%-5s%-6s%-11s\\n\"\n\t\t\tdataFormat = \"%-42s%-8s%-8s%-8s%-10s%-15s\\n\"\n\t\t\tbreak\n\t\t}\n\t}\n\tfmt.Printf(headFormat, \"IP 地址\", \"已发送\", \"已接收\", \"丢包率\", \"平均延迟\", \"下载速度 (MB/s)\")\n\tfor i := 0; i < PrintNum; i++ {\n\t\tfmt.Printf(dataFormat, dateString[i][0], dateString[i][1], dateString[i][2], dateString[i][3], dateString[i][4], dateString[i][5])\n\t}\n\tif !noOutput() {\n\t\tfmt.Printf(\"\\n完整测速结果已写入 %v 文件，可使用记事本/表格软件查看。\\n\", Output)\n\t}\n}\n\nfunc (s DownloadSpeedSet) PrintbyCountry() {\n\tif NoPrintResult() {\n\t\treturn\n\t}\n}\n"
  },
  {
    "path": "utils/csv_test.go",
    "content": "package utils\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestPingDelaySet_FilterLossRate(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\ts        PingDelaySet\n\t\twantData PingDelaySet\n\t}{\n\t\t// TODO: Add test cases.\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif gotData := tt.s.FilterLossRate(); !reflect.DeepEqual(gotData, tt.wantData) {\n\t\t\t\tt.Errorf(\"FilterLossRate() = %v, want %v\", gotData, tt.wantData)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "utils/getcountry.go",
    "content": "package utils\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"github.com/oschwald/maxminddb-golang\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n)\n\ntype IpResponse struct {\n\tStatus      string `json:\"status\"`\n\tCountryCode string `json:\"countryCode\"`\n}\n\n// 每分钟15次查询，每次最多100个ip\nfunc getCountryV1(ips []string) (coutryCodes []IpResponse) {\n\tjsonData, err := json.Marshal(ips)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn nil\n\t}\n\n\tresp, err := http.Post(\"http://ip-api.com/batch\", \"application/json\", bytes.NewBuffer(jsonData))\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn nil\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, _ := io.ReadAll(resp.Body)\n\n\tdata := make([]IpResponse, 0)\n\terr = json.Unmarshal(body, &data)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil\n\t}\n\n\tfor _, v := range data {\n\t\tcoutryCodes = append(coutryCodes, v)\n\t}\n\n\treturn\n}\n\n// 使用本地mmdb文件查国家代码\ntype Country struct {\n\tGeoNameID uint              `maxminddb:\"geoname_id\"`\n\tIsoCode   string            `maxminddb:\"iso_code\"`\n\tNames     map[string]string `maxminddb:\"names\"`\n}\n\ntype Record struct {\n\tC Country `maxminddb:\"country\"`\n}\n\ntype CountryInfo struct {\n\tdb *maxminddb.Reader\n}\n\nfunc NewCountryInfo(db *maxminddb.Reader) *CountryInfo {\n\treturn &CountryInfo{\n\t\tdb: db,\n\t}\n}\n\nfunc (c *CountryInfo) GetCountryV2(ip string) string {\n\n\tipinfo := net.ParseIP(ip)\n\tvar record Record\n\terr := c.db.Lookup(ipinfo, &record)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn \"\"\n\t}\n\n\treturn record.C.IsoCode\n}\n\nfunc (c *CountryInfo) Done() {\n\tdefer c.db.Close()\n}\n"
  },
  {
    "path": "utils/progress.go",
    "content": "package utils\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/cheggaaa/pb/v3\"\n)\n\ntype Bar struct {\n\tpb *pb.ProgressBar\n}\n\nfunc NewBar(count int, MyStrStart, MyStrEnd string) *Bar {\n\ttmpl := fmt.Sprintf(`{{counters . }} {{ bar . \"[\" \"-\" (cycle . \"↖\" \"↗\" \"↘\" \"↙\" ) \"_\" \"]\"}} %s {{string . \"MyStr\" | green}} %s `, MyStrStart, MyStrEnd)\n\tbar := pb.ProgressBarTemplate(tmpl).Start(count)\n\treturn &Bar{pb: bar}\n}\n\nfunc (b *Bar) Grow(num int, MyStrVal string) {\n\tb.pb.Set(\"MyStr\", MyStrVal).Add(num)\n}\n\nfunc (b *Bar) Done() {\n\tb.pb.Finish()\n}\n"
  },
  {
    "path": "vless_workers/_worker.js",
    "content": "// @ts-ignore\nimport { connect } from 'cloudflare:sockets';\n\n// How to generate your own UUID:\n// [Windows] Press \"Win + R\", input cmd and run:  Powershell -NoExit -Command \"[guid]::NewGuid()\"\nlet userID = 'd342d11e-d424-4583-b36e-524ab1f0afa4';\n\nconst proxyIPs = ['cdn.xn--b6gac.eu.org:443', 'cdn-all.xn--b6gac.eu.org:443'];\n\n// if you want to use ipv6 or single proxyIP, please add comment at this line and remove comment at the next line\nlet proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)];\n// how to make sure the proxyIP with port is valid?\n// go to https://proxyip.edtunnel.best/ , input your proxyIP:proxyPort, and click \"Check\" button\n// if the port is valid, value \"Proxy IP\" is true, otherwise false and the value \"Origin\" must be 443\nlet proxyPort = proxyIP.includes(':') ? proxyIP.split(':')[1] : '443';\n\n// use single proxyip instead of random\n// let proxyIP = 'cdn.xn--b6gac.eu.org';\n// ipv6 proxyIP example remove comment to use\n// let proxyIP = \"[2a01:4f8:c2c:123f:64:5:6810:c55a]\"\n\n// Example:  user:pass@host:port  or  host:port\nlet socks5Address = '';\n// socks5Relay is true, will proxy all traffic to socks5Address, otherwise socks5Address only be used for cloudflare ips\nlet socks5Relay = false;\n\nif (!isValidUUID(userID)) {\n\tthrow new Error('uuid is not valid');\n}\n\nlet parsedSocks5Address = {};\nlet enableSocks = false;\n\n\nexport default {\n\t/**\n\t * @param {import(\"@cloudflare/workers-types\").Request} request\n\t * @param {{UUID: string, PROXYIP: string, SOCKS5: string, SOCKS5_RELAY: string}} env\n\t * @param {import(\"@cloudflare/workers-types\").ExecutionContext} _ctx\n\t * @returns {Promise<Response>}\n\t */\n\tasync fetch(request, env, _ctx) {\n\t\ttry {\n\t\t\tconst { UUID, PROXYIP, SOCKS5, SOCKS5_RELAY } = env;\n\t\t\tuserID = UUID || userID;\n\t\t\tsocks5Address = SOCKS5 || socks5Address;\n\t\t\tsocks5Relay = SOCKS5_RELAY || socks5Relay;\n\t\t\tif (PROXYIP) {\n\t\t\t\t// Split PROXYIP into an array of proxy addresses\n\t\t\t\tconst proxyAddresses = PROXYIP.split(',').map(addr => addr.trim());\n\t\t\t\t// Randomly select one proxy address\n\t\t\t\tconst selectedProxy = proxyAddresses[Math.floor(Math.random() * proxyAddresses.length)];\n\t\t\t\t[proxyIP, proxyPort = '443'] = selectedProxy.split(':');\n\t\t\t} else {\n\t\t\t\tproxyPort = proxyIP.includes(':') ? proxyIP.split(':')[1] : '443';\n\t\t\t\tproxyIP = proxyIP.split(':')[0];\n\t\t\t}\n\t\t\tconsole.log('ProxyIP:', proxyIP);\n\t\t\tconsole.log('ProxyPort:', proxyPort);\n\t\t\tif (socks5Address) {\n\t\t\t\ttry {\n\t\t\t\t\t// Split SOCKS5 into an array of addresses\n\t\t\t\t\tconst socks5Addresses = socks5Address.split(',').map(addr => addr.trim());\n\t\t\t\t\t// Randomly select one SOCKS5 address\n\t\t\t\t\tconst selectedSocks5 = socks5Addresses[Math.floor(Math.random() * socks5Addresses.length)];\n\t\t\t\t\tparsedSocks5Address = socks5AddressParser(selectedSocks5);\n\t\t\t\t\tenableSocks = true;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconsole.log(err.toString());\n\t\t\t\t\tenableSocks = false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst userID_Path = userID.includes(',') ? userID.split(',')[0] : userID;\n\t\t\tconst url = new URL(request.url);\n\t\t\tconst host = request.headers.get('Host');\n\n\t\t\tif (request.headers.get('Upgrade') !== 'websocket') {\n\t\t\t\tswitch (url.pathname) {\n\t\t\t\t\tcase '/cf':\n\t\t\t\t\t\treturn new Response(JSON.stringify(request.cf, null, 4), {\n\t\t\t\t\t\t\tstatus: 200,\n\t\t\t\t\t\t\theaders: { \"Content-Type\": \"application/json;charset=utf-8\" },\n\t\t\t\t\t\t});\n\t\t\t\t\tcase `/${userID_Path}`:\n\t\t\t\t\t\treturn new Response(getConfig(userID, host), {\n\t\t\t\t\t\t\tstatus: 200,\n\t\t\t\t\t\t\theaders: { \"Content-Type\": \"text/html; charset=utf-8\" },\n\t\t\t\t\t\t});\n\t\t\t\t\tcase `/sub/${userID_Path}`:\n\t\t\t\t\t\treturn new Response(btoa(GenSub(userID, host)), {\n\t\t\t\t\t\t\tstatus: 200,\n\t\t\t\t\t\t\theaders: { \"Content-Type\": \"text/plain;charset=utf-8\" },\n\t\t\t\t\t\t});\n\t\t\t\t\tcase `/bestip/${userID_Path}`:\n\t\t\t\t\t\treturn fetch(`https://sub.xf.free.hr/auto?host=${host}&uuid=${userID}&path=/`, { headers: request.headers });\n\t\t\t\t\tdefault:\n\t\t\t\t\t\treturn handleDefaultPath(url, request);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn await ProtocolOverWSHandler(request);\n\t\t\t}\n\t\t} catch (err) {\n\t\t\treturn new Response(err.toString());\n\t\t}\n\t},\n};\n\nasync function handleDefaultPath(url, request) {\n\tconst randomHostname = hostnames[Math.floor(Math.random() * hostnames.length)];\n\tconst newHeaders = new Headers(request.headers);\n\tnewHeaders.set('cf-connecting-ip', '1.2.3.4');\n\tnewHeaders.set('x-forwarded-for', '1.2.3.4');\n\tnewHeaders.set('x-real-ip', '1.2.3.4');\n\tnewHeaders.set('referer', 'https://www.google.com/search?q=edtunnel');\n\n\tconst proxyUrl = 'https://' + randomHostname + url.pathname + url.search;\n\tconst modifiedRequest = new Request(proxyUrl, {\n\t\tmethod: request.method,\n\t\theaders: newHeaders,\n\t\tbody: request.body,\n\t\tredirect: 'manual',\n\t});\n\n\tconst proxyResponse = await fetch(modifiedRequest, { redirect: 'manual' });\n\tif ([301, 302].includes(proxyResponse.status)) {\n\t\treturn new Response(`Redirects to ${randomHostname} are not allowed.`, {\n\t\t\tstatus: 403,\n\t\t\tstatusText: 'Forbidden',\n\t\t});\n\t}\n\treturn proxyResponse;\n}\n\n/**\n * Handles protocol over WebSocket requests by creating a WebSocket pair, accepting the WebSocket connection, and processing the protocol header.\n * @param {import(\"@cloudflare/workers-types\").Request} request The incoming request object.\n * @returns {Promise<Response>} A Promise that resolves to a WebSocket response object.\n */\nasync function ProtocolOverWSHandler(request) {\n\n\t/** @type {import(\"@cloudflare/workers-types\").WebSocket[]} */\n\t// @ts-ignore\n\tconst webSocketPair = new WebSocketPair();\n\tconst [client, webSocket] = Object.values(webSocketPair);\n\n\twebSocket.accept();\n\n\tlet address = '';\n\tlet portWithRandomLog = '';\n\tconst log = (/** @type {string} */ info, /** @type {string | undefined} */ event) => {\n\t\tconsole.log(`[${address}:${portWithRandomLog}] ${info}`, event || '');\n\t};\n\tconst earlyDataHeader = request.headers.get('sec-websocket-protocol') || '';\n\n\tconst readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);\n\n\t/** @type {{ value: import(\"@cloudflare/workers-types\").Socket | null}}*/\n\tlet remoteSocketWapper = {\n\t\tvalue: null,\n\t};\n\tlet isDns = false;\n\n\t// ws --> remote\n\treadableWebSocketStream.pipeTo(new WritableStream({\n\t\tasync write(chunk, controller) {\n\t\t\tif (isDns) {\n\t\t\t\treturn await handleDNSQuery(chunk, webSocket, null, log);\n\t\t\t}\n\t\t\tif (remoteSocketWapper.value) {\n\t\t\t\tconst writer = remoteSocketWapper.value.writable.getWriter()\n\t\t\t\tawait writer.write(chunk);\n\t\t\t\twriter.releaseLock();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst {\n\t\t\t\thasError,\n\t\t\t\tmessage,\n\t\t\t\taddressType,\n\t\t\t\tportRemote = 443,\n\t\t\t\taddressRemote = '',\n\t\t\t\trawDataIndex,\n\t\t\t\tProtocolVersion = new Uint8Array([0, 0]),\n\t\t\t\tisUDP,\n\t\t\t} = processProtocolHeader(chunk, userID);\n\t\t\taddress = addressRemote;\n\t\t\tportWithRandomLog = `${portRemote}--${Math.random()} ${isUDP ? 'udp ' : 'tcp '\n\t\t\t\t} `;\n\t\t\tif (hasError) {\n\t\t\t\t// controller.error(message);\n\t\t\t\tthrow new Error(message); // cf seems has bug, controller.error will not end stream\n\t\t\t}\n\t\t\t// Handle UDP connections for DNS (port 53) only\n\t\t\tif (isUDP) {\n\t\t\t\tif (portRemote === 53) {\n\t\t\t\t\tisDns = true;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error('UDP proxy is only enabled for DNS (port 53)');\n\t\t\t\t}\n\t\t\t\treturn; // Early return after setting isDns or throwing error\n\t\t\t}\n\t\t\t// [\"version\", \"附加信息长度 N\"]\n\t\t\tconst ProtocolResponseHeader = new Uint8Array([ProtocolVersion[0], 0]);\n\t\t\tconst rawClientData = chunk.slice(rawDataIndex);\n\n\t\t\tif (isDns) {\n\t\t\t\treturn handleDNSQuery(rawClientData, webSocket, ProtocolResponseHeader, log);\n\t\t\t}\n\t\t\thandleTCPOutBound(remoteSocketWapper, addressType, addressRemote, portRemote, rawClientData, webSocket, ProtocolResponseHeader, log);\n\t\t},\n\t\tclose() {\n\t\t\tlog(`readableWebSocketStream is close`);\n\t\t},\n\t\tabort(reason) {\n\t\t\tlog(`readableWebSocketStream is abort`, JSON.stringify(reason));\n\t\t},\n\t})).catch((err) => {\n\t\tlog('readableWebSocketStream pipeTo error', err);\n\t});\n\n\treturn new Response(null, {\n\t\tstatus: 101,\n\t\t// @ts-ignore\n\t\twebSocket: client,\n\t});\n}\n\n\n/**\n * Handles outbound TCP connections.\n *\n * @param {any} remoteSocket \n * @param {string} addressRemote The remote address to connect to.\n * @param {number} portRemote The remote port to connect to.\n * @param {Uint8Array} rawClientData The raw client data to write.\n * @param {import(\"@cloudflare/workers-types\").WebSocket} webSocket The WebSocket to pass the remote socket to.\n * @param {Uint8Array} protocolResponseHeader The protocol response header.\n * @param {function} log The logging function.\n * @returns {Promise<void>} The remote socket.\n */\nasync function handleTCPOutBound(remoteSocket, addressType, addressRemote, portRemote, rawClientData, webSocket, ProtocolResponseHeader, log,) {\n\tasync function connectAndWrite(address, port, socks = false) {\n\t\t/** @type {import(\"@cloudflare/workers-types\").Socket} */\n\t\tlet tcpSocket;\n\t\tif (socks5Relay) {\n\t\t\ttcpSocket = await socks5Connect(addressType, address, port, log)\n\t\t} else {\n\t\t\ttcpSocket = socks ? await socks5Connect(addressType, address, port, log)\n\t\t\t\t: connect({\n\t\t\t\t\thostname: address,\n\t\t\t\t\tport: port,\n\t\t\t\t});\n\t\t}\n\t\tremoteSocket.value = tcpSocket;\n\t\tlog(`connected to ${address}:${port}`);\n\t\tconst writer = tcpSocket.writable.getWriter();\n\t\tawait writer.write(rawClientData); // first write, normal is tls client hello\n\t\twriter.releaseLock();\n\t\treturn tcpSocket;\n\t}\n\n\t// if the cf connect tcp socket have no incoming data, we retry to redirect ip\n\tasync function retry() {\n\t\tif (enableSocks) {\n\t\t\ttcpSocket = await connectAndWrite(addressRemote, portRemote, true);\n\t\t} else {\n\t\t\ttcpSocket = await connectAndWrite(proxyIP || addressRemote, proxyPort || portRemote, false);\n\t\t}\n\t\t// no matter retry success or not, close websocket\n\t\ttcpSocket.closed.catch(error => {\n\t\t\tconsole.log('retry tcpSocket closed error', error);\n\t\t}).finally(() => {\n\t\t\tsafeCloseWebSocket(webSocket);\n\t\t})\n\t\tremoteSocketToWS(tcpSocket, webSocket, ProtocolResponseHeader, null, log);\n\t}\n\n\tlet tcpSocket = await connectAndWrite(addressRemote, portRemote);\n\n\t// when remoteSocket is ready, pass to websocket\n\t// remote--> ws\n\tremoteSocketToWS(tcpSocket, webSocket, ProtocolResponseHeader, retry, log);\n}\n\n/**\n * Creates a readable stream from a WebSocket server, allowing for data to be read from the WebSocket.\n * @param {import(\"@cloudflare/workers-types\").WebSocket} webSocketServer The WebSocket server to create the readable stream from.\n * @param {string} earlyDataHeader The header containing early data for WebSocket 0-RTT.\n * @param {(info: string)=> void} log The logging function.\n * @returns {ReadableStream} A readable stream that can be used to read data from the WebSocket.\n */\nfunction makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) {\n\tlet readableStreamCancel = false;\n\tconst stream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\twebSocketServer.addEventListener('message', (event) => {\n\t\t\t\tconst message = event.data;\n\t\t\t\tcontroller.enqueue(message);\n\t\t\t});\n\n\t\t\twebSocketServer.addEventListener('close', () => {\n\t\t\t\tsafeCloseWebSocket(webSocketServer);\n\t\t\t\tcontroller.close();\n\t\t\t});\n\n\t\t\twebSocketServer.addEventListener('error', (err) => {\n\t\t\t\tlog('webSocketServer has error');\n\t\t\t\tcontroller.error(err);\n\t\t\t});\n\t\t\tconst { earlyData, error } = base64ToArrayBuffer(earlyDataHeader);\n\t\t\tif (error) {\n\t\t\t\tcontroller.error(error);\n\t\t\t} else if (earlyData) {\n\t\t\t\tcontroller.enqueue(earlyData);\n\t\t\t}\n\t\t},\n\n\t\tpull(_controller) {\n\t\t\t// if ws can stop read if stream is full, we can implement backpressure\n\t\t\t// https://streams.spec.whatwg.org/#example-rs-push-backpressure\n\t\t},\n\n\t\tcancel(reason) {\n\t\t\tlog(`ReadableStream was canceled, due to ${reason}`)\n\t\t\treadableStreamCancel = true;\n\t\t\tsafeCloseWebSocket(webSocketServer);\n\t\t}\n\t});\n\n\treturn stream;\n}\n\n// https://xtls.github.io/development/protocols/protocol.html\n// https://github.com/zizifn/excalidraw-backup/blob/main/v2ray-protocol.excalidraw\n\n/**\n * Processes the protocol header buffer and returns an object with the relevant information.\n * @param {ArrayBuffer} protocolBuffer The protocol header buffer to process.\n * @param {string} userID The user ID to validate against the UUID in the protocol header.\n * @returns {{\n *  hasError: boolean,\n *  message?: string,\n *  addressRemote?: string,\n *  addressType?: number,\n *  portRemote?: number,\n *  rawDataIndex?: number,\n *  protocolVersion?: Uint8Array,\n *  isUDP?: boolean\n * }} An object with the relevant information extracted from the protocol header buffer.\n */\nfunction processProtocolHeader(protocolBuffer, userID) {\n\tif (protocolBuffer.byteLength < 24) {\n\t\treturn { hasError: true, message: 'invalid data' };\n\t}\n\n\tconst dataView = new DataView(protocolBuffer);\n\tconst version = dataView.getUint8(0);\n\tconst slicedBufferString = stringify(new Uint8Array(protocolBuffer.slice(1, 17)));\n\n\tconst uuids = userID.includes(',') ? userID.split(\",\") : [userID];\n\tconst isValidUser = uuids.some(uuid => slicedBufferString === uuid.trim()) ||\n\t\t(uuids.length === 1 && slicedBufferString === uuids[0].trim());\n\n\tconsole.log(`userID: ${slicedBufferString}`);\n\n\tif (!isValidUser) {\n\t\treturn { hasError: true, message: 'invalid user' };\n\t}\n\n\tconst optLength = dataView.getUint8(17);\n\tconst command = dataView.getUint8(18 + optLength);\n\n\tif (command !== 1 && command !== 2) {\n\t\treturn { hasError: true, message: `command ${command} is not supported, command 01-tcp,02-udp,03-mux` };\n\t}\n\n\tconst portIndex = 18 + optLength + 1;\n\tconst portRemote = dataView.getUint16(portIndex);\n\tconst addressType = dataView.getUint8(portIndex + 2);\n\tlet addressValue, addressLength, addressValueIndex;\n\n\tswitch (addressType) {\n\t\tcase 1:\n\t\t\taddressLength = 4;\n\t\t\taddressValueIndex = portIndex + 3;\n\t\t\taddressValue = new Uint8Array(protocolBuffer.slice(addressValueIndex, addressValueIndex + addressLength)).join('.');\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\taddressLength = dataView.getUint8(portIndex + 3);\n\t\t\taddressValueIndex = portIndex + 4;\n\t\t\taddressValue = new TextDecoder().decode(protocolBuffer.slice(addressValueIndex, addressValueIndex + addressLength));\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\taddressLength = 16;\n\t\t\taddressValueIndex = portIndex + 3;\n\t\t\taddressValue = Array.from({ length: 8 }, (_, i) => dataView.getUint16(addressValueIndex + i * 2).toString(16)).join(':');\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn { hasError: true, message: `invalid addressType: ${addressType}` };\n\t}\n\n\tif (!addressValue) {\n\t\treturn { hasError: true, message: `addressValue is empty, addressType is ${addressType}` };\n\t}\n\n\treturn {\n\t\thasError: false,\n\t\taddressRemote: addressValue,\n\t\taddressType,\n\t\tportRemote,\n\t\trawDataIndex: addressValueIndex + addressLength,\n\t\tprotocolVersion: new Uint8Array([version]),\n\t\tisUDP: command === 2\n\t};\n}\n\n\n/**\n * Converts a remote socket to a WebSocket connection.\n * @param {import(\"@cloudflare/workers-types\").Socket} remoteSocket The remote socket to convert.\n * @param {import(\"@cloudflare/workers-types\").WebSocket} webSocket The WebSocket to connect to.\n * @param {ArrayBuffer | null} protocolResponseHeader The protocol response header.\n * @param {(() => Promise<void>) | null} retry The function to retry the connection if it fails.\n * @param {(info: string) => void} log The logging function.\n * @returns {Promise<void>} A Promise that resolves when the conversion is complete.\n */\nasync function remoteSocketToWS(remoteSocket, webSocket, protocolResponseHeader, retry, log) {\n\tlet hasIncomingData = false;\n\n\ttry {\n\t\tawait remoteSocket.readable.pipeTo(\n\t\t\tnew WritableStream({\n\t\t\t\tasync write(chunk) {\n\t\t\t\t\tif (webSocket.readyState !== WS_READY_STATE_OPEN) {\n\t\t\t\t\t\tthrow new Error('WebSocket is not open');\n\t\t\t\t\t}\n\n\t\t\t\t\thasIncomingData = true;\n\n\t\t\t\t\tif (protocolResponseHeader) {\n\t\t\t\t\t\twebSocket.send(await new Blob([protocolResponseHeader, chunk]).arrayBuffer());\n\t\t\t\t\t\tprotocolResponseHeader = null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\twebSocket.send(chunk);\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tclose() {\n\t\t\t\t\tlog(`Remote connection readable closed. Had incoming data: ${hasIncomingData}`);\n\t\t\t\t},\n\t\t\t\tabort(reason) {\n\t\t\t\t\tconsole.error(`Remote connection readable aborted:`, reason);\n\t\t\t\t},\n\t\t\t})\n\t\t);\n\t} catch (error) {\n\t\tconsole.error(`remoteSocketToWS error:`, error.stack || error);\n\t\tsafeCloseWebSocket(webSocket);\n\t}\n\n\tif (!hasIncomingData && retry) {\n\t\tlog(`No incoming data, retrying`);\n\t\tawait retry();\n\t}\n  /**\n }\n * Decodes a base64 string into an ArrayBuffer.\n * @param {string} base64Str The base64 string to decode.\n * @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.\n */\nfunction base64ToArrayBuffer(base64Str) {\n\tif (!base64Str) {\n\t\treturn { earlyData: null, error: null };\n\t}\n\ttry {\n\t\t// Convert modified Base64 for URL (RFC 4648) to standard Base64\n\t\tbase64Str = base64Str.replace(/-/g, '+').replace(/_/g, '/');\n\t\t// Decode Base64 string\n\t\tconst binaryStr = atob(base64Str);\n\t\t// Convert binary string to ArrayBuffer\n\t\tconst buffer = new ArrayBuffer(binaryStr.length);\n\t\tconst view = new Uint8Array(buffer);\n\t\tfor (let i = 0; i < binaryStr.length; i++) {\n\t\t\tview[i] = binaryStr.charCodeAt(i);\n\t\t}\n\t\treturn { earlyData: buffer, error: null };\n\t} catch (error) {\n\t\treturn { earlyData: null, error };\n\t}\n}\n\n/**\n * Checks if a given string is a valid UUID.\n * @param {string} uuid The string to validate as a UUID.\n * @returns {boolean} True if the string is a valid UUID, false otherwise.\n */\nfunction isValidUUID(uuid) {\n\t// More precise UUID regex pattern\n\tconst 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;\n\treturn uuidRegex.test(uuid);\n}\n\nconst WS_READY_STATE_OPEN = 1;\nconst WS_READY_STATE_CLOSING = 2;\n\n/**\n * Closes a WebSocket connection safely without throwing exceptions.\n * @param {import(\"@cloudflare/workers-types\").WebSocket} socket The WebSocket connection to close.\n */\nfunction safeCloseWebSocket(socket) {\n\ttry {\n\t\tif (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) {\n\t\t\tsocket.close();\n\t\t}\n\t} catch (error) {\n\t\tconsole.error('safeCloseWebSocket error:', error);\n\t}\n}\n\nconst byteToHex = Array.from({ length: 256 }, (_, i) => (i + 0x100).toString(16).slice(1));\n\nfunction unsafeStringify(arr, offset = 0) {\n\treturn [\n\t\tbyteToHex[arr[offset]],\n\t\tbyteToHex[arr[offset + 1]],\n\t\tbyteToHex[arr[offset + 2]],\n\t\tbyteToHex[arr[offset + 3]],\n\t\t'-',\n\t\tbyteToHex[arr[offset + 4]],\n\t\tbyteToHex[arr[offset + 5]],\n\t\t'-',\n\t\tbyteToHex[arr[offset + 6]],\n\t\tbyteToHex[arr[offset + 7]],\n\t\t'-',\n\t\tbyteToHex[arr[offset + 8]],\n\t\tbyteToHex[arr[offset + 9]],\n\t\t'-',\n\t\tbyteToHex[arr[offset + 10]],\n\t\tbyteToHex[arr[offset + 11]],\n\t\tbyteToHex[arr[offset + 12]],\n\t\tbyteToHex[arr[offset + 13]],\n\t\tbyteToHex[arr[offset + 14]],\n\t\tbyteToHex[arr[offset + 15]]\n\t].join('').toLowerCase();\n}\n\nfunction stringify(arr, offset = 0) {\n\tconst uuid = unsafeStringify(arr, offset);\n\tif (!isValidUUID(uuid)) {\n\t\tthrow new TypeError(\"Stringified UUID is invalid\");\n\t}\n\treturn uuid;\n}\n\n\n/**\n * Handles outbound UDP traffic by transforming the data into DNS queries and sending them over a WebSocket connection.\n * @param {import(\"@cloudflare/workers-types\").WebSocket} webSocket The WebSocket connection to send the DNS queries over.\n * @param {ArrayBuffer} protocolResponseHeader The protocol response header.\n * @param {(string) => void} log The logging function.\n * @returns {{write: (chunk: Uint8Array) => void}} An object with a write method that accepts a Uint8Array chunk to write to the transform stream.\n */\nasync function handleUDPOutBound(webSocket, protocolResponseHeader, log) {\n\n\tlet isprotocolHeaderSent = false;\n\tconst transformStream = new TransformStream({\n\t\tstart(_controller) {\n\n\t\t},\n\t\ttransform(chunk, controller) {\n\t\t\t// udp message 2 byte is the the length of udp data\n\t\t\t// TODO: this should have bug, beacsue maybe udp chunk can be in two websocket message\n\t\t\tfor (let index = 0; index < chunk.byteLength;) {\n\t\t\t\tconst lengthBuffer = chunk.slice(index, index + 2);\n\t\t\t\tconst udpPakcetLength = new DataView(lengthBuffer).getUint16(0);\n\t\t\t\tconst udpData = new Uint8Array(\n\t\t\t\t\tchunk.slice(index + 2, index + 2 + udpPakcetLength)\n\t\t\t\t);\n\t\t\t\tindex = index + 2 + udpPakcetLength;\n\t\t\t\tcontroller.enqueue(udpData);\n\t\t\t}\n\t\t},\n\t\tflush(_controller) {\n\t\t}\n\t});\n\n\t// only handle dns udp for now\n\ttransformStream.readable.pipeTo(new WritableStream({\n\t\tasync write(chunk) {\n\t\t\tconst resp = await fetch(dohURL, // dns server url\n\t\t\t\t{\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t'content-type': 'application/dns-message',\n\t\t\t\t\t},\n\t\t\t\t\tbody: chunk,\n\t\t\t\t})\n\t\t\tconst dnsQueryResult = await resp.arrayBuffer();\n\t\t\tconst udpSize = dnsQueryResult.byteLength;\n\t\t\t// console.log([...new Uint8Array(dnsQueryResult)].map((x) => x.toString(16)));\n\t\t\tconst udpSizeBuffer = new Uint8Array([(udpSize >> 8) & 0xff, udpSize & 0xff]);\n\t\t\tif (webSocket.readyState === WS_READY_STATE_OPEN) {\n\t\t\t\tlog(`doh success and dns message length is ${udpSize}`);\n\t\t\t\tif (isprotocolHeaderSent) {\n\t\t\t\t\twebSocket.send(await new Blob([udpSizeBuffer, dnsQueryResult]).arrayBuffer());\n\t\t\t\t} else {\n\t\t\t\t\twebSocket.send(await new Blob([protocolResponseHeader, udpSizeBuffer, dnsQueryResult]).arrayBuffer());\n\t\t\t\t\tisprotocolHeaderSent = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})).catch((error) => {\n\t\tlog('dns udp has error' + error)\n\t});\n\n\tconst writer = transformStream.writable.getWriter();\n\n\treturn {\n\t\t/**\n\t\t * \n\t\t * @param {Uint8Array} chunk \n\t\t */\n\t\twrite(chunk) {\n\t\t\twriter.write(chunk);\n\t\t}\n\t};\n}\n\n/**\n * \n * @param {ArrayBuffer} udpChunk \n * @param {import(\"@cloudflare/workers-types\").WebSocket} webSocket \n * @param {ArrayBuffer} protocolResponseHeader \n * @param {(string)=> void} log \n */\nasync function handleDNSQuery(udpChunk, webSocket, protocolResponseHeader, log) {\n\t// no matter which DNS server client send, we alwasy use hard code one.\n\t// beacsue someof DNS server is not support DNS over TCP\n\ttry {\n\t\tconst dnsServer = '8.8.4.4'; // change to 1.1.1.1 after cf fix connect own ip bug\n\t\tconst dnsPort = 53;\n\t\t/** @type {ArrayBuffer | null} */\n\t\tlet vlessHeader = protocolResponseHeader;\n\t\t/** @type {import(\"@cloudflare/workers-types\").Socket} */\n\t\tconst tcpSocket = connect({\n\t\t\thostname: dnsServer,\n\t\t\tport: dnsPort,\n\t\t});\n\n\t\tlog(`connected to ${dnsServer}:${dnsPort}`);\n\t\tconst writer = tcpSocket.writable.getWriter();\n\t\tawait writer.write(udpChunk);\n\t\twriter.releaseLock();\n\t\tawait tcpSocket.readable.pipeTo(new WritableStream({\n\t\t\tasync write(chunk) {\n\t\t\t\tif (webSocket.readyState === WS_READY_STATE_OPEN) {\n\t\t\t\t\tif (vlessHeader) {\n\t\t\t\t\t\twebSocket.send(await new Blob([vlessHeader, chunk]).arrayBuffer());\n\t\t\t\t\t\tvlessHeader = null;\n\t\t\t\t\t} else {\n\t\t\t\t\t\twebSocket.send(chunk);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\tclose() {\n\t\t\t\tlog(`dns server(${dnsServer}) tcp is close`);\n\t\t\t},\n\t\t\tabort(reason) {\n\t\t\t\tconsole.error(`dns server(${dnsServer}) tcp is abort`, reason);\n\t\t\t},\n\t\t}));\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t`handleDNSQuery have exception, error: ${error.message}`\n\t\t);\n\t}\n}\n\n\n/**\n * \n * @param {number} addressType\n * @param {string} addressRemote\n * @param {number} portRemote\n * @param {function} log The logging function.\n */\nasync function socks5Connect(addressType, addressRemote, portRemote, log) {\n\tconst { username, password, hostname, port } = parsedSocks5Address;\n\t// Connect to the SOCKS server\n\tconst socket = connect({\n\t\thostname,\n\t\tport,\n\t});\n\n\t// Request head format (Worker -> Socks Server):\n\t// +----+----------+----------+\n\t// |VER | NMETHODS | METHODS  |\n\t// +----+----------+----------+\n\t// | 1  |    1     | 1 to 255 |\n\t// +----+----------+----------+\n\n\t// https://en.wikipedia.org/wiki/SOCKS#SOCKS5\n\t// For METHODS:\n\t// 0x00 NO AUTHENTICATION REQUIRED\n\t// 0x02 USERNAME/PASSWORD https://datatracker.ietf.org/doc/html/rfc1929\n\tconst socksGreeting = new Uint8Array([5, 2, 0, 2]);\n\n\tconst writer = socket.writable.getWriter();\n\n\tawait writer.write(socksGreeting);\n\tlog('sent socks greeting');\n\n\tconst reader = socket.readable.getReader();\n\tconst encoder = new TextEncoder();\n\tlet res = (await reader.read()).value;\n\t// Response format (Socks Server -> Worker):\n\t// +----+--------+\n\t// |VER | METHOD |\n\t// +----+--------+\n\t// | 1  |   1    |\n\t// +----+--------+\n\tif (res[0] !== 0x05) {\n\t\tlog(`socks server version error: ${res[0]} expected: 5`);\n\t\treturn;\n\t}\n\tif (res[1] === 0xff) {\n\t\tlog(\"no acceptable methods\");\n\t\treturn;\n\t}\n\n\t// if return 0x0502\n\tif (res[1] === 0x02) {\n\t\tlog(\"socks server needs auth\");\n\t\tif (!username || !password) {\n\t\t\tlog(\"please provide username/password\");\n\t\t\treturn;\n\t\t}\n\t\t// +----+------+----------+------+----------+\n\t\t// |VER | ULEN |  UNAME   | PLEN |  PASSWD  |\n\t\t// +----+------+----------+------+----------+\n\t\t// | 1  |  1   | 1 to 255 |  1   | 1 to 255 |\n\t\t// +----+------+----------+------+----------+\n\t\tconst authRequest = new Uint8Array([\n\t\t\t1,\n\t\t\tusername.length,\n\t\t\t...encoder.encode(username),\n\t\t\tpassword.length,\n\t\t\t...encoder.encode(password)\n\t\t]);\n\t\tawait writer.write(authRequest);\n\t\tres = (await reader.read()).value;\n\t\t// expected 0x0100\n\t\tif (res[0] !== 0x01 || res[1] !== 0x00) {\n\t\t\tlog(\"fail to auth socks server\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\t// Request data format (Worker -> Socks Server):\n\t// +----+-----+-------+------+----------+----------+\n\t// |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |\n\t// +----+-----+-------+------+----------+----------+\n\t// | 1  |  1  | X'00' |  1   | Variable |    2     |\n\t// +----+-----+-------+------+----------+----------+\n\t// ATYP: address type of following address\n\t// 0x01: IPv4 address\n\t// 0x03: Domain name\n\t// 0x04: IPv6 address\n\t// DST.ADDR: desired destination address\n\t// DST.PORT: desired destination port in network octet order\n\n\t// addressType\n\t// 1--> ipv4  addressLength =4\n\t// 2--> domain name\n\t// 3--> ipv6  addressLength =16\n\tlet DSTADDR;\t// DSTADDR = ATYP + DST.ADDR\n\tswitch (addressType) {\n\t\tcase 1:\n\t\t\tDSTADDR = new Uint8Array(\n\t\t\t\t[1, ...addressRemote.split('.').map(Number)]\n\t\t\t);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tDSTADDR = new Uint8Array(\n\t\t\t\t[3, addressRemote.length, ...encoder.encode(addressRemote)]\n\t\t\t);\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tDSTADDR = new Uint8Array(\n\t\t\t\t[4, ...addressRemote.split(':').flatMap(x => [parseInt(x.slice(0, 2), 16), parseInt(x.slice(2), 16)])]\n\t\t\t);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tlog(`invild  addressType is ${addressType}`);\n\t\t\treturn;\n\t}\n\tconst socksRequest = new Uint8Array([5, 1, 0, ...DSTADDR, portRemote >> 8, portRemote & 0xff]);\n\tawait writer.write(socksRequest);\n\tlog('sent socks request');\n\n\tres = (await reader.read()).value;\n\t// Response format (Socks Server -> Worker):\n\t//  +----+-----+-------+------+----------+----------+\n\t// |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |\n\t// +----+-----+-------+------+----------+----------+\n\t// | 1  |  1  | X'00' |  1   | Variable |    2     |\n\t// +----+-----+-------+------+----------+----------+\n\tif (res[1] === 0x00) {\n\t\tlog(\"socks connection opened\");\n\t} else {\n\t\tlog(\"fail to open socks connection\");\n\t\treturn;\n\t}\n\twriter.releaseLock();\n\treader.releaseLock();\n\treturn socket;\n}\n\n/**\n * \n * @param {string} address\n */\nfunction socks5AddressParser(address) {\n\tlet [latter, former] = address.split(\"@\").reverse();\n\tlet username, password, hostname, port;\n\tif (former) {\n\t\tconst formers = former.split(\":\");\n\t\tif (formers.length !== 2) {\n\t\t\tthrow new Error('Invalid SOCKS address format');\n\t\t}\n\t\t[username, password] = formers;\n\t}\n\tconst latters = latter.split(\":\");\n\tport = Number(latters.pop());\n\tif (isNaN(port)) {\n\t\tthrow new Error('Invalid SOCKS address format');\n\t}\n\thostname = latters.join(\":\");\n\tconst regex = /^\\[.*\\]$/;\n\tif (hostname.includes(\":\") && !regex.test(hostname)) {\n\t\tthrow new Error('Invalid SOCKS address format');\n\t}\n\treturn {\n\t\tusername,\n\t\tpassword,\n\t\thostname,\n\t\tport,\n\t}\n}\n\n\nasync function parseTrojanHeader(buffer) {\n\tif (buffer.byteLength < 58) {\n\t\treturn { hasError: true, message: \"Invalid data length\" };\n\t}\n\n\tconst view = new DataView(buffer);\n\tif (view.getUint8(56) !== 0x0d || view.getUint8(57) !== 0x0a) {\n\t\treturn { hasError: true, message: \"Invalid header format (missing CR LF)\" };\n\t}\n\n\tconst password = new TextDecoder().decode(buffer.slice(0, 56));\n\tif (password !== Sha256.sha224(userID)) {\n\t\treturn { hasError: true, message: \"Invalid password\" };\n\t}\n\n\tconst socks5Data = new DataView(buffer, 58);\n\tif (socks5Data.byteLength < 6) {\n\t\treturn { hasError: true, message: \"Invalid SOCKS5 request data\" };\n\t}\n\n\tif (socks5Data.getUint8(0) !== 1) {\n\t\treturn { hasError: true, message: \"Unsupported command, only TCP (CONNECT) is allowed\" };\n\t}\n\n\tconst atype = socks5Data.getUint8(1);\n\tlet address;\n\tlet addressEnd;\n\n\tswitch (atype) {\n\t\tcase 1: // IPv4\n\t\t\taddress = Array.from(new Uint8Array(socks5Data.buffer, socks5Data.byteOffset + 2, 4)).join('.');\n\t\t\taddressEnd = 6;\n\t\t\tbreak;\n\t\tcase 3: // Domain name\n\t\t\tconst domainLength = socks5Data.getUint8(2);\n\t\t\taddress = new TextDecoder().decode(socks5Data.buffer.slice(socks5Data.byteOffset + 3, socks5Data.byteOffset + 3 + domainLength));\n\t\t\taddressEnd = 3 + domainLength;\n\t\t\tbreak;\n\t\tcase 4: // IPv6\n\t\t\taddress = Array.from(new Uint8Array(socks5Data.buffer, socks5Data.byteOffset + 2, 16))\n\t\t\t\t.map(x => x.toString(16).padStart(2, '0'))\n\t\t\t\t.join(':')\n\t\t\t\t.replace(/(:0)+:/, '::');\n\t\t\taddressEnd = 18;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn { hasError: true, message: `Invalid address type: ${atype}` };\n\t}\n\n\tconst port = socks5Data.getUint16(addressEnd);\n\n\treturn {\n\t\thasError: false,\n\t\taddress,\n\t\tport,\n\t\tdata: buffer.slice(58 + addressEnd + 2)\n\t};\n}\n\n\nconst VlessCmd = {\n\tTCP: 1,\n\tUDP: 2,\n\tMUX: 3,\n};\n\nconst VlessAddrType = {\n\tIPv4: 1,\t\t// 4-bytes\n\tDomainName: 2,\t// The first byte indicates the length of the following domain name\n\tIPv6: 3,\t\t// 16-bytes\n};\n\n/**\n * Generate a vless request header.\n * @param {number} command - The command to execute (see VlessCmd).\n * @param {number} destType - The type of destination address (see VlessAddrType).\n * @param {string} destAddr - The destination address.\n * @param {number} destPort - The destination port.\n * @param {string} uuid - The UUID of the request.\n * @returns {Uint8Array} - The vless request header as a Uint8Array.\n * @throws {Error} - If the address type is unknown.\n */\nfunction makeVlessReqHeader(command, destType, destAddr, destPort, uuid) {\n\t/** @type {number} */\n\tlet addressFieldLength;\n\t/** @type {Uint8Array | undefined} */\n\tlet addressEncoded;\n\tswitch (destType) {\n\t\tcase VlessAddrType.IPv4:\n\t\t\taddressFieldLength = 4;\n\t\t\tbreak;\n\t\tcase VlessAddrType.DomainName:\n\t\t\taddressEncoded = new TextEncoder().encode(destAddr);\n\t\t\taddressFieldLength = addressEncoded.length + 1;\n\t\t\tbreak;\n\t\tcase VlessAddrType.IPv6:\n\t\t\taddressFieldLength = 16;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown address type: ${destType}`);\n\t}\n\n\tconst uuidString = uuid.replace(/-/g, '');\n\tconst uuidOffset = 1;\n\tconst vlessHeader = new Uint8Array(22 + addressFieldLength);\n\n\t// Protocol Version = 0\n\tvlessHeader[0] = 0x00;\n\n\tfor (let i = 0; i < uuidString.length; i += 2) {\n\t\tvlessHeader[uuidOffset + i / 2] = parseInt(uuidString.substr(i, 2), 16);\n\t}\n\n\t// Additional Information Length M = 0\n\tvlessHeader[17] = 0x00;\n\n\t// Instruction\n\tvlessHeader[18] = command;\n\n\t// Port, 2-byte big-endian\n\tvlessHeader[19] = destPort >> 8;\n\tvlessHeader[20] = destPort & 0xFF;\n\n\t// Address Type\n\t// 1--> ipv4  addressLength =4\n\t// 2--> domain name addressLength=addressBuffer[1]\n\t// 3--> ipv6  addressLength =16\n\tvlessHeader[21] = destType;\n\n\t// Address\n\tswitch (destType) {\n\t\tcase VlessAddrType.IPv4:\n\t\t\tconst octetsIPv4 = destAddr.split('.');\n\t\t\tfor (let i = 0; i < 4; i++) {\n\t\t\t\tvlessHeader[22 + i] = parseInt(octetsIPv4[i]);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase VlessAddrType.DomainName:\n\t\t\tvlessHeader[22] = addressEncoded.length;\n\t\t\tvlessHeader.set(addressEncoded, 23);\n\t\t\tbreak;\n\t\tcase VlessAddrType.IPv6:\n\t\t\tconst groupsIPv6 = ipv6.split(':');\n\t\t\tfor (let i = 0; i < 8; i++) {\n\t\t\t\tconst hexGroup = parseInt(groupsIPv6[i], 16);\n\t\t\t\tvlessHeader[i * 2 + 22] = hexGroup >> 8;\n\t\t\t\tvlessHeader[i * 2 + 23] = hexGroup & 0xFF;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new Error(`Unknown address type: ${destType}`);\n\t}\n\n\treturn vlessHeader;\n}\n\n/**\n * Checks if the provided VLESS configuration is valid for the given address and stream settings.\n * @param {string} address - The address to check against.\n * @param {Object} streamSettings - The stream settings to check.\n * @throws {Error} If the outbound stream method is not 'ws'.\n * @throws {Error} If the security layer is not 'none' or 'tls'.\n * @throws {Error} If the Host field in the http header is different from the server address.\n * @throws {Error} If the SNI is different from the server address.\n */\nfunction checkVlessConfig(address, streamSettings) {\n\tif (streamSettings.network !== 'ws') {\n\t\tthrow new Error(`Unsupported outbound stream method: ${streamSettings.network}, has to be ws (Websocket)`);\n\t}\n\n\tif (streamSettings.security !== 'tls' && streamSettings.security !== 'none') {\n\t\tthrow new Error(`Usupported security layer: ${streamSettings.network}, has to be none or tls.`);\n\t}\n\n\tif (streamSettings.wsSettings && streamSettings.wsSettings.headers && streamSettings.wsSettings.headers.Host !== address) {\n\t\tthrow new Error(`The Host field in the http header is different from the server address, this is unsupported due to Cloudflare API restrictions`);\n\t}\n\n\tif (streamSettings.tlsSettings && streamSettings.tlsSettings.serverName !== address) {\n\t\tthrow new Error(`The SNI is different from the server address, this is unsupported due to Cloudflare API restrictions`);\n\t}\n}\n\n\n/**\n * Parses a VLESS URL string into its components.\n * @param {string} url The VLESS URL string in the format \"vless://uuid@remoteHost:remotePort?queryParams#descriptiveText\".\n * @returns {{\n*  protocol: string,\n*  uuid: string,\n*  remoteHost: string,\n*  remotePort: number,\n*  descriptiveText: string,\n*  queryParams: Object<string, string>\n* }} An object containing the parsed components of the VLESS URL string.\n* @throws {Error} If the URL string is in an invalid format.\n*/\nfunction parseVlessString(url) {\n\tconst regex = /^(.+):\\/\\/(.+?)@(.+?):(\\d+)(\\?[^#]*)?(#.*)?$/;\n\tconst match = url.match(regex);\n\n\tif (!match) {\n\t\tthrow new Error('Invalid URL format');\n\t}\n\n\tconst [, protocol, uuid, remoteHost, remotePort, query, descriptiveText] = match;\n\n\tconst json = {\n\t\tprotocol,\n\t\tuuid,\n\t\tremoteHost,\n\t\tremotePort: parseInt(remotePort),\n\t\tdescriptiveText: descriptiveText ? descriptiveText.substring(1) : '',\n\t\tqueryParams: {}\n\t};\n\n\tif (query) {\n\t\tconst queryFields = query.substring(1).split('&');\n\t\tqueryFields.forEach(field => {\n\t\t\tconst [key, value] = field.split('=');\n\t\t\tjson.queryParams[key] = value;\n\t\t});\n\t}\n\n\treturn json;\n}\n\n\nconst at = 'QA==';\nconst pt = 'dmxlc3M=';\nconst ed = 'RUR0dW5uZWw=';\n\n/**\n *\n * @param {string} userID - single or comma separated userIDs\n * @param {string | null} hostName\n * @returns {string}\n */\nfunction getConfig(userIDs, hostName) {\n\tconst commonUrlPart = `?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2048#${hostName}`;\n\n\t// Split the userIDs into an array\n\tconst userIDArray = userIDs.split(\",\");\n\n\t// Prepare output string for each userID\n\tconst sublink = `https://${hostName}/sub/${userIDArray[0]}?format=clash`\n\tconst subbestip = `https://${hostName}/bestip/${userIDArray[0]}`;\n\tconst 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`;\n\t// HTML Head with CSS and FontAwesome library\n\tconst htmlHead = `\n  <head>\n    <title>EDtunnel: Configuration</title>\n    <meta name='viewport' content='width=device-width, initial-scale=1'>\n    <meta property='og:site_name' content='EDtunnel: Protocol Configuration' />\n    <meta property='og:type' content='website' />\n    <meta property='og:title' content='EDtunnel - Protocol Configuration and Subscribe Output' />\n    <meta property='og:description' content='Use Cloudflare Pages and Worker serverless to implement protocol' />\n    <meta property='og:url' content='https://${hostName}/' />\n    <meta property='og:image' content='https://ipfs.io/ipfs/bafybeigd6i5aavwpr6wvnwuyayklq3omonggta4x2q7kpmgafj357nkcky' />\n    <meta name='twitter:card' content='summary_large_image' />\n    <meta name='twitter:title' content='EDtunnel - Protocol Configuration and Subscribe Output' />\n    <meta name='twitter:description' content='Use Cloudflare Pages and Worker serverless to implement protocol' />\n    <meta name='twitter:url' content='https://${hostName}/' />\n    <meta name='twitter:image' content='https://ipfs.io/ipfs/bafybeigd6i5aavwpr6wvnwuyayklq3omonggta4x2q7kpmgafj357nkcky' />\n    <meta property='og:image:width' content='1500' />\n    <meta property='og:image:height' content='1500' />\n\n    <style>\n      body {\n        font-family: 'Roboto', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;\n        background-color: #000000;\n        color: #ffffff;\n        line-height: 1.6;\n        padding: 20px;\n        max-width: 1200px;\n        margin: 0 auto;\n      }\n      .container {\n        background-color: #111111;\n        border-radius: 8px;\n        box-shadow: 0 4px 6px rgba(255, 255, 255, 0.1);\n        padding: 20px;\n        margin-bottom: 20px;\n      }\n      h1, h2 {\n        color: #ffffff;\n      }\n      .config-item {\n        background-color: #222222;\n        border: 1px solid #333333;\n        border-radius: 4px;\n        padding: 15px;\n        margin-bottom: 15px;\n      }\n      .config-item h3 {\n        margin-top: 0;\n        color: #ffffff;\n      }\n      .btn {\n        background-color: #ffffff;\n        color: #000000;\n        border: none;\n        padding: 10px 15px;\n        border-radius: 4px;\n        cursor: pointer;\n        transition: background-color 0.3s, color 0.3s;\n      }\n      .btn:hover {\n        background-color: #cccccc;\n      }\n      .btn-group {\n        margin-top: 10px;\n      }\n      .btn-group .btn {\n        margin-right: 10px;\n      }\n      pre {\n        background-color: #333333;\n        border: 1px solid #444444;\n        border-radius: 4px;\n        padding: 10px;\n        white-space: pre-wrap;\n        word-wrap: break-word;\n        color: #00ff00;\n      }\n      .logo {\n        float: left;\n        margin-right: 20px;\n        margin-bottom: 20px;\n\t\tmax-width: 30%;\n      }\n      @media (max-width: 768px) {\n        .logo {\n          float: none;\n          display: block;\n          margin: 0 auto 20px;\n          max-width: 90%; /* Adjust the max-width to fit within the container */\n        }\n        .btn-group {\n          display: flex;\n          flex-direction: column;\n          align-items: center;\n        }\n        .btn-group .btn {\n          margin-bottom: 10px;\n          width: 100%;\n          text-align: center;\n        }\n      }\n      .code-container {\n        position: relative;\n        margin-bottom: 15px;\n      }\n      .code-container pre {\n        margin: 0;\n        padding-right: 100px; /* Make space for the button */\n      }\n      .copy-btn {\n        position: absolute;\n        top: 5px;\n        right: 5px;\n        padding: 5px 10px;\n        font-size: 0.8em;\n      }\n      .subscription-info {\n        margin-top: 20px;\n        background-color: #222222;\n        border-radius: 4px;\n        padding: 15px;\n      }\n      .subscription-info h3 {\n        color: #ffffff;\n        margin-top: 0;\n      }\n      .subscription-info ul {\n        padding-left: 20px;\n      }\n      .subscription-info li {\n        margin-bottom: 10px;\n      }\n    </style>\n    <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css\">\n  </head>\n  `;\n\n\tconst header = `\n    <div class=\"container\">\n      <h1>EDtunnel: Protocol Configuration</h1>\n      <img src=\"https://ipfs.io/ipfs/bafybeigd6i5aavwpr6wvnwuyayklq3omonggta4x2q7kpmgafj357nkcky\" alt=\"EDtunnel Logo\" class=\"logo\">\n      <p>Welcome! This function generates configuration for the vless protocol. If you found this useful, please check our GitHub project:</p>\n      <p><a href=\"https://github.com/6Kmfi6HP/EDtunnel\" target=\"_blank\" style=\"color: #00ff00;\">EDtunnel - https://github.com/6Kmfi6HP/EDtunnel</a></p>\n      <div style=\"clear: both;\"></div>\n      <div class=\"btn-group\">\n        <a href=\"//${hostName}/sub/${userIDArray[0]}\" class=\"btn\" target=\"_blank\"><i class=\"fas fa-link\"></i> VLESS Subscription</a>\n        <a href=\"clash://install-config?url=${encodeURIComponent(`https://${hostName}/sub/${userIDArray[0]}?format=clash`)}\" class=\"btn\" target=\"_blank\"><i class=\"fas fa-bolt\"></i> Clash Subscription</a>\n        <a href=\"${clash_link}\" class=\"btn\" target=\"_blank\"><i class=\"fas fa-bolt\"></i> Clash Link</a>\n        <a href=\"${subbestip}\" class=\"btn\" target=\"_blank\"><i class=\"fas fa-star\"></i> Best IP Subscription</a>\n      </div>\n      <div class=\"subscription-info\">\n        <h3>Options Explained:</h3>\n        <ul>\n          <li><strong>VLESS Subscription:</strong> Direct link for VLESS protocol configuration. Suitable for clients supporting VLESS.</li>\n          <li><strong>Clash Subscription:</strong> Opens the Clash client with pre-configured settings. Best for Clash users on mobile devices.</li>\n          <li><strong>Clash Link:</strong> A web link to convert the VLESS config to Clash format. Useful for manual import or troubleshooting.</li>\n          <li><strong>Best IP Subscription:</strong> Provides a curated list of optimal server IPs for many <b>different countries</b>.</li>\n        </ul>\n        <p>Choose the option that best fits your client and needs. For most users, the VLESS or Clash Subscription will be the easiest to use.</p>\n      </div>\n    </div>\n  `;\n\n\tconst configOutput = userIDArray.map((userID) => {\n\t\tconst protocolMain = atob(pt) + '://' + userID + atob(at) + hostName + \":443\" + commonUrlPart;\n\t\tconst protocolSec = atob(pt) + '://' + userID + atob(at) + proxyIP + \":\" + proxyPort + commonUrlPart;\n\t\treturn `\n      <div class=\"container config-item\">\n        <h2>UUID: ${userID}</h2>\n        <h3>Default IP Configuration</h3>\n        <div class=\"code-container\">\n          <pre><code>${protocolMain}</code></pre>\n          <button class=\"btn copy-btn\" onclick='copyToClipboard(\"${protocolMain}\")'><i class=\"fas fa-copy\"></i> Copy</button>\n        </div>\n        \n        <h3>Best IP Configuration</h3>\n        <div class=\"code-container\">\n          <pre><code>${protocolSec}</code></pre>\n          <button class=\"btn copy-btn\" onclick='copyToClipboard(\"${protocolSec}\")'><i class=\"fas fa-copy\"></i> Copy</button>\n        </div>\n      </div>\n    `;\n\t}).join('');\n\n\treturn `\n  <html>\n  ${htmlHead}\n  <body>\n    ${header}\n    ${configOutput}\n  </body>\n  <script>\n    function copyToClipboard(text) {\n      navigator.clipboard.writeText(text)\n        .then(() => {\n          alert(\"Copied to clipboard\");\n        })\n        .catch((err) => {\n          console.error(\"Failed to copy to clipboard:\", err);\n        });\n    }\n  </script>\n  </html>`;\n}\n\nconst HttpPort = new Set([80, 8080, 8880, 2052, 2086, 2095, 2082]);\nconst HttpsPort = new Set([443, 8443, 2053, 2096, 2087, 2083]);\n\nfunction GenSub(userID_path, hostname) {\n\tconst userIDArray = userID_path.includes(',') ? userID_path.split(',') : [userID_path];\n\tconst randomPath = () => '/' + Math.random().toString(36).substring(2, 15) + '?ed=2048';\n\tconst commonUrlPartHttp = `?encryption=none&security=none&fp=random&type=ws&host=${hostname}&path=${encodeURIComponent(randomPath())}#`;\n\tconst commonUrlPartHttps = `?encryption=none&security=tls&sni=${hostname}&fp=random&type=ws&host=${hostname}&path=%2F%3Fed%3D2048#`;\n\n\tconst result = userIDArray.flatMap((userID) => {\n\t\tconst PartHttp = Array.from(HttpPort).flatMap((port) => {\n\t\t\tif (!hostname.includes('pages.dev')) {\n\t\t\t\tconst urlPart = `${hostname}-HTTP-${port}`;\n\t\t\t\tconst mainProtocolHttp = atob(pt) + '://' + userID + atob(at) + hostname + ':' + port + commonUrlPartHttp + urlPart;\n\t\t\t\treturn proxyIPs.flatMap((proxyIP) => {\n\t\t\t\t\tconst secondaryProtocolHttp = atob(pt) + '://' + userID + atob(at) + proxyIP.split(':')[0] + ':' + proxyPort + commonUrlPartHttp + urlPart + '-' + proxyIP + '-' + atob(ed);\n\t\t\t\t\treturn [mainProtocolHttp, secondaryProtocolHttp];\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn [];\n\t\t});\n\n\t\tconst PartHttps = Array.from(HttpsPort).flatMap((port) => {\n\t\t\tconst urlPart = `${hostname}-HTTPS-${port}`;\n\t\t\tconst mainProtocolHttps = atob(pt) + '://' + userID + atob(at) + hostname + ':' + port + commonUrlPartHttps + urlPart;\n\t\t\treturn proxyIPs.flatMap((proxyIP) => {\n\t\t\t\tconst secondaryProtocolHttps = atob(pt) + '://' + userID + atob(at) + proxyIP.split(':')[0] + ':' + proxyPort + commonUrlPartHttps + urlPart + '-' + proxyIP + '-' + atob(ed);\n\t\t\t\treturn [mainProtocolHttps, secondaryProtocolHttps];\n\t\t\t});\n\t\t});\n\n\t\treturn [...PartHttp, ...PartHttps];\n\t});\n\n\treturn result.join('\\n');\n}\n\nconst hostnames = [\n\t'weibo.com',                // Weibo - A popular social media platform\n\t'www.baidu.com',            // Baidu - The largest search engine in China\n\t'www.qq.com',               // QQ - A widely used instant messaging platform\n\t'www.taobao.com',           // Taobao - An e-commerce website owned by Alibaba Group\n\t'www.jd.com',               // JD.com - One of the largest online retailers in China\n\t'www.sina.com.cn',          // Sina - A Chinese online media company\n\t'www.sohu.com',             // Sohu - A Chinese internet service provider\n\t'www.tmall.com',            // Tmall - An online retail platform owned by Alibaba Group\n\t'www.163.com',              // NetEase Mail - One of the major email providers in China\n\t'www.zhihu.com',            // Zhihu - A popular question-and-answer website\n\t'www.youku.com',            // Youku - A Chinese video sharing platform\n\t'www.xinhuanet.com',        // Xinhua News Agency - Official news agency of China\n\t'www.douban.com',           // Douban - A Chinese social networking service\n\t'www.meituan.com',          // Meituan - A Chinese group buying website for local services\n\t'www.toutiao.com',          // Toutiao - A news and information content platform\n\t'www.ifeng.com',            // iFeng - A popular news website in China\n\t'www.autohome.com.cn',      // Autohome - A leading Chinese automobile online platform\n\t'www.360.cn',               // 360 - A Chinese internet security company\n\t'www.douyin.com',           // Douyin - A Chinese short video platform\n\t'www.kuaidi100.com',        // Kuaidi100 - A Chinese express delivery tracking service\n\t'www.wechat.com',           // WeChat - A popular messaging and social media app\n\t'www.csdn.net',             // CSDN - A Chinese technology community website\n\t'www.imgo.tv',              // ImgoTV - A Chinese live streaming platform\n\t'www.aliyun.com',           // Alibaba Cloud - A Chinese cloud computing company\n\t'www.eyny.com',             // Eyny - A Chinese multimedia resource-sharing website\n\t'www.mgtv.com',             // MGTV - A Chinese online video platform\n\t'www.xunlei.com',           // Xunlei - A Chinese download manager and torrent client\n\t'www.hao123.com',           // Hao123 - A Chinese web directory service\n\t'www.bilibili.com',         // Bilibili - A Chinese video sharing and streaming platform\n\t'www.youth.cn',             // Youth.cn - A China Youth Daily news portal\n\t'www.hupu.com',             // Hupu - A Chinese sports community and forum\n\t'www.youzu.com',            // Youzu Interactive - A Chinese game developer and publisher\n\t'www.panda.tv',             // Panda TV - A Chinese live streaming platform\n\t'www.tudou.com',            // Tudou - A Chinese video-sharing website\n\t'www.zol.com.cn',           // ZOL - A Chinese electronics and gadgets website\n\t'www.toutiao.io',           // Toutiao - A news and information app\n\t'www.tiktok.com',           // TikTok - A Chinese short-form video app\n\t'www.netease.com',          // NetEase - A Chinese internet technology company\n\t'www.cnki.net',             // CNKI - China National Knowledge Infrastructure, an information aggregator\n\t'www.zhibo8.cc',            // Zhibo8 - A website providing live sports streams\n\t'www.zhangzishi.cc',        // Zhangzishi - Personal website of Zhang Zishi, a public intellectual in China\n\t'www.xueqiu.com',           // Xueqiu - A Chinese online social platform for investors and traders\n\t'www.qqgongyi.com',         // QQ Gongyi - Tencent's charitable foundation platform\n\t'www.ximalaya.com',         // Ximalaya - A Chinese online audio platform\n\t'www.dianping.com',         // Dianping - A Chinese online platform for finding and reviewing local businesses\n\t'www.suning.com',           // Suning - A leading Chinese online retailer\n\t'www.zhaopin.com',          // Zhaopin - A Chinese job recruitment platform\n\t'www.jianshu.com',          // Jianshu - A Chinese online writing platform\n\t'www.mafengwo.cn',          // Mafengwo - A Chinese travel information sharing platform\n\t'www.51cto.com',            // 51CTO - A Chinese IT technical community website\n\t'www.qidian.com',           // Qidian - A Chinese web novel platform\n\t'www.ctrip.com',            // Ctrip - A Chinese travel services provider\n\t'www.pconline.com.cn',      // PConline - A Chinese technology news and review website\n\t'www.cnzz.com',             // CNZZ - A Chinese web analytics service provider\n\t'www.telegraph.co.uk',      // The Telegraph - A British newspaper website\t\n\t'www.ynet.com',             // Ynet - A Chinese news portal\n\t'www.ted.com',              // TED - A platform for ideas worth spreading\n\t'www.renren.com',           // Renren - A Chinese social networking service\n\t'www.pptv.com',             // PPTV - A Chinese online video streaming platform\n\t'www.liepin.com',           // Liepin - A Chinese online recruitment website\n\t'www.881903.com',           // 881903 - A Hong Kong radio station website\n\t'www.aipai.com',            // Aipai - A Chinese online video sharing platform\n\t'www.ttpaihang.com',        // Ttpaihang - A Chinese celebrity popularity ranking website\n\t'www.quyaoya.com',          // Quyaoya - A Chinese online ticketing platform\n\t'www.91.com',               // 91.com - A Chinese software download website\n\t'www.dianyou.cn',           // Dianyou - A Chinese game information website\n\t'www.tmtpost.com',          // TMTPost - A Chinese technology media platform\n\t'www.douban.com',           // Douban - A Chinese social networking service\n\t'www.guancha.cn',           // Guancha - A Chinese news and commentary website\n\t'www.so.com',               // So.com - A Chinese search engine\n\t'www.58.com',               // 58.com - A Chinese classified advertising website\n\t'www.cnblogs.com',          // Cnblogs - A Chinese technology blog community\n\t'www.cntv.cn',              // CCTV - China Central Television official website\n\t'www.secoo.com',            // Secoo - A Chinese luxury e-commerce platform\n];\n"
  }
]