[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: \"[BUG]\"\nlabels: bug\nassignees: GreaterFire\n\n---\n\n- [ ] I certify that I have read the contributing guidelines and I acknowledge if I don't follow the format below, or I'm using an old version of trojan, or I apparently fail to provide sufficient information (such as logs, specific numbers), or I don't check this box, my issue will be closed immediately without any notice.\n\n**Trojan Version**\nThe version of trojan you are using.\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Logs**\nIf applicable, add logs to help explain your problem.\n\n**Environment**\nWhere are you running trojan? What is your proxy set up?\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: \"[Feature Request]\"\nlabels: enhancement\nassignees: GreaterFire\n\n---\n\n- [ ] I certify that I have read the contributing guidelines and I acknowledge if I don't follow the format below or I don't check this box, my issue will be closed immediately without any notice.\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Is this problem relevant to what trojan should care about?**\nTrojan is a protocol implementation, not a full-fledged proxy client. Features such as custom routing will not be accepted.\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".gitignore",
    "content": "# Prerequisites\n*.d\n\n# Compiled Object files\n*.slo\n*.lo\n*.o\n*.obj\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Compiled Dynamic libraries\n*.so\n*.dylib\n*.dll\n\n# Fortran module files\n*.mod\n*.smod\n\n# Compiled Static libraries\n*.lai\n*.la\n*.a\n*.lib\n\n# Executables\n*.exe\n*.out\n*.app\ntrojan\n\n# Config files\n*.json\n\n# Key and certificate files\n*.pem\n\n# Systemd service files\n*.service\n\n# Cmake files\nCMakeCache.txt\nCMakeFiles\nCMakeScripts\nTesting\nMakefile\ncmake_install.cmake\ninstall_manifest.txt\ncompile_commands.json\nCTestTestfile.cmake\nbuild/\n"
  },
  {
    "path": ".gitpod.Dockerfile",
    "content": "FROM gitpod/workspace-full\n\nUSER gitpod\n\nRUN sudo apt-get update && \\\n    sudo apt-get install -y \\\n        build-essential \\\n        cmake \\\n        libboost-system-dev \\\n        libboost-program-options-dev \\\n        libssl-dev \\\n        default-libmysqlclient-dev\n"
  },
  {
    "path": ".gitpod.yml",
    "content": "image:\n  file: .gitpod.Dockerfile\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.7.2)\nproject(trojan CXX)\n\nset(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} \"${CMAKE_SOURCE_DIR}/cmake/\")\nif(NOT CMAKE_BUILD_TYPE)\n    set(CMAKE_BUILD_TYPE Release)\nendif()\nset(CMAKE_CXX_STANDARD 11)\nif(MSVC)\n    add_definitions(-D_CRT_SECURE_NO_WARNINGS)\nelse()\n    add_definitions(-Wall -Wextra)\nendif()\n\nfile(GLOB_RECURSE CPP_LIST src/*.cpp)\n\nadd_executable(trojan ${CPP_LIST})\ntarget_include_directories(trojan PRIVATE src)\n\nset(THREADS_PREFER_PTHREAD_FLAG ON)\nfind_package(Threads REQUIRED)\ntarget_link_libraries(trojan ${CMAKE_THREAD_LIBS_INIT})\n\nfind_package(Boost 1.66.0 REQUIRED COMPONENTS system program_options)\ntarget_include_directories(trojan PRIVATE ${Boost_INCLUDE_DIR})\ntarget_link_libraries(trojan ${Boost_LIBRARIES})\nif(MSVC)\n    add_definitions(-DBOOST_DATE_TIME_NO_LIB)\nendif()\n\nfind_package(OpenSSL 1.1.0 REQUIRED)\ntarget_include_directories(trojan PRIVATE ${OPENSSL_INCLUDE_DIR})\ntarget_link_libraries(trojan ${OPENSSL_LIBRARIES})\nif(OPENSSL_VERSION VERSION_GREATER_EQUAL 1.1.1)\n    option(ENABLE_SSL_KEYLOG \"Build with SSL KeyLog support\" ON)\n    if(ENABLE_SSL_KEYLOG)\n        add_definitions(-DENABLE_SSL_KEYLOG)\n    endif()\n\n    option(ENABLE_TLS13_CIPHERSUITES \"Build with TLS1.3 ciphersuites support\" ON)\n    if(ENABLE_TLS13_CIPHERSUITES)\n        add_definitions(-DENABLE_TLS13_CIPHERSUITES)\n    endif()\nendif()\n\noption(ENABLE_MYSQL \"Build with MySQL support\" ON)\nif(ENABLE_MYSQL)\n    find_package(MySQL REQUIRED)\n    target_include_directories(trojan PRIVATE ${MYSQL_INCLUDE_DIR})\n    target_link_libraries(trojan ${MYSQL_LIBRARIES})\n    add_definitions(-DENABLE_MYSQL)\nendif()\n\noption(FORCE_TCP_FASTOPEN \"Force build with TCP Fast Open support\" OFF)\nif(FORCE_TCP_FASTOPEN)\n    add_definitions(-DTCP_FASTOPEN=23 -DTCP_FASTOPEN_CONNECT=30)\nendif()\n\nif(CMAKE_SYSTEM_NAME STREQUAL Linux)\n    option(ENABLE_NAT \"Build with NAT support\" ON)\n    if(ENABLE_NAT)\n        add_definitions(-DENABLE_NAT)\n    endif()\n\n    option(ENABLE_REUSE_PORT \"Build with SO_REUSEPORT support\" ON)\n    if(ENABLE_REUSE_PORT)\n        add_definitions(-DENABLE_REUSE_PORT)\n    endif()\nendif()\n\nif(APPLE)\n    find_library(CoreFoundation CoreFoundation)\n    find_library(Security Security)\n    target_link_libraries(trojan ${CoreFoundation} ${Security})\nendif()\n\nif(WIN32)\n    target_link_libraries(trojan wsock32 ws2_32 crypt32)\nelse()\n    set(SYSTEMD_SERVICE AUTO CACHE STRING \"Install systemd service\")\n    set_property(CACHE SYSTEMD_SERVICE PROPERTY STRINGS AUTO ON OFF)\n    set(SYSTEMD_SERVICE_PATH /lib/systemd/system CACHE PATH \"Systemd service path\")\n    if(SYSTEMD_SERVICE STREQUAL AUTO)\n        if(EXISTS /usr/lib/systemd/system)\n            set(SYSTEMD_SERVICE ON)\n            set(SYSTEMD_SERVICE_PATH /usr/lib/systemd/system CACHE PATH \"Systemd service path\" FORCE)\n        elseif(EXISTS /lib/systemd/system)\n            set(SYSTEMD_SERVICE ON)\n            set(SYSTEMD_SERVICE_PATH /lib/systemd/system CACHE PATH \"Systemd service path\" FORCE)\n        endif()\n    endif()\n\n    include(GNUInstallDirs)\n    install(TARGETS trojan DESTINATION ${CMAKE_INSTALL_BINDIR})\n    install(FILES examples/server.json-example DESTINATION ${CMAKE_INSTALL_FULL_SYSCONFDIR}/trojan RENAME config.json)\n    set(DEFAULT_CONFIG ${CMAKE_INSTALL_FULL_SYSCONFDIR}/trojan/config.json CACHE STRING \"Default config path\")\n    add_definitions(-DDEFAULT_CONFIG=\"${DEFAULT_CONFIG}\")\n    install(FILES docs/trojan.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1)\n    install(DIRECTORY docs/ DESTINATION ${CMAKE_INSTALL_DOCDIR} FILES_MATCHING PATTERN \"*.md\")\n    install(DIRECTORY examples DESTINATION ${CMAKE_INSTALL_DOCDIR} FILES_MATCHING PATTERN \"*.json-example\")\n    if(SYSTEMD_SERVICE STREQUAL ON)\n        set(CONFIG_NAME config)\n        configure_file(examples/trojan.service-example trojan.service)\n        set(CONFIG_NAME %i)\n        configure_file(examples/trojan.service-example trojan@.service)\n        install(FILES ${CMAKE_BINARY_DIR}/trojan.service ${CMAKE_BINARY_DIR}/trojan@.service DESTINATION ${SYSTEMD_SERVICE_PATH})\n    endif()\n\n    enable_testing()\n    add_test(NAME LinuxSmokeTest-basic\n             COMMAND bash ${CMAKE_SOURCE_DIR}/tests/LinuxSmokeTest/basic.sh ${CMAKE_BINARY_DIR}/trojan)\n    add_test(NAME LinuxSmokeTest-fake-client\n             COMMAND bash ${CMAKE_SOURCE_DIR}/tests/LinuxSmokeTest/fake-client.sh ${CMAKE_BINARY_DIR}/trojan)\n    SET_TESTS_PROPERTIES(LinuxSmokeTest-fake-client PROPERTIES DEPENDS \"LinuxSmokeTest-basic\")\nendif()\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\nI want to first thank you for your interests in contributing to the Trojan project. Your contributions are much appreciated. To ensure an effective and efficient communication environment, here are some guidelines you should adhere to when you are considering contributing.\n\n## Issues\n\nIssues in this repository are for bug reports and feature requests, and for these purposes **only**. Irrelevant content, such as usage problems or server configuration issues, should not be discussed here. The developers will, at their discretion, either answer or ignore and close this kind of issues without any notice. The **required** communication language in this repository is English.\n\nIf you would like to file a bug report, you **must** use the bug report template and follow the instructions inside it. If you do not do so, or if the problem you reported is not considered by the developers a bug, your issue might be closed immediately.\n\nIf you would like to file a feature request, you also **must** use the feature request template and follow the instructions inside it. Note that we are trying to keep this project as small as possible because it is the core of the trojan ecosystem and will be included in other projects. For a feature to be considered, make sure that the feature you request is **really necessary** to be included in this very project. Also, we will not consider adding a dependency to the project unless it is **absolutely necessary**. If you do not do the above, your issue might be closed immediately.\n\n## Pull Requests\n\nPull requests are very welcomed. However, due to the reasons we just talked about, we will only accept features that are **really necessary** for this project. Bug fixes and security-related fixes have more chances to be reviewed by the developers.\n\nFor contributors who make frequent and high-quality contributions, there is a chance that they'll be invited to join our organization.\n"
  },
  {
    "path": "CONTRIBUTORS.md",
    "content": "# Contributors\n\n- [a-wing](https://github.com/a-wing)\n    - Add Debian build instructions in the documentation.\n- [cybmp3](https://github.com/cybmp3)\n    - Add MySQL SSL support.\n- [du5](https://github.com/du5)\n    - Update OpenSSL version in Azure Pipelines config.\n- [felixonmars](https://github.com/felixonmars)\n    - Fix incorrect systemd service path in the documentation.\n- [ffftwo](https://github.com/ffftwo)\n    - Throw an exception when `run_type` is wrong.\n- [GreaterFire](https://github.com/GreaterFire)\n    - Author of this project.\n- [JonathanHouten](https://github.com/JonathanHouten)\n    - Fix a parameter type error in the `CertOpenSystemStore` call.\n- [karuboniru](https://github.com/karuboniru)\n    - Make tests serial to avoid a race condition.\n- [KCCat](https://github.com/KCCat)\n    - Fix an ambiguity in the documentation.\n- [keur](https://github.com/keur)\n    - Replace deprecated SHA224 functions with `EVP`.\n- [klzgrad](https://github.com/klzgrad)\n    - Add Linux smoke test.\n- [LimiQS](https://github.com/LimiQS)\n    - Refine the config documentation.\n- [MargaretteMoss](https://github.com/MargaretteMoss)\n    - Add client verification to MySQL SSL connection.\n- [PragmaTwice](https://github.com/PragmaTwice)\n    - List source files automatically in CMakeLists.txt.\n- [Qv2ray-dev](https://github.com/Qv2ray-dev)\n    - Fix Azure Pipelines config.\n    - Add log callback.\n- [WeidiDeng](https://github.com/WeidiDeng)\n    - Fix incorrect Debian dependency in the documentation.\n- [WillyPillow](https://github.com/WillyPillow)\n    - Add `alpn_port_override` functionality.\n- [wongsyrone](https://github.com/wongsyrone)\n    - Add conditional MySQL compilation.\n    - Remove `SSL_CTX_set_ecdh_auto(native_context, 1)` call in new versions of OpenSSL.\n    - Fix a typo in the documentation.\n    - Add a functionality to log received signals.\n    - Fix a bug that causes trojan to crash if the connection is terminated before a session is established.\n    - Add android log facility.\n    - Refer to `basic_stream_socket` instead of `basic_socket` in SSL sockets.\n    - Cancel async tasks when stopping the service.\n    - Fix fd leak.\n    - Print OpenSSL compile-time version and build flags.\n    - Optimize APIs and other clean-ups.\n    - Update certificate verification API.\n- [xsm1997](https://github.com/xsm1997)\n    - Add `SO_REUSEPORT` support.\n    - Add TLS1.3 ciphersuites support.\n- [yiailake](https://github.com/yiailake)\n    - Add support for gitpod.\n- [zhangsan946](https://github.com/zhangsan946)\n    - Add macOS keychain support.\n- [zhyncs](https://github.com/zhyncs)\n    - Fix clang-tidy warnings.\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM alpine:3.11\n\nCOPY . trojan\nRUN apk add --no-cache --virtual .build-deps \\\n        build-base \\\n        cmake \\\n        boost-dev \\\n        openssl-dev \\\n        mariadb-connector-c-dev \\\n    && (cd trojan && cmake . && make -j $(nproc) && strip -s trojan \\\n    && mv trojan /usr/local/bin) \\\n    && rm -rf trojan \\\n    && apk del .build-deps \\\n    && apk add --no-cache --virtual .trojan-rundeps \\\n        libstdc++ \\\n        boost-system \\\n        boost-program_options \\\n        mariadb-connector-c\n\nWORKDIR /config\nCMD [\"trojan\", \"config.json\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n\nIn addition, as a special exception, the copyright holders give\npermission to link the code of portions of this program with the\nOpenSSL library under certain conditions as described in each\nindividual source file, and distribute linked combinations\nincluding the two.\n\nYou must obey the GNU General Public License in all respects\nfor all of the code used other than OpenSSL.  If you modify\nfile(s) with this exception, you may extend this exception to your\nversion of the file(s), but you are not obligated to do so.  If you\ndo not wish to do so, delete this exception statement from your\nversion.  If you delete this exception statement from all source\nfiles in the program, then also delete it here.\n"
  },
  {
    "path": "README.md",
    "content": "# trojan\n\n[![Build Status](https://dev.azure.com/GreaterFire/Trojan-GFW/_apis/build/status/trojan-gfw.trojan?branchName=master)](https://dev.azure.com/GreaterFire/Trojan-GFW/_build/latest?definitionId=5&branchName=master)\n\nAn unidentifiable mechanism that helps you bypass GFW.\n\nTrojan features multiple protocols over `TLS` to avoid both active/passive detections and ISP `QoS` limitations.\n\nTrojan is not a fixed program or protocol. It's an idea, an idea that imitating the most common service, to an extent that it behaves identically, could help you get across the Great FireWall permanently, without being identified ever. We are the GreatER Fire; we ship Trojan Horses.\n\n## Documentations\n\nAn online documentation can be found [here](https://trojan-gfw.github.io/trojan/).  \nInstallation guide on various platforms can be found in the [wiki](https://github.com/trojan-gfw/trojan/wiki/Binary-&-Package-Distributions).\n\n## Contributing\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md).\n\n## Dependencies\n\n- [CMake](https://cmake.org/) >= 3.7.2\n- [Boost](http://www.boost.org/) >= 1.66.0\n- [OpenSSL](https://www.openssl.org/) >= 1.1.0\n- [libmysqlclient](https://dev.mysql.com/downloads/connector/c/)\n\n## License\n\n[GPLv3](LICENSE)\n"
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\n\n## Supported Version\n\nThe only version that is supported by Trojan-GFW is the latest version.\n\n## Reporting a Vulnerability\n\nTo report a vulnerability, please contact GreaterFire@protonmail.com. You can make it secure by encrypting with PGP:\n\n```\n-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmQINBFnxFxcBEADedizrFWPY6WNjl8r24YSKiqGrAok52LueNmclUwG40PzyOCZG\nXXyePaTTPjpBOYT1rG4km8b/zsPsvMuC3WFZU2L4GVV7nxs/sQ/sxKOV1Ptq7xSJ\nk+Wmi93dbn1RbyzIJIlEQSiHKQuoz5bc0NkQBGrUFqETWP75MT6txLHRIt1v+GRM\nIAvHR0hzhfIMaPogkUApCjOJmRUmuj+v9F5GWj/IglFQCBCqOR/OOYLxH/IaygoV\nzwwge+5YS8aAnXFwSkl0Bs6+NzNFB1cDZwnqNvOD9tNN6Y3wCCB2eRZ4uCu5xjR/\nD1JYVJlWpIgRP1BpMt2uj28ihnlTD6OYWG8AGOlgWirdF6LutGO5yb9efanafm9o\nbfSruUBHgERTAKGitNpJXUxcKMCKvZ5W6j0JJqEnT1dVyHePAo3RBWHScdF1ScZo\nLCeGxkqMly8Tvw9uRsX36phroJOvIrb3YHWHW0GDyYvDYHGb+p8+sldSSjGSlmAU\nNZRJROs4cJGnn1Ez1VX4SWZkZrPzErpHYmy8HoZ85LlUgg0jngqzaVIRp4NoUb0/\nTq0QkTcsPXOCV1DoY6ZyCcReC2xd8mBOJjn+mi+7EXF48g3NaoktIxSssI+oV9JX\nA143yYrxJOXq/Kfu7Qq8iTCfdwE234iItdgysPc8tOYxZEOBDKIMysjzLQARAQAB\ntChHcmVhdGVyRmlyZSA8R3JlYXRlckZpcmVAcHJvdG9ubWFpbC5jb20+iQI3BBMB\nCAAhBQJZ8RcXAhsDBQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEKHd1IZTOwES\nB5sQAM6b8L9TeldziBjF9/mTmGY5rXOzwL/te02ykL0s7SoX6cj3ROxybmgzl38q\nsovlBxSQgnkz3Ti69Fk7muCCQmSYyzThpGGGalN84HNhD4UDxd2S9kB1sIEczyZj\nU1laiqV2YQjHWAsjyofUpWbz2SdL9KnmIfIdz8bwHMv0DeLDmdL0bmSVq0t/npRw\nhtyottL0hB2z06ufpq40hzypSKDleM/eIscMfv667/AcjqDzolEXbAqKiqirnjYo\nVFzGlWGEd69W6zXqtBxI1gCEGXmjTNw+0fUQbWPlhTJnGcM9ucdBIzBcdhsvAc0X\nnDtDYQLbXIzVMTYPatUqqTmdtpZGFsRR7pw7taoZ87TaPm1gsHoWMHOE9vM9XYF9\nk6jXCiTD7shyF3EpJn/6W6ErYsui8R3B3P7apvqikq2/oO/aaVj5WcV2ebW/bEns\nOMAn0wDwAgGcctsER/WI0zfrS3CI4D+PvM36PnheulL4UxukXkdku0ayyhxDdHiY\n9EPL+TgBR2OmDo/06EuUNLDSgbbEM0vgV0BrZNx6Nkh8zXFoUCFkEmKrBgXpr1V8\nDXhkVS6XRlx5sm/rxgUfOaF7EJt2LRMtdHY2TYHl+r1jRFV6ZhRFVfQOMOAFhK2x\ntXOxB/v13g1WHd/VisE+SYX9r6QmDoz0xiiyTXoZd/ZPyjnzuQINBFnxFxcBEACz\nTBFEKzPOMxd41WWV/I+sKmdgpoX1nlC1TxhUXxaRXoBr+sV7sUAnPKa4lQ5PzGHk\nFDugdN85NaqI0wVOjr6/VnRcnNB+KuBA/JAb9zdRD4MbV92EpZrdDivtvsGvjsxr\n6jip5qBckNLDw19EC0hijstmolHP44Px9W+wMpE0MPx0olfaKHujBRQe+K0ehaT8\nFyf/2a93nG/UjRa0hLdYBwHMR1+Qf7WJsEAkc86fSUNuJMMQZDeacsCBlehqtsxb\nXyGEYT5oekxe7EmvCYi9LWvoGPPzYdkvhUUVycZ72OwN9y/I8cy3b8GOFqu9B4E7\nqFYp3IJpu8XUS6nCjyce+kZnDk8lUJwVMgWFZAKEk+GuEpAguf4iZ/yrF3A6Tw2Q\nQOpzsqnibQhg6Y5valDaEXYy14n20+aT/hGhmBdE0kto37vL43bY4nJEKqLjYkLw\nN0wlZ2XjFIqRNVK/JPJepmS2X1CFEJF81XTkuxk9OqjQyTE670iRAwEH8DAZkyjO\nWKyhPhIC7OhXtDtuaygISOQraUN5KTXB8G9jEj5hDs9Ej9xsUnnSkVlR/DgYfbkR\nZYbE3Zt8iXnp9Cual5ex546DPLCOmOw3QzUMQnzMdco02sC4pK0Bg9sAUUe5HsA9\nJlzArCMn8lR6thG9a1WfOd3uk36YqQz1R0ZrRB0IhwARAQABiQIfBBgBCAAJBQJZ\n8RcXAhsMAAoJEKHd1IZTOwESuukQAKlALJErXL0NhUO1ClSUJ+h8Mwx2X39czRWz\nsP6vC8Fq11lCEPZip49+rWHCf7QczV/+Trvh4NmlBjuVDPaJDix7Z6kXk7fjIDZE\nig4oRZUoSziM5iIFx8hspKCImqiY9OCOvMyLshzhmY7feUwIcSC7+bM82KaSR6HO\n8LG6NKBllW5LoD3KIzlEwRD7wrN9qFJUUihsFCjWN1RIF+OiXjw7wl5qTUST32H3\nfPziK6M+ZfC2SuNB5YTTfEqUH+QbKeaqIr6P+s2WtGa8tPbCPi54xJJvx7hwpHzv\nfU5mKYHqcW66AKwTFgMeJDYFtkNe/n5zNvYNLQGaxa+i9/NXNug0scd936FTf0An\nsoHKqs10vBUbRS9MlAdOt2cW+HZDaXtGzXCx+zYDWAVaYg6IbjmoQZGNoHFbAXTW\nMIxNgnMtL3Rt8flKvu7beCpNyLWhrF5ZVz8n8+D6gpB3vr4+FPdozlXAdA8QFDsb\nPSOs5rvotj3EvYla0dYBFp8DpryLmFMPcmtVat4hHS36VYN8rkweXO2ZUp+UBLxk\nkve9N9BjNfOSM8UcZlaW2+azYUYjhVTjyYOE9i/TSVMS/NFboi2L9zvRdhKqKLyI\nsqPNFo+QCHzltRQXekccvs2wc6iiuVBOMFErS2ClFOAiHDT9cFU5sidJ19dEoN9h\n4wT+LHpX\n=Z2PM\n-----END PGP PUBLIC KEY BLOCK-----\n```\n"
  },
  {
    "path": "azure-pipelines.yml",
    "content": "stages:\n\n- stage: Build\n  jobs:\n\n  - job: Linux\n    pool:\n      vmImage: ubuntu-latest\n    container:\n      image: trojangfw/centos-build:latest\n    steps:\n    - script: |\n        set -euo pipefail\n        echo 'target_link_libraries(trojan dl)' >> CMakeLists.txt\n        cmake -DMYSQL_INCLUDE_DIR=/usr/local/include/mariadb -DMYSQL_LIBRARY=/usr/local/lib/mariadb/libmysqlclient.a -DDEFAULT_CONFIG=config.json -DFORCE_TCP_FASTOPEN=ON -DBoost_USE_STATIC_LIBS=ON .\n        make\n        strip -s trojan\n    - publish: $(System.DefaultWorkingDirectory)/trojan\n      artifact: LinuxBinary\n\n  - job: macOS\n    pool:\n      vmImage: macOS-latest\n    steps:\n    - script: |\n        set -euo pipefail\n        brew install boost openssl@1.1\n        cmake -DBoost_USE_STATIC_LIBS=ON -DOPENSSL_INCLUDE_DIR=/usr/local/opt/openssl@1.1/include -DOPENSSL_CRYPTO_LIBRARY=/usr/local/opt/openssl@1.1/lib/libcrypto.a -DOPENSSL_SSL_LIBRARY=/usr/local/opt/openssl@1.1/lib/libssl.a -DDEFAULT_CONFIG=config.json -DENABLE_MYSQL=OFF -DCMAKE_OSX_DEPLOYMENT_TARGET=10.13 .\n        make\n        strip -SXTx trojan\n    - publish: $(System.DefaultWorkingDirectory)/trojan\n      artifact: macOSBinary\n\n  - job: Windows\n    pool:\n      vmImage: windows-latest\n    steps:\n    - bash: |\n        set -euo pipefail\n        curl -LO https://slproweb.com/download/Win64OpenSSL-1_1_1h.exe\n        powershell \".\\\\Win64OpenSSL-1_1_1h.exe /silent /sp- /suppressmsgboxes /DIR='C:\\\\Program Files\\\\OpenSSL-Win64'\"\n        cmake -DBoost_INCLUDE_DIR=\"${BOOST_ROOT_1_72_0}/include\" -DBoost_USE_STATIC_LIBS=ON -DOPENSSL_ROOT_DIR='C:/Program Files/OpenSSL-Win64' -DOPENSSL_USE_STATIC_LIBS=ON -DENABLE_MYSQL=OFF .\n        cmake --build . --config Release\n    - publish: $(System.DefaultWorkingDirectory)/Release/trojan.exe\n      artifact: WindowsBinary\n\n- stage: Test\n  jobs:\n\n  - job: Linux\n    pool:\n      vmImage: ubuntu-latest\n    steps:\n    - download: current\n      artifact: LinuxBinary\n    - script: |\n        set -uo pipefail\n        BINARY=\"$PIPELINE_WORKSPACE/LinuxBinary/trojan\"\n        chmod +x \"$BINARY\"\n        mkdir results\n        cp -r \"$(tests/LinuxSmokeTest/basic.sh \"$BINARY\")\" results/basic\n        cp -r \"$(tests/LinuxSmokeTest/fake-client.sh \"$BINARY\")\" results/fake-client\n      env:\n        PIPELINE_WORKSPACE: $(Pipeline.Workspace)\n    - publish: $(System.DefaultWorkingDirectory)/results\n      artifact: LinuxTest\n\n- stage: Package\n  jobs:\n\n  - job: Linux\n    pool:\n      vmImage: ubuntu-latest\n    steps:\n    - download: current\n      artifact: LinuxBinary\n    - script: |\n        set -euo pipefail\n        BINARY=\"$PIPELINE_WORKSPACE/LinuxBinary/trojan\"\n        chmod +x \"$BINARY\"\n        mkdir trojan\n        cp \"$BINARY\" trojan/trojan\n        cp -r examples CONTRIBUTORS.md LICENSE README.md trojan\n        cp examples/server.json-example trojan/config.json\n        tar cf trojan-linux-amd64.tar trojan\n        xz trojan-linux-amd64.tar\n      env:\n        PIPELINE_WORKSPACE: $(Pipeline.Workspace)\n    - publish: $(System.DefaultWorkingDirectory)/trojan-linux-amd64.tar.xz\n      artifact: LinuxRelease\n\n  - job: macOS\n    pool:\n      vmImage: macOS-latest\n    steps:\n    - download: current\n      artifact: macOSBinary\n    - script: |\n        set -euo pipefail\n        BINARY=\"$PIPELINE_WORKSPACE/macOSBinary/trojan\"\n        chmod +x \"$BINARY\"\n        mkdir trojan\n        cp \"$BINARY\" trojan/trojan\n        cp -r examples CONTRIBUTORS.md LICENSE README.md trojan\n        cp examples/client.json-example trojan/config.json\n        rm trojan/examples/nat.json-example trojan/examples/trojan.service-example\n        cat > trojan/start.command <<EOF\n        #!/bin/sh\n\n        cd \"\\$(dirname \"\\$0\")\"\n        ./trojan\n        EOF\n        chmod +x trojan/start.command\n        zip -r9 trojan-macos.zip trojan\n      env:\n        PIPELINE_WORKSPACE: $(Pipeline.Workspace)\n    - publish: $(System.DefaultWorkingDirectory)/trojan-macos.zip\n      artifact: macOSRelease\n\n  - job: Windows\n    pool:\n      vmImage: windows-latest\n    steps:\n    - download: current\n      artifact: WindowsBinary\n    - bash: |\n        set -euo pipefail\n        BINARY=\"$PIPELINE_WORKSPACE/WindowsBinary/trojan.exe\"\n        mkdir trojan\n        cp \"$BINARY\" trojan/trojan.exe\n        cp -r examples CONTRIBUTORS.md LICENSE README.md trojan\n        cp examples/client.json-example trojan/config.json\n        rm trojan/examples/nat.json-example trojan/examples/trojan.service-example\n        7z a -mx=9 trojan-win.zip trojan\n      env:\n        PIPELINE_WORKSPACE: $(Pipeline.Workspace)\n    - publish: $(System.DefaultWorkingDirectory)/trojan-win.zip\n      artifact: WindowsRelease\n"
  },
  {
    "path": "cmake/FindMySQL.cmake",
    "content": "# - Find mysqlclient\n# Find the native MySQL includes and library\n#\n#  MYSQL_INCLUDE_DIR - where to find mysql.h, etc.\n#  MYSQL_LIBRARIES   - List of libraries when using MySQL.\n#  MYSQL_FOUND       - True if MySQL found.\n\nIF (MYSQL_INCLUDE_DIR)\n  # Already in cache, be silent\n  SET(MYSQL_FIND_QUIETLY TRUE)\nENDIF (MYSQL_INCLUDE_DIR)\n\nFIND_PATH(MYSQL_INCLUDE_DIR mysql.h\n  /usr/local/include/mysql\n  /usr/include/mysql\n)\n\nSET(MYSQL_NAMES mysqlclient mysqlclient_r)\nFIND_LIBRARY(MYSQL_LIBRARY\n  NAMES ${MYSQL_NAMES}\n  PATHS /usr/lib /usr/local/lib\n  PATH_SUFFIXES mysql\n)\n\nIF (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)\n  SET(MYSQL_FOUND TRUE)\n  SET( MYSQL_LIBRARIES ${MYSQL_LIBRARY} )\nELSE (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)\n  SET(MYSQL_FOUND FALSE)\n  SET( MYSQL_LIBRARIES )\nENDIF (MYSQL_INCLUDE_DIR AND MYSQL_LIBRARY)\n\nIF (MYSQL_FOUND)\n  IF (NOT MYSQL_FIND_QUIETLY)\n    MESSAGE(STATUS \"Found MySQL: ${MYSQL_LIBRARY}\")\n  ENDIF (NOT MYSQL_FIND_QUIETLY)\nELSE (MYSQL_FOUND)\n  IF (MYSQL_FIND_REQUIRED)\n    MESSAGE(STATUS \"Looked for MySQL libraries named ${MYSQL_NAMES}.\")\n    MESSAGE(FATAL_ERROR \"Could NOT find MySQL library\")\n  ENDIF (MYSQL_FIND_REQUIRED)\nENDIF (MYSQL_FOUND)\n\nMARK_AS_ADVANCED(\n  MYSQL_LIBRARY\n  MYSQL_INCLUDE_DIR\n  )\n"
  },
  {
    "path": "docs/README.md",
    "content": "# Trojan Documentation\n\nTrojan is an unidentifiable mechanism for bypassing GFW. This documentation introduces the trojan protocol, explains its underlying ideas, and provides a guide to it.\n\n## Contents\n\n- [Overview](overview)\n- [The Trojan Protocol](protocol)\n- [Config](config)\n- [Authenticator](authenticator)\n- [Build](build)\n- [Usage](usage)\n"
  },
  {
    "path": "docs/_config.yml",
    "content": "theme: jekyll-theme-cayman\nshow_downloads: true\n"
  },
  {
    "path": "docs/authenticator.md",
    "content": "# Authenticator\n\nTrojan servers can authenticate users according to not only passwords in the config file but also entries in a MySQL (MariaDB) database. To turn this functionality on, set `enabled` field in the MySQL config to `true` and correctly configure the server address, credentials, and etc. If you would like to connect to the database securely, you can fill the `ca` field indicating the MySQL server's CA file and optionally fill the `key` and `cert` fields indicating the client's private key and certificate:\n\n```json\n\"mysql\": {\n    \"enabled\": true,\n    \"server_addr\": \"127.0.0.1\",\n    \"server_port\": 3306,\n    \"database\": \"trojan\",\n    \"username\": \"trojan\",\n    \"password\": \"\",\n    \"key\": \"\",\n    \"cert\": \"\",\n    \"ca\": \"\"\n}\n```\n\nThe table has to be named `users`. An example table structure could be:\n\n```sql\nCREATE TABLE users (\n    id INT UNSIGNED NOT NULL AUTO_INCREMENT,\n    username VARCHAR(64) NOT NULL,\n    password CHAR(56) NOT NULL,\n    quota BIGINT NOT NULL DEFAULT 0,\n    download BIGINT UNSIGNED NOT NULL DEFAULT 0,\n    upload BIGINT UNSIGNED NOT NULL DEFAULT 0,\n    PRIMARY KEY (id),\n    INDEX (password)\n);\n```\n\nNote that trojan will only read/write the `password`, `quota`, `download`, and `upload` fields. Other fields exist for management convenience. The passwords stored in the table have to be hashed by SHA224 for efficiency and security reasons.\n\nUpon receiving a Trojan Request, **if the server fails to match the password with any passwords set in the config file**, it will query the database for the user. If it succeeds, trojan will check whether `download + upload < quota`; if so, the connection is granted. **A negative `quota` value means infinite quota.** After a connection is closed, trojan will increment `download` and `upload` fields of that user by the amount of data the user has used.\n\nThe unit of `quota`, `download`, and `upload` fields is Byte.\n\n[Homepage](.) | [Prev Page](config) | [Next Page](build)\n"
  },
  {
    "path": "docs/build.md",
    "content": "# Build\n\nWe'll only cover the build process on Linux since we will be providing Windows and macOS binaries. Building trojan on every platform is similar.\n\n## Dependencies\n\nInstall these dependencies before you build (note that the test has some [additional dependencies](https://github.com/trojan-gfw/trojan/blob/master/tests/LinuxSmokeTest/README.md)):\n\n- [CMake](https://cmake.org/) >= 3.7.2\n- [Boost](http://www.boost.org/) >= 1.66.0\n- [OpenSSL](https://www.openssl.org/) >= 1.1.0\n- [libmysqlclient](https://dev.mysql.com/downloads/connector/c/)\n\nFor Debian users, run `sudo apt -y install build-essential cmake libboost-system-dev libboost-program-options-dev libssl-dev default-libmysqlclient-dev` to install all the necessary dependencies.\n\n## Clone\n\nType in\n\n```bash\ngit clone https://github.com/trojan-gfw/trojan.git\ncd trojan/\n```\n\nto clone the project and go into the directory.\n\n## Build and Install\n\nType in\n\n```bash\nmkdir build\ncd build/\ncmake ..\nmake\nctest\nsudo make install\n```\n\nto build, test, and install trojan. If everything goes well you'll be able to use trojan.\n\nThe `cmake ..` command can be extended with the following options:\n\n- `-DDEFAULT_CONFIG=/path/to/default/config.json`: the default path trojan will look for config (defaults to `${CMAKE_INSTALL_FULL_SYSCONFDIR}/trojan/config.json`).\n- `ENABLE_MYSQL`\n    - `-DENABLE_MYSQL=ON`: build with MySQL support (default).\n    - `-DENABLE_MYSQL=OFF`: build without MySQL support.\n- `ENABLE_NAT` (Only on Linux)\n    - `-DENABLE_NAT=ON`: build with NAT support (default).\n    - `-DENABLE_NAT=OFF`: build without NAT support.\n- `ENABLE_REUSE_PORT` (Only on Linux)\n    - `-DENABLE_REUSE_PORT=ON`: build with `SO_REUSEPORT` support (default).\n    - `-DENABLE_REUSE_PORT=OFF`: build without `SO_REUSEPORT` support.\n- `ENABLE_SSL_KEYLOG` (OpenSSL >= 1.1.1)\n    - `-DENABLE_SSL_KEYLOG=ON`: build with SSL KeyLog support (default).\n    - `-DENABLE_SSL_KEYLOG=OFF`: build without SSL KeyLog support.\n- `ENABLE_TLS13_CIPHERSUITES` (OpenSSL >= 1.1.1)\n    - `-DENABLE_TLS13_CIPHERSUITES=ON`: build with TLS1.3 ciphersuites support (default).\n    - `-DENABLE_TLS13_CIPHERSUITES=OFF`: build without TLS1.3 ciphersuites support.\n- `FORCE_TCP_FASTOPEN`\n    - `-DFORCE_TCP_FASTOPEN=ON`: force build with `TCP_FASTOPEN` support.\n    - `-DFORCE_TCP_FASTOPEN=OFF`: build with `TCP_FASTOPEN` support based on system capabilities (default).\n- `SYSTEMD_SERVICE`\n    - `-DSYSTEMD_SERVICE=AUTO`: detect systemd automatically and decide whether to install service (default).\n    - `-DSYSTEMD_SERVICE=ON`: install systemd service unconditionally.\n    - `-DSYSTEMD_SERVICE=OFF`: don't install systemd service unconditionally.\n- `-DSYSTEMD_SERVICE_PATH=/path/to/systemd/system`: the path to which the systemd service will be installed (defaults to `/lib/systemd/system`).\n\nAfter installation, config examples will be installed to `${CMAKE_INSTALL_DOCDIR}/examples/` and a server config will be installed to `${CMAKE_INSTALL_FULL_SYSCONFDIR}/trojan/config.json`.\n\n[Homepage](.) | [Prev Page](authenticator) | [Next Page](usage)\n"
  },
  {
    "path": "docs/config.md",
    "content": "# Config\n\nIn this page, we will look at the config file of trojan. Trojan uses [`JSON`](https://en.wikipedia.org/wiki/JSON) as the format of the config.\n\n**Note: all \"\\\\\" in the paths under Windows MUST be replaced with \"/\".**\n\n## A valid client.json\n\n```json\n{\n    \"run_type\": \"client\",\n    \"local_addr\": \"127.0.0.1\",\n    \"local_port\": 1080,\n    \"remote_addr\": \"example.com\",\n    \"remote_port\": 443,\n    \"password\": [\n        \"password1\"\n    ],\n    \"log_level\": 1,\n    \"ssl\": {\n        \"verify\": true,\n        \"verify_hostname\": true,\n        \"cert\": \"\",\n        \"cipher\": \"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA\",\n        \"cipher_tls13\": \"TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384\",\n        \"sni\": \"\",\n        \"alpn\": [\n            \"h2\",\n            \"http/1.1\"\n        ],\n        \"reuse_session\": true,\n        \"session_ticket\": false,\n        \"curves\": \"\"\n    },\n    \"tcp\": {\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    }\n}\n```\n\n- `run_type`: running trojan as `client`\n- `local_addr`: a `SOCKS5` server interface will be bound to the specified interface. Feel free to change this to ``0.0.0.0``, ``::1``, ``::`` or other addresses, if you know what you are doing.\n- `local_port`: a `SOCKS5` interface will be bound to this port\n- `remote_addr`: server address (hostname)\n- `remote_port`: server port\n- `password`: password used for verification (only the first password in the array will be used)\n- `log_level`: how much log to dump. 0: ALL; 1: INFO; 2: WARN; 3: ERROR; 4: FATAL; 5: OFF.\n- `ssl`: `SSL` specific configurations\n    - `verify`: whether to verify `SSL` certificate **STRONGLY RECOMMENDED**\n    - `verify_hostname`: whether to verify `SSL` hostname (specified in the `sni` field) **STRONGLY RECOMMENDED**\n    - `cert`: if `verify` is set to `true`, the same certificate used by the server or a collection of `CA` certificates could be provided. If you leave this field blank, `OpenSSL` will try to look for a system `CA` store and will be likely to fail. Certificates can be retrieved with [this simple Python script](https://github.com/trojan-gfw/trojan/blob/master/scripts/getcert.py).\n    - `cipher`: a cipher list to send and use\n    - `cipher_tls13`: a cipher list for TLS 1.3 to use\n    - `sni`: the Server Name Indication field in the `SSL` handshake. If left blank, it will be set to `remote_addr`.\n    - `alpn`: a list of `ALPN` protocols to send\n    - `reuse_session`: whether to reuse `SSL` session\n    - `session_ticket`: whether to use session tickets for session resumption\n    - `curves`: `ECC` curves to send and use\n- `tcp`: `TCP` specific configurations\n    - `no_delay`: whether to disable Nagle's algorithm\n    - `keep_alive`: whether to enable TCP Keep Alive\n    - `reuse_port`: whether to enable TCP port reuse (kernel support required)\n    - `fast_open`: whether to enable TCP Fast Open (kernel support required)\n    - `fast_open_qlen`: the server's limit on the size of the queue of TFO requests that have not yet completed the three-way handshake\n\n## A valid forward.json\n\nThis forward config is for port forwarding through a trojan connection. Everything is the same as the client config, except for `target_addr` and `target_port`, which point to the destination endpoint, and `udp_timeout`, which controls how long (in seconds) a UDP session will last in idle.\n\nPROTIP: If you simply want to redirect a raw TCP connection, you can use `iptables` or `socat` to do that. The forward mode is not for this purpose.\n\n```json\n{\n    \"run_type\": \"forward\",\n    \"local_addr\": \"127.0.0.1\",\n    \"local_port\": 5901,\n    \"remote_addr\": \"example.com\",\n    \"remote_port\": 443,\n    \"target_addr\": \"127.0.0.1\",\n    \"target_port\": 5901,\n    \"password\": [\n        \"password1\"\n    ],\n    \"udp_timeout\": 60,\n    \"log_level\": 1,\n    \"ssl\": {\n        \"verify\": true,\n        \"verify_hostname\": true,\n        \"cert\": \"\",\n        \"cipher\": \"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA\",\n        \"cipher_tls13\": \"TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384\",\n        \"sni\": \"\",\n        \"alpn\": [\n            \"h2\",\n            \"http/1.1\"\n        ],\n        \"reuse_session\": true,\n        \"session_ticket\": false,\n        \"curves\": \"\"\n    },\n    \"tcp\": {\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    }\n}\n```\n\n## A valid nat.json\n\nThe NAT config is for transparent proxy. You'll need to [setup iptables rules](https://github.com/shadowsocks/shadowsocks-libev/tree/v3.3.1#transparent-proxy) to use it. Everything is the same as the client config.\n\n```json\n{\n    \"run_type\": \"nat\",\n    \"local_addr\": \"127.0.0.1\",\n    \"local_port\": 12345,\n    \"remote_addr\": \"example.com\",\n    \"remote_port\": 443,\n    \"password\": [\n        \"password1\"\n    ],\n    \"log_level\": 1,\n    \"ssl\": {\n        \"verify\": true,\n        \"verify_hostname\": true,\n        \"cert\": \"\",\n        \"cipher\": \"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA\",\n        \"cipher_tls13\": \"TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384\",\n        \"sni\": \"\",\n        \"alpn\": [\n            \"h2\",\n            \"http/1.1\"\n        ],\n        \"reuse_session\": true,\n        \"session_ticket\": false,\n        \"curves\": \"\"\n    },\n    \"tcp\": {\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    }\n}\n```\n\n## A valid server.json\n\n```json\n{\n    \"run_type\": \"server\",\n    \"local_addr\": \"0.0.0.0\",\n    \"local_port\": 443,\n    \"remote_addr\": \"127.0.0.1\",\n    \"remote_port\": 80,\n    \"password\": [\n        \"password1\",\n        \"password2\"\n    ],\n    \"log_level\": 1,\n    \"ssl\": {\n        \"cert\": \"/path/to/certificate.crt\",\n        \"key\": \"/path/to/private.key\",\n        \"key_password\": \"\",\n        \"cipher\": \"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384\",\n        \"cipher_tls13\": \"TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384\",\n        \"prefer_server_cipher\": true,\n        \"alpn\": [\n            \"http/1.1\"\n        ],\n        \"alpn_port_override\": {\n            \"h2\": 81\n        },\n        \"reuse_session\": true,\n        \"session_ticket\": false,\n        \"session_timeout\": 600,\n        \"plain_http_response\": \"\",\n        \"curves\": \"\",\n        \"dhparam\": \"\"\n    },\n    \"tcp\": {\n        \"prefer_ipv4\": false,\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    },\n    \"mysql\": {\n        \"enabled\": false,\n        \"server_addr\": \"127.0.0.1\",\n        \"server_port\": 3306,\n        \"database\": \"trojan\",\n        \"username\": \"trojan\",\n        \"password\": \"\",\n        \"key\": \"\",\n        \"cert\": \"\",\n        \"ca\": \"\"\n    }\n}\n```\n\n- `run_type`: running trojan as `server`\n- `local_addr`: trojan server will be bound to the specified interface. Feel free to change this to `::` or other addresses, if you know what you are doing.\n- `local_port`: trojan server will be bound to this port\n- `remote_addr`: the endpoint address that trojan server will connect to when encountering [other protocols](protocol#other-protocols)\n- `remote_port`: the endpoint port that trojan server will connect when encountering [other protocols](protocol#other-protocols)\n- `password`: an array of passwords used for verification\n- `log_level`: how much log to dump. 0: ALL; 1: INFO; 2: WARN; 3: ERROR; 4: FATAL; 5: OFF.\n- `ssl`: `SSL` specific configurations\n    - `cert`: server certificate **STRONGLY RECOMMENDED TO BE SIGNED BY A CA**. It's preferred to use the full chain certificate here instead of the certificate alone.\n    - `key`: private key file for encryption\n    - `key_password`: password of the private key file\n    - `cipher`: a cipher list to use\n    - `cipher_tls13`: a cipher list for TLS 1.3 to use\n    - `prefer_server_cipher`: whether to prefer server cipher list in a connection\n    - `alpn`: a list of `ALPN` protocols to reply\n    - `alpn_port_override`: overrides the remote port to the specified value if an `ALPN` is matched. Useful for running NGINX with HTTP/1.1 and HTTP/2 Cleartext on different ports.\n    - `reuse_session`: whether to reuse `SSL` session\n    - `session_ticket`: whether to use session tickets for session resumption\n    - `session_timeout`: if `reuse_session` is set to `true`, specify `SSL` session timeout\n    - `plain_http_response`: respond to plain http request with this file (raw TCP)\n    - `curves`: `ECC` curves to use\n    - `dhparam`: if left blank, default (RFC 3526) dhparam will be used, otherwise the specified dhparam file will be used\n- `tcp`: `TCP` specific configurations\n    - `prefer_ipv4`: whether to connect to the IPv4 address when there are both IPv6 and IPv4 addresses for a domain\n    - `no_delay`: whether to disable Nagle's algorithm\n    - `keep_alive`: whether to enable TCP Keep Alive\n    - `reuse_port`: whether to enable TCP port reuse (kernel support required)\n    - `fast_open`: whether to enable TCP Fast Open (kernel support required)\n    - `fast_open_qlen`: the server's limit on the size of the queue of TFO requests that have not yet completed the three-way handshake\n- `mysql`: see [Authenticator](authenticator)\n\n[Homepage](.) | [Prev Page](protocol) | [Next Page](authenticator)\n"
  },
  {
    "path": "docs/overview.md",
    "content": "# Overview\n\nOn penetrating GFW, people assume that strong encryption and random obfuscation may cheat GFW's filtration mechanism. However, trojan implements the direct opposite: it imitates the most common protocol across the wall, `HTTPS`, to trick GFW into thinking that it is `HTTPS`.\n\nThe [next page](protocol) introduces the trojan protocol and how it hides itself from active and passive detections.\n\n[Homepage](.) | [Next Page](protocol)\n"
  },
  {
    "path": "docs/protocol.md",
    "content": "# The Trojan Protocol\n\nWe will now show how a trojan server will react to a **valid Trojan Protocol** and **other protocols** (possibly `HTTPS` or any other probes).\n\n## Valid Trojan Protocol\n\nWhen a trojan client connects to a server, it first performs a **real** `TLS` handshake. If the handshake succeeds, all subsequent traffic will be protected by `TLS`; otherwise, the server will close the connection immediately as any `HTTPS` server would. (Trojan now also supports nginx-like response to plain HTTP requests.) Then the client sends the following structure:\n\n```\n+-----------------------+---------+----------------+---------+----------+\n| hex(SHA224(password)) |  CRLF   | Trojan Request |  CRLF   | Payload  |\n+-----------------------+---------+----------------+---------+----------+\n|          56           | X'0D0A' |    Variable    | X'0D0A' | Variable |\n+-----------------------+---------+----------------+---------+----------+\n\nwhere Trojan Request is a SOCKS5-like request:\n\n+-----+------+----------+----------+\n| CMD | ATYP | DST.ADDR | DST.PORT |\n+-----+------+----------+----------+\n|  1  |  1   | Variable |    2     |\n+-----+------+----------+----------+\n\nwhere:\n\n    o  CMD\n        o  CONNECT X'01'\n        o  UDP ASSOCIATE X'03'\n    o  ATYP address type of following address\n        o  IP V4 address: X'01'\n        o  DOMAINNAME: X'03'\n        o  IP V6 address: X'04'\n    o  DST.ADDR desired destination address\n    o  DST.PORT desired destination port in network octet order\n```\n\nMore information on `SOCKS5` requests can be found [here](https://tools.ietf.org/html/rfc1928).\n\nIf the connection is a `UDP ASSOCIATE`, then each `UDP` packet has the following format:\n\n```\n+------+----------+----------+--------+---------+----------+\n| ATYP | DST.ADDR | DST.PORT | Length |  CRLF   | Payload  |\n+------+----------+----------+--------+---------+----------+\n|  1   | Variable |    2     |   2    | X'0D0A' | Variable |\n+------+----------+----------+--------+---------+----------+\n```\n\nWhen the server receives the first data packet, it checks if the hashed password is correct and the Trojan Request is valid. If not, the protocol is considered \"other protocols\" (see next section). Note that the first packet will have payload appended. This avoids length pattern detection and may reduce the number of packets to be sent.\n\nIf the request is valid, the trojan server connects to the endpoint indicated by the `DST.ADDR` and `DST.PORT` field and opens a direct tunnel between the endpoint and trojan client.\n\n(Trojan client is simply a Trojan Protocol-`SOCKS5` converter. There is no detail worth illustrating.)\n\n## Other Protocols\n\nBecause typically a trojan server is to be assumed to be an `HTTPS` server, the listening socket is always a `TLS` socket. After performing `TLS` handshake, if the trojan server decides that the traffic is \"other protocols\", it opens a tunnel between a preset endpoint (by default it is `127.0.0.1:80`, the local `HTTP` server) to the client so the preset endpoint takes the control of the decrypted `TLS` traffic.\n\n## Anti-detection\n\n### Active Detection\n\nAll connection without correct structure and password will be redirected to a preset endpoint, so the trojan server behaves exactly the same as that endpoint (by default `HTTP`) if a suspicious probe connects (or just a fan of you connecting to your blog XD).\n\n### Passive Detection\n\nBecause the traffic is protected by `TLS` (it is users' responsibility to use a valid certificate), if you are visiting an `HTTP` site, the traffic looks the same as `HTTPS` (there is only one `RTT` after `TLS` handshake); if you are not visiting an `HTTP` site, then the traffic looks the same as `HTTPS` kept alive or `WebSocket`. Because of this, trojan can also bypass ISP `QoS` limitations.\n\nFor more information, go to [Issue #14](https://github.com/trojan-gfw/trojan/issues/14).\n\n[Homepage](.) | [Prev Page](overview) | [Next Page](config)\n"
  },
  {
    "path": "docs/trojan.1",
    "content": ".TH TROJAN 1 \"June 2020\" \"version 1.16.0\"\n.SH NAME\ntrojan \\- an unidentifiable mechanism that helps you bypass GFW\n.SH SYNOPSIS\n.B trojan\n[\\fB\\-htv\\fR] [\\fB\\-l\\fR \\fILOG\\fR] [\\fB\\-k\\fR \\fIKEYLOG\\fR] [[\\fB\\-c\\fR] \\fICONFIG\\fR]\n.SH DESCRIPTION\n.B trojan\nis an unidentifiable mechanism that helps you bypass GFW. It will load the config file located in\n.I CONFIG\nand start either a proxy client or a proxy server.\n.SH OPTIONS\n.TP\n.BR \\-c, \" \" \\-\\-config=\\fICONFIG\\fR\nSet the config file to be loaded. Default is \\fI/etc/trojan/config.json\\fR.\n.TP\n.BR \\-h, \" \" \\-\\-help\nPrint help message.\n.TP\n.BR \\-k, \" \" \\-\\-keylog=\\fIKEYLOG\\fR\nSet the keylog file to be written.\n.TP\n.BR \\-l, \" \" \\-\\-log=\\fILOG\\fR\nSet the log file to be written. If not specified, the log will be outputted to stderr.\n.TP\n.BR \\-t, \" \" \\-\\-test\nTest the config file, without starting a server.\n.TP\n.BR \\-v, \" \" \\-\\-version\nPrint version and build info.\n.SH FILES\n.TP\n.IR /etc/trojan/config.json\nThe default config file. See <https://trojan\\-gfw.github.io/trojan/config> for details.\n.SH SEE ALSO\nFull documentation at: <https://trojan\\-gfw.github.io/trojan/>\n"
  },
  {
    "path": "docs/usage.md",
    "content": "# Usage\n\n```\nusage: ./trojan [-htv] [-l LOG] [-k KEYLOG] [[-c] CONFIG]\noptions:\n  -c [ --config ] CONFIG specify config file\n  -h [ --help ]          print help message\n  -k [ --keylog ] KEYLOG specify keylog file location (OpenSSL >= 1.1.1)\n  -l [ --log ] LOG       specify log file location\n  -t [ --test ]          test config file\n  -v [ --version ]       print version and build info\n```\n\nThe default value for CONFIG is where the default config is installed on Linux and other UNIX-like systems and `config.json` on Windows.\n\nOn Linux and other UNIX-like systems, the behavior of the handlers for the following signals are overridden:\n\n- `SIGHUP`: Upon receiving `SIGHUP`, trojan will stop the service, reload the config, and restart the service. All existing connections are dropped. As a side effect, if trojan is left in the background of a shell, it will not exit when the shell exits.\n- `SIGUSR1`: Upon receiving `SIGUSR1`, trojan will reload the certificate and private key of the `SSL` server. No existing connections are dropped, and the new certificate doesn't affect these connections.\n\nMake sure your [config file](config) is valid. Configuring trojan is not trivial: there are several ideas you need to understand and several pitfalls you might fall into. Unless you are an expert, you shouldn't configure a trojan server all by yourself.\n\nHere, we will present a list of things you should do before you start a trojan server:\n\n- setup an `HTTP` server and make it useful in some sense (to deceive `GFW`).\n- register a domain name for your server.\n- Apply for or self-sign (**NOT RECOMMENDED**) an `SSL` certificate.\n- Correctly write the [config file](config).\n\n[Shadowsocks SIP003](https://shadowsocks.org/en/spec/Plugin.html) is supported by trojan, but it is added as an experimental feature and is not standard at all, so it will not be documented here.\n\n[Homepage](.) | [Prev Page](build)\n"
  },
  {
    "path": "examples/client.json-example",
    "content": "{\n    \"run_type\": \"client\",\n    \"local_addr\": \"127.0.0.1\",\n    \"local_port\": 1080,\n    \"remote_addr\": \"example.com\",\n    \"remote_port\": 443,\n    \"password\": [\n        \"password1\"\n    ],\n    \"log_level\": 1,\n    \"ssl\": {\n        \"verify\": true,\n        \"verify_hostname\": true,\n        \"cert\": \"\",\n        \"cipher\": \"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA\",\n        \"cipher_tls13\": \"TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384\",\n        \"sni\": \"\",\n        \"alpn\": [\n            \"h2\",\n            \"http/1.1\"\n        ],\n        \"reuse_session\": true,\n        \"session_ticket\": false,\n        \"curves\": \"\"\n    },\n    \"tcp\": {\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    }\n}\n"
  },
  {
    "path": "examples/forward.json-example",
    "content": "{\n    \"run_type\": \"forward\",\n    \"local_addr\": \"127.0.0.1\",\n    \"local_port\": 5901,\n    \"remote_addr\": \"example.com\",\n    \"remote_port\": 443,\n    \"target_addr\": \"127.0.0.1\",\n    \"target_port\": 5901,\n    \"password\": [\n        \"password1\"\n    ],\n    \"udp_timeout\": 60,\n    \"log_level\": 1,\n    \"ssl\": {\n        \"verify\": true,\n        \"verify_hostname\": true,\n        \"cert\": \"\",\n        \"cipher\": \"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA\",\n        \"cipher_tls13\": \"TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384\",\n        \"sni\": \"\",\n        \"alpn\": [\n            \"h2\",\n            \"http/1.1\"\n        ],\n        \"reuse_session\": true,\n        \"session_ticket\": false,\n        \"curves\": \"\"\n    },\n    \"tcp\": {\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    }\n}\n"
  },
  {
    "path": "examples/nat.json-example",
    "content": "{\n    \"run_type\": \"nat\",\n    \"local_addr\": \"127.0.0.1\",\n    \"local_port\": 12345,\n    \"remote_addr\": \"example.com\",\n    \"remote_port\": 443,\n    \"password\": [\n        \"password1\"\n    ],\n    \"log_level\": 1,\n    \"ssl\": {\n        \"verify\": true,\n        \"verify_hostname\": true,\n        \"cert\": \"\",\n        \"cipher\": \"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA:AES128-SHA:AES256-SHA:DES-CBC3-SHA\",\n        \"cipher_tls13\": \"TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384\",\n        \"sni\": \"\",\n        \"alpn\": [\n            \"h2\",\n            \"http/1.1\"\n        ],\n        \"reuse_session\": true,\n        \"session_ticket\": false,\n        \"curves\": \"\"\n    },\n    \"tcp\": {\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    }\n}\n"
  },
  {
    "path": "examples/server.json-example",
    "content": "{\n    \"run_type\": \"server\",\n    \"local_addr\": \"0.0.0.0\",\n    \"local_port\": 443,\n    \"remote_addr\": \"127.0.0.1\",\n    \"remote_port\": 80,\n    \"password\": [\n        \"password1\",\n        \"password2\"\n    ],\n    \"log_level\": 1,\n    \"ssl\": {\n        \"cert\": \"/path/to/certificate.crt\",\n        \"key\": \"/path/to/private.key\",\n        \"key_password\": \"\",\n        \"cipher\": \"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384\",\n        \"cipher_tls13\": \"TLS_AES_128_GCM_SHA256:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_256_GCM_SHA384\",\n        \"prefer_server_cipher\": true,\n        \"alpn\": [\n            \"http/1.1\"\n        ],\n        \"alpn_port_override\": {\n            \"h2\": 81\n        },\n        \"reuse_session\": true,\n        \"session_ticket\": false,\n        \"session_timeout\": 600,\n        \"plain_http_response\": \"\",\n        \"curves\": \"\",\n        \"dhparam\": \"\"\n    },\n    \"tcp\": {\n        \"prefer_ipv4\": false,\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    },\n    \"mysql\": {\n        \"enabled\": false,\n        \"server_addr\": \"127.0.0.1\",\n        \"server_port\": 3306,\n        \"database\": \"trojan\",\n        \"username\": \"trojan\",\n        \"password\": \"\",\n        \"key\": \"\",\n        \"cert\": \"\",\n        \"ca\": \"\"\n    }\n}\n"
  },
  {
    "path": "examples/trojan.service-example",
    "content": "[Unit]\nDescription=trojan\nDocumentation=man:trojan(1) https://trojan-gfw.github.io/trojan/config https://trojan-gfw.github.io/trojan/\nAfter=network.target network-online.target nss-lookup.target mysql.service mariadb.service mysqld.service\n\n[Service]\nType=simple\nStandardError=journal\nUser=nobody\nAmbientCapabilities=CAP_NET_BIND_SERVICE\nExecStart=@CMAKE_INSTALL_FULL_BINDIR@/trojan @CMAKE_INSTALL_FULL_SYSCONFDIR@/trojan/@CONFIG_NAME@.json\nExecReload=/bin/kill -HUP $MAINPID\nRestart=on-failure\nRestartSec=1s\n\n[Install]\nWantedBy=multi-user.target\n"
  },
  {
    "path": "scripts/getcert.py",
    "content": "#!/usr/bin/env python3\n\n# This file is part of the trojan project.\n# Trojan is an unidentifiable mechanism that helps you bypass GFW.\n# Copyright (C) 2017-2020  The Trojan Authors.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nimport socket\nimport ssl\nimport sys\n\ndef input_with_default(prompt, default):\n    print('{} [{}]: '.format(prompt, default), file=sys.stderr, end='')\n    line = input()\n    return line if line else default\n\ndef main(argc, argv):\n    if argc == 1:\n        hostname = input_with_default('Enter hostname', 'example.com')\n        port = int(input_with_default('Enter port number', '443'))\n    elif argc == 2:\n        hostname = argv[1]\n        port = 443\n    elif argc == 3:\n        hostname = argv[1]\n        port = int(argv[2])\n    else:\n        print('usage: {} [hostname] [port]'.format(argv[0]), file=sys.stderr)\n        exit(1)\n    ctx = ssl.create_default_context()\n    ctx.check_hostname = False\n    ctx.verify_mode = ssl.CERT_NONE\n    with socket.create_connection((hostname, port)) as sock:\n        with ctx.wrap_socket(sock, server_hostname=hostname) as ssock:\n            print(ssl.DER_cert_to_PEM_cert(ssock.getpeercert(True)), end='')\n\nif __name__ == '__main__':\n    main(len(sys.argv), sys.argv)\n"
  },
  {
    "path": "src/core/authenticator.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"authenticator.h\"\n#include <cstdlib>\n#include <stdexcept>\nusing namespace std;\n\n#ifdef ENABLE_MYSQL\n\nAuthenticator::Authenticator(const Config &config) {\n    mysql_init(&con);\n    Log::log_with_date_time(\"connecting to MySQL server \" + config.mysql.server_addr + ':' + to_string(config.mysql.server_port), Log::INFO);\n    if (!config.mysql.ca.empty()) {\n        if (!config.mysql.key.empty() && !config.mysql.cert.empty()) {\n            mysql_ssl_set(&con, config.mysql.key.c_str(), config.mysql.cert.c_str(), config.mysql.ca.c_str(), nullptr, nullptr);\n        } else {\n            mysql_ssl_set(&con, nullptr, nullptr, config.mysql.ca.c_str(), nullptr, nullptr);\n        }\n    }\n    if (mysql_real_connect(&con, config.mysql.server_addr.c_str(),\n                                 config.mysql.username.c_str(),\n                                 config.mysql.password.c_str(),\n                                 config.mysql.database.c_str(),\n                                 config.mysql.server_port, nullptr, 0) == nullptr) {\n        throw runtime_error(mysql_error(&con));\n    }\n    bool reconnect = true;\n    mysql_options(&con, MYSQL_OPT_RECONNECT, &reconnect);\n    Log::log_with_date_time(\"connected to MySQL server\", Log::INFO);\n}\n\nbool Authenticator::auth(const string &password) {\n    if (!is_valid_password(password)) {\n        return false;\n    }\n    if (mysql_query(&con, (\"SELECT quota, download + upload FROM users WHERE password = '\" + password + '\\'').c_str())) {\n        Log::log_with_date_time(mysql_error(&con), Log::ERROR);\n        return false;\n    }\n    MYSQL_RES *res = mysql_store_result(&con);\n    if (res == nullptr) {\n        Log::log_with_date_time(mysql_error(&con), Log::ERROR);\n        return false;\n    }\n    MYSQL_ROW row = mysql_fetch_row(res);\n    if (row == nullptr) {\n        mysql_free_result(res);\n        return false;\n    }\n    int64_t quota = atoll(row[0]);\n    int64_t used = atoll(row[1]);\n    mysql_free_result(res);\n    if (quota < 0) {\n        return true;\n    }\n    if (used >= quota) {\n        Log::log_with_date_time(password + \" ran out of quota\", Log::WARN);\n        return false;\n    }\n    return true;\n}\n\nvoid Authenticator::record(const string &password, uint64_t download, uint64_t upload) {\n    if (!is_valid_password(password)) {\n        return;\n    }\n    if (mysql_query(&con, (\"UPDATE users SET download = download + \" + to_string(download) + \", upload = upload + \" + to_string(upload) + \" WHERE password = '\" + password + '\\'').c_str())) {\n        Log::log_with_date_time(mysql_error(&con), Log::ERROR);\n    }\n}\n\nbool Authenticator::is_valid_password(const string &password) {\n    if (password.size() != PASSWORD_LENGTH) {\n        return false;\n    }\n    for (size_t i = 0; i < PASSWORD_LENGTH; ++i) {\n        if (!((password[i] >= '0' && password[i] <= '9') || (password[i] >= 'a' && password[i] <= 'f'))) {\n            return false;\n        }\n    }\n    return true;\n}\n\nAuthenticator::~Authenticator() {\n    mysql_close(&con);\n}\n\n#else // ENABLE_MYSQL\n\nAuthenticator::Authenticator(const Config&) {}\nbool Authenticator::auth(const string&) { return true; }\nvoid Authenticator::record(const string&, uint64_t, uint64_t) {}\nbool Authenticator::is_valid_password(const string&) { return true; }\nAuthenticator::~Authenticator() {}\n\n#endif // ENABLE_MYSQL\n"
  },
  {
    "path": "src/core/authenticator.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _AUTHENTICATOR_H_\n#define _AUTHENTICATOR_H_\n\n#ifdef ENABLE_MYSQL\n#include <mysql.h>\n#endif // ENABLE_MYSQL\n#include \"config.h\"\n\nclass Authenticator {\nprivate:\n#ifdef ENABLE_MYSQL\n    MYSQL con{};\n#endif // ENABLE_MYSQL\n    enum {\n        PASSWORD_LENGTH=56\n    };\n    static bool is_valid_password(const std::string &password);\npublic:\n    explicit Authenticator(const Config &config);\n    bool auth(const std::string &password);\n    void record(const std::string &password, uint64_t download, uint64_t upload);\n    ~Authenticator();\n};\n\n#endif // _AUTHENTICATOR_H_\n"
  },
  {
    "path": "src/core/config.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"config.h\"\n#include <cstdlib>\n#include <sstream>\n#include <stdexcept>\n#include <boost/property_tree/json_parser.hpp>\n#include <openssl/evp.h>\nusing namespace std;\nusing namespace boost::property_tree;\n\nvoid Config::load(const string &filename) {\n    ptree tree;\n    read_json(filename, tree);\n    populate(tree);\n}\n\nvoid Config::populate(const string &JSON) {\n    istringstream s(JSON);\n    ptree tree;\n    read_json(s, tree);\n    populate(tree);\n}\n\nvoid Config::populate(const ptree &tree) {\n    string rt = tree.get(\"run_type\", string(\"client\"));\n    if (rt == \"server\") {\n        run_type = SERVER;\n    } else if (rt == \"forward\") {\n        run_type = FORWARD;\n    } else if (rt == \"nat\") {\n        run_type = NAT;\n    } else if (rt == \"client\") {\n        run_type = CLIENT;\n    } else {\n        throw runtime_error(\"wrong run_type in config file\");\n    }\n    local_addr = tree.get(\"local_addr\", string());\n    local_port = tree.get(\"local_port\", uint16_t());\n    remote_addr = tree.get(\"remote_addr\", string());\n    remote_port = tree.get(\"remote_port\", uint16_t());\n    target_addr = tree.get(\"target_addr\", string());\n    target_port = tree.get(\"target_port\", uint16_t());\n    map<string, string>().swap(password);\n    if (tree.get_child_optional(\"password\")) {\n        for (auto& item: tree.get_child(\"password\")) {\n            string p = item.second.get_value<string>();\n            password[SHA224(p)] = p;\n        }\n    }\n    udp_timeout = tree.get(\"udp_timeout\", 60);\n    log_level = static_cast<Log::Level>(tree.get(\"log_level\", 1));\n    ssl.verify = tree.get(\"ssl.verify\", true);\n    ssl.verify_hostname = tree.get(\"ssl.verify_hostname\", true);\n    ssl.cert = tree.get(\"ssl.cert\", string());\n    ssl.key = tree.get(\"ssl.key\", string());\n    ssl.key_password = tree.get(\"ssl.key_password\", string());\n    ssl.cipher = tree.get(\"ssl.cipher\", string());\n    ssl.cipher_tls13 = tree.get(\"ssl.cipher_tls13\", string());\n    ssl.prefer_server_cipher = tree.get(\"ssl.prefer_server_cipher\", true);\n    ssl.sni = tree.get(\"ssl.sni\", string());\n    ssl.alpn = \"\";\n    if (tree.get_child_optional(\"ssl.alpn\")) {\n        for (auto& item: tree.get_child(\"ssl.alpn\")) {\n            string proto = item.second.get_value<string>();\n            ssl.alpn += (char)((unsigned char)(proto.length()));\n            ssl.alpn += proto;\n        }\n    }\n    map<string, uint16_t>().swap(ssl.alpn_port_override);\n    if (tree.get_child_optional(\"ssl.alpn_port_override\")) {\n        for (auto& item: tree.get_child(\"ssl.alpn_port_override\")) {\n            ssl.alpn_port_override[item.first] = item.second.get_value<uint16_t>();\n        }\n    }\n    ssl.reuse_session = tree.get(\"ssl.reuse_session\", true);\n    ssl.session_ticket = tree.get(\"ssl.session_ticket\", false);\n    ssl.session_timeout = tree.get(\"ssl.session_timeout\", long(600));\n    ssl.plain_http_response = tree.get(\"ssl.plain_http_response\", string());\n    ssl.curves = tree.get(\"ssl.curves\", string());\n    ssl.dhparam = tree.get(\"ssl.dhparam\", string());\n    tcp.prefer_ipv4 = tree.get(\"tcp.prefer_ipv4\", false);\n    tcp.no_delay = tree.get(\"tcp.no_delay\", true);\n    tcp.keep_alive = tree.get(\"tcp.keep_alive\", true);\n    tcp.reuse_port = tree.get(\"tcp.reuse_port\", false);\n    tcp.fast_open = tree.get(\"tcp.fast_open\", false);\n    tcp.fast_open_qlen = tree.get(\"tcp.fast_open_qlen\", 20);\n    mysql.enabled = tree.get(\"mysql.enabled\", false);\n    mysql.server_addr = tree.get(\"mysql.server_addr\", string(\"127.0.0.1\"));\n    mysql.server_port = tree.get(\"mysql.server_port\", uint16_t(3306));\n    mysql.database = tree.get(\"mysql.database\", string(\"trojan\"));\n    mysql.username = tree.get(\"mysql.username\", string(\"trojan\"));\n    mysql.password = tree.get(\"mysql.password\", string());\n    mysql.key = tree.get(\"mysql.key\", string());\n    mysql.cert = tree.get(\"mysql.cert\", string());\n    mysql.ca = tree.get(\"mysql.ca\", string());\n}\n\nbool Config::sip003() {\n    char *JSON = getenv(\"SS_PLUGIN_OPTIONS\");\n    if (JSON == nullptr) {\n        return false;\n    }\n    populate(JSON);\n    switch (run_type) {\n        case SERVER:\n            local_addr = getenv(\"SS_REMOTE_HOST\");\n            local_port = atoi(getenv(\"SS_REMOTE_PORT\"));\n            break;\n        case CLIENT:\n        case NAT:\n            throw runtime_error(\"SIP003 with wrong run_type\");\n        case FORWARD:\n            remote_addr = getenv(\"SS_REMOTE_HOST\");\n            remote_port = atoi(getenv(\"SS_REMOTE_PORT\"));\n            local_addr = getenv(\"SS_LOCAL_HOST\");\n            local_port = atoi(getenv(\"SS_LOCAL_PORT\"));\n            break;\n    }\n    return true;\n}\n\nstring Config::SHA224(const string &message) {\n    uint8_t digest[EVP_MAX_MD_SIZE];\n    char mdString[(EVP_MAX_MD_SIZE << 1) + 1];\n    unsigned int digest_len;\n    EVP_MD_CTX *ctx;\n    if ((ctx = EVP_MD_CTX_new()) == nullptr) {\n        throw runtime_error(\"could not create hash context\");\n    }\n    if (!EVP_DigestInit_ex(ctx, EVP_sha224(), nullptr)) {\n        EVP_MD_CTX_free(ctx);\n        throw runtime_error(\"could not initialize hash context\");\n    }\n    if (!EVP_DigestUpdate(ctx, message.c_str(), message.length())) {\n        EVP_MD_CTX_free(ctx);\n        throw runtime_error(\"could not update hash\");\n    }\n    if (!EVP_DigestFinal_ex(ctx, digest, &digest_len)) {\n        EVP_MD_CTX_free(ctx);\n        throw runtime_error(\"could not output hash\");\n    }\n\n    for (unsigned int i = 0; i < digest_len; ++i) {\n        sprintf(mdString + (i << 1), \"%02x\", (unsigned int)digest[i]);\n    }\n    mdString[digest_len << 1] = '\\0';\n    EVP_MD_CTX_free(ctx);\n    return string(mdString);\n}\n"
  },
  {
    "path": "src/core/config.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _CONFIG_H_\n#define _CONFIG_H_\n\n#include <cstdint>\n#include <map>\n#include <boost/property_tree/ptree.hpp>\n#include \"log.h\"\n\nclass Config {\npublic:\n    enum RunType {\n        SERVER,\n        CLIENT,\n        FORWARD,\n        NAT\n    } run_type;\n    std::string local_addr;\n    uint16_t local_port;\n    std::string remote_addr;\n    uint16_t remote_port;\n    std::string target_addr;\n    uint16_t target_port;\n    std::map<std::string, std::string> password;\n    int udp_timeout;\n    Log::Level log_level;\n    class SSLConfig {\n    public:\n        bool verify;\n        bool verify_hostname;\n        std::string cert;\n        std::string key;\n        std::string key_password;\n        std::string cipher;\n        std::string cipher_tls13;\n        bool prefer_server_cipher;\n        std::string sni;\n        std::string alpn;\n        std::map<std::string, uint16_t> alpn_port_override;\n        bool reuse_session;\n        bool session_ticket;\n        long session_timeout;\n        std::string plain_http_response;\n        std::string curves;\n        std::string dhparam;\n    } ssl;\n    class TCPConfig {\n    public:\n        bool prefer_ipv4;\n        bool no_delay;\n        bool keep_alive;\n        bool reuse_port;\n        bool fast_open;\n        int fast_open_qlen;\n    } tcp;\n    class MySQLConfig {\n    public:\n        bool enabled;\n        std::string server_addr;\n        uint16_t server_port;\n        std::string database;\n        std::string username;\n        std::string password;\n        std::string key;\n        std::string cert;\n        std::string ca;\n    } mysql;\n    void load(const std::string &filename);\n    void populate(const std::string &JSON);\n    bool sip003();\n    static std::string SHA224(const std::string &message);\nprivate:\n    void populate(const boost::property_tree::ptree &tree);\n};\n\n#endif // _CONFIG_H_\n"
  },
  {
    "path": "src/core/log.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"log.h\"\n#include <cstring>\n#include <cerrno>\n#include <stdexcept>\n#include <sstream>\n#include <boost/date_time/posix_time/posix_time.hpp>\n#include <boost/date_time/posix_time/posix_time_io.hpp>\n#ifdef ENABLE_ANDROID_LOG\n#include <android/log.h>\n#endif // ENABLE_ANDROID_LOG\nusing namespace std;\nusing namespace boost::posix_time;\nusing namespace boost::asio::ip;\n\nLog::Level Log::level(INFO);\nFILE *Log::keylog(nullptr);\nFILE *Log::output_stream(stderr);\nLog::LogCallback Log::log_callback{};\n\nvoid Log::log(const string &message, Level level) {\n    if (level >= Log::level) {\n#ifdef ENABLE_ANDROID_LOG\n        __android_log_print(ANDROID_LOG_ERROR, \"trojan\", \"%s\\n\",\n                            message.c_str());\n#else\n        fprintf(output_stream, \"%s\\n\", message.c_str());\n        fflush(output_stream);\n#endif // ENABLE_ANDROID_LOG\n        if (log_callback) {\n            log_callback(message, level);\n        }\n    }\n}\n\nvoid Log::log_with_date_time(const string &message, Level level) {\n    static const char *level_strings[]= {\"ALL\", \"INFO\", \"WARN\", \"ERROR\", \"FATAL\", \"OFF\"};\n    auto *facet = new time_facet(\"[%Y-%m-%d %H:%M:%S] \");\n    ostringstream stream;\n    stream.imbue(locale(stream.getloc(), facet));\n    stream << second_clock::local_time();\n    string level_string = '[' + string(level_strings[level]) + \"] \";\n    log(stream.str() + level_string + message, level);\n}\n\nvoid Log::log_with_endpoint(const tcp::endpoint &endpoint, const string &message, Level level) {\n    log_with_date_time(endpoint.address().to_string() + ':' + to_string(endpoint.port()) + ' ' + message, level);\n}\n\nvoid Log::redirect(const string &filename) {\n    FILE *fp = fopen(filename.c_str(), \"a\");\n    if (fp == nullptr) {\n        throw runtime_error(filename + \": \" + strerror(errno));\n    }\n    if (output_stream != stderr) {\n        fclose(output_stream);\n    }\n    output_stream = fp;\n}\n\nvoid Log::redirect_keylog(const string &filename) {\n    FILE *fp = fopen(filename.c_str(), \"a\");\n    if (fp == nullptr) {\n        throw runtime_error(filename + \": \" + strerror(errno));\n    }\n    if (keylog != nullptr) {\n        fclose(keylog);\n    }\n    keylog = fp;\n}\n\nvoid Log::set_callback(LogCallback cb) {\n    log_callback = move(cb);\n}\n\nvoid Log::reset() {\n    if (output_stream != stderr) {\n        fclose(output_stream);\n        output_stream = stderr;\n    }\n    if (keylog != nullptr) {\n        fclose(keylog);\n        keylog = nullptr;\n    }\n}\n"
  },
  {
    "path": "src/core/log.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _LOG_H_\n#define _LOG_H_\n\n#include <cstdio>\n#include <string>\n#include <boost/asio/ip/tcp.hpp>\n\n#ifdef ERROR // windows.h\n#undef ERROR\n#endif // ERROR\n\nclass Log {\npublic:\n    enum Level {\n        ALL = 0,\n        INFO = 1,\n        WARN = 2,\n        ERROR = 3,\n        FATAL = 4,\n        OFF = 5\n    };\n    typedef std::function<void(const std::string &, Level)> LogCallback;\n    static Level level;\n    static FILE *keylog;\n    static void log(const std::string &message, Level level = ALL);\n    static void log_with_date_time(const std::string &message, Level level = ALL);\n    static void log_with_endpoint(const boost::asio::ip::tcp::endpoint &endpoint, const std::string &message, Level level = ALL);\n    static void redirect(const std::string &filename);\n    static void redirect_keylog(const std::string &filename);\n    static void set_callback(LogCallback cb);\n    static void reset();\nprivate:\n    static FILE *output_stream;\n    static LogCallback log_callback;\n};\n\n#endif // _LOG_H_\n"
  },
  {
    "path": "src/core/service.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"service.h\"\n#include <cstring>\n#include <cerrno>\n#include <stdexcept>\n#include <fstream>\n#ifdef _WIN32\n#include <wincrypt.h>\n#include <tchar.h>\n#endif // _WIN32\n#ifdef __APPLE__\n#include <Security/Security.h>\n#endif // __APPLE__\n#include <openssl/opensslv.h>\n#include \"session/serversession.h\"\n#include \"session/clientsession.h\"\n#include \"session/forwardsession.h\"\n#include \"session/natsession.h\"\n#include \"ssl/ssldefaults.h\"\n#include \"ssl/sslsession.h\"\nusing namespace std;\nusing namespace boost::asio::ip;\nusing namespace boost::asio::ssl;\n\n#ifdef ENABLE_REUSE_PORT\ntypedef boost::asio::detail::socket_option::boolean<SOL_SOCKET, SO_REUSEPORT> reuse_port;\n#endif // ENABLE_REUSE_PORT\n\nService::Service(Config &config, bool test) :\n    config(config),\n    socket_acceptor(io_context),\n    ssl_context(context::sslv23),\n    auth(nullptr),\n    udp_socket(io_context) {\n#ifndef ENABLE_NAT\n    if (config.run_type == Config::NAT) {\n        throw runtime_error(\"NAT is not supported\");\n    }\n#endif // ENABLE_NAT\n    if (!test) {\n        tcp::resolver resolver(io_context);\n        tcp::endpoint listen_endpoint = *resolver.resolve(config.local_addr, to_string(config.local_port)).begin();\n        socket_acceptor.open(listen_endpoint.protocol());\n        socket_acceptor.set_option(tcp::acceptor::reuse_address(true));\n\n        if (config.tcp.reuse_port) {\n#ifdef ENABLE_REUSE_PORT\n            socket_acceptor.set_option(reuse_port(true));\n#else  // ENABLE_REUSE_PORT\n            Log::log_with_date_time(\"SO_REUSEPORT is not supported\", Log::WARN);\n#endif // ENABLE_REUSE_PORT\n        }\n\n        socket_acceptor.bind(listen_endpoint);\n        socket_acceptor.listen();\n        if (config.run_type == Config::FORWARD) {\n            auto udp_bind_endpoint = udp::endpoint(listen_endpoint.address(), listen_endpoint.port());\n            udp_socket.open(udp_bind_endpoint.protocol());\n            udp_socket.bind(udp_bind_endpoint);\n        }\n    }\n    Log::level = config.log_level;\n    auto native_context = ssl_context.native_handle();\n    ssl_context.set_options(context::default_workarounds | context::no_sslv2 | context::no_sslv3 | context::single_dh_use);\n    if (!config.ssl.curves.empty()) {\n        SSL_CTX_set1_curves_list(native_context, config.ssl.curves.c_str());\n    }\n    if (config.run_type == Config::SERVER) {\n        ssl_context.use_certificate_chain_file(config.ssl.cert);\n        ssl_context.set_password_callback([this](size_t, context_base::password_purpose) {\n            return this->config.ssl.key_password;\n        });\n        ssl_context.use_private_key_file(config.ssl.key, context::pem);\n        if (config.ssl.prefer_server_cipher) {\n            SSL_CTX_set_options(native_context, SSL_OP_CIPHER_SERVER_PREFERENCE);\n        }\n        if (!config.ssl.alpn.empty()) {\n            SSL_CTX_set_alpn_select_cb(native_context, [](SSL*, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *config) -> int {\n                if (SSL_select_next_proto((unsigned char**)out, outlen, (unsigned char*)(((Config*)config)->ssl.alpn.c_str()), ((Config*)config)->ssl.alpn.length(), in, inlen) != OPENSSL_NPN_NEGOTIATED) {\n                    return SSL_TLSEXT_ERR_NOACK;\n                }\n                return SSL_TLSEXT_ERR_OK;\n            }, &config);\n        }\n        if (config.ssl.reuse_session) {\n            SSL_CTX_set_timeout(native_context, config.ssl.session_timeout);\n            if (!config.ssl.session_ticket) {\n                SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET);\n            }\n        } else {\n            SSL_CTX_set_session_cache_mode(native_context, SSL_SESS_CACHE_OFF);\n            SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET);\n        }\n        if (!config.ssl.plain_http_response.empty()) {\n            ifstream ifs(config.ssl.plain_http_response, ios::binary);\n            if (!ifs.is_open()) {\n                throw runtime_error(config.ssl.plain_http_response + \": \" + strerror(errno));\n            }\n            plain_http_response = string(istreambuf_iterator<char>(ifs), istreambuf_iterator<char>());\n        }\n        if (config.ssl.dhparam.empty()) {\n            ssl_context.use_tmp_dh(boost::asio::const_buffer(SSLDefaults::g_dh2048_sz, SSLDefaults::g_dh2048_sz_size));\n        } else {\n            ssl_context.use_tmp_dh_file(config.ssl.dhparam);\n        }\n        if (config.mysql.enabled) {\n#ifdef ENABLE_MYSQL\n            auth = new Authenticator(config);\n#else // ENABLE_MYSQL\n            Log::log_with_date_time(\"MySQL is not supported\", Log::WARN);\n#endif // ENABLE_MYSQL\n        }\n    } else {\n        if (config.ssl.sni.empty()) {\n            config.ssl.sni = config.remote_addr;\n        }\n        if (config.ssl.verify) {\n            ssl_context.set_verify_mode(verify_peer);\n            if (config.ssl.cert.empty()) {\n                ssl_context.set_default_verify_paths();\n#ifdef _WIN32\n                HCERTSTORE h_store = CertOpenSystemStore(0, _T(\"ROOT\"));\n                if (h_store) {\n                    X509_STORE *store = SSL_CTX_get_cert_store(native_context);\n                    PCCERT_CONTEXT p_context = NULL;\n                    while ((p_context = CertEnumCertificatesInStore(h_store, p_context))) {\n                        const unsigned char *encoded_cert = p_context->pbCertEncoded;\n                        X509 *x509 = d2i_X509(NULL, &encoded_cert, p_context->cbCertEncoded);\n                        if (x509) {\n                            X509_STORE_add_cert(store, x509);\n                            X509_free(x509);\n                        }\n                    }\n                    CertCloseStore(h_store, 0);\n                }\n#endif // _WIN32\n#ifdef __APPLE__\n                SecKeychainSearchRef pSecKeychainSearch = NULL;\n                SecKeychainRef pSecKeychain;\n                OSStatus status = noErr;\n                X509 *cert = NULL;\n\n                // Leopard and above store location\n                status = SecKeychainOpen (\"/System/Library/Keychains/SystemRootCertificates.keychain\", &pSecKeychain);\n                if (status == noErr) {\n                    X509_STORE *store = SSL_CTX_get_cert_store(native_context);\n                    status = SecKeychainSearchCreateFromAttributes (pSecKeychain, kSecCertificateItemClass, NULL, &pSecKeychainSearch);\n                     for (;;) {\n                        SecKeychainItemRef pSecKeychainItem = nil;\n\n                        status = SecKeychainSearchCopyNext (pSecKeychainSearch, &pSecKeychainItem);\n                        if (status == errSecItemNotFound) {\n                            break;\n                        }\n\n                        if (status == noErr) {\n                            void *_pCertData;\n                            UInt32 _pCertLength;\n                            status = SecKeychainItemCopyAttributesAndData (pSecKeychainItem, NULL, NULL, NULL, &_pCertLength, &_pCertData);\n\n                            if (status == noErr && _pCertData != NULL) {\n                                unsigned char *ptr;\n\n                                ptr = (unsigned char *)_pCertData;       /*required because d2i_X509 is modifying pointer */\n                                cert = d2i_X509 (NULL, (const unsigned char **) &ptr, _pCertLength);\n                                if (cert == NULL) {\n                                    continue;\n                                }\n\n                                if (!X509_STORE_add_cert (store, cert)) {\n                                    X509_free (cert);\n                                    continue;\n                                }\n                                X509_free (cert);\n\n                                status = SecKeychainItemFreeAttributesAndData (NULL, _pCertData);\n                            }\n                        }\n                        if (pSecKeychainItem != NULL) {\n                            CFRelease (pSecKeychainItem);\n                        }\n                    }\n                    CFRelease (pSecKeychainSearch);\n                    CFRelease (pSecKeychain);\n                }\n#endif // __APPLE__\n            } else {\n                ssl_context.load_verify_file(config.ssl.cert);\n            }\n            if (config.ssl.verify_hostname) {\n#if BOOST_VERSION >= 107300\n                ssl_context.set_verify_callback(host_name_verification(config.ssl.sni));\n#else\n                ssl_context.set_verify_callback(rfc2818_verification(config.ssl.sni));\n#endif\n            }\n            X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();\n            X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_PARTIAL_CHAIN);\n            SSL_CTX_set1_param(native_context, param);\n            X509_VERIFY_PARAM_free(param);\n        } else {\n            ssl_context.set_verify_mode(verify_none);\n        }\n        if (!config.ssl.alpn.empty()) {\n            SSL_CTX_set_alpn_protos(native_context, (unsigned char*)(config.ssl.alpn.c_str()), config.ssl.alpn.length());\n        }\n        if (config.ssl.reuse_session) {\n            SSL_CTX_set_session_cache_mode(native_context, SSL_SESS_CACHE_CLIENT);\n            SSLSession::set_callback(native_context);\n            if (!config.ssl.session_ticket) {\n                SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET);\n            }\n        } else {\n            SSL_CTX_set_options(native_context, SSL_OP_NO_TICKET);\n        }\n    }\n    if (!config.ssl.cipher.empty()) {\n        SSL_CTX_set_cipher_list(native_context, config.ssl.cipher.c_str());\n    }\n    if (!config.ssl.cipher_tls13.empty()) {\n#ifdef ENABLE_TLS13_CIPHERSUITES\n        SSL_CTX_set_ciphersuites(native_context, config.ssl.cipher_tls13.c_str());\n#else  // ENABLE_TLS13_CIPHERSUITES\n        Log::log_with_date_time(\"TLS1.3 ciphersuites are not supported\", Log::WARN);\n#endif // ENABLE_TLS13_CIPHERSUITES\n    }\n\n    if (!test) {\n        if (config.tcp.no_delay) {\n            socket_acceptor.set_option(tcp::no_delay(true));\n        }\n        if (config.tcp.keep_alive) {\n            socket_acceptor.set_option(boost::asio::socket_base::keep_alive(true));\n        }\n        if (config.tcp.fast_open) {\n#ifdef TCP_FASTOPEN\n            using fastopen = boost::asio::detail::socket_option::integer<IPPROTO_TCP, TCP_FASTOPEN>;\n            boost::system::error_code ec;\n            socket_acceptor.set_option(fastopen(config.tcp.fast_open_qlen), ec);\n#else // TCP_FASTOPEN\n            Log::log_with_date_time(\"TCP_FASTOPEN is not supported\", Log::WARN);\n#endif // TCP_FASTOPEN\n#ifndef TCP_FASTOPEN_CONNECT\n            Log::log_with_date_time(\"TCP_FASTOPEN_CONNECT is not supported\", Log::WARN);\n#endif // TCP_FASTOPEN_CONNECT\n        }\n    }\n    if (Log::keylog) {\n#ifdef ENABLE_SSL_KEYLOG\n        SSL_CTX_set_keylog_callback(native_context, [](const SSL*, const char *line) {\n            fprintf(Log::keylog, \"%s\\n\", line);\n            fflush(Log::keylog);\n        });\n#else // ENABLE_SSL_KEYLOG\n        Log::log_with_date_time(\"SSL KeyLog is not supported\", Log::WARN);\n#endif // ENABLE_SSL_KEYLOG\n    }\n}\n\nvoid Service::run() {\n    async_accept();\n    if (config.run_type == Config::FORWARD) {\n        udp_async_read();\n    }\n    tcp::endpoint local_endpoint = socket_acceptor.local_endpoint();\n    string rt;\n    if (config.run_type == Config::SERVER) {\n        rt = \"server\";\n    } else if (config.run_type == Config::FORWARD) {\n        rt = \"forward\";\n    } else if (config.run_type == Config::NAT) {\n        rt = \"nat\";\n    } else {\n        rt = \"client\";\n    }\n    Log::log_with_date_time(string(\"trojan service (\") + rt + \") started at \" + local_endpoint.address().to_string() + ':' + to_string(local_endpoint.port()), Log::WARN);\n    io_context.run();\n    Log::log_with_date_time(\"trojan service stopped\", Log::WARN);\n}\n\nvoid Service::stop() {\n    boost::system::error_code ec;\n    socket_acceptor.cancel(ec);\n    if (udp_socket.is_open()) {\n        udp_socket.cancel(ec);\n        udp_socket.close(ec);\n    }\n    io_context.stop();\n}\n\nvoid Service::async_accept() {\n    shared_ptr<Session>session(nullptr);\n    if (config.run_type == Config::SERVER) {\n        session = make_shared<ServerSession>(config, io_context, ssl_context, auth, plain_http_response);\n    } else if (config.run_type == Config::FORWARD) {\n        session = make_shared<ForwardSession>(config, io_context, ssl_context);\n    } else if (config.run_type == Config::NAT) {\n        session = make_shared<NATSession>(config, io_context, ssl_context);\n    } else {\n        session = make_shared<ClientSession>(config, io_context, ssl_context);\n    }\n    socket_acceptor.async_accept(session->accept_socket(), [this, session](const boost::system::error_code error) {\n        if (error == boost::asio::error::operation_aborted) {\n            // got cancel signal, stop calling myself\n            return;\n        }\n        if (!error) {\n            boost::system::error_code ec;\n            auto endpoint = session->accept_socket().remote_endpoint(ec);\n            if (!ec) {\n                Log::log_with_endpoint(endpoint, \"incoming connection\");\n                session->start();\n            }\n        }\n        async_accept();\n    });\n}\n\nvoid Service::udp_async_read() {\n    udp_socket.async_receive_from(boost::asio::buffer(udp_read_buf, MAX_LENGTH), udp_recv_endpoint, [this](const boost::system::error_code error, size_t length) {\n        if (error == boost::asio::error::operation_aborted) {\n            // got cancel signal, stop calling myself\n            return;\n        }\n        if (error) {\n            stop();\n            throw runtime_error(error.message());\n        }\n        string data((const char *)udp_read_buf, length);\n        for (auto it = udp_sessions.begin(); it != udp_sessions.end();) {\n            auto next = ++it;\n            --it;\n            if (it->expired()) {\n                udp_sessions.erase(it);\n            } else if (it->lock()->process(udp_recv_endpoint, data)) {\n                udp_async_read();\n                return;\n            }\n            it = next;\n        }\n        Log::log_with_endpoint(tcp::endpoint(udp_recv_endpoint.address(), udp_recv_endpoint.port()), \"new UDP session\");\n        auto session = make_shared<UDPForwardSession>(config, io_context, ssl_context, udp_recv_endpoint, [this](const udp::endpoint &endpoint, const string &data) {\n            boost::system::error_code ec;\n            udp_socket.send_to(boost::asio::buffer(data), endpoint, 0, ec);\n            if (ec == boost::asio::error::no_permission) {\n                Log::log_with_endpoint(tcp::endpoint(endpoint.address(), endpoint.port()), \"dropped a UDP packet due to firewall policy or rate limit\");\n            } else if (ec) {\n                throw runtime_error(ec.message());\n            }\n        });\n        udp_sessions.emplace_back(session);\n        session->start();\n        session->process(udp_recv_endpoint, data);\n        udp_async_read();\n    });\n}\n\nboost::asio::io_context &Service::service() {\n    return io_context;\n}\n\nvoid Service::reload_cert() {\n    if (config.run_type == Config::SERVER) {\n        Log::log_with_date_time(\"reloading certificate and private key. . . \", Log::WARN);\n        ssl_context.use_certificate_chain_file(config.ssl.cert);\n        ssl_context.use_private_key_file(config.ssl.key, context::pem);\n        boost::system::error_code ec;\n        socket_acceptor.cancel(ec);\n        async_accept();\n        Log::log_with_date_time(\"certificate and private key reloaded\", Log::WARN);\n    } else {\n        Log::log_with_date_time(\"cannot reload certificate and private key: wrong run_type\", Log::ERROR);\n    }\n}\n\nService::~Service() {\n    if (auth) {\n        delete auth;\n        auth = nullptr;\n    }\n}\n"
  },
  {
    "path": "src/core/service.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _SERVICE_H_\n#define _SERVICE_H_\n\n#include <list>\n#include <boost/version.hpp>\n#include <boost/asio/io_context.hpp>\n#include <boost/asio/ssl.hpp>\n#include <boost/asio/ip/udp.hpp>\n#include \"authenticator.h\"\n#include \"session/udpforwardsession.h\"\n\nclass Service {\nprivate:\n    enum {\n        MAX_LENGTH = 8192\n    };\n    const Config &config;\n    boost::asio::io_context io_context;\n    boost::asio::ip::tcp::acceptor socket_acceptor;\n    boost::asio::ssl::context ssl_context;\n    Authenticator *auth;\n    std::string plain_http_response;\n    boost::asio::ip::udp::socket udp_socket;\n    std::list<std::weak_ptr<UDPForwardSession> > udp_sessions;\n    uint8_t udp_read_buf[MAX_LENGTH]{};\n    boost::asio::ip::udp::endpoint udp_recv_endpoint;\n    void async_accept();\n    void udp_async_read();\npublic:\n    explicit Service(Config &config, bool test = false);\n    void run();\n    void stop();\n    boost::asio::io_context &service();\n    void reload_cert();\n    ~Service();\n};\n\n#endif // _SERVICE_H_\n"
  },
  {
    "path": "src/core/version.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"version.h\"\nusing namespace std;\n\nconst string Version::version(\"1.16.0\");\n\nstring Version::get_version() {\n    return version;\n}\n"
  },
  {
    "path": "src/core/version.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _VERSION_H_\n#define _VERSION_H_\n\n#include <string>\n\nclass Version {\nprivate:\n    const static std::string version;\npublic:\n    static std::string get_version();\n};\n\n#endif // _VERSION_H_\n"
  },
  {
    "path": "src/main.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <cstdlib>\n#include <iostream>\n#include <boost/asio/signal_set.hpp>\n#include <boost/program_options.hpp>\n#include <boost/version.hpp>\n#include <openssl/opensslv.h>\n#ifdef ENABLE_MYSQL\n#include <mysql.h>\n#endif // ENABLE_MYSQL\n#include \"core/service.h\"\n#include \"core/version.h\"\nusing namespace std;\nusing namespace boost::asio;\nnamespace po = boost::program_options;\n\n#ifndef DEFAULT_CONFIG\n#define DEFAULT_CONFIG \"config.json\"\n#endif // DEFAULT_CONFIG\n\nvoid signal_async_wait(signal_set &sig, Service &service, bool &restart) {\n    sig.async_wait([&](const boost::system::error_code error, int signum) {\n        if (error) {\n            return;\n        }\n        Log::log_with_date_time(\"got signal: \" + to_string(signum), Log::WARN);\n        switch (signum) {\n            case SIGINT:\n            case SIGTERM:\n                service.stop();\n                break;\n#ifndef _WIN32\n            case SIGHUP:\n                restart = true;\n                service.stop();\n                break;\n            case SIGUSR1:\n                service.reload_cert();\n                signal_async_wait(sig, service, restart);\n                break;\n#endif // _WIN32\n        }\n    });\n}\n\nint main(int argc, const char *argv[]) {\n    try {\n        Log::log(\"Welcome to trojan \" + Version::get_version(), Log::FATAL);\n        string config_file;\n        string log_file;\n        string keylog_file;\n        bool test;\n        po::options_description desc(\"options\");\n        desc.add_options()\n            (\"config,c\", po::value<string>(&config_file)->default_value(DEFAULT_CONFIG)->value_name(\"CONFIG\"), \"specify config file\")\n            (\"help,h\", \"print help message\")\n            (\"keylog,k\", po::value<string>(&keylog_file)->value_name(\"KEYLOG\"), \"specify keylog file location (OpenSSL >= 1.1.1)\")\n            (\"log,l\", po::value<string>(&log_file)->value_name(\"LOG\"), \"specify log file location\")\n            (\"test,t\", po::bool_switch(&test), \"test config file\")\n            (\"version,v\", \"print version and build info\")\n        ;\n        po::positional_options_description pd;\n        pd.add(\"config\", 1);\n        po::variables_map vm;\n        po::store(po::command_line_parser(argc, argv).options(desc).positional(pd).run(), vm);\n        po::notify(vm);\n        if (vm.count(\"help\")) {\n            Log::log(string(\"usage: \") + argv[0] + \" [-htv] [-l LOG] [-k KEYLOG] [[-c] CONFIG]\", Log::FATAL);\n            cerr << desc;\n            exit(EXIT_SUCCESS);\n        }\n        if (vm.count(\"version\")) {\n            Log::log(string(\"Boost \") + BOOST_LIB_VERSION + \", \" + OpenSSL_version(OPENSSL_VERSION), Log::FATAL);\n#ifdef ENABLE_MYSQL\n            Log::log(string(\" [Enabled] MySQL Support (\") + mysql_get_client_info() + ')', Log::FATAL);\n#else // ENABLE_MYSQL\n            Log::log(\"[Disabled] MySQL Support\", Log::FATAL);\n#endif // ENABLE_MYSQL\n#ifdef TCP_FASTOPEN\n            Log::log(\" [Enabled] TCP_FASTOPEN Support\", Log::FATAL);\n#else // TCP_FASTOPEN\n            Log::log(\"[Disabled] TCP_FASTOPEN Support\", Log::FATAL);\n#endif // TCP_FASTOPEN\n#ifdef TCP_FASTOPEN_CONNECT\n            Log::log(\" [Enabled] TCP_FASTOPEN_CONNECT Support\", Log::FATAL);\n#else // TCP_FASTOPEN_CONNECT\n            Log::log(\"[Disabled] TCP_FASTOPEN_CONNECT Support\", Log::FATAL);\n#endif // TCP_FASTOPEN_CONNECT\n#if ENABLE_SSL_KEYLOG\n            Log::log(\" [Enabled] SSL KeyLog Support\", Log::FATAL);\n#else // ENABLE_SSL_KEYLOG\n            Log::log(\"[Disabled] SSL KeyLog Support\", Log::FATAL);\n#endif // ENABLE_SSL_KEYLOG\n#ifdef ENABLE_NAT\n            Log::log(\" [Enabled] NAT Support\", Log::FATAL);\n#else // ENABLE_NAT\n            Log::log(\"[Disabled] NAT Support\", Log::FATAL);\n#endif // ENABLE_NAT\n#ifdef ENABLE_TLS13_CIPHERSUITES\n            Log::log(\" [Enabled] TLS1.3 Ciphersuites Support\", Log::FATAL);\n#else // ENABLE_TLS13_CIPHERSUITES\n            Log::log(\"[Disabled] TLS1.3 Ciphersuites Support\", Log::FATAL);\n#endif // ENABLE_TLS13_CIPHERSUITES\n#ifdef ENABLE_REUSE_PORT\n            Log::log(\" [Enabled] TCP Port Reuse Support\", Log::FATAL);\n#else // ENABLE_REUSE_PORT\n            Log::log(\"[Disabled] TCP Port Reuse Support\", Log::FATAL);\n#endif // ENABLE_REUSE_PORT\n            Log::log(\"OpenSSL Information\", Log::FATAL);\n            if (OpenSSL_version_num() != OPENSSL_VERSION_NUMBER) {\n                Log::log(string(\"\\tCompile-time Version: \") + OPENSSL_VERSION_TEXT, Log::FATAL);\n            }\n            Log::log(string(\"\\tBuild Flags: \") + OpenSSL_version(OPENSSL_CFLAGS), Log::FATAL);\n            exit(EXIT_SUCCESS);\n        }\n        if (vm.count(\"log\")) {\n            Log::redirect(log_file);\n        }\n        if (vm.count(\"keylog\")) {\n            Log::redirect_keylog(keylog_file);\n        }\n        bool restart;\n        Config config;\n        do {\n            restart = false;\n            if (config.sip003()) {\n                Log::log_with_date_time(\"SIP003 is loaded\", Log::WARN);\n            } else {\n                config.load(config_file);\n            }\n            Service service(config, test);\n            if (test) {\n                Log::log(\"The config file looks good.\", Log::OFF);\n                exit(EXIT_SUCCESS);\n            }\n            signal_set sig(service.service());\n            sig.add(SIGINT);\n            sig.add(SIGTERM);\n#ifndef _WIN32\n            sig.add(SIGHUP);\n            sig.add(SIGUSR1);\n#endif // _WIN32\n            signal_async_wait(sig, service, restart);\n            service.run();\n            if (restart) {\n                Log::log_with_date_time(\"trojan service restarting. . . \", Log::WARN);\n            }\n        } while (restart);\n        Log::reset();\n        exit(EXIT_SUCCESS);\n    } catch (const exception &e) {\n        Log::log_with_date_time(string(\"fatal: \") + e.what(), Log::FATAL);\n        Log::log_with_date_time(\"exiting. . . \", Log::FATAL);\n        exit(EXIT_FAILURE);\n    }\n}\n"
  },
  {
    "path": "src/proto/socks5address.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"socks5address.h\"\n#include <cstdio>\nusing namespace std;\nusing namespace boost::asio::ip;\n\nbool SOCKS5Address::parse(const string &data, size_t &address_len) {\n    if (data.length() == 0 || (data[0] != IPv4 && data[0] != DOMAINNAME && data[0] != IPv6)) {\n        return false;\n    }\n    address_type = static_cast<AddressType>(data[0]);\n    switch (address_type) {\n        case IPv4: {\n            if (data.length() > 4 + 2) {\n                address = to_string(uint8_t(data[1])) + '.' +\n                          to_string(uint8_t(data[2])) + '.' +\n                          to_string(uint8_t(data[3])) + '.' +\n                          to_string(uint8_t(data[4]));\n                port = (uint8_t(data[5]) << 8) | uint8_t(data[6]);\n                address_len = 1 + 4 + 2;\n                return true;\n            }\n            break;\n        }\n        case DOMAINNAME: {\n            uint8_t domain_len = data[1];\n            if (domain_len == 0) {\n                // invalid domain len\n                break;\n            }\n            if (data.length() > (unsigned int)(1 + domain_len + 2)) {\n                address = data.substr(2, domain_len);\n                port = (uint8_t(data[domain_len + 2]) << 8) | uint8_t(data[domain_len + 3]);\n                address_len =  1 + 1 + domain_len + 2;\n                return true;\n            }\n            break;\n        }\n        case IPv6: {\n            if (data.length() > 16 + 2) {\n                char t[40];\n                sprintf(t, \"%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x\",\n                        uint8_t(data[1]), uint8_t(data[2]), uint8_t(data[3]), uint8_t(data[4]),\n                        uint8_t(data[5]), uint8_t(data[6]), uint8_t(data[7]), uint8_t(data[8]),\n                        uint8_t(data[9]), uint8_t(data[10]), uint8_t(data[11]), uint8_t(data[12]),\n                        uint8_t(data[13]), uint8_t(data[14]), uint8_t(data[15]), uint8_t(data[16]));\n                address = t;\n                port = (uint8_t(data[17]) << 8) | uint8_t(data[18]);\n                address_len = 1 + 16 + 2;\n                return true;\n            }\n            break;\n        }\n    }\n    return false;\n}\n\nstring SOCKS5Address::generate(const udp::endpoint &endpoint) {\n    if (endpoint.address().is_unspecified()) {\n        return string(\"\\x01\\x00\\x00\\x00\\x00\\x00\\x00\", 7);\n    }\n    string ret;\n    if (endpoint.address().is_v4()) {\n        ret += '\\x01';\n        auto ip = endpoint.address().to_v4().to_bytes();\n        for (int i = 0; i < 4; ++i) {\n            ret += char(ip[i]);\n        }\n    }\n    if (endpoint.address().is_v6()) {\n        ret += '\\x04';\n        auto ip = endpoint.address().to_v6().to_bytes();\n        for (int i = 0; i < 16; ++i) {\n            ret += char(ip[i]);\n        }\n    }\n    ret += char(uint8_t(endpoint.port() >> 8));\n    ret += char(uint8_t(endpoint.port() & 0xFF));\n    return ret;\n}\n"
  },
  {
    "path": "src/proto/socks5address.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _SOCKS5ADDRESS_H_\n#define _SOCKS5ADDRESS_H_\n\n#include <cstdint>\n#include <string>\n#include <boost/asio/ip/udp.hpp>\n\nclass SOCKS5Address {\npublic:\n    enum AddressType {\n        IPv4 = 1,\n        DOMAINNAME = 3,\n        IPv6 = 4\n    } address_type;\n    std::string address;\n    uint16_t port;\n    bool parse(const std::string &data, size_t &address_len);\n    static std::string generate(const boost::asio::ip::udp::endpoint &endpoint);\n};\n\n#endif // _SOCKS5ADDRESS_H_\n"
  },
  {
    "path": "src/proto/trojanrequest.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"trojanrequest.h\"\nusing namespace std;\n\nint TrojanRequest::parse(const string &data) {\n    size_t first = data.find(\"\\r\\n\");\n    if (first == string::npos) {\n        return -1;\n    }\n    password = data.substr(0, first);\n    payload = data.substr(first + 2);\n    if (payload.length() == 0 || (payload[0] != CONNECT && payload[0] != UDP_ASSOCIATE)) {\n        return -1;\n    }\n    command = static_cast<Command>(payload[0]);\n    size_t address_len;\n    bool is_addr_valid = address.parse(payload.substr(1), address_len);\n    if (!is_addr_valid || payload.length() < address_len + 3 || payload.substr(address_len + 1, 2) != \"\\r\\n\") {\n        return -1;\n    }\n    payload = payload.substr(address_len + 3);\n    return data.length();\n}\n\nstring TrojanRequest::generate(const string &password, const string &domainname, uint16_t port, bool tcp) {\n    string ret = password + \"\\r\\n\";\n    if (tcp) {\n        ret += '\\x01';\n    } else {\n        ret += '\\x03';\n    }\n    ret += '\\x03';\n    ret += char(uint8_t(domainname.length()));\n    ret += domainname;\n    ret += char(uint8_t(port >> 8));\n    ret += char(uint8_t(port & 0xFF));\n    ret += \"\\r\\n\";\n    return ret;\n}\n"
  },
  {
    "path": "src/proto/trojanrequest.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _TROJANREQUEST_H_\n#define _TROJANREQUEST_H_\n\n#include \"socks5address.h\"\n\nclass TrojanRequest {\npublic:\n    std::string password;\n    enum Command {\n        CONNECT = 1,\n        UDP_ASSOCIATE = 3\n    } command;\n    SOCKS5Address address;\n    std::string payload;\n    int parse(const std::string &data);\n    static std::string generate(const std::string &password, const std::string &domainname, uint16_t port, bool tcp);\n};\n\n#endif // _TROJANREQUEST_H_\n"
  },
  {
    "path": "src/proto/udppacket.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"udppacket.h\"\nusing namespace std;\nusing namespace boost::asio::ip;\n\nbool UDPPacket::parse(const string &data, size_t &udp_packet_len) {\n    if (data.length() <= 0) {\n        return false;\n    }\n    size_t address_len;\n    bool is_addr_valid = address.parse(data, address_len);\n    if (!is_addr_valid || data.length() < address_len + 2) {\n        return false;\n    }\n    length = (uint8_t(data[address_len]) << 8) | uint8_t(data[address_len + 1]);\n    if (data.length() < address_len + 4 + length || data.substr(address_len + 2, 2) != \"\\r\\n\") {\n        return false;\n    }\n    payload = data.substr(address_len + 4, length);\n    udp_packet_len = address_len + 4 + length;\n    return true;\n}\n\nstring UDPPacket::generate(const udp::endpoint &endpoint, const string &payload) {\n    string ret = SOCKS5Address::generate(endpoint);\n    ret += char(uint8_t(payload.length() >> 8));\n    ret += char(uint8_t(payload.length() & 0xFF));\n    ret += \"\\r\\n\";\n    ret += payload;\n    return ret;\n}\n\nstring UDPPacket::generate(const string &domainname, uint16_t port, const string &payload) {\n    string ret = \"\\x03\";\n    ret += char(uint8_t(domainname.length()));\n    ret += domainname;\n    ret += char(uint8_t(port >> 8));\n    ret += char(uint8_t(port & 0xFF));\n    ret += char(uint8_t(payload.length() >> 8));\n    ret += char(uint8_t(payload.length() & 0xFF));\n    ret += \"\\r\\n\";\n    ret += payload;\n    return ret;\n}\n"
  },
  {
    "path": "src/proto/udppacket.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _UDPPACKET_H_\n#define _UDPPACKET_H_\n\n#include \"socks5address.h\"\n\nclass UDPPacket {\npublic:\n    SOCKS5Address address;\n    uint16_t length;\n    std::string payload;\n    bool parse(const std::string &data, size_t &udp_packet_len);\n    static std::string generate(const boost::asio::ip::udp::endpoint &endpoint, const std::string &payload);\n    static std::string generate(const std::string &domainname, uint16_t port, const std::string &payload);\n};\n\n#endif // _UDPPACKET_H_\n"
  },
  {
    "path": "src/session/clientsession.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"clientsession.h\"\n#include \"proto/trojanrequest.h\"\n#include \"proto/udppacket.h\"\n#include \"ssl/sslsession.h\"\nusing namespace std;\nusing namespace boost::asio::ip;\nusing namespace boost::asio::ssl;\n\nClientSession::ClientSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context) :\n    Session(config, io_context),\n    status(HANDSHAKE),\n    first_packet_recv(false),\n    in_socket(io_context),\n    out_socket(io_context, ssl_context) {}\n\ntcp::socket& ClientSession::accept_socket() {\n    return in_socket;\n}\n\nvoid ClientSession::start() {\n    boost::system::error_code ec;\n    start_time = time(nullptr);\n    in_endpoint = in_socket.remote_endpoint(ec);\n    if (ec) {\n        destroy();\n        return;\n    }\n    auto ssl = out_socket.native_handle();\n    if (!config.ssl.sni.empty()) {\n        SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str());\n    }\n    if (config.ssl.reuse_session) {\n        SSL_SESSION *session = SSLSession::get_session();\n        if (session) {\n            SSL_set_session(ssl, session);\n        }\n    }\n    in_async_read();\n}\n\nvoid ClientSession::in_async_read() {\n    auto self = shared_from_this();\n    in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) {\n        if (error == boost::asio::error::operation_aborted) {\n            return;\n        }\n        if (error) {\n            destroy();\n            return;\n        }\n        in_recv(string((const char*)in_read_buf, length));\n    });\n}\n\nvoid ClientSession::in_async_write(const string &data) {\n    auto self = shared_from_this();\n    auto data_copy = make_shared<string>(data);\n    boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) {\n        if (error) {\n            destroy();\n            return;\n        }\n        in_sent();\n    });\n}\n\nvoid ClientSession::out_async_read() {\n    auto self = shared_from_this();\n    out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) {\n        if (error) {\n            destroy();\n            return;\n        }\n        out_recv(string((const char*)out_read_buf, length));\n    });\n}\n\nvoid ClientSession::out_async_write(const string &data) {\n    auto self = shared_from_this();\n    auto data_copy = make_shared<string>(data);\n    boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) {\n        if (error) {\n            destroy();\n            return;\n        }\n        out_sent();\n    });\n}\n\nvoid ClientSession::udp_async_read() {\n    auto self = shared_from_this();\n    udp_socket.async_receive_from(boost::asio::buffer(udp_read_buf, MAX_LENGTH), udp_recv_endpoint, [this, self](const boost::system::error_code error, size_t length) {\n        if (error == boost::asio::error::operation_aborted) {\n            return;\n        }\n        if (error) {\n            destroy();\n            return;\n        }\n        udp_recv(string((const char*)udp_read_buf, length), udp_recv_endpoint);\n    });\n}\n\nvoid ClientSession::udp_async_write(const string &data, const udp::endpoint &endpoint) {\n    auto self = shared_from_this();\n    auto data_copy = make_shared<string>(data);\n    udp_socket.async_send_to(boost::asio::buffer(*data_copy), endpoint, [this, self, data_copy](const boost::system::error_code error, size_t) {\n        if (error) {\n            destroy();\n            return;\n        }\n        udp_sent();\n    });\n}\n\nvoid ClientSession::in_recv(const string &data) {\n    switch (status) {\n        case HANDSHAKE: {\n            if (data.length() < 2 || data[0] != 5 || data.length() != (unsigned int)(unsigned char)data[1] + 2) {\n                Log::log_with_endpoint(in_endpoint, \"unknown protocol\", Log::ERROR);\n                destroy();\n                return;\n            }\n            bool has_method = false;\n            for (int i = 2; i < data[1] + 2; ++i) {\n                if (data[i] == 0) {\n                    has_method = true;\n                    break;\n                }\n            }\n            if (!has_method) {\n                Log::log_with_endpoint(in_endpoint, \"unsupported auth method\", Log::ERROR);\n                in_async_write(string(\"\\x05\\xff\", 2));\n                status = INVALID;\n                return;\n            }\n            in_async_write(string(\"\\x05\\x00\", 2));\n            break;\n        }\n        case REQUEST: {\n            if (data.length() < 7 || data[0] != 5 || data[2] != 0) {\n                Log::log_with_endpoint(in_endpoint, \"bad request\", Log::ERROR);\n                destroy();\n                return;\n            }\n            out_write_buf = config.password.cbegin()->first + \"\\r\\n\" + data[1] + data.substr(3) + \"\\r\\n\";\n            TrojanRequest req;\n            if (req.parse(out_write_buf) == -1) {\n                Log::log_with_endpoint(in_endpoint, \"unsupported command\", Log::ERROR);\n                in_async_write(string(\"\\x05\\x07\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\", 10));\n                status = INVALID;\n                return;\n            }\n            is_udp = req.command == TrojanRequest::UDP_ASSOCIATE;\n            if (is_udp) {\n                udp::endpoint bindpoint(in_socket.local_endpoint().address(), 0);\n                boost::system::error_code ec;\n                udp_socket.open(bindpoint.protocol(), ec);\n                if (ec) {\n                    destroy();\n                    return;\n                }\n                udp_socket.bind(bindpoint);\n                Log::log_with_endpoint(in_endpoint, \"requested UDP associate to \" + req.address.address + ':' + to_string(req.address.port) + \", open UDP socket \" + udp_socket.local_endpoint().address().to_string() + ':' + to_string(udp_socket.local_endpoint().port()) + \" for relay\", Log::INFO);\n                in_async_write(string(\"\\x05\\x00\\x00\", 3) + SOCKS5Address::generate(udp_socket.local_endpoint()));\n            } else {\n                Log::log_with_endpoint(in_endpoint, \"requested connection to \" + req.address.address + ':' + to_string(req.address.port), Log::INFO);\n                in_async_write(string(\"\\x05\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\x00\\x00\", 10));\n            }\n            break;\n        }\n        case CONNECT: {\n            sent_len += data.length();\n            first_packet_recv = true;\n            out_write_buf += data;\n            break;\n        }\n        case FORWARD: {\n            sent_len += data.length();\n            out_async_write(data);\n            break;\n        }\n        case UDP_FORWARD: {\n            Log::log_with_endpoint(in_endpoint, \"unexpected data from TCP port\", Log::ERROR);\n            destroy();\n            break;\n        }\n        default: break;\n    }\n}\n\nvoid ClientSession::in_sent() {\n    switch (status) {\n        case HANDSHAKE: {\n            status = REQUEST;\n            in_async_read();\n            break;\n        }\n        case REQUEST: {\n            status = CONNECT;\n            in_async_read();\n            if (is_udp) {\n                udp_async_read();\n            }\n            auto self = shared_from_this();\n            resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, const tcp::resolver::results_type& results) {\n                if (error || results.empty()) {\n                    Log::log_with_endpoint(in_endpoint, \"cannot resolve remote server hostname \" + config.remote_addr + \": \" + error.message(), Log::ERROR);\n                    destroy();\n                    return;\n                }\n                auto iterator = results.begin();\n                Log::log_with_endpoint(in_endpoint, config.remote_addr + \" is resolved to \" + iterator->endpoint().address().to_string(), Log::ALL);\n                boost::system::error_code ec;\n                out_socket.next_layer().open(iterator->endpoint().protocol(), ec);\n                if (ec) {\n                    destroy();\n                    return;\n                }\n                if (config.tcp.no_delay) {\n                    out_socket.next_layer().set_option(tcp::no_delay(true));\n                }\n                if (config.tcp.keep_alive) {\n                    out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true));\n                }\n#ifdef TCP_FASTOPEN_CONNECT\n                if (config.tcp.fast_open) {\n                    using fastopen_connect = boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>;\n                    boost::system::error_code ec;\n                    out_socket.next_layer().set_option(fastopen_connect(true), ec);\n                }\n#endif // TCP_FASTOPEN_CONNECT\n                out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) {\n                    if (error) {\n                        Log::log_with_endpoint(in_endpoint, \"cannot establish connection to remote server \" + config.remote_addr + ':' + to_string(config.remote_port) + \": \" + error.message(), Log::ERROR);\n                        destroy();\n                        return;\n                    }\n                    out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) {\n                        if (error) {\n                            Log::log_with_endpoint(in_endpoint, \"SSL handshake failed with \" + config.remote_addr + ':' + to_string(config.remote_port) + \": \" + error.message(), Log::ERROR);\n                            destroy();\n                            return;\n                        }\n                        Log::log_with_endpoint(in_endpoint, \"tunnel established\");\n                        if (config.ssl.reuse_session) {\n                            auto ssl = out_socket.native_handle();\n                            if (!SSL_session_reused(ssl)) {\n                                Log::log_with_endpoint(in_endpoint, \"SSL session not reused\");\n                            } else {\n                                Log::log_with_endpoint(in_endpoint, \"SSL session reused\");\n                            }\n                        }\n                        boost::system::error_code ec;\n                        if (is_udp) {\n                            if (!first_packet_recv) {\n                                udp_socket.cancel(ec);\n                            }\n                            status = UDP_FORWARD;\n                        } else {\n                            if (!first_packet_recv) {\n                                in_socket.cancel(ec);\n                            }\n                            status = FORWARD;\n                        }\n                        out_async_read();\n                        out_async_write(out_write_buf);\n                    });\n                });\n            });\n            break;\n        }\n        case FORWARD: {\n            out_async_read();\n            break;\n        }\n        case INVALID: {\n            destroy();\n            break;\n        }\n        default: break;\n    }\n}\n\nvoid ClientSession::out_recv(const string &data) {\n    if (status == FORWARD) {\n        recv_len += data.length();\n        in_async_write(data);\n    } else if (status == UDP_FORWARD) {\n        udp_data_buf += data;\n        udp_sent();\n    }\n}\n\nvoid ClientSession::out_sent() {\n    if (status == FORWARD) {\n        in_async_read();\n    } else if (status == UDP_FORWARD) {\n        udp_async_read();\n    }\n}\n\nvoid ClientSession::udp_recv(const string &data, const udp::endpoint&) {\n    if (data.length() == 0) {\n        return;\n    }\n    if (data.length() < 3 || data[0] || data[1] || data[2]) {\n        Log::log_with_endpoint(in_endpoint, \"bad UDP packet\", Log::ERROR);\n        destroy();\n        return;\n    }\n    SOCKS5Address address;\n    size_t address_len;\n    bool is_addr_valid = address.parse(data.substr(3), address_len);\n    if (!is_addr_valid) {\n        Log::log_with_endpoint(in_endpoint, \"bad UDP packet\", Log::ERROR);\n        destroy();\n        return;\n    }\n    size_t length = data.length() - 3 - address_len;\n    Log::log_with_endpoint(in_endpoint, \"sent a UDP packet of length \" + to_string(length) + \" bytes to \" + address.address + ':' + to_string(address.port));\n    string packet = data.substr(3, address_len) + char(uint8_t(length >> 8)) + char(uint8_t(length & 0xFF)) + \"\\r\\n\" + data.substr(address_len + 3);\n    sent_len += length;\n    if (status == CONNECT) {\n        first_packet_recv = true;\n        out_write_buf += packet;\n    } else if (status == UDP_FORWARD) {\n        out_async_write(packet);\n    }\n}\n\nvoid ClientSession::udp_sent() {\n    if (status == UDP_FORWARD) {\n        UDPPacket packet;\n        size_t packet_len;\n        bool is_packet_valid = packet.parse(udp_data_buf, packet_len);\n        if (!is_packet_valid) {\n            if (udp_data_buf.length() > MAX_LENGTH) {\n                Log::log_with_endpoint(in_endpoint, \"UDP packet too long\", Log::ERROR);\n                destroy();\n                return;\n            }\n            out_async_read();\n            return;\n        }\n        Log::log_with_endpoint(in_endpoint, \"received a UDP packet of length \" + to_string(packet.length) + \" bytes from \" + packet.address.address + ':' + to_string(packet.address.port));\n        SOCKS5Address address;\n        size_t address_len;\n        bool is_addr_valid = address.parse(udp_data_buf, address_len);\n        if (!is_addr_valid) {\n            Log::log_with_endpoint(in_endpoint, \"udp_sent: invalid UDP packet address\", Log::ERROR);\n            destroy();\n            return;\n        }\n        string reply = string(\"\\x00\\x00\\x00\", 3) + udp_data_buf.substr(0, address_len) + packet.payload;\n        udp_data_buf = udp_data_buf.substr(packet_len);\n        recv_len += packet.length;\n        udp_async_write(reply, udp_recv_endpoint);\n    }\n}\n\nvoid ClientSession::destroy() {\n    if (status == DESTROY) {\n        return;\n    }\n    status = DESTROY;\n    Log::log_with_endpoint(in_endpoint, \"disconnected, \" + to_string(recv_len) + \" bytes received, \" + to_string(sent_len) + \" bytes sent, lasted for \" + to_string(time(nullptr) - start_time) + \" seconds\", Log::INFO);\n    boost::system::error_code ec;\n    resolver.cancel();\n    if (in_socket.is_open()) {\n        in_socket.cancel(ec);\n        in_socket.shutdown(tcp::socket::shutdown_both, ec);\n        in_socket.close(ec);\n    }\n    if (udp_socket.is_open()) {\n        udp_socket.cancel(ec);\n        udp_socket.close(ec);\n    }\n    if (out_socket.next_layer().is_open()) {\n        auto self = shared_from_this();\n        auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) {\n            if (error == boost::asio::error::operation_aborted) {\n                return;\n            }\n            boost::system::error_code ec;\n            ssl_shutdown_timer.cancel();\n            out_socket.next_layer().cancel(ec);\n            out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec);\n            out_socket.next_layer().close(ec);\n        };\n        out_socket.next_layer().cancel(ec);\n        out_socket.async_shutdown(ssl_shutdown_cb);\n        ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT));\n        ssl_shutdown_timer.async_wait(ssl_shutdown_cb);\n    }\n}\n"
  },
  {
    "path": "src/session/clientsession.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _CLIENTSESSION_H_\n#define _CLIENTSESSION_H_\n\n#include \"session.h\"\n#include <boost/asio/ssl.hpp>\n\nclass ClientSession : public Session {\nprivate:\n    enum Status {\n        HANDSHAKE,\n        REQUEST,\n        CONNECT,\n        FORWARD,\n        UDP_FORWARD,\n        INVALID,\n        DESTROY\n    } status;\n    bool is_udp{};\n    bool first_packet_recv;\n    boost::asio::ip::tcp::socket in_socket;\n    boost::asio::ssl::stream<boost::asio::ip::tcp::socket>out_socket;\n    void destroy();\n    void in_async_read();\n    void in_async_write(const std::string &data);\n    void in_recv(const std::string &data);\n    void in_sent();\n    void out_async_read();\n    void out_async_write(const std::string &data);\n    void out_recv(const std::string &data);\n    void out_sent();\n    void udp_async_read();\n    void udp_async_write(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint);\n    void udp_recv(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint);\n    void udp_sent();\npublic:\n    ClientSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context);\n    boost::asio::ip::tcp::socket& accept_socket() override;\n    void start() override;\n};\n\n#endif // _CLIENTSESSION_H_\n"
  },
  {
    "path": "src/session/forwardsession.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"forwardsession.h\"\n#include \"proto/trojanrequest.h\"\n#include \"ssl/sslsession.h\"\nusing namespace std;\nusing namespace boost::asio::ip;\nusing namespace boost::asio::ssl;\n\nForwardSession::ForwardSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context) :\n    Session(config, io_context),\n    status(CONNECT),\n    first_packet_recv(false),\n    in_socket(io_context),\n    out_socket(io_context, ssl_context) {}\n\ntcp::socket& ForwardSession::accept_socket() {\n    return in_socket;\n}\n\nvoid ForwardSession::start() {\n    boost::system::error_code ec;\n    start_time = time(nullptr);\n    in_endpoint = in_socket.remote_endpoint(ec);\n    if (ec) {\n        destroy();\n        return;\n    }\n    auto ssl = out_socket.native_handle();\n    if (!config.ssl.sni.empty()) {\n        SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str());\n    }\n    if (config.ssl.reuse_session) {\n        SSL_SESSION *session = SSLSession::get_session();\n        if (session) {\n            SSL_set_session(ssl, session);\n        }\n    }\n    out_write_buf = TrojanRequest::generate(config.password.cbegin()->first, config.target_addr, config.target_port, true);\n    in_async_read();\n    Log::log_with_endpoint(in_endpoint, \"forwarding to \" + config.target_addr + ':' + to_string(config.target_port) + \" via \" + config.remote_addr + ':' + to_string(config.remote_port), Log::INFO);\n    auto self = shared_from_this();\n    resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, const tcp::resolver::results_type& results) {\n        if (error || results.empty()) {\n            Log::log_with_endpoint(in_endpoint, \"cannot resolve remote server hostname \" + config.remote_addr + \": \" + error.message(), Log::ERROR);\n            destroy();\n            return;\n        }\n        auto iterator = results.begin();\n        Log::log_with_endpoint(in_endpoint, config.remote_addr + \" is resolved to \" + iterator->endpoint().address().to_string(), Log::ALL);\n        boost::system::error_code ec;\n        out_socket.next_layer().open(iterator->endpoint().protocol(), ec);\n        if (ec) {\n            destroy();\n            return;\n        }\n        if (config.tcp.no_delay) {\n            out_socket.next_layer().set_option(tcp::no_delay(true));\n        }\n        if (config.tcp.keep_alive) {\n            out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true));\n        }\n#ifdef TCP_FASTOPEN_CONNECT\n        if (config.tcp.fast_open) {\n            using fastopen_connect = boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>;\n            boost::system::error_code ec;\n            out_socket.next_layer().set_option(fastopen_connect(true), ec);\n        }\n#endif // TCP_FASTOPEN_CONNECT\n        out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) {\n            if (error) {\n                Log::log_with_endpoint(in_endpoint, \"cannot establish connection to remote server \" + config.remote_addr + ':' + to_string(config.remote_port) + \": \" + error.message(), Log::ERROR);\n                destroy();\n                return;\n            }\n            out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) {\n                if (error) {\n                    Log::log_with_endpoint(in_endpoint, \"SSL handshake failed with \" + config.remote_addr + ':' + to_string(config.remote_port) + \": \" + error.message(), Log::ERROR);\n                    destroy();\n                    return;\n                }\n                Log::log_with_endpoint(in_endpoint, \"tunnel established\");\n                if (config.ssl.reuse_session) {\n                    auto ssl = out_socket.native_handle();\n                    if (!SSL_session_reused(ssl)) {\n                        Log::log_with_endpoint(in_endpoint, \"SSL session not reused\");\n                    } else {\n                        Log::log_with_endpoint(in_endpoint, \"SSL session reused\");\n                    }\n                }\n                boost::system::error_code ec;\n                if (!first_packet_recv) {\n                    in_socket.cancel(ec);\n                }\n                status = FORWARD;\n                out_async_read();\n                out_async_write(out_write_buf);\n            });\n        });\n    });\n}\n\nvoid ForwardSession::in_async_read() {\n    auto self = shared_from_this();\n    in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) {\n        if (error == boost::asio::error::operation_aborted) {\n            return;\n        }\n        if (error) {\n            destroy();\n            return;\n        }\n        in_recv(string((const char*)in_read_buf, length));\n    });\n}\n\nvoid ForwardSession::in_async_write(const string &data) {\n    auto self = shared_from_this();\n    auto data_copy = make_shared<string>(data);\n    boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) {\n        if (error) {\n            destroy();\n            return;\n        }\n        in_sent();\n    });\n}\n\nvoid ForwardSession::out_async_read() {\n    auto self = shared_from_this();\n    out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) {\n        if (error) {\n            destroy();\n            return;\n        }\n        out_recv(string((const char*)out_read_buf, length));\n    });\n}\n\nvoid ForwardSession::out_async_write(const string &data) {\n    auto self = shared_from_this();\n    auto data_copy = make_shared<string>(data);\n    boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) {\n        if (error) {\n            destroy();\n            return;\n        }\n        out_sent();\n    });\n}\n\nvoid ForwardSession::in_recv(const string &data) {\n    if (status == CONNECT) {\n        sent_len += data.length();\n        first_packet_recv = true;\n        out_write_buf += data;\n    } else if (status == FORWARD) {\n        sent_len += data.length();\n        out_async_write(data);\n    }\n}\n\nvoid ForwardSession::in_sent() {\n    if (status == FORWARD) {\n        out_async_read();\n    }\n}\n\nvoid ForwardSession::out_recv(const string &data) {\n    if (status == FORWARD) {\n        recv_len += data.length();\n        in_async_write(data);\n    }\n}\n\nvoid ForwardSession::out_sent() {\n    if (status == FORWARD) {\n        in_async_read();\n    }\n}\n\nvoid ForwardSession::destroy() {\n    if (status == DESTROY) {\n        return;\n    }\n    status = DESTROY;\n    Log::log_with_endpoint(in_endpoint, \"disconnected, \" + to_string(recv_len) + \" bytes received, \" + to_string(sent_len) + \" bytes sent, lasted for \" + to_string(time(nullptr) - start_time) + \" seconds\", Log::INFO);\n    boost::system::error_code ec;\n    resolver.cancel();\n    if (in_socket.is_open()) {\n        in_socket.cancel(ec);\n        in_socket.shutdown(tcp::socket::shutdown_both, ec);\n        in_socket.close(ec);\n    }\n    if (out_socket.next_layer().is_open()) {\n        auto self = shared_from_this();\n        auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) {\n            if (error == boost::asio::error::operation_aborted) {\n                return;\n            }\n            boost::system::error_code ec;\n            ssl_shutdown_timer.cancel();\n            out_socket.next_layer().cancel(ec);\n            out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec);\n            out_socket.next_layer().close(ec);\n        };\n        out_socket.next_layer().cancel(ec);\n        out_socket.async_shutdown(ssl_shutdown_cb);\n        ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT));\n        ssl_shutdown_timer.async_wait(ssl_shutdown_cb);\n    }\n}\n"
  },
  {
    "path": "src/session/forwardsession.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _FORWARDSESSION_H_\n#define _FORWARDSESSION_H_\n\n#include \"session.h\"\n#include <boost/asio/ssl.hpp>\n\nclass ForwardSession : public Session {\nprivate:\n    enum Status {\n        CONNECT,\n        FORWARD,\n        DESTROY\n    } status;\n    bool first_packet_recv;\n    boost::asio::ip::tcp::socket in_socket;\n    boost::asio::ssl::stream<boost::asio::ip::tcp::socket>out_socket;\n    void destroy();\n    void in_async_read();\n    void in_async_write(const std::string &data);\n    void in_recv(const std::string &data);\n    void in_sent();\n    void out_async_read();\n    void out_async_write(const std::string &data);\n    void out_recv(const std::string &data);\n    void out_sent();\npublic:\n    ForwardSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context);\n    boost::asio::ip::tcp::socket& accept_socket() override;\n    void start() override;\n};\n\n#endif // _FORWARDSESSION_H_\n"
  },
  {
    "path": "src/session/natsession.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"natsession.h\"\n#include \"proto/trojanrequest.h\"\n#include \"ssl/sslsession.h\"\nusing namespace std;\nusing namespace boost::asio::ip;\nusing namespace boost::asio::ssl;\n\n// These 2 definitions are respectively from linux/netfilter_ipv4.h and\n// linux/netfilter_ipv6/ip6_tables.h. Including them will 1) cause linux-headers\n// to be one of trojan's dependencies, which is not good, and 2) prevent trojan\n// from even compiling.\n#ifndef SO_ORIGINAL_DST\n#define SO_ORIGINAL_DST 80\n#endif // SO_ORIGINAL_DST\n#ifndef IP6T_SO_ORIGINAL_DST\n#define IP6T_SO_ORIGINAL_DST 80\n#endif // IP6T_SO_ORIGINAL_DST\n\nNATSession::NATSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context) :\n    Session(config, io_context),\n    status(CONNECT),\n    first_packet_recv(false),\n    in_socket(io_context),\n    out_socket(io_context, ssl_context) {}\n\ntcp::socket& NATSession::accept_socket() {\n    return in_socket;\n}\n\npair<string, uint16_t> NATSession::get_target_endpoint() {\n#ifdef ENABLE_NAT\n    int fd = in_socket.native_handle();\n    // Taken from https://github.com/shadowsocks/shadowsocks-libev/blob/v3.3.1/src/redir.c.\n    sockaddr_storage destaddr;\n    memset(&destaddr, 0, sizeof(sockaddr_storage));\n    socklen_t socklen = sizeof(destaddr);\n    int error = getsockopt(fd, SOL_IPV6, IP6T_SO_ORIGINAL_DST, &destaddr, &socklen);\n    if (error) {\n        error = getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, &destaddr, &socklen);\n        if (error) {\n            return make_pair(\"\", 0);\n        }\n    }\n    char ipstr[INET6_ADDRSTRLEN];\n    uint16_t port;\n    if (destaddr.ss_family == AF_INET) {\n        auto *sa = (sockaddr_in*) &destaddr;\n        inet_ntop(AF_INET, &(sa->sin_addr), ipstr, INET_ADDRSTRLEN);\n        port = ntohs(sa->sin_port);\n    } else {\n        auto *sa = (sockaddr_in6*) &destaddr;\n        inet_ntop(AF_INET6, &(sa->sin6_addr), ipstr, INET6_ADDRSTRLEN);\n        port = ntohs(sa->sin6_port);\n    }\n    return make_pair(ipstr, port);\n#else // ENABLE_NAT\n    return make_pair(\"\", 0);\n#endif // ENABLE_NAT\n}\n\nvoid NATSession::start() {\n    boost::system::error_code ec;\n    start_time = time(nullptr);\n    in_endpoint = in_socket.remote_endpoint(ec);\n    if (ec) {\n        destroy();\n        return;\n    }\n    auto ssl = out_socket.native_handle();\n    if (!config.ssl.sni.empty()) {\n        SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str());\n    }\n    if (config.ssl.reuse_session) {\n        SSL_SESSION *session = SSLSession::get_session();\n        if (session) {\n            SSL_set_session(ssl, session);\n        }\n    }\n    auto target_endpoint = get_target_endpoint();\n    string &target_addr = target_endpoint.first;\n    uint16_t target_port = target_endpoint.second;\n    if (target_port == 0) {\n        destroy();\n        return;\n    }\n    out_write_buf = TrojanRequest::generate(config.password.cbegin()->first, target_addr, target_port, true);\n    in_async_read();\n    Log::log_with_endpoint(in_endpoint, \"forwarding to \" + target_addr + ':' + to_string(target_port) + \" via \" + config.remote_addr + ':' + to_string(config.remote_port), Log::INFO);\n    auto self = shared_from_this();\n    resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, const tcp::resolver::results_type& results) {\n        if (error || results.empty()) {\n            Log::log_with_endpoint(in_endpoint, \"cannot resolve remote server hostname \" + config.remote_addr + \": \" + error.message(), Log::ERROR);\n            destroy();\n            return;\n        }\n        auto iterator = results.begin();\n        Log::log_with_endpoint(in_endpoint, config.remote_addr + \" is resolved to \" + iterator->endpoint().address().to_string(), Log::ALL);\n        boost::system::error_code ec;\n        out_socket.next_layer().open(iterator->endpoint().protocol(), ec);\n        if (ec) {\n            destroy();\n            return;\n        }\n        if (config.tcp.no_delay) {\n            out_socket.next_layer().set_option(tcp::no_delay(true));\n        }\n        if (config.tcp.keep_alive) {\n            out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true));\n        }\n#ifdef TCP_FASTOPEN_CONNECT\n        if (config.tcp.fast_open) {\n            using fastopen_connect = boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>;\n            boost::system::error_code ec;\n            out_socket.next_layer().set_option(fastopen_connect(true), ec);\n        }\n#endif // TCP_FASTOPEN_CONNECT\n        out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) {\n            if (error) {\n                Log::log_with_endpoint(in_endpoint, \"cannot establish connection to remote server \" + config.remote_addr + ':' + to_string(config.remote_port) + \": \" + error.message(), Log::ERROR);\n                destroy();\n                return;\n            }\n            out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) {\n                if (error) {\n                    Log::log_with_endpoint(in_endpoint, \"SSL handshake failed with \" + config.remote_addr + ':' + to_string(config.remote_port) + \": \" + error.message(), Log::ERROR);\n                    destroy();\n                    return;\n                }\n                Log::log_with_endpoint(in_endpoint, \"tunnel established\");\n                if (config.ssl.reuse_session) {\n                    auto ssl = out_socket.native_handle();\n                    if (!SSL_session_reused(ssl)) {\n                        Log::log_with_endpoint(in_endpoint, \"SSL session not reused\");\n                    } else {\n                        Log::log_with_endpoint(in_endpoint, \"SSL session reused\");\n                    }\n                }\n                boost::system::error_code ec;\n                if (!first_packet_recv) {\n                    in_socket.cancel(ec);\n                }\n                status = FORWARD;\n                out_async_read();\n                out_async_write(out_write_buf);\n            });\n        });\n    });\n}\n\nvoid NATSession::in_async_read() {\n    auto self = shared_from_this();\n    in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) {\n        if (error == boost::asio::error::operation_aborted) {\n            return;\n        }\n        if (error) {\n            destroy();\n            return;\n        }\n        in_recv(string((const char*)in_read_buf, length));\n    });\n}\n\nvoid NATSession::in_async_write(const string &data) {\n    auto self = shared_from_this();\n    auto data_copy = make_shared<string>(data);\n    boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) {\n        if (error) {\n            destroy();\n            return;\n        }\n        in_sent();\n    });\n}\n\nvoid NATSession::out_async_read() {\n    auto self = shared_from_this();\n    out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) {\n        if (error) {\n            destroy();\n            return;\n        }\n        out_recv(string((const char*)out_read_buf, length));\n    });\n}\n\nvoid NATSession::out_async_write(const string &data) {\n    auto self = shared_from_this();\n    auto data_copy = make_shared<string>(data);\n    boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) {\n        if (error) {\n            destroy();\n            return;\n        }\n        out_sent();\n    });\n}\n\nvoid NATSession::in_recv(const string &data) {\n    if (status == CONNECT) {\n        sent_len += data.length();\n        first_packet_recv = true;\n        out_write_buf += data;\n    } else if (status == FORWARD) {\n        sent_len += data.length();\n        out_async_write(data);\n    }\n}\n\nvoid NATSession::in_sent() {\n    if (status == FORWARD) {\n        out_async_read();\n    }\n}\n\nvoid NATSession::out_recv(const string &data) {\n    if (status == FORWARD) {\n        recv_len += data.length();\n        in_async_write(data);\n    }\n}\n\nvoid NATSession::out_sent() {\n    if (status == FORWARD) {\n        in_async_read();\n    }\n}\n\nvoid NATSession::destroy() {\n    if (status == DESTROY) {\n        return;\n    }\n    status = DESTROY;\n    Log::log_with_endpoint(in_endpoint, \"disconnected, \" + to_string(recv_len) + \" bytes received, \" + to_string(sent_len) + \" bytes sent, lasted for \" + to_string(time(nullptr) - start_time) + \" seconds\", Log::INFO);\n    boost::system::error_code ec;\n    resolver.cancel();\n    if (in_socket.is_open()) {\n        in_socket.cancel(ec);\n        in_socket.shutdown(tcp::socket::shutdown_both, ec);\n        in_socket.close(ec);\n    }\n    if (out_socket.next_layer().is_open()) {\n        auto self = shared_from_this();\n        auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) {\n            if (error == boost::asio::error::operation_aborted) {\n                return;\n            }\n            boost::system::error_code ec;\n            ssl_shutdown_timer.cancel();\n            out_socket.next_layer().cancel(ec);\n            out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec);\n            out_socket.next_layer().close(ec);\n        };\n        out_socket.next_layer().cancel(ec);\n        out_socket.async_shutdown(ssl_shutdown_cb);\n        ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT));\n        ssl_shutdown_timer.async_wait(ssl_shutdown_cb);\n    }\n}\n"
  },
  {
    "path": "src/session/natsession.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _NATSESSION_H_\n#define _NATSESSION_H_\n\n#include \"session.h\"\n#include <boost/asio/ssl.hpp>\n\nclass NATSession : public Session {\nprivate:\n    enum Status {\n        CONNECT,\n        FORWARD,\n        DESTROY\n    } status;\n    bool first_packet_recv;\n    boost::asio::ip::tcp::socket in_socket;\n    boost::asio::ssl::stream<boost::asio::ip::tcp::socket>out_socket;\n    void destroy();\n    void in_async_read();\n    void in_async_write(const std::string &data);\n    void in_recv(const std::string &data);\n    void in_sent();\n    void out_async_read();\n    void out_async_write(const std::string &data);\n    void out_recv(const std::string &data);\n    void out_sent();\n    std::pair<std::string, uint16_t> get_target_endpoint();\npublic:\n    NATSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context);\n    boost::asio::ip::tcp::socket& accept_socket() override;\n    void start() override;\n};\n\n#endif // _NATSESSION_H_\n"
  },
  {
    "path": "src/session/serversession.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"serversession.h\"\n#include \"proto/trojanrequest.h\"\n#include \"proto/udppacket.h\"\nusing namespace std;\nusing namespace boost::asio::ip;\nusing namespace boost::asio::ssl;\n\nServerSession::ServerSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context, Authenticator *auth, const string &plain_http_response) :\n    Session(config, io_context),\n    status(HANDSHAKE),\n    in_socket(io_context, ssl_context),\n    out_socket(io_context),\n    udp_resolver(io_context),\n    auth(auth),\n    plain_http_response(plain_http_response) {}\n\ntcp::socket& ServerSession::accept_socket() {\n    return (tcp::socket&)in_socket.next_layer();\n}\n\nvoid ServerSession::start() {\n    boost::system::error_code ec;\n    start_time = time(nullptr);\n    in_endpoint = in_socket.next_layer().remote_endpoint(ec);\n    if (ec) {\n        destroy();\n        return;\n    }\n    auto self = shared_from_this();\n    in_socket.async_handshake(stream_base::server, [this, self](const boost::system::error_code error) {\n        if (error) {\n            Log::log_with_endpoint(in_endpoint, \"SSL handshake failed: \" + error.message(), Log::ERROR);\n            if (error.message() == \"http request\" && !plain_http_response.empty()) {\n                recv_len += plain_http_response.length();\n                boost::asio::async_write(accept_socket(), boost::asio::buffer(plain_http_response), [this, self](const boost::system::error_code, size_t) {\n                    destroy();\n                });\n                return;\n            }\n            destroy();\n            return;\n        }\n        in_async_read();\n    });\n}\n\nvoid ServerSession::in_async_read() {\n    auto self = shared_from_this();\n    in_socket.async_read_some(boost::asio::buffer(in_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) {\n        if (error) {\n            destroy();\n            return;\n        }\n        in_recv(string((const char*)in_read_buf, length));\n    });\n}\n\nvoid ServerSession::in_async_write(const string &data) {\n    auto self = shared_from_this();\n    auto data_copy = make_shared<string>(data);\n    boost::asio::async_write(in_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) {\n        if (error) {\n            destroy();\n            return;\n        }\n        in_sent();\n    });\n}\n\nvoid ServerSession::out_async_read() {\n    auto self = shared_from_this();\n    out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) {\n        if (error) {\n            destroy();\n            return;\n        }\n        out_recv(string((const char*)out_read_buf, length));\n    });\n}\n\nvoid ServerSession::out_async_write(const string &data) {\n    auto self = shared_from_this();\n    auto data_copy = make_shared<string>(data);\n    boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) {\n        if (error) {\n            destroy();\n            return;\n        }\n        out_sent();\n    });\n}\n\nvoid ServerSession::udp_async_read() {\n    auto self = shared_from_this();\n    udp_socket.async_receive_from(boost::asio::buffer(udp_read_buf, MAX_LENGTH), udp_recv_endpoint, [this, self](const boost::system::error_code error, size_t length) {\n        if (error) {\n            destroy();\n            return;\n        }\n        udp_recv(string((const char*)udp_read_buf, length), udp_recv_endpoint);\n    });\n}\n\nvoid ServerSession::udp_async_write(const string &data, const udp::endpoint &endpoint) {\n    auto self = shared_from_this();\n    auto data_copy = make_shared<string>(data);\n    udp_socket.async_send_to(boost::asio::buffer(*data_copy), endpoint, [this, self, data_copy](const boost::system::error_code error, size_t) {\n        if (error) {\n            destroy();\n            return;\n        }\n        udp_sent();\n    });\n}\n\nvoid ServerSession::in_recv(const string &data) {\n    if (status == HANDSHAKE) {\n        TrojanRequest req;\n        bool valid = req.parse(data) != -1;\n        if (valid) {\n            auto password_iterator = config.password.find(req.password);\n            if (password_iterator == config.password.end()) {\n                valid = false;\n                if (auth && auth->auth(req.password)) {\n                    valid = true;\n                    auth_password = req.password;\n                    Log::log_with_endpoint(in_endpoint, \"authenticated by authenticator (\" + req.password.substr(0, 7) + ')', Log::INFO);\n                }\n            } else {\n                Log::log_with_endpoint(in_endpoint, \"authenticated as \" + password_iterator->second, Log::INFO);\n            }\n            if (!valid) {\n                Log::log_with_endpoint(in_endpoint, \"valid trojan request structure but possibly incorrect password (\" + req.password + ')', Log::WARN);\n            }\n        }\n        string query_addr = valid ? req.address.address : config.remote_addr;\n        string query_port = to_string([&]() {\n            if (valid) {\n                return req.address.port;\n            }\n            const unsigned char *alpn_out;\n            unsigned int alpn_len;\n            SSL_get0_alpn_selected(in_socket.native_handle(), &alpn_out, &alpn_len);\n            if (alpn_out == nullptr) {\n                return config.remote_port;\n            }\n            auto it = config.ssl.alpn_port_override.find(string(alpn_out, alpn_out + alpn_len));\n            return it == config.ssl.alpn_port_override.end() ? config.remote_port : it->second;\n        }());\n        if (valid) {\n            out_write_buf = req.payload;\n            if (req.command == TrojanRequest::UDP_ASSOCIATE) {\n                Log::log_with_endpoint(in_endpoint, \"requested UDP associate to \" + req.address.address + ':' + to_string(req.address.port), Log::INFO);\n                status = UDP_FORWARD;\n                udp_data_buf = out_write_buf;\n                udp_sent();\n                return;\n            } else {\n                Log::log_with_endpoint(in_endpoint, \"requested connection to \" + req.address.address + ':' + to_string(req.address.port), Log::INFO);\n            }\n        } else {\n            Log::log_with_endpoint(in_endpoint, \"not trojan request, connecting to \" + query_addr + ':' + query_port, Log::WARN);\n            out_write_buf = data;\n        }\n        sent_len += out_write_buf.length();\n        auto self = shared_from_this();\n        resolver.async_resolve(query_addr, query_port, [this, self, query_addr, query_port](const boost::system::error_code error, const tcp::resolver::results_type& results) {\n            if (error || results.empty()) {\n                Log::log_with_endpoint(in_endpoint, \"cannot resolve remote server hostname \" + query_addr + \": \" + error.message(), Log::ERROR);\n                destroy();\n                return;\n            }\n            auto iterator = results.begin();\n            if (config.tcp.prefer_ipv4) {\n                for (auto it = results.begin(); it != results.end(); ++it) {\n                    const auto &addr = it->endpoint().address();\n                    if (addr.is_v4()) {\n                        iterator = it;\n                        break;\n                    }\n                }\n            }\n            Log::log_with_endpoint(in_endpoint, query_addr + \" is resolved to \" + iterator->endpoint().address().to_string(), Log::ALL);\n            boost::system::error_code ec;\n            out_socket.open(iterator->endpoint().protocol(), ec);\n            if (ec) {\n                destroy();\n                return;\n            }\n            if (config.tcp.no_delay) {\n                out_socket.set_option(tcp::no_delay(true));\n            }\n            if (config.tcp.keep_alive) {\n                out_socket.set_option(boost::asio::socket_base::keep_alive(true));\n            }\n#ifdef TCP_FASTOPEN_CONNECT\n            if (config.tcp.fast_open) {\n                using fastopen_connect = boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>;\n                boost::system::error_code ec;\n                out_socket.set_option(fastopen_connect(true), ec);\n            }\n#endif // TCP_FASTOPEN_CONNECT\n            out_socket.async_connect(*iterator, [this, self, query_addr, query_port](const boost::system::error_code error) {\n                if (error) {\n                    Log::log_with_endpoint(in_endpoint, \"cannot establish connection to remote server \" + query_addr + ':' + query_port + \": \" + error.message(), Log::ERROR);\n                    destroy();\n                    return;\n                }\n                Log::log_with_endpoint(in_endpoint, \"tunnel established\");\n                status = FORWARD;\n                out_async_read();\n                if (!out_write_buf.empty()) {\n                    out_async_write(out_write_buf);\n                } else {\n                    in_async_read();\n                }\n            });\n        });\n    } else if (status == FORWARD) {\n        sent_len += data.length();\n        out_async_write(data);\n    } else if (status == UDP_FORWARD) {\n        udp_data_buf += data;\n        udp_sent();\n    }\n}\n\nvoid ServerSession::in_sent() {\n    if (status == FORWARD) {\n        out_async_read();\n    } else if (status == UDP_FORWARD) {\n        udp_async_read();\n    }\n}\n\nvoid ServerSession::out_recv(const string &data) {\n    if (status == FORWARD) {\n        recv_len += data.length();\n        in_async_write(data);\n    }\n}\n\nvoid ServerSession::out_sent() {\n    if (status == FORWARD) {\n        in_async_read();\n    }\n}\n\nvoid ServerSession::udp_recv(const string &data, const udp::endpoint &endpoint) {\n    if (status == UDP_FORWARD) {\n        size_t length = data.length();\n        Log::log_with_endpoint(in_endpoint, \"received a UDP packet of length \" + to_string(length) + \" bytes from \" + endpoint.address().to_string() + ':' + to_string(endpoint.port()));\n        recv_len += length;\n        in_async_write(UDPPacket::generate(endpoint, data));\n    }\n}\n\nvoid ServerSession::udp_sent() {\n    if (status == UDP_FORWARD) {\n        UDPPacket packet;\n        size_t packet_len;\n        bool is_packet_valid = packet.parse(udp_data_buf, packet_len);\n        if (!is_packet_valid) {\n            if (udp_data_buf.length() > MAX_LENGTH) {\n                Log::log_with_endpoint(in_endpoint, \"UDP packet too long\", Log::ERROR);\n                destroy();\n                return;\n            }\n            in_async_read();\n            return;\n        }\n        Log::log_with_endpoint(in_endpoint, \"sent a UDP packet of length \" + to_string(packet.length) + \" bytes to \" + packet.address.address + ':' + to_string(packet.address.port));\n        udp_data_buf = udp_data_buf.substr(packet_len);\n        string query_addr = packet.address.address;\n        auto self = shared_from_this();\n        udp_resolver.async_resolve(query_addr, to_string(packet.address.port), [this, self, packet, query_addr](const boost::system::error_code error, const udp::resolver::results_type& results) {\n            if (error || results.empty()) {\n                Log::log_with_endpoint(in_endpoint, \"cannot resolve remote server hostname \" + query_addr + \": \" + error.message(), Log::ERROR);\n                destroy();\n                return;\n            }\n            auto iterator = results.begin();\n            if (config.tcp.prefer_ipv4) {\n                for (auto it = results.begin(); it != results.end(); ++it) {\n                    const auto &addr = it->endpoint().address();\n                    if (addr.is_v4()) {\n                        iterator = it;\n                        break;\n                    }\n                }\n            }\n            Log::log_with_endpoint(in_endpoint, query_addr + \" is resolved to \" + iterator->endpoint().address().to_string(), Log::ALL);\n            if (!udp_socket.is_open()) {\n                auto protocol = iterator->endpoint().protocol();\n                boost::system::error_code ec;\n                udp_socket.open(protocol, ec);\n                if (ec) {\n                    destroy();\n                    return;\n                }\n                udp_socket.bind(udp::endpoint(protocol, 0));\n                udp_async_read();\n            }\n            sent_len += packet.length;\n            udp_async_write(packet.payload, *iterator);\n        });\n    }\n}\n\nvoid ServerSession::destroy() {\n    if (status == DESTROY) {\n        return;\n    }\n    status = DESTROY;\n    Log::log_with_endpoint(in_endpoint, \"disconnected, \" + to_string(recv_len) + \" bytes received, \" + to_string(sent_len) + \" bytes sent, lasted for \" + to_string(time(nullptr) - start_time) + \" seconds\", Log::INFO);\n    if (auth && !auth_password.empty()) {\n        auth->record(auth_password, recv_len, sent_len);\n    }\n    boost::system::error_code ec;\n    resolver.cancel();\n    udp_resolver.cancel();\n    if (out_socket.is_open()) {\n        out_socket.cancel(ec);\n        out_socket.shutdown(tcp::socket::shutdown_both, ec);\n        out_socket.close(ec);\n    }\n    if (udp_socket.is_open()) {\n        udp_socket.cancel(ec);\n        udp_socket.close(ec);\n    }\n    if (in_socket.next_layer().is_open()) {\n        auto self = shared_from_this();\n        auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) {\n            if (error == boost::asio::error::operation_aborted) {\n                return;\n            }\n            boost::system::error_code ec;\n            ssl_shutdown_timer.cancel();\n            in_socket.next_layer().cancel(ec);\n            in_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec);\n            in_socket.next_layer().close(ec);\n        };\n        in_socket.next_layer().cancel(ec);\n        in_socket.async_shutdown(ssl_shutdown_cb);\n        ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT));\n        ssl_shutdown_timer.async_wait(ssl_shutdown_cb);\n    }\n}\n"
  },
  {
    "path": "src/session/serversession.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _SERVERSESSION_H_\n#define _SERVERSESSION_H_\n\n#include \"session.h\"\n#include <boost/asio/ssl.hpp>\n#include \"core/authenticator.h\"\n\nclass ServerSession : public Session {\nprivate:\n    enum Status {\n        HANDSHAKE,\n        FORWARD,\n        UDP_FORWARD,\n        DESTROY\n    } status;\n    boost::asio::ssl::stream<boost::asio::ip::tcp::socket>in_socket;\n    boost::asio::ip::tcp::socket out_socket;\n    boost::asio::ip::udp::resolver udp_resolver;\n    Authenticator *auth;\n    std::string auth_password;\n    const std::string &plain_http_response;\n    void destroy();\n    void in_async_read();\n    void in_async_write(const std::string &data);\n    void in_recv(const std::string &data);\n    void in_sent();\n    void out_async_read();\n    void out_async_write(const std::string &data);\n    void out_recv(const std::string &data);\n    void out_sent();\n    void udp_async_read();\n    void udp_async_write(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint);\n    void udp_recv(const std::string &data, const boost::asio::ip::udp::endpoint &endpoint);\n    void udp_sent();\npublic:\n    ServerSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context, Authenticator *auth, const std::string &plain_http_response);\n    boost::asio::ip::tcp::socket& accept_socket() override;\n    void start() override;\n};\n\n#endif // _SERVERSESSION_H_\n"
  },
  {
    "path": "src/session/session.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"session.h\"\n\nSession::Session(const Config &config, boost::asio::io_context &io_context) : config(config),\n                                                                              recv_len(0),\n                                                                              sent_len(0),\n                                                                              resolver(io_context),\n                                                                              udp_socket(io_context),\n                                                                              ssl_shutdown_timer(io_context) {}\n\nSession::~Session() = default;\n"
  },
  {
    "path": "src/session/session.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _SESSION_H_\n#define _SESSION_H_\n\n#include <ctime>\n#include <memory>\n#include <boost/asio/io_context.hpp>\n#include <boost/asio/ip/udp.hpp>\n#include <boost/asio/steady_timer.hpp>\n#include \"core/config.h\"\n\nclass Session : public std::enable_shared_from_this<Session> {\nprotected:\n    enum {\n        MAX_LENGTH = 8192,\n        SSL_SHUTDOWN_TIMEOUT = 30\n    };\n    const Config &config;\n    uint8_t in_read_buf[MAX_LENGTH]{};\n    uint8_t out_read_buf[MAX_LENGTH]{};\n    uint8_t udp_read_buf[MAX_LENGTH]{};\n    uint64_t recv_len;\n    uint64_t sent_len;\n    time_t start_time{};\n    std::string out_write_buf;\n    std::string udp_data_buf;\n    boost::asio::ip::tcp::resolver resolver;\n    boost::asio::ip::tcp::endpoint in_endpoint;\n    boost::asio::ip::udp::socket udp_socket;\n    boost::asio::ip::udp::endpoint udp_recv_endpoint;\n    boost::asio::steady_timer ssl_shutdown_timer;\npublic:\n    Session(const Config &config, boost::asio::io_context &io_context);\n    virtual boost::asio::ip::tcp::socket& accept_socket() = 0;\n    virtual void start() = 0;\n    virtual ~Session();\n};\n\n#endif // _SESSION_H_\n"
  },
  {
    "path": "src/session/udpforwardsession.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"udpforwardsession.h\"\n#include <stdexcept>\n#include <utility>\n#include \"ssl/sslsession.h\"\n#include \"proto/trojanrequest.h\"\n#include \"proto/udppacket.h\"\nusing namespace std;\nusing namespace boost::asio::ip;\nusing namespace boost::asio::ssl;\n\nUDPForwardSession::UDPForwardSession(const Config &config, boost::asio::io_context &io_context, context &ssl_context, const udp::endpoint &endpoint, UDPWrite in_write) :\n    Session(config, io_context),\n    status(CONNECT),\n    in_write(move(in_write)),\n    out_socket(io_context, ssl_context),\n    gc_timer(io_context) {\n    udp_recv_endpoint = endpoint;\n    in_endpoint = tcp::endpoint(endpoint.address(), endpoint.port());\n}\n\ntcp::socket& UDPForwardSession::accept_socket() {\n    throw logic_error(\"accept_socket does not exist in UDPForwardSession\");\n}\n\nvoid UDPForwardSession::start() {\n    timer_async_wait();\n    start_time = time(nullptr);\n    auto ssl = out_socket.native_handle();\n    if (!config.ssl.sni.empty()) {\n        SSL_set_tlsext_host_name(ssl, config.ssl.sni.c_str());\n    }\n    if (config.ssl.reuse_session) {\n        SSL_SESSION *session = SSLSession::get_session();\n        if (session) {\n            SSL_set_session(ssl, session);\n        }\n    }\n    out_write_buf = TrojanRequest::generate(config.password.cbegin()->first, config.target_addr, config.target_port, false);\n    Log::log_with_endpoint(in_endpoint, \"forwarding UDP packets to \" + config.target_addr + ':' + to_string(config.target_port) + \" via \" + config.remote_addr + ':' + to_string(config.remote_port), Log::INFO);\n    auto self = shared_from_this();\n    resolver.async_resolve(config.remote_addr, to_string(config.remote_port), [this, self](const boost::system::error_code error, const tcp::resolver::results_type& results) {\n        if (error || results.empty()) {\n            Log::log_with_endpoint(in_endpoint, \"cannot resolve remote server hostname \" + config.remote_addr + \": \" + error.message(), Log::ERROR);\n            destroy();\n            return;\n        }\n        auto iterator = results.begin();\n        Log::log_with_endpoint(in_endpoint, config.remote_addr + \" is resolved to \" + iterator->endpoint().address().to_string(), Log::ALL);\n        boost::system::error_code ec;\n        out_socket.next_layer().open(iterator->endpoint().protocol(), ec);\n        if (ec) {\n            destroy();\n            return;\n        }\n        if (config.tcp.no_delay) {\n            out_socket.next_layer().set_option(tcp::no_delay(true));\n        }\n        if (config.tcp.keep_alive) {\n            out_socket.next_layer().set_option(boost::asio::socket_base::keep_alive(true));\n        }\n#ifdef TCP_FASTOPEN_CONNECT\n        if (config.tcp.fast_open) {\n            using fastopen_connect = boost::asio::detail::socket_option::boolean<IPPROTO_TCP, TCP_FASTOPEN_CONNECT>;\n            boost::system::error_code ec;\n            out_socket.next_layer().set_option(fastopen_connect(true), ec);\n        }\n#endif // TCP_FASTOPEN_CONNECT\n        out_socket.next_layer().async_connect(*iterator, [this, self](const boost::system::error_code error) {\n            if (error) {\n                Log::log_with_endpoint(in_endpoint, \"cannot establish connection to remote server \" + config.remote_addr + ':' + to_string(config.remote_port) + \": \" + error.message(), Log::ERROR);\n                destroy();\n                return;\n            }\n            out_socket.async_handshake(stream_base::client, [this, self](const boost::system::error_code error) {\n                if (error) {\n                    Log::log_with_endpoint(in_endpoint, \"SSL handshake failed with \" + config.remote_addr + ':' + to_string(config.remote_port) + \": \" + error.message(), Log::ERROR);\n                    destroy();\n                    return;\n                }\n                Log::log_with_endpoint(in_endpoint, \"tunnel established\");\n                if (config.ssl.reuse_session) {\n                    auto ssl = out_socket.native_handle();\n                    if (!SSL_session_reused(ssl)) {\n                        Log::log_with_endpoint(in_endpoint, \"SSL session not reused\");\n                    } else {\n                        Log::log_with_endpoint(in_endpoint, \"SSL session reused\");\n                    }\n                }\n                status = FORWARDING;\n                out_async_read();\n                out_async_write(out_write_buf);\n                out_write_buf.clear();\n            });\n        });\n    });\n}\n\nbool UDPForwardSession::process(const udp::endpoint &endpoint, const string &data) {\n    if (endpoint != udp_recv_endpoint) {\n        return false;\n    }\n    in_recv(data);\n    return true;\n}\n\nvoid UDPForwardSession::out_async_read() {\n    auto self = shared_from_this();\n    out_socket.async_read_some(boost::asio::buffer(out_read_buf, MAX_LENGTH), [this, self](const boost::system::error_code error, size_t length) {\n        if (error) {\n            destroy();\n            return;\n        }\n        out_recv(string((const char*)out_read_buf, length));\n    });\n}\n\nvoid UDPForwardSession::out_async_write(const string &data) {\n    auto self = shared_from_this();\n    auto data_copy = make_shared<string>(data);\n    boost::asio::async_write(out_socket, boost::asio::buffer(*data_copy), [this, self, data_copy](const boost::system::error_code error, size_t) {\n        if (error) {\n            destroy();\n            return;\n        }\n        out_sent();\n    });\n}\n\nvoid UDPForwardSession::timer_async_wait()\n{\n    gc_timer.expires_after(chrono::seconds(config.udp_timeout));\n    auto self = shared_from_this();\n    gc_timer.async_wait([this, self](const boost::system::error_code error) {\n        if (!error) {\n            Log::log_with_endpoint(in_endpoint, \"UDP session timeout\");\n            destroy();\n        }\n    });\n}\n\nvoid UDPForwardSession::in_recv(const string &data) {\n    if (status == DESTROY) {\n        return;\n    }\n    gc_timer.cancel();\n    timer_async_wait();\n    string packet = UDPPacket::generate(config.target_addr, config.target_port, data);\n    size_t length = data.length();\n    Log::log_with_endpoint(in_endpoint, \"sent a UDP packet of length \" + to_string(length) + \" bytes to \" + config.target_addr + ':' + to_string(config.target_port));\n    sent_len += length;\n    if (status == FORWARD) {\n        status = FORWARDING;\n        out_async_write(packet);\n    } else {\n        out_write_buf += packet;\n    }\n}\n\nvoid UDPForwardSession::out_recv(const string &data) {\n    if (status == FORWARD || status == FORWARDING) {\n        gc_timer.cancel();\n        timer_async_wait();\n        udp_data_buf += data;\n        for (;;) {\n            UDPPacket packet;\n            size_t packet_len;\n            bool is_packet_valid = packet.parse(udp_data_buf, packet_len);\n            if (!is_packet_valid) {\n                if (udp_data_buf.length() > MAX_LENGTH) {\n                    Log::log_with_endpoint(in_endpoint, \"UDP packet too long\", Log::ERROR);\n                    destroy();\n                    return;\n                }\n                break;\n            }\n            Log::log_with_endpoint(in_endpoint, \"received a UDP packet of length \" + to_string(packet.length) + \" bytes from \" + packet.address.address + ':' + to_string(packet.address.port));\n            udp_data_buf = udp_data_buf.substr(packet_len);\n            recv_len += packet.length;\n            in_write(udp_recv_endpoint, packet.payload);\n        }\n        out_async_read();\n    }\n}\n\nvoid UDPForwardSession::out_sent() {\n    if (status == FORWARDING) {\n        if (out_write_buf.length() == 0) {\n            status = FORWARD;\n        } else {\n            out_async_write(out_write_buf);\n            out_write_buf.clear();\n        }\n    }\n}\n\nvoid UDPForwardSession::destroy() {\n    if (status == DESTROY) {\n        return;\n    }\n    status = DESTROY;\n    Log::log_with_endpoint(in_endpoint, \"disconnected, \" + to_string(recv_len) + \" bytes received, \" + to_string(sent_len) + \" bytes sent, lasted for \" + to_string(time(nullptr) - start_time) + \" seconds\", Log::INFO);\n    resolver.cancel();\n    gc_timer.cancel();\n    if (out_socket.next_layer().is_open()) {\n        auto self = shared_from_this();\n        auto ssl_shutdown_cb = [this, self](const boost::system::error_code error) {\n            if (error == boost::asio::error::operation_aborted) {\n                return;\n            }\n            boost::system::error_code ec;\n            ssl_shutdown_timer.cancel();\n            out_socket.next_layer().cancel(ec);\n            out_socket.next_layer().shutdown(tcp::socket::shutdown_both, ec);\n            out_socket.next_layer().close(ec);\n        };\n        boost::system::error_code ec;\n        out_socket.next_layer().cancel(ec);\n        out_socket.async_shutdown(ssl_shutdown_cb);\n        ssl_shutdown_timer.expires_after(chrono::seconds(SSL_SHUTDOWN_TIMEOUT));\n        ssl_shutdown_timer.async_wait(ssl_shutdown_cb);\n    }\n}\n"
  },
  {
    "path": "src/session/udpforwardsession.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _UDPFORWARDSESSION_H_\n#define _UDPFORWARDSESSION_H_\n\n#include \"session.h\"\n#include <boost/asio/ssl.hpp>\n#include <boost/asio/steady_timer.hpp>\n\nclass UDPForwardSession : public Session {\npublic:\n    typedef std::function<void(const boost::asio::ip::udp::endpoint&, const std::string&)> UDPWrite;\nprivate:\n    enum Status {\n        CONNECT,\n        FORWARD,\n        FORWARDING,\n        DESTROY\n    } status;\n    UDPWrite in_write;\n    boost::asio::ssl::stream<boost::asio::ip::tcp::socket>out_socket;\n    boost::asio::steady_timer gc_timer;\n    void destroy();\n    void in_recv(const std::string &data);\n    void out_async_read();\n    void out_async_write(const std::string &data);\n    void out_recv(const std::string &data);\n    void out_sent();\n    void timer_async_wait();\npublic:\n    UDPForwardSession(const Config &config, boost::asio::io_context &io_context, boost::asio::ssl::context &ssl_context, const boost::asio::ip::udp::endpoint &endpoint, UDPWrite in_write);\n    boost::asio::ip::tcp::socket& accept_socket() override;\n    void start() override;\n    bool process(const boost::asio::ip::udp::endpoint &endpoint, const std::string &data);\n};\n\n#endif // _UDPFORWARDSESSION_H_\n"
  },
  {
    "path": "src/ssl/ssldefaults.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"ssldefaults.h\"\n\nconst char SSLDefaults::g_dh2048_sz[] =\n    \"-----BEGIN DH PARAMETERS-----\\n\"\n    \"MIIBCAKCAQEA///////////JD9qiIWjCNMTGYouA3BzRKQJOCIpnzHQCC76mOxOb\\n\"\n    \"IlFKCHmONATd75UZs806QxswKwpt8l8UN0/hNW1tUcJF5IW1dmJefsb0TELppjft\\n\"\n    \"awv/XLb0Brft7jhr+1qJn6WunyQRfEsf5kkoZlHs5Fs9wgB8uKFjvwWY2kg2HFXT\\n\"\n    \"mmkWP6j9JM9fg2VdI9yjrZYcYvNWIIVSu57VKQdwlpZtZww1Tkq8mATxdGwIyhgh\\n\"\n    \"fDKQXkYuNs474553LBgOhgObJ4Oi7Aeij7XFXfBvTFLJ3ivL9pVYFxg5lUl86pVq\\n\"\n    \"5RXSJhiY+gUQFXKOWoqsqmj//////////wIBAg==\\n\"\n    \"-----END DH PARAMETERS-----\";\n\nconst size_t SSLDefaults::g_dh2048_sz_size = sizeof(g_dh2048_sz);\n"
  },
  {
    "path": "src/ssl/ssldefaults.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _SSLDEFAULTS_H_\n#define _SSLDEFAULTS_H_\n\n#include <cstddef>\n\nclass SSLDefaults {\npublic:\n    static const char g_dh2048_sz[];\n    static const size_t g_dh2048_sz_size;\n};\n\n#endif // _SSLDEFAULTS_H_\n"
  },
  {
    "path": "src/ssl/sslsession.cpp",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"sslsession.h\"\nusing namespace std;\n\nlist<SSL_SESSION*>SSLSession::sessions;\n\nint SSLSession::new_session_cb(SSL*, SSL_SESSION *session) {\n    sessions.push_front(session);\n    return 0;\n}\n\nvoid SSLSession::remove_session_cb(SSL_CTX*, SSL_SESSION *session) {\n    sessions.remove(session);\n}\n\nSSL_SESSION *SSLSession::get_session() {\n    if (sessions.empty()) {\n        return nullptr;\n    }\n    return sessions.front();\n}\n\nvoid SSLSession::set_callback(SSL_CTX *context) {\n    SSL_CTX_sess_set_new_cb(context, new_session_cb);\n    SSL_CTX_sess_set_remove_cb(context, remove_session_cb);\n}\n"
  },
  {
    "path": "src/ssl/sslsession.h",
    "content": "/*\n * This file is part of the trojan project.\n * Trojan is an unidentifiable mechanism that helps you bypass GFW.\n * Copyright (C) 2017-2020  The Trojan Authors.\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef _SSLSESSION_H_\n#define _SSLSESSION_H_\n\n#include <list>\n#include <openssl/ssl.h>\n\nclass SSLSession {\nprivate:\n    static std::list<SSL_SESSION*>sessions;\n    static int new_session_cb(SSL*, SSL_SESSION *session);\n    static void remove_session_cb(SSL_CTX*, SSL_SESSION *session);\npublic:\n    static SSL_SESSION *get_session();\n    static void set_callback(SSL_CTX *context);\n};\n\n#endif // _SSLSESSION_H_\n"
  },
  {
    "path": "tests/.gitignore",
    "content": "# Allow config files in tests\n!*.json\n"
  },
  {
    "path": "tests/LinuxSmokeTest/README.md",
    "content": "# Linux Smoke Test\n\n## Dependencies\n\n- curl\n- netcat\n- openssl\n- python3\n\n## Usage\n\n```\n./basic.sh /path/to/trojan\n./fake-client.sh /path/to/trojan\n```\n"
  },
  {
    "path": "tests/LinuxSmokeTest/basic.sh",
    "content": "#!/bin/bash\nset -eu\n\nsource \"$(dirname \"$0\")/common.sh\"\n\ncp server.json client.json forward.json \"$TMPDIR\"\ncd \"$TMPDIR\"\n\nexec 2>> test.log\n\nyes '' | openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 1 -nodes\n\nmkdir true\ncd true\necho true > whoami.txt\npython3 -m http.server 10081 > server.log 2>&1 &\nPID1=\"$!\"\ncd ..\n\nmkdir fake\ncd fake\necho fake > whoami.txt\npython3 -m http.server 10080 > server.log 2>&1 &\nPID2=\"$!\"\ncd ..\n\n./trojan -v\n\n./trojan -t server.json\n./trojan server.json -l server.log &\nPID3=\"$!\"\n\n./trojan -t client.json\n./trojan client.json -l client.log &\nPID4=\"$!\"\n\n./trojan -t forward.json\n./trojan forward.json -l forward.log &\nPID5=\"$!\"\n\nwait_port 10081\nwait_port 10080\nwait_port 10443\nwait_port 11080\nwait_port 20081\n\nWHOAMI=$(curl -v --socks5 127.0.0.1:11080 http://127.0.0.1:10081/whoami.txt)\nWHOAMI2=$(curl -v http://127.0.0.1:20081/whoami.txt)\nkill -KILL \"$PID1\" \"$PID2\" \"$PID3\" \"$PID4\" \"$PID5\"\nif [[ \"$WHOAMI\" = \"true\" && \"$WHOAMI2\" = \"true\" ]]; then\n    exit 0\nelse\n    exit 1\nfi\n"
  },
  {
    "path": "tests/LinuxSmokeTest/client.json",
    "content": "{\n    \"run_type\": \"client\",\n    \"local_addr\": \"127.0.0.1\",\n    \"local_port\": 11080,\n    \"remote_addr\": \"127.0.0.1\",\n    \"remote_port\": 10443,\n    \"password\": [\n        \"linux-smoke-test-password\"\n    ],\n    \"log_level\": 0,\n    \"ssl\": {\n        \"verify\": true,\n        \"verify_hostname\": false,\n        \"cert\": \"cert.pem\",\n        \"cipher\": \"\",\n        \"cipher_tls13\": \"\",\n        \"sni\": \"\",\n        \"alpn\": [],\n        \"reuse_session\": false,\n        \"session_ticket\": false,\n        \"curves\": \"\"\n    },\n    \"tcp\": {\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    }\n}\n"
  },
  {
    "path": "tests/LinuxSmokeTest/common.sh",
    "content": "function check_available() {\n    if ! command -v \"$1\" > /dev/null; then\n        echo \"$1 is required.\"\n        exit 1\n    fi\n}\n\nfunction wait_port() {\n    until nc -z 127.0.0.1 \"$1\"; do\n        sleep 0.1\n    done\n}\n\nif [[ \"$#\" != \"1\" ]]; then\n    echo \"usage: $0 path_to_trojan\"\n    exit 1\nfi\n\ncheck_available curl\ncheck_available nc\ncheck_available openssl\ncheck_available python3\n\nSCRIPTDIR=\"$(dirname \"$0\")\"\nTMPDIR=\"$(mktemp -d)\"\n\necho \"$TMPDIR\"\ncp \"$1\" \"$TMPDIR/trojan\"\ncd \"$SCRIPTDIR\"\n"
  },
  {
    "path": "tests/LinuxSmokeTest/fake-client.json",
    "content": "{\n    \"run_type\": \"client\",\n    \"local_addr\": \"127.0.0.1\",\n    \"local_port\": 11080,\n    \"remote_addr\": \"127.0.0.1\",\n    \"remote_port\": 10443,\n    \"password\": [\n        \"wrong-password\"\n    ],\n    \"log_level\": 0,\n    \"ssl\": {\n        \"verify\": true,\n        \"verify_hostname\": false,\n        \"cert\": \"cert.pem\",\n        \"cipher\": \"\",\n        \"cipher_tls13\": \"\",\n        \"sni\": \"\",\n        \"alpn\": [],\n        \"reuse_session\": false,\n        \"session_ticket\": false,\n        \"curves\": \"\"\n    },\n    \"tcp\": {\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    }\n}\n"
  },
  {
    "path": "tests/LinuxSmokeTest/fake-client.sh",
    "content": "#!/bin/bash\nset -u\n\nsource \"$(dirname \"$0\")/common.sh\"\n\ncp server.json fake-client.json forward.json \"$TMPDIR\"\ncd \"$TMPDIR\"\n\nexec 2>> test.log\n\nyes '' | openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 1 -nodes\n\nmkdir true\ncd true\necho true > whoami.txt\npython3 -m http.server 10081 > server.log 2>&1 &\nPID1=\"$!\"\ncd ..\n\nmkdir fake\ncd fake\necho fake > whoami.txt\npython3 -m http.server 10080 > server.log 2>&1 &\nPID2=\"$!\"\ncd ..\n\n./trojan -v\n\n./trojan -t server.json\n./trojan server.json -l server.log &\nPID3=\"$!\"\n\n./trojan -t fake-client.json\n./trojan fake-client.json -l fake-client.log &\nPID4=\"$!\"\n\nwait_port 10081\nwait_port 10080\nwait_port 10443\nwait_port 11080\n\nWHOAMI=$(curl -v --socks5 127.0.0.1:11080 http://127.0.0.1:10081/whoami.txt)\nWHOAMI2=$(curl -v --insecure https://127.0.0.1:10443/whoami.txt)\nkill -KILL \"$PID1\" \"$PID2\" \"$PID3\" \"$PID4\"\nif [[ \"$WHOAMI\" != \"true\" && \"$WHOAMI2\" = \"fake\" ]]; then\n    exit 0\nelse\n    exit 1\nfi\n"
  },
  {
    "path": "tests/LinuxSmokeTest/forward.json",
    "content": "{\n    \"run_type\": \"forward\",\n    \"local_addr\": \"127.0.0.1\",\n    \"local_port\": 20081,\n    \"remote_addr\": \"127.0.0.1\",\n    \"remote_port\": 10443,\n    \"target_addr\": \"127.0.0.1\",\n    \"target_port\": 10081,\n    \"password\": [\n        \"linux-smoke-test-password\"\n    ],\n    \"udp_timeout\": 60,\n    \"log_level\": 0,\n    \"ssl\": {\n        \"verify\": true,\n        \"verify_hostname\": false,\n        \"cert\": \"cert.pem\",\n        \"cipher\": \"\",\n        \"cipher_tls13\": \"\",\n        \"sni\": \"\",\n        \"alpn\": [],\n        \"reuse_session\": false,\n        \"session_ticket\": false,\n        \"curves\": \"\"\n    },\n    \"tcp\": {\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    }\n}\n"
  },
  {
    "path": "tests/LinuxSmokeTest/server.json",
    "content": "{\n    \"run_type\": \"server\",\n    \"local_addr\": \"127.0.0.1\",\n    \"local_port\": 10443,\n    \"remote_addr\": \"127.0.0.1\",\n    \"remote_port\": 10080,\n    \"password\": [\"linux-smoke-test-password\"],\n    \"log_level\": 0,\n    \"ssl\": {\n        \"cert\": \"cert.pem\",\n        \"key\": \"key.pem\",\n        \"key_password\": \"\",\n        \"cipher\": \"\",\n        \"cipher_tls13\": \"\",\n        \"prefer_server_cipher\": true,\n        \"alpn\": [],\n        \"alpn_port_override\": {},\n        \"reuse_session\": false,\n        \"session_ticket\": false,\n        \"session_timeout\": 600,\n        \"plain_http_response\": \"\",\n        \"curves\": \"\",\n        \"dhparam\": \"\"\n    },\n    \"tcp\": {\n        \"prefer_ipv4\": false,\n        \"no_delay\": true,\n        \"keep_alive\": true,\n        \"reuse_port\": false,\n        \"fast_open\": false,\n        \"fast_open_qlen\": 20\n    },\n    \"mysql\": {\n        \"enabled\": false,\n        \"server_addr\": \"\",\n        \"server_port\": 0,\n        \"database\": \"\",\n        \"username\": \"\",\n        \"password\": \"\",\n        \"key\": \"\",\n        \"cert\": \"\",\n        \"ca\": \"\"\n    }\n}\n"
  }
]