[
  {
    "path": ".github/workflows/build.yml",
    "content": "name: Build\non: [push]\njobs:\n  build:\n    name: Build\n    runs-on: ubuntu-latest\n    steps:\n\n    - name: Set up Go 1.13\n      uses: actions/setup-go@v1\n      with:\n        go-version: 1.13\n      id: go\n\n    - name: Check out code into the Go module directory\n      uses: actions/checkout@v1\n\n    - name: Get dependencies\n      run: |\n        mkdir -p ~/go/src/github.com/ihciah\n        ln -s \"$(pwd)/../rabbit-tcp\" ~/go/src/github.com/ihciah/rabbit-tcp\n        go get -v -t -d ./...\n\n    - name: Build\n      run: go build -v cmd/rabbit.go\n"
  },
  {
    "path": ".github/workflows/publish-docker.yml",
    "content": "name: Publish Docker\non:\n  push:\n    tags:\n      - 'v*'\n\njobs:\n  build:\n    name: Publish Docker\n    runs-on: ubuntu-latest\n    steps:\n\n      - name: Check out code into the Go module directory\n        uses: actions/checkout@v1\n\n      - name: Publish to Registry\n        uses: ihciah/Publish-Docker-Github-Action@master\n        with:\n          name: ihciah/rabbit\n          username: ${{ secrets.DOCKER_USERNAME }}\n          password: ${{ secrets.DOCKER_PASSWORD }}\n          spectag: ${{ github.ref }}"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: Upload Release\non:\n  push:\n    tags:\n      - 'v*'\n\njobs:\n  build:\n    name: Upload Release\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@master\n\n      - name: Set up Go 1.13\n        uses: actions/setup-go@v1\n        with:\n          go-version: 1.13\n        id: go\n\n      - name: Check out code into the Go module directory\n        uses: actions/checkout@v1\n\n      - name: Get dependencies\n        run: |\n          mkdir -p ~/go/src/github.com/ihciah\n          ln -s \"$(pwd)/../rabbit-tcp\" ~/go/src/github.com/ihciah/rabbit-tcp\n          go get -v -t -d ./...\n\n      - name: Build\n        run: |\n          TAG=${{ github.ref }}\n          TAG=${TAG#\"refs/tags/\"}\n          TAG=${TAG#\"v\"}\n          TAG=${TAG#\"V\"}\n          make releases RABBITVERSION=$TAG\n\n      - name: Create Release\n        id: create_release\n        uses: actions/create-release@v1.0.0\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          tag_name: ${{ github.ref }}\n          release_name: Release ${{ github.ref }}\n          draft: false\n          prerelease: false\n\n      - name: Upload Release windows-amd64\n        uses: actions/upload-release-asset@v1.0.1\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          upload_url: ${{ steps.create_release.outputs.upload_url }}\n          asset_path: bin/rabbit-windows-amd64.zip\n          asset_name: rabbit-windows-amd64.zip\n          asset_content_type: application/zip\n\n      - name: Upload Release windows-386\n        uses: actions/upload-release-asset@v1.0.1\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          upload_url: ${{ steps.create_release.outputs.upload_url }}\n          asset_path: bin/rabbit-windows-386.zip\n          asset_name: rabbit-windows-386.zip\n          asset_content_type: application/zip\n\n      - name: Upload Release linux-amd64\n        uses: actions/upload-release-asset@v1.0.1\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          upload_url: ${{ steps.create_release.outputs.upload_url }}\n          asset_path: bin/rabbit-linux-amd64.gz\n          asset_name: rabbit-linux-amd64.gz\n          asset_content_type: application/gzip\n\n      - name: Upload Release linux-386\n        uses: actions/upload-release-asset@v1.0.1\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          upload_url: ${{ steps.create_release.outputs.upload_url }}\n          asset_path: bin/rabbit-linux-386.gz\n          asset_name: rabbit-linux-386.gz\n          asset_content_type: application/gzip\n\n      - name: Upload Release linux-arm64\n        uses: actions/upload-release-asset@v1.0.1\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          upload_url: ${{ steps.create_release.outputs.upload_url }}\n          asset_path: bin/rabbit-linux-arm64.gz\n          asset_name: rabbit-linux-arm64.gz\n          asset_content_type: application/gzip\n\n      - name: Upload Release linux-arm\n        uses: actions/upload-release-asset@v1.0.1\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          upload_url: ${{ steps.create_release.outputs.upload_url }}\n          asset_path: bin/rabbit-linux-arm.gz\n          asset_name: rabbit-linux-arm.gz\n          asset_content_type: application/gzip\n\n      - name: Upload Release darwin-amd64\n        uses: actions/upload-release-asset@v1.0.1\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          upload_url: ${{ steps.create_release.outputs.upload_url }}\n          asset_path: bin/rabbit-darwin-amd64.gz\n          asset_name: rabbit-darwin-amd64.gz\n          asset_content_type: application/gzip\n\n      - name: Upload Release darwin-386\n        uses: actions/upload-release-asset@v1.0.1\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        with:\n          upload_url: ${{ steps.create_release.outputs.upload_url }}\n          asset_path: bin/rabbit-darwin-386.gz\n          asset_name: rabbit-darwin-386.gz\n          asset_content_type: application/gzip"
  },
  {
    "path": ".gitignore",
    "content": "# Binaries for programs and plugins\n*.exe\n*.exe~\n*.dll\n*.so\n*.dylib\n\n# Test binary, build with `go test -c`\n*.test\n\n# Output of the go coverage tool, specifically when used with LiteIDE\n*.out\n\n# idea\n.idea\n/bin\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM golang:1-alpine AS builder\n\nRUN mkdir -p /go/src/github.com/ihciah/rabbit-tcp\nCOPY . /go/src/github.com/ihciah/rabbit-tcp\n\nRUN apk upgrade \\\n    && apk add git \\\n    && apk add make \\\n    && cd /go/src/github.com/ihciah/rabbit-tcp \\\n    && go get -v -t -d ./... \\\n    && make\n\nFROM alpine:latest AS dist\nLABEL maintainer=\"ihciah <ihciah@gmail.com>\"\n\nENV MODE s\nENV PASSWORD PASSWORD\nENV RABBITADDR :443\nENV LISTEN :9891\nENV DEST=\nENV TUNNELN 6\nENV VERBOSE 2\n\nCOPY --from=builder /go/src/github.com/ihciah/rabbit-tcp/bin/rabbit /usr/bin/rabbit\n\nCMD exec rabbit \\\n      --mode=$MODE \\\n      --password=$PASSWORD \\\n      --rabbit-addr=$RABBITADDR \\\n      --listen=$LISTEN \\\n      --dest=$DEST \\\n      --tunnelN=$TUNNELN \\\n      --verbose=$VERBOSE"
  },
  {
    "path": "LICENCE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 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 Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\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,\nour General Public Licenses are 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.\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  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\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 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 work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be 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 Affero 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 Affero 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 Affero 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 Affero General Public License as published\n    by 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 Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\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 AGPL, see\n<https://www.gnu.org/licenses/>."
  },
  {
    "path": "Makefile",
    "content": "NAME=rabbit\nBINDIR=bin\nVERSIONPARAM=\nifdef RABBITVERSION\n\tVERSIONPARAM=-X 'main.Version=$(RABBITVERSION)'\nendif\nGOBUILD=CGO_ENABLED=0 go build -ldflags \"-w -s $(VERSIONPARAM)\"\nBUILDFILE=cmd/rabbit.go\n\ncurrent:\n\t$(GOBUILD) -o $(BINDIR)/$(NAME) $(BUILDFILE)\n\nall: linux-amd64 linux-386 linux-arm64 linux-arm darwin-amd64 darwin-386 windows-amd64 windows-386\n\nlinux-amd64:\n\tGOARCH=amd64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@ $(BUILDFILE)\n\nlinux-386:\n\tGOARCH=386 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@ $(BUILDFILE)\n\nlinux-arm64:\n\tGOARCH=arm64 GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@ $(BUILDFILE)\n\nlinux-arm:\n\tGOARCH=arm GOOS=linux $(GOBUILD) -o $(BINDIR)/$(NAME)-$@ $(BUILDFILE)\n\ndarwin-amd64:\n\tGOARCH=amd64 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@ $(BUILDFILE)\n\ndarwin-386:\n\tGOARCH=386 GOOS=darwin $(GOBUILD) -o $(BINDIR)/$(NAME)-$@ $(BUILDFILE)\n\nwindows-amd64:\n\tGOARCH=amd64 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe $(BUILDFILE)\n\nwindows-386:\n\tGOARCH=386 GOOS=windows $(GOBUILD) -o $(BINDIR)/$(NAME)-$@.exe $(BUILDFILE)\n\nreleases: linux-amd64 linux-386 linux-arm64 linux-arm darwin-amd64 darwin-386 windows-amd64 windows-386\n\tchmod +x $(BINDIR)/$(NAME)-*\n\tgzip $(BINDIR)/$(NAME)-linux-amd64\n\tgzip $(BINDIR)/$(NAME)-linux-386\n\tgzip $(BINDIR)/$(NAME)-linux-arm64\n\tgzip $(BINDIR)/$(NAME)-linux-arm\n\tgzip $(BINDIR)/$(NAME)-darwin-amd64\n\tgzip $(BINDIR)/$(NAME)-darwin-386\n\tzip -m -j $(BINDIR)/$(NAME)-windows-amd64.zip $(BINDIR)/$(NAME)-windows-amd64.exe\n\tzip -m -j $(BINDIR)/$(NAME)-windows-386.zip $(BINDIR)/$(NAME)-windows-386.exe\n\nclean:\n\trm $(BINDIR)/*"
  },
  {
    "path": "README.MD",
    "content": "# Rabbit TCP\n\n![Build badge](https://github.com/ihciah/rabbit-tcp/workflows/Build/badge.svg) ![Docker pull badge](https://img.shields.io/docker/pulls/ihciah/rabbit)\n\nA multi-connection TCP forwarder created for accelerating TCP connections\n\nEnglish | [中文](README_ZH.MD)\n\n## Introduction\n\nThis project is created to support and forward TCP connections. It will split bytes into blocks and reconstruct them during forwarding.\nAll upper connections visible to all users are carried by `N` underlying physical connections, and even a single upper connection is forwarded through all underlying connections.\n\nDue to the use of multiple connections, similar to the multi-threaded downloader, this project can accelerate the connection without any more traffic consumption (bilateral deployment is required).\nThis project the extension of the accelerating method of [ShadowSocks-magic](https://github.com/ihciah/go-shadowsocks-magic).\n\n![Rabbit TCP](.github/resources/rabbit-tcp.svg)\n\n## Get Started\nThis project can work in standalone proxy mode or inline in other Golang code.\n\nHere are two common usage examples. For detailed documentation, please go to the [Wiki](https://github.com/ihciah/rabbit-tcp/wiki).\n\n### Accelerate any TCP service in a standalone proxy mode\n#### Server side\n1. Install [Docker](https://docs.docker.com/install/linux/docker-ce/debian/#install-using-the-convenience-script) and [docker-compose](https://docs.docker.com/compose/install/)\n2. Download and edit `docker-compose-server.yml` ([Link](https://github.com/ihciah/rabbit-tcp/raw/master/docker-compose-server.yml))\n    ```yaml\n    rabbit-server:\n      image: ihciah/rabbit\n      ports:\n        - \"$RABBIT_PORT:9891/tcp\"\n      environment:\n        - MODE=s\n        - PASSWORD=$RABBIT_PASSWORD\n        - RABBITADDR=:9891\n        - VERBOSE=2\n      restart: always\n    ```\n   - `$RABBIT_PORT` replaced with RabbitTCP service port, which should be the same as the client side\n   - `$RABBIT_PASSWORD`  replaced with RabbitTCP service password, which should be the same as the client side\n3. Run in the same directory `docker-compose -f docker-compose-server.yml up -d`\n\n#### Client side\n1. Install [Docker](https://docs.docker.com/install/linux/docker-ce/debian/#install-using-the-convenience-script) and [docker-compose](https://docs.docker.com/compose/install/)\n2. Download and edit `docker-compose-client.yml` ([Link](https://github.com/ihciah/rabbit-tcp/raw/master/docker-compose-client.yml))\n    ```yaml\n    rabbit-client:\n      image: ihciah/rabbit\n      ports:\n        - \"$CLIENT_LISTEN_PORT:9892/tcp\"\n      environment:\n        - MODE=c\n        - PASSWORD=$RABBIT_PASSWORD\n        - RABBITADDR=$RABBIT_ADDR\n        - LISTEN=:9892\n        - DEST=$SERVICE_ADDR\n        - TUNNELN=6\n        - VERBOSE=2\n      restart: always\n    ```\n   - `$RABBIT_ADDR` replaced with `ip_or_domain:port` , which should be the same as the server side\n   - `$RABBIT_PASSWORD` replaced with RabbitTCP service password, which should be the same as the server side\n   - `$SERVICE_ADDR` replaced with the `ip_or_domain:port` of the target service\n   - `$CLIENT_LISTEN_PORT` replaced with local listen port, which can be dialed when connecting to the target service with acceleration.\n   - Modify `TUNNELN` if you want to change count of physical connections\n3. Run in the same directory `docker-compose -f docker-compose-server.yml up -d`\n\n### Accelerate ShadowSocks service in a standalone proxy mode with plugin\nThe server-side configuration is the same as above. Please note that except for Rabbit TCP server, you have to [run ShadowSocks service](https://github.com/shadowsocks/shadowsocks-libev/blob/master/docker/alpine/docker-compose.yml) too.\n\nConfigure client-side as above is useful too if you want to run a forwarder on a server inside the blocked area.\n\nHowever, run docker or daemon service on client devices is not so user-friendly. What recommended is the plugin built for ShadowSocks: [Rabbit Plugin](https://github.com/ihciah/rabbit-plugin).\n\n1. [Download the latest Rabbit Plugin release](https://github.com/ihciah/rabbit-plugin/releases), unzip it and put it into the ShadowSocks folder(same as ShadowSocks.exe).\n2. Fill in ShadowSocks client configuration(Take [ShadowSocks Windows](https://github.com/shadowsocks/shadowsocks-windows) as an example)\n    - Server Addr: Rabbit TCP service ip/domain\n    - Server Port: Rabbit TCP service port\n    - Password: ShadowSocks password\n    - Encryption: ShadowSocks Encryption\n    - Plugin Program: The binary filename(without `.exe`)\n    - Plugin Options: `serviceAddr=SHADOWSOCKS_ADDR;password=RABBIT_PASSWORD;tunnelN=4`\n        - `SHADOWSOCKS_ADDR` is ShadowSocks server address(ip:port or domain:port), for example: `10.10.10.10:443`\n        - `RABBIT_PASSWORD` is Rabbit TCP password\n        - Modify `tunnelN` to change count of physical connections\n3. Save\n\n## Speedup Result\n\nEnvironment:\n\n- `Chrome <--> ShadowsocksWindows <--> RabbitTCP <==[ISP]==> RabbitTCP <--> ShadowsocksLibev`\n- Local ISP: China Unicom - Shanghai\n- Remote ISP: Amazon LightSail - Tokyo\n- Physical Connections Count: 4\n\n\nSpeedup with Rabbit TCP([Link](https://www.speedtest.net/result/8667412671)):\n\n![Speed with rabbit-tcp](.github/resources/SpeedWithRabbit.jpg)\n\nOriginal ShadowSocks libev([Link](https://www.speedtest.net/result/8667415664)):\n\n![Speed without rabbit-tcp](.github/resources/SpeedWithoutRabbit.jpg)\n"
  },
  {
    "path": "README_ZH.MD",
    "content": "# Rabbit TCP\n\n![Build badge](https://github.com/ihciah/rabbit-tcp/workflows/Build/badge.svg) ![Docker pull badge](https://img.shields.io/docker/pulls/ihciah/rabbit)\n\n一个为加速而生的多连接 TCP 转发器\n\n[English](README.MD) | 中文\n\n## 简介\n\n这个项目用来承载并转发 TCP 流量，并在转发时对流量进行分拆与重组。\n所有用户可见的上层连接均由 `N` 条底层物理连接承载，即便是单条用户连接也会经所有底层连接进行转发。\n\n由于使用了多条连接，与多线程下载器类似，本项目可以在不多消耗流量的情况下对连接进行加速（需双边部署）。\n这个项目是 [ShadowSocks-magic](https://github.com/ihciah/go-shadowsocks-magic) 中加速方案的扩展。\n\n![Rabbit TCP](.github/resources/rabbit-tcp.svg)\n\n## 开始使用\n本项目既可以以独立代理模式工作，也可以内嵌在其他 Golang 代码中提供服务。\n\n以下列举两种常用用法，详细的文档请移步 [Wiki](https://github.com/ihciah/rabbit-tcp/wiki)。\n\n### 以独立代理模式加速任意 TCP 服务\n#### 服务端\n1. 安装 [Docker](https://docs.docker.com/install/linux/docker-ce/debian/#install-using-the-convenience-script) 和 [docker-compose](https://docs.docker.com/compose/install/)\n2. 下载并修改 `docker-compose-server.yml` 文件([链接](https://github.com/ihciah/rabbit-tcp/raw/master/docker-compose-server.yml))\n    ```yaml\n    rabbit-server:\n      image: ihciah/rabbit\n      ports:\n        - \"$RABBIT_PORT:9891/tcp\"\n      environment:\n        - MODE=s\n        - PASSWORD=$RABBIT_PASSWORD\n        - RABBITADDR=:9891\n        - VERBOSE=2\n      restart: always\n    ```\n   - `$RABBIT_PORT` 替换为 RabbitTCP 服务端口，与 Client 保持一致即可\n   - `$RABBIT_PASSWORD` 替换为 RabbitTCP 服务密码，与 Client 保持一致即可\n3. 在该文件同目录运行 `docker-compose -f docker-compose-server.yml up -d`\n\n#### 客户端\n1. 安装 [Docker](https://docs.docker.com/install/linux/docker-ce/debian/#install-using-the-convenience-script) 和 [docker-compose](https://docs.docker.com/compose/install/)\n2. 下载并修改 `docker-compose-client.yml` 文件([链接](https://github.com/ihciah/rabbit-tcp/raw/master/docker-compose-client.yml))\n    ```yaml\n    rabbit-client:\n      image: ihciah/rabbit\n      ports:\n        - \"$CLIENT_LISTEN_PORT:9892/tcp\"\n      environment:\n        - MODE=c\n        - PASSWORD=$RABBIT_PASSWORD\n        - RABBITADDR=$RABBIT_ADDR\n        - LISTEN=:9892\n        - DEST=$SERVICE_ADDR\n        - TUNNELN=6\n        - VERBOSE=2\n      restart: always\n    ```\n   - `$RABBIT_ADDR` 替换为 RabbitTCP 服务 `地址:端口` ，端口与服务端保持一致即可\n   - `$RABBIT_PASSWORD` 替换为 RabbitTCP 服务密码，与服务端保持一致即可\n   - `$SERVICE_ADDR` 替换为待加速的服务 `地址:端口` \n   - `$CLIENT_LISTEN_PORT` 替换为本地监听端口，后续若要加速访问目标服务，连接该端口即可\n   - 修改 `TUNNELN` 可以控制底层物理连接数\n3. 在该文件同目录运行 `docker-compose -f docker-compose-server.yml up -d`\n\n### 以独立代理 + 插件模式加速 ShadowSocks 服务\n服务端配置同上。请注意 Rabbit TCP 并不包含 ShadowSocks，你仍然需要[运行 ShadowSocks](https://github.com/shadowsocks/shadowsocks-libev/blob/master/docker/alpine/docker-compose.yml)。\n\n客户端可以按照上述配置，如运行在国内服务器上用作中转。\n\n在用户终端上，运行 Docker 或直接运行后台服务较为麻烦。推荐使用为 ShadowSocks 定制的插件 [Rabbit Plugin](https://github.com/ihciah/rabbit-plugin)。\n\n1. [下载最新 Rabbit Plugin 发布版](https://github.com/ihciah/rabbit-plugin/releases)并解压缩后放入 ShadowSocks 同目录\n2. 在 ShadowSocks 客户端中填写信息(以 [ShadowSocks Windows](https://github.com/shadowsocks/shadowsocks-windows) 为例)\n    - 服务器地址填写 Rabbit TCP 服务器\n    - 服务器端口填写 Rabbit TCP 端口\n    - 密码填写 ShadowSocks 密码\n    - 加密方式填写 ShadowSocks 加密方式\n    - 插件程序填写刚刚放入的插件程序文件名(不包含 `.exe` 后缀)\n    - 插件选项填写 `serviceAddr=SHADOWSOCKS_ADDR;password=RABBIT_PASSWORD;tunnelN=4`\n        - `SHADOWSOCKS_ADDR` 替换为 ShadowSocks 服务地址（包含端口），如 `10.10.10.10:443`\n        - `RABBIT_PASSWORD` 替换为 Rabbit TCP 密码，与服务端保持一致\n        - 修改 `tunnelN` 对应数值控制底层物理连接个数\n3. 保存即可\n\n## 加速效果\n\n测试环境:\n\n- `Chrome <--> ShadowsocksWindows <--> RabbitTCP <==[ISP]==> RabbitTCP <--> ShadowsocksLibev`\n- 本地运营商: 中国联通 - 上海\n- 远程运营商: Amazon LightSail - 东京\n- 底层连接数: 4\n\n\n使用 Rabbit TCP 加速([Link](https://www.speedtest.net/result/8667412671)):\n\n![Speed with rabbit-tcp](.github/resources/SpeedWithRabbit.jpg)\n\n使用原版 ShadowSocks-libev([Link](https://www.speedtest.net/result/8667415664)):\n\n![Speed without rabbit-tcp](.github/resources/SpeedWithoutRabbit.jpg)\n\n"
  },
  {
    "path": "block/block.go",
    "content": "package block\n\nimport (\n\t\"encoding/binary\"\n\t\"io\"\n\n\t\"go.uber.org/atomic\"\n)\n\nconst (\n\tTypeConnect = iota\n\tTypeDisconnect\n\tTypeData\n\n\tShutdownRead = iota\n\tShutdownWrite\n\tShutdownBoth\n\n\tHeaderSize = 1 + 4 + 4 + 4\n\tDataSize   = 16*1024 - 13\n\tMaxSize    = HeaderSize + DataSize\n)\n\ntype Block struct {\n\tType         uint8  // 1 byte\n\tConnectionID uint32 // 4 bytes\n\tBlockID      uint32 // 4 bytes\n\tBlockLength  uint32 // 4 bytes\n\tBlockData    []byte\n\tpacked       []byte\n}\n\nfunc (block *Block) Pack() []byte {\n\tif block.packed != nil {\n\t\treturn block.packed\n\t}\n\tblock.packed = make([]byte, HeaderSize+len(block.BlockData))\n\tblock.packed[0] = block.Type\n\tbinary.LittleEndian.PutUint32(block.packed[1:], block.ConnectionID)\n\tbinary.LittleEndian.PutUint32(block.packed[5:], block.BlockID)\n\tbinary.LittleEndian.PutUint32(block.packed[9:], block.BlockLength)\n\tcopy(block.packed[HeaderSize:], block.BlockData)\n\treturn block.packed\n}\n\nfunc NewBlockFromReader(reader io.Reader) (*Block, error) {\n\theaderBuf := make([]byte, HeaderSize)\n\tblock := Block{}\n\t_, err := io.ReadFull(reader, headerBuf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblock.Type = headerBuf[0]\n\tblock.ConnectionID = binary.LittleEndian.Uint32(headerBuf[1:])\n\tblock.BlockID = binary.LittleEndian.Uint32(headerBuf[5:])\n\tblock.BlockLength = binary.LittleEndian.Uint32(headerBuf[9:])\n\tblock.BlockData = make([]byte, block.BlockLength)\n\tif block.BlockLength > 0 {\n\t\t_, err = io.ReadFull(reader, block.BlockData)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &block, nil\n}\n\nfunc NewConnectBlock(connectID uint32, blockID uint32, address string) Block {\n\tdata := []byte(address)\n\treturn Block{\n\t\tType:         TypeConnect,\n\t\tConnectionID: connectID,\n\t\tBlockID:      blockID,\n\t\tBlockLength:  uint32(len(data)),\n\t\tBlockData:    data,\n\t}\n}\n\nfunc newDataBlock(connectID uint32, blockID uint32, data []byte) Block {\n\t// We should copy data now\n\tblk := Block{\n\t\tType:         TypeData,\n\t\tConnectionID: connectID,\n\t\tBlockID:      blockID,\n\t\tBlockLength:  uint32(len(data)),\n\t\tBlockData:    data,\n\t}\n\tblk.Pack()\n\treturn blk\n}\n\nfunc NewDataBlocks(connectID uint32, blockID *atomic.Uint32, data []byte) []Block {\n\tblocks := make([]Block, 0)\n\tfor cursor := 0; cursor < len(data); {\n\t\tend := cursor + DataSize\n\t\tif len(data) < end {\n\t\t\tend = len(data)\n\t\t}\n\t\tblocks = append(blocks, newDataBlock(connectID, blockID.Inc()-1, data[cursor:end]))\n\t\tcursor = end\n\t}\n\treturn blocks\n}\n\nfunc NewDisconnectBlock(connectID uint32, blockID uint32, shutdownType uint8) Block {\n\treturn Block{\n\t\tType:         TypeDisconnect,\n\t\tConnectionID: connectID,\n\t\tBlockID:      blockID,\n\t\tBlockLength:  1,\n\t\tBlockData:    []byte{shutdownType},\n\t}\n}\n"
  },
  {
    "path": "client/client.go",
    "content": "package client\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/ihciah/rabbit-tcp/connection\"\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"github.com/ihciah/rabbit-tcp/peer\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel\"\n)\n\ntype Client struct {\n\tpeer   peer.ClientPeer\n\tlogger *logger.Logger\n}\n\nfunc NewClient(tunnelNum int, endpoint string, cipher tunnel.Cipher) Client {\n\treturn Client{\n\t\tpeer:   peer.NewClientPeer(tunnelNum, endpoint, cipher),\n\t\tlogger: logger.NewLogger(\"[Client]\"),\n\t}\n}\n\nfunc (c *Client) Dial(address string) connection.HalfOpenConn {\n\treturn c.peer.Dial(address)\n}\n\nfunc (c *Client) ServeForward(listen, dest string) error {\n\tlistener, err := net.Listen(\"tcp\", listen)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tc.logger.Errorf(\"Error when accept connection: %v.\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tgo func() {\n\t\t\tc.logger.Infoln(\"Accepted a connection.\")\n\t\t\tconnProxy := c.Dial(dest)\n\t\t\tbiRelay(conn.(*net.TCPConn), connProxy, c.logger)\n\t\t}()\n\t}\n}\n\nfunc biRelay(left, right connection.HalfOpenConn, logger *logger.Logger) {\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo relay(left, right, &wg, logger, \"local <- tunnel\")\n\twg.Add(1)\n\tgo relay(right, left, &wg, logger, \"local -> tunnel\")\n\twg.Wait()\n\t// logger.Errorf(\"===========> Close client biRelay\")\n\t_ = left.Close()\n\t_ = right.Close()\n}\n\nfunc relay(dst, src connection.HalfOpenConn, wg *sync.WaitGroup, logger *logger.Logger, label string) {\n\tdefer wg.Done()\n\t_, err := io.Copy(dst, src)\n\tif err != nil {\n\t\t_ = dst.SetDeadline(time.Now())\n\t\t_ = src.SetDeadline(time.Now())\n\t\t_ = dst.Close()\n\t\t_ = src.Close()\n\t\tif err != io.EOF {\n\t\t\tlogger.Errorf(\"Error when relay client: %v.\\n\", err)\n\t\t}\n\t} else {\n\t\t// logger.Debugf(\"!!!!!!!!!!!!!!!! %s : dst close write\", label)\n\t\tdst.CloseWrite()\n\t\t// logger.Debugf(\"!!!!!!!!!!!!!!!! %s : src close read\", label)\n\t\tsrc.CloseRead()\n\t}\n}\n"
  },
  {
    "path": "cmd/rabbit.go",
    "content": "package main\n\nimport (\n\t\"flag\"\n\t\"github.com/ihciah/rabbit-tcp/client\"\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"github.com/ihciah/rabbit-tcp/server\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel\"\n\t\"log\"\n\t\"strings\"\n)\n\nvar Version = \"No version information\"\n\nconst (\n\tClientMode = iota\n\tServerMode\n\tDefaultPassword = \"PASSWORD\"\n)\n\nfunc parseFlags() (pass bool, mode int, password string, addr string, listen string, dest string, tunnelN int, verbose int) {\n\tvar modeString string\n\tvar printVersion bool\n\tflag.StringVar(&modeString, \"mode\", \"c\", \"running mode(s or c)\")\n\tflag.StringVar(&password, \"password\", DefaultPassword, \"password\")\n\tflag.StringVar(&addr, \"rabbit-addr\", \":443\", \"listen(server mode) or remote(client mode) address used by rabbit-tcp\")\n\tflag.StringVar(&listen, \"listen\", \"\", \"[Client Only] listen address, eg: 127.0.0.1:2333\")\n\tflag.StringVar(&dest, \"dest\", \"\", \"[Client Only] destination address, eg: shadowsocks server address\")\n\tflag.IntVar(&tunnelN, \"tunnelN\", 4, \"[Client Only] number of tunnels to use in rabbit-tcp\")\n\tflag.IntVar(&verbose, \"verbose\", 2, \"verbose level(0~5)\")\n\tflag.BoolVar(&printVersion, \"version\", false, \"show version\")\n\tflag.Parse()\n\n\tpass = true\n\n\t// version\n\tif printVersion {\n\t\tlog.Println(\"Rabbit TCP (https://github.com/ihciah/rabbit-tcp/)\")\n\t\tlog.Printf(\"Version: %s.\\n\", Version)\n\t\tpass = false\n\t\treturn\n\t}\n\n\t// mode\n\tmodeString = strings.ToLower(modeString)\n\tif modeString == \"c\" || modeString == \"client\" {\n\t\tmode = ClientMode\n\t} else if modeString == \"s\" || modeString == \"server\" {\n\t\tmode = ServerMode\n\t} else {\n\t\tlog.Printf(\"Unsupported mode %s.\\n\", modeString)\n\t\tpass = false\n\t\treturn\n\t}\n\n\t// password\n\tif password == \"\" {\n\t\tlog.Println(\"Password must be specified.\")\n\t\tpass = false\n\t\treturn\n\t}\n\tif password == DefaultPassword {\n\t\tlog.Println(\"Password must be changed instead of default password.\")\n\t\tpass = false\n\t\treturn\n\t}\n\n\t// listen, dest, tunnelN\n\tif mode == ClientMode {\n\t\tif listen == \"\" {\n\t\t\tlog.Println(\"Listen address must be specified in client mode.\")\n\t\t\tpass = false\n\t\t}\n\t\tif dest == \"\" {\n\t\t\tlog.Println(\"Destination address must be specified in client mode.\")\n\t\t\tpass = false\n\t\t}\n\t\tif tunnelN == 0 {\n\t\t\tlog.Println(\"Tunnel number must be positive.\")\n\t\t\tpass = false\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\tpass, mode, password, addr, listen, dest, tunnelN, verbose := parseFlags()\n\tif !pass {\n\t\treturn\n\t}\n\tcipher, _ := tunnel.NewAEADCipher(\"CHACHA20-IETF-POLY1305\", nil, password)\n\tlogger.LEVEL = verbose\n\tif mode == ClientMode {\n\t\tc := client.NewClient(tunnelN, addr, cipher)\n\t\tc.ServeForward(listen, dest)\n\t} else {\n\t\ts := server.NewServer(cipher)\n\t\ts.Serve(addr)\n\t}\n}\n"
  },
  {
    "path": "connection/block_processor.go",
    "content": "package connection\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com/ihciah/rabbit-tcp/block\"\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"go.uber.org/atomic\"\n)\n\n// 1. Join blocks from chan to connection orderedRecvQueue\n// 2. Send bytes or control block\ntype blockProcessor struct {\n\tcache          map[uint32]block.Block\n\tlogger         *logger.Logger\n\trelayCtx       context.Context\n\tremoveFromPool context.CancelFunc\n\n\tsendBlockID     atomic.Uint32\n\trecvBlockID     uint32\n\tlastRecvBlockID uint32\n}\n\nfunc newBlockProcessor(ctx context.Context, removeFromPool context.CancelFunc) blockProcessor {\n\treturn blockProcessor{\n\t\tcache:          make(map[uint32]block.Block),\n\t\trelayCtx:       ctx,\n\t\tremoveFromPool: removeFromPool,\n\t\tlogger:         logger.NewLogger(\"[BlockProcessor]\"),\n\t}\n}\n\n// Join blocks and send buffer to connection\n// TODO: If waiting a packet for TIMEOUT, break the connection; otherwise re-countdown for next waiting packet.\nfunc (x *blockProcessor) OrderedRelay(connection Connection) {\n\tx.logger.Infof(\"Ordered Relay of Connection %d started.\\n\", connection.GetConnectionID())\n\tfor {\n\t\tselect {\n\t\tcase blk := <-connection.getRecvQueue():\n\t\t\tif blk.BlockID+1 > x.lastRecvBlockID {\n\t\t\t\t// Update lastRecvBlockID\n\t\t\t\tx.lastRecvBlockID = blk.BlockID + 1\n\t\t\t}\n\t\t\tif x.recvBlockID == blk.BlockID {\n\t\t\t\t// Can send directly\n\t\t\t\tx.logger.Debugf(\"Send Block %d directly\\n\", blk.BlockID)\n\t\t\t\tconnection.getOrderedRecvQueue() <- blk\n\t\t\t\tx.recvBlockID++\n\t\t\t\tfor {\n\t\t\t\t\tblk, ok := x.cache[x.recvBlockID]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tx.logger.Debugf(\"Send Block %d from cache\\n\", blk.BlockID)\n\t\t\t\t\tconnection.getOrderedRecvQueue() <- blk\n\t\t\t\t\tdelete(x.cache, x.recvBlockID)\n\t\t\t\t\tx.recvBlockID++\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Cannot send directly\n\t\t\t\tif blk.BlockID < x.recvBlockID {\n\t\t\t\t\t// We don't need this old block\n\t\t\t\t\tx.logger.Debugf(\"Block %d is too old to cache\\n\", blk.BlockID)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tx.logger.Debugf(\"Put Block %d to cache\\n\", blk.BlockID)\n\t\t\t\tx.cache[blk.BlockID] = blk\n\t\t\t}\n\t\tcase <-time.After(PacketWaitTimeoutSec * time.Second):\n\t\t\tx.logger.Debugf(\"Packet wait time exceed of Connection %d.\\n\", connection.GetConnectionID())\n\t\t\tif x.recvBlockID == x.lastRecvBlockID {\n\t\t\t\tx.logger.Debugf(\"recvBlockId == lastRecvBlockID(%d), but Connection %d is not in waiting status, continue.\\n\", x.recvBlockID, connection.GetConnectionID())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tx.logger.Warnf(\"Connection %d is going to be killed due to timeout.\\n\", connection.GetConnectionID())\n\t\t\tx.removeFromPool()\n\t\tcase <-x.relayCtx.Done():\n\t\t\tx.logger.Infof(\"Ordered Relay of Connection %d stopped.\\n\", connection.GetConnectionID())\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (x *blockProcessor) packData(data []byte, connectionID uint32) []block.Block {\n\treturn block.NewDataBlocks(connectionID, &x.sendBlockID, data)\n}\n\nfunc (x *blockProcessor) packConnect(address string, connectionID uint32) block.Block {\n\treturn block.NewConnectBlock(connectionID, x.sendBlockID.Inc()-1, address)\n}\n\nfunc (x *blockProcessor) packDisconnect(connectionID uint32, shutdownType uint8) block.Block {\n\treturn block.NewDisconnectBlock(connectionID, x.sendBlockID.Inc()-1, shutdownType)\n}\n"
  },
  {
    "path": "connection/connection.go",
    "content": "package connection\n\nimport (\n\t\"net\"\n\n\t\"github.com/ihciah/rabbit-tcp/block\"\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"go.uber.org/atomic\"\n)\n\ntype HalfOpenConn interface {\n\tnet.Conn\n\tCloseRead() error\n\tCloseWrite() error\n}\n\ntype CloseWrite interface {\n\tCloseWrite() error\n}\n\ntype CloseRead interface {\n\tCloseRead() error\n}\n\ntype Connection interface {\n\tHalfOpenConn\n\tGetConnectionID() uint32\n\tgetOrderedRecvQueue() chan block.Block\n\tgetRecvQueue() chan block.Block\n\n\tRecvBlock(block.Block)\n\n\tSendConnect(address string)\n\tSendDisconnect(uint8)\n\n\tOrderedRelay(connection Connection) // Run orderedRelay infinitely\n\tStop()                              // Stop all related relay and remove itself from connectionPool\n}\n\ntype baseConnection struct {\n\tblockProcessor   blockProcessor\n\tconnectionID     uint32\n\tclosed           *atomic.Bool\n\tsendQueue        chan<- block.Block // Same as connectionPool\n\trecvQueue        chan block.Block\n\torderedRecvQueue chan block.Block\n\tlogger           *logger.Logger\n}\n\nfunc (bc *baseConnection) Stop() {\n\tbc.logger.Debugf(\"connection stop\\n\")\n\tbc.blockProcessor.removeFromPool()\n}\n\nfunc (bc *baseConnection) OrderedRelay(connection Connection) {\n\tbc.blockProcessor.OrderedRelay(connection)\n}\n\nfunc (bc *baseConnection) GetConnectionID() uint32 {\n\treturn bc.connectionID\n}\n\nfunc (bc *baseConnection) getRecvQueue() chan block.Block {\n\treturn bc.recvQueue\n}\n\nfunc (bc *baseConnection) getOrderedRecvQueue() chan block.Block {\n\treturn bc.orderedRecvQueue\n}\n\nfunc (bc *baseConnection) RecvBlock(blk block.Block) {\n\tbc.recvQueue <- blk\n}\n\nfunc (bc *baseConnection) SendConnect(address string) {\n\tbc.logger.Debugf(\"Send connect to %s block.\\n\", address)\n\tblk := bc.blockProcessor.packConnect(address, bc.connectionID)\n\tbc.sendQueue <- blk\n}\n\nfunc (bc *baseConnection) SendDisconnect(shutdownType uint8) {\n\tbc.logger.Debugf(\"Send disconnect block: %v\\n\", shutdownType)\n\tblk := bc.blockProcessor.packDisconnect(bc.connectionID, shutdownType)\n\tbc.sendQueue <- blk\n\tif shutdownType == block.ShutdownBoth {\n\t\tbc.Stop()\n\t}\n}\n\nfunc (bc *baseConnection) sendData(data []byte) {\n\tbc.logger.Debugln(\"Send data block.\")\n\tblocks := bc.blockProcessor.packData(data, bc.connectionID)\n\tfor _, blk := range blocks {\n\t\tbc.sendQueue <- blk\n\t}\n}\n"
  },
  {
    "path": "connection/const.go",
    "content": "package connection\n\nconst (\n\tOrderedRecvQueueSize    = 24        // OrderedRecvQueue channel cap\n\tRecvQueueSize           = 24        // RecvQueue channel cap\n\tOutboundRecvBuffer      = 16 * 1024 // 16K receive buffer for Outbound Connection\n\tOutboundBlockTimeoutSec = 3         // Wait the period and check exit signal\n\tPacketWaitTimeoutSec    = 7         // If block processor is waiting for a \"hole\", and no packet comes within this limit, the Connection will be closed\n)\n"
  },
  {
    "path": "connection/inbound_connection.go",
    "content": "package connection\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"math/rand\"\n\t\"net\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/ihciah/rabbit-tcp/block\"\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"go.uber.org/atomic\"\n)\n\ntype InboundConnection struct {\n\tbaseConnection\n\tdataBuffer ByteRingBuffer\n\n\twriteCtx context.Context\n\treadCtx  context.Context\n\n\treadClosed  *atomic.Bool\n\twriteClosed *atomic.Bool\n}\n\nfunc NewInboundConnection(sendQueue chan<- block.Block, ctx context.Context, removeFromPool context.CancelFunc) Connection {\n\tconnectionID := rand.Uint32()\n\tc := InboundConnection{\n\t\tbaseConnection: baseConnection{\n\t\t\tblockProcessor:   newBlockProcessor(ctx, removeFromPool),\n\t\t\tconnectionID:     connectionID,\n\t\t\tclosed:           atomic.NewBool(false),\n\t\t\tsendQueue:        sendQueue,\n\t\t\trecvQueue:        make(chan block.Block, RecvQueueSize),\n\t\t\torderedRecvQueue: make(chan block.Block, OrderedRecvQueueSize),\n\t\t\tlogger:           logger.NewLogger(fmt.Sprintf(\"[InboundConnection-%d]\", connectionID)),\n\t\t},\n\t\tdataBuffer:  NewByteRingBuffer(block.MaxSize),\n\t\treadCtx:     ctx,\n\t\twriteCtx:    ctx,\n\t\treadClosed:  atomic.NewBool(false),\n\t\twriteClosed: atomic.NewBool(false),\n\t}\n\tc.logger.Infof(\"InboundConnection %d created.\\n\", connectionID)\n\treturn &c\n}\n\nfunc (c *InboundConnection) Read(b []byte) (n int, err error) {\n\treadN := 0\n\n\tif !c.dataBuffer.Empty() {\n\t\t// There's something left in buffer\n\t\treadN += c.dataBuffer.Read(b)\n\t\tif readN == len(b) {\n\t\t\t// if dst is full, return\n\t\t\treturn readN, nil\n\t\t}\n\t}\n\n\tif c.closed.Load() || c.readClosed.Load() {\n\t\t// Connection is closed, should read all data left in channel\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase blk := <-c.orderedRecvQueue:\n\t\t\t\t_ = c.readBlock(&blk, &readN, b)\n\t\t\t\tif readN == len(b) {\n\t\t\t\t\treturn readN, nil\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tif readN != 0 {\n\t\t\t\t\treturn readN, nil\n\t\t\t\t} else {\n\t\t\t\t\treturn 0, io.EOF\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Read at lease something\n\tif readN == 0 {\n\t\tselect {\n\t\tcase blk := <-c.orderedRecvQueue:\n\t\t\tc.logger.Debugln(\"Read in a block.\")\n\t\t\terr := c.readBlock(&blk, &readN, b)\n\t\t\tif err == io.EOF || readN == len(b) {\n\t\t\t\tif readN != 0 {\n\t\t\t\t\treturn readN, nil\n\t\t\t\t} else {\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-c.readCtx.Done():\n\t\t\tc.logger.Infoln(\"ReadDeadline exceeded.\")\n\t\t\tif readN != 0 {\n\t\t\t\treturn readN, nil\n\t\t\t} else {\n\t\t\t\treturn 0, io.EOF\n\t\t\t}\n\t\t}\n\t}\n\n\tif readN == 0 {\n\t\tc.logger.Errorln(\"Unknown error.\")\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase blk := <-c.orderedRecvQueue:\n\t\t\terr := c.readBlock(&blk, &readN, b)\n\t\t\tc.logger.Debugln(\"Read in a block.\")\n\t\t\tif err == io.EOF || readN == len(b) {\n\t\t\t\treturn readN, nil\n\t\t\t}\n\t\tcase <-c.readCtx.Done():\n\t\t\tc.logger.Infoln(\"ReadDeadline exceeded.\")\n\t\t\treturn readN, nil\n\t\tdefault:\n\t\t\treturn readN, nil\n\t\t}\n\t}\n}\n\nfunc (c *InboundConnection) readBlock(blk *block.Block, readN *int, b []byte) (err error) {\n\tswitch blk.Type {\n\tcase block.TypeDisconnect:\n\t\t// TODO: decide shutdown type\n\t\tif blk.BlockData[0] == block.ShutdownBoth {\n\t\t\tc.closed.Store(true)\n\t\t\treturn io.EOF\n\t\t} else if blk.BlockData[0] == block.ShutdownWrite {\n\t\t\tc.readClosed.Store(true)\n\t\t\treturn io.EOF\n\t\t} else if blk.BlockData[0] == block.ShutdownRead {\n\t\t\tc.writeClosed.Store(true)\n\t\t\treturn nil\n\t\t}\n\tcase block.TypeData:\n\t\tdst := b[*readN:]\n\t\tif len(dst) < len(blk.BlockData) {\n\t\t\t// if dst can't put a block, put part of it and return\n\t\t\tc.dataBuffer.OverWrite(blk.BlockData)\n\t\t\t*readN += c.dataBuffer.Read(dst)\n\t\t\treturn\n\t\t}\n\t\t// if dst can put a block, put it\n\t\t*readN += copy(dst, blk.BlockData)\n\t}\n\treturn\n}\n\nfunc (c *InboundConnection) Write(b []byte) (n int, err error) {\n\t// TODO: tag all blocks from b using WaitGroup\n\t// TODO: and wait all blocks sent?\n\tif c.writeClosed.Load() || c.closed.Load() {\n\t\treturn 0, syscall.EINVAL\n\t}\n\tc.sendData(b)\n\treturn len(b), nil\n}\n\nfunc (c *InboundConnection) Close() error {\n\tif c.closed.CAS(false, true) {\n\t\tc.SendDisconnect(block.ShutdownBoth)\n\t}\n\tc.Stop()\n\treturn nil\n}\n\nfunc (c *InboundConnection) CloseRead() error {\n\tc.SendDisconnect(block.ShutdownRead)\n\treturn nil\n}\n\nfunc (c *InboundConnection) CloseWrite() error {\n\tc.SendDisconnect(block.ShutdownWrite)\n\treturn nil\n}\n\nfunc (c *InboundConnection) LocalAddr() net.Addr {\n\t// TODO\n\treturn nil\n}\n\nfunc (c *InboundConnection) RemoteAddr() net.Addr {\n\t// TODO\n\treturn nil\n}\n\nfunc (c *InboundConnection) SetDeadline(t time.Time) error {\n\t_ = c.SetReadDeadline(t)\n\t_ = c.SetWriteDeadline(t)\n\treturn nil\n}\n\nfunc (c *InboundConnection) SetReadDeadline(t time.Time) error {\n\tc.readCtx, _ = context.WithDeadline(context.Background(), t)\n\treturn nil\n}\n\nfunc (c *InboundConnection) SetWriteDeadline(t time.Time) error {\n\tc.writeCtx, _ = context.WithDeadline(context.Background(), t)\n\treturn nil\n}\n"
  },
  {
    "path": "connection/outbound_connection.go",
    "content": "package connection\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com/ihciah/rabbit-tcp/block\"\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"go.uber.org/atomic\"\n)\n\ntype OutboundConnection struct {\n\tbaseConnection\n\tHalfOpenConn\n\tctx    context.Context\n\tcancel context.CancelFunc\n}\n\nfunc NewOutboundConnection(connectionID uint32, sendQueue chan<- block.Block, ctx context.Context, removeFromPool context.CancelFunc) Connection {\n\tc := OutboundConnection{\n\t\tbaseConnection: baseConnection{\n\t\t\tblockProcessor:   newBlockProcessor(ctx, removeFromPool),\n\t\t\tconnectionID:     connectionID,\n\t\t\tclosed:           atomic.NewBool(true),\n\t\t\tsendQueue:        sendQueue,\n\t\t\trecvQueue:        make(chan block.Block, RecvQueueSize),\n\t\t\torderedRecvQueue: make(chan block.Block, OrderedRecvQueueSize),\n\t\t\tlogger:           logger.NewLogger(fmt.Sprintf(\"[OutboundConnection-%d]\", connectionID)),\n\t\t},\n\t\tctx:    ctx,\n\t\tcancel: removeFromPool,\n\t}\n\tc.logger.Infof(\"OutboundConnection %d created.\\n\", connectionID)\n\treturn &c\n}\n\nfunc (oc *OutboundConnection) closeThenCancelWithOnceSend() {\n\toc.HalfOpenConn.Close()\n\toc.cancel()\n\tif oc.closed.CAS(false, true) {\n\t\toc.SendDisconnect(block.ShutdownBoth)\n\t}\n}\n\nfunc (oc *OutboundConnection) closeThenCancel() {\n\toc.HalfOpenConn.Close()\n\toc.cancel()\n}\n\n// real connection -> ConnectionPool's SendQueue -> TunnelPool\nfunc (oc *OutboundConnection) RecvRelay() {\n\trecvBuffer := make([]byte, OutboundRecvBuffer)\n\tfor {\n\t\toc.HalfOpenConn.SetReadDeadline(time.Now().Add(OutboundBlockTimeoutSec * time.Second))\n\t\tn, err := oc.HalfOpenConn.Read(recvBuffer)\n\t\tif err == nil {\n\t\t\toc.sendData(recvBuffer[:n])\n\t\t\toc.HalfOpenConn.SetReadDeadline(time.Time{})\n\t\t} else if err == io.EOF {\n\t\t\toc.logger.Debugln(\"EOF received from outbound connection.\")\n\t\t\toc.closeThenCancelWithOnceSend()\n\t\t\treturn\n\t\t} else if netErr, ok := err.(net.Error); ok && netErr.Timeout() {\n\t\t\toc.logger.Debugln(\"Receive timeout from outbound connection.\")\n\t\t} else {\n\t\t\toc.logger.Errorf(\"Error when recv relay outbound connection: %v\\n.\", err)\n\t\t\toc.closeThenCancelWithOnceSend()\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase <-oc.ctx.Done():\n\t\t\t// Should read all before leave, or packet will be lost\n\t\t\tfor {\n\t\t\t\tn, err := oc.HalfOpenConn.Read(recvBuffer)\n\t\t\t\tif err == nil {\n\t\t\t\t\toc.logger.Debugln(\"Data received from outbound connection successfully after close.\")\n\t\t\t\t\toc.sendData(recvBuffer[:n])\n\t\t\t\t} else {\n\t\t\t\t\toc.logger.Debugf(\"Error when receiving data from outbound connection after close: %v.\\n\", err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\n// orderedRecvQueue -> real connection\nfunc (oc *OutboundConnection) SendRelay() {\n\tfor {\n\t\tselect {\n\t\tcase blk := <-oc.orderedRecvQueue:\n\t\t\tswitch blk.Type {\n\t\t\tcase block.TypeConnect:\n\t\t\t\t// Will do nothing!\n\t\t\t\tcontinue\n\t\t\tcase block.TypeData:\n\t\t\t\toc.logger.Debugln(\"Send out DATA bytes.\")\n\t\t\t\toc.HalfOpenConn.SetWriteDeadline(time.Now().Add(OutboundBlockTimeoutSec * time.Second))\n\t\t\t\t_, err := oc.HalfOpenConn.Write(blk.BlockData)\n\t\t\t\tif err == nil {\n\t\t\t\t\toc.HalfOpenConn.SetWriteDeadline(time.Time{})\n\t\t\t\t} else {\n\t\t\t\t\toc.logger.Errorf(\"Error when send relay outbound connection: %v\\n.\", err)\n\t\t\t\t\toc.closeThenCancelWithOnceSend()\n\t\t\t\t}\n\t\t\tcase block.TypeDisconnect:\n\t\t\t\tif blk.BlockData[0] == block.ShutdownRead {\n\t\t\t\t\toc.logger.Debugf(\"CloseRead for remote connection\\n\")\n\t\t\t\t\toc.HalfOpenConn.CloseRead()\n\t\t\t\t} else if blk.BlockData[0] == block.ShutdownWrite {\n\t\t\t\t\toc.logger.Debugf(\"CloseWrite for remote connection\\n\")\n\t\t\t\t\toc.HalfOpenConn.CloseWrite()\n\t\t\t\t} else {\n\t\t\t\t\toc.logger.Debugln(\"Send out DISCONNECT action.\")\n\t\t\t\t\toc.closeThenCancel()\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-oc.ctx.Done():\n\t\t\toc.closeThenCancelWithOnceSend()\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (oc *OutboundConnection) RecvBlock(blk block.Block) {\n\tif blk.Type == block.TypeConnect {\n\t\taddress := string(blk.BlockData)\n\t\tgo oc.connect(address)\n\t}\n\toc.recvQueue <- blk\n}\n\nfunc (oc *OutboundConnection) connect(address string) {\n\toc.logger.Debugln(\"Send out CONNECTION action.\")\n\tif !oc.closed.Load() || oc.HalfOpenConn != nil {\n\t\treturn\n\t}\n\trawConn, err := net.Dial(\"tcp\", address)\n\tif err == nil {\n\t\toc.logger.Infof(\"Dial to %s successfully.\\n\", address)\n\t\toc.HalfOpenConn = rawConn.(*net.TCPConn)\n\t\toc.closed.Toggle()\n\t\tgo oc.RecvRelay()\n\t\tgo oc.SendRelay()\n\t} else {\n\t\toc.logger.Warnf(\"Error when dial to %s: %v.\\n\", address, err)\n\t\toc.SendDisconnect(block.ShutdownBoth)\n\t}\n}\n"
  },
  {
    "path": "connection/ring_buffer.go",
    "content": "package connection\n\ntype ByteRingBuffer struct {\n\tbuffer []byte\n\thead   int\n\ttail   int\n}\n\nfunc NewByteRingBuffer(size uint32) ByteRingBuffer {\n\tbuffer := make([]byte, size)\n\treturn ByteRingBuffer{\n\t\tbuffer: buffer,\n\t}\n}\n\nfunc (rb *ByteRingBuffer) OverWrite(data []byte) {\n\tif len(rb.buffer) < len(data) {\n\t\trb.buffer = make([]byte, len(data))\n\t}\n\tn := copy(rb.buffer, data)\n\trb.head = 0\n\trb.tail = n\n}\n\nfunc (rb *ByteRingBuffer) Read(data []byte) int {\n\tn := len(data)\n\tif n > rb.tail-rb.head {\n\t\tn = rb.tail - rb.head\n\t}\n\tcopy(data, rb.buffer[rb.head:rb.tail])\n\trb.head += n\n\treturn n\n}\n\nfunc (rb *ByteRingBuffer) Empty() bool {\n\treturn rb.tail-rb.head == 0\n}\n"
  },
  {
    "path": "connection_pool/pool.go",
    "content": "package connection_pool\n\nimport (\n\t\"context\"\n\t\"github.com/ihciah/rabbit-tcp/block\"\n\t\"github.com/ihciah/rabbit-tcp/connection\"\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel_pool\"\n\t\"sync\"\n)\n\nconst (\n\tSendQueueSize = 48 // SendQueue channel cap\n)\n\ntype ConnectionPool struct {\n\tconnectionMapping   map[uint32]connection.Connection\n\tmappingLock         sync.RWMutex\n\ttunnelPool          *tunnel_pool.TunnelPool\n\tsendQueue           chan block.Block\n\tacceptNewConnection bool\n\tlogger              *logger.Logger\n\n\tctx    context.Context\n\tcancel context.CancelFunc\n}\n\nfunc NewConnectionPool(pool *tunnel_pool.TunnelPool, acceptNewConnection bool, backgroundCtx context.Context) *ConnectionPool {\n\tctx, cancel := context.WithCancel(backgroundCtx)\n\tcp := &ConnectionPool{\n\t\tconnectionMapping:   make(map[uint32]connection.Connection),\n\t\ttunnelPool:          pool,\n\t\tsendQueue:           make(chan block.Block, SendQueueSize),\n\t\tacceptNewConnection: acceptNewConnection,\n\t\tlogger:              logger.NewLogger(\"[ConnectionPool]\"),\n\t\tctx:                 ctx,\n\t\tcancel:              cancel,\n\t}\n\tcp.logger.Infoln(\"Connection Pool created.\")\n\tgo cp.sendRelay()\n\tgo cp.recvRelay()\n\treturn cp\n}\n\n// Create InboundConnection, and it to ConnectionPool and return\nfunc (cp *ConnectionPool) NewPooledInboundConnection() connection.Connection {\n\tconnCtx, removeConnFromPool := context.WithCancel(cp.ctx)\n\tc := connection.NewInboundConnection(cp.sendQueue, connCtx, removeConnFromPool)\n\tcp.addConnection(c)\n\tgo func() {\n\t\t<-connCtx.Done()\n\t\tcp.removeConnection(c)\n\t}()\n\treturn c\n}\n\n// Create OutboundConnection, and it to ConnectionPool and return\nfunc (cp *ConnectionPool) NewPooledOutboundConnection(connectionID uint32) connection.Connection {\n\tconnCtx, removeConnFromPool := context.WithCancel(cp.ctx)\n\tc := connection.NewOutboundConnection(connectionID, cp.sendQueue, connCtx, removeConnFromPool)\n\tcp.addConnection(c)\n\tgo func() {\n\t\t<-connCtx.Done()\n\t\tcp.removeConnection(c)\n\t}()\n\treturn c\n}\n\nfunc (cp *ConnectionPool) addConnection(conn connection.Connection) {\n\tcp.logger.Infof(\"Connection %d added to connection pool.\\n\", conn.GetConnectionID())\n\tcp.mappingLock.Lock()\n\tdefer cp.mappingLock.Unlock()\n\tcp.connectionMapping[conn.GetConnectionID()] = conn\n\tgo conn.OrderedRelay(conn)\n}\n\nfunc (cp *ConnectionPool) removeConnection(conn connection.Connection) {\n\tcp.logger.Infof(\"Connection %d removed from connection pool.\\n\", conn.GetConnectionID())\n\tcp.mappingLock.Lock()\n\tdefer cp.mappingLock.Unlock()\n\tif _, ok := cp.connectionMapping[conn.GetConnectionID()]; ok {\n\t\tdelete(cp.connectionMapping, conn.GetConnectionID())\n\t}\n}\n\n// Deliver blocks from tunnelPool channel to specified connections\nfunc (cp *ConnectionPool) recvRelay() {\n\tcp.logger.Infoln(\"Recv Relay started.\")\n\tfor {\n\t\tselect {\n\t\tcase blk := <-cp.tunnelPool.GetRecvQueue():\n\t\t\tconnID := blk.ConnectionID\n\t\t\tvar conn connection.Connection\n\t\t\tvar ok bool\n\t\t\tcp.mappingLock.RLock()\n\t\t\tconn, ok = cp.connectionMapping[connID]\n\t\t\tcp.mappingLock.RUnlock()\n\t\t\tif !ok {\n\t\t\t\tif cp.acceptNewConnection {\n\t\t\t\t\tconn = cp.NewPooledOutboundConnection(blk.ConnectionID)\n\t\t\t\t\tcp.logger.Infoln(\"Connection created and added to connectionPool.\")\n\t\t\t\t} else {\n\t\t\t\t\tcp.logger.Errorln(\"Unknown connection.\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tconn.RecvBlock(blk)\n\t\t\tcp.logger.Debugf(\"Block %d(type: %d) put to connRecvQueue.\\n\", blk.BlockID, blk.Type)\n\t\tcase <-cp.ctx.Done():\n\t\t\tcp.logger.Infoln(\"Recv Relay stopped.\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\n// Deliver blocks from connPool's sendQueue to tunnelPool\n// TODO: Maybe QOS can be implemented here\nfunc (cp *ConnectionPool) sendRelay() {\n\tcp.logger.Infoln(\"Send Relay started.\")\n\tfor {\n\t\tselect {\n\t\tcase blk := <-cp.sendQueue:\n\t\t\tcp.tunnelPool.GetSendQueue() <- blk\n\t\t\tcp.logger.Debugf(\"Block %d(type: %d) put to connSendQueue.\\n\", blk.BlockID, blk.Type)\n\t\tcase <-cp.ctx.Done():\n\t\t\tcp.logger.Infoln(\"Send Relay stopped.\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (cp *ConnectionPool) stopRelay() {\n\tcp.logger.Infoln(\"Stop all ConnectionPool Relay.\")\n\tcp.cancel()\n}\n"
  },
  {
    "path": "docker-compose-client.yml",
    "content": "rabbit-client:\n  image: ihciah/rabbit\n  ports:\n    - \"9892:443/tcp\"\n  environment:\n    - MODE=c\n    - PASSWORD=password\n    - RABBITADDR=your.rabbit.server:9891\n    - LISTEN=:443\n    - DEST=your.service:port\n    - TUNNELN=6\n    - VERBOSE=2\n  restart: always"
  },
  {
    "path": "docker-compose-server.yml",
    "content": "rabbit-server:\n  image: ihciah/rabbit\n  ports:\n    - \"9891:443/tcp\"\n  environment:\n    - MODE=s\n    - PASSWORD=password\n    - RABBITADDR=:443\n    - VERBOSE=2\n  restart: always"
  },
  {
    "path": "go.mod",
    "content": "module github.com/ihciah/rabbit-tcp\n\ngo 1.13\n\nrequire (\n\tgo.uber.org/atomic v1.6.0\n\tgolang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d\n)\n"
  },
  {
    "path": "go.sum",
    "content": "github.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/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/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngo.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk=\ngo.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=\ngolang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\ngolang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d h1:1ZiEyfaQIg3Qh0EoqpwAakHVhecoE5wlSg5GjnafJGw=\ngolang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=\ngolang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs=\ngolang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=\ngolang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=\ngolang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=\ngolang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=\ngolang.org/x/sync v0.0.0-20190423024810-112230192c58/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-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=\ngolang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\ngolang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=\ngolang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c h1:IGkKhmfzcztjm6gYkykvu/NiS8kaqbCWAEWWAyf8J5U=\ngolang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=\ngolang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\n"
  },
  {
    "path": "logger/logger.go",
    "content": "package logger\n\nimport (\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\tLogLevelOff = iota\n\tLogLevelFatal\n\tLogLevelError\n\tLogLevelWarn\n\tLogLevelInfo\n\tLogLevelDebug\n)\n\nvar LEVEL int = LogLevelOff\n\ntype Logger struct {\n\tlogger *log.Logger\n\tlevel  int\n}\n\nfunc NewLogger(prefix string) *Logger {\n\treturn &Logger{\n\t\tlogger: log.New(os.Stdout, prefix, log.LstdFlags),\n\t\tlevel:  LEVEL,\n\t}\n}\n\nfunc (l *Logger) Debugln(v string) {\n\tif l.level >= LogLevelDebug {\n\t\tl.logger.Println(\"[Debug] \" + v)\n\t}\n}\n\nfunc (l *Logger) Debugf(format string, v ...interface{}) {\n\tif l.level >= LogLevelDebug {\n\t\tl.logger.Printf(\"[Debug] \"+format, v...)\n\t}\n}\n\nfunc (l *Logger) Infoln(v string) {\n\tif l.level >= LogLevelInfo {\n\t\tl.logger.Println(\"[Info] \" + v)\n\t}\n}\n\nfunc (l *Logger) Infof(format string, v ...interface{}) {\n\tif l.level >= LogLevelInfo {\n\t\tl.logger.Printf(\"[Info] \"+format, v...)\n\t}\n}\n\nfunc (l *Logger) Warnln(v string) {\n\tif l.level >= LogLevelWarn {\n\t\tl.logger.Println(\"[Warn] \" + v)\n\t}\n}\n\nfunc (l *Logger) Warnf(format string, v ...interface{}) {\n\tif l.level >= LogLevelWarn {\n\t\tl.logger.Printf(\"[Warn] \"+format, v...)\n\t}\n}\n\nfunc (l *Logger) Errorln(v string) {\n\tif l.level >= LogLevelError {\n\t\tl.logger.Println(\"[Error] \" + v)\n\t}\n}\n\nfunc (l *Logger) Errorf(format string, v ...interface{}) {\n\tif l.level >= LogLevelError {\n\t\tl.logger.Printf(\"[Error] \"+format, v...)\n\t}\n}\n\nfunc (l *Logger) Fatalln(v string) {\n\tif l.level >= LogLevelFatal {\n\t\tl.logger.Println(\"[Fatal] \" + v)\n\t}\n}\n\nfunc (l *Logger) Fatalf(format string, v ...interface{}) {\n\tif l.level >= LogLevelFatal {\n\t\tl.logger.Printf(\"[Fatal] \"+format, v...)\n\t}\n}\n"
  },
  {
    "path": "peer/client.go",
    "content": "package peer\n\nimport (\n\t\"context\"\n\t\"github.com/ihciah/rabbit-tcp/connection\"\n\t\"github.com/ihciah/rabbit-tcp/connection_pool\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel_pool\"\n\t\"math/rand\"\n)\n\ntype ClientPeer struct {\n\tPeer\n}\n\nfunc NewClientPeer(tunnelNum int, endpoint string, cipher tunnel.Cipher) ClientPeer {\n\tif initRand() != nil {\n\t\tpanic(\"Error when initialize random seed.\")\n\t}\n\tpeerID := rand.Uint32()\n\treturn newClientPeerWithID(peerID, tunnelNum, endpoint, cipher)\n}\n\nfunc newClientPeerWithID(peerID uint32, tunnelNum int, endpoint string, cipher tunnel.Cipher) ClientPeer {\n\tpeerCtx, removePeerFunc := context.WithCancel(context.Background())\n\n\tpoolManager := tunnel_pool.NewClientManager(tunnelNum, endpoint, peerID, cipher)\n\ttunnelPool := tunnel_pool.NewTunnelPool(peerID, &poolManager, peerCtx)\n\tconnectionPool := connection_pool.NewConnectionPool(tunnelPool, false, peerCtx)\n\n\treturn ClientPeer{\n\t\tPeer: Peer{\n\t\t\tpeerID:         peerID,\n\t\t\tconnectionPool: *connectionPool,\n\t\t\ttunnelPool:     *tunnelPool,\n\t\t\tctx:            peerCtx,\n\t\t\tcancel:         removePeerFunc,\n\t\t},\n\t}\n}\n\nfunc (cp *ClientPeer) Dial(address string) connection.Connection {\n\tconn := cp.connectionPool.NewPooledInboundConnection()\n\tconn.SendConnect(address)\n\treturn conn\n}\n"
  },
  {
    "path": "peer/peer.go",
    "content": "package peer\n\nimport (\n\t\"context\"\n\tcrand \"crypto/rand\"\n\t\"encoding/binary\"\n\t\"github.com/ihciah/rabbit-tcp/connection_pool\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel_pool\"\n\t\"io\"\n\t\"math/rand\"\n)\n\ntype Peer struct {\n\tpeerID         uint32\n\tconnectionPool connection_pool.ConnectionPool\n\ttunnelPool     tunnel_pool.TunnelPool\n\tctx            context.Context\n\tcancel         context.CancelFunc\n}\n\nfunc (p *Peer) Stop() {\n\tp.cancel()\n}\n\nfunc initRand() error {\n\tseedSize := 8\n\tseedBytes := make([]byte, seedSize)\n\t_, err := io.ReadFull(crand.Reader, seedBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\trand.Seed(int64(binary.LittleEndian.Uint64(seedBytes)))\n\treturn nil\n}\n"
  },
  {
    "path": "peer/peer_group.go",
    "content": "package peer\n\nimport (\n\t\"context\"\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel_pool\"\n\t\"net\"\n\t\"sync\"\n)\n\ntype PeerGroup struct {\n\tlock        sync.Mutex\n\tcipher      tunnel.Cipher\n\tpeerMapping map[uint32]*ServerPeer\n\tlogger      *logger.Logger\n}\n\nfunc NewPeerGroup(cipher tunnel.Cipher) PeerGroup {\n\tif initRand() != nil {\n\t\tpanic(\"Error when initialize random seed.\")\n\t}\n\treturn PeerGroup{\n\t\tcipher:      cipher,\n\t\tpeerMapping: make(map[uint32]*ServerPeer),\n\t\tlogger:      logger.NewLogger(\"[PeerGroup]\"),\n\t}\n}\n\n// Add a tunnel to it's peer; will create peer if not exists\nfunc (pg *PeerGroup) AddTunnel(tunnel *tunnel_pool.Tunnel) error {\n\t// add tunnel to peer(if absent, create peer to peer_group)\n\tpg.lock.Lock()\n\tvar peer *ServerPeer\n\tvar ok bool\n\n\tpeerID := tunnel.GetPeerID()\n\tif peer, ok = pg.peerMapping[peerID]; !ok {\n\t\tpeerContext, removePeerFunc := context.WithCancel(context.Background())\n\t\tserverPeer := NewServerPeerWithID(peerID, peerContext, removePeerFunc)\n\t\tpeer = &serverPeer\n\t\tpg.peerMapping[peerID] = peer\n\t\tpg.logger.Infof(\"Server Peer %d added to PeerGroup.\\n\", peerID)\n\n\t\tgo func() {\n\t\t\t<-peerContext.Done()\n\t\t\tpg.RemovePeer(peerID)\n\t\t}()\n\t}\n\tpg.lock.Unlock()\n\tpeer.tunnelPool.AddTunnel(tunnel)\n\treturn nil\n}\n\n// Like AddTunnel, add a raw connection\nfunc (pg *PeerGroup) AddTunnelFromConn(conn net.Conn) error {\n\ttun, err := tunnel_pool.NewPassiveTunnel(conn, pg.cipher)\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn err\n\t}\n\treturn pg.AddTunnel(&tun)\n}\n\nfunc (pg *PeerGroup) RemovePeer(peerID uint32) {\n\tpg.logger.Infof(\"Server Peer %d removed from peer group.\\n\", peerID)\n\tpg.lock.Lock()\n\tdefer pg.lock.Unlock()\n\tdelete(pg.peerMapping, peerID)\n}\n"
  },
  {
    "path": "peer/server.go",
    "content": "package peer\n\nimport (\n\t\"context\"\n\t\"github.com/ihciah/rabbit-tcp/connection_pool\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel_pool\"\n)\n\ntype ServerPeer struct {\n\tPeer\n}\n\nfunc NewServerPeerWithID(peerID uint32, peerContext context.Context, removePeerFunc context.CancelFunc) ServerPeer {\n\tpoolManager := tunnel_pool.NewServerManager(removePeerFunc)\n\ttunnelPool := tunnel_pool.NewTunnelPool(peerID, &poolManager, peerContext)\n\n\tconnectionPool := connection_pool.NewConnectionPool(tunnelPool, true, peerContext)\n\n\treturn ServerPeer{\n\t\tPeer: Peer{\n\t\t\tpeerID:         peerID,\n\t\t\tconnectionPool: *connectionPool,\n\t\t\ttunnelPool:     *tunnelPool,\n\t\t\tctx:            peerContext,\n\t\t\tcancel:         removePeerFunc,\n\t\t},\n\t}\n}\n"
  },
  {
    "path": "server/server.go",
    "content": "package server\n\nimport (\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"github.com/ihciah/rabbit-tcp/peer\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel\"\n\t\"net\"\n)\n\ntype Server struct {\n\tpeerGroup peer.PeerGroup\n\tlogger    *logger.Logger\n}\n\nfunc NewServer(cipher tunnel.Cipher) Server {\n\treturn Server{\n\t\tpeerGroup: peer.NewPeerGroup(cipher),\n\t\tlogger:    logger.NewLogger(\"[Server]\"),\n\t}\n}\n\nfunc (s *Server) Serve(address string) error {\n\tlistener, err := net.Listen(\"tcp\", address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\ts.logger.Errorf(\"Error when accept connection: %v.\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\terr = s.peerGroup.AddTunnelFromConn(conn)\n\t\tif err != nil {\n\t\t\ts.logger.Errorf(\"Error when add tunnel to tunnel pool: %v.\\n\", err)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "tunnel/aead.go",
    "content": "package tunnel\n\nimport (\n\t\"crypto/aes\"\n\t\"crypto/cipher\"\n\t\"errors\"\n\t\"golang.org/x/crypto/chacha20poly1305\"\n\t\"strings\"\n)\n\nvar ErrCipherNotSupported = errors.New(\"cipher not supported\")\n\nconst (\n\taeadAes128Gcm        = \"AEAD_AES_128_GCM\"\n\taeadAes192Gcm        = \"AEAD_AES_192_GCM\"\n\taeadAes256Gcm        = \"AEAD_AES_256_GCM\"\n\taeadChacha20Poly1305 = \"AEAD_CHACHA20_POLY1305\"\n)\n\n// List of AEAD ciphers: key size in bytes and constructor\nvar aeadList = map[string]struct {\n\tKeySize int\n\tNew     func([]byte) (Cipher, error)\n}{\n\taeadAes128Gcm:        {16, aesGCM},\n\taeadAes192Gcm:        {24, aesGCM},\n\taeadAes256Gcm:        {32, aesGCM},\n\taeadChacha20Poly1305: {32, chacha20Poly1305},\n}\n\nfunc makeAESGCM(key []byte) (cipher.AEAD, error) {\n\tblk, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cipher.NewGCM(blk)\n}\n\n// aesGCM creates a new Cipher with a pre-shared key. len(psk) must be\n// one of 16, 24, or 32 to select AES-128/196/256-GCM.\nfunc aesGCM(psk []byte) (Cipher, error) {\n\tswitch l := len(psk); l {\n\tcase 16, 24, 32: // AES 128/196/256\n\tdefault:\n\t\treturn nil, aes.KeySizeError(l)\n\t}\n\treturn &metaCipher{psk: psk, makeAEAD: makeAESGCM}, nil\n}\n\n// chacha20Poly1305 creates a new Cipher with a pre-shared key. len(psk)\n// must be 32.\nfunc chacha20Poly1305(psk []byte) (Cipher, error) {\n\tif len(psk) != chacha20poly1305.KeySize {\n\t\treturn nil, KeySizeError(chacha20poly1305.KeySize)\n\t}\n\treturn &metaCipher{psk: psk, makeAEAD: chacha20poly1305.New}, nil\n}\n\nfunc NewAEADCipher(name string, key []byte, password string) (Cipher, error) {\n\tname = strings.ToUpper(name)\n\tswitch name {\n\tcase \"CHACHA20-IETF-POLY1305\":\n\t\tname = aeadChacha20Poly1305\n\tcase \"AES-128-GCM\":\n\t\tname = aeadAes128Gcm\n\tcase \"AES-192-GCM\":\n\t\tname = aeadAes192Gcm\n\tcase \"AES-256-GCM\":\n\t\tname = aeadAes256Gcm\n\t}\n\n\tif choice, ok := aeadList[name]; ok {\n\t\tif key == nil || len(key) == 0 {\n\t\t\tkey = kdf(password, choice.KeySize)\n\t\t}\n\t\tif len(key) != choice.KeySize {\n\t\t\treturn nil, KeySizeError(choice.KeySize)\n\t\t}\n\t\taead, err := choice.New(key)\n\t\treturn aead, err\n\t}\n\treturn nil, ErrCipherNotSupported\n}\n"
  },
  {
    "path": "tunnel/cipher.go",
    "content": "package tunnel\n\nimport (\n\t\"crypto/cipher\"\n\t\"crypto/md5\"\n\t\"crypto/sha1\"\n\t\"golang.org/x/crypto/hkdf\"\n\t\"io\"\n\t\"strconv\"\n)\n\ntype Cipher interface {\n\tKeySize() int\n\tSaltSize() int\n\tEncrypter(salt []byte) (cipher.AEAD, error)\n\tDecrypter(salt []byte) (cipher.AEAD, error)\n}\n\ntype KeySizeError int\n\nfunc (e KeySizeError) Error() string {\n\treturn \"key size error: need \" + strconv.Itoa(int(e)) + \" bytes\"\n}\n\nfunc hkdfSHA1(secret, salt, info, outkey []byte) {\n\tr := hkdf.New(sha1.New, secret, salt, info)\n\tif _, err := io.ReadFull(r, outkey); err != nil {\n\t\tpanic(err) // should never happen\n\t}\n}\n\ntype metaCipher struct {\n\tpsk      []byte\n\tmakeAEAD func(key []byte) (cipher.AEAD, error)\n}\n\nfunc (a *metaCipher) KeySize() int { return len(a.psk) }\nfunc (a *metaCipher) SaltSize() int {\n\tif ks := a.KeySize(); ks > 16 {\n\t\treturn ks\n\t}\n\treturn 16\n}\nfunc (a *metaCipher) Encrypter(salt []byte) (cipher.AEAD, error) {\n\tsubkey := make([]byte, a.KeySize())\n\thkdfSHA1(a.psk, salt, []byte(\"ss-subkey\"), subkey)\n\treturn a.makeAEAD(subkey)\n}\nfunc (a *metaCipher) Decrypter(salt []byte) (cipher.AEAD, error) {\n\tsubkey := make([]byte, a.KeySize())\n\thkdfSHA1(a.psk, salt, []byte(\"ss-subkey\"), subkey)\n\treturn a.makeAEAD(subkey)\n}\n\nfunc kdf(password string, keyLen int) []byte {\n\tvar b, prev []byte\n\th := md5.New()\n\tfor len(b) < keyLen {\n\t\th.Write(prev)\n\t\th.Write([]byte(password))\n\t\tb = h.Sum(b)\n\t\tprev = b[len(b)-h.Size():]\n\t\th.Reset()\n\t}\n\treturn b[:keyLen]\n}\n"
  },
  {
    "path": "tunnel/tunnel.go",
    "content": "package tunnel\n\nimport (\n\t\"bytes\"\n\t\"crypto/cipher\"\n\t\"crypto/rand\"\n\t\"io\"\n\t\"net\"\n)\n\n// payloadSizeMask is the maximum size of payload in bytes.\nconst payloadSizeMask = 0x3FFF // 16*1024 - 1\n\ntype writer struct {\n\tio.Writer\n\tcipher.AEAD\n\tnonce []byte\n\tbuf   []byte\n}\n\n// NewWriter wraps an io.Writer with AEAD encryption.\nfunc NewWriter(w io.Writer, aead cipher.AEAD) io.Writer { return newWriter(w, aead) }\n\nfunc newWriter(w io.Writer, aead cipher.AEAD) *writer {\n\treturn &writer{\n\t\tWriter: w,\n\t\tAEAD:   aead,\n\t\tbuf:    make([]byte, 2+aead.Overhead()+payloadSizeMask+aead.Overhead()),\n\t\tnonce:  make([]byte, aead.NonceSize()),\n\t}\n}\n\n// Write encrypts b and writes to the embedded io.Writer.\nfunc (w *writer) Write(b []byte) (int, error) {\n\tn, err := w.ReadFrom(bytes.NewBuffer(b))\n\treturn int(n), err\n}\n\n// ReadFrom reads from the given io.Reader until EOF or error, encrypts and\n// writes to the embedded io.Writer. Returns number of bytes read from r and\n// any error encountered.\nfunc (w *writer) ReadFrom(r io.Reader) (n int64, err error) {\n\tfor {\n\t\tbuf := w.buf\n\t\tpayloadBuf := buf[2+w.Overhead() : 2+w.Overhead()+payloadSizeMask]\n\t\tnr, er := r.Read(payloadBuf)\n\n\t\tif nr > 0 {\n\t\t\tn += int64(nr)\n\t\t\tbuf = buf[:2+w.Overhead()+nr+w.Overhead()]\n\t\t\tpayloadBuf = payloadBuf[:nr]\n\t\t\tbuf[0], buf[1] = byte(nr>>8), byte(nr) // big-endian payload size\n\t\t\tw.Seal(buf[:0], w.nonce, buf[:2], nil)\n\t\t\tincrement(w.nonce)\n\n\t\t\tw.Seal(payloadBuf[:0], w.nonce, payloadBuf, nil)\n\t\t\tincrement(w.nonce)\n\n\t\t\t_, ew := w.Writer.Write(buf)\n\t\t\tif ew != nil {\n\t\t\t\terr = ew\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif er != nil {\n\t\t\tif er != io.EOF { // ignore EOF as per io.ReaderFrom contract\n\t\t\t\terr = er\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn n, err\n}\n\ntype reader struct {\n\tio.Reader\n\tcipher.AEAD\n\tnonce    []byte\n\tbuf      []byte\n\tleftover []byte\n}\n\n// NewReader wraps an io.Reader with AEAD decryption.\nfunc NewReader(r io.Reader, aead cipher.AEAD) io.Reader { return newReader(r, aead) }\n\nfunc newReader(r io.Reader, aead cipher.AEAD) *reader {\n\treturn &reader{\n\t\tReader: r,\n\t\tAEAD:   aead,\n\t\tbuf:    make([]byte, payloadSizeMask+aead.Overhead()),\n\t\tnonce:  make([]byte, aead.NonceSize()),\n\t}\n}\n\n// read and decrypt a record into the internal buffer. Return decrypted payload length and any error encountered.\nfunc (r *reader) read() (int, error) {\n\t// decrypt payload size\n\tbuf := r.buf[:2+r.Overhead()]\n\t_, err := io.ReadFull(r.Reader, buf)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t_, err = r.Open(buf[:0], r.nonce, buf, nil)\n\tincrement(r.nonce)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tsize := (int(buf[0])<<8 + int(buf[1])) & payloadSizeMask\n\n\t// decrypt payload\n\tbuf = r.buf[:size+r.Overhead()]\n\t_, err = io.ReadFull(r.Reader, buf)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t_, err = r.Open(buf[:0], r.nonce, buf, nil)\n\tincrement(r.nonce)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn size, nil\n}\n\n// Read reads from the embedded io.Reader, decrypts and writes to b.\nfunc (r *reader) Read(b []byte) (int, error) {\n\t// copy decrypted bytes (if any) from previous record first\n\tif len(r.leftover) > 0 {\n\t\tn := copy(b, r.leftover)\n\t\tr.leftover = r.leftover[n:]\n\t\treturn n, nil\n\t}\n\n\tn, err := r.read()\n\tm := copy(b, r.buf[:n])\n\tif m < n { // insufficient len(b), keep leftover for next read\n\t\tr.leftover = r.buf[m:n]\n\t}\n\treturn m, err\n}\n\n// WriteTo reads from the embedded io.Reader, decrypts and writes to w until\n// there's no more data to write or when an error occurs. Return number of\n// bytes written to w and any error encountered.\nfunc (r *reader) WriteTo(w io.Writer) (n int64, err error) {\n\t// write decrypted bytes left over from previous record\n\tfor len(r.leftover) > 0 {\n\t\tnw, ew := w.Write(r.leftover)\n\t\tr.leftover = r.leftover[nw:]\n\t\tn += int64(nw)\n\t\tif ew != nil {\n\t\t\treturn n, ew\n\t\t}\n\t}\n\n\tfor {\n\t\tnr, er := r.read()\n\t\tif nr > 0 {\n\t\t\tnw, ew := w.Write(r.buf[:nr])\n\t\t\tn += int64(nw)\n\n\t\t\tif ew != nil {\n\t\t\t\terr = ew\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif er != nil {\n\t\t\tif er != io.EOF { // ignore EOF as per io.Copy contract (using src.WriteTo shortcut)\n\t\t\t\terr = er\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn n, err\n}\n\n// increment little-endian encoded unsigned integer b. Wrap around on overflow.\nfunc increment(b []byte) {\n\tfor i := range b {\n\t\tb[i]++\n\t\tif b[i] != 0 {\n\t\t\treturn\n\t\t}\n\t}\n}\n\ntype streamConn struct {\n\tnet.Conn\n\tCipher\n\tr *reader\n\tw *writer\n}\n\nfunc (c *streamConn) initReader() error {\n\tsalt := make([]byte, c.SaltSize())\n\tif _, err := io.ReadFull(c.Conn, salt); err != nil {\n\t\treturn err\n\t}\n\n\taead, err := c.Decrypter(salt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.r = newReader(c.Conn, aead)\n\treturn nil\n}\n\nfunc (c *streamConn) Read(b []byte) (int, error) {\n\tif c.r == nil {\n\t\tif err := c.initReader(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn c.r.Read(b)\n}\n\nfunc (c *streamConn) WriteTo(w io.Writer) (int64, error) {\n\tif c.r == nil {\n\t\tif err := c.initReader(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn c.r.WriteTo(w)\n}\n\nfunc (c *streamConn) initWriter() error {\n\tsalt := make([]byte, c.SaltSize())\n\tif _, err := io.ReadFull(rand.Reader, salt); err != nil {\n\t\treturn err\n\t}\n\taead, err := c.Encrypter(salt)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = c.Conn.Write(salt)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.w = newWriter(c.Conn, aead)\n\treturn nil\n}\n\nfunc (c *streamConn) Write(b []byte) (int, error) {\n\tif c.w == nil {\n\t\tif err := c.initWriter(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn c.w.Write(b)\n}\n\nfunc (c *streamConn) ReadFrom(r io.Reader) (int64, error) {\n\tif c.w == nil {\n\t\tif err := c.initWriter(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn c.w.ReadFrom(r)\n}\n\n// NewEncryptedConn wraps a stream-oriented net.Conn with cipher.\nfunc NewEncryptedConn(c net.Conn, ciph Cipher) net.Conn {\n\tif ciph == nil {\n\t\treturn c\n\t}\n\treturn &streamConn{Conn: c, Cipher: ciph}\n}\n"
  },
  {
    "path": "tunnel_pool/const.go",
    "content": "package tunnel_pool\n\nconst (\n\tErrorWaitSec          = 3  // If a tunnel cannot be dialed, will wait for this period and retry infinitely\n\tTunnelBlockTimeoutSec = 8  // If a tunnel cannot send a block within the limit, will treat it a dead tunnel\n\tEmptyPoolDestroySec   = 60 // The pool will be destroyed(server side) if no tunnel dialed in\n\tSendQueueSize         = 48 // SendQueue channel cap\n\tRecvQueueSize         = 48 // RecvQueue channel cap\n)\n"
  },
  {
    "path": "tunnel_pool/manager.go",
    "content": "package tunnel_pool\n\nimport (\n\t\"context\"\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel\"\n\t\"go.uber.org/atomic\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype Manager interface {\n\tNotify(pool *TunnelPool)         // When TunnelPool size changed, Notify should be called\n\tDecreaseNotify(pool *TunnelPool) // When TunnelPool size decreased, DecreaseNotify should be called\n}\n\ntype ClientManager struct {\n\tdecreaseNotifyLock sync.Mutex // Only one decrease notify can run at the same time\n\ttunnelNum          int\n\tendpoint           string\n\tpeerID             uint32\n\tcipher             tunnel.Cipher\n\tlogger             *logger.Logger\n}\n\nfunc NewClientManager(tunnelNum int, endpoint string, peerID uint32, cipher tunnel.Cipher) ClientManager {\n\treturn ClientManager{\n\t\ttunnelNum: tunnelNum,\n\t\tendpoint:  endpoint,\n\t\tcipher:    cipher,\n\t\tpeerID:    peerID,\n\t\tlogger:    logger.NewLogger(\"[ClientManager]\"),\n\t}\n}\n\n// Keep tunnelPool size above tunnelNum\nfunc (cm *ClientManager) DecreaseNotify(pool *TunnelPool) {\n\tcm.decreaseNotifyLock.Lock()\n\tdefer cm.decreaseNotifyLock.Unlock()\n\ttunnelCount := len(pool.tunnelMapping)\n\n\tfor tunnelToCreate := cm.tunnelNum - tunnelCount; tunnelToCreate > 0; {\n\t\tselect {\n\t\tcase <-pool.ctx.Done():\n\t\t\t// Have to return if pool cancel is called.\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tcm.logger.Infof(\"Need %d new tunnels now.\\n\", tunnelToCreate)\n\t\tconn, err := net.Dial(\"tcp\", cm.endpoint)\n\t\tif err != nil {\n\t\t\tcm.logger.Errorf(\"Error when dial to %s: %v.\\n\", cm.endpoint, err)\n\t\t\ttime.Sleep(ErrorWaitSec * time.Second)\n\t\t\tcontinue\n\t\t}\n\t\ttun, err := NewActiveTunnel(conn, cm.cipher, cm.peerID)\n\t\tif err != nil {\n\t\t\tcm.logger.Errorf(\"Error when create active tunnel: %v\\n\", err)\n\t\t\ttime.Sleep(ErrorWaitSec * time.Second)\n\t\t\tcontinue\n\t\t}\n\t\tpool.AddTunnel(&tun)\n\t\ttunnelToCreate--\n\t\tcm.logger.Infof(\"Successfully dialed to %s. TunnelToCreate: %d\\n\", cm.endpoint, tunnelToCreate)\n\t}\n}\n\nfunc (cm *ClientManager) Notify(pool *TunnelPool) {}\n\ntype ServerManager struct {\n\tnotifyLock          sync.Mutex // Only one notify can run in the same time\n\tremovePeerFunc      context.CancelFunc\n\tcancelCountDownFunc context.CancelFunc\n\ttriggered           atomic.Bool\n\tlogger              *logger.Logger\n}\n\nfunc NewServerManager(removePeerFunc context.CancelFunc) ServerManager {\n\treturn ServerManager{\n\t\tlogger:         logger.NewLogger(\"[ServerManager]\"),\n\t\tremovePeerFunc: removePeerFunc,\n\t}\n}\n\n// If tunnelPool size is zero for more than EmptyPoolDestroySec, delete it\nfunc (sm *ServerManager) Notify(pool *TunnelPool) {\n\ttunnelCount := len(pool.tunnelMapping)\n\n\tif tunnelCount == 0 && sm.triggered.CAS(false, true) {\n\t\tvar destroyAfterCtx context.Context\n\t\tdestroyAfterCtx, sm.cancelCountDownFunc = context.WithCancel(context.Background())\n\t\tgo func(*ServerManager) {\n\t\t\tselect {\n\t\t\tcase <-destroyAfterCtx.Done():\n\t\t\t\tsm.logger.Debugln(\"ServerManager notify canceled.\")\n\t\t\tcase <-time.After(EmptyPoolDestroySec * time.Second):\n\t\t\t\tsm.logger.Infoln(\"ServerManager will be destroyed.\")\n\t\t\t\tsm.removePeerFunc()\n\t\t\t}\n\t\t}(sm)\n\t}\n\n\tif tunnelCount != 0 && sm.triggered.CAS(true, false) {\n\t\tsm.cancelCountDownFunc()\n\t}\n}\n\nfunc (sm *ServerManager) DecreaseNotify(pool *TunnelPool) {}\n"
  },
  {
    "path": "tunnel_pool/pool.go",
    "content": "package tunnel_pool\n\nimport (\n\t\"context\"\n\t\"github.com/ihciah/rabbit-tcp/block\"\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"sync\"\n)\n\ntype TunnelPool struct {\n\tmutex          sync.Mutex\n\ttunnelMapping  map[uint32]*Tunnel\n\tpeerID         uint32\n\tmanager        Manager\n\tsendQueue      chan block.Block\n\tsendRetryQueue chan block.Block\n\trecvQueue      chan block.Block\n\tctx            context.Context\n\tcancel         context.CancelFunc // currently useless\n\tlogger         *logger.Logger\n}\n\nfunc NewTunnelPool(peerID uint32, manager Manager, peerContext context.Context) *TunnelPool {\n\tctx, cancel := context.WithCancel(peerContext)\n\ttp := &TunnelPool{\n\t\ttunnelMapping:  make(map[uint32]*Tunnel),\n\t\tpeerID:         peerID,\n\t\tmanager:        manager,\n\t\tsendQueue:      make(chan block.Block, SendQueueSize),\n\t\tsendRetryQueue: make(chan block.Block, SendQueueSize),\n\t\trecvQueue:      make(chan block.Block, RecvQueueSize),\n\t\tctx:            ctx,\n\t\tcancel:         cancel,\n\t\tlogger:         logger.NewLogger(\"[TunnelPool]\"),\n\t}\n\ttp.logger.Infof(\"Tunnel Pool of peer %d created.\\n\", peerID)\n\tgo manager.DecreaseNotify(tp)\n\treturn tp\n}\n\n// Add a tunnel to tunnelPool and start bi-relay\nfunc (tp *TunnelPool) AddTunnel(tunnel *Tunnel) {\n\ttp.logger.Infof(\"Tunnel %d added to Peer %d.\\n\", tunnel.tunnelID, tp.peerID)\n\ttp.mutex.Lock()\n\tdefer tp.mutex.Unlock()\n\n\ttp.tunnelMapping[tunnel.tunnelID] = tunnel\n\ttp.manager.Notify(tp)\n\n\ttunnel.ctx, tunnel.cancel = context.WithCancel(tp.ctx)\n\tgo func() {\n\t\t<-tunnel.ctx.Done()\n\t\ttp.RemoveTunnel(tunnel)\n\t}()\n\n\tgo tunnel.OutboundRelay(tp.sendQueue, tp.sendRetryQueue)\n\tgo tunnel.InboundRelay(tp.recvQueue)\n}\n\n// Remove a tunnel from tunnelPool and stop bi-relay\nfunc (tp *TunnelPool) RemoveTunnel(tunnel *Tunnel) {\n\ttp.logger.Infof(\"Tunnel %d to peer %d removed from pool.\\n\", tunnel.tunnelID, tunnel.peerID)\n\ttp.mutex.Lock()\n\tdefer tp.mutex.Unlock()\n\tif tunnel, ok := tp.tunnelMapping[tunnel.tunnelID]; ok {\n\t\tdelete(tp.tunnelMapping, tunnel.tunnelID)\n\t\ttp.manager.Notify(tp)\n\t\tgo tp.manager.DecreaseNotify(tp)\n\t}\n}\n\nfunc (tp *TunnelPool) GetSendQueue() chan block.Block {\n\treturn tp.sendQueue\n}\n\nfunc (tp *TunnelPool) GetRecvQueue() chan block.Block {\n\treturn tp.recvQueue\n}\n"
  },
  {
    "path": "tunnel_pool/tunnel.go",
    "content": "package tunnel_pool\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com/ihciah/rabbit-tcp/block\"\n\t\"github.com/ihciah/rabbit-tcp/logger\"\n\t\"github.com/ihciah/rabbit-tcp/tunnel\"\n\t\"io\"\n\t\"math/rand\"\n\t\"net\"\n\t\"time\"\n)\n\ntype Tunnel struct {\n\tnet.Conn\n\tctx      context.Context\n\tcancel   context.CancelFunc\n\ttunnelID uint32\n\tpeerID   uint32\n\tlogger   *logger.Logger\n}\n\n// Create a new tunnel from a net.Conn and cipher with random tunnelID\nfunc NewActiveTunnel(conn net.Conn, ciph tunnel.Cipher, peerID uint32) (Tunnel, error) {\n\ttun := newTunnelWithID(conn, ciph, peerID)\n\treturn tun, tun.activeExchangePeerID()\n}\n\nfunc NewPassiveTunnel(conn net.Conn, ciph tunnel.Cipher) (Tunnel, error) {\n\ttun := newTunnelWithID(conn, ciph, 0)\n\treturn tun, tun.passiveExchangePeerID()\n}\n\n// Create a new tunnel from a net.Conn and cipher with given tunnelID\nfunc newTunnelWithID(conn net.Conn, ciph tunnel.Cipher, peerID uint32) Tunnel {\n\ttunnelID := rand.Uint32()\n\ttun := Tunnel{\n\t\tConn:     tunnel.NewEncryptedConn(conn, ciph),\n\t\tpeerID:   peerID,\n\t\ttunnelID: tunnelID,\n\t\tlogger:   logger.NewLogger(fmt.Sprintf(\"[Tunnel-%d]\", tunnelID)),\n\t}\n\ttun.logger.Infoln(\"Tunnel created.\")\n\treturn tun\n}\n\nfunc (tunnel *Tunnel) activeExchangePeerID() (err error) {\n\terr = tunnel.sendPeerID(tunnel.peerID)\n\tif err != nil {\n\t\ttunnel.logger.Errorf(\"Cannot exchange peerID(send failed: %v).\\n\", err)\n\t\treturn err\n\t}\n\tpeerID, err := tunnel.recvPeerID()\n\tif err != nil {\n\t\ttunnel.logger.Errorf(\"Cannot exchange peerID(recv failed: %v).\\n\", err)\n\t\treturn err\n\t}\n\tif tunnel.peerID != peerID {\n\t\ttunnel.logger.Errorf(\"Cannot exchange peerID(local: %d, remote: %d).\\n\", tunnel.peerID, peerID)\n\t\treturn errors.New(\"invalid exchanging\")\n\t}\n\ttunnel.logger.Infoln(\"PeerID exchange successfully.\")\n\treturn\n}\n\nfunc (tunnel *Tunnel) passiveExchangePeerID() (err error) {\n\tpeerID, err := tunnel.recvPeerID()\n\tif err != nil {\n\t\ttunnel.logger.Errorf(\"Cannot exchange peerID(recv failed: %v).\\n\", err)\n\t\treturn err\n\t}\n\terr = tunnel.sendPeerID(peerID)\n\tif err != nil {\n\t\ttunnel.logger.Errorf(\"Cannot exchange peerID(send failed: %v).\\n\", err)\n\t\treturn err\n\t}\n\ttunnel.peerID = peerID\n\ttunnel.logger.Infoln(\"PeerID exchange successfully.\")\n\treturn\n}\n\nfunc (tunnel *Tunnel) sendPeerID(peerID uint32) error {\n\tpeerIDBuffer := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(peerIDBuffer, peerID)\n\t_, err := io.CopyN(tunnel.Conn, bytes.NewReader(peerIDBuffer), 4)\n\tif err != nil {\n\t\ttunnel.logger.Errorf(\"Peer id sent with error:%v.\\n\", err)\n\t\treturn err\n\t}\n\ttunnel.logger.Infoln(\"Peer id sent.\")\n\treturn nil\n}\n\nfunc (tunnel *Tunnel) recvPeerID() (uint32, error) {\n\tpeerIDBuffer := make([]byte, 4)\n\t_, err := io.ReadFull(tunnel.Conn, peerIDBuffer)\n\tif err != nil {\n\t\ttunnel.logger.Errorf(\"Peer id recv with error:%v.\\n\", err)\n\t\treturn 0, err\n\t}\n\tpeerID := binary.LittleEndian.Uint32(peerIDBuffer)\n\ttunnel.logger.Infoln(\"Peer id recv.\")\n\treturn peerID, nil\n}\n\n// Read block from send channel, pack it and send\nfunc (tunnel *Tunnel) OutboundRelay(normalQueue, retryQueue chan block.Block) {\n\ttunnel.logger.Infoln(\"Outbound relay started.\")\n\tfor {\n\t\t// cancel is of highest priority\n\t\tselect {\n\t\tcase <-tunnel.ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\t// retryQueue is of secondary highest priority\n\t\tselect {\n\t\tcase <-tunnel.ctx.Done():\n\t\t\treturn\n\t\tcase blk := <-retryQueue:\n\t\t\ttunnel.packThenSend(blk, retryQueue)\n\t\tdefault:\n\t\t}\n\t\t// normalQueue is of secondary highest priority\n\t\tselect {\n\t\tcase <-tunnel.ctx.Done():\n\t\t\treturn\n\t\tcase blk := <-retryQueue:\n\t\t\ttunnel.packThenSend(blk, retryQueue)\n\t\tcase blk := <-normalQueue:\n\t\t\ttunnel.packThenSend(blk, retryQueue)\n\t\t}\n\t}\n}\n\nfunc (tunnel *Tunnel) packThenSend(blk block.Block, retryQueue chan block.Block) {\n\tdataToSend := blk.Pack()\n\treader := bytes.NewReader(dataToSend)\n\n\ttunnel.Conn.SetWriteDeadline(time.Now().Add(TunnelBlockTimeoutSec * time.Second))\n\tn, err := io.Copy(tunnel.Conn, reader)\n\tif err != nil || n != int64(len(dataToSend)) {\n\t\ttunnel.logger.Warnf(\"Error when send bytes to tunnel: (n: %d, error: %v).\\n\", n, err)\n\t\t// Tunnel down and message has not been fully sent.\n\t\ttunnel.closeThenCancel()\n\t\tgo func() {\n\t\t\tretryQueue <- blk\n\t\t}()\n\t\t// Use new goroutine to avoid channel blocked\n\t} else {\n\t\ttunnel.Conn.SetWriteDeadline(time.Time{})\n\t\ttunnel.logger.Debugf(\"Copied data to tunnel successfully(n: %d).\\n\", n)\n\t}\n}\n\n// Read bytes from connection, parse it to block then put in recv channel\nfunc (tunnel *Tunnel) InboundRelay(output chan<- block.Block) {\n\ttunnel.logger.Infoln(\"Inbound relay started.\")\n\tfor {\n\t\tselect {\n\t\tcase <-tunnel.ctx.Done():\n\t\t\t// Should read all before leave, or packet will be lost\n\t\t\tfor {\n\t\t\t\t// Will never be blocked because the tunnel is closed\n\t\t\t\tblk, err := block.NewBlockFromReader(tunnel.Conn)\n\t\t\t\tif err == nil {\n\t\t\t\t\ttunnel.logger.Debugf(\"Block received from tunnel(type: %d) successfully after close.\\n\", blk.Type)\n\t\t\t\t\toutput <- *blk\n\t\t\t\t} else {\n\t\t\t\t\ttunnel.logger.Debugf(\"Error when receiving block from tunnel after close: %v.\\n\", err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\tdefault:\n\t\t\tblk, err := block.NewBlockFromReader(tunnel.Conn)\n\t\t\tif err != nil {\n\t\t\t\t// Server will never close connection in normal cases\n\t\t\t\ttunnel.logger.Errorf(\"Error when receiving block from tunnel: %v.\\n\", err)\n\t\t\t\t// Tunnel down and message has not been fully read.\n\t\t\t\ttunnel.closeThenCancel()\n\t\t\t} else {\n\t\t\t\ttunnel.logger.Debugf(\"Block received from tunnel(type: %d)successfully.\\n\", blk.Type)\n\t\t\t\toutput <- *blk\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (tunnel *Tunnel) GetPeerID() uint32 {\n\treturn tunnel.peerID\n}\n\nfunc (tunnel *Tunnel) closeThenCancel() {\n\ttunnel.Close()\n\ttunnel.cancel()\n}\n"
  }
]