├── .gitignore ├── etc ├── default │ └── dehprox ├── init.d │ └── dehprox └── dehprox.conf ├── .gitmodules ├── src ├── Address.hpp ├── TestProxy │ ├── CMakeLists.txt │ └── Main.cpp ├── DnsServer.hpp ├── DnsDatabase.hpp ├── CMakeLists.txt ├── DirectLine.hpp ├── ProxyLine.hpp ├── Client.hpp ├── Settings.hpp ├── ProxyServer.hpp ├── DirectLine.cpp ├── ProxyServer.cpp ├── Main.cpp ├── ProxyLine.cpp ├── DnsDatabase.cpp ├── Settings.cpp ├── Client.cpp └── DnsServer.cpp ├── 3rdparty └── CMakeLists.txt ├── Jenkinsfile ├── CMakeLists.txt ├── .clang-format ├── README.md ├── LICENSE └── CDeploy /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /.vscode 3 | 4 | /build 5 | -------------------------------------------------------------------------------- /etc/default/dehprox: -------------------------------------------------------------------------------- 1 | # Additional options that are passed to the daemon. 2 | DAEMON_OPTS= 3 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "3rdparty/libnstd"] 2 | path = 3rdparty/libnstd 3 | url = ../libnstd.git 4 | -------------------------------------------------------------------------------- /src/Address.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include 5 | 6 | struct Address 7 | { 8 | uint32 addr; 9 | uint16 port; 10 | 11 | Address() : addr(Socket::anyAddress), port(0) {} 12 | }; 13 | -------------------------------------------------------------------------------- /src/TestProxy/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | set(sources 3 | Main.cpp 4 | ) 5 | 6 | add_executable(TestProxy 7 | ${sources} 8 | ) 9 | 10 | target_link_libraries(TestProxy PRIVATE 11 | libnstd::Core libnstd::Socket 12 | ) 13 | 14 | source_group("" FILES ${sources}) 15 | 16 | set_property(TARGET TestProxy PROPERTY FOLDER "src/TestProxy") 17 | -------------------------------------------------------------------------------- /src/DnsServer.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include "Settings.hpp" 5 | 6 | #include 7 | 8 | class DnsServer 9 | { 10 | public: 11 | DnsServer(const Settings& settings) : _settings(settings) {} 12 | 13 | bool start(); 14 | 15 | uint run(); 16 | 17 | private: 18 | const Settings& _settings; 19 | Socket _socket; 20 | }; 21 | -------------------------------------------------------------------------------- /src/DnsDatabase.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include 5 | 6 | class DnsDatabase 7 | { 8 | public: 9 | static bool resolve(const String& hostname, uint32& addr); 10 | 11 | static bool reverseResolve(uint32 addr, String& hostname); 12 | 13 | static uint32 resolveFake(const String& hostname); 14 | 15 | static bool isFake(uint32 addr); 16 | 17 | static bool reverseResolveFake(uint32 addr, String& hostname); 18 | }; 19 | -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | set(sources 3 | Address.hpp 4 | Client.cpp 5 | Client.hpp 6 | DirectLine.cpp 7 | DirectLine.hpp 8 | DnsDatabase.cpp 9 | DnsDatabase.hpp 10 | DnsServer.cpp 11 | DnsServer.hpp 12 | Main.cpp 13 | ProxyLine.cpp 14 | ProxyLine.hpp 15 | ProxyServer.cpp 16 | ProxyServer.hpp 17 | Settings.cpp 18 | Settings.hpp 19 | ) 20 | 21 | add_executable(dehprox 22 | ${sources} 23 | ) 24 | 25 | target_link_libraries(dehprox PRIVATE 26 | libnstd::Core libnstd::Socket 27 | ) 28 | 29 | source_group("" FILES ${sources}) 30 | 31 | set_property(TARGET dehprox PROPERTY FOLDER "src") 32 | 33 | install(TARGETS dehprox DESTINATION usr/sbin) 34 | 35 | add_subdirectory(TestProxy) 36 | 37 | -------------------------------------------------------------------------------- /3rdparty/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | set(DISABLE_ADD_TEST True) 4 | function(add_test) 5 | if(NOT DISABLE_ADD_TEST) 6 | _add_test(${ARGV}) 7 | endif() 8 | endfunction() 9 | 10 | set(DISABLE_INSTALL True) 11 | function(install) 12 | if(NOT DISABLE_INSTALL) 13 | _install(${ARGV}) 14 | endif() 15 | endfunction() 16 | 17 | set(DISABLE_ENABLE_TESTING True) 18 | function(enable_testing) 19 | if(NOT DISABLE_ENABLE_TESTING) 20 | _enable_testing(${ARGV}) 21 | endif() 22 | endfunction() 23 | 24 | set(DISABLE_ADD_SUBDIRECTORY True) 25 | function(add_subdirectory) 26 | if(NOT DISABLE_ADD_SUBDIRECTORY OR "${ARGV0}" STREQUAL "libnstd" OR "${ARGV0}" STREQUAL "src" OR "${ARGV0}" STREQUAL "Socket") 27 | _add_subdirectory(${ARGV}) 28 | endif() 29 | endfunction() 30 | 31 | add_subdirectory(libnstd) 32 | 33 | set_property(TARGET nstd nstdSocket PROPERTY FOLDER "3rdparty") 34 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | pipeline { 2 | agent none 3 | stages { 4 | stage('All') { 5 | matrix { 6 | agent { 7 | label "${platform}" 8 | } 9 | axes { 10 | axis { 11 | name 'platform' 12 | values 'ubuntu22.04-x86_64', 'ubuntu20.04-x86_64', 'ubuntu18.04-x86_64', 'raspbian10-armv7l', 'rocky8-x86_64' 13 | } 14 | } 15 | stages { 16 | stage('Build') { 17 | steps { 18 | cmakeBuild buildDir: 'build', cleanBuild: true, installation: 'InSearchPath', buildType: 'Release', cmakeArgs: '-G Ninja' 19 | cmake workingDir: 'build', arguments: '--build . --target package', installation: 'InSearchPath' 20 | } 21 | } 22 | } 23 | post { 24 | always { 25 | archiveArtifacts artifacts: 'build/dehprox-*.deb,build/dehprox-*.rpm' 26 | } 27 | } 28 | } 29 | } 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /src/DirectLine.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include "Address.hpp" 5 | 6 | #include 7 | 8 | class DirectLine : public Server::Establisher::ICallback, public Server::Client::ICallback 9 | { 10 | public: 11 | class ICallback 12 | { 13 | public: 14 | virtual void onOpened(DirectLine&) = 0; 15 | virtual void onClosed(DirectLine&, const String& error) = 0; 16 | 17 | protected: 18 | ICallback() {} 19 | ~ICallback() {} 20 | }; 21 | 22 | public: 23 | DirectLine(Server& server, Server::Client& client, ICallback& callback); 24 | ~DirectLine(); 25 | 26 | Server::Client* getHandle() {return _handle;} 27 | 28 | bool connect(const Address& address); 29 | 30 | String getDebugInfo() const; 31 | 32 | public: // Server::Establisher::ICallback 33 | Server::Client::ICallback *onConnected(Server::Client &client) override; 34 | void onAbolished() override; 35 | 36 | public: // Server::Client::ICallback 37 | void onRead() override; 38 | void onWrite() override; 39 | void onClosed() override; 40 | 41 | private: 42 | Server& _server; 43 | Server::Client& _client; 44 | ICallback& _callback; 45 | Server::Establisher* _establisher; 46 | Server::Client* _handle; 47 | int64 _lastReadActivity; 48 | }; 49 | -------------------------------------------------------------------------------- /src/ProxyLine.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include "Settings.hpp" 5 | 6 | #include 7 | #include 8 | 9 | class ProxyLine : public Server::Establisher::ICallback, public Server::Client::ICallback 10 | { 11 | public: 12 | class ICallback 13 | { 14 | public: 15 | virtual void onOpened(ProxyLine&) = 0; 16 | virtual void onClosed(ProxyLine&, const String& error) = 0; 17 | 18 | protected: 19 | ICallback() {} 20 | ~ICallback() {} 21 | }; 22 | 23 | public: 24 | ProxyLine(Server& server, Server::Client& client, ICallback& callback, Settings& settings); 25 | ~ProxyLine(); 26 | 27 | Server::Client* getHandle() {return _handle;} 28 | 29 | bool connect(const String& hostname, int16 port); 30 | 31 | String getDebugInfo() const; 32 | 33 | public: // Server::Establisher::ICallback 34 | Server::Client::ICallback *onConnected(Server::Client &client) override; 35 | void onAbolished() override; 36 | 37 | public: // Server::Client::ICallback 38 | void onRead() override; 39 | void onWrite() override; 40 | void onClosed() override; 41 | 42 | private: 43 | Server& _server; 44 | Server::Client& _client; 45 | ICallback& _callback; 46 | Settings& _settings; 47 | Server::Establisher* _establisher; 48 | Server::Client* _handle; 49 | String _hostname; 50 | uint16 _port; 51 | Address _httpProxyAddr; 52 | bool _connected; 53 | String _proxyResponse; 54 | int64 _lastReadActivity; 55 | }; 56 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | cmake_minimum_required(VERSION 3.5) 3 | cmake_policy(SET CMP0048 NEW) 4 | 5 | project(dehprox VERSION 1.1.0) 6 | 7 | set(CDEPLOY_NO_DEBUG_BUILD True) 8 | set(CDEPLOY_NO_COMPILER True) 9 | 10 | include(CDeploy) 11 | 12 | add_subdirectory(3rdparty) 13 | add_subdirectory(src) 14 | 15 | set(CPACK_PACKAGE_CONTACT "Colin Graf ") 16 | set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}") 17 | set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Transparent DNS and TCP to HTTP proxy redirector") 18 | set(CMAKE_PROJECT_HOMEPAGE_URL "https://github.com/craflin/dehprox") 19 | set(CPACK_PACKAGING_INSTALL_PREFIX "/") 20 | 21 | if(CDEPLOY_OS MATCHES "debian.*" OR CDEPLOY_OS MATCHES "ubuntu.*" OR CDEPLOY_OS MATCHES "raspbian.*") 22 | set(CPACK_GENERATOR "DEB") 23 | #set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT") 24 | set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "${CMAKE_PROJECT_HOMEPAGE_URL}") 25 | set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6 (>= 2.15)") 26 | set(CPACK_DEBIAN_PACKAGE_SECTION "net") 27 | endif() 28 | 29 | if(CDEPLOY_OS MATCHES "rhel.*" OR CDEPLOY_OS MATCHES "centos.*" OR CDEPLOY_OS MATCHES "rocky.*" OR CDEPLOY_OS MATCHES "alma.*") 30 | set(CPACK_GENERATOR "RPM") 31 | set(CPACK_RPM_PACKAGE_LICENSE "Apache License") 32 | set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION "/usr/sbin") 33 | endif() 34 | 35 | 36 | include(CPack) 37 | 38 | install(FILES etc/dehprox.conf DESTINATION etc) 39 | install(FILES etc/default/dehprox DESTINATION etc/default) 40 | install(PROGRAMS etc/init.d/dehprox DESTINATION etc/init.d) 41 | -------------------------------------------------------------------------------- /src/Client.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include 5 | 6 | #include "DirectLine.hpp" 7 | #include "ProxyLine.hpp" 8 | #include "Settings.hpp" 9 | 10 | class Client : public Server::Client::ICallback 11 | , public DirectLine::ICallback 12 | , public ProxyLine::ICallback 13 | { 14 | public: 15 | class ICallback 16 | { 17 | public: 18 | virtual void onClosed(Client& client) = 0; 19 | 20 | protected: 21 | ICallback() {} 22 | ~ICallback() {} 23 | }; 24 | 25 | public: 26 | Client(Server& server, Server::Client& client, const Address& clientAddr, ICallback& callback, Settings& settings); 27 | ~Client(); 28 | 29 | bool init(); 30 | 31 | String getDebugInfo() const; 32 | 33 | public: // Server::Client::ICallback 34 | void onRead() override; 35 | void onWrite() override; 36 | void onClosed() override; 37 | 38 | public: // DirectLine::ICallback 39 | void onOpened(DirectLine&) override; 40 | void onClosed(DirectLine&, const String& error) override; 41 | 42 | public: // ProxyLine::ICallback 43 | void onOpened(ProxyLine&) override; 44 | void onClosed(ProxyLine&, const String& error) override; 45 | 46 | private: 47 | Server& _server; 48 | Server::Client& _handle; 49 | ICallback& _callback; 50 | Settings& _settings; 51 | ProxyLine* _proxyLine; 52 | DirectLine* _directLine; 53 | Server::Client* _activeLine; 54 | Address _address; 55 | Address _destination; 56 | String _destinationHostname; 57 | int64 _lastReadActivity; 58 | 59 | private: 60 | void close(const String& error); 61 | }; 62 | 63 | -------------------------------------------------------------------------------- /src/Settings.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "Address.hpp" 10 | 11 | struct Settings 12 | { 13 | public: 14 | Settings(const String& file); 15 | 16 | const Address& getListenAddr() const {return _listenAddr;} 17 | const Address& getDebugListenAddr() const {return _debugListenAddr;} 18 | const Address& getDnsListenAddr() const {return _dnsListenAddr;} 19 | const Address& getProxyAddr(const String& destination); 20 | bool isAutoProxySkipEnabled() const {return _autoProxySkip;} 21 | bool isWhiteListEmpty() const {return _whiteList.isEmpty();} 22 | bool isInWhiteList(const String& destination) const; 23 | bool isInBlackList(const String& destination) const; 24 | bool isInSkipProxyList(const String& destination) const; 25 | bool isInSkipProxyRangeList(uint32 ip) const; 26 | 27 | private: 28 | typedef HashMap> DestinationHttpProxyAddrsMap; 29 | 30 | struct IpRange 31 | { 32 | uint32 network; 33 | uint32 mask; 34 | }; 35 | 36 | private: 37 | Address _listenAddr; 38 | Address _debugListenAddr; 39 | Address _dnsListenAddr; 40 | Array
_httpProxyAddrs; 41 | DestinationHttpProxyAddrsMap _destinationHttpProxyAddrs; 42 | bool _autoProxySkip; 43 | HashSet _whiteList; 44 | HashSet _blackList; 45 | HashSet _skipProxyList; 46 | Array _skipProxyRanges; 47 | 48 | private: 49 | Settings(const Settings&); 50 | Settings& operator=(const Settings&); 51 | }; 52 | -------------------------------------------------------------------------------- /src/ProxyServer.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include 5 | #include 6 | 7 | #include "Client.hpp" 8 | #include "Settings.hpp" 9 | 10 | class ProxyServer : public Server::Listener::ICallback 11 | , public Client::ICallback 12 | { 13 | public: 14 | ProxyServer(Settings& settings); 15 | 16 | bool start(); 17 | bool startDebugPort(); 18 | 19 | void run(); 20 | 21 | public: // Server::Listener::ICallback 22 | Server::Client::ICallback *onAccepted(Server::Client &client, uint32 ip, uint16 port) override; 23 | 24 | public: // Client::ICallback 25 | void onClosed(Client& client) override; 26 | 27 | private: 28 | class DebugListener; 29 | 30 | class DebugClient : public Server::Client::ICallback 31 | { 32 | public: 33 | DebugClient(DebugListener& parent, Server::Client& handle) : _parent(parent), _handle(handle) {} 34 | 35 | public: // Server::Client::ICallback 36 | void onRead() override; 37 | void onWrite() override {} 38 | void onClosed() override; 39 | 40 | private: 41 | DebugListener& _parent; 42 | Server::Client& _handle; 43 | }; 44 | 45 | class DebugListener : public Server::Listener::ICallback 46 | { 47 | public: 48 | DebugListener(ProxyServer& parent) : _parent(parent) {} 49 | 50 | public: // Server::Listener::ICallback 51 | Server::Client::ICallback *onAccepted(Server::Client &client, uint32 ip, uint16 port) override; 52 | 53 | private: 54 | ProxyServer& _parent; 55 | PoolList _debugClients; 56 | 57 | friend class DebugClient; 58 | }; 59 | 60 | private: 61 | Settings& _settings; 62 | Server _server; 63 | PoolList<::Client> _clients; 64 | DebugListener _debugListener; 65 | }; 66 | -------------------------------------------------------------------------------- /etc/init.d/dehprox: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | ### BEGIN INIT INFO 4 | # Provides: dehprox 5 | # Required-Start: $network 6 | # Required-Stop: $network 7 | # Default-Start: 2 3 4 5 8 | # Default-Stop: 0 1 6 9 | # Short-Description: Transparent DNS and TCP to HTTP proxy redirector 10 | # Description: Dehprox accepts DNS and TCP traffic that has been 11 | # redirected from a network interface to dehprox. TCP 12 | # traffic is redirected to a HTTP proxy server and DNS 13 | # queries are answered with a fake address that is mapped 14 | # back to the hostname when establising the connection using 15 | # the HTTP proxy. 16 | ### END INIT INFO 17 | # 18 | # DAEMON Location of the binary 19 | # 20 | 21 | PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin 22 | DAEMON=/usr/sbin/dehprox 23 | NAME=dehprox 24 | DESC="Dehprox DNS and TCP to HTTP proxy redirector" 25 | DAEMON_OPTS= 26 | 27 | test -x $DAEMON || exit 0 28 | 29 | # Include custom values if available 30 | if [ -f /etc/default/dehprox ] ; then 31 | . /etc/default/dehprox 32 | fi 33 | 34 | DAEMON_OPTS="-b $DAEMON_OPTS" 35 | 36 | start() { 37 | echo -n "Starting $DESC: " 38 | 39 | $DAEMON $DAEMON_OPTS 40 | if [ $? -eq 0 ]; then 41 | echo "$NAME." 42 | else 43 | echo "failed!" 44 | fi 45 | } 46 | 47 | stop() { 48 | echo -n "Stopping $DESC: " 49 | kill $(pidof $DAEMON) 50 | if [ $? -eq 0 ]; then 51 | echo "$NAME." 52 | else 53 | echo "failed!" 54 | fi 55 | } 56 | 57 | case "$1" in 58 | start) 59 | start 60 | ;; 61 | stop) 62 | stop 63 | ;; 64 | restart|reload|force-reload) 65 | stop 66 | start 67 | ;; 68 | *) 69 | echo "Usage: $0 {start|stop|restart|reload|force-reload}" >&2 70 | exit 2 71 | ;; 72 | esac 73 | 74 | exit 0 75 | -------------------------------------------------------------------------------- /etc/dehprox.conf: -------------------------------------------------------------------------------- 1 | 2 | #listenAddr 0.0.0.0:62124 3 | # The listen address of the transparent TCP/IP to proxy connection redirector. 4 | 5 | #dnsListenAddr 0.0.0.0:62124 6 | # The listen address of the DNS surrogate server. 7 | # It can be set to 0 to disable the DNS surrogate server. 8 | 9 | #httpProxyAddr 127.0.0.1:3128 10 | # The address of the HTTP proxy server to be used. 11 | # It can define the proxy server for a specific destination. 12 | # Multiple fallback proxies or proxies for the same destination can be defined for load balancing. 13 | # Example: 14 | #httpProxyAddr 192.168.0.251:3128 example2.com 15 | #httpProxyAddr 192.168.0.252:3128 example2.com 16 | #httpProxyAddr 192.168.0.253:3128 17 | #httpProxyAddr 192.168.0.254:3128 18 | # The proxies for a destination are also used for its subdomains. 19 | 20 | #autoProxySkip True 21 | # If the connection redirector should try to connect to a resolvable addresses without a proxy. 22 | 23 | # White listed and black listed destinations. 24 | # Example: 25 | #allowDest example1.com 26 | #allowDest example2.com 27 | #denyDest sub.example2.com 28 | # The default is an empty list of allowed destinations and an empty list of denied destinations, which results in all destinations being accepted. 29 | # All destinations (except denied destinations) are accepted if the list of allowed destinations is empty. 30 | # If the list of allowed destinations is not empty, only the allowed destinations will be accepted. 31 | # A listed destination includes all its subdomains and denied subdomains overrule allowed destinations. 32 | 33 | # Destinations for which a proxy will not be used. 34 | # Example: 35 | #skipProxyDest 192.168.0.23 36 | #skipProxyDest example2.com 37 | # This does also affect subdomains of these destinations. 38 | 39 | # IP ranges for which a proxy will not be used. 40 | # Example: 41 | #skipProxyRange 10.20.1.0/24 42 | #skipProxyRange 192.168.0.0/16 43 | -------------------------------------------------------------------------------- /src/DirectLine.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "DirectLine.hpp" 3 | 4 | #include 5 | #include 6 | 7 | DirectLine::DirectLine(Server& server, Server::Client& client, ICallback& callback) 8 | : _server(server) 9 | , _client(client) 10 | , _callback(callback) 11 | , _establisher(nullptr) 12 | , _handle(nullptr) 13 | , _lastReadActivity(0) 14 | { 15 | ; 16 | } 17 | 18 | DirectLine::~DirectLine() 19 | { 20 | if(_establisher) 21 | _server.remove(*_establisher); 22 | if (_handle) 23 | _server.remove(*_handle); 24 | 25 | } 26 | 27 | bool DirectLine::connect(const Address& address) 28 | { 29 | _establisher = _server.connect(address.addr, address.port, *this); 30 | if (!_establisher) 31 | return false; 32 | return true; 33 | } 34 | 35 | Server::Client::ICallback *DirectLine::onConnected(Server::Client &client) 36 | { 37 | _handle = &client; 38 | _callback.onOpened(*this); 39 | return this; 40 | } 41 | 42 | void DirectLine::onAbolished() 43 | { 44 | _callback.onClosed(*this, Error::getErrorString()); 45 | } 46 | 47 | void DirectLine::onRead() 48 | { 49 | byte buffer[262144]; 50 | usize size; 51 | if (!_handle->read(buffer, sizeof(buffer), size)) 52 | return; 53 | usize postponed = 0; 54 | if (!_client.write(buffer, size, &postponed)) 55 | return; 56 | if (postponed) 57 | _handle->suspend(); 58 | _lastReadActivity = Time::time(); 59 | } 60 | 61 | void DirectLine::onWrite() 62 | { 63 | _client.resume(); 64 | } 65 | 66 | void DirectLine::onClosed() 67 | { 68 | _callback.onClosed(*this, "Closed by peer"); 69 | } 70 | 71 | String DirectLine::getDebugInfo() const 72 | { 73 | if (!_handle) 74 | return String("connecting"); 75 | 76 | uint32 ip = 0; 77 | uint16 port = 0; 78 | _handle->getSocket().getSockName(ip, port); 79 | 80 | //direct0.0.0.0:82878active8 81 | return String::fromPrintf("direct%s:%hu%d%s%d%d", 82 | (const char*)Socket::inetNtoA(ip), port, 83 | (int)_handle->getSocket().getFileDescriptor(), 84 | _handle->isSuspended() ? "suspended" : "active", 85 | _lastReadActivity ? (int)((Time::time() - _lastReadActivity) / 1000) : -1, 86 | (int)_handle->getSendBufferSize()); 87 | } 88 | -------------------------------------------------------------------------------- /src/ProxyServer.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "ProxyServer.hpp" 3 | 4 | #include 5 | 6 | ProxyServer::ProxyServer(Settings& settings) : _settings(settings) , _debugListener(*this) 7 | { 8 | _server.setReuseAddress(true); 9 | _server.setKeepAlive(true); 10 | _server.setNoDelay(true); 11 | } 12 | 13 | bool ProxyServer::start() 14 | { 15 | const Address& listenAddr = _settings.getListenAddr(); 16 | if (!_server.listen(listenAddr.addr, listenAddr.port, *this)) 17 | return false; 18 | return true; 19 | } 20 | 21 | 22 | bool ProxyServer::startDebugPort() 23 | { 24 | const Address& debugListenAddr = _settings.getDebugListenAddr(); 25 | if (debugListenAddr.port) 26 | if (!_server.listen(debugListenAddr.addr, debugListenAddr.port, _debugListener)) 27 | return false; 28 | return true; 29 | } 30 | 31 | void ProxyServer::run() 32 | { 33 | _server.run(); 34 | } 35 | 36 | Server::Client::ICallback *ProxyServer::onAccepted(Server::Client &client_, uint32 ip, uint16 port) 37 | { 38 | Address address; 39 | address.addr = ip; 40 | address.port = port; 41 | 42 | ::Client& client = _clients.append(_server, client_, address, *this, _settings); 43 | if (!client.init()) 44 | { 45 | _clients.remove(client); 46 | return nullptr; 47 | } 48 | return &client; 49 | } 50 | 51 | void ProxyServer::onClosed(Client& client) 52 | { 53 | _clients.remove(client); 54 | } 55 | 56 | Server::Client::ICallback *ProxyServer::DebugListener::onAccepted(Server::Client &client, uint32, uint16) 57 | { 58 | return &_debugClients.append(*this, client); 59 | } 60 | 61 | void ProxyServer::DebugClient::onRead() 62 | { 63 | byte buffer[262144]; 64 | usize size; 65 | if (!_handle.read(buffer, sizeof(buffer), size)) 66 | return; 67 | 68 | String response; 69 | response.append("\n"); 70 | response.append("\n"); 71 | response.append("\n"); 72 | response.append("

\n"); 73 | response.append("\n"); 74 | 75 | response.append(""); 76 | 77 | for (PoolList<::Client>::Iterator i = _parent._parent._clients.begin(), end =_parent._parent._clients.end(); i != end; ++i) 78 | { 79 | const ::Client& client = *i; 80 | response.append(client.getDebugInfo()); 81 | response.append("\n"); 82 | } 83 | 84 | response.append("
clientfdpollidlesndbufdestinationmodesockfdpollidlesndbufproxy
\n"); 85 | response.append("

\n"); 86 | response.append("\n"); 87 | response.append("\n"); 88 | String header = String::fromPrintf("HTTP/1.1 200 OK\r\nContent-Length: %d\r\nContent-Type: text/html\r\nConnection: Closed\r\n\r\n", (int)response.length()); 89 | _handle.write((const byte*)(const char*)header, header.length()); 90 | _handle.write((const byte*)(const char*)response, response.length()); 91 | } 92 | 93 | void ProxyServer::DebugClient::onClosed() 94 | { 95 | _parent._parent._server.remove(_handle); 96 | _parent._debugClients.remove(*this); 97 | } 98 | -------------------------------------------------------------------------------- /src/Main.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "ProxyServer.hpp" 9 | #include "DnsServer.hpp" 10 | 11 | int main(int argc, char* argv[]) 12 | { 13 | String logFile; 14 | String configFile("/etc/dehprox.conf"); 15 | 16 | // parse parameters 17 | { 18 | Process::Option options[] = { 19 | { 'b', "daemon", Process::argumentFlag | Process::optionalFlag }, 20 | { 'c', "config", Process::argumentFlag }, 21 | { 'h', "help", Process::optionFlag }, 22 | }; 23 | Process::Arguments arguments(argc, argv, options); 24 | int character; 25 | String argument; 26 | while (arguments.read(character, argument)) 27 | switch (character) 28 | { 29 | case 'b': 30 | logFile = argument.isEmpty() ? String("/dev/null") : argument; 31 | break; 32 | case 'c': 33 | configFile = argument; 34 | break; 35 | case '?': 36 | Console::errorf("Unknown option: %s.\n", (const char*)argument); 37 | return -1; 38 | case ':': 39 | Console::errorf("Option %s required an argument.\n", (const char*)argument); 40 | return -1; 41 | default: 42 | Console::errorf("Usage: %s [-b] [-c ]\n\ 43 | \n\ 44 | -b, --daemon[=]\n\ 45 | Detach from calling shell and write output to .\n\ 46 | \n\ 47 | -c , --config[=]\n\ 48 | Load configuration from . (Default is /etc/dehprox.conf)\n\ 49 | \n", argv[0]); 50 | return -1; 51 | } 52 | } 53 | 54 | Log::setLevel(Log::debug); 55 | 56 | // load settings 57 | Settings settings(configFile); 58 | 59 | // daemonize process 60 | #ifndef _WIN32 61 | if(!logFile.isEmpty()) 62 | { 63 | Log::infof("Starting as daemon..."); 64 | if(!Process::daemonize(logFile)) 65 | { 66 | Log::errorf("Could not daemonize process: %s", (const char*)Error::getErrorString()); 67 | return -1; 68 | } 69 | Log::setDevice(Log::syslog); 70 | Log::setLevel(Log::info); 71 | } 72 | #endif 73 | 74 | // start dns server 75 | DnsServer dnsServer(settings); 76 | const Address& dnsListenAddr = settings.getDnsListenAddr(); 77 | if (dnsListenAddr.port) 78 | { 79 | if (!dnsServer.start()) 80 | return Log::errorf("Could not start DNS server on UDP port %s:%hu: %s", (const char*)Socket::inetNtoA(dnsListenAddr.addr), (uint16)dnsListenAddr.port, (const char*)Socket::getErrorString()), 1; 81 | Log::infof("Listening on UDP port %hu...", (uint16)dnsListenAddr.port); 82 | } 83 | 84 | // start transparent proxy server 85 | ProxyServer proxyServer(settings); 86 | const Address& listenAddr = settings.getListenAddr(); 87 | if (!proxyServer.start()) 88 | return Log::errorf("Could not start proxy server on TCP port %s:%hu: %s", (const char*)Socket::inetNtoA(listenAddr.addr), (uint16)listenAddr.port, (const char*)Socket::getErrorString()), 1; 89 | Log::infof("Listening on TCP port %hu...", (uint16)listenAddr.port); 90 | 91 | // start listening for debug connections 92 | const Address& debugListenAddr = settings.getDebugListenAddr(); 93 | if (debugListenAddr.port) 94 | { 95 | if (!proxyServer.startDebugPort()) 96 | return Log::errorf("Could not start proxy server on debug TCP port %s:%hu: %s", (const char*)Socket::inetNtoA(debugListenAddr.addr), (uint16)debugListenAddr.port, (const char*)Socket::getErrorString()), 1; 97 | Log::infof("Listening on debug TCP port %hu...", (uint16)debugListenAddr.port); 98 | } 99 | 100 | // run dns server 101 | Thread dnsThread; 102 | if (dnsListenAddr.port) 103 | { 104 | if (!dnsThread.start(dnsServer, &DnsServer::run)) 105 | return Log::errorf("Could not start thread: %s", (const char*)Socket::getErrorString()), 1; 106 | } 107 | 108 | // run transparent proxy server 109 | proxyServer.run(); 110 | return 1; 111 | } 112 | -------------------------------------------------------------------------------- /src/ProxyLine.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "ProxyLine.hpp" 3 | 4 | #include 5 | #include 6 | 7 | ProxyLine::ProxyLine(Server& server, Server::Client& client, ICallback& callback, Settings& settings) 8 | : _server(server) 9 | , _client(client) 10 | , _callback(callback) 11 | , _settings(settings) 12 | , _establisher(nullptr) 13 | , _handle(nullptr) 14 | , _port() 15 | , _connected(false) 16 | , _lastReadActivity(0) 17 | { 18 | ; 19 | } 20 | 21 | ProxyLine::~ProxyLine() 22 | { 23 | if(_establisher) 24 | _server.remove(*_establisher); 25 | if (_handle) 26 | _server.remove(*_handle); 27 | } 28 | 29 | bool ProxyLine::connect(const String& hostname, int16 port) 30 | { 31 | _hostname = hostname; 32 | _port = port; 33 | _httpProxyAddr = _settings.getProxyAddr(hostname); 34 | _establisher = _server.connect(_httpProxyAddr.addr, _httpProxyAddr.port, *this); 35 | if (!_establisher) 36 | return false; 37 | return true; 38 | } 39 | 40 | Server::Client::ICallback *ProxyLine::onConnected(Server::Client &client) 41 | { 42 | _handle = &client; 43 | String connectMsg; 44 | connectMsg.printf("CONNECT %s:%hu HTTP/1.1\r\nHost: %s:%hu\r\n\r\n", (const char*)_hostname, _port, (const char*)_hostname, _port); 45 | client.write((const byte*)(const char*)connectMsg, connectMsg.length()); 46 | return this; 47 | } 48 | 49 | void ProxyLine::onAbolished() 50 | { 51 | _callback.onClosed(*this, Error::getErrorString()); 52 | } 53 | 54 | void ProxyLine::onRead() 55 | { 56 | byte buffer[262144 + 1]; 57 | usize size; 58 | if (!_handle->read(buffer, sizeof(buffer) - 1, size)) 59 | return; 60 | if (_connected) 61 | { 62 | usize postponed = 0; 63 | if (!_client.write(buffer, size, &postponed)) 64 | return; 65 | if (postponed) 66 | _handle->suspend(); 67 | _lastReadActivity = Time::time(); 68 | } 69 | else 70 | { 71 | buffer[size] = '\0'; 72 | _proxyResponse.append((const char*)buffer, size); 73 | // expecting "HTTP/1.1 200 Connection established\r\n\r\n" 74 | const char* headerEnd = _proxyResponse.find("\r\n\r\n"); 75 | if (headerEnd) 76 | { 77 | if (_proxyResponse.compare("HTTP/1.1 200 ", 13) == 0) 78 | { 79 | const char* bufferPos = headerEnd + 4; 80 | usize remainingSize = _proxyResponse.length() - (bufferPos - (const char*)_proxyResponse); 81 | if (remainingSize) 82 | _client.write((const byte*)bufferPos, remainingSize); 83 | _proxyResponse = String(); 84 | _connected = true; 85 | _callback.onOpened(*this); 86 | _lastReadActivity = Time::time(); 87 | } 88 | else 89 | { 90 | const char* firstLineEnd = _proxyResponse.find("\r\n"); 91 | _callback.onClosed(*this, _proxyResponse.substr(0, firstLineEnd - (const char*)_proxyResponse)); 92 | } 93 | } 94 | else if (_proxyResponse.length() > 256) 95 | _callback.onClosed(*this, "Invalid HTTP reponse"); 96 | } 97 | } 98 | 99 | void ProxyLine::onWrite() 100 | { 101 | if (_connected) 102 | _client.resume(); 103 | } 104 | 105 | void ProxyLine::onClosed() 106 | { 107 | _callback.onClosed(*this, "Closed by proxy server"); 108 | } 109 | 110 | String ProxyLine::getDebugInfo() const 111 | { 112 | if (!_handle) 113 | return String("connecting"); 114 | 115 | uint32 ip = 0; 116 | uint16 port = 0; 117 | _handle->getSocket().getSockName(ip, port); 118 | 119 | //proxy0.0.0.0:82878active810.43.214.107:8080 120 | return String::fromPrintf("proxy%s:%hu%d%s%d%d%s:%hu", 121 | (const char*)Socket::inetNtoA(ip), port, 122 | (int)_handle->getSocket().getFileDescriptor(), 123 | _handle->isSuspended() ? "suspended" : "active", 124 | _lastReadActivity ? (int)((Time::time() - _lastReadActivity) / 1000) : -1, 125 | (int)_handle->getSendBufferSize(), 126 | (const char*)Socket::inetNtoA(_httpProxyAddr.addr), _httpProxyAddr.port); 127 | } 128 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Cpp 3 | # BasedOnStyle: WebKit 4 | AccessModifierOffset: -4 5 | AlignAfterOpenBracket: DontAlign 6 | AlignConsecutiveMacros: false 7 | AlignConsecutiveAssignments: false 8 | AlignConsecutiveDeclarations: false 9 | AlignEscapedNewlines: Right 10 | AlignOperands: false 11 | AlignTrailingComments: false 12 | AllowAllArgumentsOnNextLine: true 13 | AllowAllConstructorInitializersOnNextLine: true 14 | AllowAllParametersOfDeclarationOnNextLine: true 15 | AllowShortBlocksOnASingleLine: Empty 16 | AllowShortCaseLabelsOnASingleLine: false 17 | AllowShortFunctionsOnASingleLine: All 18 | AllowShortLambdasOnASingleLine: All 19 | AllowShortIfStatementsOnASingleLine: Never 20 | AllowShortLoopsOnASingleLine: false 21 | AlwaysBreakAfterDefinitionReturnType: None 22 | AlwaysBreakAfterReturnType: None 23 | AlwaysBreakBeforeMultilineStrings: false 24 | AlwaysBreakTemplateDeclarations: MultiLine 25 | BinPackArguments: true 26 | BinPackParameters: true 27 | BraceWrapping: 28 | AfterCaseLabel: false 29 | AfterClass: true 30 | AfterControlStatement: true 31 | AfterEnum: true 32 | AfterFunction: true 33 | AfterNamespace: false 34 | AfterObjCDeclaration: true 35 | AfterStruct: true 36 | AfterUnion: true 37 | AfterExternBlock: false 38 | BeforeCatch: true 39 | BeforeElse: true 40 | IndentBraces: false 41 | SplitEmptyFunction: true 42 | SplitEmptyRecord: true 43 | SplitEmptyNamespace: true 44 | BreakBeforeBinaryOperators: All 45 | BreakBeforeBraces: Custom 46 | BreakBeforeInheritanceComma: true 47 | BreakInheritanceList: BeforeColon 48 | BreakBeforeTernaryOperators: true 49 | BreakConstructorInitializersBeforeComma: false 50 | BreakConstructorInitializers: BeforeComma 51 | BreakAfterJavaFieldAnnotations: false 52 | BreakStringLiterals: true 53 | ColumnLimit: 0 54 | CommentPragmas: '^ IWYU pragma:' 55 | CompactNamespaces: false 56 | ConstructorInitializerAllOnOneLineOrOnePerLine: false 57 | ConstructorInitializerIndentWidth: 4 58 | ContinuationIndentWidth: 4 59 | Cpp11BracedListStyle: false 60 | DeriveLineEnding: true 61 | DerivePointerAlignment: false 62 | DisableFormat: false 63 | ExperimentalAutoDetectBinPacking: false 64 | FixNamespaceComments: false 65 | ForEachMacros: 66 | - foreach 67 | - Q_FOREACH 68 | - BOOST_FOREACH 69 | IncludeBlocks: Preserve 70 | IncludeCategories: 71 | - Regex: '^"(llvm|llvm-c|clang|clang-c)/' 72 | Priority: 2 73 | SortPriority: 0 74 | - Regex: '^(<|"(gtest|gmock|isl|json)/)' 75 | Priority: 3 76 | SortPriority: 0 77 | - Regex: '.*' 78 | Priority: 1 79 | SortPriority: 0 80 | IncludeIsMainRegex: '(Test)?$' 81 | IncludeIsMainSourceRegex: '' 82 | IndentCaseLabels: false 83 | IndentGotoLabels: true 84 | IndentPPDirectives: None 85 | IndentWidth: 4 86 | IndentWrappedFunctionNames: false 87 | JavaScriptQuotes: Leave 88 | JavaScriptWrapImports: true 89 | KeepEmptyLinesAtTheStartOfBlocks: true 90 | MacroBlockBegin: '' 91 | MacroBlockEnd: '' 92 | MaxEmptyLinesToKeep: 1 93 | NamespaceIndentation: None 94 | ObjCBinPackProtocolList: Auto 95 | ObjCBlockIndentWidth: 4 96 | ObjCSpaceAfterProperty: true 97 | ObjCSpaceBeforeProtocolList: true 98 | PenaltyBreakAssignment: 2 99 | PenaltyBreakBeforeFirstCallParameter: 19 100 | PenaltyBreakComment: 300 101 | PenaltyBreakFirstLessLess: 120 102 | PenaltyBreakString: 1000 103 | PenaltyBreakTemplateDeclaration: 10 104 | PenaltyExcessCharacter: 1000000 105 | PenaltyReturnTypeOnItsOwnLine: 60 106 | PointerAlignment: Left 107 | ReflowComments: true 108 | SortIncludes: true 109 | SortUsingDeclarations: true 110 | SpaceAfterCStyleCast: false 111 | SpaceAfterLogicalNot: false 112 | SpaceAfterTemplateKeyword: true 113 | SpaceBeforeAssignmentOperators: true 114 | SpaceBeforeCpp11BracedList: true 115 | SpaceBeforeCtorInitializerColon: true 116 | SpaceBeforeInheritanceColon: true 117 | SpaceBeforeParens: ControlStatements 118 | SpaceBeforeRangeBasedForLoopColon: true 119 | SpaceInEmptyBlock: true 120 | SpaceInEmptyParentheses: false 121 | SpacesBeforeTrailingComments: 1 122 | SpacesInAngles: false 123 | SpacesInConditionalStatement: false 124 | SpacesInContainerLiterals: true 125 | SpacesInCStyleCastParentheses: false 126 | SpacesInParentheses: false 127 | SpacesInSquareBrackets: false 128 | SpaceBeforeSquareBrackets: false 129 | Standard: Latest 130 | StatementMacros: 131 | - Q_UNUSED 132 | - QT_REQUIRE_VERSION 133 | TabWidth: 8 134 | UseCRLF: false 135 | UseTab: Never 136 | ... 137 | 138 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Dehprox 3 | 4 | [![Build Status](http://xaws6t1emwa2m5pr.myfritz.net:8080/buildStatus/icon?job=craflin%2Fdehprox%2Fmaster)](http://xaws6t1emwa2m5pr.myfritz.net:8080/job/craflin/job/dehprox/job/master/) 5 | 6 | Dehprox is a transparent DNS and TCP to HTTP proxy redirector (for Linux). 7 | It is designed to run in heavily guarded networks, where it is not possible to access some parts of the network without an HTTP proxy or to resolve DNS queries using a DNS to TCP or HTTP tunnel. 8 | DNS queries are answered with surrogate addresses that are mapped back to the hostname when the transparent proxy tries to establish a connection using the HTTP proxy. 9 | 10 | If your network is not that restricted, you should probably look at other TCP to proxy server redirectors like [redsocks2](https://github.com/semigodking/redsocks). 11 | 12 | ## Features 13 | 14 | * TCP traffic to HTTP proxy server redirection. 15 | * DNS resolution and resolution faking. 16 | * Automatic detection of a faster route without the HTTP proxy 17 | * White and black listing of destination addresses. 18 | * Using a specific proxy for certain destination addresses. 19 | * Skipping the HTTP proxy for certain IP ranges. 20 | 21 | ## Motivation 22 | 23 | In some cases, it is very time consuming to configure your system and your tools (that may ignore your system settings) to use a HTTP proxy and some tools might not support proxy servers at all. 24 | Hence, it might be a good idea to set up a little router that allows you to use your network like a network without a proxy. 25 | 26 | ## Build Instructions 27 | 28 | * Clone the repository and initialize submodules. 29 | * Build the project with `cmake`. 30 | * You can build a `deb` or `rpm` package using the target `package` in CMake. 31 | 32 | ## Router Setup 33 | 34 | * Use a machine (which may be virtual) with two network interfaces. 35 | * The first interface has to be connected to the network where you can reach the HTTP proxy. 36 | * The second interface will act as your gateway. Set it up with a somewhat static IPv4 address and it may or may not be in the same network. 37 | * Configure your `iptables` to redirect incoming DNS and TCP traffic from the second interface (except TCP traffic directly directed to your router) to the transparent proxy: 38 | ``` 39 | iptables -t nat -A PREROUTING -i -p udp --dport 53 -j DNAT --to :62124 40 | iptables -t nat -A PREROUTING -i -p tcp ! -d -j DNAT --to :62124 41 | ``` 42 | * Install `dehprox`, configure the HTTP proxy in `/etc/dehprox.conf` (if necessary) and start the `dehprox` server. 43 | * Configure your clients to be in the same network as the second interface and to use the IP address of the second interface as gateway and DNS server. 44 | * If there is no DHCP server in the network of the second interface, you can configure a DHCP server to run on the second interface to auto-configure your clients. 45 | * With some iptables rules, you can configure your router to do IP forwarding and to not route some IP ranges to dehprox to skip the proxy for these IP ranges. (But don't ask me how.) 46 | 47 | (It might be possible to set up the proxy in different ways (like using it locally without a second machine), but I have not yet tried anything else.) 48 | 49 | ## How Does it Work? 50 | 51 | Dehprox acts as DNS server and as a transparent proxy server if traffic from a network interface is redirected to dehprox using `iptables` rules and if clients are configured to use that interface as gateway and DNS server. 52 | 53 | If the system receives a DNS resolution request (on the configured interface) it is redirected to UDP port 62124. 54 | Dehproxy listens on this port and receives the DNS resolution request. 55 | It tries to resolve the request using the default DNS resolution settings of the system. 56 | If it can be resolved, the answer is redirected to requester. 57 | If it cannot be resolved, dehprox generates and returns a fake address in the `100.64.0.0/10` reserved IP address range. 58 | 59 | If a client tries to establish a connection to such a address (or any address), it is redirected to TCP port 62124 of the router system because of the `iptables` rules. 60 | Dehprox listens an this port and accepts the connection. 61 | The original destination of the connection can be determined with the socket option `SO_ORIGINAL_DST`. 62 | If it is one of the fake addresses in the `100.64.0.0/10` range, it is mapped back to the hostname and the HTTP proxy server is used to establish a connection to the host (if possible). 63 | If it is not a fake address, dehprox tries to connect to that address with and without the proxy server. 64 | The connection that is established first is the one that is used and the other one is discarded. 65 | -------------------------------------------------------------------------------- /src/DnsDatabase.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "DnsDatabase.hpp" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #define FAKE_ADDR_SUBNET 0x64400000 // "Shared Address Space for Service Providers" 10 | #define FAKE_ADDR_SUBNET_MASK (~(0xffffffff >> 10)) 11 | 12 | namespace { 13 | 14 | struct AddrInfo 15 | { 16 | uint32 addr; 17 | int64 timestamp; 18 | }; 19 | 20 | Mutex _mutex; 21 | HashMap _nameToAddr(2000); 22 | HashMap _addrToName(2000); 23 | 24 | void _cleanupAddresses() 25 | { 26 | // remove addresses older than 15 minutes from cache 27 | int64 now = Time::time(); 28 | while (!_nameToAddr.isEmpty()) 29 | { 30 | const AddrInfo& addrInfo = *_nameToAddr.begin(); 31 | if (now - addrInfo.timestamp > 60 * 60 * 1000) // 1 hour 32 | { 33 | if (addrInfo.addr != 0) 34 | _addrToName.remove(addrInfo.addr); 35 | _nameToAddr.removeFront(); 36 | } 37 | else 38 | break; 39 | } 40 | } 41 | } 42 | 43 | bool DnsDatabase::resolve(const String& hostname, uint32& addr) 44 | { 45 | { 46 | _mutex.lock(); 47 | HashMap::Iterator it = _nameToAddr.find(hostname); 48 | if (it != _nameToAddr.end()) 49 | { 50 | const AddrInfo& addrInfo = *it; 51 | addr = addrInfo.addr; 52 | bool result = addrInfo.addr != 0; 53 | if (Time::time() - addrInfo.timestamp <= 10 * 60 * 1000) // the cached entry should not be older than 10 minutes 54 | { 55 | _mutex.unlock(); 56 | return result; 57 | } 58 | } 59 | _mutex.unlock(); 60 | } 61 | 62 | bool result = Socket::getHostByName(hostname, addr); 63 | 64 | { 65 | _mutex.lock(); 66 | HashMap::Iterator it = _nameToAddr.find(hostname); 67 | if (it != _nameToAddr.end()) 68 | { 69 | if (it->addr != 0) 70 | _addrToName.remove(it->addr); 71 | _nameToAddr.remove(it); 72 | } 73 | AddrInfo addrInfo = {result ? addr : 0, Time::time()}; 74 | _nameToAddr.append(hostname, addrInfo); 75 | if (result) 76 | _addrToName.append(addr, hostname); 77 | _mutex.unlock(); 78 | } 79 | 80 | return result; 81 | } 82 | 83 | bool DnsDatabase::reverseResolve(uint32 addr, String& hostname) 84 | { 85 | if ((addr & FAKE_ADDR_SUBNET_MASK) == FAKE_ADDR_SUBNET) 86 | return false; 87 | bool result = false; 88 | { 89 | _mutex.lock(); 90 | HashMap::Iterator it = _addrToName.find(addr); 91 | if (it != _addrToName.end()) 92 | { 93 | result = true; 94 | hostname = *it; 95 | } 96 | _cleanupAddresses(); 97 | _mutex.unlock(); 98 | } 99 | return result; 100 | } 101 | 102 | uint32 DnsDatabase::resolveFake(const String& hostname) 103 | { 104 | uint32 fakeAddr; 105 | 106 | { 107 | _mutex.lock(); 108 | HashMap::Iterator it = _nameToAddr.find(hostname); 109 | if (it != _nameToAddr.end() && it->addr != 0) 110 | { 111 | fakeAddr = it->addr; 112 | } 113 | else 114 | { 115 | if (it != _nameToAddr.end()) 116 | _nameToAddr.remove(it); 117 | 118 | // create a somewhat deterministic unique fake addr using a hashsum of the hostname 119 | fakeAddr = hash(hostname); 120 | for (int i = 1;; ++i) 121 | { 122 | if (i == 200) 123 | { 124 | fakeAddr = (uint32)Time::microTicks(); // add true randomness after 200 failed unique addr generation attempts 125 | i = 0; 126 | } 127 | fakeAddr *= 16807; 128 | if (!hostname.isEmpty()) 129 | fakeAddr ^= ((const char*)hostname)[i % hostname.length()]; 130 | fakeAddr = (fakeAddr & ~FAKE_ADDR_SUBNET_MASK) | FAKE_ADDR_SUBNET; 131 | if ((fakeAddr & 0xff) == 0xff || (fakeAddr & 0xff00) == 0xff00 || (fakeAddr & 0xff0000) == 0xff0000) 132 | continue; 133 | HashMap::Iterator it = _addrToName.find(fakeAddr); 134 | if (it != _addrToName.end()) 135 | continue; 136 | break; 137 | } 138 | AddrInfo addrInfo = {fakeAddr, Time::time()}; 139 | _nameToAddr.append(hostname, addrInfo); 140 | _addrToName.append(fakeAddr, hostname); 141 | } 142 | _mutex.unlock(); 143 | } 144 | 145 | return fakeAddr; 146 | } 147 | 148 | bool DnsDatabase::isFake(uint32 addr) 149 | { 150 | return (addr & FAKE_ADDR_SUBNET_MASK) == FAKE_ADDR_SUBNET; 151 | } 152 | 153 | bool DnsDatabase::reverseResolveFake(uint32 addr, String& hostname) 154 | { 155 | if ((addr & FAKE_ADDR_SUBNET_MASK) != FAKE_ADDR_SUBNET) 156 | return false; 157 | bool result = false; 158 | { 159 | _mutex.lock(); 160 | HashMap::Iterator it = _addrToName.find(addr); 161 | if (it != _addrToName.end()) 162 | { 163 | result = true; 164 | hostname = *it; 165 | } 166 | _cleanupAddresses(); 167 | _mutex.unlock(); 168 | } 169 | return result; 170 | } 171 | -------------------------------------------------------------------------------- /src/Settings.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "Settings.hpp" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | Settings::Settings(const String& file) : _autoProxySkip(true) 10 | { 11 | Address defaultHttpProxyAddr; 12 | defaultHttpProxyAddr.addr = Socket::loopbackAddress; 13 | defaultHttpProxyAddr.port = 3128; 14 | _httpProxyAddrs.append(defaultHttpProxyAddr); 15 | 16 | _listenAddr.port = 62124; 17 | _dnsListenAddr.port = 62124; 18 | 19 | String conf; 20 | if (!File::readAll(file, conf)) 21 | return; 22 | List lines; 23 | conf.split(lines, "\n\r"); 24 | bool httpProxyAddrsSet = false; 25 | for (List::Iterator i = lines.begin(), end = lines.end(); i != end; ++i) 26 | { 27 | String line = *i; 28 | const char* lineEnd = line.find('#'); 29 | if (lineEnd) 30 | line.resize(lineEnd - (const char*)line); 31 | line.trim(); 32 | if (line.isEmpty()) 33 | continue; 34 | List tokens; 35 | line.split(tokens, " \t"); 36 | if (tokens.size() < 2) 37 | continue; 38 | const String& option = *tokens.begin(); 39 | const String& value = *(++tokens.begin()); 40 | if (option == "httpProxyAddr") 41 | { 42 | if (!httpProxyAddrsSet) 43 | { 44 | httpProxyAddrsSet = true; 45 | _httpProxyAddrs.clear(); 46 | } 47 | 48 | Address addr; 49 | addr.addr = Socket::inetAddr(value, &addr.port); 50 | 51 | if (tokens.size() > 2) 52 | { 53 | const String& destination = *(++(++tokens.begin())); 54 | 55 | DestinationHttpProxyAddrsMap::Iterator it = _destinationHttpProxyAddrs.find(destination); 56 | if (it == _destinationHttpProxyAddrs.end()) 57 | it = _destinationHttpProxyAddrs.insert(_destinationHttpProxyAddrs.end(), destination, Array
()); 58 | it->append(addr); 59 | } 60 | else 61 | _httpProxyAddrs.append(addr); 62 | } 63 | else if (option == "listenAddr") 64 | _listenAddr.addr = Socket::inetAddr(value, &_listenAddr.port); 65 | else if (option == "debugListenAddr") 66 | _debugListenAddr.addr = Socket::inetAddr(value, &_debugListenAddr.port); 67 | else if (option == "dnsListenAddr") 68 | _dnsListenAddr.addr = Socket::inetAddr(value, &_dnsListenAddr.port); 69 | else if (option == "autoProxySkip") 70 | _autoProxySkip = value.toBool(); 71 | else if (option == "allowDest") 72 | _whiteList.append(value); 73 | else if (option == "denyDest") 74 | _blackList.append(value); 75 | else if (option == "skipProxyDest") 76 | _skipProxyList.append(value); 77 | else if (option == "skipProxyRange") 78 | { 79 | List tokens; 80 | value.split(tokens, "/\\"); 81 | if (tokens.size() < 2) 82 | { 83 | Log::warningf("Cannot parse value: %s", (const char*)value); 84 | continue; 85 | } 86 | IpRange range; 87 | range.network = Socket::inetAddr(*tokens.begin()); 88 | uint32 subnet = (++tokens.begin())->toUInt(); 89 | range.mask = (uint32)-1 << (32 - subnet); 90 | range.network &= range.mask; 91 | _skipProxyRanges.append(range); 92 | } 93 | else 94 | Log::warningf("Unknown option: %s", (const char*)option); 95 | } 96 | } 97 | 98 | namespace { 99 | bool isInList(const String& hostname_, const HashSet& list) 100 | { 101 | if (list.contains(hostname_)) 102 | return true; 103 | const char* x = hostname_.find('.'); 104 | if (!x) 105 | return false; 106 | String hostname = hostname_.substr(x - (const char*)hostname_ + 1); 107 | for (;;) 108 | { 109 | if (list.contains(hostname)) 110 | return true; 111 | const char* x = hostname.find('.'); 112 | if (!x) 113 | return false; 114 | hostname = hostname.substr(x - (const char*)hostname + 1); 115 | } 116 | } 117 | } 118 | 119 | bool Settings::isInWhiteList(const String& destination) const 120 | { 121 | return ::isInList(destination, _whiteList); 122 | } 123 | 124 | bool Settings::isInBlackList(const String& destination) const 125 | { 126 | return ::isInList(destination, _blackList); 127 | } 128 | 129 | bool Settings::isInSkipProxyList(const String& destination) const 130 | { 131 | return ::isInList(destination, _skipProxyList); 132 | } 133 | 134 | bool Settings::isInSkipProxyRangeList(uint32 ip) const 135 | { 136 | for (Array::Iterator i = _skipProxyRanges.begin(), end = _skipProxyRanges.end(); i != end; ++i) 137 | { 138 | const IpRange& range = *i; 139 | if ((ip & range.mask) == range.network) 140 | return true; 141 | } 142 | return false; 143 | } 144 | 145 | namespace { 146 | const Address& getRandomProxyAddr(const Array
& addrs) 147 | { 148 | return addrs[Math::random() % addrs.size()]; 149 | } 150 | } 151 | 152 | const Address& Settings::getProxyAddr(const String& destination_) 153 | { 154 | DestinationHttpProxyAddrsMap::Iterator it = _destinationHttpProxyAddrs.find(destination_); 155 | if (it != _destinationHttpProxyAddrs.end()) 156 | return getRandomProxyAddr(*it); 157 | if (const char* x = destination_.find('.')) 158 | { 159 | String destination = destination_.substr(x - (const char*)destination_ + 1); 160 | for (;;) 161 | { 162 | it = _destinationHttpProxyAddrs.find(destination); 163 | if (it != _destinationHttpProxyAddrs.end()) 164 | return getRandomProxyAddr(*it); 165 | const char* x = destination.find('.'); 166 | if (!x) 167 | break; 168 | destination = destination.substr(x - (const char*)destination + 1); 169 | } 170 | } 171 | return getRandomProxyAddr(_httpProxyAddrs); 172 | } 173 | -------------------------------------------------------------------------------- /src/Client.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "Client.hpp" 3 | 4 | #ifndef _WIN32 5 | #include 6 | #include 7 | #endif 8 | 9 | #include 10 | #include 11 | #include 12 | 13 | #include "DnsDatabase.hpp" 14 | #include "DirectLine.hpp" 15 | #include "ProxyLine.hpp" 16 | 17 | bool getOriginalDst(Socket& s, uint32& addr, uint16& port) 18 | { 19 | #ifdef _WIN32 20 | return s.getSockName(addr, port); 21 | #else 22 | sockaddr_in destAddr; 23 | usize destAddrLen = sizeof(destAddr); 24 | if(!s.getSockOpt(SOL_IP, SO_ORIGINAL_DST, &destAddr, destAddrLen)) 25 | return false; 26 | addr = ntohl(destAddr.sin_addr.s_addr); 27 | port = ntohs(destAddr.sin_port); 28 | return true; 29 | #endif 30 | } 31 | 32 | Client::Client(Server& server, Server::Client& client, const Address& clientAddr, ICallback& callback, Settings& settings) 33 | : _server(server) 34 | , _handle(client) 35 | , _callback(callback) 36 | , _settings(settings) 37 | , _proxyLine(nullptr) 38 | , _directLine(nullptr) 39 | , _activeLine(nullptr) 40 | , _address(clientAddr) 41 | , _lastReadActivity(0) 42 | { 43 | ; 44 | } 45 | 46 | Client::~Client() 47 | { 48 | _server.remove(_handle); 49 | Log::debugf("%s: Closed client for %s:%hu (%s)", (const char*)Socket::inetNtoA(_address.addr), 50 | (const char*)Socket::inetNtoA(_destination.addr), _destination.port, (const char*)_destinationHostname); 51 | delete _proxyLine; 52 | delete _directLine; 53 | } 54 | 55 | bool Client::init() 56 | { 57 | Socket& clientSocket = _handle.getSocket(); 58 | if (!getOriginalDst(clientSocket, _destination.addr, _destination.port)) 59 | return false; 60 | 61 | bool directConnect = false; 62 | bool proxyConnect = false; 63 | const char* rejectReason = nullptr; 64 | if (DnsDatabase::reverseResolveFake(_destination.addr, _destinationHostname)) 65 | proxyConnect = true; 66 | else if (DnsDatabase::reverseResolve(_destination.addr, _destinationHostname)) 67 | { 68 | directConnect = _settings.isAutoProxySkipEnabled(); 69 | proxyConnect = true; 70 | } 71 | else if (!DnsDatabase::isFake(_destination.addr)) 72 | { 73 | _destinationHostname = Socket::inetNtoA(_destination.addr); 74 | directConnect = _settings.isAutoProxySkipEnabled(); 75 | proxyConnect = true; 76 | } 77 | else 78 | rejectReason = "Unknown surrogate address"; 79 | 80 | if (!rejectReason) 81 | { 82 | if (!_settings.isWhiteListEmpty() && !_settings.isInWhiteList(_destinationHostname)) 83 | rejectReason = "Not listed in white list"; 84 | else if (_settings.isInBlackList(_destinationHostname)) 85 | rejectReason = "Listed in black list"; 86 | } 87 | 88 | if (rejectReason) 89 | { 90 | Log::infof("%s: Rejected client for %s:%hu (%s): %s", (const char*)Socket::inetNtoA(_address.addr), 91 | (const char*)Socket::inetNtoA(_destination.addr), _destination.port, (const char*)_destinationHostname, rejectReason); 92 | return false; 93 | } 94 | 95 | if (_settings.isInSkipProxyList(_destinationHostname) || _settings.isInSkipProxyRangeList(_destination.addr)) 96 | { 97 | directConnect = true; 98 | proxyConnect = false; 99 | } 100 | 101 | Log::debugf("%s: Accepted client for %s:%hu (%s)", (const char*)Socket::inetNtoA(_address.addr), 102 | (const char*)Socket::inetNtoA(_destination.addr), _destination.port, (const char*)_destinationHostname); 103 | 104 | if (directConnect) 105 | { 106 | _directLine = new DirectLine(_server, _handle, *this); 107 | if (!_directLine->connect(_destination)) 108 | return false; 109 | } 110 | 111 | if (proxyConnect) 112 | { 113 | _proxyLine = new ProxyLine(_server, _handle, *this, _settings); 114 | if (!_proxyLine->connect(_destinationHostname, _destination.port)) 115 | return false; 116 | } 117 | 118 | _handle.suspend(); 119 | return true; 120 | } 121 | 122 | void Client::onRead() 123 | { 124 | byte buffer[262144]; 125 | usize size; 126 | if (!_handle.read(buffer, sizeof(buffer), size)) 127 | return; 128 | usize postponed = 0; 129 | if (!_activeLine->write(buffer, size, &postponed)) 130 | return; 131 | if (postponed) 132 | _handle.suspend(); 133 | _lastReadActivity = Time::time(); 134 | } 135 | 136 | void Client::onWrite() 137 | { 138 | if (_activeLine) 139 | _activeLine->resume(); 140 | } 141 | 142 | void Client::onClosed() 143 | { 144 | _callback.onClosed(*this); 145 | } 146 | 147 | void Client::onOpened(DirectLine&) 148 | { 149 | _activeLine = _directLine->getHandle(); 150 | delete _proxyLine; 151 | _proxyLine = nullptr; 152 | Log::infof("%s: Established direct connection with %s:%hu", (const char*)Socket::inetNtoA(_address.addr), 153 | (const char*)_destinationHostname, _destination.port); 154 | _handle.resume(); 155 | } 156 | 157 | void Client::onClosed(DirectLine&, const String& error) 158 | { 159 | delete _directLine; 160 | _directLine = nullptr; 161 | if (!_proxyLine) 162 | close(error); 163 | } 164 | 165 | void Client::onOpened(ProxyLine&) 166 | { 167 | _activeLine = _proxyLine->getHandle(); 168 | delete _directLine; 169 | _directLine = nullptr; 170 | Log::infof("%s: Established proxy connection with %s:%hu", (const char*)Socket::inetNtoA(_address.addr), 171 | (const char*)_destinationHostname, _destination.port); 172 | _handle.resume(); 173 | } 174 | 175 | void Client::onClosed(ProxyLine&, const String& error) 176 | { 177 | delete _proxyLine; 178 | _proxyLine = nullptr; 179 | if (!_directLine) 180 | close(error); 181 | } 182 | 183 | void Client::close(const String& error) 184 | { 185 | if (!_activeLine) 186 | Log::infof("%s: Failed to establish connection with %s:%hu: %s", (const char*)Socket::inetNtoA(_address.addr), 187 | (const char*)_destinationHostname, _destination.port, (const char*)error); 188 | _callback.onClosed(*this); 189 | } 190 | 191 | String Client::getDebugInfo() const 192 | { 193 | String result(""); 194 | 195 | //192.168.0.196:5626977active8k8s.pforgeipt.intra.airbusds.corp:443", 196 | result += String::fromPrintf("%s:%hu%d%s%d%d%s:%hu", 197 | (const char*)Socket::inetNtoA(_address.addr), _address.port, (int)_handle.getSocket().getFileDescriptor(), 198 | _handle.isSuspended() ? "suspended" : "active", _lastReadActivity ? (int)((Time::time() - _lastReadActivity) / 1000) : (int)-1, 199 | (int)_handle.getSendBufferSize(), 200 | (const char*)_destinationHostname, _destination.port); 201 | 202 | if (_proxyLine && !_directLine) 203 | result.append(_proxyLine->getDebugInfo()); 204 | else if (_directLine && !_proxyLine) 205 | result.append(_directLine->getDebugInfo()); 206 | else 207 | result.append(String("connecting")); 208 | 209 | result.append(""); 210 | return result; 211 | } 212 | -------------------------------------------------------------------------------- /src/DnsServer.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "DnsServer.hpp" 3 | 4 | #ifdef _WIN32 5 | #include 6 | #else 7 | #include 8 | #endif 9 | 10 | #include 11 | 12 | #include 13 | 14 | #include "DnsDatabase.hpp" 15 | 16 | namespace { 17 | 18 | #pragma pack(push, 1) 19 | struct DnsHeader 20 | { 21 | uint16 id; 22 | uint16 flags; 23 | uint16 questionCount; 24 | uint16 answerCount; 25 | uint16 nameServerRecordCount; 26 | uint16 additionalRecordCount; 27 | }; 28 | struct DnsQuestion 29 | { 30 | uint16 queryType; 31 | uint16 queryClass; 32 | }; 33 | struct DnsAnswer 34 | { 35 | uint16 name; 36 | uint16 answerType; 37 | uint16 answerClass; 38 | uint32 validityTime; 39 | uint16 len; 40 | uint32 addr; 41 | }; 42 | #pragma pack(pop) 43 | 44 | #define DNS_QR_BIT 0x80 45 | #define DNS_RA_BIT 0x8000 46 | 47 | bool skipQuestion(const byte*& pos, const byte* end) 48 | { 49 | for (;;) 50 | { 51 | if (pos == end) 52 | return false; 53 | uint8 len = *(pos++); 54 | if (!len) 55 | break; 56 | if (pos + len > end) 57 | return false; 58 | pos += len; 59 | } 60 | if (pos + sizeof(DnsQuestion) > end) 61 | return false; 62 | pos += sizeof(DnsQuestion); 63 | return true; 64 | } 65 | 66 | bool parseQuestion(const byte*& pos, const byte* end, String& host, DnsQuestion& question) 67 | { 68 | host.clear(); 69 | for (;;) 70 | { 71 | if (pos == end) 72 | return false; 73 | uint8 len = *(pos++); 74 | if (!len) 75 | break; 76 | if (pos + len > end) 77 | return false; 78 | if (!host.isEmpty()) 79 | host.append('.'); 80 | host.append((const char*)pos, len); 81 | pos += len; 82 | } 83 | if (pos + sizeof(DnsQuestion) > end) 84 | return false; 85 | question.queryType = ntohs(((const DnsQuestion*)pos)->queryType); 86 | question.queryClass = ntohs(((const DnsQuestion*)pos)->queryClass); 87 | pos += sizeof(DnsQuestion); 88 | return true; 89 | } 90 | 91 | bool appendAnswer(const byte*& pos, const byte* end, const DnsQuestion& question, usize offset, uint32 addr) 92 | { 93 | if (pos + sizeof(DnsAnswer) > end) 94 | return false; 95 | DnsAnswer* answer = (DnsAnswer*)pos; 96 | answer->name = htons(offset | 0xc000); 97 | answer->answerType = htons(question.queryType); 98 | answer->answerClass = htons(question.queryClass); 99 | answer->validityTime = htonl(10 * 60); // 10 minutes 100 | answer->len = htons(sizeof(uint32)); 101 | answer->addr = htonl(addr); 102 | pos += sizeof(DnsAnswer); 103 | return true; 104 | } 105 | 106 | } 107 | 108 | bool DnsServer::start() 109 | { 110 | const Address& dnsListenAddr = _settings.getDnsListenAddr(); 111 | if (!_socket.open(Socket::udpProtocol) || 112 | !_socket.setReuseAddress() || 113 | !_socket.bind(dnsListenAddr.addr, dnsListenAddr.port)) 114 | return false; 115 | return true; 116 | } 117 | 118 | uint DnsServer::run() 119 | { 120 | byte query[4096 * 2]; 121 | byte response[4096 * 2]; 122 | Address sender; 123 | String hostname; 124 | DnsHeader* queryHeader = (DnsHeader*)query; 125 | DnsHeader* responseHeader = (DnsHeader*)response; 126 | const byte* responseEnd = response + sizeof(response); 127 | for (;;) 128 | { 129 | ssize size = _socket.recvFrom(query, sizeof(query), sender.addr, sender.port); 130 | if (size < 0) 131 | break; 132 | if (size < sizeof(DnsHeader)) 133 | continue; 134 | uint16 flags = ntohs(queryHeader->flags); 135 | if (flags & DNS_QR_BIT) 136 | continue; 137 | uint16 questionCount = ntohs(queryHeader->questionCount); 138 | const byte* pos = (const byte*)(queryHeader + 1); 139 | const byte* end = query + size; 140 | for (uint16 i = 0; i < questionCount; ++i) 141 | if (!skipQuestion(pos, end)) 142 | goto ignoreRequest; 143 | { 144 | usize querySize = end - query; 145 | const byte* responsePos = response + querySize; 146 | pos = (const byte*)(queryHeader + 1); 147 | uint16 answerCount = 0; 148 | for (uint16 i = 0; i < questionCount; ++i) 149 | { 150 | const byte* pointerPos = pos; 151 | DnsQuestion question; 152 | if (!parseQuestion(pos, end, hostname, question)) 153 | goto ignoreRequest; 154 | 155 | const char* rejectReason = nullptr; 156 | if (!_settings.isWhiteListEmpty() && !_settings.isInWhiteList(hostname)) 157 | rejectReason = "Not listed in white list"; 158 | else if (_settings.isInBlackList(hostname)) 159 | rejectReason = "Listed in black list"; 160 | 161 | if (rejectReason) 162 | { 163 | Log::infof("%s: Ignored DNS query for %s: %s", (const char*)Socket::inetNtoA(sender.addr), (const char*)hostname, rejectReason); 164 | continue; // don't try to resolve black listed hostnames to keep them out of the DnsDatabase 165 | } 166 | 167 | uint32 addr; 168 | bool isFakeAddr = false; 169 | if (!DnsDatabase::resolve(hostname, addr)) 170 | { 171 | if (!hostname.find('.')) 172 | { 173 | Log::debugf("%s: Ignored DNS query for %s", (const char*)Socket::inetNtoA(sender.addr), (const char*)hostname); 174 | continue; 175 | } 176 | addr = DnsDatabase::resolveFake(hostname); 177 | isFakeAddr = true; 178 | } 179 | 180 | Log::debugf("%s: Answered DNS query for %s with %s%s", (const char*)Socket::inetNtoA(sender.addr), 181 | (const char*)hostname, (const char*)Socket::inetNtoA(addr), isFakeAddr ? " (surrogate)" : ""); 182 | 183 | if (!appendAnswer(responsePos, responseEnd, question, pointerPos - query, addr)) 184 | goto ignoreRequest; 185 | ++answerCount; 186 | } 187 | // create response header 188 | memcpy(responseHeader, query, querySize); 189 | responseHeader->flags = htons(flags | DNS_QR_BIT | DNS_RA_BIT); 190 | responseHeader->answerCount = htons(answerCount); 191 | responseHeader->nameServerRecordCount = 0; 192 | responseHeader->additionalRecordCount = 0; 193 | 194 | // send response 195 | _socket.sendTo((byte*)responseHeader, responsePos - (byte*)responseHeader, sender.addr, sender.port); 196 | } 197 | ignoreRequest:; 198 | } 199 | return 1; 200 | } 201 | -------------------------------------------------------------------------------- /src/TestProxy/Main.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | class Client : public Server::Client::ICallback, public Server::Establisher::ICallback 10 | { 11 | public: 12 | class ICallback 13 | { 14 | public: 15 | virtual void onClosed(Client& client) = 0; 16 | 17 | protected: 18 | ICallback() {} 19 | ~ICallback() {} 20 | }; 21 | 22 | public: 23 | Client(Server& server, Server::Client& client, ICallback& callback) : _server(server), _client(client), _callback(callback), _uplink(nullptr), _targetPort(0), _httpConnectMethod(false), _establisher(nullptr) {} 24 | ~Client(); 25 | 26 | public: // Server::Client::ICallback 27 | void onRead() override; 28 | void onWrite() override; 29 | void onClosed() override { _callback.onClosed(*this); } 30 | 31 | private: // Server::Establisher::ICallback 32 | Server::Client::ICallback *onConnected(Server::Client &client) override; 33 | void onAbolished() override; 34 | 35 | private: 36 | class Uplink : public Server::Client::ICallback 37 | { 38 | public: 39 | Server::Client& _uplink; 40 | 41 | public: 42 | Uplink(Client& client, Server::Client& uplink) : _uplink(uplink), _p(client) {} 43 | ~Uplink(); 44 | 45 | private: // Server::Client::ICallback 46 | void onRead() override; 47 | void onWrite() override; 48 | void onClosed() override; 49 | 50 | private: 51 | Client& _p; 52 | }; 53 | 54 | private: 55 | Server& _server; 56 | Server::Client& _client; 57 | ICallback& _callback; 58 | Uplink* _uplink; 59 | String _target; 60 | uint16 _targetPort; 61 | bool _httpConnectMethod; 62 | Server::Establisher* _establisher; 63 | Buffer _receiveBuffer; 64 | }; 65 | 66 | Client::~Client() 67 | { 68 | _server.remove(_client); 69 | if (_establisher) 70 | _server.remove(*_establisher); 71 | delete _uplink; 72 | } 73 | 74 | Client::Uplink::~Uplink() 75 | { 76 | _p._server.remove(_uplink); 77 | } 78 | 79 | namespace { 80 | 81 | bool parseNextWord(const char*& str, String& word) 82 | { 83 | while (String::isSpace(*str)) 84 | ++str; 85 | const char* end = String::findOneOf(str, " \r\t\n"); 86 | if (!end) 87 | return false; 88 | word.attach(str, end - str); 89 | str = end; 90 | return true; 91 | } 92 | 93 | bool parseSkipLine(const char*& str) 94 | { 95 | const char* end = String::findOneOf(str, "\r\n"); 96 | if (!end) 97 | return false; 98 | str = end; 99 | if (*str == '\r') 100 | ++str; 101 | if (*str == '\n') 102 | ++str; 103 | return *str != '\r' && *str != '\n'; 104 | } 105 | 106 | void parseHost(const String& uri, String& host, uint16& port) 107 | { 108 | const char* uriStart = uri; 109 | const char* portStart = String::find(uriStart, ':'); 110 | if (portStart) 111 | { 112 | port = String::toInt(portStart + 1); 113 | host = uri.substr(0, portStart - uriStart); 114 | } 115 | else 116 | { 117 | host = uri; 118 | port = 0; 119 | } 120 | } 121 | 122 | } 123 | 124 | void Client::onRead() 125 | { 126 | byte buffer[262144 + 1]; 127 | usize size; 128 | if (!_client.read(buffer, sizeof(buffer) - 1, size)) 129 | return; 130 | if (_uplink) 131 | { 132 | usize postponed = 0; 133 | if (!_uplink->_uplink.write(buffer, size, &postponed)) 134 | return; 135 | if (postponed) 136 | _client.suspend(); 137 | } 138 | else if (_establisher) 139 | _receiveBuffer.append(buffer, size); 140 | else 141 | { 142 | _receiveBuffer.append(buffer, size); 143 | const char* headerStart = (const char*)(const byte*)_receiveBuffer; 144 | const char* headerEnd = String::find(headerStart, "\r\n\r\n"); 145 | if (headerEnd) 146 | { 147 | _client.suspend(); 148 | 149 | const char* i = headerStart; 150 | String method; 151 | String uri; 152 | parseNextWord(i, method); 153 | parseNextWord(i, uri); 154 | { 155 | String headerField; 156 | while (parseSkipLine(i)) 157 | { 158 | if (!parseNextWord(i, headerField)) 159 | break; 160 | if (headerField == "Host:") 161 | { 162 | String host; 163 | parseNextWord(i, host); 164 | parseHost(host, _target, _targetPort); 165 | break; 166 | } 167 | } 168 | } 169 | if (method == "CONNECT") 170 | { 171 | _httpConnectMethod = true; 172 | if (!_target.isEmpty()) 173 | parseHost(uri, _target, _targetPort); 174 | if (!_targetPort) 175 | _targetPort = 80; 176 | _receiveBuffer.removeFront(headerEnd + 4 - headerStart); 177 | } 178 | else 179 | { 180 | int protocolLen = 0; 181 | uint16 defaultPort = 80; 182 | if (uri.startsWith("http://")) 183 | protocolLen = 4; 184 | else if (uri.startsWith("https://")) 185 | { 186 | protocolLen = 5; 187 | defaultPort = 443; 188 | } 189 | if (!_targetPort) 190 | _targetPort = defaultPort; 191 | String uriTarget; 192 | uint16 uriPort; 193 | if (protocolLen) 194 | { 195 | const char* uriStart = (const char*)uri; 196 | const char* hostStart = (const char*)uri + (protocolLen + 3); 197 | const char* hostEnd = String::find(hostStart, "/"); 198 | if (!hostEnd) 199 | hostEnd = (const char*)uri + uri.length(); 200 | String host; 201 | host.attach(hostStart, hostEnd - hostStart); 202 | parseHost(host, uriTarget, uriPort); 203 | if (!uriPort) 204 | uriPort = defaultPort; 205 | if (_target.isEmpty()) 206 | { 207 | _target = uriTarget; 208 | _targetPort = uriPort; 209 | } 210 | //if (_target == uriTarget && _targetPort == uriPort) 211 | //{ 212 | // const char* uriSplit = String::find(headerStart + method.length(), "//"); 213 | // if (uriSplit) 214 | // { 215 | // uriSplit = String::find(uriSplit + 2, '/'); 216 | // if (uriSplit) 217 | // { 218 | // usize toRemove = uriSplit - headerStart - (method.length() + 1); 219 | // _receiveBuffer.removeFront(toRemove); 220 | // Memory::copy(_receiveBuffer, method, method.length()); 221 | // ((char*)(byte*)_receiveBuffer)[method.length()] = ' '; 222 | // headerStart = (const char*)(const byte*)_receiveBuffer; 223 | // } 224 | // } 225 | //} 226 | } 227 | } 228 | 229 | if (_target.isEmpty()) 230 | { 231 | String request(headerStart, headerEnd - headerStart); 232 | Console::printf("Ignored request: %s\n", (const char*)request); 233 | _callback.onClosed(*this); 234 | } 235 | else 236 | { 237 | String request(headerStart, headerEnd - headerStart); 238 | Console::printf("Handled request: %s\n", (const char*)request); 239 | 240 | Console::printf("Connecting to %s:%d...\n", (const char*)_target, (int)_targetPort); 241 | _establisher = _server.connect(_target, _targetPort, *this); 242 | } 243 | 244 | } 245 | else if (_receiveBuffer.size() > 8 * 1024) 246 | _callback.onClosed(*this); 247 | } 248 | } 249 | 250 | void Client::onWrite() 251 | { 252 | if (_uplink) 253 | _uplink->_uplink.resume(); 254 | } 255 | 256 | void Client::Uplink::onRead() 257 | { 258 | byte buffer[262144 + 1]; 259 | usize size; 260 | if (!_uplink.read(buffer, sizeof(buffer) - 1, size)) 261 | return; 262 | usize postponed; 263 | if (!_p._client.write(buffer, size, &postponed)) 264 | return; 265 | if (postponed) 266 | _uplink.suspend(); 267 | } 268 | 269 | void Client::Uplink::onWrite() 270 | { 271 | _p._client.resume(); 272 | } 273 | 274 | void Client::Uplink::onClosed() 275 | { 276 | _p._callback.onClosed(_p); 277 | } 278 | 279 | Server::Client::ICallback *Client::onConnected(Server::Client &client) 280 | { 281 | Console::printf("Connected to %s:%d\n", (const char*)_target, (int)_targetPort); 282 | if (_httpConnectMethod) 283 | { 284 | String response("HTTP/1.1 200 OK\r\n\r\n"); 285 | if (!_client.write((const byte*)(const char*)response, response.length())) 286 | return nullptr; 287 | } 288 | _uplink = new Uplink(*this, client); 289 | usize postponed = 0; 290 | if (!_receiveBuffer.isEmpty()) 291 | { 292 | if (!client.write(_receiveBuffer, _receiveBuffer.size(), &postponed)) 293 | return nullptr; 294 | _receiveBuffer.clear(); 295 | } 296 | if (!postponed) 297 | _client.resume(); 298 | return _uplink; 299 | } 300 | 301 | void Client::onAbolished() 302 | { 303 | _callback.onClosed(*this); 304 | } 305 | 306 | class Listener : public Server::Listener::ICallback, public Client::ICallback 307 | { 308 | public: 309 | Listener(Server& server) : _server(server) {} 310 | 311 | public: // Server::Listener::ICallback 312 | Server::Client::ICallback* onAccepted(Server::Client& client, uint32 ip, uint16 port) override; 313 | 314 | public: // Client::ICallback 315 | void onClosed(Client& client) override; 316 | 317 | private: 318 | Server& _server; 319 | PoolList _clients; 320 | }; 321 | 322 | Server::Client::ICallback* Listener::onAccepted(Server::Client& client, uint32 ip, uint16 port) 323 | { 324 | return &_clients.append(_server, client, *this); 325 | } 326 | 327 | void Listener::onClosed(Client& client) 328 | { 329 | _clients.remove(client); 330 | } 331 | 332 | int main(int argc, char* argv[]) 333 | { 334 | uint16 port = 3128; 335 | 336 | Server server; 337 | server.setReuseAddress(true); 338 | server.setKeepAlive(true); 339 | server.setNoDelay(true); 340 | 341 | Listener listener(server); 342 | 343 | if (!server.listen(Socket::anyAddress, port, listener)) 344 | return Log::errorf("Could not start proxy server on TCP port %hu: %s", (uint16)port, (const char*)Socket::getErrorString()), 1; 345 | Log::infof("Listening on TCP port %hu...", (uint16)port); 346 | 347 | server.run(); 348 | return 1; 349 | } 350 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /CDeploy: -------------------------------------------------------------------------------- 1 | 2 | function(deploy_package package version) 3 | 4 | include(CMakeParseArguments) 5 | 6 | set(options NO_OS NO_ARCH NO_COMPILER NO_CACHE) 7 | set(oneValueArgs) 8 | set(multiValueArgs) 9 | cmake_parse_arguments(_ "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) 10 | 11 | if(MSVC) 12 | foreach(config ${CMAKE_CONFIGURATION_TYPES}) 13 | if(NOT "${config}" STREQUAL "Debug") 14 | string(TOUPPER "${config}" config_upper) 15 | set(CMAKE_MAP_IMPORTED_CONFIG_${config_upper} Release) 16 | endif() 17 | endforeach() 18 | endif() 19 | 20 | if(NOT __NO_CACHE) 21 | find_package(${package} ${version} EXACT QUIET CONFIG NO_DEFAULT_PATH) 22 | endif() 23 | 24 | if(NOT ${package}_FOUND) 25 | 26 | string(TOLOWER "${package}" filename) 27 | set(filename "${filename}-${version}") 28 | if(NOT __NO_OS) 29 | set(filename "${filename}-${CDEPLOY_OS}") 30 | endif() 31 | if(NOT __NO_ARCH) 32 | set(filename "${filename}-${CDEPLOY_ARCH}") 33 | endif() 34 | if(NOT __NO_COMPILER) 35 | set(filename "${filename}-${CDEPLOY_COMPILER}") 36 | endif() 37 | set(filename "${filename}.zip") 38 | 39 | if(NOT CDEPLOY_CACHE_DIR) 40 | set(CDEPLOY_CACHE_DIR "$ENV{CDEPLOY_CACHE_DIR}") 41 | if(NOT CDEPLOY_CACHE_DIR) 42 | if(WIN32) 43 | set(CDEPLOY_CACHE_DIR "$ENV{USERPROFILE}/.cmake/downloadcache") 44 | else() 45 | set(CDEPLOY_CACHE_DIR "$ENV{HOME}/.cmake/downloadcache") 46 | endif() 47 | endif() 48 | endif() 49 | 50 | set(cache_file "${CDEPLOY_CACHE_DIR}/${filename}") 51 | if(NOT __NO_CACHE AND EXISTS "${cache_file}") 52 | message("-- Found ${filename} in cache") 53 | else() 54 | 55 | set(repository "${__UNPARSED_ARGUMENTS}") 56 | if(NOT repository) 57 | if(CDEPLOY_REPOSITORY) 58 | set(repository "${CDEPLOY_REPOSITORY}") 59 | else() 60 | set(repository "$ENV{CDEPLOY_REPOSITORY}") 61 | endif() 62 | endif() 63 | 64 | set(url "${repository}/${filename}") 65 | message("-- Downloading ${url}") 66 | file(DOWNLOAD "${url}" "${cache_file}.part" STATUS download_status) 67 | list(GET download_status 0 _download_result) 68 | if(NOT ${_download_result} EQUAL 0) 69 | list(GET download_status 1 _download_error) 70 | message(FATAL_ERROR "Could not download: ${_download_error} (${_download_result})") 71 | return() 72 | endif() 73 | file(RENAME "${cache_file}.part" "${cache_file}") 74 | endif() 75 | 76 | execute_process(COMMAND ${CMAKE_COMMAND} -E tar tf "${cache_file}" 77 | WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" 78 | OUTPUT_VARIABLE _unzip_output 79 | RESULT_VARIABLE _unzip_result) 80 | if(NOT ${_unzip_result} EQUAL 0) 81 | message(FATAL_ERROR "Could not extract file") 82 | return() 83 | endif() 84 | string(REGEX REPLACE "([^/]+).*" "\\1" _extract_dir "${_unzip_output}") 85 | 86 | execute_process(COMMAND ${CMAKE_COMMAND} -E tar xf "${cache_file}" 87 | WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" 88 | RESULT_VARIABLE _unzip_result) 89 | if(NOT ${_unzip_result} EQUAL 0) 90 | message(FATAL_ERROR "Could not extract file") 91 | return() 92 | endif() 93 | 94 | set(package_folder "${CMAKE_BINARY_DIR}/${_extract_dir}") 95 | 96 | find_package(${package} ${version} EXACT QUIET CONFIG REQUIRED 97 | PATHS "${package_folder}" NO_DEFAULT_PATH 98 | ) 99 | 100 | endif() 101 | endfunction() 102 | 103 | function(get_target_arch var) 104 | set(${var} ${CMAKE_SYSTEM_PROCESSOR}) 105 | if(WIN32) 106 | if(MSVC) 107 | if(CMAKE_CL_64) 108 | set(${var} x64) 109 | else() 110 | set(${var} x86) 111 | endif() 112 | elseif(CMAKE_COMPILER_IS_GNUCC) # CMAKE_CXX_COMPILER_ARCHITECTURE_ID does not provide anything with MinGW compilers 113 | execute_process(COMMAND "${CMAKE_CXX_COMPILER}" -v OUTPUT_VARIABLE GCC_VERSION_OUTPUT ERROR_VARIABLE GCC_VERSION_OUTPUT) 114 | if(GCC_VERSION_OUTPUT MATCHES ".*x86_64.*") 115 | set(${var} x64) 116 | else() 117 | set(${var} x86) 118 | endif() 119 | endif() 120 | endif() 121 | set(${var} ${${var}} PARENT_SCOPE) 122 | endfunction() 123 | 124 | function(get_target_compiler var) 125 | if(CMAKE_COMPILER_IS_GNUCC) 126 | string(REGEX REPLACE "([0-9]+\\.[0-9]+).*" "\\1" gcc_version "${CMAKE_CXX_COMPILER_VERSION}") 127 | if(NOT gcc_version VERSION_LESS "5.0") 128 | string(REGEX REPLACE "([0-9]+).*" "\\1" gcc_version "${gcc_version}") 129 | endif() 130 | set(${var} "gcc${gcc_version}") 131 | elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") 132 | string(REGEX REPLACE "([0-9]+).*" "clang\\1" ${var} "${CMAKE_CXX_COMPILER_VERSION}") 133 | elseif(MSVC) 134 | set(MSVC_YEARS 2008 2010 2012 2013 2015 2017 2019) 135 | set(MSVC_MSC_VERS 150 160 170 180 190 191 192) 136 | string(SUBSTRING "${MSVC_VERSION}" 0 3 MSVC_VER_SHORT) 137 | list(FIND MSVC_MSC_VERS ${MSVC_VER_SHORT} MSVC_INDEX) 138 | list(GET MSVC_YEARS ${MSVC_INDEX} MSVS_YEAR) 139 | set(${var} vs${MSVS_YEAR}) 140 | else() 141 | set(${var} ${CMAKE_CXX_COMPILER_ID}${CMAKE_CXX_COMPILER_VERSION}) 142 | endif() 143 | set(${var} ${${var}} PARENT_SCOPE) 144 | endfunction() 145 | 146 | function(get_target_os var) 147 | if(WIN32) 148 | set(${var} windows) 149 | else() 150 | file(GLOB ETC_RELEASE_FILES /etc/*-release) 151 | list(REMOVE_ITEM ETC_RELEASE_FILES /etc/lsb-release) 152 | list(GET ETC_RELEASE_FILES 0 ETC_RELEASE_FILE) 153 | file(READ "${ETC_RELEASE_FILE}" ETC_RELEASE_FILE_CONTENT) 154 | string(REGEX REPLACE "=|\n" ";" ETC_RELEASE_FILE_CONTENT "${ETC_RELEASE_FILE_CONTENT}") 155 | string(REGEX REPLACE "; +| +;" ";" ETC_RELEASE_FILE_CONTENT "${ETC_RELEASE_FILE_CONTENT}") 156 | list(FIND ETC_RELEASE_FILE_CONTENT "NAME" NAME_INDEX) 157 | if(NAME_INDEX GREATER -1) 158 | math(EXPR NAME_INDEX "${NAME_INDEX} + 1") 159 | list(GET ETC_RELEASE_FILE_CONTENT "${NAME_INDEX}" ETC_RELEASE_NAME) 160 | else() 161 | list(GET ETC_RELEASE_FILE_CONTENT 0 ETC_RELEASE_NAME) 162 | endif() 163 | string(REGEX MATCH "[^ \"]+" ETC_RELEASE_NAME "${ETC_RELEASE_NAME}") 164 | list(FIND ETC_RELEASE_FILE_CONTENT "VERSION_ID" VERSION_INDEX) 165 | if(NOT VERSION_INDEX GREATER -1) 166 | list(FIND ETC_RELEASE_FILE_CONTENT "VERSION" VERSION_INDEX) 167 | endif() 168 | if(VERSION_INDEX GREATER -1) 169 | math(EXPR VERSION_INDEX "${VERSION_INDEX} + 1") 170 | list(GET ETC_RELEASE_FILE_CONTENT "${VERSION_INDEX}" ETC_RELEASE_VERSION) 171 | string(REGEX MATCH "[^ \"]+" ETC_RELEASE_VERSION "${ETC_RELEASE_VERSION}") 172 | else() 173 | string(REGEX MATCH "[0-9]+" ETC_RELEASE_VERSION "${ETC_RELEASE_FILE_CONTENT}") 174 | endif() 175 | string(TOLOWER "${ETC_RELEASE_NAME}${ETC_RELEASE_VERSION}" ${var}) 176 | endif() 177 | set(${var} ${${var}} PARENT_SCOPE) 178 | endfunction() 179 | 180 | get_target_arch(CDEPLOY_ARCH) 181 | get_target_compiler(CDEPLOY_COMPILER) 182 | get_target_os(CDEPLOY_OS) 183 | 184 | set(CPACK_GENERATOR "ZIP") 185 | string(TOLOWER "${PROJECT_NAME}" CPACK_PACKAGE_FILE_NAME) 186 | set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${PROJECT_VERSION}") 187 | if(NOT CDEPLOY_NO_OS) 188 | set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CDEPLOY_OS}") 189 | endif() 190 | if(NOT CDEPLOY_NO_ARCH) 191 | set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CDEPLOY_ARCH}") 192 | endif() 193 | if(NOT CDEPLOY_NO_COMPILER) 194 | set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CDEPLOY_COMPILER}") 195 | endif() 196 | 197 | if(MSVC AND NOT CDEPLOY_NO_DEBUG_BUILD) 198 | 199 | set_property(GLOBAL PROPERTY USE_FOLDERS ON) 200 | set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER ".cmake") 201 | 202 | include(ExternalProject) 203 | 204 | ExternalProject_Add(DEBUG_BUILD 205 | SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}" 206 | BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/build-debug" 207 | CMAKE_ARGS "-DCMAKE_INSTALL_PREFIX=${CMAKE_CURRENT_BINARY_DIR}/install-debug" -DCDEPLOY_NO_DEBUG_BUILD=True 208 | BUILD_COMMAND ${CMAKE_COMMAND} --build "${CMAKE_CURRENT_BINARY_DIR}/build-debug" --config Debug 209 | INSTALL_COMMAND ${CMAKE_COMMAND} --build "${CMAKE_CURRENT_BINARY_DIR}/build-debug" --config Debug --target install 210 | ) 211 | file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/install-debug") 212 | install(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/install-debug/" DESTINATION . USE_SOURCE_PERMISSIONS) 213 | 214 | set_property(TARGET DEBUG_BUILD PROPERTY FOLDER ".cmake") 215 | if(NOT CDEPLOY_DEBUG_BUILD) 216 | set_property(TARGET DEBUG_BUILD PROPERTY EXCLUDE_FROM_DEFAULT_BUILD True) 217 | set_property(TARGET DEBUG_BUILD PROPERTY EXCLUDE_FROM_ALL True) 218 | endif() 219 | 220 | endif() 221 | if(CDEPLOY_DEBUG_BUILD) 222 | endif() 223 | 224 | if(MSVC) 225 | set(CMAKE_DEBUG_POSTFIX d) 226 | endif() 227 | 228 | file(REMOVE "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in") 229 | 230 | function(deploy_export_init) 231 | 232 | if(NOT EXISTS "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in") 233 | file(WRITE "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "@PACKAGE_INIT@\n\n") 234 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "set_and_check(INSTALL_DIR \"@PACKAGE_INSTALL_DIR@\")\n\n") 235 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "include(CMakeFindDependencyMacro)\n\n") 236 | endif() 237 | 238 | endfunction() 239 | 240 | function(deploy_export_dependency name) 241 | deploy_export_init() 242 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "find_dependency(${name} ${ARGN})\n\n") 243 | endfunction() 244 | 245 | function(deploy_export name) 246 | 247 | include(CMakeParseArguments) 248 | 249 | set(options INTERFACE LIBRARY STATIC SHARED EXECUTABLE) 250 | set(oneValueArgs CONFIGURATION IMPORTED_LOCATION IMPORTED_IMPLIB) 251 | set(multiValueArgs INTERFACE_INCLUDE_DIRECTORIES PROPERTIES) 252 | cmake_parse_arguments(_ "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) 253 | 254 | deploy_export_init() 255 | 256 | set(target_flags) 257 | if(__STATIC) 258 | set(target_flags "${target_flags} STATIC") 259 | endif() 260 | if(__SHARED) 261 | set(target_flags "${target_flags} SHARED") 262 | endif() 263 | if(__INTERFACE) 264 | set(target_flags "${target_flags} INTERFACE") 265 | endif() 266 | 267 | set(target_config) 268 | if(__CONFIGURATION) 269 | string(TOUPPER "${__CONFIGURATION}" __CONFIGURATION) 270 | set(target_config "_${__CONFIGURATION}") 271 | endif() 272 | 273 | set(target_properties) 274 | if(__IMPORTED_LOCATION) 275 | set(target_properties "${target_properties} IMPORTED_LOCATION${target_config} \"\${INSTALL_DIR}/${__IMPORTED_LOCATION}\"") 276 | endif() 277 | if(__IMPORTED_IMPLIB) 278 | set(target_properties "${target_properties} IMPORTED_IMPLIB${target_config} \"\${INSTALL_DIR}/${__IMPORTED_IMPLIB}\"") 279 | endif() 280 | if(__INTERFACE_INCLUDE_DIRECTORIES) 281 | set(target_properties "${target_properties} INTERFACE_INCLUDE_DIRECTORIES \"") 282 | foreach(dir ${__INTERFACE_INCLUDE_DIRECTORIES}) 283 | set(target_properties "${target_properties}\${INSTALL_DIR}/${dir};") 284 | endforeach() 285 | set(target_properties "${target_properties}\"") 286 | endif() 287 | if(__PROPERTIES) 288 | foreach(arg ${__PROPERTIES}) 289 | set(target_properties "${target_properties} ${arg}") 290 | endforeach() 291 | endif() 292 | 293 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "if(NOT TARGET ${PROJECT_NAME}::${name})\n") 294 | if(__LIBRARY OR __INTERFACE) 295 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" " add_library(${PROJECT_NAME}::${name} ${target_flags} IMPORTED GLOBAL)\n") 296 | else() 297 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" " add_executable(${PROJECT_NAME}::${name} IMPORTED GLOBAL)\n") 298 | endif() 299 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "endif()\n") 300 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "set_target_properties(${PROJECT_NAME}::${name}\n") 301 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" " PROPERTIES\n") 302 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" " ${target_properties}\n") 303 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" ")\n") 304 | if(__CONFIGURATION) 305 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "set_property(TARGET ${PROJECT_NAME}::${name} APPEND PROPERTY IMPORTED_CONFIGURATIONS ${__CONFIGURATION})\n") 306 | endif() 307 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "\n") 308 | 309 | endfunction() 310 | 311 | function(install_deploy_export) 312 | include(CMakePackageConfigHelpers) 313 | if(EXISTS "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in") 314 | set(INSTALL_DIR .) 315 | configure_package_config_file("${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "${PROJECT_NAME}Config.cmake" 316 | INSTALL_DESTINATION "lib/cmake/${PROJECT_NAME}" 317 | PATH_VARS 318 | INSTALL_DIR 319 | ) 320 | install(FILES "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake" DESTINATION "lib/cmake/${PROJECT_NAME}") 321 | else() 322 | install(EXPORT ${PROJECT_NAME}Config 323 | DESTINATION "lib/cmake/${PROJECT_NAME}" 324 | NAMESPACE ${PROJECT_NAME}:: 325 | ) 326 | endif() 327 | write_basic_package_version_file("${PROJECT_NAME}ConfigVersion.cmake" COMPATIBILITY ExactVersion) 328 | install(FILES "${CMAKE_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" DESTINATION "lib/cmake/${PROJECT_NAME}") 329 | endfunction() 330 | 331 | --------------------------------------------------------------------------------