├── .clang-format ├── .gitignore ├── .gitmodules ├── .travis.yml ├── CMakeLists.txt ├── LICENSE ├── Makefile.mingw ├── README.md ├── SConstruct ├── appveyor.yml ├── bsd_getopt.c ├── bsd_getopt.h ├── connector.c ├── connector.h ├── dns_forward.c ├── dns_forward.h ├── encrypt.c ├── encrypt.h ├── evhtp-config.h.win32 ├── evhtp_get.c ├── evhtp_proxy.c ├── evhtp_sock_relay.c ├── http_connector.c ├── log.c ├── log.h ├── lru.c ├── parse_forward_param.c ├── parse_forward_param.h ├── parse_forward_param.rl ├── proxy.vcxproj ├── ss_connector.c ├── utils.c └── utils.h /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: LLVM 2 | ColumnLimit: 100 3 | IndentWidth: 4 4 | UseTab: Never 5 | BreakBeforeBraces: Linux 6 | AllowShortIfStatementsOnASingleLine: false 7 | IndentCaseLabels: false 8 | IndentPPDirectives: AfterHash 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # cmake manages these; they shouldn't go in version control 2 | # 3 | # 4 | # they aren't going into version control, but shouldn't be 5 | # completely ignored. I'm removing the mods here. 6 | # 7 | build/ 8 | *.d 9 | *.o 10 | *.obj 11 | *.exe 12 | *.dll 13 | *.zip 14 | .*.swp 15 | *~ 16 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "libevhtp"] 2 | path = libevhtp 3 | url = https://github.com/boytm/libevhtp 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: c 2 | 3 | compiler: 4 | - clang 5 | - gcc 6 | 7 | env: 8 | # build without shadowsocks protocol 9 | - ENABLE_SS: OFF 10 | USE_CRYPTO_OPENSSL: OFF 11 | USE_CRYPTO_MBEDTLS: OFF 12 | 13 | # build with openssl library 14 | - ENABLE_SS: ON 15 | USE_CRYPTO_OPENSSL: ON 16 | USE_CRYPTO_MBEDTLS: OFF 17 | 18 | # build with mbed TLS library 19 | - ENABLE_SS: ON 20 | USE_CRYPTO_OPENSSL: OFF 21 | USE_CRYPTO_MBEDTLS: ON 22 | MBEDTLS_VERSION: 2.1.18 23 | 24 | # build https proxy with openssl library 25 | - ENABLE_SS: ON 26 | ENABLE_HTTPS_PROXY: ON 27 | USE_CRYPTO_OPENSSL: ON 28 | USE_CRYPTO_MBEDTLS: OFF 29 | 30 | sudo: required 31 | dist: trusty 32 | 33 | branches: 34 | except: 35 | - /^v[0-9]/ 36 | 37 | addons: 38 | apt: 39 | sources: 40 | # aliases defined in https://github.com/travis-ci/apt-source-whitelist 41 | #- deadsnakes 42 | - sourceline: 'ppa:ondrej/apache2' 43 | packages: 44 | - cmake 45 | - cmake-data 46 | - scons 47 | - libssl-dev 48 | 49 | install: 50 | # build and install libevent 51 | - wget https://github.com/libevent/libevent/releases/download/release-2.1.8-stable/libevent-2.1.8-stable.tar.gz && tar -xf libevent-2.1.8-stable.tar.gz && cd libevent-2.1.8-stable && ./configure && make && sudo make install && cd - 52 | # build and install mbedtls 53 | - test "$USE_CRYPTO_MBEDTLS" != true || ( wget https://tls.mbed.org/download/mbedtls-${MBEDTLS_VERSION}-gpl.tgz && tar -xf mbedtls-${MBEDTLS_VERSION}-gpl.tgz && cd mbedtls-${MBEDTLS_VERSION} && make && sudo make install && cd - ) 54 | 55 | script: 56 | - scons && scons --clean 57 | - mkdir -p build && cd build && cmake .. -DENABLE_HTTPS_PROXY:STRING=$ENABLE_HTTPS_PROXY -DENABLE_SS:STRING=$ENABLE_SS -DUSE_CRYPTO_OPENSSL:STRING=$USE_CRYPTO_OPENSSL -DUSE_CRYPTO_MBEDTLS:STRING=$USE_CRYPTO_MBEDTLS && make 58 | 59 | notifications: 60 | recipients: 61 | - boycht@gmail.com 62 | email: 63 | on_success: change 64 | on_failure: always 65 | 66 | # vim:set sts=2 sw=2 tw=0 et: 67 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required (VERSION 2.8.11) 2 | project(mproxy) 3 | 4 | set(MPROXY_MAJOR_VERSION 0) 5 | set(MPROXY_MINOR_VERSION 3) 6 | set(MPROXY_PATCH_VERSION 0) 7 | 8 | set(CMAKE_VERBOSE_MAKEFILE on) 9 | 10 | #set(CMAKE_C_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -Wall -g -O0") 11 | #set(CMAKE_C_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -Wall -O2") 12 | if( NOT CMAKE_BUILD_TYPE ) 13 | set( CMAKE_BUILD_TYPE Debug CACHE STRING 14 | "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." 15 | FORCE ) 16 | endif() 17 | 18 | # -DENABLE_SS:STRING=ON 19 | OPTION(ENABLE_SS "Enable shadowsocks protocol" ON) 20 | # -DUSE_CRYPTO_OPENSSL:STRING=ON 21 | OPTION(USE_CRYPTO_OPENSSL "Use OpenSSL crypt library" ON) 22 | OPTION(USE_CRYPTO_MBEDTLS "Use mbed TLS crypt library" OFF) 23 | # -DENABLE_HTTPS_PROXY:STRING=ON 24 | OPTION(ENABLE_HTTPS_PROXY "Enable https proxy" OFF) 25 | 26 | # add source files to DIR_SRCS 27 | aux_source_directory(. DIR_SRCS) 28 | 29 | # libevhtp subdir 30 | # add a variable of the same name to the cache, so options in subdirectory can be changed 31 | if (NOT ENABLE_HTTPS_PROXY) 32 | set(EVHTP_DISABLE_SSL ON CACHE BOOL "Disable ssl") 33 | endif() 34 | set(EVHTP_DISABLE_EVTHR ON CACHE BOOL "Disable thread") 35 | set(EVHTP_DISABLE_REGEX ON CACHE BOOL "Disable regex") 36 | add_subdirectory(libevhtp) 37 | 38 | include_directories(SYSTEM ${LIBEVENT_INCLUDE_DIR}) 39 | set(MPROXY_LIBS ${MPROXY_LIBS} ${LIBEVENT_LIBRARY}) 40 | if (WIN32) 41 | find_library(LIB_WS32 ws2_32) 42 | set(MPROXY_LIBS ${MPROXY_LIBS} ${LIB_WS32}) 43 | elseif (NOT APPLE) 44 | find_library(LIB_RT rt) 45 | set(MPROXY_LIBS ${MPROXY_LIBS} ${LIB_RT}) 46 | endif() 47 | 48 | CHECK_FUNCTION_EXISTS(strerror_r HAVE_STRERROR_R) 49 | if (HAVE_STRERROR_R) 50 | add_definitions(-DHAVE_STRERROR_R=1) 51 | endif() 52 | 53 | CHECK_FUNCTION_EXISTS(splice HAVE_SPLICE) 54 | if (HAVE_SPLICE) 55 | add_definitions(-DHAVE_SPLICE=1) 56 | endif() 57 | 58 | set(MPROXY_SOURCES parse_forward_param.c dns_forward.c connector.c http_connector.c evhtp_proxy.c evhtp_sock_relay.c lru.c utils.c log.c) 59 | if (MSVC) 60 | add_definitions(-D_WINSOCK_DEPRECATED_NO_WARNINGS -D_CRT_SECURE_NO_WARNINGS) 61 | set(MPROXY_SOURCES ${MPROXY_SOURCES} bsd_getopt.c ) 62 | endif() 63 | 64 | if (USE_CRYPTO_OPENSSL) 65 | find_package(OpenSSL 1.1.0) 66 | if (OPENSSL_FOUND) 67 | include_directories(SYSTEM ${OPENSSL_INCLUDE_DIR}) 68 | add_definitions(-DUSE_CRYPTO_OPENSSL=1) 69 | set (MPROXY_LIBS ${MPROXY_LIBS} ${OPENSSL_CRYPTO_LIBRARY}) 70 | else() 71 | message(WARNING "Unable to find OpenSSL ") 72 | set(USE_CRYPTO_OPENSSL OFF) 73 | endif() 74 | elseif (USE_CRYPTO_MBEDTLS) 75 | find_path(MBEDTLS_INCLUDE_DIR mbedtls/cipher.h 76 | HINTS ${MBEDTLS_ROOT_DIR} 77 | PATH_SUFFIXES include) 78 | find_library(MBEDCRYPTO_LIBRARY mbedcrypto 79 | HINTS ${MBEDTLS_ROOT_DIR} 80 | PATH_SUFFIXES library lib) 81 | if (MBEDTLS_INCLUDE_DIR AND MBEDCRYPTO_LIBRARY) 82 | include_directories(${MBEDTLS_INCLUDE_DIR}) 83 | add_definitions(-DUSE_CRYPTO_MBEDTLS=1) 84 | set (MPROXY_LIBS ${MPROXY_LIBS} ${MBEDCRYPTO_LIBRARY}) 85 | else() 86 | message(WARNING "Unable to find mbed TLS ") 87 | set(USE_CRYPTO_MBEDTLS OFF) 88 | endif() 89 | endif() 90 | 91 | if (ENABLE_SS) 92 | if (USE_CRYPTO_OPENSSL OR USE_CRYPTO_MBEDTLS) 93 | add_definitions(-DENABLE_SS=1) 94 | set(MPROXY_SOURCES ${MPROXY_SOURCES} ss_connector.c encrypt.c ) 95 | else() 96 | message(WARNING "OpenSSL or mbed TLS is required to enable shadowsocks protocol ") 97 | set(ENABLE_SS OFF) 98 | endif() 99 | else() 100 | set(USE_CRYPTO_OPENSSL OFF) 101 | set(USE_CRYPTO_MBEDTLS OFF) 102 | endif() 103 | 104 | add_executable(mproxy ${MPROXY_SOURCES} ) 105 | target_link_libraries(mproxy evhtp ${MPROXY_LIBS}) 106 | 107 | message("") 108 | message(STATUS "${Blue}CMAKE_BUILD_TYPE${ColourReset} : " ${BoldRed}${CMAKE_BUILD_TYPE}${ColourReset}) 109 | message(STATUS "${Blue}ENABLE_HTTPS_PROXY${ColourReset} : " ${BoldRed}${ENABLE_HTTPS_PROXY}${ColourReset}) 110 | message(STATUS "${Blue}ENABLE_SS${ColourReset} : " ${BoldRed}${ENABLE_SS}${ColourReset}) 111 | message(STATUS "${Blue}USE_CRYPTO_OPENSSL${ColourReset} : " ${BoldRed}${USE_CRYPTO_OPENSSL}${ColourReset}) 112 | message(STATUS "${Blue}USE_CRYPTO_MBEDTLS${ColourReset} : " ${BoldRed}${USE_CRYPTO_MBEDTLS}${ColourReset}) 113 | 114 | # vim:set sts=4 sw=4 tw=0 et: 115 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | 676 | -------------------------------------------------------------------------------- /Makefile.mingw: -------------------------------------------------------------------------------- 1 | 2 | #OPENSSL_DIR=/d/openssl 3 | OPENSSL_DIR=/d/openssl-1.1.0 4 | MBEDTLS_DIR=/d/Sources/mbedtls-2.1.14 5 | LIBEVENT_DIR=/d/Sources/libevent-2.1.8-stable 6 | SYSINC:= $(LIBEVENT_DIR)/include/ \ 7 | $(LIBEVENT_DIR)/WIN32-Code/ \ 8 | $(OPENSSL_DIR)/include \ 9 | $(MBEDTLS_DIR)/include 10 | SYSLIB:= $(LIBEVENT_DIR)/.libs/ \ 11 | $(OPENSSL_DIR)/lib \ 12 | $(MBEDTLS_DIR)/library 13 | 14 | CC:= gcc 15 | CFLAGS:= -Wall -g -O2 -static -DNDEBUG -DNO_SYS_UN=1 -DENABLE_SS=1 \ 16 | -Ilibevhtp -I libevhtp/compat/ \ 17 | -levent -lws2_32 \ 18 | -DUSE_CRYPTO_MBEDTLS=1 -lmbedcrypto \ 19 | $(addprefix -isystem , $(SYSINC)) \ 20 | $(addprefix -L , $(SYSLIB)) 21 | 22 | sources:= evhtp_proxy.c evhtp_sock_relay.c connector.c lru.c log.c \ 23 | ss_connector.c encrypt.c http_connector.c dns_forward.c \ 24 | libevhtp/evhtp.c libevhtp/htparse.c libevhtp/evhtp_numtoa.c \ 25 | parse_forward_param.c 26 | objects:= $(addprefix obj/, $(sources:.c=.o)) 27 | depends:= $(addprefix obj/, $(sources:.c=.d)) 28 | 29 | .PHONY: all clean 30 | 31 | all: mproxy 32 | 33 | libevhtp/evhtp-config.h: evhtp-config.h.win32 34 | cp $< $@ 35 | 36 | libevhtp/compat/sys/tree.h libevhtp/compat/sys/queue.h : %.h : %.h.in 37 | cp $< $@ 38 | 39 | parse_forward_param.c: parse_forward_param.rl 40 | ragel -C -o $@ $< 41 | 42 | $(objects): obj/%.o: %.c 43 | $(CC) -c $(CFLAGS) $< -o $@ 44 | 45 | $(depends): obj/%.d: %.c 46 | mkdir -p `dirname $@` 47 | $(CC) -MM $(CFLAGS) $< -MF $@ -MT $(@:.d=.o) 48 | 49 | $(depends) : libevhtp/evhtp-config.h libevhtp/compat/sys/queue.h libevhtp/compat/sys/tree.h 50 | 51 | include $(depends) 52 | 53 | mproxy : $(objects) 54 | $(CC) -o $@ $^ $(CFLAGS) 55 | 56 | clean: 57 | -rm -f $(objects) mproxy 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mproxy 2 | [![Build Status](https://travis-ci.org/boytm/mproxy.svg?branch=master)](https://travis-ci.org/boytm/mproxy) 3 | [![Appveyor Build status](https://ci.appveyor.com/api/projects/status/8jk67xy7xtr9ij2a?svg=true)](https://ci.appveyor.com/project/boytm/mproxy) 4 | 5 | [中文使用帮助](https://github.com/boytm/mproxy/wiki) 6 | 7 | mproxy is a multi mode http/https proxy. 8 | 9 | 1. as a normal HTTP/HTTPS proxy 10 | 11 | 2. as a SOCKS5 proxy to HTTP proxy converter 12 | 13 | 3. as a shadowsocks HTTP client 14 | 15 | 3proxy can work as mode 1 and mode 2, but his threaded model cannot scale well. 16 | 17 | When possible, use splice to speed up HTTP CONNECT socket relay under mode 1,2. 18 | 19 | Based on a modified libevhtp library, the original version have some bugs when as HTTP client library. 20 | 21 | Why HTTP proxy instead of SOCKSs proxy? Because some client only support HTTP proxy, for example IE9 only support 22 | SOCKS4/HTTP proxy, and some version control system like subversion mercurial only support HTTP proxy. 23 | Currently HTTPS proxy is only supported by a few clients, eg. Chrome, Firefox 31+, curl 7.52.0+. 24 | 25 | # Installation # 26 | 27 | ### Install required development components 28 | _libevent 2.0.12+_ (except [libevent 2.0.22 stable](https://github.com/libevent/libevent/issues/335)), _OpenSSL 1.1.0+ or mbed TLS_ (optional) 29 | 30 | Win32 require _VC++ 2013/2015_ or _MinGW-w64 and MSYS_ . 31 | 32 | Linux require _cmake_ or _scons_. 33 | 34 | ### Compile 35 | #### Win32 36 | * MinGW 37 | >make -f Makefile.mingw 38 | 39 | * VC++ 2013/2015/2017 40 | open the _proxy.vcxproj_ directly, set your libevent and openssl directories then compile 41 | 42 | #### Linux 43 | * CMake, enable all protocol 44 | >cmake . -DENABLE_HTTPS_PROXY:STRING=ON -DENABLE_SS:STRING=ON -DCMAKE_BUILD_TYPE=Release && make 45 | 46 | * CMake, disable shadowsocks protocol 47 | >cmake . -DENABLE_SS:STRING=OFF && make 48 | 49 | # Usage # 50 | 51 | Multi Mode HTTP proxy 52 | Usage: 53 | mproxy [options] 54 | Options: 55 | -l proxy listen port, default 8081 56 | -b local address to bind, default 0.0.0.0; IPv6 address 57 | must starts with "ipv6:" 58 | -p socks5/shadowsocks server port 59 | -s socks5/shadowsocks server address 60 | -m encrypt method of remote shadowsocks server 61 | -k password of remote shadowsocks server 62 | --pac pac file 63 | --dns name server, default port 53 64 | --user set user and group 65 | --pid-file pid file 66 | --ssl_certificate set ssl certificate 67 | --ssl_certificate_key set ssl private key 68 | -V show version number and quit 69 | -h show help 70 | Supported encryption methods for shadowsocks: 71 | Stream Cipher: 72 | table, rc4, rc4-md5, aes-128-cfb, aes-192-cfb, aes-256-cfb, 73 | bf-cfb, camellia-128-cfb, camellia-192-cfb, camellia-256-cfb, 74 | cast5-cfb, des-cfb, idea-cfb, rc2-cfb, seed-cfb, aes-128-ofb, 75 | aes-192-ofb, aes-256-ofb, aes-128-ctr, aes-192-ctr, aes-256-ctr, 76 | aes-128-cfb8, aes-192-cfb8, aes-256-cfb8, aes-128-cfb1, 77 | aes-192-cfb1, aes-256-cfb1 78 | AEAD Cipher: 79 | chacha20-ietf-poly1305, aes-128-gcm, aes-192-gcm, aes-256-gcm, 80 | aes-128-ocb, aes-192-ocb, aes-256-ocb 81 | 82 | 83 | ### Examples 84 | 85 | simple HTTP proxy, listen 127.0.0.1:8081 86 | 87 | ./mproxy -b 127.0.0.1 -l8081 88 | or 89 | ./mproxy -b ipv4:127.0.0.1 -l8081 90 | 91 | simple HTTP proxy, listen IPv6 [::1]:8081 92 | 93 | ./mproxy -b ipv6:::1 -l8081 94 | 95 | HTTPS proxy, use certificate issued by Let's Encrypt, listen IPv6 [::1]:8081 96 | 97 | ./mproxy -b ipv6:::1 -l8081 --ssl_certificate /etc/letsencrypt/live/your.domain/fullchain.pem --ssl_certificate_key /etc/letsencrypt/live/your.domain/privkey.pem 98 | 99 | convert local machine's SOCKS5 proxy at 127.0.0.1:1080 to HTTP proxy at 127.0.0.1:8087 100 | 101 | ./mproxy -b127.0.0.1 -l8087 -s 127.0.0.1 -p 1080 102 | 103 | worked as shadowsocks client, shadowsocks server address 9.9.9.9:9999, encrypt method aes-256-cfb, password mysspassword 104 | 105 | ./mproxy -b127.0.0.1 -l8087 -s 9.9.9.9 -p 9999 -k mysspassword -m aes-256-cfb 106 | 107 | worked as shadowsocks client, encrypt method rc4-md5, password mysspassword, and serve local PAC file 108 | 109 | ./mproxy -b127.0.0.1 -l8087 -s 9.9.9.9 -p 9999 -k mysspassword -m rc4-md5 --pac /path/to/pac/file 110 | 111 | ### TODO 112 | 113 | DNS cache 114 | 115 | LRU with multi thread 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /SConstruct: -------------------------------------------------------------------------------- 1 | 2 | from SCons.Defaults import processDefines 3 | 4 | def config_h_build(target, source, env): 5 | config_h_defines = { } 6 | for define in processDefines(env["CPPDEFINES"]): 7 | l = define.split("=", 1) 8 | if len(l) == 2: 9 | config_h_defines[l[0]] = l[1] 10 | else: 11 | config_h_defines[l[0]] = "" 12 | 13 | #print config_h_defines 14 | for a_target, a_source in zip(target, source): 15 | with open(str(a_target), "w") as config_h: 16 | with open(str(a_source), "r") as f: 17 | for line in f: 18 | if line.startswith("#cmakedefine "): 19 | _, key = line.split(None, 1) 20 | key = key.strip() 21 | if key in config_h_defines: 22 | config_h.write("#define %s %s\n" % (key, config_h_defines[key])) 23 | else: 24 | config_h.write("#undef %s\n" % key) 25 | else: 26 | config_h.write("%s" % line) 27 | 28 | #env = Environment(CCFLAGS = '-g -O0 -Wall') 29 | env = Environment(CCFLAGS = '-g -O2 -Wall') 30 | #env['CPPDEFINES'] = ['EVHTP_DEBUG=1'] 31 | #env['CPPFLAGS'] = 32 | #env['CPPPATH'] = [] 33 | #env['LIBPATH'] = [] 34 | #env['LIBS'] = [] 35 | env['EVHTP_DIR'] = 'libevhtp' 36 | libs = ['pthread', 'rt'] 37 | 38 | if not env.GetOption('clean'): 39 | conf = Configure(env) 40 | if not conf.CheckLibWithHeader('event', 'event2/event.h', 'c'): 41 | print 'libevent 2.12+ required!' 42 | Exit(1) 43 | 44 | if not conf.CheckHeader('sys/un.h'): 45 | conf.env.Append(CPPDEFINES = "NO_SYS_UN") 46 | if not conf.CheckHeader('sys/queue.h'): 47 | env.Command('$EVHTP_DIR/compat/sys/queue.h', '$EVHTP_DIR/compat/sys/queue.h.in', 'cp $SOURCES $TARGET') 48 | if not conf.CheckHeader('sys/tree.h'): 49 | env.Command('$EVHTP_DIR/compat/sys/tree.h', '$EVHTP_DIR/compat/sys/tree.h.in', 'cp $SOURCES $TARGET') 50 | if not conf.CheckFunc('strndup'): 51 | conf.env.Append(CPPDEFINES = ['NO_STRNDUP']) 52 | if not conf.CheckFunc('strnlen'): 53 | conf.env.Append(CPPDEFINES = ['NO_STRNLEN']) 54 | if conf.CheckHeader('openssl/evp.h') and conf.CheckHeader('openssl/kdf.h'): 55 | conf.env.Append(CPPDEFINES = ['USE_CRYPTO_OPENSSL', 'ENABLE_SS']) 56 | if conf.CheckFunc('strerror_r'): 57 | conf.env.Append(CPPDEFINES = ['HAVE_STRERROR_R']) 58 | if conf.CheckFunc('splice'): 59 | conf.env.Append(CPPDEFINES = ['HAVE_SPLICE']) 60 | if not conf.CheckLib('event_openssl'): 61 | conf.env.Append(CPPDEFINES = ['EVHTP_DISABLE_SSL']) 62 | libs += ['event', 'crypto'] 63 | else: 64 | libs += ['event', 'event_openssl', 'ssl', 'crypto', 'dl'] 65 | 66 | conf.env.Append(CPPDEFINES = {"EVHTP_SYS_ARCH" : (8 * conf.CheckTypeSize("size_t"))}) 67 | conf.env.Append(CPPDEFINES = ['EVHTP_DISABLE_REGEX', 'EVHTP_DISABLE_EVTHR']) 68 | env = conf.Finish() 69 | 70 | if env['PLATFORM'] in ('win32', 'mingw'): 71 | env['LIBS'] += "ws2_32" 72 | 73 | env.Decider('timestamp-match') 74 | 75 | config_h_action = Action(config_h_build, varlist=['CPPDEFINES']) 76 | env.Command('$EVHTP_DIR/evhtp-config.h', '$EVHTP_DIR/evhtp-config.h.in', config_h_action) 77 | env.Append(CPPPATH = ['libevhtp', 'libevhtp/compat']) 78 | libevhtp_srcs = Split('libevhtp/evhtp.c libevhtp/evhtp_numtoa.c libevhtp/evthr.c libevhtp/htparse.c') 79 | libevhtp_objs = [env.Object(i) for i in libevhtp_srcs] 80 | 81 | 82 | env.Program('evhtp_get', ['evhtp_get.c', ] + libevhtp_objs, 83 | LIBS = libs, 84 | LIBPATH = ['/usr/local/lib', '/usr/lib', ]) 85 | 86 | mproxy = env.Program('mproxy', Split('evhtp_proxy.c evhtp_sock_relay.c lru.c dns_forward.c connector.c http_connector.c ss_connector.c encrypt.c utils.c log.c parse_forward_param.c') + libevhtp_objs, 87 | CCFLAGS = env['CCFLAGS'] + ' ', 88 | LIBS = libs, 89 | LIBPATH = ['/usr/local/lib', '/usr/lib', ]) 90 | 91 | env.Install('/usr/local/bin', mproxy) 92 | env.Alias('install', '/usr/local/bin') 93 | 94 | # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 95 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | 2 | # build mproxy on AppVeyor - https://ci.appveyor.com 3 | 4 | #shallow_clone: true 5 | clone_depth: 10 6 | 7 | version: '{build}' 8 | image: 9 | - Visual Studio 2017 10 | 11 | environment: 12 | LIBEVENT_VERSION: 2.1.10 13 | BOOST_ROOT: C:\Libraries\boost_1_59_0 14 | BOOST_LIBRARYDIR: C:\Libraries\boost_1_59_0\lib64-msvc-14.0 15 | 16 | matrix: 17 | # build without shadowsocks protocol 18 | - ENABLE_SS: OFF 19 | USE_CRYPTO_OPENSSL: OFF 20 | USE_CRYPTO_MBEDTLS: OFF 21 | CMAKE_GENERATOR: "Visual Studio 15 2017 Win64" 22 | BUILD_SUFFIX: "vc2017_x64" 23 | BITS: 64 24 | 25 | # build with openssl library 26 | - ENABLE_SS: ON 27 | USE_CRYPTO_OPENSSL: ON 28 | USE_CRYPTO_MBEDTLS: OFF 29 | CMAKE_GENERATOR: "Visual Studio 15 2017 Win64" 30 | BUILD_SUFFIX: "openssl_vc2017_x64" 31 | BITS: 64 32 | OPENSSL_VERSION: 1_1_1j 33 | OPENSSL_DIR: C:\OpenSSL 34 | OPENSSL_ROOT_DIR: C:\OpenSSL 35 | 36 | # build with mbed TLS library 37 | - ENABLE_SS: ON 38 | USE_CRYPTO_OPENSSL: OFF 39 | USE_CRYPTO_MBEDTLS: ON 40 | MBEDTLS_VERSION: 2.16.6 41 | CMAKE_GENERATOR: "Visual Studio 15 2017 Win64" 42 | BUILD_SUFFIX: "mbedtls_vc2017_x64" 43 | BITS: 64 44 | 45 | # x86 build with mbed TLS library 46 | - ENABLE_SS: ON 47 | USE_CRYPTO_OPENSSL: OFF 48 | USE_CRYPTO_MBEDTLS: ON 49 | MBEDTLS_VERSION: 2.16.6 50 | CMAKE_GENERATOR: "Visual Studio 15 2017" 51 | BUILD_SUFFIX: "mbedtls_vc2017_x86" 52 | BITS: 32 53 | 54 | # build https proxy with openssl library 55 | #- ENABLE_SS: ON 56 | # ENABLE_HTTPS_PROXY: ON 57 | # USE_CRYPTO_OPENSSL: ON 58 | # USE_CRYPTO_MBEDTLS: OFF 59 | 60 | install: 61 | - ECHO "Filesystem root:" 62 | - ps: "ls \"C:/\"" 63 | # recursive clone 64 | - git submodule update --init --recursive --depth 3 65 | # VC env 66 | - '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars%BITS%.bat"' 67 | # install OpenSSL 68 | - mkdir C:\OpenSSL 69 | - ps: if (Test-Path env:OPENSSL_VERSION) { Start-FileDownload "http://slproweb.com/download/Win${env:BITS}OpenSSL-${env:OPENSSL_VERSION}.exe" } 70 | - if defined OPENSSL_VERSION Win%BITS%OpenSSL-%OPENSSL_VERSION%.exe /SILENT /VERYSILENT /SP- /DIR="C:\OpenSSL" 71 | #- appveyor DownloadFile https://curl.haxx.se/ca/cacert.pem -FileName C:\OpenSSL\cacert.pem 72 | # mbedTLS 73 | - cd \ 74 | - if defined MBEDTLS_VERSION appveyor DownloadFile https://tls.mbed.org/download/mbedtls-%MBEDTLS_VERSION%-apache.tgz 75 | - if defined MBEDTLS_VERSION 7z x mbedtls-%MBEDTLS_VERSION%-apache.tgz -so | 7z x -si -ttar > nul 76 | - if defined MBEDTLS_VERSION cd mbedtls-%MBEDTLS_VERSION% 77 | - if defined MBEDTLS_VERSION mkdir lib 78 | - if defined MBEDTLS_VERSION mkdir cmake-build 79 | - if defined MBEDTLS_VERSION cd cmake-build 80 | - if defined MBEDTLS_VERSION cmake -G "%CMAKE_GENERATOR%" .. 81 | - if defined MBEDTLS_VERSION cmake --build . --config Release --target mbedtls 82 | - if defined MBEDTLS_VERSION move library\Release\*.lib ..\lib\ 83 | # Libevent 84 | - cd \ 85 | - appveyor DownloadFile https://github.com/libevent/libevent/releases/download/release-%LIBEVENT_VERSION%-stable/libevent-%LIBEVENT_VERSION%-stable.tar.gz 86 | - 7z x libevent-%LIBEVENT_VERSION%-stable.tar.gz -so | 7z x -si -ttar > nul 87 | - cd libevent-%LIBEVENT_VERSION%-stable 88 | - nmake -f Makefile.nmake static_libs 89 | - mkdir lib 90 | - move *.lib lib\ 91 | - move WIN32-Code\nmake\event2\* include\event2\ 92 | - move *.h include\ 93 | - cd .. 94 | # 95 | - cd %APPVEYOR_BUILD_FOLDER% 96 | 97 | 98 | build_script: 99 | - set PATH=C:\ProgramData\chocolatey\bin;C:\apache-ant-1.9.6\bin;%PATH% 100 | - set JAVA_HOME=C:\Program Files\Java\jdk1.7.0 101 | - set PATH=%JAVA_HOME%\bin;%PATH% 102 | # - set PATH=%PATH%;C:\Program Files (x86)\Haskell Platform\2014.2.0.0\bin 103 | # - set PATH=%PATH%;C:\Program Files (x86)\Haskell Platform\2014.2.0.0\lib\extralibs\bin 104 | - set PATH=C:\Python27-x64\scripts;C:\Python27-x64;%PATH% 105 | - mkdir cmake-build 106 | - cd cmake-build 107 | - cmake -G "%CMAKE_GENERATOR%" -DENABLE_HTTPS_PROXY:STRING="%ENABLE_HTTPS_PROXY%" -DENABLE_SS:STRING="%ENABLE_SS%" -DUSE_CRYPTO_OPENSSL:STRING="%USE_CRYPTO_OPENSSL%" -DUSE_CRYPTO_MBEDTLS="%USE_CRYPTO_MBEDTLS%" -DLIBEVENT_ROOT=C:\libevent-%LIBEVENT_VERSION%-stable -DMBEDTLS_ROOT_DIR=C:\mbedtls-%MBEDTLS_VERSION% -DBOOST_ROOT="%BOOST_ROOT%" -DBOOST_LIBRARYDIR="%BOOST_LIBRARYDIR%" .. 108 | - cmake --build . --config Release 109 | # TODO: 110 | # - cpack 111 | # - ctest 112 | 113 | artifacts: 114 | - path: cmake-build\Release 115 | name: mproxy_$(BUILD_SUFFIX) 116 | 117 | deploy: 118 | #release: mproxy_v$(appveyor_build_version) 119 | #description: 'Release description' 120 | provider: GitHub 121 | auth_token: 122 | secure: wFxle0z6fJTg0aVgEyl46GbOPGvVb/WvnNmmO5ifTaBQx5Q3qlhlfwwIpuABfuty 123 | artifact: /mproxy_.*/ 124 | draft: true 125 | prerelease: false 126 | on: 127 | appveyor_repo_tag: true # deploy on tag push only 128 | 129 | -------------------------------------------------------------------------------- /bsd_getopt.c: -------------------------------------------------------------------------------- 1 | /*- 2 | * Copyright (c) 2000 The NetBSD Foundation, Inc. 3 | * All rights reserved. 4 | * 5 | * This code is derived from software contributed to The NetBSD Foundation 6 | * by Dieter Baron and Thomas Klausner. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions 10 | * are met: 11 | * 1. Redistributions of source code must retain the above copyright 12 | * notice, this list of conditions and the following disclaimer. 13 | * 2. Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * 3. All advertising materials mentioning features or use of this software 17 | * must display the following acknowledgement: 18 | * This product includes software developed by the NetBSD 19 | * Foundation, Inc. and its contributors. 20 | * 4. Neither the name of The NetBSD Foundation nor the names of its 21 | * contributors may be used to endorse or promote products derived 22 | * from this software without specific prior written permission. 23 | * 24 | * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 25 | * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 26 | * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 27 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 28 | * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 29 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 30 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 31 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 32 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 33 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 34 | * POSSIBILITY OF SUCH DAMAGE. 35 | */ 36 | 37 | #include "bsd_getopt.h" 38 | #include 39 | #include 40 | #include 41 | 42 | #ifdef WIN32 43 | #include 44 | #else 45 | #define _tcslen strlen 46 | #define _tcsncmp strncmp 47 | #define _tcschr strchr 48 | #define _ftprintf fprintf 49 | 50 | #define _T(x) x 51 | #endif 52 | 53 | #if !defined(HAVE_GETOPT_LONG) 54 | int opterr = 1; /* if error message should be printed */ 55 | int optind = 1; /* index into parent argv vector */ 56 | int optopt = '?'; /* character checked for validity */ 57 | int optreset; /* reset getopt */ 58 | TCHAR *optarg; /* argument associated with option */ 59 | 60 | #define IGNORE_FIRST (*options == '-' || *options == '+') 61 | #define PRINT_ERROR ((opterr) && ((*options != ':') \ 62 | || (IGNORE_FIRST && options[1] != ':'))) 63 | #define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL) 64 | #define PERMUTE (!IS_POSIXLY_CORRECT && !IGNORE_FIRST) 65 | /* XXX: GNU ignores PC if *options == '-' */ 66 | #define IN_ORDER (!IS_POSIXLY_CORRECT && *options == '-') 67 | 68 | /* return values */ 69 | #define BADCH (int)'?' 70 | #define BADARG ((IGNORE_FIRST && options[1] == ':') \ 71 | || (*options == ':') ? (int)':' : (int)'?') 72 | #define INORDER (int)1 73 | 74 | #define EMSG _T("") 75 | 76 | static int getopt_internal(int, TCHAR * const *, const TCHAR *); 77 | static int gcd(int, int); 78 | static void permute_args(int, int, int, TCHAR * const *); 79 | 80 | static TCHAR *place = EMSG; /* option letter processing */ 81 | 82 | /* XXX: set optreset to 1 rather than these two */ 83 | static int nonopt_start = -1; /* first non option argument (for permute) */ 84 | static int nonopt_end = -1; /* first option after non options (for permute) */ 85 | 86 | /* Error messages */ 87 | static const TCHAR recargchar[] = _T("option requires an argument -- %c\n"); 88 | static const TCHAR recargstring[] = _T("option requires an argument -- %s\n"); 89 | static const TCHAR ambig[] = _T("ambiguous option -- %.*s\n"); 90 | static const TCHAR noarg[] = _T("option doesn't take an argument -- %.*s\n"); 91 | static const TCHAR illoptchar[] = _T("unknown option -- %c\n"); 92 | static const TCHAR illoptstring[] = _T("unknown option -- %s\n"); 93 | 94 | 95 | /* 96 | * Compute the greatest common divisor of a and b. 97 | */ 98 | static int 99 | gcd(int a, int b) 100 | { 101 | int c; 102 | 103 | c = a % b; 104 | while (c != 0) { 105 | a = b; 106 | b = c; 107 | c = a % b; 108 | } 109 | 110 | return b; 111 | } 112 | 113 | /* 114 | * Exchange the block from nonopt_start to nonopt_end with the block 115 | * from nonopt_end to opt_end (keeping the same order of arguments 116 | * in each block). 117 | */ 118 | static void 119 | permute_args(int panonopt_start, 120 | int panonopt_end, 121 | int opt_end, 122 | TCHAR * const *nargv) 123 | { 124 | int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; 125 | TCHAR *swap; 126 | 127 | /* 128 | * compute lengths of blocks and number and size of cycles 129 | */ 130 | nnonopts = panonopt_end - panonopt_start; 131 | nopts = opt_end - panonopt_end; 132 | ncycle = gcd(nnonopts, nopts); 133 | cyclelen = (opt_end - panonopt_start) / ncycle; 134 | 135 | for (i = 0; i < ncycle; i++) { 136 | cstart = panonopt_end+i; 137 | pos = cstart; 138 | for (j = 0; j < cyclelen; j++) { 139 | if (pos >= panonopt_end) 140 | pos -= nnonopts; 141 | else 142 | pos += nopts; 143 | swap = nargv[pos]; 144 | /* LINTED const cast */ 145 | ((TCHAR **) nargv)[pos] = nargv[cstart]; 146 | /* LINTED const cast */ 147 | ((TCHAR **)nargv)[cstart] = swap; 148 | } 149 | } 150 | } 151 | 152 | /* 153 | * getopt_internal -- 154 | * Parse argc/argv argument vector. Called by user level routines. 155 | * Returns -2 if -- is found (can be long option or end of options marker). 156 | */ 157 | static int 158 | getopt_internal(int nargc, 159 | TCHAR * const *nargv, 160 | const TCHAR *options) 161 | { 162 | TCHAR *oli; /* option letter list index */ 163 | int optchar; 164 | 165 | optarg = NULL; 166 | 167 | /* 168 | * XXX Some programs (like rsyncd) expect to be able to 169 | * XXX re-initialize optind to 0 and have getopt_long(3) 170 | * XXX properly function again. Work around this braindamage. 171 | */ 172 | if (optind == 0) 173 | optind = 1; 174 | 175 | if (optreset) 176 | nonopt_start = nonopt_end = -1; 177 | start: 178 | if (optreset || !*place) { /* update scanning pointer */ 179 | optreset = 0; 180 | if (optind >= nargc) { /* end of argument vector */ 181 | place = EMSG; 182 | if (nonopt_end != -1) { 183 | /* do permutation, if we have to */ 184 | permute_args(nonopt_start, nonopt_end, 185 | optind, nargv); 186 | optind -= nonopt_end - nonopt_start; 187 | } 188 | else if (nonopt_start != -1) { 189 | /* 190 | * If we skipped non-options, set optind 191 | * to the first of them. 192 | */ 193 | optind = nonopt_start; 194 | } 195 | nonopt_start = nonopt_end = -1; 196 | return -1; 197 | } 198 | if ((*(place = nargv[optind]) != '-') 199 | || (place[1] == '\0')) { /* found non-option */ 200 | place = EMSG; 201 | if (IN_ORDER) { 202 | /* 203 | * GNU extension: 204 | * return non-option as argument to option 1 205 | */ 206 | optarg = nargv[optind++]; 207 | return INORDER; 208 | } 209 | if (!PERMUTE) { 210 | /* 211 | * if no permutation wanted, stop parsing 212 | * at first non-option 213 | */ 214 | return -1; 215 | } 216 | /* do permutation */ 217 | if (nonopt_start == -1) 218 | nonopt_start = optind; 219 | else if (nonopt_end != -1) { 220 | permute_args(nonopt_start, nonopt_end, 221 | optind, nargv); 222 | nonopt_start = optind - 223 | (nonopt_end - nonopt_start); 224 | nonopt_end = -1; 225 | } 226 | optind++; 227 | /* process next argument */ 228 | goto start; 229 | } 230 | if (nonopt_start != -1 && nonopt_end == -1) 231 | nonopt_end = optind; 232 | if (place[1] && *++place == '-') { /* found "--" */ 233 | place++; 234 | return -2; 235 | } 236 | } 237 | if ((optchar = (int)*place++) == (int)':' || 238 | (oli = _tcschr(options + (IGNORE_FIRST ? 1 : 0), optchar)) == NULL) { 239 | /* option letter unknown or ':' */ 240 | if (!*place) 241 | ++optind; 242 | if (PRINT_ERROR) 243 | _ftprintf(stderr, illoptchar, optchar); 244 | optopt = optchar; 245 | return BADCH; 246 | } 247 | if (optchar == 'W' && oli[1] == ';') { /* -W long-option */ 248 | /* XXX: what if no long options provided (called by getopt)? */ 249 | if (*place) 250 | return -2; 251 | 252 | if (++optind >= nargc) { /* no arg */ 253 | place = EMSG; 254 | if (PRINT_ERROR) 255 | _ftprintf(stderr, recargchar, optchar); 256 | optopt = optchar; 257 | return BADARG; 258 | } else /* white space */ 259 | place = nargv[optind]; 260 | /* 261 | * Handle -W arg the same as --arg (which causes getopt to 262 | * stop parsing). 263 | */ 264 | return -2; 265 | } 266 | if (*++oli != ':') { /* doesn't take argument */ 267 | if (!*place) 268 | ++optind; 269 | } else { /* takes (optional) argument */ 270 | optarg = NULL; 271 | if (*place) /* no white space */ 272 | optarg = place; 273 | /* XXX: disable test for :: if PC? (GNU doesn't) */ 274 | else if (oli[1] != ':') { /* arg not optional */ 275 | if (++optind >= nargc) { /* no arg */ 276 | place = EMSG; 277 | if (PRINT_ERROR) 278 | _ftprintf(stderr, recargchar, optchar); 279 | optopt = optchar; 280 | return BADARG; 281 | } else 282 | optarg = nargv[optind]; 283 | } 284 | place = EMSG; 285 | ++optind; 286 | } 287 | /* dump back option letter */ 288 | return optchar; 289 | } 290 | 291 | /* 292 | * getopt -- 293 | * Parse argc/argv argument vector. 294 | * 295 | * [eventually this will replace the real getopt] 296 | */ 297 | int 298 | getopt(int nargc, TCHAR * const *nargv, const TCHAR *options) 299 | { 300 | int retval; 301 | 302 | if ((retval = getopt_internal(nargc, nargv, options)) == -2) { 303 | ++optind; 304 | /* 305 | * We found an option (--), so if we skipped non-options, 306 | * we have to permute. 307 | */ 308 | if (nonopt_end != -1) { 309 | permute_args(nonopt_start, nonopt_end, optind, 310 | nargv); 311 | optind -= nonopt_end - nonopt_start; 312 | } 313 | nonopt_start = nonopt_end = -1; 314 | retval = -1; 315 | } 316 | return retval; 317 | } 318 | 319 | /* 320 | * getopt_long -- 321 | * Parse argc/argv argument vector. 322 | */ 323 | int 324 | getopt_long(int nargc, 325 | TCHAR * const *nargv, 326 | const TCHAR *options, 327 | const struct option *long_options, 328 | int *idx) 329 | { 330 | int retval; 331 | 332 | /* idx may be NULL */ 333 | 334 | if ((retval = getopt_internal(nargc, nargv, options)) == -2) { 335 | TCHAR *current_argv, *has_equal; 336 | size_t current_argv_len; 337 | int i, match; 338 | 339 | current_argv = place; 340 | match = -1; 341 | 342 | optind++; 343 | place = EMSG; 344 | 345 | if (*current_argv == '\0') { /* found "--" */ 346 | /* 347 | * We found an option (--), so if we skipped 348 | * non-options, we have to permute. 349 | */ 350 | if (nonopt_end != -1) { 351 | permute_args(nonopt_start, nonopt_end, 352 | optind, nargv); 353 | optind -= nonopt_end - nonopt_start; 354 | } 355 | nonopt_start = nonopt_end = -1; 356 | return -1; 357 | } 358 | if ((has_equal = _tcschr(current_argv, _T('='))) != NULL) { 359 | /* argument found (--option=arg) */ 360 | current_argv_len = has_equal - current_argv; 361 | has_equal++; 362 | } else 363 | current_argv_len = _tcslen(current_argv); 364 | 365 | for (i = 0; long_options[i].name; i++) { 366 | /* find matching long option */ 367 | if (_tcsncmp(current_argv, long_options[i].name, 368 | current_argv_len)) 369 | continue; 370 | 371 | if (_tcslen(long_options[i].name) == 372 | (unsigned)current_argv_len) { 373 | /* exact match */ 374 | match = i; 375 | break; 376 | } 377 | if (match == -1) /* partial match */ 378 | match = i; 379 | else { 380 | /* ambiguous abbreviation */ 381 | if (PRINT_ERROR) 382 | _ftprintf(stderr, ambig, (int)current_argv_len, 383 | current_argv); 384 | optopt = 0; 385 | return BADCH; 386 | } 387 | } 388 | if (match != -1) { /* option found */ 389 | if (long_options[match].has_arg == no_argument 390 | && has_equal) { 391 | if (PRINT_ERROR) 392 | _ftprintf(stderr, noarg, (int)current_argv_len, 393 | current_argv); 394 | /* 395 | * XXX: GNU sets optopt to val regardless of 396 | * flag 397 | */ 398 | if (long_options[match].flag == NULL) 399 | optopt = long_options[match].val; 400 | else 401 | optopt = 0; 402 | return BADARG; 403 | } 404 | if (long_options[match].has_arg == required_argument || 405 | long_options[match].has_arg == optional_argument) { 406 | if (has_equal) 407 | optarg = has_equal; 408 | else if (long_options[match].has_arg == 409 | required_argument) { 410 | /* 411 | * optional argument doesn't use 412 | * next nargv 413 | */ 414 | optarg = nargv[optind++]; 415 | } 416 | } 417 | if ((long_options[match].has_arg == required_argument) 418 | && (optarg == NULL)) { 419 | /* 420 | * Missing argument; leading ':' 421 | * indicates no error should be generated 422 | */ 423 | if (PRINT_ERROR) 424 | _ftprintf(stderr, recargstring, current_argv); 425 | /* 426 | * XXX: GNU sets optopt to val regardless 427 | * of flag 428 | */ 429 | if (long_options[match].flag == NULL) 430 | optopt = long_options[match].val; 431 | else 432 | optopt = 0; 433 | --optind; 434 | return BADARG; 435 | } 436 | } else { /* unknown option */ 437 | if (PRINT_ERROR) 438 | _ftprintf(stderr, illoptstring, current_argv); 439 | optopt = 0; 440 | return BADCH; 441 | } 442 | if (long_options[match].flag) { 443 | *long_options[match].flag = long_options[match].val; 444 | retval = 0; 445 | } else 446 | retval = long_options[match].val; 447 | if (idx) 448 | *idx = match; 449 | } 450 | return retval; 451 | } 452 | #endif /* !GETOPT_LONG || !GETOPT */ 453 | -------------------------------------------------------------------------------- /bsd_getopt.h: -------------------------------------------------------------------------------- 1 | /* bsd_getopt.h 2 | * 3 | * Chris Collins 4 | */ 5 | 6 | /** header created for NetBSD getopt/getopt_long */ 7 | 8 | #ifndef HAVE_GETOPT_LONG 9 | #ifndef _BSD_GETOPT_H 10 | #define _BSD_GETOPT_H 11 | 12 | #ifdef WIN32 13 | #include 14 | #else 15 | #define TCHAR char 16 | #endif 17 | 18 | #ifdef __cplusplus 19 | extern "C" { 20 | #endif 21 | 22 | extern int opterr; /* prevent the error message by setting opterr to 0 */ 23 | extern int optind; 24 | extern int optopt; 25 | extern int optreset; 26 | extern TCHAR *optarg; 27 | 28 | struct option { 29 | TCHAR *name; 30 | int has_arg; 31 | int *flag; 32 | int val; 33 | }; 34 | 35 | #define no_argument 0 36 | #define required_argument 1 37 | #define optional_argument 2 38 | 39 | extern int getopt(int nargc, TCHAR * const *nargv, const TCHAR *options); 40 | extern int getopt_long(int nargc, TCHAR * const *nargv, const TCHAR *options, const struct option *long_options, int *idx); 41 | 42 | #ifdef __cplusplus 43 | } /* extern "C" */ 44 | #endif 45 | 46 | #endif /* _BSD_GETOPT_H */ 47 | #endif 48 | -------------------------------------------------------------------------------- /connector.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include "connector.h" 13 | 14 | const char *socks5_strstatus[] = { 15 | "ok", 16 | "server failure", 17 | "connection not allowed by ruleset", 18 | "network unreachable", 19 | "host unreachable", 20 | "connection refused", 21 | "TTL expired", 22 | "command not supported", 23 | "address type not supported", 24 | }; 25 | 26 | enum socks5_conn_status { 27 | SCONN_TCP_INIT = 0, 28 | SCONN_INIT = 100, 29 | SCONN_AUTH_METHODS_SENT, 30 | SCONN_REQUEST_SENT, 31 | SCONN_CONNECT_TRANSMITTING, 32 | SCONN_ERROR 33 | }; 34 | 35 | #define SOCKS5_AUTH_NONE (0x00) 36 | #define SOCKS5_AUTH_UNACCEPTABLE (0xFF) 37 | 38 | #define SOCKS5_CMD_CONNECT (0x01) 39 | #define SOCKS5_CMD_BIND (0x02) 40 | #define SOCKS5_CMD_UDP_ASSOC (0x03) 41 | #define SOCKS5_CMD_VALID(cmd) \ 42 | (((cmd) > 0x00) && ((cmd) < 0x04)) 43 | 44 | #define SOCKS5_ATYPE_IPV4 (0x01) 45 | #define SOCKS5_ATYPE_DOMAIN (0x03) 46 | #define SOCKS5_ATYPE_IPV6 (0x04) 47 | #define SOCKS5_ATYPE_VALID(cmd) \ 48 | (((cmd) > 0x00) && ((cmd) < 0x05) && ((cmd) != 0x02)) 49 | 50 | #define SOCKS5_REP_SUCCEEDED (0x00) 51 | #define SOCKS5_REP_GENERAL_FAILURE (0x01) 52 | #define SOCKS5_REP_NOT_ALLOWED (0x02) 53 | #define SOCKS5_REP_NET_UNREACHABLE (0x03) 54 | #define SOCKS5_REP_HOST_UNREACHABLE (0x04) 55 | #define SOCKS5_REP_CONN_REFUSED (0x05) 56 | #define SOCKS5_REP_TTL_EXPIRED (0x06) 57 | #define SOCKS5_REP_BAD_COMMAND (0x07) 58 | #define SOCKS5_REP_ATYPE_UNSUPPORTED (0x08) 59 | 60 | /* 61 | * socks5_conn 62 | */ 63 | typedef struct socks5_conn_t { 64 | struct bufferevent *client; 65 | //struct bufferevent *dst; 66 | enum socks5_conn_status status; 67 | // unsigned char auth_method; 68 | // unsigned char command; 69 | char host[256]; 70 | uint16_t port; 71 | connect_callback cb; 72 | void *arg; 73 | } socks5_conn; 74 | 75 | static void send_auth_methods(socks5_conn *conn) 76 | { 77 | char data[] = {0x05, 0x01, 0x00}; // version 5 no authentication 78 | bufferevent_write(conn->client, data, sizeof(data)); 79 | conn->status = SCONN_AUTH_METHODS_SENT; 80 | 81 | bufferevent_enable(conn->client, EV_READ | EV_WRITE); 82 | } 83 | 84 | static void send_request(socks5_conn *conn) 85 | { 86 | char data[7 + 255] = {0x05, 0x01, 0x00}; // version 5 connect 87 | data[3] = 0x03; // domain 88 | size_t domain_len = strlen(conn->host); 89 | assert(domain_len <= 255); 90 | uint16_t net_port = htons(conn->port); 91 | 92 | data[4] = domain_len; 93 | memcpy(data + 5, conn->host, domain_len); 94 | memcpy(data + 5 + domain_len, &net_port, 2); 95 | 96 | bufferevent_write(conn->client, data, 3 + 1 + 1 + domain_len + 2); 97 | 98 | conn->status = SCONN_REQUEST_SENT; 99 | } 100 | 101 | static void read_auth_methods(socks5_conn *conn) 102 | { 103 | char data[2] = {0}; 104 | struct evbuffer *buffer; 105 | size_t have; 106 | 107 | buffer = bufferevent_get_input(conn->client); 108 | have = evbuffer_get_length(buffer); 109 | 110 | if (have < 2) // 111 | goto needmore; 112 | 113 | evbuffer_copyout(buffer, data, 2); 114 | 115 | if (data[0] != 0x05) { 116 | // ERROR protocol version 117 | goto fail; 118 | } 119 | 120 | if (data[1] != 0x00) { 121 | /* 122 | o X'00' NO AUTHENTICATION REQUIRED 123 | o X'01' GSSAPI 124 | o X'02' USERNAME/PASSWORD 125 | o X'03' to X'7F' IANA ASSIGNED 126 | o X'80' to X'FE' RESERVED FOR PRIVATE METHODS 127 | o X'FF' NO ACCEPTABLE METHODS 128 | */ 129 | goto fail; 130 | } 131 | 132 | evbuffer_drain(buffer, 2); 133 | send_request(conn); 134 | return; 135 | 136 | fail: 137 | conn->status = SCONN_ERROR; 138 | return; 139 | 140 | needmore: 141 | return; 142 | } 143 | 144 | static void read_reply(socks5_conn *conn) 145 | { 146 | uint8_t data[7 + 255] = {0}; 147 | struct evbuffer *buffer; 148 | size_t have, consume = 0; 149 | 150 | buffer = bufferevent_get_input(conn->client); 151 | have = evbuffer_get_length(buffer); 152 | 153 | if (have < 8) // domain at least 1 byte 154 | goto needmore; 155 | 156 | evbuffer_copyout(buffer, data, 8); 157 | if (data[0] != 0x05) { 158 | // ERROR protocol version 159 | goto fail; 160 | } 161 | 162 | if (data[1] != 0x00) { 163 | /* 164 | o X'00' succeeded 165 | o X'01' general SOCKS server failure 166 | o X'02' connection not allowed by ruleset 167 | o X'03' Network unreachable 168 | o X'04' Host unreachable 169 | o X'05' Connection refused 170 | o X'06' TTL expired 171 | o X'07' Command not supported 172 | o X'08' Address type not supported 173 | o X'09' to X'FF' unassigned 174 | */ 175 | goto fail; 176 | } 177 | 178 | uint8_t atype = data[3]; 179 | 180 | if (atype == SOCKS5_ATYPE_IPV4) { 181 | if (have < 10) 182 | goto needmore; 183 | 184 | consume = 10; 185 | } else if (atype == SOCKS5_ATYPE_IPV6) { 186 | if (have < 22) 187 | goto needmore; 188 | 189 | consume = 22; 190 | } else if (atype == SOCKS5_ATYPE_DOMAIN) { 191 | unsigned char addrlen; 192 | 193 | addrlen = data[4]; 194 | if (have < (7 + addrlen)) 195 | goto needmore; 196 | 197 | consume = 7 + addrlen; 198 | } else { 199 | goto fail ; // Unknown address type 200 | } 201 | 202 | evbuffer_drain(buffer, consume); 203 | conn->status = SCONN_CONNECT_TRANSMITTING; 204 | return; 205 | 206 | fail: 207 | conn->status = SCONN_ERROR; 208 | 209 | needmore: 210 | return; 211 | } 212 | 213 | static void readcb(struct bufferevent *bev, void *ctx) 214 | { 215 | socks5_conn *conn = (socks5_conn*)ctx; 216 | 217 | switch (conn->status) 218 | { 219 | case SCONN_AUTH_METHODS_SENT: 220 | read_auth_methods(conn); 221 | break; 222 | case SCONN_REQUEST_SENT: 223 | read_reply(conn); 224 | break; 225 | default: 226 | break; 227 | } 228 | 229 | if (conn->status == SCONN_CONNECT_TRANSMITTING) { 230 | LOGD("SOCKS5 negotiate successfully"); 231 | bufferevent_setcb(bev, NULL, NULL, NULL, NULL); 232 | 233 | conn->cb(bev, conn->arg); 234 | 235 | free(conn); 236 | } else if (conn->status == SCONN_ERROR) { 237 | LOGE("SOCKS5 encounter unknown response during negotiate"); 238 | // error 239 | conn->cb(NULL, conn->arg); 240 | 241 | free(conn); 242 | bufferevent_free(bev); // protocol error, close socket 243 | } 244 | } 245 | 246 | static void eventcb(struct bufferevent *bev, short what, void *ctx) 247 | { 248 | socks5_conn *conn = (socks5_conn*)ctx; 249 | if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) { 250 | char buf[4096] = {'\0'}; 251 | // during handshake, EOF is an error also 252 | LOGE("bev %p (sock %d) event: 0x%hx %s", bev, bufferevent_getfd(bev), what, socket_error(buf, sizeof(buf))); 253 | 254 | // error 255 | conn->cb(NULL, conn->arg); 256 | 257 | free(conn); 258 | bufferevent_free(bev); 259 | } else if (what & BEV_EVENT_CONNECTED) { 260 | LOGD("upstrem connected with bev %p (sock %d)", bev, bufferevent_getfd(bev)); 261 | #if defined TCP_NODELAY 262 | if (g_enable_nodelay == 1) { 263 | int on = 1; 264 | setsockopt(bufferevent_getfd(bev), IPPROTO_TCP, TCP_NODELAY, (void *)&on, sizeof(on)); 265 | } 266 | #endif 267 | 268 | if (conn->status == SCONN_INIT) { 269 | /* socks5 */ 270 | send_auth_methods(conn); 271 | } else { 272 | /* TCP */ 273 | bufferevent_setcb(bev, NULL, NULL, NULL, NULL); 274 | 275 | conn->cb(bev, conn->arg); 276 | 277 | free(conn); 278 | } 279 | } 280 | } 281 | 282 | void connect_socks5(struct event_base *evbase, struct evdns_base *evdns_base, const char *hostname, int port, connect_callback cb, void *arg) 283 | { 284 | struct bufferevent *bev = NULL; 285 | socks5_conn *conn = (socks5_conn*)calloc(1, sizeof(socks5_conn)); 286 | if (NULL == conn) { 287 | goto fail; 288 | } 289 | 290 | strcpy(conn->host, hostname); 291 | conn->port = port; 292 | conn->cb = cb; 293 | conn->arg = arg; 294 | 295 | if (g_socks_server && g_socks_port != 0) { 296 | hostname = g_socks_server; 297 | port =g_socks_port; 298 | 299 | conn->status = SCONN_INIT; 300 | } 301 | 302 | bev = bufferevent_socket_new(evbase, -1, BEV_OPT_CLOSE_ON_FREE/*|BEV_OPT_DEFER_CALLBACKS*/); 303 | if (NULL == bev) { 304 | LOGE("bufferevent create failed"); 305 | goto fail; 306 | } 307 | 308 | // eventcb() might be called in bufferevent_socket_connect_hostname(), when name resolve is done 309 | // immediately and bufferevent_socket_connect() failed immediately. 310 | // When hostname is pure IP address, or hostname is in /etc/hosts file, evutil_getaddrinfo_async() call its 311 | // callback in itself, not after. 312 | // bufferevent_socket_connect() usually failed immediately with socket() exceed ulimit open files. 313 | conn->client = bev; 314 | bufferevent_setcb(bev, readcb, NULL, eventcb, conn); /* must be set before bufferevent_socket_connect_hostname() */ 315 | 316 | if (bufferevent_socket_connect_hostname(bev, evdns_base, PF_UNSPEC, hostname, port) < 0) { 317 | LOGE("bufferevent connect %s:%d failed", hostname, port); 318 | goto fail; 319 | } 320 | 321 | // Because eventcb() might have been called, so we cannot do anything with bev or conn here. 322 | // If you want, you must use BEV_OPT_DEFER_CALLBACKS to force eventcb() executed after bufferevent_socket_connect_hostname(). 323 | 324 | return; 325 | 326 | fail: 327 | if (bev) 328 | bufferevent_free(bev); 329 | cb(NULL, arg); 330 | if (conn) 331 | free(conn); 332 | } 333 | 334 | #if 0 335 | 336 | void connect_cb(struct bufferevent *bev, void *arg) 337 | { 338 | if (bev) { 339 | fprintf(stderr, "connect success\n"); 340 | 341 | const char headers[] = 342 | "GET / HTTP/1.1\r\n" 343 | "Connection: Keep-Alive\r\n" 344 | "\r\n"; 345 | bufferevent_write(bev, headers, sizeof(headers) - 1); // without ending '\0' 346 | } else { 347 | fprintf(stderr, "connect fail\n"); 348 | } 349 | } 350 | 351 | const char *g_socks_server = "127.0.0.1"; 352 | int g_socks_port = 1080; 353 | 354 | int main( int argc, char* argv[] ) 355 | { 356 | struct event *ev_sigterm; 357 | event_base *evbase; 358 | evdns_base *evdns; 359 | 360 | #ifdef WIN32 361 | WORD wVersionRequested; 362 | WSADATA wsaData; 363 | int err; 364 | 365 | /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */ 366 | wVersionRequested = MAKEWORD(2, 2); 367 | 368 | err = WSAStartup(wVersionRequested, &wsaData); 369 | #endif 370 | 371 | evbase = event_base_new(); 372 | evdns = evdns_base_new(evbase, 1); 373 | evdns_base_set_option(evdns, "randomize-case:", "0"); 374 | 375 | #ifndef WIN32 376 | ev_sigterm = evsignal_new(evbase, SIGTERM, sigterm_cb, evbase); 377 | evsignal_add(ev_sigterm, NULL); 378 | #endif 379 | 380 | connect_socks5(evbase, evdns, "www.baidu.com", 80, connect_cb, NULL); 381 | 382 | event_base_loop(evbase, 0); 383 | 384 | printf("Clean exit\n"); 385 | return 0; 386 | } 387 | #endif 388 | -------------------------------------------------------------------------------- /connector.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include "evhtp.h" 5 | #include "utils.h" 6 | 7 | #define MAX_OUTPUT (512*1024) 8 | #define MAX_REQUEST_BODY_SIZE (1024*1024) 9 | 10 | extern struct evdns_base *evdns; 11 | 12 | const char* socket_error(char *buf, int len); 13 | 14 | extern int g_https_proxy; 15 | extern int g_enable_nodelay; 16 | 17 | typedef void (*connect_callback)(struct bufferevent *bev, void *arg); 18 | void connect_upstream(struct event_base *evbase, struct evdns_base *evdns_base, const char *hostname, int port, connect_callback cb, void *arg); 19 | /* HTTP or HTTPS */ 20 | void connect_http(struct event_base *evbase, struct evdns_base *evdns_base, const char *hostname, int port, connect_callback cb, void *arg); 21 | 22 | /* shadowsocks */ 23 | void connect_ss(struct event_base *evbase, struct evdns_base *evdns_base, const char *hostname, int port, connect_callback cb, void *arg); 24 | 25 | /* shadowsocks */ 26 | extern int g_ss_method; 27 | extern const char *g_ss_server; 28 | extern int g_ss_port; 29 | extern char *g_ss_key; 30 | 31 | /* TCP or SOCKS5 */ 32 | void connect_socks5(struct event_base *evbase, struct evdns_base *evdns_base, const char *hostname, int port, connect_callback cb, void *arg); 33 | 34 | /* SOCKS5 */ 35 | extern const char *g_socks_server; 36 | extern int g_socks_port; 37 | 38 | /* lru */ 39 | typedef void (*lru_get_callback)(evhtp_connection_t *conn, void *arg); 40 | 41 | void lru_set(const char *host, uint16_t port, evhtp_connection_t *conn); 42 | void lru_get(const char *host, uint16_t port, lru_get_callback cb, void *arg); 43 | int lru_init(evbase_t *base); 44 | void lru_fini(); 45 | 46 | 47 | -------------------------------------------------------------------------------- /dns_forward.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #ifdef _WIN32 9 | #include 10 | #else 11 | #include 12 | #include 13 | #include 14 | #endif 15 | 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | #include "dns_forward.h" 22 | #include "connector.h" 23 | #include "log.h" 24 | #include "utils.h" 25 | #include "parse_forward_param.h" 26 | 27 | #ifdef __GNUC__ 28 | # define PACK( __Declaration__ ) __Declaration__ __attribute__((__packed__)) 29 | #elif defined(_MSC_VER) 30 | # define PACK( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop)) 31 | #endif 32 | 33 | #define QID_BUCKET_SIZE 1024 34 | #define MAX_INFIGHT (QID_BUCKET_SIZE * 2) 35 | #define DEFAULT_DNS_SERVER_PORT 53 36 | 37 | /* True iff e is an error that means a read/write operation can be retried. */ 38 | #ifndef WIN32 39 | # define EVUTIL_ERR_RW_RETRIABLE(e) \ 40 | ((e) == EINTR || (e) == EAGAIN) 41 | #else 42 | # define EVUTIL_ERR_RW_RETRIABLE(e) \ 43 | ((e) == WSAEWOULDBLOCK || (e) == WSAEINTR) 44 | #endif 45 | 46 | #undef LIST_FOREACH_SAFE 47 | #define LIST_FOREACH_SAFE(var, head, field, tvar) \ 48 | for ((var) = LIST_FIRST((head)); \ 49 | (var) && ((tvar) = LIST_NEXT((var), field), 1); \ 50 | (var) = (tvar)) 51 | 52 | 53 | typedef struct dns_header_t { 54 | uint16_t id; 55 | uint8_t qr_opcode_aa_tc_rd; 56 | uint8_t ra_z_rcode; 57 | uint16_t qdcount; 58 | uint16_t ancount; 59 | uint16_t nscount; 60 | uint16_t arcount; // may be >0 for EDNS queries 61 | } dns_header; 62 | 63 | PACK(struct dns_tcp_pkt_t { 64 | uint16_t sz; 65 | union { 66 | dns_header hdr; 67 | char raw[0xffff]; 68 | } dns; 69 | }); 70 | 71 | typedef struct dns_tcp_pkt_t dns_tcp_pkt; 72 | 73 | typedef struct inflight_req_t { 74 | RB_ENTRY(inflight_req_t) next_rb; 75 | LIST_ENTRY(inflight_req_t) next; 76 | 77 | uint16_t id; // in network byte order 78 | uint16_t mapped_id; // in network byte order 79 | 80 | struct sockaddr_storage clientaddr; 81 | } inflight_req; 82 | 83 | LIST_HEAD(qid_head, inflight_req_t); 84 | 85 | static int inflight_req_compare(const inflight_req *lhs, const inflight_req *rhs) 86 | { 87 | if (lhs->id == rhs->id) { 88 | return evutil_sockaddr_cmp((const struct sockaddr *)(&lhs->clientaddr), 89 | (const struct sockaddr *)(&rhs->clientaddr), 90 | 1); 91 | } else { 92 | return lhs->id - rhs->id; 93 | } 94 | } 95 | 96 | RB_HEAD(inflight_req_tree, inflight_req_t); 97 | RB_GENERATE(inflight_req_tree, inflight_req_t, next_rb, inflight_req_compare); 98 | 99 | typedef struct dns_forwarder_t 100 | { 101 | int inflight_count; 102 | uint16_t upstream_ready:1; 103 | uint16_t dns_server_port; 104 | char *dns_server; 105 | 106 | struct event* listener; 107 | struct bufferevent *bev; // upstream dns server 108 | struct evdns_base *evdns_base; 109 | 110 | struct inflight_req_tree tree_head; 111 | struct qid_head queries_by_qid[QID_BUCKET_SIZE]; 112 | } dnsu2t_instance; 113 | 114 | 115 | static inflight_req* request_find_from_trans_id(dnsu2t_instance *instance, uint16_t trans_id) { 116 | struct qid_head *qhead = &instance->queries_by_qid[trans_id % QID_BUCKET_SIZE]; 117 | 118 | inflight_req *item = NULL; 119 | 120 | LIST_FOREACH(item, qhead, next) { 121 | if (item && item->mapped_id == trans_id) { 122 | return item; 123 | } 124 | } 125 | 126 | return NULL; 127 | } 128 | 129 | 130 | static uint16_t transaction_id_pick(dnsu2t_instance *instance) { 131 | for (;;) { 132 | uint16_t trans_id; 133 | evutil_secure_rng_get_bytes(&trans_id, sizeof(trans_id)); 134 | 135 | if (trans_id == 0xffff) continue; 136 | /* now check to see if that id is already inflight */ 137 | if (request_find_from_trans_id(instance, trans_id) == NULL) 138 | return trans_id; 139 | } 140 | } 141 | 142 | 143 | static void clear_infight_queries(dnsu2t_instance *self) 144 | { 145 | int i = 0; 146 | for (i = 0; i < QID_BUCKET_SIZE; ++i) { 147 | struct qid_head *qhead = &self->queries_by_qid[i]; 148 | 149 | inflight_req *item = NULL; 150 | inflight_req *tvar = NULL; 151 | 152 | LIST_FOREACH_SAFE(item, qhead, next, tvar) { 153 | inflight_req *ti = RB_REMOVE(inflight_req_tree, &self->tree_head, item); 154 | assert(ti == item); 155 | free(item); 156 | --self->inflight_count; 157 | } 158 | LIST_INIT(qhead); // clear list 159 | } 160 | assert(self->inflight_count == 0); 161 | } 162 | 163 | static void dns_upstream_readcb(struct bufferevent *bev, void *ctx) 164 | { 165 | dnsu2t_instance *self = ctx; 166 | for (;;) { 167 | dns_tcp_pkt in; 168 | struct evbuffer *buffer; 169 | size_t have; 170 | int sent; 171 | evutil_socket_t fd = event_get_fd(self->listener); 172 | 173 | buffer = bufferevent_get_input(self->bev); 174 | have = evbuffer_get_length(buffer); 175 | 176 | if (have < 2) // 177 | goto needmore; 178 | 179 | evbuffer_copyout(buffer, &in.sz, sizeof(in.sz)); 180 | uint16_t pktlen = ntohs(in.sz); 181 | if (pktlen < sizeof(dns_header)) { 182 | LOGE("malformed DNS reply"); 183 | goto failed; 184 | } 185 | if (have < pktlen + sizeof(in.sz)) { 186 | goto needmore; 187 | } 188 | 189 | bufferevent_read(bev, &in, pktlen + sizeof(in.sz)); 190 | uint16_t qid = in.dns.hdr.id; 191 | inflight_req* req = request_find_from_trans_id(self, qid); 192 | assert(req); 193 | in.dns.hdr.id = req->id; // restore id 194 | --self->inflight_count; 195 | RB_REMOVE(inflight_req_tree, &self->tree_head, req); 196 | // struct qid_head *qhead = &self->queries_by_qid[qid % QID_BUCKET_SIZE]; 197 | LIST_REMOVE(req, next); 198 | 199 | sent = sendto(fd, in.dns.raw, pktlen, 0, 200 | (struct sockaddr*)&req->clientaddr, sizeof(req->clientaddr) 201 | ); 202 | free(req); 203 | if (sent < 0) { 204 | int err = evutil_socket_geterror(fd); 205 | if (EVUTIL_ERR_RW_RETRIABLE(err)) 206 | return; 207 | LOGE("Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err), err); 208 | } 209 | } 210 | return; 211 | 212 | failed: 213 | self->bev = NULL; 214 | self->upstream_ready = 0; 215 | clear_infight_queries(self); 216 | bufferevent_free(bev); 217 | return; 218 | 219 | needmore: 220 | return; 221 | } 222 | 223 | static void dns_upstream_eventcb(struct bufferevent *bev, short what, void *ctx) 224 | { 225 | dnsu2t_instance *self = ctx; 226 | if (what & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) { 227 | LOGI("dns upstream bev %p (sock %d) event: 0x%hx", bev, bufferevent_getfd(bev), what); 228 | 229 | // error 230 | self->bev = NULL; 231 | self->upstream_ready = 0; 232 | clear_infight_queries(self); 233 | 234 | bufferevent_free(bev); 235 | } 236 | } 237 | 238 | static void dns_upstream_connect_cb(struct bufferevent *bev, void *arg) 239 | { 240 | int error; 241 | dnsu2t_instance *self = arg; 242 | struct event_base *base = event_get_base(self->listener); 243 | struct evdns_base *evdns = self->evdns_base; 244 | 245 | if (NULL == bev) { 246 | LOGE("connect upstream failed, retry"); 247 | connect_upstream(base, evdns, self->dns_server, self->dns_server_port, dns_upstream_connect_cb, self); 248 | return; 249 | } 250 | error = event_add(self->listener, NULL); 251 | if (error) { 252 | LOGE("enable dns listener event failed"); 253 | exit(1); 254 | } 255 | self->bev = bev; 256 | self->upstream_ready = 1; 257 | bufferevent_setcb(bev, dns_upstream_readcb, NULL, dns_upstream_eventcb, self); 258 | bufferevent_enable(bev, EV_READ); 259 | } 260 | 261 | static void dns_read_request(int srvfd, short what, void *arg) 262 | { 263 | dnsu2t_instance *self = arg; 264 | struct sockaddr_storage ss; 265 | ev_socklen_t addrlen = sizeof(ss); 266 | dns_tcp_pkt in; 267 | 268 | assert(self->listener); 269 | struct event_base *base = event_get_base(self->listener); 270 | struct evdns_base *evdns = self->evdns_base; 271 | 272 | assert(srvfd == event_get_fd(self->listener)); 273 | if (! (self->bev && self->upstream_ready)) { 274 | event_del(self->listener); 275 | connect_upstream(base, evdns, self->dns_server, self->dns_server_port, dns_upstream_connect_cb, self); 276 | return; 277 | } 278 | 279 | for (;;) { 280 | const int r = 281 | recvfrom(srvfd, in.dns.raw, sizeof(in.dns.raw), 0, (struct sockaddr *)&ss, &addrlen); 282 | if (r < 0) { 283 | int err = evutil_socket_geterror(srvfd); 284 | if (EVUTIL_ERR_RW_RETRIABLE(err)) 285 | return; 286 | LOGE("recvfrom failed: %s", evutil_socket_error_to_string(err)); 287 | return; 288 | } 289 | if (r < sizeof(dns_header) || r > 65536) { 290 | LOGE("invalid dns rquest"); 291 | continue; 292 | } 293 | 294 | inflight_req *key = (inflight_req*)calloc(1, sizeof(inflight_req)); 295 | key->id = in.dns.hdr.id; 296 | memcpy(&key->clientaddr, &ss, addrlen); 297 | 298 | // find 299 | inflight_req *req = RB_FIND(inflight_req_tree, &self->tree_head, key); 300 | if (req) { 301 | // dns query re-transmission 302 | continue; 303 | } 304 | 305 | if (self->inflight_count > MAX_INFIGHT) { 306 | // too many inflight queries, ignore new queries 307 | continue; 308 | } 309 | 310 | uint16_t trans_id = transaction_id_pick(self); 311 | 312 | key->mapped_id = trans_id; 313 | in.dns.hdr.id = trans_id; 314 | in.sz = htons(r); 315 | bufferevent_write(self->bev, &in, r + 2); 316 | 317 | self->inflight_count++; 318 | 319 | // insert into client rb tree 320 | if (RB_INSERT(inflight_req_tree, &self->tree_head, key)) { 321 | LOGE("insert into rb tree failed"); 322 | continue; 323 | } 324 | 325 | // insert into relay list 326 | struct qid_head *qhead = &self->queries_by_qid[trans_id % QID_BUCKET_SIZE]; 327 | LIST_INSERT_HEAD(qhead, key, next); 328 | } 329 | } 330 | 331 | void dns_forwarder_free(struct dns_forwarder_t *instance) 332 | { 333 | if (!instance) { 334 | return; 335 | } 336 | if (instance->bev) { 337 | bufferevent_free(instance->bev); 338 | instance->bev = NULL; 339 | } 340 | 341 | if (instance->listener && event_initialized(instance->listener)) { 342 | if (event_del(instance->listener) != 0) 343 | LOGE("event_del failed"); 344 | if (evutil_closesocket(event_get_fd(instance->listener)) != 0) 345 | LOGE("close listener fd failed"); 346 | event_free(instance->listener); 347 | instance->listener = NULL; 348 | } 349 | 350 | clear_infight_queries(instance); 351 | free(instance->dns_server); 352 | instance->dns_server = NULL; 353 | 354 | memset(instance, 0, sizeof(*instance)); 355 | free(instance); 356 | } 357 | 358 | struct dns_forwarder_t* dns_forwarder_new(struct event_base *evbase, struct evdns_base *evdns_base, struct forwarder_param_t *param) 359 | { 360 | evutil_socket_t fd = -1; 361 | int on = 1; 362 | int error; 363 | int i; 364 | char bindaddr[INET6_ADDRSTRLEN + 6] = {0}; 365 | dnsu2t_instance *instance = calloc(1, sizeof(dnsu2t_instance)); 366 | instance->evdns_base = evdns_base; 367 | instance->dns_server = strdup(param->forward_ip); 368 | instance->dns_server_port = param->forward_port; 369 | snprintf(bindaddr, sizeof(bindaddr) - 1, "%s:%hu", param->bind_ip, param->bind_port); 370 | 371 | // initialize RB_TREE and LIST 372 | for (i = 0; i < QID_BUCKET_SIZE; ++i){ 373 | struct qid_head *qhead = &instance->queries_by_qid[i]; 374 | LIST_INIT(qhead); // clean list 375 | } 376 | 377 | RB_INIT(&instance->tree_head); 378 | 379 | // create listen socket 380 | struct sockaddr_storage ss; 381 | struct sockaddr *address; 382 | int addrlen = sizeof(ss); 383 | if (evutil_parse_sockaddr_port(bindaddr, (struct sockaddr *)&ss, &addrlen)) { 384 | LOGE("Unable to parse address %s", bindaddr); 385 | goto failed; 386 | } 387 | address = (struct sockaddr*)&ss; 388 | 389 | fd = socket(address->sa_family, SOCK_DGRAM, 0); 390 | if (fd == -1) { 391 | goto failed; 392 | } 393 | 394 | evutil_make_socket_closeonexec(fd); 395 | evutil_make_socket_nonblocking(fd); 396 | setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); 397 | 398 | if (bind(fd, address, addrlen)) { 399 | LOGE("bind address failed"); 400 | goto failed; 401 | } 402 | 403 | instance->listener = event_new(evbase, fd, EV_READ | EV_PERSIST, dns_read_request, instance); 404 | if (!instance->listener) { 405 | goto failed; 406 | } 407 | fd = -1; // transfer ownership 408 | error = event_add(instance->listener, NULL); 409 | if (error) { 410 | goto failed; 411 | } 412 | 413 | LOGI("DNS forwarding listen at %s, forward to %s:%hu", bindaddr, instance->dns_server, instance->dns_server_port); 414 | return instance; 415 | 416 | failed: 417 | if (fd != -1) { 418 | evutil_closesocket(fd); 419 | } 420 | dns_forwarder_free(instance); 421 | return NULL; 422 | } 423 | -------------------------------------------------------------------------------- /dns_forward.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | struct forwarder_param_t; 6 | 7 | struct dns_forwarder_t; 8 | struct dns_forwarder_t* dns_forwarder_new(struct event_base *evbase, struct evdns_base *evdns_base, struct forwarder_param_t *param); 9 | void dns_forwarder_free(struct dns_forwarder_t*); 10 | -------------------------------------------------------------------------------- /encrypt.h: -------------------------------------------------------------------------------- 1 | /* 2 | * encrypt.h - Define the enryptor's interface 3 | * 4 | * Copyright (C) 2013 - 2014, Max Lv 5 | * 6 | * This file is part of the shadowsocks-libev. 7 | * 8 | * shadowsocks-libev is free software; you can redistribute it and/or modify 9 | * it under the terms of the GNU General Public License as published by 10 | * the Free Software Foundation; either version 3 of the License, or 11 | * (at your option) any later version. 12 | * 13 | * shadowsocks-libev is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU General Public License 19 | * along with pdnsd; see the file COPYING. If not, see 20 | * . 21 | */ 22 | 23 | #ifndef _ENCRYPT_H 24 | #define _ENCRYPT_H 25 | 26 | #ifdef HAVE_CONFIG_H 27 | #include "config.h" 28 | #endif 29 | 30 | #ifndef _WIN32 31 | #include 32 | #else 33 | #include // ntoh hton 34 | 35 | #ifdef max 36 | #undef max 37 | #endif 38 | 39 | #ifdef min 40 | #undef min 41 | #endif 42 | 43 | #endif 44 | 45 | #include 46 | #include 47 | #include 48 | #include 49 | 50 | #ifdef _MSC_VER 51 | #define ssize_t int 52 | #endif 53 | 54 | 55 | #if defined(USE_CRYPTO_OPENSSL) 56 | 57 | #include 58 | typedef EVP_CIPHER cipher_kt_t; 59 | typedef EVP_CIPHER_CTX cipher_evp_t; 60 | typedef EVP_MD digest_type_t; 61 | #define MAX_KEY_LENGTH EVP_MAX_KEY_LENGTH 62 | #define MAX_IV_LENGTH EVP_MAX_IV_LENGTH 63 | #define MAX_MD_SIZE EVP_MAX_MD_SIZE 64 | 65 | #elif defined(USE_CRYPTO_MBEDTLS) 66 | 67 | #include 68 | #include 69 | typedef mbedtls_cipher_info_t cipher_kt_t; 70 | typedef mbedtls_cipher_context_t cipher_evp_t; 71 | typedef mbedtls_md_info_t digest_type_t; 72 | #define MAX_KEY_LENGTH 64 73 | #define MAX_IV_LENGTH MBEDTLS_MAX_IV_LENGTH 74 | #define MAX_MD_SIZE MBEDTLS_MD_MAX_SIZE 75 | 76 | #endif 77 | 78 | #define MAX_NONCE_LENGTH MAX_IV_LENGTH // 32??? 79 | #define MAX_TAG_LENGTH 16 80 | #define CHUNK_SIZE_LEN 2 81 | #define CHUNK_SIZE_MASK 0x3FFF 82 | 83 | #define ADDRTYPE_MASK 0xF 84 | 85 | #define CRYPTO_ERROR -2 86 | #define CRYPTO_NEED_MORE -1 87 | #define CRYPTO_OK 0 88 | 89 | 90 | 91 | #ifdef USE_CRYPTO_APPLECC 92 | 93 | #include 94 | 95 | #define kCCAlgorithmInvalid UINT32_MAX 96 | #define kCCContextValid 0 97 | #define kCCContextInvalid -1 98 | 99 | typedef struct { 100 | CCCryptorRef cryptor; 101 | int valid; 102 | CCOperation encrypt; 103 | CCAlgorithm cipher; 104 | CCMode mode; 105 | CCPadding padding; 106 | uint8_t iv[MAX_IV_LENGTH]; 107 | uint8_t key[MAX_KEY_LENGTH]; 108 | size_t iv_len; 109 | size_t key_len; 110 | } cipher_cc_t; 111 | 112 | #endif 113 | 114 | typedef struct { 115 | #if defined(USE_CRYPTO_OPENSSL) 116 | cipher_evp_t *evp; 117 | #else 118 | cipher_evp_t evp; 119 | #endif 120 | #ifdef USE_CRYPTO_APPLECC 121 | cipher_cc_t cc; 122 | #endif 123 | uint8_t salt[MAX_KEY_LENGTH]; // first rand bytes of TCP stream, used by HKDF 124 | uint8_t skey[MAX_KEY_LENGTH]; // HKDF derived AEAD key 125 | uint8_t nonce[MAX_NONCE_LENGTH]; // AEAD iv, increment every operation 126 | } cipher_ctx_t; 127 | 128 | #define BLOCK_SIZE 32 129 | 130 | #define NONE -1 131 | enum{ 132 | TABLE = 0, 133 | RC4, 134 | RC4_MD5, 135 | AES_128_CFB, 136 | AES_192_CFB, 137 | AES_256_CFB, 138 | BF_CFB, 139 | CAMELLIA_128_CFB, 140 | CAMELLIA_192_CFB, 141 | CAMELLIA_256_CFB, 142 | CAST5_CFB, 143 | DES_CFB, 144 | IDEA_CFB, 145 | RC2_CFB, 146 | SEED_CFB, 147 | AES_128_OFB, 148 | AES_192_OFB, 149 | AES_256_OFB, 150 | AES_128_CTR, 151 | AES_192_CTR, 152 | AES_256_CTR, 153 | AES_128_CFB8, 154 | AES_192_CFB8, 155 | AES_256_CFB8, 156 | AES_128_CFB1, 157 | AES_192_CFB1, 158 | AES_256_CFB1, 159 | CHACHA20, 160 | AES_128_GCM, 161 | AES_192_GCM, 162 | AES_256_GCM, 163 | AES_128_OCB, 164 | AES_192_OCB, 165 | AES_256_OCB, 166 | CHACHA20_IETF_POLY1305, 167 | CIPHER_NUM, /* must be last */ 168 | }; 169 | 170 | 171 | #define min(a, b) (((a) < (b)) ? (a) : (b)) 172 | #define max(a, b) (((a) > (b)) ? (a) : (b)) 173 | 174 | struct enc_ctx { 175 | unsigned int init:1; 176 | unsigned int aead:1; 177 | cipher_ctx_t evp; 178 | }; 179 | 180 | char * ss_encrypt_all(int buf_size, char *plaintext, ssize_t *len, int method); 181 | char * ss_decrypt_all(int buf_size, char *ciphertext, ssize_t *len, int method); 182 | char * ss_encrypt(char *ciphertext, char *plaintext, ssize_t *len, 183 | struct enc_ctx *ctx); 184 | char * ss_decrypt(char *plaintext, char *ciphertext, ssize_t *len, 185 | struct enc_ctx *ctx); 186 | int aead_encrypt(char *ciphertext, char *plaintext, ssize_t *len, struct enc_ctx *ctx); 187 | int aead_decrypt(char *plaintext, char *ciphertext, ssize_t *len, struct enc_ctx *ctx); 188 | 189 | void enc_ctx_init(int method, struct enc_ctx *ctx, int enc); 190 | int enc_init(const char *pass, const char *method); 191 | int enc_get_iv_len(void); 192 | void cipher_context_release(cipher_ctx_t *evp); 193 | unsigned char *enc_md5(const unsigned char *d, size_t n, unsigned char *md); 194 | void enc_print_all_methods(char *buf, size_t len); 195 | 196 | #endif // _ENCRYPT_H 197 | -------------------------------------------------------------------------------- /evhtp-config.h.win32: -------------------------------------------------------------------------------- 1 | #ifndef __EVHTP_CONFIG_H__ 2 | #define __EVHTP_CONFIG_H__ 3 | 4 | #ifdef __cplusplus 5 | extern "C" { 6 | #endif 7 | 8 | #ifndef EVHTP_EXPORT 9 | # if (defined __GNUC__ && __GNUC__ >= 4) || defined __INTEL_COMPILER || defined __clang__ 10 | # define EVHTP_EXPORT __attribute__ ((visibility("default"))) 11 | # else 12 | # define EVHTP_EXPORT 13 | # endif 14 | #endif 15 | 16 | #ifdef WIN32 17 | # define NO_SYS_UN 1 18 | # define NO_STRNDUP 1 19 | # ifdef _MSC_VER 20 | # define inline __inline 21 | # define ssize_t int 22 | # define strcasecmp _stricmp 23 | # define strncasecmp _strnicmp 24 | # if _MSC_VER <= 1800 /* VC++ 2015 have C99 snprintf */ 25 | # define snprintf evutil_snprintf 26 | # endif 27 | # endif 28 | #endif 29 | 30 | #if defined(_MSC_VER) && _MSC_VER >= 1500 // MSVC 2008 31 | # define DEPRECATED(message) __declspec(deprecated(message)) 32 | #elif defined(__clang__) && defined(__has_feature) 33 | # if __has_feature(attribute_deprecated_with_message) 34 | # define DEPRECATED(message) __attribute__ ((deprecated(message))) 35 | # endif 36 | # elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)) 37 | # define DEPRECATED(message) __attribute__ ((deprecated(message))) 38 | # elif defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) 39 | # define DEPRECATED(message) __attribute__((__deprecated__)) 40 | # else 41 | # define DEPRECATED(message) 42 | #endif 43 | 44 | 45 | 46 | 47 | #define EVHTP_SYS_ARCH 64 48 | #define EVHTP_DISABLE_REGEX 49 | #define EVHTP_DISABLE_SSL 50 | #define EVHTP_DISABLE_EVTHR 51 | 52 | /* #undef EVHTP_DISABLE_EVTHR */ 53 | /* #undef EVHTP_DISABLE_REGEX */ 54 | /* #undef EVHTP_DISABLE_SSL */ 55 | /* #undef EVHTP_DISABLE_EVTHR */ 56 | /* #undef EVHTP_USE_TCMALLOC */ 57 | /* #undef EVHTP_USE_JEMALLOC */ 58 | /* #undef EVHTP_USE_TCMALLOC */ 59 | 60 | #ifdef EVHTP_USE_TCMALLOC 61 | #include 62 | #define malloc(size) tc_malloc(size) 63 | #define calloc(count, size) tc_calloc(count, size) 64 | #define realloc(ptr, size) tc_realloc(ptr, size) 65 | #define free(ptr) tc_free(ptr) 66 | #endif 67 | 68 | #ifdef EVHTP_USE_JEMALLOC 69 | #define JEMALLOC_NO_DEMANGLE 70 | #include 71 | #define malloc(size) je_malloc(size) 72 | #define calloc(count, size) je_calloc(count, size) 73 | #define realloc(ptr, size) je_realloc(ptr, size) 74 | #define free(ptr) je_free(ptr) 75 | #endif 76 | 77 | 78 | #ifdef __cplusplus 79 | } 80 | #endif 81 | 82 | #endif 83 | -------------------------------------------------------------------------------- /evhtp_get.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | static void 11 | print_error(evhtp_request_t * req, evhtp_error_flags errtype, void * arg) { 12 | printf("evhtp error\n"); 13 | } 14 | 15 | 16 | static void 17 | request_cb(evhtp_request_t * req, void * arg) { 18 | printf("hi %zu\n", evbuffer_get_length(req->buffer_in)); 19 | } 20 | 21 | static evhtp_res 22 | print_data(evhtp_request_t * req, evbuf_t * buf, void * arg) { 23 | size_t len = evbuffer_get_length(buf); 24 | 25 | printf("Got %zu bytes\n", len); 26 | fwrite(evbuffer_pullup(buf, len), 1, len, stdout); 27 | printf("-------\n"); 28 | 29 | return EVHTP_RES_OK; 30 | } 31 | 32 | static evhtp_res 33 | print_new_chunk_len(evhtp_request_t * req, uint64_t len, void * arg) { 34 | printf("started new chunk, %" PRIu64 " bytes\n", len); 35 | 36 | return EVHTP_RES_OK; 37 | } 38 | 39 | static evhtp_res 40 | print_chunk_complete(evhtp_request_t * req, void * arg) { 41 | printf("ended a single chunk\n"); 42 | 43 | return EVHTP_RES_OK; 44 | } 45 | 46 | static evhtp_res 47 | print_chunks_complete(evhtp_request_t * req, void * arg) { 48 | printf("all chunks read\n"); 49 | 50 | return EVHTP_RES_OK; 51 | } 52 | static evhtp_res print_headers(evhtp_request_t * req, evhtp_headers_t * hdr, void * arg) { 53 | printf("all headers ok\n"); 54 | evhtp_kv_t * kv; 55 | 56 | TAILQ_FOREACH(kv, hdr, next) { 57 | printf("%*s:%s\n", kv->klen, kv->key, kv->val); 58 | } 59 | 60 | 61 | return EVHTP_RES_OK; 62 | } 63 | 64 | static evhtp_res print_conn_error(evhtp_connection_t * connection, evhtp_error_flags errtype, void * arg) { 65 | printf("connection hook error \n"); 66 | 67 | return EVHTP_RES_OK; 68 | } 69 | 70 | 71 | 72 | int 73 | main(int argc, char ** argv) { 74 | evbase_t * evbase; 75 | struct evdns_base * evdns; 76 | evhtp_connection_t * conn; 77 | evhtp_request_t * request; 78 | const char *path = "/"; 79 | const char *host = argv[1]; 80 | if (argc >= 3) 81 | path = argv[2]; 82 | 83 | evbase = event_base_new(); 84 | evdns = evdns_base_new(evbase, 1); 85 | conn = evhtp_connection_new_dns(evbase, evdns, host, 80); 86 | request = evhtp_request_new(request_cb, evbase); 87 | 88 | evhtp_set_hook(&request->hooks, evhtp_hook_on_error, print_error, NULL); 89 | evhtp_set_hook(&request->hooks, evhtp_hook_on_headers, print_headers, evbase); 90 | evhtp_set_hook(&request->hooks, evhtp_hook_on_read, print_data, evbase); 91 | evhtp_set_hook(&request->hooks, evhtp_hook_on_new_chunk, print_new_chunk_len, NULL); 92 | evhtp_set_hook(&request->hooks, evhtp_hook_on_chunk_complete, print_chunk_complete, NULL); 93 | evhtp_set_hook(&request->hooks, evhtp_hook_on_chunks_complete, print_chunks_complete, NULL); 94 | 95 | evhtp_headers_add_header(request->headers_out, 96 | evhtp_header_new("Host", host, 0, 0)); 97 | //evhtp_headers_add_header(request->headers_out, 98 | // evhtp_header_new("Accept-Encoding", "deflate, gzip", 0, 0)); 99 | evhtp_headers_add_header(request->headers_out, 100 | evhtp_header_new("User-Agent", "libevhtp", 0, 0)); 101 | evhtp_headers_add_header(request->headers_out, 102 | evhtp_header_new("Connection", "close", 0, 0)); 103 | evhtp_headers_add_header(request->headers_out, 104 | evhtp_header_new("Accept", "*/*", 0, 0)); 105 | 106 | evhtp_set_hook(&conn->hooks, evhtp_hook_on_conn_error, print_conn_error, NULL); 107 | 108 | evhtp_make_request(conn, request, htp_method_GET, path); 109 | //evhtp_make_request(conn, request, htp_method_HEAD, "/"); 110 | 111 | event_base_loop(evbase, 0); 112 | event_base_free(evbase); 113 | 114 | return 0; 115 | } 116 | 117 | -------------------------------------------------------------------------------- /evhtp_proxy.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #ifdef _MSC_VER 11 | # ifndef NDEBUG 12 | # include "vld.h" 13 | # endif 14 | # include "bsd_getopt.h" 15 | #else 16 | # include 17 | #endif 18 | #include 19 | #ifdef ENABLE_SS 20 | # if defined(USE_CRYPTO_OPENSSL) 21 | # include /* version */ 22 | # elif defined(USE_CRYPTO_MBEDTLS) 23 | # include /* version */ 24 | # endif 25 | # include "encrypt.h" 26 | #endif 27 | 28 | #include "evhtp.h" 29 | 30 | #include "connector.h" 31 | #include "dns_forward.h" 32 | #include "parse_forward_param.h" 33 | 34 | #ifndef EVHTP_DISABLE_SSL 35 | # define ENABLE_HTTPS_PROXY 36 | #endif 37 | 38 | #define PROGRAM_VERSION "0.6" 39 | #define DEFAULT_LISTEN_PORT 8081 40 | #define DEFAULT_BIND_ADDRESS "0.0.0.0" 41 | #define DEFAULT_SOCKS5_PORT 1080 42 | 43 | void relay(struct bufferevent *b_in, struct bufferevent *b_out); 44 | 45 | static void backend_cb(evhtp_request_t *backend_req, void *arg); 46 | static void connect_cb(struct bufferevent *bev, void *arg); 47 | static void lru_get_cb(evhtp_connection_t *conn, void *arg); 48 | 49 | static void response_proxy_pac_file(evhtp_request_t *frontend_req); 50 | 51 | #ifdef USE_THREAD 52 | static struct evdns_base *evdnss[128] = {}; 53 | #else 54 | struct evdns_base *evdns = NULL; 55 | #endif 56 | const char *g_socks_server = NULL; 57 | int g_socks_port = DEFAULT_SOCKS5_PORT; 58 | int g_https_proxy = 0; 59 | int use_syslog = 0; 60 | int g_enable_nodelay = 0; 61 | 62 | enum upstream_mode { 63 | UPSTREAM_TCP, 64 | UPSTREAM_SOCKS5, 65 | UPSTREAM_HTTP, 66 | UPSTREAM_HTTPS, 67 | UPSTREAM_SS, 68 | }; 69 | enum upstream_mode g_upstream_mode = UPSTREAM_TCP; 70 | 71 | static const char* upstream_mode_to_str(enum upstream_mode mode) 72 | { 73 | switch (mode) { 74 | case UPSTREAM_TCP: 75 | return "TCP"; 76 | 77 | case UPSTREAM_SOCKS5: 78 | return "SOCKS5"; 79 | 80 | case UPSTREAM_HTTP: 81 | return "HTTP"; 82 | 83 | case UPSTREAM_HTTPS: 84 | return "HTTPS"; 85 | 86 | case UPSTREAM_SS: 87 | return "SS"; 88 | 89 | default: 90 | return "Unknown"; 91 | } 92 | } 93 | 94 | void connect_upstream(struct event_base *evbase, struct evdns_base *evdns_base, const char *hostname, int port, connect_callback cb, void *arg) 95 | { 96 | switch (g_upstream_mode) 97 | { 98 | case UPSTREAM_TCP: 99 | /* fallthrough */ 100 | case UPSTREAM_SOCKS5: 101 | return connect_socks5(evbase, evdns_base, hostname, port, cb, arg); 102 | 103 | case UPSTREAM_HTTP: 104 | /* fallthrough */ 105 | case UPSTREAM_HTTPS: 106 | /* TODO: only for CONNECT method */ 107 | return connect_http(evbase, evdns_base, hostname, port, cb, arg); 108 | 109 | #ifdef ENABLE_SS 110 | case UPSTREAM_SS: 111 | return connect_ss(evbase, evdns_base, hostname, port, cb, arg); 112 | #endif 113 | default: 114 | LOGE("Unknown upstream"); 115 | cb(NULL, arg); 116 | } 117 | } 118 | 119 | // error occur before read all headers 120 | static void 121 | backend_conn_error(evhtp_request_t * req, evhtp_error_flags errtype, void * arg) 122 | { 123 | evhtp_request_t * frontend_req = (evhtp_request_t *)arg; 124 | evhtp_request_t * backend_req = req; 125 | LOGE("evhtp backend req %p error %hu while transport HTTP header", backend_req, errtype); 126 | 127 | evhtp_send_reply(frontend_req, EVHTP_RES_BADGATEWAY); // return 502 bad gateway, when connect fail 128 | evhtp_request_resume(frontend_req); 129 | 130 | evhtp_unset_hook(&frontend_req->hooks, evhtp_hook_on_error); 131 | } 132 | 133 | // error after read all headers 134 | static void 135 | backend_trans_error(evhtp_request_t * req, evhtp_error_flags errtype, void * arg) 136 | { 137 | evhtp_request_t * frontend_req = (evhtp_request_t *)arg; 138 | evhtp_request_t * backend_req = req; 139 | LOGE("evhtp backend req %p error %hu while transport HTTP body", backend_req, errtype); 140 | 141 | backend_cb(backend_req, frontend_req); // finish transport 142 | } 143 | 144 | static void 145 | frontend_error(evhtp_request_t * req, evhtp_error_flags errtype, void * arg) 146 | { 147 | evhtp_request_t * backend_req = (evhtp_request_t *)arg; 148 | LOGE("evhtp frontend req %p error %hu, cancel backend req %p", req, errtype, backend_req); 149 | 150 | if (req->status == EVHTP_RES_PAUSE) { 151 | evhtp_request_resume(req); // paused connection cannot be freed automatically by socket EOF|error 152 | } 153 | if (backend_req->status == EVHTP_RES_PAUSE) { 154 | evhtp_request_resume(backend_req); // paused connection cannot be freed automatically by socket EOF|error 155 | } 156 | 157 | // cancel request 158 | evhtp_unset_hook(&backend_req->hooks, evhtp_hook_on_error); 159 | evhtp_connection_t *ev_conn = evhtp_request_get_connection(backend_req); 160 | LOGE("evhtp free backend connection %p backend req %p", ev_conn, backend_req); 161 | evhtp_connection_free(ev_conn); 162 | } 163 | 164 | static evhtp_res resume_backend_request(evhtp_connection_t * conn, void * arg) 165 | { 166 | evhtp_request_t * backend_req = (evhtp_request_t *)arg; 167 | 168 | LOGD("resume backend request %p", backend_req); 169 | evhtp_request_resume(backend_req); 170 | 171 | evhtp_unset_hook(&conn->hooks, evhtp_hook_on_write); 172 | 173 | return EVHTP_RES_OK; 174 | } 175 | 176 | 177 | static evhtp_res 178 | backend_body(evhtp_request_t * req, evbuf_t * buf, void * arg) 179 | { 180 | evhtp_request_t * frontend_req = (evhtp_request_t *)arg; 181 | //size_t len = evbuffer_get_length(buf); 182 | 183 | //LOGD("relay http body, got %u bytes", (unsigned)len); 184 | //fwrite(evbuffer_pullup(buf, len), 1, len, stdout); 185 | 186 | evhtp_send_reply_chunk(frontend_req, buf); 187 | 188 | //evbuffer_drain(buf, -1); // remove readed data 189 | 190 | if (evbuffer_get_length(bufferevent_get_output(evhtp_request_get_bev(frontend_req))) > MAX_OUTPUT) { 191 | LOGD("too many data, stop backend request %p", req); 192 | evhtp_request_pause(req); 193 | 194 | evhtp_set_hook(&evhtp_request_get_connection(frontend_req)->hooks, evhtp_hook_on_write, resume_backend_request, req); 195 | } 196 | 197 | return EVHTP_RES_OK; 198 | } 199 | 200 | static evhtp_res backend_headers(evhtp_request_t * backend_req, evhtp_headers_t * headers, void * arg) 201 | { 202 | evhtp_request_t * frontend_req = (evhtp_request_t *)arg; 203 | evhtp_header_t *kv = NULL; 204 | 205 | LOGD("backend req %p all headers ok", backend_req); 206 | 207 | TAILQ_FOREACH(kv, headers, next) { 208 | //printf("%*s:%*s\n", kv->klen, kv->key, kv->vlen, kv->val); 209 | if (strcasecmp(kv->key, "Connection") == 0) { 210 | continue; 211 | } 212 | if (strcasecmp(kv->key, "Transfer-Encoding") == 0) { 213 | continue; 214 | } 215 | evhtp_kvs_add_kv(frontend_req->headers_out, evhtp_kv_new(kv->key, 216 | kv->val, 217 | kv->k_heaped, 218 | kv->v_heaped)); 219 | } 220 | 221 | evhtp_send_reply_chunk_start(frontend_req, evhtp_request_status(backend_req)); 222 | evhtp_request_resume(frontend_req); 223 | 224 | evhtp_set_hook(&backend_req->hooks, evhtp_hook_on_error, 225 | (evhtp_hook)backend_trans_error, frontend_req); 226 | 227 | return EVHTP_RES_OK; 228 | } 229 | void backend_eventcb(evhtp_connection_t *c, short events, void *arg) 230 | { 231 | evhtp_request_t * frontend_req = (evhtp_request_t *)arg; 232 | LOGD("backend connection %p (paused %d) event %hd, frontend req %p", c, c->paused, events, frontend_req); 233 | } 234 | 235 | int 236 | make_request(evhtp_connection_t * conn, 237 | evthr_t * evthr, 238 | const char * const path, 239 | htp_method method, 240 | evhtp_headers_t * headers, 241 | evbuf_t * body, 242 | evhtp_callback_cb cb, 243 | void * arg) 244 | { 245 | evhtp_request_t * request; 246 | evhtp_header_t * kv = NULL; 247 | evhtp_request_t * frontend_req = (evhtp_request_t *)arg; 248 | 249 | #ifndef EVHTP_DISABLE_EVTHR 250 | conn->thread = evthr; 251 | #endif 252 | request = evhtp_request_new(cb, arg); 253 | 254 | TAILQ_FOREACH(kv, headers, next) { 255 | if (strcasecmp(kv->key, "Connection") == 0) { 256 | continue; 257 | } 258 | if (strcasecmp(kv->key, "Proxy-Connection") == 0) { 259 | continue; 260 | } 261 | evhtp_kvs_add_kv(request->headers_out, evhtp_kv_new(kv->key, 262 | kv->val, 263 | kv->k_heaped, 264 | kv->v_heaped)); 265 | } 266 | //if((header = evhtp_kvs_find_kv(request->headers_out, "Accept-Encoding"))) { 267 | // evhtp_header_rm_and_free(request->headers_out, header); 268 | //} 269 | // evhtp_headers_add_header(request->headers_out, 270 | // evhtp_header_new("Connection", "close", 0, 0)); 271 | 272 | 273 | evbuffer_add_buffer(request->buffer_out, body); 274 | 275 | // hook 276 | evhtp_set_hook(&request->hooks, evhtp_hook_on_error, (evhtp_hook)backend_conn_error, arg); 277 | evhtp_set_hook(&request->hooks, evhtp_hook_on_headers, backend_headers, arg); 278 | evhtp_set_hook(&request->hooks, evhtp_hook_on_read, backend_body, arg); 279 | evhtp_set_hook(&conn->hooks, evhtp_hook_on_event, (evhtp_hook)backend_eventcb, arg); 280 | 281 | evhtp_set_hook(&frontend_req->hooks, evhtp_hook_on_error, (evhtp_hook)frontend_error, request); 282 | 283 | LOGD("frontend req %p making backend request %p (connection %p), path %s", frontend_req, request, conn, path); 284 | evhtp_make_request(conn, request, method, path); 285 | 286 | return 0; 287 | } 288 | 289 | static void 290 | backend_cb(evhtp_request_t * backend_req, void * arg) { 291 | //evhtp_header_t *header = NULL; 292 | evhtp_request_t * frontend_req = (evhtp_request_t *)arg; 293 | 294 | LOGD("backend req %p (connection %p) finish http response.", backend_req, backend_req->conn); 295 | evhtp_send_reply_chunk_end(frontend_req); 296 | 297 | evhtp_unset_hook(&frontend_req->hooks, evhtp_hook_on_error); 298 | evhtp_unset_hook(&backend_req->hooks, evhtp_hook_on_error); 299 | 300 | if (backend_req->keepalive) { 301 | const char *host = frontend_req->uri->authority->hostname; 302 | uint16_t port = frontend_req->uri->authority->port ? frontend_req->uri->authority->port : 80; 303 | lru_set(host, port, backend_req->conn); 304 | evhtp_request_free(backend_req); // evhtp_make_request() does not free previous request 305 | } 306 | } 307 | 308 | static void 309 | frontend_cb(evhtp_request_t * req, void * arg) { 310 | #ifdef USE_THREAD 311 | int * aux; 312 | int thr; 313 | struct evdns_base * evdns; 314 | 315 | aux = (int *)evthr_get_aux(req->conn->thread); 316 | thr = *aux; 317 | 318 | LOGD(" Received frontend request on thread %d... ", thr); 319 | evdns = evdnss[thr]; 320 | evbase_t * evbase = evthr_get_base(req->conn->thread); 321 | #else 322 | evbase_t * evbase = req->conn->evbase; 323 | #endif 324 | 325 | const char *host = req->uri->authority->hostname; 326 | uint16_t port = req->uri->authority->port ? req->uri->authority->port : 80; 327 | LOGD("frontend req %p (connection %p) receive HTTP request for %s:%u", req, req->conn, host, port); 328 | 329 | if (host == NULL) { 330 | // non proxy request, so return proxy.pac file 331 | return response_proxy_pac_file(req); 332 | } 333 | if (strlen(host) > 255) { 334 | LOGE("domain %s too long", host); 335 | return evhtp_send_reply(req, EVHTP_RES_SERVERR); 336 | } 337 | 338 | /* Pause the frontend request while we run the backend requests. */ 339 | evhtp_request_pause(req); 340 | 341 | if (htp_method_CONNECT == req->method) { 342 | connect_upstream(evbase, evdns, host, port, connect_cb, req); // async connect 343 | } else { 344 | lru_get(host, port, lru_get_cb, req); 345 | } 346 | } 347 | 348 | void connect_cb(struct bufferevent *bev, void *arg) 349 | { 350 | evhtp_request_t * req = (evhtp_request_t *)arg; 351 | 352 | if (NULL == bev) { 353 | evhtp_send_reply(req, EVHTP_RES_BADGATEWAY); // return 502 bad gateway, when connect fail 354 | evhtp_request_resume(req); 355 | return; 356 | } 357 | 358 | LOGD("ready to relay http socket for frontend req %p", req); 359 | evbev_t * b_in = evhtp_request_take_ownership(req); 360 | evhtp_connection_free(evhtp_request_get_connection(req)); 361 | 362 | const char headers[] = 363 | "HTTP/1.1 200 OK\r\n" 364 | "Connection: Keep-Alive\r\n" 365 | "\r\n"; 366 | bufferevent_write(b_in, headers, sizeof(headers) - 1); // without ending '\0' 367 | 368 | relay(b_in, bev); 369 | } 370 | 371 | void lru_get_cb(evhtp_connection_t *conn, void *arg) 372 | { 373 | evhtp_request_t * req = (evhtp_request_t *)arg; 374 | LOGD("lru get backend connection %p for frontend req %p", conn, req); 375 | 376 | if (NULL == conn) { 377 | evhtp_send_reply(req, EVHTP_RES_BADGATEWAY); // return 502 bad gateway, when connect fail 378 | evhtp_request_resume(req); 379 | return; 380 | } 381 | 382 | evbuf_t *uri = evbuffer_new(); 383 | if (req->uri->query_raw) { 384 | evbuffer_add_printf(uri, "%s?%s", req->uri->path->full, req->uri->query_raw); 385 | } else { 386 | evbuffer_add_reference(uri, req->uri->path->full, strlen(req->uri->path->full), NULL, NULL); 387 | } 388 | 389 | make_request( 390 | conn, 391 | #ifndef EVHTP_DISABLE_EVTHR 392 | req->conn->thread, 393 | #else 394 | NULL, 395 | #endif 396 | (char*)evbuffer_pullup(uri, -1), 397 | req->method, 398 | req->headers_in, req->buffer_in, 399 | backend_cb, req); 400 | 401 | evbuffer_free(uri); 402 | } 403 | static const char *g_proxy_pac_path = NULL; 404 | static char *g_proxy_pac_content = NULL; 405 | static size_t g_proxy_pac_length = 0; 406 | 407 | void load_proxy_pac_file(const char *path) 408 | { 409 | FILE *pac = fopen(path, "rb"); 410 | if (pac) { 411 | fseek(pac, 0, SEEK_END); 412 | g_proxy_pac_length = ftell(pac); 413 | if (g_proxy_pac_length == 0) 414 | goto fail; 415 | fseek(pac, 0, SEEK_SET); 416 | g_proxy_pac_content = (char *)malloc(g_proxy_pac_length); 417 | if (g_proxy_pac_content == NULL) 418 | goto fail; 419 | fread(g_proxy_pac_content, 1, g_proxy_pac_length, pac); 420 | fclose(pac); 421 | return; 422 | } else { 423 | LOGE("open proxy pac file failed"); 424 | } 425 | 426 | fail: 427 | g_proxy_pac_length = 0; 428 | if (pac) 429 | fclose(pac); 430 | } 431 | 432 | static void response_proxy_pac_file(evhtp_request_t * frontend_req) 433 | { 434 | LOGD("response proxy.pac to client"); 435 | if (g_proxy_pac_length && 0 == strcmp(frontend_req->uri->path->full, "/proxy.pac")) { 436 | evhtp_headers_add_header(frontend_req->headers_out, 437 | evhtp_header_new("Content-Type", "application/x-ns-proxy-autoconfig", 0, 0)); 438 | evbuffer_add_reference(frontend_req->buffer_out, g_proxy_pac_content, g_proxy_pac_length, NULL, NULL); 439 | evhtp_send_reply(frontend_req, EVHTP_RES_OK); 440 | } else { 441 | evhtp_send_reply(frontend_req, EVHTP_RES_SERVERR); /* internal server error */ 442 | } 443 | } 444 | 445 | /* Terminate gracefully on SIGTERM */ 446 | void 447 | sigterm_cb(int fd, short event, void * arg) { 448 | evbase_t * evbase = (evbase_t *)arg; 449 | struct timeval tv = { .tv_usec = 100000, .tv_sec = 0 }; /* 100 ms */ 450 | 451 | event_base_loopexit(evbase, &tv); 452 | } 453 | 454 | #ifdef USE_THREAD 455 | void 456 | init_thread_cb(evhtp_t * htp, evthr_t * thr, void * arg) { 457 | static int aux = 0; 458 | 459 | LOGD("Spinning up a thread: %d", ++aux); 460 | evthr_set_aux(thr, &aux); 461 | evbase_t * evbase = evthr_get_base(thr); 462 | evdnss[aux] = evdns_base_new(evbase, 1); 463 | evdns_base_set_option(evdnss[aux], "randomize-case:", "0"); 464 | } 465 | #endif 466 | 467 | void version(const char *program) 468 | { 469 | printf("%s " PROGRAM_VERSION " built at " __TIME__ " " __DATE__ "\n", program); 470 | printf(" libevent %s\n", event_get_version()); 471 | #ifdef ENABLE_SS 472 | # if defined(USE_CRYPTO_OPENSSL) 473 | printf(" %s\n", SSLeay_version(SSLEAY_VERSION)); // OPENSSL_VERSION_TEXT SHLIB_VERSION_NUMBER 474 | # elif defined(USE_CRYPTO_MBEDTLS) 475 | char buf[256] = {'\0'}; 476 | mbedtls_version_get_string_full(buf); 477 | printf(" %s\n", buf); // MBEDTLS_VERSION_STRING_FULL 478 | # endif 479 | #endif 480 | } 481 | 482 | void usage(const char *program) 483 | { 484 | printf("\nUsage: %s [options]\n", program); 485 | printf( 486 | " -l proxy listen port, default %d\n" 487 | " -b local address to bind, default " DEFAULT_BIND_ADDRESS "\n" 488 | #ifndef ENABLE_SS 489 | " -p socks5 server port\n" 490 | " -s socks5 server address\n" 491 | #else 492 | " -p socks5/ss server port\n" 493 | " -s socks5/ss server address\n" 494 | " -m encrypt method of remote ss server\n" 495 | " -k password of remote ss server\n" 496 | " --pac pac file\n" 497 | #endif 498 | " --dns name server\n" 499 | #ifndef _WIN32 500 | " --user set user and group\n" 501 | " --pid-file pid file\n" 502 | #endif 503 | #ifdef ENABLE_HTTPS_PROXY 504 | " --ssl-certificate \n" 505 | " set ssl certificate\n" 506 | " --ssl-certificate-key \n" 507 | " set ssl private key\n" 508 | #endif 509 | #ifdef TCP_NODELAY 510 | " --tcp-nodelay enable TCP NODELAY\n" 511 | #endif 512 | " --client-max-body-size \n" 513 | " maximum allowed size of the client request body(unit MB, 0 allow any size, default 1MB)\n" 514 | " --dns-forwarder <[bind_ip:]bind_port:forward_ip:forward_port> \n" 515 | " forward local dns request to dns server via tcp\n" 516 | " -v, --verbose verbose logging\n" 517 | " -V, --version show version number and quit\n" 518 | " -h, --help show help\n", DEFAULT_LISTEN_PORT); 519 | #ifdef ENABLE_SS 520 | char buf[4096] = {'\0'}; 521 | enc_print_all_methods(buf, sizeof(buf)/sizeof(buf[0])); 522 | printf( 523 | "\nSupported ss encryption methods:\n" 524 | " %s\n", buf); 525 | #endif 526 | 527 | } 528 | 529 | enum { 530 | OPTION_PAC = CHAR_MAX + 1, 531 | OPTION_DNS, 532 | OPTION_USERSPEC, 533 | OPTION_PID_FILE, 534 | OPTION_SSL_CERTIFICATE, 535 | OPTION_SSL_CERTIFICATE_KEY, 536 | OPTION_TCP_NODELAY, 537 | OPTION_CLIENT_MAX_BODY_SIZE, 538 | OPTION_DNS_FORWARDER, 539 | }; 540 | 541 | int 542 | main(int argc, char ** argv) { 543 | evbase_t *evbase = NULL; 544 | evhtp_t *evhtp = NULL; 545 | uint16_t port = DEFAULT_LISTEN_PORT; // default listen port 546 | const char *bind_address = DEFAULT_BIND_ADDRESS; 547 | const char *password = NULL; 548 | const char *method = NULL; 549 | const char *name_server = NULL; 550 | const char *dns_forwarder = NULL; 551 | #ifndef _WIN32 552 | const char *userspec = NULL; 553 | const char *pid_file = NULL; 554 | #endif 555 | #ifdef ENABLE_HTTPS_PROXY 556 | const char *ssl_certificate = NULL; 557 | const char *ssl_certificate_key = NULL; 558 | #endif 559 | int client_max_body_size = MAX_REQUEST_BODY_SIZE; 560 | int verbose = 0; 561 | int opt; 562 | int option_index = 0; 563 | static struct option long_options[] = { 564 | {"pac", required_argument, NULL, OPTION_PAC}, 565 | {"dns", required_argument, NULL, OPTION_DNS}, 566 | #ifndef _WIN32 567 | {"user", required_argument, NULL, OPTION_USERSPEC}, 568 | {"pid-file", required_argument, NULL, OPTION_PID_FILE}, 569 | #endif 570 | #ifdef ENABLE_HTTPS_PROXY 571 | // for compatible only 572 | {"ssl_certificate", required_argument, NULL, OPTION_SSL_CERTIFICATE}, 573 | {"ssl_certificate_key", required_argument, NULL, OPTION_SSL_CERTIFICATE_KEY}, 574 | {"ssl-certificate", required_argument, NULL, OPTION_SSL_CERTIFICATE}, 575 | {"ssl-certificate-key", required_argument, NULL, OPTION_SSL_CERTIFICATE_KEY}, 576 | #endif 577 | #ifdef TCP_NODELAY 578 | {"tcp-nodelay", no_argument, NULL, OPTION_TCP_NODELAY}, 579 | #endif 580 | {"client-max-body-size", required_argument, NULL, OPTION_CLIENT_MAX_BODY_SIZE}, 581 | {"dns-forwarder", required_argument, NULL, OPTION_DNS_FORWARDER}, 582 | {"help", no_argument, NULL, 'h'}, 583 | {"verbose", no_argument, NULL, 'v'}, 584 | {"version", no_argument, NULL, 'V'}, 585 | {NULL, 0, NULL, 0} 586 | }; 587 | 588 | #ifdef _WIN32 589 | WSADATA wsaData; 590 | int err = WSAStartup(MAKEWORD(2, 2), &wsaData); // require Windows Sockets version 2.2 591 | if (err != 0) { 592 | fprintf(stderr, "WSAStartup failed with error: %d\n", err); 593 | return EXIT_FAILURE; 594 | } 595 | #endif 596 | 597 | while ((opt = getopt_long( 598 | argc, argv, "hu:b:l:p:s:m:k:vV", 599 | long_options, &option_index) 600 | ) != -1) 601 | { 602 | switch (opt) 603 | { 604 | case 's': 605 | g_socks_server = optarg; 606 | g_upstream_mode = UPSTREAM_SOCKS5 ; 607 | break; 608 | case 'p': 609 | g_socks_port = atoi(optarg); 610 | break; 611 | case 'm': 612 | method = optarg; 613 | break; 614 | case 'k': 615 | password = optarg; 616 | break; 617 | case 'b': 618 | bind_address = optarg; 619 | break; 620 | case 'l': 621 | port = atoi(optarg); 622 | break; 623 | case 'v': 624 | verbose = 1; 625 | break; 626 | case OPTION_PAC: 627 | g_proxy_pac_path = optarg; 628 | break; 629 | case OPTION_DNS: 630 | name_server = optarg; 631 | break; 632 | #ifndef _WIN32 633 | case OPTION_USERSPEC: 634 | userspec = optarg; 635 | break; 636 | case OPTION_PID_FILE: 637 | pid_file = optarg; 638 | break; 639 | #endif 640 | #ifdef ENABLE_HTTPS_PROXY 641 | case OPTION_SSL_CERTIFICATE: 642 | ssl_certificate = optarg; 643 | break; 644 | case OPTION_SSL_CERTIFICATE_KEY: 645 | ssl_certificate_key = optarg; 646 | break; 647 | #endif 648 | case OPTION_TCP_NODELAY: 649 | g_enable_nodelay = 1; 650 | break; 651 | case OPTION_CLIENT_MAX_BODY_SIZE: 652 | client_max_body_size = 1024 * 1024 * atof(optarg); 653 | break; 654 | case OPTION_DNS_FORWARDER: 655 | dns_forwarder = optarg; 656 | break; 657 | case 'V': 658 | version(argv[0]); 659 | exit(EXIT_SUCCESS); 660 | break; 661 | case 'h': 662 | default: 663 | usage(argv[0]); 664 | exit(EXIT_FAILURE); 665 | break; 666 | } 667 | } 668 | 669 | log_init(NULL, verbose ? LOG_LEVEL_DEBUG : LOG_LEVEL_INFO); 670 | 671 | #ifdef ENABLE_SS 672 | if (password && method) 673 | { 674 | g_upstream_mode = UPSTREAM_SS; 675 | g_ss_method = enc_init(password, method); 676 | g_ss_server = g_socks_server; 677 | g_ss_port = g_socks_port; 678 | 679 | } 680 | #endif 681 | if (g_proxy_pac_path && g_proxy_pac_path[0]) { 682 | load_proxy_pac_file(g_proxy_pac_path); 683 | } 684 | 685 | evbase = event_base_new(); 686 | if (name_server) { 687 | evdns = evdns_base_new(evbase, 0); 688 | if (-1 == evdns_base_nameserver_ip_add(evdns, name_server)) { 689 | LOGE("Invalid name server: %s", name_server); 690 | return EXIT_FAILURE; 691 | } 692 | } else { 693 | evdns = evdns_base_new(evbase, 1); 694 | if (evdns_base_count_nameservers(evdns) == 0){ 695 | LOGE("System configured without nameserver"); 696 | return EXIT_FAILURE; 697 | } 698 | } 699 | 700 | evdns_base_set_option(evdns, "randomize-case:", "0"); 701 | 702 | evhtp = evhtp_new(evbase, NULL); 703 | evhtp->enable_nodelay = g_enable_nodelay; 704 | evhtp->disable_parse_query_body = 1; 705 | evhtp->max_body_size = client_max_body_size; 706 | 707 | 708 | #ifdef ENABLE_HTTPS_PROXY 709 | evhtp_ssl_cfg_t ssl_cfg = {}; 710 | if (ssl_certificate) { 711 | g_https_proxy = 1; 712 | ssl_cfg.pemfile = ssl_certificate; 713 | ssl_cfg.privfile = ssl_certificate_key; 714 | //ssl_cfg.cafile = "/etc/ssl/certs/ca-bundle.crt"; // RHEL 7 715 | //ssl_cfg.capath = "/etc/ssl/certs/"; // Ubuntu 16.04 716 | if (0 != evhtp_ssl_init(evhtp, &ssl_cfg)) { 717 | LOGE("Init SSL failed"); 718 | return EXIT_FAILURE; 719 | } 720 | evhtp->bev_flags |= BEV_OPT_DEFER_CALLBACKS; 721 | } 722 | #endif 723 | 724 | #ifdef USE_THREAD 725 | evhtp_set_gencb(evhtp, frontend_cb, NULL); 726 | evhtp_use_threads(evhtp, init_thread_cb, 2, NULL); 727 | #else 728 | evhtp_set_gencb(evhtp, frontend_cb, NULL); 729 | #endif 730 | 731 | lru_init(evbase); 732 | struct dns_forwarder_t *dnsforwarder = NULL; 733 | if (dns_forwarder) { 734 | struct forwarder_param_t param = {0}; 735 | if (0 == parse_forward_param(dns_forwarder, strlen(dns_forwarder), ¶m)) { 736 | dnsforwarder = dns_forwarder_new(evbase, evdns, ¶m); 737 | } 738 | else { 739 | LOGE("parse forward param failed"); 740 | } 741 | } 742 | 743 | #ifndef _WIN32 744 | struct event *ev_sigterm; 745 | ev_sigterm = evsignal_new(evbase, SIGTERM, sigterm_cb, evbase); 746 | evsignal_add(ev_sigterm, NULL); 747 | #endif 748 | struct event *ev_sigint; 749 | ev_sigint = evsignal_new(evbase, SIGINT, sigterm_cb, evbase); 750 | evsignal_add(ev_sigint, NULL); 751 | 752 | if (0 != evhtp_bind_socket(evhtp, bind_address, port, 1024)) { 753 | LOGE("Bind address %s:%hu failed", bind_address, port); 754 | return EXIT_FAILURE; 755 | } 756 | LOGI("%s listen at %s:%hu, upstream protocol %s", (g_https_proxy ? "HTTPS" : "HTTP"), 757 | bind_address, port, 758 | upstream_mode_to_str(g_upstream_mode)); 759 | 760 | #ifndef _WIN32 761 | if (pid_file && 0 != write_pid_file(pid_file)) { 762 | LOGE("Write pid file failed"); 763 | return EXIT_FAILURE; 764 | } 765 | if (userspec && 0 != change_user(userspec)) { 766 | LOGE("Change user failed"); 767 | return EXIT_FAILURE; 768 | } 769 | #endif // !_WIN32 770 | 771 | event_base_loop(evbase, 0); 772 | 773 | event_free(ev_sigint); 774 | #ifndef _WIN32 775 | event_free(ev_sigterm); 776 | #endif 777 | 778 | evhtp_unbind_socket(evhtp); 779 | dns_forwarder_free(dnsforwarder); 780 | lru_fini(); 781 | evdns_base_free(evdns, 1); 782 | evhtp_free(evhtp); 783 | event_base_free(evbase); 784 | LOGD("Clean exit"); 785 | return 0; 786 | } 787 | 788 | 789 | // vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 790 | -------------------------------------------------------------------------------- /evhtp_sock_relay.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This example code shows how to write an (optionally encrypting) SSL proxy 3 | * with Libevent's bufferevent layer. 4 | * 5 | * XXX It's a little ugly and should probably be cleaned up. 6 | * */ 7 | 8 | #ifdef HAVE_SPLICE 9 | #define _GNU_SOURCE 1 10 | #endif 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | #ifdef _WIN32 18 | #include 19 | #include 20 | #else 21 | #include 22 | #include 23 | #include 24 | #include 25 | #endif 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #include "connector.h" 34 | #include "utils.h" 35 | 36 | 37 | static void drained_writecb(struct bufferevent *bev, void *ctx); 38 | static void eventcb(struct bufferevent *bev, short what, void *ctx); 39 | 40 | const char* socket_error(char *buf, int len) 41 | { 42 | #ifdef _WIN32 43 | if (FormatMessage( 44 | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 45 | NULL, WSAGetLastError(), 46 | MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 47 | buf, len, NULL)) { 48 | return buf; 49 | } 50 | #elif defined(HAVE_STRERROR_R) 51 | #if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE 52 | if (0 == strerror_r(errno, buf, len)) { 53 | return buf; 54 | } 55 | # else 56 | return strerror_r(errno, buf, len); 57 | # endif 58 | #else 59 | return strerror(errno); 60 | #endif 61 | return ""; 62 | } 63 | 64 | static void 65 | readcb(struct bufferevent *bev, void *ctx) 66 | { 67 | struct bufferevent *partner = ctx; 68 | struct evbuffer *src, *dst; 69 | size_t len; 70 | src = bufferevent_get_input(bev); 71 | len = evbuffer_get_length(src); 72 | if (!partner) { 73 | evbuffer_drain(src, len); 74 | return; 75 | } 76 | dst = bufferevent_get_output(partner); 77 | evbuffer_add_buffer(dst, src); 78 | 79 | if (evbuffer_get_length(dst) >= MAX_OUTPUT) { 80 | /* We're giving the other side data faster than it can 81 | * * pass it on. Stop reading here until we have drained the 82 | * * other side to MAX_OUTPUT/2 bytes. */ 83 | bufferevent_setcb(partner, readcb, drained_writecb, 84 | eventcb, bev); 85 | bufferevent_setwatermark(partner, EV_WRITE, MAX_OUTPUT/2, 86 | MAX_OUTPUT); 87 | bufferevent_disable(bev, EV_READ); 88 | } 89 | } 90 | 91 | static void 92 | drained_writecb(struct bufferevent *bev, void *ctx) 93 | { 94 | struct bufferevent *partner = ctx; 95 | 96 | /* We were choking the other side until we drained our outbuf a bit. 97 | * * Now it seems drained. */ 98 | bufferevent_setcb(bev, readcb, NULL, eventcb, partner); 99 | bufferevent_setwatermark(bev, EV_WRITE, 0, 0); 100 | if (partner) 101 | bufferevent_enable(partner, EV_READ); 102 | } 103 | 104 | static void 105 | close_on_finished_writecb(struct bufferevent *bev, void *ctx) 106 | { 107 | struct evbuffer *b = bufferevent_get_output(bev); 108 | 109 | if (evbuffer_get_length(b) == 0) { 110 | bufferevent_free(bev); 111 | } 112 | } 113 | 114 | static void 115 | eventcb(struct bufferevent *bev, short what, void *ctx) 116 | { 117 | struct bufferevent *partner = ctx; 118 | 119 | if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) { 120 | char buf[4096] = {'\0'}; 121 | if (what & BEV_EVENT_ERROR) { 122 | LOGE("bev %p (sock %d) event: 0x%hx, errno: %s", bev, bufferevent_getfd(bev), 123 | what, socket_error(buf, sizeof(buf))); 124 | } else { 125 | LOGD("bev %p (sock %d) event: 0x%hx", bev, bufferevent_getfd(bev), what); 126 | } 127 | 128 | if (partner) { 129 | /* Flush all pending data */ 130 | readcb(bev, ctx); 131 | 132 | if (evbuffer_get_length( 133 | bufferevent_get_output(partner))) { 134 | /* We still have to flush data from the other 135 | * * side, but when that's done, close the other 136 | * * side. */ 137 | bufferevent_setcb(partner, 138 | NULL, close_on_finished_writecb, 139 | eventcb, NULL); 140 | bufferevent_disable(partner, EV_READ); 141 | } else { 142 | /* We have nothing left to say to the other 143 | * * side; close it. */ 144 | bufferevent_free(partner); 145 | } 146 | } 147 | bufferevent_free(bev); 148 | } 149 | else if (what & BEV_EVENT_CONNECTED){ 150 | 151 | } 152 | } 153 | 154 | #ifdef HAVE_SPLICE 155 | 156 | struct pipe 157 | { 158 | int data; /* data length in pipe buffer */ 159 | int produce; /* pipe, write to */ 160 | int consume; /* pipe, read from */ 161 | }; 162 | 163 | typedef struct sock_relay_ctx_t 164 | { 165 | /* defer free, because of BEV_OPT_CLOSE_ON_FREE */ 166 | struct bufferevent *frontend, *backend; 167 | 168 | int fd_fe, fd_be; 169 | 170 | struct pipe pipe_fe_be; /* channel: frontend -> pipe -> backend */ 171 | struct pipe pipe_be_fe; /* channel: backend -> pipe -> frontend */ 172 | 173 | struct event *frontend_read; 174 | struct event *frontend_write; 175 | struct event *backend_read; 176 | struct event *backend_write; 177 | int eof_bits; /* indicate which channel should stop read */ 178 | } sock_relay_ctx; 179 | 180 | #define FRONTEND_BACKEND_EOF 1 181 | #define BACKEND_FRONTEND_EOF 2 182 | #define BOTH_EOF (FRONTEND_BACKEND_EOF | BACKEND_FRONTEND_EOF) 183 | 184 | int init_pipe(struct pipe *p) 185 | { 186 | p->data = 0; 187 | int pipefd[2] = {0}; 188 | 189 | int rc = pipe2(pipefd, O_NONBLOCK | O_CLOEXEC); 190 | if (rc == -1) 191 | { 192 | LOGE("pipe2 failed: %s", strerror(errno)); 193 | goto fail; 194 | } 195 | else 196 | { 197 | p->produce = pipefd[1]; 198 | p->consume = pipefd[0]; 199 | return 0; 200 | } 201 | 202 | fail: 203 | p->produce = -1; 204 | p->consume = -1; 205 | return -1; 206 | } 207 | 208 | void fini_pipe(struct pipe *p) 209 | { 210 | if (p->data) 211 | { 212 | LOGE("discard %d pipe data", p->data); 213 | } 214 | 215 | if (p->produce >= 0) 216 | { 217 | close(p->produce); 218 | p->produce = -1; 219 | } 220 | if (p->consume >= 0) 221 | { 222 | close(p->consume); 223 | p->consume = -1; 224 | } 225 | } 226 | 227 | void sock_relay_ctx_free(sock_relay_ctx *ctx) 228 | { 229 | LOGD("free with EOF bits %x", ctx->eof_bits); 230 | 231 | /* event_del() and free resource */ 232 | event_free(ctx->frontend_read); 233 | event_free(ctx->frontend_write); 234 | event_free(ctx->backend_read); 235 | event_free(ctx->backend_write); 236 | 237 | fini_pipe(&ctx->pipe_fe_be); 238 | fini_pipe(&ctx->pipe_be_fe); 239 | 240 | bufferevent_free(ctx->frontend); 241 | bufferevent_free(ctx->backend); 242 | 243 | free(ctx); 244 | } 245 | 246 | #define MAX_DATA_IN_PIPE MAX_OUTPUT 247 | 248 | /* 249 | * move from fd to pipe buffer 250 | */ 251 | int socket_to_pipe(sock_relay_ctx *ctx, int fd, struct pipe *pipe, size_t *count) 252 | { 253 | int retval = 0; 254 | size_t len = *count; 255 | 256 | while (len) { 257 | int rc = splice(fd, NULL, pipe->produce, NULL, len, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); 258 | if (rc < 0) { 259 | if (errno == EINTR) { 260 | continue; 261 | } else if (errno == EAGAIN) { 262 | /* there are two reasons for EAGAIN : 263 | * - nothing in the socket buffer (standard) 264 | * - pipe is full 265 | * - the connection is closed (kernel < 2.6.27.13) 266 | */ 267 | 268 | break; 269 | } else { 270 | LOGE("splice error with sock %d: %s", fd, strerror(errno)); 271 | goto fail; 272 | } 273 | } else if (rc == 0) { 274 | // fd end of file (kernel >= 2.6.27.13) 275 | LOGD("splice %d EOF", fd); 276 | goto eof; 277 | 278 | } else { 279 | retval += rc; 280 | len -= rc; 281 | pipe->data += rc; 282 | 283 | LOGD("splice read %d bytes from fd %d", rc, fd); 284 | 285 | break; 286 | } 287 | } 288 | 289 | *count = retval; 290 | return 0; 291 | 292 | eof: 293 | fail: 294 | *count = retval; 295 | return -1; 296 | } 297 | 298 | /* 299 | * move from pipe buffer to out_fd 300 | */ 301 | int socket_from_pipe(sock_relay_ctx *ctx, int fd, struct pipe *pipe, size_t *count) 302 | { 303 | int retval = 0; 304 | size_t len = *count; 305 | 306 | while (len) 307 | { 308 | int rc = splice(pipe->consume, NULL, fd, NULL, len, SPLICE_F_MOVE | SPLICE_F_NONBLOCK/* | SPLICE_F_MORE*/); 309 | if (rc <= 0) { 310 | if (rc == 0 || errno == EAGAIN) { 311 | break; 312 | } else if (errno == EINTR) { 313 | continue; 314 | } else { 315 | LOGE("splice error with sock %d: %s", fd, strerror(errno)); 316 | goto fail; 317 | } 318 | } else { 319 | len -= rc; 320 | pipe->data -= rc; 321 | retval += rc; 322 | 323 | LOGD("splice write %d bytes to fd %d", rc, fd); 324 | break; 325 | } 326 | } 327 | 328 | *count = retval; 329 | return retval; 330 | 331 | fail: 332 | *count = retval; 333 | return -1; 334 | } 335 | 336 | static void relaycb(evutil_socket_t fd, short events, void *arg) 337 | { 338 | sock_relay_ctx *ctx = (sock_relay_ctx*)arg; 339 | 340 | if (events & EV_READ) { 341 | int to_be = (fd == ctx->fd_fe); 342 | struct pipe *pipe = (to_be ? &ctx->pipe_fe_be : &ctx->pipe_be_fe); 343 | struct event *ev_write = (to_be ? ctx->backend_write : ctx->frontend_write); 344 | struct event *ev_read = (to_be ? ctx->frontend_read : ctx->backend_read); 345 | 346 | int try_write = (pipe->data == 0); 347 | size_t count = MAX_DATA_IN_PIPE; 348 | 349 | int rc = socket_to_pipe(ctx, fd, pipe, &count); 350 | if (rc < 0) { 351 | /* stop read when EOF or ERROR */ 352 | event_del(ev_read); 353 | int eof = (to_be ? FRONTEND_BACKEND_EOF : BACKEND_FRONTEND_EOF); 354 | ctx->eof_bits |= eof; 355 | LOGD("set channel EOF bits %x", eof); 356 | } 357 | 358 | if (count > 0 && try_write) { 359 | count = pipe->data; 360 | rc = socket_from_pipe(ctx, (to_be ? ctx->fd_be : ctx->fd_fe), pipe, &count); 361 | } 362 | 363 | if (pipe->data) { 364 | /* stop read and wait write */ 365 | event_del(ev_read); 366 | event_add(ev_write, NULL); 367 | } 368 | } else if (events | EV_WRITE) { 369 | int to_be = (fd == ctx->fd_be); 370 | struct pipe *pipe = (to_be ? &ctx->pipe_fe_be : &ctx->pipe_be_fe); 371 | struct event *ev_write = (to_be ? ctx->backend_write : ctx->frontend_write); 372 | struct event *ev_read = (to_be ? ctx->frontend_read : ctx->backend_read); 373 | 374 | size_t count = pipe->data; 375 | 376 | int rc = socket_from_pipe(ctx, fd, pipe, &count); 377 | if (rc < 0) { 378 | /* stop write when ERROR */ 379 | event_del(ev_write); 380 | int eof = (to_be ? FRONTEND_BACKEND_EOF : BACKEND_FRONTEND_EOF); 381 | ctx->eof_bits |= eof; 382 | LOGD("set channel EOF bits %x", eof); 383 | } 384 | 385 | if (pipe->data == 0) { 386 | /* stop write and wait read*/ 387 | event_del(ev_write); 388 | event_add(ev_read, NULL); 389 | } 390 | } 391 | 392 | if (ctx->eof_bits & BOTH_EOF) { 393 | if (BOTH_EOF == (ctx->eof_bits & BOTH_EOF)) { 394 | sock_relay_ctx_free(ctx); /* both channel detect error */ 395 | } else if (ctx->pipe_fe_be.data == 0 && ctx->pipe_be_fe.data == 0) { 396 | sock_relay_ctx_free(ctx); /* one socket EOF or error, but other channel wait read */ 397 | } 398 | } 399 | } 400 | 401 | static int use_splice = 1; 402 | 403 | int flush_bufferevent_to_pipe(struct bufferevent *bev, struct pipe *pipe) 404 | { 405 | struct evbuffer *evbuf = bufferevent_get_output(bev); 406 | int len = evbuffer_get_length(evbuf); 407 | if (len > 0) { 408 | int iovec_len = evbuffer_peek(evbuf, -1, NULL, NULL, 0); 409 | 410 | struct iovec iov[iovec_len]; 411 | 412 | evbuffer_peek(evbuf, -1, NULL, iov, iovec_len); 413 | 414 | ssize_t rc = vmsplice(pipe->produce, iov, 415 | iovec_len, SPLICE_F_NONBLOCK); 416 | if (rc < 0) { 417 | LOGE("vmsplice error: %s", strerror(errno)); 418 | return -1; 419 | } 420 | else if (rc != len) 421 | { 422 | LOGE("too long to fit pipe buffer"); 423 | return -1; 424 | } 425 | 426 | // ok 427 | evbuffer_drain(evbuf, len); 428 | pipe->data += len; 429 | } 430 | 431 | return 0; 432 | } 433 | #endif 434 | 435 | /* 436 | * local/frontend/ 437 | * remote/backend/upstream 438 | */ 439 | void 440 | relay(struct bufferevent *local, struct bufferevent *remote) 441 | { 442 | LOGD("relay bev %p <--> %p", local, remote); 443 | #ifdef HAVE_SPLICE 444 | if (use_splice && !g_https_proxy && bufferevent_get_underlying(remote) == NULL) { 445 | sock_relay_ctx *conn = calloc(sizeof(sock_relay_ctx), 1); 446 | assert(conn); 447 | 448 | conn->frontend = local; 449 | conn->backend = remote; 450 | conn->fd_fe = bufferevent_getfd(conn->frontend); 451 | conn->fd_be = bufferevent_getfd(conn->backend); 452 | bufferevent_disable(local, EV_READ | EV_WRITE); 453 | bufferevent_disable(remote, EV_READ | EV_WRITE); 454 | 455 | if (-1 == init_pipe(&conn->pipe_fe_be) || 456 | -1 == init_pipe(&conn->pipe_be_fe)) { 457 | goto fail; 458 | } 459 | 460 | struct event_base *base = bufferevent_get_base(conn->frontend); 461 | 462 | // relay input buffer 463 | #define RELAY_BUFFER(from, to) do { \ 464 | if (evbuffer_get_length(bufferevent_get_input(from)) > 0) { \ 465 | evbuffer_add_buffer(bufferevent_get_output(to), bufferevent_get_input(from)); \ 466 | } \ 467 | } while (0) 468 | 469 | RELAY_BUFFER(local, remote); 470 | RELAY_BUFFER(remote, local); 471 | 472 | // flush output buffer to pipe; 473 | if (0 != flush_bufferevent_to_pipe(local, &conn->pipe_be_fe) || 474 | 0 != flush_bufferevent_to_pipe(remote, &conn->pipe_fe_be)) { 475 | goto fail; 476 | } 477 | 478 | // 479 | conn->frontend_read = event_new(base, conn->fd_fe, EV_PERSIST | EV_READ, relaycb, conn); 480 | conn->frontend_write = event_new(base, conn->fd_fe, EV_PERSIST | EV_WRITE, relaycb, conn); 481 | 482 | conn->backend_read = event_new(base, conn->fd_be, EV_PERSIST | EV_READ, relaycb, conn); 483 | conn->backend_write = event_new(base, conn->fd_be, EV_PERSIST | EV_WRITE, relaycb, conn); 484 | 485 | // setup read or write event 486 | if (conn->pipe_fe_be.data) { 487 | event_add(conn->backend_write, NULL); 488 | } else { 489 | event_add(conn->frontend_read, NULL); 490 | } 491 | 492 | if (conn->pipe_be_fe.data) { 493 | event_add(conn->frontend_write, NULL); 494 | } else { 495 | event_add(conn->backend_read, NULL); 496 | } 497 | 498 | return; 499 | 500 | fail: 501 | sock_relay_ctx_free(conn); 502 | } else 503 | #endif 504 | { 505 | bufferevent_setcb(local, readcb, NULL, eventcb, remote); 506 | bufferevent_setcb(remote, readcb, NULL, eventcb, local); 507 | 508 | bufferevent_enable(local, EV_READ | EV_WRITE); 509 | bufferevent_enable(remote, EV_READ | EV_WRITE); 510 | } 511 | } 512 | 513 | 514 | 515 | 516 | -------------------------------------------------------------------------------- /http_connector.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include "libevhtp/htparse.h" 12 | 13 | #include "connector.h" 14 | 15 | 16 | enum http_conn_status { 17 | HTTP_CONN_TCP_INIT = 0, 18 | HTTP_CONN_INIT = 100, /* HTTP CONNECT method */ 19 | HTTP_CONN_REQUEST_SENT, 20 | HTTP_CONN_CONNECT_TRANSMITTING, 21 | HTTP_CONN_ERROR 22 | }; 23 | 24 | /* 25 | * http_conn 26 | */ 27 | typedef struct http_conn_t { 28 | struct bufferevent *client; 29 | //struct bufferevent *dst; 30 | enum http_conn_status status; 31 | 32 | char host[256]; 33 | uint16_t port; 34 | uint8_t response_complete; 35 | htparser *parser; 36 | connect_callback cb; 37 | void *arg; 38 | } http_conn; 39 | 40 | static void free_http_conn(http_conn *conn) 41 | { 42 | /* ignore bufferevent which will be returned */ 43 | if (conn->parser) { 44 | free(conn->parser); 45 | conn->parser = NULL; 46 | } 47 | free(conn); 48 | } 49 | 50 | static void send_request(http_conn *conn) 51 | { 52 | char data[1024] = {'\0'}; 53 | size_t data_len = sizeof(data) - 1; 54 | int ret = snprintf(data, data_len, 55 | "CONNECT %s:%d HTTP/1.1\r\n" 56 | "Host: %s:%d\r\n" 57 | "Proxy-Connection: Keep-Alive\r\n" 58 | "\r\n", conn->host, conn->port, conn->host, conn->port); 59 | if (ret == -1 || ret >= data_len) { 60 | LOGE("format HTTP request failed"); 61 | goto fail; 62 | } 63 | 64 | bufferevent_write(conn->client, data, ret); 65 | bufferevent_enable(conn->client, EV_READ | EV_WRITE); 66 | 67 | conn->status = HTTP_CONN_REQUEST_SENT; 68 | return; 69 | 70 | fail: 71 | conn->status = HTTP_CONN_ERROR; 72 | } 73 | 74 | static int _hdrs_complete(htparser * p) { 75 | http_conn * conn = (http_conn *)htparser_get_userdata(p); 76 | 77 | conn->response_complete = 1; 78 | 79 | /* 0 need body, 1 no body */ 80 | return 1; 81 | } 82 | 83 | static htparse_hooks hooks = { 84 | .on_hdrs_complete = _hdrs_complete 85 | }; 86 | 87 | static void read_response(http_conn *conn) 88 | { 89 | struct evbuffer *buffer; 90 | size_t have; 91 | size_t parsed_sz; 92 | htparser *p = conn->parser; 93 | 94 | buffer = bufferevent_get_input(conn->client); 95 | have = evbuffer_get_length(buffer); 96 | char *data = (char *)evbuffer_pullup(buffer, have); 97 | 98 | /* TODO: response have body */ 99 | parsed_sz = htparser_run(p, &hooks, data, have); 100 | 101 | evbuffer_drain(buffer, parsed_sz); 102 | if (htparser_get_error(p) != htparse_error_none) { 103 | LOGE("parse HTTP response failed: %s", htparser_get_strerror(p)); 104 | goto fail; 105 | } 106 | 107 | if (conn->response_complete) { 108 | unsigned int status = htparser_get_status(p); 109 | if (status >= 200 && status < 300) { 110 | assert(parsed_sz == have); 111 | conn->status = HTTP_CONN_CONNECT_TRANSMITTING; 112 | } else { 113 | LOGE("HTTP response status: %d", status); 114 | goto fail; 115 | } 116 | } 117 | return; 118 | 119 | fail: 120 | conn->status = HTTP_CONN_ERROR; 121 | return; 122 | } 123 | 124 | static void readcb(struct bufferevent *bev, void *ctx) 125 | { 126 | http_conn *conn = (http_conn*)ctx; 127 | 128 | switch (conn->status) 129 | { 130 | case HTTP_CONN_REQUEST_SENT: 131 | read_response(conn); 132 | break; 133 | default: 134 | break; 135 | } 136 | LOGD("connection status: %d", conn->status); 137 | 138 | if (conn->status == HTTP_CONN_CONNECT_TRANSMITTING) { 139 | LOGD("HTTP negotiate successfully"); 140 | bufferevent_setcb(bev, NULL, NULL, NULL, NULL); 141 | 142 | conn->cb(bev, conn->arg); 143 | 144 | free_http_conn(conn); 145 | } else if (conn->status == HTTP_CONN_ERROR) { 146 | LOGE("HTTP negotiate ERROR"); 147 | // error 148 | conn->cb(NULL, conn->arg); 149 | 150 | free_http_conn(conn); 151 | bufferevent_free(bev); // protocol error, close socket 152 | } 153 | } 154 | 155 | static void eventcb(struct bufferevent *bev, short what, void *ctx) 156 | { 157 | http_conn *conn = (http_conn*)ctx; 158 | if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) { 159 | char buf[4096] = {'\0'}; 160 | // during handshake, EOF is an error also 161 | LOGE("bev %p (sock %d) event: 0x%hx %s", bev, bufferevent_getfd(bev), what, socket_error(buf, sizeof(buf))); 162 | 163 | goto fail; 164 | } else if (what & BEV_EVENT_CONNECTED) { 165 | LOGD("upstrem connected with bev %p (sock %d)", bev, bufferevent_getfd(bev)); 166 | #if defined TCP_NODELAY 167 | if (g_enable_nodelay == 1) { 168 | int on = 1; 169 | setsockopt(bufferevent_getfd(bev), IPPROTO_TCP, TCP_NODELAY, (void *)&on, sizeof(on)); 170 | } 171 | #endif 172 | 173 | if (conn->status == HTTP_CONN_INIT) { 174 | /* HTTP */ 175 | send_request(conn); 176 | 177 | if (conn->status == HTTP_CONN_ERROR) { 178 | goto fail; 179 | } 180 | } else { 181 | /* TCP */ 182 | bufferevent_setcb(bev, NULL, NULL, NULL, NULL); 183 | 184 | conn->cb(bev, conn->arg); 185 | 186 | free_http_conn(conn); 187 | } 188 | } 189 | return; 190 | 191 | fail: 192 | // error 193 | conn->cb(NULL, conn->arg); 194 | 195 | free_http_conn(conn); 196 | bufferevent_free(bev); 197 | } 198 | 199 | void connect_http(struct event_base *evbase, struct evdns_base *evdns_base, const char *hostname, int port, connect_callback cb, void *arg) 200 | { 201 | struct bufferevent *bev = NULL; 202 | http_conn *conn = (http_conn*)calloc(1, sizeof(http_conn)); 203 | if (NULL == conn) { 204 | goto fail; 205 | } 206 | 207 | strcpy(conn->host, hostname); 208 | conn->port = port; 209 | conn->cb = cb; 210 | conn->arg = arg; 211 | 212 | if (hostname && port) { 213 | /* tunnel via HTTP CONNECT method */ 214 | htparser * p = htparser_new(); 215 | if (p == NULL) { 216 | goto fail; 217 | } 218 | htparser_init(p, htp_type_response); 219 | htparser_set_userdata(p, conn); 220 | conn->parser = p; 221 | 222 | conn->status = HTTP_CONN_INIT; 223 | } /* else: just a connection to HTTP proxy */ 224 | 225 | hostname = g_socks_server; 226 | port =g_socks_port; 227 | 228 | bev = bufferevent_socket_new(evbase, -1, BEV_OPT_CLOSE_ON_FREE/*|BEV_OPT_DEFER_CALLBACKS*/); 229 | if (NULL == bev) { 230 | LOGE("bufferevent create failed"); 231 | goto fail; 232 | } 233 | 234 | // eventcb() might be called in bufferevent_socket_connect_hostname(), when name resolve is done 235 | // immediately and bufferevent_socket_connect() failed immediately. 236 | // When hostname is pure IP address, or hostname is in /etc/hosts file, evutil_getaddrinfo_async() call its 237 | // callback in itself, not after. 238 | // bufferevent_socket_connect() usually failed immediately with socket() exceed ulimit open files. 239 | conn->client = bev; 240 | bufferevent_setcb(bev, readcb, NULL, eventcb, conn); /* must be set before bufferevent_socket_connect_hostname() */ 241 | 242 | if (bufferevent_socket_connect_hostname(bev, evdns_base, PF_UNSPEC, hostname, port) < 0) { 243 | LOGE("bufferevent connect %s:%d failed", hostname, port); 244 | goto fail; 245 | } 246 | 247 | // Because eventcb() might have been called, so we cannot do anything with bev or conn here. 248 | // If you want, you must use BEV_OPT_DEFER_CALLBACKS to force eventcb() executed after bufferevent_socket_connect_hostname(). 249 | 250 | return; 251 | 252 | fail: 253 | if (bev) 254 | bufferevent_free(bev); 255 | cb(NULL, arg); 256 | if (conn) 257 | free_http_conn(conn); 258 | } 259 | 260 | #if 0 261 | 262 | void connect_cb(struct bufferevent *bev, void *arg) 263 | { 264 | if (bev) { 265 | fprintf(stderr, "connect success\n"); 266 | 267 | const char headers[] = 268 | "GET / HTTP/1.1\r\n" 269 | "Connection: Keep-Alive\r\n" 270 | "\r\n"; 271 | bufferevent_write(bev, headers, sizeof(headers) - 1); // without ending '\0' 272 | } else { 273 | fprintf(stderr, "connect fail\n"); 274 | } 275 | } 276 | 277 | const char *g_socks_server = "127.0.0.1"; 278 | int g_socks_port = 1080; 279 | 280 | int main( int argc, char* argv[] ) 281 | { 282 | struct event *ev_sigterm; 283 | event_base *evbase; 284 | evdns_base *evdns; 285 | 286 | #ifdef WIN32 287 | WORD wVersionRequested; 288 | WSADATA wsaData; 289 | int err; 290 | 291 | /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */ 292 | wVersionRequested = MAKEWORD(2, 2); 293 | 294 | err = WSAStartup(wVersionRequested, &wsaData); 295 | #endif 296 | 297 | evbase = event_base_new(); 298 | evdns = evdns_base_new(evbase, 1); 299 | evdns_base_set_option(evdns, "randomize-case:", "0"); 300 | 301 | #ifndef WIN32 302 | ev_sigterm = evsignal_new(evbase, SIGTERM, sigterm_cb, evbase); 303 | evsignal_add(ev_sigterm, NULL); 304 | #endif 305 | 306 | connect_http(evbase, evdns, "www.baidu.com", 80, connect_cb, NULL); 307 | 308 | event_base_loop(evbase, 0); 309 | 310 | printf("Clean exit\n"); 311 | return 0; 312 | } 313 | #endif 314 | -------------------------------------------------------------------------------- /log.c: -------------------------------------------------------------------------------- 1 | #include "log.h" 2 | 3 | #define DEFAULT_LOG_FILE stdout 4 | 5 | LogPriority log_prio_base = LOG_LEVEL_DEBUG; 6 | FILE *log_file = NULL; 7 | 8 | void log_init(const char *filename, LogPriority prio) 9 | { 10 | FILE *f = NULL; 11 | log_prio_base = prio; 12 | 13 | if (filename && (f = fopen(filename, "a"))) { 14 | log_file = f; 15 | } else { 16 | log_file = DEFAULT_LOG_FILE; 17 | } 18 | } 19 | 20 | void log_fini() 21 | { 22 | if (log_file != DEFAULT_LOG_FILE) { 23 | fclose(log_file); 24 | } 25 | } 26 | 27 | 28 | -------------------------------------------------------------------------------- /log.h: -------------------------------------------------------------------------------- 1 | #ifndef __LOG_H__ 2 | #define __LOG_H__ 3 | 4 | #include 5 | #include 6 | 7 | #define __QUOTE(x) # x 8 | #define _QUOTE(x) __QUOTE(x) 9 | #if _WIN32 10 | # define DIRECTORY_SEPARATOR_CHAR '\\' 11 | #else 12 | # define DIRECTORY_SEPARATOR_CHAR '/' 13 | #endif 14 | 15 | #ifdef _MSC_VER 16 | # define inline __inline 17 | # if _MSC_VER <= 1800 /* VC++ 2013 claim this, but still leads to C2065, so try VC++ 2015 */ 18 | # define __func__ __FUNCTION__ 19 | /* VC++ 2015 have C99 snprintf */ 20 | # define snprintf evutil_snprintf 21 | # endif 22 | #endif 23 | 24 | #define __FILENAME__ (strrchr(__FILE__, DIRECTORY_SEPARATOR_CHAR) ? \ 25 | strrchr(__FILE__, DIRECTORY_SEPARATOR_CHAR) + 1 : __FILE__) 26 | 27 | #ifdef ANDROID 28 | # include 29 | 30 | #define TAG "mproxy" 31 | 32 | #define LOG(prio, fmt, ...) \ 33 | ((void)__android_log_print(prio, TAG, \ 34 | __FILE__ ":[" _QUOTE(__LINE__) "]\t" fmt, ## __VA_ARGS__)) 35 | 36 | #define LOGD(...) LOG(ANDROID_LOG_DEBUG, __VA_ARGS__) 37 | #define LOGI(...) LOG(ANDROID_LOG_INFO, __VA_ARGS__) 38 | #define LOGW(...) LOG(ANDROID_LOG_WARN, __VA_ARGS__) 39 | #define LOGE(...) LOG(ANDROID_LOG_ERROR, __VA_ARGS__) 40 | 41 | #else 42 | typedef enum LogPriority { 43 | LOG_LEVEL_VERBOSE, 44 | LOG_LEVEL_DEBUG, 45 | LOG_LEVEL_INFO, 46 | LOG_LEVEL_WARN, 47 | LOG_LEVEL_ERROR, 48 | LOG_LEVEL_FATAL, 49 | } LogPriority; 50 | 51 | extern LogPriority log_prio_base; 52 | extern FILE *log_file; 53 | 54 | static inline const char* PRIORITY_TO_STRING(LogPriority prio) 55 | { 56 | #define case_statement(x) case LOG_LEVEL_ ## x: return (#x); 57 | 58 | switch(prio) 59 | { 60 | case_statement(DEBUG); 61 | case_statement(INFO); 62 | case_statement(WARN); 63 | case_statement(ERROR); 64 | case_statement(FATAL); 65 | default: 66 | return ("UNKOWN"); 67 | } 68 | 69 | #undef case_statement 70 | } 71 | 72 | #if defined(_WIN32) 73 | /* The Visual C++ implementation will suppress a trailing comma if no arguments are passed to the ellipsis. */ 74 | #define LOG(prio, fmt, ...) do { \ 75 | if (prio >= log_prio_base) { \ 76 | time_t t = time(NULL); \ 77 | struct tm dm; localtime_s(&dm, &t); \ 78 | \ 79 | fprintf(log_file, "[%02d:%02d:%02d] %s %s:[" _QUOTE(__LINE__) "]: " \ 80 | fmt "\n", dm.tm_hour, dm.tm_min, dm.tm_sec, PRIORITY_TO_STRING(prio), __FILENAME__, ## __VA_ARGS__); \ 81 | fflush(log_file); \ 82 | } \ 83 | } while (0) 84 | #else 85 | #define LOG(prio, fmt, ...) do { \ 86 | if (prio >= log_prio_base) { \ 87 | time_t t = time(NULL); \ 88 | struct tm dm; localtime_r(&t, &dm); \ 89 | \ 90 | fprintf(log_file, "[%02d:%02d:%02d] %s %s:[" _QUOTE(__LINE__) "]: " \ 91 | fmt "\n", dm.tm_hour, dm.tm_min, dm.tm_sec, PRIORITY_TO_STRING(prio), __FILENAME__, ## __VA_ARGS__); \ 92 | fflush(log_file); \ 93 | } \ 94 | } while (0) 95 | #endif 96 | 97 | #ifdef _MSC_VER 98 | #define LOGD(fmt, ...) LOG(LOG_LEVEL_DEBUG, fmt, ## __VA_ARGS__) 99 | #define LOGI(fmt, ...) LOG(LOG_LEVEL_INFO, fmt, ## __VA_ARGS__) 100 | #define LOGW(fmt, ...) LOG(LOG_LEVEL_WARN, fmt, ## __VA_ARGS__) 101 | #define LOGE(fmt, ...) LOG(LOG_LEVEL_ERROR, fmt, ## __VA_ARGS__) 102 | #else 103 | #define LOGD(fmt, ...) LOG(LOG_LEVEL_DEBUG, fmt, ## __VA_ARGS__) 104 | #define LOGI(fmt, ...) LOG(LOG_LEVEL_INFO, fmt, ## __VA_ARGS__) 105 | #define LOGW(fmt, ...) LOG(LOG_LEVEL_WARN, fmt, ## __VA_ARGS__) 106 | #define LOGE(fmt, ...) LOG(LOG_LEVEL_ERROR, fmt, ## __VA_ARGS__) 107 | #endif 108 | 109 | void log_init(const char *filename, LogPriority prio); 110 | void log_fini(); 111 | 112 | #endif 113 | 114 | #endif 115 | -------------------------------------------------------------------------------- /lru.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include "evhtp.h" 11 | #include "connector.h" 12 | 13 | #ifdef _MSC_VER 14 | #define strcasecmp _stricmp 15 | #endif 16 | #define container_of(ptr, type, member) ({ \ 17 | const typeof( ((type *)0)->member ) *__mptr = (ptr); \ 18 | (type *)( (char *)__mptr - offsetof(type,member) );}) 19 | 20 | #define LRU_LIFE 30 21 | 22 | static evhtp_res lru_conn_error(evhtp_connection_t *connection, evhtp_error_flags errtype, void *arg); 23 | 24 | struct tree_item; 25 | 26 | struct connection_item 27 | { 28 | evhtp_connection_t *connection; 29 | time_t last_use; 30 | struct tree_item *parent; 31 | 32 | TAILQ_ENTRY(connection_item) queue_field; 33 | TAILQ_ENTRY(connection_item) tree_list_field; 34 | }; 35 | 36 | struct tree_item 37 | { 38 | char hostname[256]; 39 | int port; 40 | 41 | TAILQ_HEAD(, connection_item) free_list; 42 | 43 | RB_ENTRY(tree_item) field; 44 | }; 45 | 46 | TAILQ_HEAD(queue, connection_item); 47 | 48 | static int TreeItemCompare(const struct tree_item *lhs, const struct tree_item *rhs) 49 | { 50 | if (lhs->port == rhs->port) { 51 | return strcasecmp(lhs->hostname, rhs->hostname); 52 | } else { 53 | return lhs->port - rhs->port; 54 | } 55 | } 56 | 57 | RB_HEAD(lru_tree, tree_item); 58 | RB_GENERATE(lru_tree, tree_item, field, TreeItemCompare); 59 | 60 | struct lru_base 61 | { 62 | struct queue queue; 63 | struct lru_tree tree_head; 64 | struct event_base *evbase; 65 | struct event *timer_ev; 66 | }; 67 | 68 | static struct lru_base *lru; 69 | 70 | evhtp_connection_t * cache_get(const char *hostname, int port) 71 | { 72 | evhtp_connection_t *retval = NULL; 73 | struct tree_item *ti = NULL; 74 | 75 | struct tree_item item; 76 | strcpy(item.hostname, hostname); 77 | item.port = port; 78 | 79 | ti = RB_FIND(lru_tree, &lru->tree_head, &item); 80 | if (ti) { 81 | struct connection_item *bi = TAILQ_FIRST(&ti->free_list); 82 | if (bi) { 83 | assert(bi->parent == ti); 84 | LOGD("LRU get connection %p %s:%d, last %d", bi->connection, hostname, (int)port, (int)bi->last_use); 85 | TAILQ_REMOVE(&ti->free_list, bi, tree_list_field); // remove from tree 86 | if (TAILQ_EMPTY(&ti->free_list)) { 87 | ti = RB_REMOVE(lru_tree, &lru->tree_head, ti); // list empty then erase tree item 88 | assert(ti); 89 | free(ti); 90 | } 91 | 92 | bi->parent = NULL; 93 | TAILQ_REMOVE(&lru->queue, bi, queue_field); // remove from queue 94 | retval = bi->connection; 95 | evhtp_unset_hook(&bi->connection->hooks, evhtp_hook_on_conn_error); 96 | free(bi); 97 | return retval; 98 | } 99 | } 100 | 101 | return NULL; 102 | } 103 | 104 | void cache_put(const char *hostname, int port, evhtp_connection_t *conn) 105 | { 106 | struct tree_item *ti; 107 | struct tree_item item; 108 | strcpy(item.hostname, hostname); 109 | item.port = port; 110 | 111 | ti = RB_FIND(lru_tree, &lru->tree_head, &item); 112 | if (ti == NULL) { 113 | ti = (struct tree_item *)calloc(1, sizeof(*ti)); 114 | assert(ti); 115 | TAILQ_INIT(&ti->free_list); 116 | strcpy(ti->hostname, hostname); 117 | ti->port = port; 118 | 119 | if (RB_INSERT(lru_tree, &lru->tree_head, ti)) { 120 | assert(0); 121 | } 122 | } 123 | 124 | { 125 | struct timeval tv; 126 | struct connection_item *bi = (struct connection_item *)calloc(1, sizeof(struct connection_item)); 127 | assert(bi); 128 | bi->connection = conn; 129 | event_base_gettimeofday_cached(lru->evbase, &tv); 130 | bi->last_use = tv.tv_sec; 131 | bi->parent = ti; 132 | TAILQ_INSERT_HEAD(&ti->free_list, bi, tree_list_field); // insert tree list 133 | 134 | // check clear timer 135 | if (TAILQ_EMPTY(&lru->queue) && event_pending(lru->timer_ev, EV_TIMEOUT, NULL) == 0) { 136 | struct timeval timeout = {LRU_LIFE, 0}; 137 | event_add(lru->timer_ev, &timeout); 138 | } 139 | TAILQ_INSERT_HEAD(&lru->queue, bi, queue_field); // insert into queue 140 | 141 | evhtp_set_hook(&bi->connection->hooks, evhtp_hook_on_conn_error, (evhtp_hook)lru_conn_error, bi); 142 | LOGD("LRU put connection %p %s:%d, last %d", conn, hostname, (int)port, (int)bi->last_use); 143 | } 144 | 145 | } 146 | 147 | #ifndef TAILQ_FOREACH_REVERSE_SAFE 148 | #define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \ 149 | for ((var) = TAILQ_LAST((head), headname); \ 150 | (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \ 151 | (var) = (tvar)) 152 | #endif 153 | 154 | #ifndef RB_FOREACH_SAFE 155 | #define RB_FOREACH_SAFE(x, name, head, tvar) \ 156 | for ((x) = RB_MIN(name, head); \ 157 | ((x) != NULL) && ((tvar) = name ## _RB_NEXT(x), (x) != NULL); \ 158 | (x) = (tvar)) 159 | #endif 160 | 161 | static void clear_item(struct connection_item *bi, int error) 162 | { 163 | LOGD("LRU clear connection %p %s:%d, last %d", bi->connection, bi->parent->hostname, (int)bi->parent->port, (int)bi->last_use); 164 | TAILQ_REMOVE(&bi->parent->free_list, bi, tree_list_field); // remove from tree free list 165 | 166 | if (TAILQ_EMPTY(&bi->parent->free_list)) { 167 | // empty tree item 168 | struct tree_item *ti; 169 | ti = RB_REMOVE(lru_tree, &lru->tree_head, bi->parent); 170 | assert(ti && ti == bi->parent); 171 | free(ti); 172 | } 173 | 174 | TAILQ_REMOVE(&lru->queue, bi, queue_field); // remove from queue 175 | evhtp_unset_hook(&bi->connection->hooks, evhtp_hook_on_conn_error); 176 | if (!error) 177 | evhtp_connection_free(bi->connection); 178 | free(bi); 179 | } 180 | 181 | static void timercb(evutil_socket_t fd, short events, void *arg) 182 | { 183 | struct connection_item *bi = NULL; 184 | struct connection_item *temp; 185 | struct timeval tv; 186 | event_base_gettimeofday_cached(lru->evbase, &tv); 187 | 188 | TAILQ_FOREACH_REVERSE_SAFE(bi, &lru->queue, queue, queue_field, temp) { 189 | if (tv.tv_sec < LRU_LIFE + bi->last_use) 190 | break; 191 | 192 | LOGD("LRU timeout connection %p %s:%d, last %d, now %d", bi->connection, bi->parent->hostname, (int)bi->parent->port, (int)bi->last_use, (int)tv.tv_sec); 193 | clear_item(bi, 0); 194 | } 195 | 196 | if (!TAILQ_EMPTY(&lru->queue)) 197 | { 198 | bi = TAILQ_LAST(&lru->queue, queue); 199 | struct timeval timeout = { .tv_sec = LRU_LIFE + bi->last_use - tv.tv_sec, .tv_usec = 0 }; 200 | event_add(lru->timer_ev, &timeout); 201 | } 202 | } 203 | 204 | struct lru_connect_cb_arg 205 | { 206 | lru_get_callback cb; 207 | evhtp_request_t *req; 208 | }; 209 | 210 | static void lru_connect_cb(struct bufferevent *bev, void *arg) 211 | { 212 | evhtp_connection_t *conn = NULL; 213 | struct lru_connect_cb_arg *connect_arg = (struct lru_connect_cb_arg*)arg; 214 | 215 | if (bev) { 216 | conn = evhtp_connection_new_from_bev(bev); 217 | LOGD("create connection %p from bev %p", conn, evhtp_connection_get_bev(conn)); 218 | } else { 219 | LOGE("lru_connect connect error"); 220 | } 221 | 222 | connect_arg->cb(conn, connect_arg->req); 223 | free(connect_arg); 224 | } 225 | 226 | static evhtp_res lru_conn_error(evhtp_connection_t * connection, evhtp_error_flags errtype, void * arg) 227 | { 228 | struct connection_item *bi = (struct connection_item *)arg; 229 | assert (bi && bi->parent && bi->connection == connection); 230 | LOGD("connection %p (bev %p %s:%d) hook error %hu", connection, evhtp_connection_get_bev(connection), 231 | bi->parent->hostname, (int)bi->parent->port, errtype); 232 | clear_item(bi, 1); 233 | 234 | return EVHTP_RES_OK; 235 | } 236 | 237 | int lru_init(evbase_t *base) 238 | { 239 | lru = calloc(sizeof(struct lru_base), 1); 240 | if (NULL == lru) { 241 | goto fail; 242 | } 243 | TAILQ_INIT(&lru->queue); 244 | RB_INIT(&lru->tree_head); 245 | 246 | lru->evbase = base; 247 | lru->timer_ev = event_new(base, -1, 0, timercb, base); 248 | if (NULL == lru->timer_ev) { 249 | goto fail; 250 | } 251 | 252 | return 0; 253 | 254 | fail: 255 | if (lru) { 256 | free(lru); 257 | lru = NULL; 258 | } 259 | return -1; 260 | } 261 | 262 | void lru_fini() 263 | { 264 | struct connection_item *bi = NULL; 265 | struct connection_item *temp; 266 | 267 | LOGD("LRU fini"); 268 | TAILQ_FOREACH_REVERSE_SAFE(bi, &lru->queue, queue, queue_field, temp) { 269 | clear_item(bi, 0); 270 | } 271 | 272 | if (lru->timer_ev) { 273 | event_del(lru->timer_ev); 274 | event_free(lru->timer_ev); 275 | } 276 | 277 | free(lru); 278 | lru = NULL; 279 | } 280 | 281 | void lru_get(const char *host, uint16_t port, lru_get_callback cb, void *arg) 282 | { 283 | evhtp_request_t * req = (evhtp_request_t *)arg; 284 | evhtp_connection_t *conn = cache_get(host, port); 285 | if (conn) { 286 | LOGD("LRU get connection %p (bev %p) from cache %s:%d", conn, evhtp_connection_get_bev(conn), host, (int)port); 287 | cb(conn, arg); 288 | } else { 289 | struct lru_connect_cb_arg *connect_arg = 290 | (struct lru_connect_cb_arg*)calloc(1, sizeof(struct lru_connect_cb_arg)); 291 | assert(connect_arg); 292 | connect_arg->cb = cb; 293 | connect_arg->req = req; 294 | connect_upstream(req->conn->evbase, evdns, host, port, lru_connect_cb, connect_arg); // async connect 295 | } 296 | } 297 | 298 | void lru_set(const char *host, uint16_t port, evhtp_connection_t *conn) 299 | { 300 | cache_put(host, port, conn); 301 | } 302 | -------------------------------------------------------------------------------- /parse_forward_param.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | #define INET6_ADDRSTRLEN 46 6 | 7 | struct forwarder_param_t 8 | { 9 | char bind_ip[INET6_ADDRSTRLEN]; 10 | char forward_ip[INET6_ADDRSTRLEN]; 11 | unsigned short bind_port; 12 | unsigned short forward_port; 13 | }; 14 | 15 | int parse_forward_param(const char *str, size_t len, struct forwarder_param_t *param); 16 | 17 | -------------------------------------------------------------------------------- /parse_forward_param.rl: -------------------------------------------------------------------------------- 1 | #include "parse_forward_param.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #if DEBUG 8 | # define LOGE(fmt, ...) fprintf(stderr, fmt "\n", ## __VA_ARGS__) 9 | # define LOGD LOGE 10 | #else 11 | # include "log.h" 12 | #endif 13 | 14 | 15 | %%{ 16 | machine parse_forward_param; 17 | 18 | action char {;} 19 | action err_char { 20 | LOGE("%*s", (int)len, str); 21 | LOGE("%*s", (int)(1 + p - str), "^"); 22 | goto fail; 23 | } 24 | 25 | action init_bind_ip {bind_ip_start = p;} 26 | action finish_bind_ip { 27 | LOGD("bind ip %.*s", (int)(p - bind_ip_start), bind_ip_start); 28 | strncpy(param->bind_ip, bind_ip_start, p - bind_ip_start); 29 | } 30 | 31 | action init_bind_port {bind_port_start = p;} 32 | action finish_bind_port { 33 | LOGD("bind port %.*s", (int)(p - bind_port_start), bind_port_start); 34 | int port = atoi(bind_port_start); 35 | if (port <= 0 || port > 65535) { 36 | LOGE("invalid port range"); 37 | goto fail; 38 | } 39 | param->bind_port = (unsigned short)port; 40 | } 41 | 42 | action init_forward_ip {forward_ip_start = p;} 43 | action finish_forward_ip { 44 | LOGD("forward ip %.*s", (int)(p - forward_ip_start), forward_ip_start); 45 | strncpy(param->forward_ip, forward_ip_start, p - forward_ip_start); 46 | } 47 | 48 | action init_forward_port {forward_port_start = p;} 49 | action finish_forward_port { 50 | LOGD("forward port %.*s", (int)(p - forward_port_start), forward_port_start); 51 | int port = atoi(forward_port_start); 52 | if (port <= 0 || port > 65535) { 53 | LOGE("invalid port range"); 54 | goto fail; 55 | } 56 | param->forward_port = (unsigned short)port; 57 | } 58 | 59 | 60 | #alpha = [a-zA-Z]; 61 | #digit = [0-9]; 62 | hexdigit = [0-9a-fA-F]; 63 | unreserved = alpha | digit | [\-._~]; 64 | pct_encoded = "%" hexdigit{2}; 65 | sub_delims = [!$&'()*+,;=]; 66 | pchar = unreserved | pct_encoded | sub_delims | [:@]; 67 | 68 | scheme = alpha (alpha | digit | [\-+.])*; 69 | userinfo = (unreserved | pct_encoded | sub_delims | ":")* ; 70 | dec_octet 71 | = digit 72 | | [\x31-\x39] digit 73 | | "1" digit{2} 74 | | "2" [\x30-\x34] digit 75 | | "25" [\x30-\x35]; 76 | ipv4address = dec_octet "." dec_octet "." dec_octet "." dec_octet; 77 | h16 = hexdigit{1,4}; 78 | ls32 = h16 ":" h16 | ipv4address; 79 | ipv6address 80 | = (h16 ":"){6} ls32 81 | | "::" (h16 ":"){5} ls32 82 | | ( h16)? "::" (h16 ":"){4} ls32 83 | | ((h16 ":"){0,1} h16)? "::" (h16 ":"){3} ls32 84 | | ((h16 ":"){0,2} h16)? "::" (h16 ":"){2} ls32 85 | | ((h16 ":"){0,3} h16)? "::" h16 ":" ls32 86 | | ((h16 ":"){0,4} h16)? "::" ls32 87 | | ((h16 ":"){0,5} h16)? "::" h16 88 | | ((h16 ":"){0,6} h16)? "::"; 89 | ipvfuture = "v" hexdigit+ "." (unreserved | sub_delims | ":" )+; 90 | ip_literal = "[" ( ipv6address | ipvfuture ) "]"; 91 | reg_name = (unreserved | pct_encoded | sub_delims)*; 92 | ip = ipv4address | ip_literal; 93 | host 94 | = ip_literal 95 | | ipv4address 96 | | reg_name ; 97 | port = digit{1,5} ; 98 | 99 | 100 | main := ( 101 | (ip > init_bind_ip % finish_bind_ip ":")? 102 | port > init_bind_port % finish_bind_port ":" 103 | ip > init_forward_ip % finish_forward_ip ":" 104 | port > init_forward_port % finish_forward_port 105 | ) $! err_char; 106 | }%% 107 | 108 | 109 | %%{ 110 | write data; 111 | }%% 112 | 113 | /* 114 | * input format: 115 | * [bind_ip]:bind_port:forward_ip:forward_port 116 | * return: 0 success 117 | */ 118 | int parse_forward_param(const char *str, size_t len, struct forwarder_param_t *param) 119 | { 120 | const char *bind_ip_start = NULL, *bind_port_start = NULL, *forward_ip_start = NULL, *forward_port_start = NULL; 121 | 122 | 123 | int cs = 0; 124 | const char *p = str; 125 | const char *pe = p + len; 126 | const char *eof = pe; 127 | 128 | %% write init; 129 | %% write exec; 130 | 131 | if(cs >= parse_forward_param_first_final) 132 | { 133 | if (param->bind_ip[0] == 0) 134 | { 135 | strcpy(param->bind_ip, "127.0.0.1"); 136 | } 137 | 138 | LOGD("success %s:%hu --> %s:%hu\n", param->bind_ip, param->bind_port, param->forward_ip, param->forward_port); 139 | 140 | return 0; 141 | } 142 | LOGE("param is too short"); 143 | 144 | fail: 145 | if (param->bind_ip[0]) { 146 | param->bind_ip[0] = '\0'; 147 | } 148 | if (param->forward_ip[0]) { 149 | param->forward_ip[0] = '\0'; 150 | } 151 | 152 | return -1; 153 | } 154 | 155 | 156 | #if DEBUG 157 | int main(int argc, char **argv) 158 | { 159 | for(int idx = 1; idx < argc; ++idx) 160 | { 161 | struct forwarder_param_t param = {0}; 162 | LOGD("\nparse: %s\n", argv[idx]); 163 | parse_forward_param(argv[idx], strlen(argv[idx]), ¶m); 164 | } 165 | 166 | return 0; 167 | } 168 | #endif 169 | -------------------------------------------------------------------------------- /proxy.vcxproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | 14 | {D93F8D57-E613-4045-A1AC-5319852EC35F} 15 | Win32Proj 16 | proxy 17 | mproxy 18 | 19 | 20 | 21 | Application 22 | true 23 | v120_xp 24 | MultiByte 25 | 26 | 27 | Application 28 | false 29 | v120 30 | true 31 | MultiByte 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | true 45 | D:\Sources\libevent-2.0.21-stable\WIN32-Code;D:\Sources\libevent-2.0.21-stable\include;D:\openssl\include;libevhtp\compat;libevhtp;$(IncludePath) 46 | D:\Sources\libevent-2.0.21-stable;D:\openssl\lib;$(LibraryPath) 47 | 48 | 49 | false 50 | D:\Sources\libevent-2.0.21-stable\WIN32-Code;D:\Sources\libevent-2.0.21-stable\include;D:\openssl\include;libevhtp\compat;libevhtp;$(VCInstallDir)PlatformSDK\include;D:\Sources\boost_1_56_0;D:\Sources\WTL90_4140_Final\Include;$(IncludePath) 51 | D:\Sources\libevent-2.0.21-stable;D:\openssl\lib;$(LibraryPath) 52 | 53 | 54 | 55 | 56 | 57 | Level3 58 | Disabled 59 | WIN32;_DEBUG;_CONSOLE;NO_SYS_UN=1;ENABLE_SS=1;USE_CRYPTO_OPENSSL=1;%(PreprocessorDefinitions) 60 | %(UndefinePreprocessorDefinitions) 61 | 62 | 63 | Console 64 | true 65 | libevent.lib;libeay32.lib;ws2_32.lib;%(AdditionalDependencies) 66 | 67 | 68 | 69 | 70 | Level3 71 | 72 | 73 | MaxSpeed 74 | true 75 | true 76 | WIN32;NDEBUG;_CONSOLE;NO_SYS_UN=1;ENABLE_SS=1;USE_CRYPTO_OPENSSL=1;%(PreprocessorDefinitions) 77 | 78 | 79 | Console 80 | true 81 | true 82 | true 83 | libevent.lib;libeay32.lib;ws2_32.lib;%(AdditionalDependencies) 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | -------------------------------------------------------------------------------- /ss_connector.c: -------------------------------------------------------------------------------- 1 | #ifdef ENABLE_SS 2 | #include 3 | #include 4 | #include 5 | #ifdef _WIN32 6 | # include 7 | #endif 8 | 9 | #include 10 | #include 11 | 12 | #include "connector.h" 13 | 14 | #undef HAVE_CONFIG_H 15 | #include "encrypt.h" 16 | #include "utils.h" 17 | 18 | #ifdef _MSC_VER 19 | #define alloca _alloca 20 | #endif 21 | 22 | /* 23 | * ss_conn 24 | */ 25 | typedef struct ss_conn_t { 26 | struct bufferevent *client; 27 | 28 | struct enc_ctx e_ctx; 29 | struct enc_ctx d_ctx; 30 | 31 | //enum socks5_conn_status status; 32 | 33 | char host[256]; 34 | uint16_t port; 35 | connect_callback cb; 36 | void *arg; 37 | } ss_conn; 38 | 39 | 40 | int g_ss_method; 41 | const char *g_ss_server; 42 | int g_ss_port; 43 | char *g_ss_key; 44 | 45 | static void free_context(void *ctx) 46 | { 47 | ss_conn *conn = (ss_conn*)ctx; 48 | 49 | // For both OpenSSL and mbed TLS, release is free pointer in struct and zero struct. 50 | // And release a zeroed struct is safe. 51 | cipher_context_release(&conn->e_ctx.evp); 52 | cipher_context_release(&conn->d_ctx.evp); 53 | 54 | free(conn); 55 | } 56 | 57 | static enum bufferevent_filter_result input_filter(struct evbuffer *src, struct evbuffer *dst, ev_ssize_t dst_limit, enum bufferevent_flush_mode mode, void *ctx) 58 | { 59 | int i; 60 | ss_conn *conn = (ss_conn*)ctx; 61 | 62 | #define CRYPT(method, crypt_ctx, extra_len) \ 63 | do { \ 64 | int iovec_len = evbuffer_peek(src, -1, NULL, NULL, 0); \ 65 | \ 66 | struct evbuffer_iovec *vec_src = alloca(sizeof(struct evbuffer_iovec) * iovec_len); \ 67 | struct evbuffer_iovec vec_dst[1]; \ 68 | \ 69 | evbuffer_peek(src, -1, NULL, vec_src, iovec_len); \ 70 | if (1 != evbuffer_reserve_space(dst, evbuffer_get_length(src) + (extra_len), vec_dst, 1)) { \ 71 | /* malloc space failed */ \ 72 | return BEV_ERROR; \ 73 | } \ 74 | vec_dst[0].iov_len = 0; \ 75 | \ 76 | for (i = 0; i < iovec_len; i++) { \ 77 | ssize_t r = vec_src[i].iov_len; \ 78 | char *buf = ss_ ## method((char*)vec_dst[0].iov_base + vec_dst[0].iov_len, vec_src[i].iov_base, &r, &(crypt_ctx)); \ 79 | if (!buf) { \ 80 | /* crypt error */ \ 81 | LOGE( # method " failed"); \ 82 | return BEV_ERROR; \ 83 | } \ 84 | \ 85 | vec_dst[0].iov_len += r; \ 86 | } \ 87 | \ 88 | evbuffer_drain(src, -1); \ 89 | if (-1 == evbuffer_commit_space(dst, vec_dst, 1)) { \ 90 | LOGE("evbuffer commit space failed"); \ 91 | return BEV_ERROR; \ 92 | } \ 93 | } while(0) 94 | 95 | if (conn->d_ctx.aead) 96 | { 97 | struct evbuffer_iovec vec_dst[1]; 98 | char *ciphertext = evbuffer_pullup(src, -1); 99 | if (1 != evbuffer_reserve_space(dst, evbuffer_get_length(src) + BLOCK_SIZE, vec_dst, 1)) { 100 | /* malloc space failed */ 101 | return BEV_ERROR; 102 | } 103 | vec_dst[0].iov_len = 0; 104 | 105 | int consume = evbuffer_get_length(src); 106 | int produce = aead_decrypt(vec_dst[0].iov_base, ciphertext, &consume, &conn->e_ctx); 107 | if (produce < 0) { 108 | LOGE("aead decrypt failed"); 109 | return BEV_ERROR; 110 | } 111 | else if (produce == 0 && consume == 0) { 112 | return BEV_NEED_MORE; 113 | } 114 | else { 115 | evbuffer_drain(src, consume); 116 | vec_dst[0].iov_len = produce; 117 | 118 | if (-1 == evbuffer_commit_space(dst, vec_dst, 1)) { 119 | LOGE("evbuffer commit space failed"); 120 | return BEV_ERROR; 121 | } 122 | } 123 | } 124 | else { 125 | CRYPT(decrypt, conn->d_ctx, BLOCK_SIZE); 126 | } 127 | 128 | return BEV_OK; 129 | } 130 | 131 | static enum bufferevent_filter_result output_filter(struct evbuffer *src, struct evbuffer *dst, ev_ssize_t dst_limit, enum bufferevent_flush_mode mode, void *ctx) 132 | { 133 | int i; 134 | ss_conn *conn = (ss_conn*)ctx; 135 | 136 | /*{ 137 | int iovec_len = evbuffer_peek(src, -1, NULL, NULL, 0); 138 | 139 | struct evbuffer_iovec vec_src[iovec_len]; 140 | struct evbuffer_iovec vec_dst[1]; 141 | 142 | evbuffer_peek(src, -1, NULL, vec_src, iovec_len); 143 | if (1 != evbuffer_reserve_space(dst, evbuffer_get_length(src) + MAX_IV_LENGTH + BLOCK_SIZE, vec_dst, 1)) { 144 | // malloc space failed 145 | return BEV_ERROR; 146 | } 147 | vec_dst[0].iov_len = 0; 148 | 149 | for (i = 0; i < iovec_len; i++) 150 | { 151 | ssize_t r = vec_src[i].iov_len; 152 | char *buf = ss_encrypt((char*)vec_dst[0].iov_base + vec_dst[0].iov_len, vec_src[i].iov_base, &r, &conn->e_ctx); 153 | if (!buf) { 154 | // crypt error 155 | LOGE("ss_encrypt failed"); 156 | return BEV_ERROR; 157 | } 158 | 159 | vec_dst[0].iov_len += r; 160 | } 161 | 162 | evbuffer_drain(src, -1); 163 | if (-1 == evbuffer_commit_space(dst, vec_dst, 1)) { 164 | return BEV_ERROR; 165 | } 166 | }*/ 167 | if (conn->e_ctx.aead) 168 | { 169 | int src_len = evbuffer_get_length(src); 170 | do { 171 | int consume = src_len > CHUNK_SIZE_MASK ? CHUNK_SIZE_MASK : src_len; 172 | struct evbuffer_iovec vec_dst[1]; 173 | char *plaintext = evbuffer_pullup(src, consume); 174 | if (1 != evbuffer_reserve_space(dst, consume + (CHUNK_SIZE_LEN + 2 * MAX_TAG_LENGTH + BLOCK_SIZE), vec_dst, 1)) { 175 | /* malloc space failed */ 176 | return BEV_ERROR; 177 | } 178 | vec_dst[0].iov_len = 0; 179 | 180 | //int consume = evbuffer_get_length(src); 181 | int produce = aead_encrypt(vec_dst[0].iov_base, plaintext, &consume, &conn->d_ctx); 182 | if (produce < 0) { 183 | LOGE("aead encrypt failed"); 184 | return BEV_ERROR; 185 | } 186 | evbuffer_drain(src, consume); 187 | vec_dst[0].iov_len = produce; 188 | 189 | if (-1 == evbuffer_commit_space(dst, vec_dst, 1)) { 190 | LOGE("evbuffer commit space failed"); 191 | return BEV_ERROR; 192 | } 193 | //LOGD("src %d consume %d", src_len, consume); 194 | src_len -= consume; 195 | } while(src_len > 0); 196 | } 197 | else 198 | { 199 | CRYPT(encrypt, conn->e_ctx, MAX_IV_LENGTH + BLOCK_SIZE); 200 | } 201 | 202 | 203 | return BEV_OK; 204 | } 205 | 206 | static void ss_eventcb(struct bufferevent *bev, short what, void *ctx) 207 | { 208 | struct bufferevent *bev_filter = NULL; 209 | ss_conn *conn = (ss_conn*)ctx; 210 | if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) { 211 | char buf[4096] = {'\0'}; 212 | // during handshake, EOF is an error also 213 | LOGE("bev %p (sock %d) event: 0x%hx %s", bev, bufferevent_getfd(bev), what, socket_error(buf, sizeof(buf))); 214 | 215 | // error 216 | conn->cb(NULL, conn->arg); 217 | 218 | free_context(conn); 219 | bufferevent_free(bev); 220 | } else if (what & BEV_EVENT_CONNECTED) { 221 | LOGD("upstrem connected with bev %p (sock %d)", bev, bufferevent_getfd(bev)); 222 | #if defined TCP_NODELAY 223 | if (g_enable_nodelay == 1) { 224 | int on = 1; 225 | setsockopt(bufferevent_getfd(bev), IPPROTO_TCP, TCP_NODELAY, (void *)&on, sizeof(on)); 226 | } 227 | #endif 228 | 229 | /* TCP */ 230 | bufferevent_setcb(bev, NULL, NULL, NULL, NULL); 231 | 232 | /* ss */ 233 | enc_ctx_init(g_ss_method, &conn->e_ctx, 1); 234 | enc_ctx_init(g_ss_method, &conn->d_ctx, 0); 235 | 236 | /* any changes in output evbuffer will call output_filter, so must be deferred */ 237 | bev_filter = bufferevent_filter_new(bev, input_filter, output_filter, BEV_OPT_CLOSE_ON_FREE/*|BEV_OPT_DEFER_CALLBACKS*/, free_context, ctx); 238 | 239 | if (bev_filter) { 240 | LOGD("create filter bev %p from bev %p ", bev_filter, bev); 241 | 242 | /* same as SOCKS5 Requests 243 | +------+----------+----------+ 244 | | ATYP | DST.ADDR | DST.PORT | 245 | +------+----------+----------+ 246 | | 1 | Variable | 2 | 247 | +------+----------+----------+ 248 | */ 249 | char data[1 + 1 + 255 + 2] = {0x03, }; // DOMAINNAME: X'03 250 | size_t domain_len = strlen(conn->host); 251 | assert(domain_len <= 255); 252 | uint16_t net_port = htons(conn->port); 253 | 254 | data[1] = domain_len; 255 | memcpy(data + 2, conn->host, domain_len); 256 | memcpy(data + 2 + domain_len, &net_port, 2); 257 | 258 | /* currently BEV_OPT_DEFER_CALLBACKS no effect with bufferevent_filter_new(), so defer it manually */ 259 | evbuffer_defer_callbacks(bufferevent_get_output(bev_filter), bufferevent_get_base(bev_filter)); 260 | bufferevent_write(bev_filter, data, 1 + 1 + domain_len + 2); 261 | 262 | conn->cb(bev_filter, conn->arg); 263 | } else { 264 | LOGE("create filter event failed"); 265 | conn->cb(bev_filter, conn->arg); 266 | 267 | free_context(conn); 268 | bufferevent_free(bev); 269 | } 270 | } 271 | } 272 | 273 | void connect_ss(struct event_base *evbase, struct evdns_base *evdns_base, const char *hostname, int port, connect_callback cb, void *arg) 274 | { 275 | struct bufferevent *bev = NULL; 276 | ss_conn *conn = (ss_conn*)calloc(1, sizeof(ss_conn)); 277 | if (NULL == conn) { 278 | goto fail; 279 | } 280 | 281 | strcpy(conn->host, hostname); 282 | conn->port = port; 283 | conn->cb = cb; 284 | conn->arg = arg; 285 | 286 | assert(g_ss_server && g_ss_port != 0); 287 | hostname = g_ss_server; 288 | port =g_ss_port; 289 | 290 | bev = bufferevent_socket_new(evbase, -1, BEV_OPT_CLOSE_ON_FREE/*|BEV_OPT_DEFER_CALLBACKS*/); 291 | if (NULL == bev) { 292 | LOGE("bufferevent create failed"); 293 | goto fail; 294 | } 295 | 296 | conn->client = bev; 297 | bufferevent_setcb(bev, NULL, NULL, ss_eventcb, conn); 298 | 299 | if (bufferevent_socket_connect_hostname(bev, evdns_base, PF_UNSPEC, hostname, port) < 0) { 300 | LOGE("bufferevent connect ss server %s:%d failed", hostname, port); 301 | goto fail; 302 | } 303 | 304 | return; 305 | 306 | fail: 307 | LOGE("connect host %s:%d failed", hostname, port); 308 | if (bev) 309 | bufferevent_free(bev); 310 | cb(NULL, arg); 311 | if (conn) 312 | free_context(conn); 313 | } 314 | 315 | #endif 316 | -------------------------------------------------------------------------------- /utils.c: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | #ifndef _WIN32 8 | # include 9 | # include 10 | # include 11 | # include 12 | # include 13 | # include 14 | #endif 15 | 16 | #ifndef _WIN32 17 | int write_pid_file(const char *pid_file) 18 | { 19 | int pidfd = -1; 20 | char pidstr[100] = {0}; 21 | int ret = 1; 22 | ssize_t len; 23 | 24 | unlink(pid_file); 25 | pidfd = open(pid_file, O_CREAT | O_WRONLY | O_TRUNC, 0644); 26 | if (pidfd < 0) { 27 | LOGE("Open pid file failed: %s", strerror(errno)); 28 | goto out; 29 | } 30 | snprintf(pidstr, sizeof(pidstr), "%d\n", getpid()); 31 | len = write(pidfd, pidstr, strlen(pidstr)); 32 | if (len == -1) { 33 | LOGE("Write pid file failed: %s", strerror(errno)); 34 | goto out; 35 | } 36 | ret = 0; // success 37 | 38 | out: 39 | if (pidfd >= 0) close(pidfd); 40 | return ret; 41 | } 42 | 43 | /* 44 | * getpwnam() and getgrnam() is MT-Unsafe 45 | * return 0 on success 46 | */ 47 | int change_user(const char *userspec) 48 | { 49 | char buf[4096] = { '\0' }; 50 | struct passwd *pw = NULL; 51 | struct group *gr = NULL; 52 | gid_t gid; 53 | uid_t uid; 54 | int saved; 55 | int ret = 1; 56 | 57 | saved = errno; 58 | strncpy(buf, userspec, sizeof(buf) / sizeof(buf[0]) - 1); 59 | 60 | const char *user_name = buf; 61 | const char *group_name = NULL; 62 | char *pos = strchr(buf, ':'); 63 | 64 | if (pos) { 65 | *pos = '\0'; 66 | group_name = pos + 1; 67 | } 68 | 69 | errno = 0; 70 | if (NULL == (pw = getpwnam(user_name))) { 71 | LOGE("Cannot find user '%s': %s", user_name, (errno ? strerror(errno) : "")); 72 | goto out; 73 | } else { 74 | uid = pw->pw_uid; 75 | gid = pw->pw_gid; 76 | } 77 | 78 | if (group_name && group_name[0]) { 79 | errno = 0; 80 | if (NULL == (gr = getgrnam(group_name))) { 81 | LOGE("Cannot find group '%s': %s", group_name, (errno ? strerror(errno) : "")); 82 | goto out; 83 | } else { 84 | gid = gr->gr_gid; 85 | } 86 | } 87 | 88 | if (0 != setgid(gid)) { 89 | LOGE("Set group ID failed %u: %s", (unsigned)gid, strerror(errno)); 90 | goto out; 91 | } 92 | if (0 != setuid(uid)) { 93 | LOGE("Set user ID failed %u: %s", (unsigned)uid, strerror(errno)); 94 | goto out; 95 | } 96 | 97 | ret = 0; // success 98 | 99 | out: 100 | errno = saved; 101 | return ret; 102 | } 103 | #endif // !_WIN32 104 | 105 | void hexdump(FILE *out, const void *p, int len) 106 | { 107 | const unsigned char *line; 108 | int i; 109 | int thisline; 110 | int offset; 111 | 112 | line = (const unsigned char *)p; 113 | offset = 0; 114 | 115 | while (offset < len) { 116 | fprintf(out, "%04x ", offset); 117 | thisline = len - offset; 118 | 119 | if (thisline > 16) { 120 | thisline = 16; 121 | } 122 | 123 | for (i = 0; i < thisline; i++) { 124 | fprintf(out, "%02x ", line[i]); 125 | } 126 | 127 | for (; i < 16; i++) { 128 | fprintf(out, " "); 129 | } 130 | 131 | for (i = 0; i < thisline; i++) { 132 | fprintf(out, "%c", (line[i] >= 0x20 && line[i] < 0x7f) ? line[i] : '.'); 133 | } 134 | 135 | fprintf(out, "\n"); 136 | offset += thisline; 137 | line += thisline; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /utils.h: -------------------------------------------------------------------------------- 1 | #ifndef __UTILS_H__ 2 | #define __UTILS_H__ 3 | 4 | #include 5 | #include "log.h" 6 | 7 | #ifndef _WIN32 8 | int write_pid_file(const char *pid_file); 9 | int change_user(const char *userspec); 10 | #endif 11 | void hexdump(FILE *out, const void *p, int len); 12 | 13 | #endif // __UTILS_H__ 14 | --------------------------------------------------------------------------------