├── .gitignore ├── etc ├── default │ └── gchsd ├── gchsd.conf └── init.d │ └── gchsd ├── .gitmodules ├── src ├── Address.hpp ├── Authentications.hpp ├── Settings.hpp ├── AskPass.cpp ├── NamedMutex.hpp ├── NamedMutex.cpp ├── CMakeLists.txt ├── Worker.hpp ├── Settings.cpp ├── Authentications.cpp ├── Main.cpp └── Worker.cpp ├── 3rdparty └── CMakeLists.txt ├── CMakeLists.txt ├── Jenkinsfile ├── README.md ├── LICENSE └── CDeploy /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /.vscode 3 | 4 | /build 5 | -------------------------------------------------------------------------------- /etc/default/gchsd: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /etc/gchsd.conf: -------------------------------------------------------------------------------- 1 | 2 | # The listen address of the HTTP server. 3 | # The default is: 4 | #listenAddr 0.0.0.0:80 5 | 6 | # The directory in which cached Git repositories are stored. 7 | # The default is: 8 | #cacheDir /tmp/gchsd 9 | -------------------------------------------------------------------------------- /src/Authentications.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include 5 | 6 | void storeAuth(const String& repo, const String& auth); 7 | void removeAuth(const String& repo, const String& auth); 8 | bool checkAuth(const String& repo, const String& auth); 9 | bool authRequired(const String& repo); 10 | -------------------------------------------------------------------------------- /src/Settings.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include 5 | 6 | #include "Address.hpp" 7 | 8 | struct Settings 9 | { 10 | String askpassPath; 11 | Address listenAddr; 12 | String cacheDir; 13 | 14 | Settings(); 15 | 16 | static void loadSettings(const String& file, Settings& settings); 17 | }; 18 | -------------------------------------------------------------------------------- /src/AskPass.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | 6 | int main(int argc, char* argv[]) 7 | { 8 | String arg1; 9 | if (argc > 1) 10 | arg1.attach(argv[1], String::length(argv[1])); 11 | if (arg1.startsWith("Username")) 12 | Console::print(Process::getEnvironmentVariable("GCHSD_USERNAME")); 13 | else if (arg1.startsWith("Password")) 14 | Console::print(Process::getEnvironmentVariable("GCHSD_PASSWORD")); 15 | else 16 | return 1; 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /src/NamedMutex.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | class NamedMutexGuard 8 | { 9 | public: 10 | NamedMutexGuard(const String& name); 11 | ~NamedMutexGuard(); 12 | 13 | private: 14 | struct NamedMutex 15 | { 16 | Mutex mutex; 17 | usize count; 18 | 19 | NamedMutex() : count(0) {} 20 | }; 21 | 22 | typedef PoolMap MutexMap; 23 | 24 | private: 25 | MutexMap::Iterator _object; 26 | 27 | private: 28 | static MutexMap _objects; 29 | }; 30 | -------------------------------------------------------------------------------- /src/NamedMutex.cpp: -------------------------------------------------------------------------------- 1 | #include "NamedMutex.hpp" 2 | 3 | namespace { 4 | Mutex _mutex; 5 | } 6 | 7 | NamedMutexGuard::MutexMap NamedMutexGuard::_objects; 8 | 9 | NamedMutexGuard::NamedMutexGuard(const String& name) 10 | { 11 | { 12 | Mutex::Guard guard(_mutex); 13 | _object = _objects.find(name); 14 | if (_object == _objects.end()) 15 | _object = _objects.insert(_objects.end(), name); 16 | ++_object->count; 17 | } 18 | _object->mutex.lock(); 19 | } 20 | 21 | NamedMutexGuard::~NamedMutexGuard() 22 | { 23 | _object->mutex.unlock(); 24 | { 25 | Mutex::Guard guard(_mutex); 26 | if (--_object->count == 0) 27 | _objects.remove(_object); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | set(sources 3 | Authentications.cpp 4 | Authentications.hpp 5 | Address.hpp 6 | Main.cpp 7 | NamedMutex.cpp 8 | NamedMutex.hpp 9 | Settings.cpp 10 | Settings.hpp 11 | Worker.cpp 12 | Worker.hpp 13 | ) 14 | 15 | add_executable(gchsd 16 | ${sources} 17 | ) 18 | 19 | target_link_libraries(gchsd PRIVATE 20 | libnstd::Socket 21 | ZLIB::ZLIB 22 | ) 23 | 24 | source_group("" FILES ${sources}) 25 | set_property(TARGET gchsd PROPERTY FOLDER "src") 26 | 27 | 28 | set(sources 29 | AskPass.cpp 30 | ) 31 | 32 | add_executable(gchsd-askpass 33 | ${sources} 34 | ) 35 | target_link_libraries(gchsd-askpass PRIVATE 36 | libnstd::Core 37 | ) 38 | 39 | source_group("" FILES ${sources}) 40 | set_property(TARGET gchsd-askpass PROPERTY FOLDER "src") 41 | 42 | 43 | 44 | install(TARGETS gchsd gchsd-askpass DESTINATION usr/sbin) 45 | 46 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/Worker.hpp: -------------------------------------------------------------------------------- 1 | 2 | #pragma once 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "Settings.hpp" 10 | 11 | class Worker 12 | { 13 | public: 14 | class ICallback 15 | { 16 | public: 17 | virtual void onFinished() = 0; 18 | }; 19 | 20 | public: 21 | Worker(const Settings& settings, Socket& client, ICallback& callback); 22 | bool join(); 23 | 24 | private: 25 | const Settings& _settings; 26 | ICallback& _callback; 27 | Socket _client; 28 | Thread _thread; 29 | 30 | Mutex _mutex; 31 | bool _finished; 32 | 33 | private: 34 | uint main(); 35 | void handleRequest(); 36 | void handleGetRequest(const String& repoUrl, const String& repo, const String& auth); 37 | void handlePostRequest(const String& repo, const String& auth, Buffer& body); 38 | }; 39 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | 2 | cmake_minimum_required(VERSION 3.1) 3 | cmake_policy(SET CMP0048 NEW) 4 | 5 | project(gchsd VERSION 0.3.3) 6 | 7 | find_package(ZLIB REQUIRED) 8 | 9 | set(CDEPLOY_NO_DEBUG_BUILD True) 10 | set(CDEPLOY_NO_COMPILER True) 11 | 12 | include(CDeploy) 13 | 14 | add_subdirectory(3rdparty) 15 | add_subdirectory(src) 16 | 17 | set(CPACK_GENERATOR "DEB") 18 | set(CPACK_PACKAGE_CONTACT "Colin Graf ") 19 | set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}") 20 | set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "A mirroring Git HTTP server daemon") 21 | set(CPACK_PACKAGING_INSTALL_PREFIX "/") 22 | #set(CPACK_DEBIAN_FILE_NAME "DEB-DEFAULT") 23 | set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://github.com/craflin/git-cache-http-server") 24 | set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6 (>= 2.15), git, sudo") 25 | set(CPACK_DEBIAN_PACKAGE_SECTION "net") 26 | 27 | include(CPack) 28 | 29 | install(FILES etc/gchsd.conf DESTINATION etc) 30 | install(FILES etc/default/gchsd DESTINATION etc/default) 31 | install(PROGRAMS etc/init.d/gchsd DESTINATION etc/init.d) 32 | -------------------------------------------------------------------------------- /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' 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 | archiveArtifacts artifacts: 'build/*.deb' 21 | } 22 | } 23 | } 24 | } 25 | } 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /etc/init.d/gchsd: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | ### BEGIN INIT INFO 4 | # Provides: gchsd 5 | # Required-Start: $network 6 | # Required-Stop: $network 7 | # Default-Start: 2 3 4 5 8 | # Default-Stop: 0 1 6 9 | # Short-Description: A mirroring Git HTTP server daemon 10 | # Description: The daemon caches the original repository and updates the cache as needed. 11 | ### END INIT INFO 12 | # 13 | # DAEMON Location of the binary 14 | # 15 | 16 | PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin 17 | DAEMON=/usr/sbin/gchsd 18 | NAME=gchsd 19 | DESC="A mirroring Git HTTP server daemon" 20 | DAEMON_OPTS= 21 | 22 | test -x $DAEMON || exit 0 23 | 24 | # Include custom values if available 25 | if [ -f /etc/default/gchsd ] ; then 26 | . /etc/default/gchsd 27 | fi 28 | 29 | DAEMON_OPTS="-b $DAEMON_OPTS" 30 | 31 | start() { 32 | echo -n "Starting $DESC: " 33 | 34 | sudo -i -- exec $DAEMON $DAEMON_OPTS 35 | if [ $? -eq 0 ]; then 36 | echo "$NAME." 37 | else 38 | echo "failed!" 39 | fi 40 | } 41 | 42 | stop() { 43 | echo -n "Stopping $DESC: " 44 | kill $(pidof $DAEMON) 45 | if [ $? -eq 0 ]; then 46 | echo "$NAME." 47 | else 48 | echo "failed!" 49 | fi 50 | } 51 | 52 | case "$1" in 53 | start) 54 | start 55 | ;; 56 | stop) 57 | stop 58 | ;; 59 | restart|reload|force-reload) 60 | stop 61 | start 62 | ;; 63 | *) 64 | echo "Usage: $0 {start|stop|restart|reload|force-reload}" >&2 65 | exit 2 66 | ;; 67 | esac 68 | 69 | exit 0 70 | -------------------------------------------------------------------------------- /src/Settings.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "Settings.hpp" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | Settings::Settings() 11 | : askpassPath(File::getDirectoryName(Process::getExecutablePath()) + "/gchsd-askpass") 12 | , listenAddr{Socket::anyAddress, 80} 13 | , cacheDir(Directory::getTempDirectory() + "/gchsd") 14 | { 15 | ; 16 | } 17 | 18 | void Settings::loadSettings(const String& file, Settings& settings) 19 | { 20 | String conf; 21 | if (!File::readAll(file, conf)) 22 | return; 23 | List lines; 24 | conf.split(lines, "\n\r"); 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 == "cacheDir") 41 | settings.cacheDir = value; 42 | else if (option == "listenAddr") 43 | settings.listenAddr.addr = Socket::inetAddr(value, &settings.listenAddr.port); 44 | else 45 | Log::warningf("Unknown option: %s", (const char*)option); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Authentications.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "Authentications.hpp" 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | namespace { 9 | typedef HashMap AuthMap; 10 | 11 | Mutex _mutex; 12 | AuthMap _authentications; 13 | 14 | String getKey(const String& repo, const String& auth) 15 | { 16 | return repo + " " + auth; 17 | } 18 | 19 | void _cleanup(int64 now) 20 | { 21 | while (!_authentications.isEmpty()) 22 | { 23 | if (now - _authentications.front() < 60 * 60 * 1000) // 1 hour 24 | break; 25 | _authentications.removeFront(); 26 | } 27 | } 28 | } 29 | 30 | void storeAuth(const String& repo, const String& auth) 31 | { 32 | String key = getKey(repo, auth); 33 | int64 now = Time::time(); 34 | { 35 | Mutex::Guard guard(_mutex); 36 | _cleanup(now); 37 | _authentications.remove(key); 38 | _authentications.append(key, now); 39 | } 40 | } 41 | 42 | void removeAuth(const String& repo, const String& auth) 43 | { 44 | String key = getKey(repo, auth); 45 | { 46 | Mutex::Guard guard(_mutex); 47 | _authentications.remove(key); 48 | } 49 | } 50 | 51 | bool checkAuth(const String& repo, const String& auth) 52 | { 53 | String key = getKey(repo, auth); 54 | int64 now = Time::time(); 55 | { 56 | Mutex::Guard guard(_mutex); 57 | _cleanup(now); 58 | return _authentications.contains(key); 59 | } 60 | } 61 | 62 | bool authRequired(const String& repo) 63 | { 64 | int64 now = Time::time(); 65 | String key = getKey(repo, String()); 66 | { 67 | Mutex::Guard guard(_mutex); 68 | _cleanup(now); 69 | if (_authentications.contains(key)) 70 | return false; 71 | for (AuthMap::Iterator i = _authentications.begin(), end = _authentications.end(); i != end; ++i) 72 | if (i.key().startsWith(key)) 73 | return true; 74 | return false; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # gchsd - Git Cache HTTP Server Daemon 3 | 4 | [![Build Status](http://xaws6t1emwa2m5pr.myfritz.net:8080/buildStatus/icon?job=craflin%2Fgit-cache-http-server%2Fmaster)](http://xaws6t1emwa2m5pr.myfritz.net:8080/job/craflin/job/git-cache-http-server/job/master/) 5 | 6 | A daemon to mirror remote Git repositories and serve them over HTTP, automatically updating the mirror as needed. 7 | 8 | It was developed to be used in CI environments to improve the performance of Git clone and fetch operations. 9 | 10 | The project is a C++ clone of jonasmalacofilho's [git-cache-http-server](https://github.com/jonasmalacofilho/git-cache-http-server). 11 | However, there are these differences and improvements: 12 | * The repository cache is updated sequentially and for each git fetch or clone operation to avoid race conditions when the remote is updated while some request is updating the cache. 13 | * The authentication works by fetching or cloning the remote instead of testing if the remote is accessible using the credentials. 14 | * It can easily be configured to run as a systemd daemon. 15 | 16 | ## Build Instructions 17 | 18 | (It was developed on and for Debian-based platforms, it can probably also be compiled on other platforms, but don't ask me how.) 19 | 20 | * Clone the Git repository and initialize submodules. `git clone https://github.com/craflin/git-cache-http-server.git && cd git-cache-http-server && git submodule update --init` 21 | * Install zlib1g-dev. `sudo apt-get install zlib1g-dev` 22 | * Build the project with CMake. `mkdir build && cd build && cmake .. && cmake --build .` 23 | * You can build a *deb* package using the *package* target in CMake. `cmake --build . --target package` 24 | 25 | ## Server Setup 26 | 27 | * Install *git*. `sudo apt-get install git` 28 | * Install *gchsd* from the *deb* package. `wget https://github.com/craflin/git-cache-http-server/releases/download//gchsd--.deb && sudo dpkg -i ./gchsd--.deb` 29 | * If needed, configure a cache directory (default is */tmp/gchsd*) and listen port (default is *80*) in */etc/gchsd.conf*. 30 | * Start the *gchsd* daemon with `sudo systemctl daemon-reload && sudo systemctl start gchsd`. 31 | * You can use `sudo systemctl enable gchsd` to let the system automatically start the daemon after a restart. 32 | 33 | ## Client Setup 34 | 35 | * Run `git config --global url."http://[:]/https://".insteadOf https://` to use the mirror instead of the original source. 36 | -------------------------------------------------------------------------------- /src/Main.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "Settings.hpp" 9 | #include "Worker.hpp" 10 | 11 | class Main 12 | : private Worker::ICallback 13 | { 14 | public: 15 | Main(const Settings& settings) 16 | : _settings(settings) 17 | { 18 | ; 19 | } 20 | 21 | bool start() 22 | { 23 | if (!_serverSocket.open() || 24 | !_serverSocket.setReuseAddress() || 25 | !_serverSocket.setNonBlocking() || 26 | !_serverSocket.bind(_settings.listenAddr.addr, _settings.listenAddr.port) || 27 | !_serverSocket.listen()) 28 | return false; 29 | _poll.set(_serverSocket, Socket::Poll::acceptFlag); 30 | return true; 31 | } 32 | 33 | void run() 34 | { 35 | for (Socket::Poll::Event event; _poll.poll(event, 1000 * 1000);) 36 | if (event.socket == &_serverSocket) 37 | { 38 | uint32 ip; 39 | uint16 port; 40 | Socket client; 41 | if (_serverSocket.accept(client, ip, port)) 42 | _workers.append(_settings, client, *this); 43 | } 44 | else 45 | { 46 | for(PoolList::Iterator i = _workers.begin(), next; i != _workers.end(); i = next) 47 | { 48 | next = i; 49 | ++next; 50 | if (i->join()) 51 | _workers.remove(i); 52 | } 53 | } 54 | } 55 | 56 | private: 57 | const Settings& _settings; 58 | Socket _serverSocket; 59 | Socket::Poll _poll; 60 | PoolList _workers; 61 | 62 | private: 63 | void onFinished() override { _poll.interrupt(); } 64 | }; 65 | 66 | int main(int argc, char* argv[]) 67 | { 68 | String logFile; 69 | String configFile("/etc/gchsd.conf"); 70 | 71 | // parse parameters 72 | { 73 | Process::Option options[] = { 74 | { 'b', "daemon", Process::argumentFlag | Process::optionalFlag }, 75 | { 'c', "config", Process::argumentFlag }, 76 | { 'h', "help", Process::optionFlag }, 77 | }; 78 | Process::Arguments arguments(argc, argv, options); 79 | int character; 80 | String argument; 81 | while (arguments.read(character, argument)) 82 | switch (character) 83 | { 84 | case 'b': 85 | logFile = argument.isEmpty() ? String("/dev/null") : argument; 86 | break; 87 | case 'c': 88 | configFile = argument; 89 | break; 90 | case '?': 91 | Console::errorf("Unknown option: %s.\n", (const char*)argument); 92 | return -1; 93 | case ':': 94 | Console::errorf("Option %s required an argument.\n", (const char*)argument); 95 | return -1; 96 | default: 97 | Console::errorf("Usage: %s [-b] [-c ]\n\ 98 | \n\ 99 | -b, --daemon[=]\n\ 100 | Detach from calling shell and write output to .\n\ 101 | \n\ 102 | -c , --config[=]\n\ 103 | Load configuration from . (Default is /etc/gchsd.conf)\n\ 104 | \n", 105 | argv[0]); 106 | return -1; 107 | } 108 | } 109 | 110 | Log::setLevel(Log::debug); 111 | 112 | // load settings 113 | Settings settings; 114 | Settings::loadSettings(configFile, settings); 115 | 116 | // daemonize process 117 | #ifndef _WIN32 118 | if (!logFile.isEmpty()) 119 | { 120 | Log::infof("Starting as daemon..."); 121 | if (!Process::daemonize(logFile)) 122 | { 123 | Log::errorf("Could not daemonize process: %s", (const char*)Error::getErrorString()); 124 | return -1; 125 | } 126 | Log::setDevice(Log::syslog); 127 | Log::setLevel(Log::info); 128 | } 129 | #endif 130 | 131 | // start the server 132 | Main main(settings); 133 | if (!main.start()) 134 | return Log::errorf("Could not listen on TCP port %s:%hu: %s", (const char*)Socket::inetNtoA(settings.listenAddr.addr), (uint16)settings.listenAddr.port, (const char*)Socket::getErrorString()), 1; 135 | Log::infof("Listening on TCP port %hu...", (uint16)settings.listenAddr.port); 136 | 137 | // run the server 138 | main.run(); 139 | return 1; 140 | } 141 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/Worker.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "Worker.hpp" 3 | #include "NamedMutex.hpp" 4 | #include "Authentications.hpp" 5 | 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | #include 13 | 14 | namespace { 15 | 16 | Buffer gunzip(const Buffer& input) 17 | { 18 | Buffer result; 19 | const int blockSize = 0xffff; 20 | z_stream stream = { 0 }; 21 | if (inflateInit2(&stream, 16 | MAX_WBITS) != Z_OK) 22 | return Buffer(); 23 | stream.avail_in = input.size(); 24 | stream.next_in = (z_const Bytef *)(const byte*)input; 25 | result.reserve(blockSize); 26 | stream.avail_out = blockSize; 27 | stream.next_out = (byte*)result; 28 | for (;;) 29 | { 30 | int n = inflate(&stream, Z_NO_FLUSH); 31 | switch (n) 32 | { 33 | case Z_OK: 34 | result.resize(stream.total_out); 35 | result.reserve(result.size() + blockSize); 36 | stream.avail_out = blockSize; 37 | stream.next_out = (byte*)result + result.size(); 38 | break; 39 | case Z_STREAM_END: 40 | result.resize(stream.total_out); 41 | return result; 42 | default: 43 | return Buffer(); 44 | } 45 | } 46 | return result; 47 | } 48 | 49 | } 50 | 51 | Worker::Worker(const Settings& settings, Socket& client, ICallback& callback) 52 | : _settings(settings) 53 | , _callback(callback) 54 | , _finished(false) 55 | { 56 | _client.swap(client); 57 | _thread.start(*this, &Worker::main); 58 | } 59 | 60 | bool Worker::join() 61 | { 62 | { 63 | Mutex::Guard guard(_mutex); 64 | if (!_finished) 65 | return false; 66 | } 67 | _thread.join(); 68 | return true; 69 | } 70 | 71 | 72 | uint Worker::main() 73 | { 74 | handleRequest(); 75 | { 76 | Mutex::Guard guard(_mutex); 77 | _finished = true; 78 | } 79 | _callback.onFinished(); 80 | return 0; 81 | } 82 | 83 | namespace { 84 | 85 | bool readHttpRequest(Socket& client, String& header, Buffer& body) 86 | { 87 | byte buffer[1024]; 88 | usize size = 0; 89 | for (;;) 90 | { 91 | ssize i = client.recv(buffer + size, sizeof(buffer) - 1 - size); 92 | if (i <= 0) 93 | return false; 94 | size += i; 95 | buffer[i] = '\0'; 96 | const char* headerEnd = String::find((const char*)buffer, "\r\n\r\n"); 97 | if (headerEnd) 98 | { 99 | header = String((const char*)buffer, headerEnd - (const char*)buffer); 100 | const char* contentLengthAttr = header.find("\r\nContent-Length: "); 101 | if (contentLengthAttr) 102 | { 103 | contentLengthAttr += 18; 104 | const char* lineEnd = String::find(contentLengthAttr, "\r\n"); 105 | if (!lineEnd) 106 | lineEnd = (const char*)header + header.length(); 107 | String contentLengthStr = header.substr(contentLengthAttr - (const char*)header, lineEnd - contentLengthAttr); 108 | uint64 contentLength = contentLengthStr.toUInt64(); 109 | body.clear(); 110 | body.reserve(contentLength); 111 | body.append((const byte*)headerEnd + 4, size - (headerEnd + 4 - (const char*)buffer)); 112 | byte* buf = (byte*)body; 113 | while (body.size() < contentLength) 114 | { 115 | ssize i = client.recv(buf + body.size(), contentLength - body.size()); 116 | if (i <= 0) 117 | return false; 118 | body.resize(body.size() + i); 119 | } 120 | } 121 | return true; 122 | } 123 | if (size == sizeof(buffer) - 1) 124 | return false; 125 | } 126 | } 127 | 128 | bool parseHeader(const String& header, String& method, String& path) 129 | { 130 | const char* n = header.find("\r\n"); 131 | if (!n) 132 | return false; 133 | String firstLine = header.substr(0, n - (const char*)header); 134 | List tokens; 135 | firstLine.split(tokens, " "); 136 | if (tokens.size() < 2) 137 | return false; 138 | method = tokens.front(); 139 | path = *(++tokens.begin()); 140 | return true; 141 | } 142 | 143 | String getRequestUrl(const String& path) 144 | { 145 | String result = path.startsWith("/") ? path.substr(1) : path; 146 | if (result.startsWith("https://") || result.startsWith("http://")) 147 | return result; 148 | if (result.startsWith("https:/")) 149 | return String("https://") + result.substr(7); 150 | if (result.startsWith("http:/")) 151 | return String("http://") + result.substr(6); 152 | result.prepend("http://"); 153 | return result; 154 | } 155 | 156 | bool parseGetRequestPath(const String& path, String& repoUrl, String& repo, String& service) 157 | { 158 | String url = getRequestUrl(path); 159 | const char* x = url.find("/info/refs?service="); 160 | if (!x) 161 | return false; 162 | usize split = x - (const char*)url; 163 | repoUrl = url.substr(0, split); 164 | service = url.substr(split + 19); 165 | bool https = url.startsWith("https://"); 166 | usize serverStart = https ? 8 : 7; 167 | repo = url.substr(serverStart, split - serverStart); 168 | return true; 169 | } 170 | 171 | 172 | bool parsePostRequestPath(const String& path, String& repoUrl, String& repo, String& service) 173 | { 174 | String url = getRequestUrl(path); 175 | if (!url.endsWith("/git-upload-pack")) 176 | return false; 177 | repoUrl = url.substr(0, url.length() - 16); 178 | service = url.substr(repoUrl.length() + 1); 179 | bool https = url.startsWith("https://"); 180 | usize serverStart = https ? 8 : 7; 181 | repo = url.substr(serverStart, repoUrl.length() - serverStart); 182 | return true; 183 | } 184 | 185 | bool getAuth(const String& header, String& auth) 186 | { 187 | const char* authStart = header.find("\r\nAuthorization: "); 188 | if (!authStart) 189 | return false; 190 | authStart += 17; 191 | const char* authEnd = String::find(authStart, "\r\n"); 192 | if (!authEnd) 193 | return false; 194 | auth = header.substr(authStart - (const char*)header, authEnd - authStart); 195 | return true; 196 | } 197 | 198 | void requestAuth(Socket& client) 199 | { 200 | String response = "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"\"\r\n\r\n"; 201 | client.send((const byte*)(const char*)response, response.length()); 202 | } 203 | 204 | void respondError(Socket& client) 205 | { 206 | 207 | String response = "HTTP/1.1 500 Internal Server Error\r\n\r\n"; 208 | client.send((const byte*)(const char*)response, response.length()); 209 | } 210 | 211 | } 212 | 213 | void Worker::handleRequest() 214 | { 215 | String header; 216 | Buffer body; 217 | if (!readHttpRequest(_client, header, body)) 218 | return; 219 | String method; 220 | String path; 221 | if (!parseHeader(header, method, path)) 222 | return; 223 | 224 | Log::infof("%s %s", (const char*)method, (const char*)path); 225 | 226 | String repoUrl; 227 | String repo; 228 | String service; 229 | if (method == "GET") 230 | { 231 | if (!parseGetRequestPath(path, repoUrl, repo, service)) 232 | return; 233 | } 234 | else if (method == "POST") 235 | { 236 | if (!parsePostRequestPath(path, repoUrl, repo, service)) 237 | return; 238 | } 239 | else 240 | return; 241 | 242 | if (service != "git-upload-pack") 243 | return; 244 | 245 | String auth; 246 | getAuth(header, auth); 247 | if (auth.isEmpty() && authRequired(repo)) 248 | { 249 | requestAuth(_client); 250 | return; 251 | } 252 | 253 | if (method == "GET") 254 | handleGetRequest(repoUrl, repo, auth); 255 | else if (method == "POST") 256 | { 257 | if (header.find("\r\nContent-Encoding: gzip\r\n")) 258 | body = gunzip(body); 259 | handlePostRequest(repo, auth, body); 260 | } 261 | } 262 | 263 | namespace { 264 | void decodeAuth(const String& auth, String& username, String& password) 265 | { 266 | if (!auth.startsWith("Basic ")) 267 | return; 268 | String base64auth; 269 | base64auth.attach((const char*)auth + 6, auth.length() - 6); 270 | String authDecoded = String::fromBase64(base64auth); 271 | const char* userNameEnd = authDecoded.find(':'); 272 | if (userNameEnd) 273 | { 274 | username = authDecoded.substr(0, userNameEnd - (const char*)authDecoded); 275 | password = authDecoded.substr(username.length() + 1); 276 | } 277 | else 278 | username = authDecoded; 279 | } 280 | 281 | String readAllStdError(Process& process) 282 | { 283 | String result; 284 | char buf[1024]; 285 | for (;;) 286 | { 287 | uint streams = Process::stderrStream; 288 | ssize n = process.read(buf, sizeof(buf) -1, streams); 289 | if (n <= 0) 290 | return result; 291 | buf[n] = '\0'; 292 | result.append(buf); 293 | } 294 | } 295 | 296 | enum class UpdateResult 297 | { 298 | Success, 299 | AuthFailure, 300 | Error, 301 | }; 302 | 303 | UpdateResult updateRepository(const String& repoUrl, const String& askpassPath, const String& cacheDir, const String& auth) 304 | { 305 | String username; 306 | String password; 307 | if (!auth.isEmpty()) 308 | decodeAuth(auth, username, password); 309 | 310 | Map envs = Process::getEnvironmentVariables(); 311 | envs.insert("GIT_ASKPASS", askpassPath); 312 | envs.insert("GCHSD_USERNAME", username); 313 | envs.insert("GCHSD_PASSWORD", password); 314 | 315 | { 316 | NamedMutexGuard guard(cacheDir); 317 | 318 | String command = String("git -C \"") + cacheDir + "\" fetch --quiet --prune --prune-tags"; 319 | Log::infof("%s", (const char*)command); 320 | Process process; 321 | uint32 pid = process.open(command, Process::stderrStream, envs); 322 | if (!pid) 323 | { 324 | Log::errorf("Could not launch command '%s': %s", (const char*)command, (const char*)Error::getErrorString()); 325 | return UpdateResult::Error; 326 | } 327 | String stderr = readAllStdError(process); 328 | uint32 exitCode = 1; 329 | process.join(exitCode); 330 | if (exitCode != 0) 331 | { 332 | if (stderr.find(" Authentication failed ")) 333 | return UpdateResult::AuthFailure; 334 | 335 | command = String("git clone --quiet --mirror \"") + repoUrl + "\" \"" + cacheDir + "\""; 336 | Log::infof("%s", (const char*)command); 337 | uint32 pid = process.open(command, Process::stderrStream, envs); 338 | if (!pid) 339 | { 340 | Log::errorf("Could not launch command '%s': %s", (const char*)command, (const char*)Error::getErrorString()); 341 | return UpdateResult::Error; 342 | } 343 | stderr = readAllStdError(process); 344 | process.join(exitCode); 345 | if (exitCode != 0) 346 | { 347 | if (stderr.find(" Authentication failed ")) 348 | return UpdateResult::AuthFailure; 349 | stderr.trim(); 350 | Log::errorf("Clone failed: %s", (const char*)stderr); 351 | return UpdateResult::Error; 352 | } 353 | } 354 | } 355 | return UpdateResult::Success; 356 | } 357 | 358 | } 359 | 360 | void Worker::handleGetRequest(const String& repoUrl, const String& repo, const String& auth) 361 | { 362 | // create cache dir 363 | String cacheDir = _settings.cacheDir + "/" + repo; 364 | if (!Directory::create(cacheDir)) 365 | return Log::errorf("Could not create directory '%s': %s", (const char*)cacheDir, (const char*)Error::getErrorString()); 366 | 367 | // update cache 368 | switch (updateRepository(repoUrl, _settings.askpassPath, cacheDir, auth)) 369 | { 370 | case UpdateResult::AuthFailure: 371 | removeAuth(repo, auth); 372 | requestAuth(_client); 373 | return; 374 | case UpdateResult::Error: 375 | if (checkAuth(repo, auth)) 376 | break; // Git fetch failed, but the cache might be up-to-date. So, let's try to continue... 377 | respondError(_client); 378 | return; 379 | case UpdateResult::Success: 380 | storeAuth(repo, auth); 381 | break; 382 | } 383 | 384 | // info response 385 | { 386 | NamedMutexGuard guard(cacheDir); 387 | 388 | String command = String("git-upload-pack --stateless-rpc --advertise-refs \"") + cacheDir + "\""; 389 | Log::infof("%s", (const char*)command); 390 | Process process; 391 | uint32 pid = process.open(command); 392 | if (!pid) 393 | return Log::errorf("Could not launch command '%s': %s", (const char*)command, (const char*)Error::getErrorString()); 394 | 395 | String response = "HTTP/1.1 200 OK\r\n"; 396 | response.append("Content-Type: application/x-git-upload-pack-advertisement\r\n"); 397 | response.append("Cache-Control: no-cache\r\n\r\n"); 398 | response.append("001e# service=git-upload-pack\n0000"); 399 | if (_client.send((const byte*)(const char*)response, response.length()) != response.length()) 400 | return; 401 | 402 | byte buf[0xffff]; 403 | ssize len; 404 | for (;;) 405 | { 406 | len = process.read(buf, sizeof(buf)); 407 | if (len < 0) 408 | return; 409 | if (len == 0) 410 | break; 411 | if (_client.send(buf, len) != len) 412 | { 413 | process.terminate(); 414 | while (process.read(buf, sizeof(buf)) > 0); 415 | return; 416 | } 417 | } 418 | } 419 | } 420 | 421 | void Worker::handlePostRequest(const String& repo, const String& auth, Buffer& body) 422 | { 423 | if (!checkAuth(repo, auth)) 424 | { 425 | requestAuth(_client); 426 | return; 427 | } 428 | 429 | String cacheDir = _settings.cacheDir + "/" + repo; 430 | 431 | { 432 | NamedMutexGuard guard(cacheDir); 433 | 434 | String command = String("git-upload-pack --stateless-rpc \"") + cacheDir + "\""; 435 | Log::infof("%s", (const char*)command); 436 | Process process; 437 | uint32 pid = process.open(command, Process::stdoutStream | Process::stdinStream); 438 | if (!pid) 439 | return Log::errorf("Could not launch command '%s': %s", (const char*)command, (const char*)Error::getErrorString()); 440 | 441 | if (process.write((const byte*)body, body.size()) != body.size()) 442 | return; 443 | process.close(Process::stdinStream); 444 | 445 | String response = "HTTP/1.1 200 OK\r\n"; 446 | response.append("Content-Type: application/x-git-upload-pack-result\r\n"); 447 | response.append("Cache-Control: no-cache\r\n\r\n"); 448 | if (_client.send((const byte*)(const char*)response, response.length()) != response.length()) 449 | return; 450 | 451 | byte buf[0xffff]; 452 | ssize len; 453 | for (;;) 454 | { 455 | len = process.read(buf, sizeof(buf)); 456 | if (len < 0) 457 | return; 458 | if (len == 0) 459 | break; 460 | if (_client.send(buf, len) != len) 461 | { 462 | process.terminate(); 463 | while (process.read(buf, sizeof(buf)) > 0); 464 | return; 465 | } 466 | } 467 | } 468 | } 469 | -------------------------------------------------------------------------------- /CDeploy: -------------------------------------------------------------------------------- 1 | 2 | macro(deploy_package package version) 3 | 4 | include(CMakeParseArguments) 5 | 6 | cmake_parse_arguments(_deploy_package "NO_OS;NO_ARCH;NO_COMPILER;NO_CACHE;NO_CONFIG_MAPPING" "" "COMPONENTS" ${ARGN}) 7 | 8 | if(MSVC) 9 | if(_deploy_package_NO_CONFIG_MAPPING) 10 | foreach(_deploy_package_config ${CMAKE_CONFIGURATION_TYPES}) 11 | if(NOT "${_deploy_package_config}" STREQUAL "Debug") 12 | string(TOUPPER "${_deploy_package_config}" _deploy_package_config) 13 | unset(CMAKE_MAP_IMPORTED_CONFIG_${_deploy_package_config}) 14 | endif() 15 | endforeach() 16 | else() 17 | foreach(_deploy_package_config ${CMAKE_CONFIGURATION_TYPES}) 18 | if(NOT "${_deploy_package_config}" STREQUAL "Debug") 19 | string(TOUPPER "${_deploy_package_config}" _deploy_package_config) 20 | set(CMAKE_MAP_IMPORTED_CONFIG_${_deploy_package_config} Release) 21 | endif() 22 | endforeach() 23 | endif() 24 | endif() 25 | 26 | set(_deploy_package_find_package_args) 27 | if(_deploy_package_COMPONENTS) 28 | list(APPEND _deploy_package_find_package_args COMPONENTS ${_deploy_package_COMPONENTS}) 29 | endif() 30 | 31 | if("${version}" MATCHES "[^\\-]+-.+") 32 | string(REGEX REPLACE "([^\\-]+)-.+" "\\1" _deploy_package_find_version "${version}") 33 | else() 34 | set(_deploy_package_find_version "${version}") 35 | endif() 36 | 37 | if(NOT _deploy_package_NO_CACHE) 38 | find_package(${package} ${_deploy_package_find_version} EXACT QUIET CONFIG ${_deploy_package_find_package_args} NO_DEFAULT_PATH) 39 | endif() 40 | 41 | if(NOT ${package}_FOUND) 42 | 43 | function(_deploy_package_download) 44 | 45 | foreach(component ${_deploy_package_COMPONENTS}) 46 | set(${package}${component}_DIR "${package}${component}_DIR-NOTFOUND" PARENT_SCOPE) 47 | endforeach() 48 | 49 | string(TOLOWER "${package}" filename) 50 | set(filename "${filename}-${version}") 51 | if(NOT _deploy_package_NO_OS) 52 | set(filename "${filename}-${CDEPLOY_OS}") 53 | endif() 54 | if(NOT _deploy_package_NO_ARCH) 55 | set(filename "${filename}-${CDEPLOY_ARCH}") 56 | endif() 57 | if(NOT _deploy_package_NO_COMPILER) 58 | set(filename "${filename}-${CDEPLOY_COMPILER}") 59 | endif() 60 | set(filename "${filename}.zip") 61 | 62 | if(NOT CDEPLOY_CACHE_DIR) 63 | set(CDEPLOY_CACHE_DIR "$ENV{CDEPLOY_CACHE_DIR}") 64 | if(NOT CDEPLOY_CACHE_DIR) 65 | if(WIN32) 66 | set(CDEPLOY_CACHE_DIR "$ENV{USERPROFILE}/.cmake/downloadcache") 67 | else() 68 | set(CDEPLOY_CACHE_DIR "$ENV{HOME}") 69 | if(NOT CDEPLOY_CACHE_DIR OR "${CDEPLOY_CACHE_DIR}" STREQUAL "/") 70 | set(CDEPLOY_CACHE_DIR "/tmp") 71 | else() 72 | set(CDEPLOY_CACHE_DIR "${CDEPLOY_CACHE_DIR}/.cmake/downloadcache") 73 | endif() 74 | endif() 75 | endif() 76 | endif() 77 | 78 | set(cache_file "${CDEPLOY_CACHE_DIR}/${filename}") 79 | if(NOT _deploy_package_NO_CACHE AND EXISTS "${cache_file}") 80 | message("-- Found ${filename} in cache") 81 | else() 82 | 83 | set(repository "${_deploy_package_UNPARSED_ARGUMENTS}") 84 | if(NOT repository) 85 | if(CDEPLOY_REPOSITORY) 86 | set(repository "${CDEPLOY_REPOSITORY}") 87 | else() 88 | set(repository "$ENV{CDEPLOY_REPOSITORY}") 89 | endif() 90 | endif() 91 | 92 | set(url "${repository}/${filename}") 93 | message("-- Downloading ${url}") 94 | file(DOWNLOAD "${url}" "${cache_file}.part" STATUS download_status) 95 | list(GET download_status 0 _download_result) 96 | if(NOT ${_download_result} EQUAL 0) 97 | list(GET download_status 1 _download_error) 98 | message(FATAL_ERROR "Could not download: ${_download_error} (${_download_result})") 99 | return() 100 | endif() 101 | file(RENAME "${cache_file}.part" "${cache_file}") 102 | endif() 103 | 104 | execute_process(COMMAND ${CMAKE_COMMAND} -E tar tf "${cache_file}" 105 | WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" 106 | OUTPUT_VARIABLE _unzip_output 107 | RESULT_VARIABLE _unzip_result) 108 | if(NOT ${_unzip_result} EQUAL 0) 109 | message(FATAL_ERROR "Could not extract file") 110 | return() 111 | endif() 112 | string(REGEX REPLACE "([^/]+).*" "\\1" _extract_dir "${_unzip_output}") 113 | 114 | execute_process(COMMAND ${CMAKE_COMMAND} -E tar xf "${cache_file}" 115 | WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" 116 | RESULT_VARIABLE _unzip_result) 117 | if(NOT ${_unzip_result} EQUAL 0) 118 | message(FATAL_ERROR "Could not extract file") 119 | return() 120 | endif() 121 | 122 | set(_deploy_package_package_folder "${CMAKE_BINARY_DIR}/${_extract_dir}" PARENT_SCOPE) 123 | endfunction() 124 | 125 | _deploy_package_download() 126 | 127 | find_package(${package} ${_deploy_package_find_version} EXACT QUIET CONFIG REQUIRED 128 | ${_deploy_package_find_package_args} 129 | PATHS "${_deploy_package_package_folder}" NO_DEFAULT_PATH 130 | ) 131 | 132 | endif() 133 | endmacro() 134 | 135 | function(get_target_arch var) 136 | set(${var} ${CMAKE_SYSTEM_PROCESSOR}) 137 | if(WIN32) 138 | if(MSVC) 139 | if(CMAKE_CL_64) 140 | set(${var} x64) 141 | else() 142 | set(${var} x86) 143 | endif() 144 | elseif(CMAKE_COMPILER_IS_GNUCC) # CMAKE_CXX_COMPILER_ARCHITECTURE_ID does not provide anything with MinGW compilers 145 | execute_process(COMMAND "${CMAKE_CXX_COMPILER}" -v OUTPUT_VARIABLE GCC_VERSION_OUTPUT ERROR_VARIABLE GCC_VERSION_OUTPUT) 146 | if(GCC_VERSION_OUTPUT MATCHES ".*x86_64.*") 147 | set(${var} x64) 148 | else() 149 | set(${var} x86) 150 | endif() 151 | endif() 152 | endif() 153 | set(${var} ${${var}} PARENT_SCOPE) 154 | endfunction() 155 | 156 | function(get_target_compiler var) 157 | if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") 158 | string(REGEX REPLACE "([0-9]+\\.[0-9]+).*" "\\1" gcc_version "${CMAKE_CXX_COMPILER_VERSION}") 159 | if(NOT gcc_version VERSION_LESS "5.0") 160 | string(REGEX REPLACE "([0-9]+).*" "\\1" gcc_version "${gcc_version}") 161 | endif() 162 | set(${var} "gcc${gcc_version}") 163 | elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") 164 | string(REGEX REPLACE "([0-9]+).*" "clang\\1" ${var} "${CMAKE_CXX_COMPILER_VERSION}") 165 | elseif(MSVC) 166 | set(MSVC_YEARS 2008 2010 2012 2013 2015 2017 2019) 167 | set(MSVC_MSC_VERS 150 160 170 180 190 191 192) 168 | string(SUBSTRING "${MSVC_VERSION}" 0 3 MSVC_VER_SHORT) 169 | list(FIND MSVC_MSC_VERS ${MSVC_VER_SHORT} MSVC_INDEX) 170 | list(GET MSVC_YEARS ${MSVC_INDEX} MSVS_YEAR) 171 | set(${var} vs${MSVS_YEAR}) 172 | else() 173 | string(TOLOWER "${CMAKE_CXX_COMPILER_ID}${CMAKE_CXX_COMPILER_VERSION}" ${var}) 174 | endif() 175 | set(${var} ${${var}} PARENT_SCOPE) 176 | endfunction() 177 | 178 | function(get_target_os var) 179 | if(WIN32) 180 | set(${var} windows) 181 | elseif(APPLE) 182 | set(${var} macos) 183 | else() 184 | file(GLOB ETC_RELEASE_FILES /etc/*-release) 185 | list(REMOVE_ITEM ETC_RELEASE_FILES /etc/lsb-release) 186 | list(GET ETC_RELEASE_FILES 0 ETC_RELEASE_FILE) 187 | file(READ "${ETC_RELEASE_FILE}" ETC_RELEASE_FILE_CONTENT) 188 | string(REGEX REPLACE "=|\n" ";" ETC_RELEASE_FILE_CONTENT "${ETC_RELEASE_FILE_CONTENT}") 189 | string(REGEX REPLACE "; +| +;" ";" ETC_RELEASE_FILE_CONTENT "${ETC_RELEASE_FILE_CONTENT}") 190 | list(FIND ETC_RELEASE_FILE_CONTENT "NAME" NAME_INDEX) 191 | if(NAME_INDEX GREATER -1) 192 | math(EXPR NAME_INDEX "${NAME_INDEX} + 1") 193 | list(GET ETC_RELEASE_FILE_CONTENT "${NAME_INDEX}" ETC_RELEASE_NAME) 194 | else() 195 | list(GET ETC_RELEASE_FILE_CONTENT 0 ETC_RELEASE_NAME) 196 | endif() 197 | string(REGEX MATCH "[^ \"]+" ETC_RELEASE_NAME "${ETC_RELEASE_NAME}") 198 | list(FIND ETC_RELEASE_FILE_CONTENT "VERSION_ID" VERSION_INDEX) 199 | if(NOT VERSION_INDEX GREATER -1) 200 | list(FIND ETC_RELEASE_FILE_CONTENT "VERSION" VERSION_INDEX) 201 | endif() 202 | if(VERSION_INDEX GREATER -1) 203 | math(EXPR VERSION_INDEX "${VERSION_INDEX} + 1") 204 | list(GET ETC_RELEASE_FILE_CONTENT "${VERSION_INDEX}" ETC_RELEASE_VERSION) 205 | string(REGEX MATCH "[^ \"]+" ETC_RELEASE_VERSION "${ETC_RELEASE_VERSION}") 206 | else() 207 | string(REGEX MATCH "[0-9]+" ETC_RELEASE_VERSION "${ETC_RELEASE_FILE_CONTENT}") 208 | endif() 209 | string(TOLOWER "${ETC_RELEASE_NAME}${ETC_RELEASE_VERSION}" ${var}) 210 | endif() 211 | set(${var} ${${var}} PARENT_SCOPE) 212 | endfunction() 213 | 214 | get_target_arch(CDEPLOY_ARCH) 215 | get_target_compiler(CDEPLOY_COMPILER) 216 | get_target_os(CDEPLOY_OS) 217 | 218 | set(CPACK_GENERATOR "ZIP") 219 | string(TOLOWER "${PROJECT_NAME}" CPACK_PACKAGE_FILE_NAME) 220 | set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${PROJECT_VERSION}") 221 | if(CDEPLOY_PACKAGE_REVISION) 222 | set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CDEPLOY_PACKAGE_REVISION}") 223 | endif() 224 | if(NOT CDEPLOY_NO_OS) 225 | set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CDEPLOY_OS}") 226 | endif() 227 | if(NOT CDEPLOY_NO_ARCH) 228 | set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CDEPLOY_ARCH}") 229 | endif() 230 | if(NOT CDEPLOY_NO_COMPILER) 231 | set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_FILE_NAME}-${CDEPLOY_COMPILER}") 232 | endif() 233 | 234 | if(MSVC AND NOT CDEPLOY_NO_DEBUG_BUILD) 235 | 236 | set_property(GLOBAL PROPERTY USE_FOLDERS ON) 237 | set_property(GLOBAL PROPERTY PREDEFINED_TARGETS_FOLDER ".cmake") 238 | 239 | include(ExternalProject) 240 | 241 | ExternalProject_Add(DEBUG_BUILD 242 | SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}" 243 | BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/build-debug" 244 | CMAKE_ARGS "-DCMAKE_INSTALL_PREFIX=${CMAKE_CURRENT_BINARY_DIR}/install-debug" -DCDEPLOY_NO_DEBUG_BUILD=True -DCMAKE_BUILD_TYPE=Debug 245 | BUILD_COMMAND ${CMAKE_COMMAND} --build "${CMAKE_CURRENT_BINARY_DIR}/build-debug" --config Debug 246 | INSTALL_COMMAND ${CMAKE_COMMAND} --build "${CMAKE_CURRENT_BINARY_DIR}/build-debug" --config Debug --target install 247 | BUILD_ALWAYS True 248 | ) 249 | file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/install-debug") 250 | install(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/install-debug/" DESTINATION . USE_SOURCE_PERMISSIONS) 251 | 252 | set_property(TARGET DEBUG_BUILD PROPERTY FOLDER ".cmake") 253 | if(NOT CDEPLOY_DEBUG_BUILD) 254 | set_property(TARGET DEBUG_BUILD PROPERTY EXCLUDE_FROM_DEFAULT_BUILD True) 255 | set_property(TARGET DEBUG_BUILD PROPERTY EXCLUDE_FROM_ALL True) 256 | endif() 257 | 258 | endif() 259 | if(CDEPLOY_DEBUG_BUILD) 260 | endif() 261 | 262 | if(MSVC) 263 | set(CMAKE_DEBUG_POSTFIX d) 264 | endif() 265 | 266 | file(REMOVE "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in") 267 | 268 | function(deploy_export_init) 269 | 270 | if(NOT EXISTS "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in") 271 | file(WRITE "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "@PACKAGE_INIT@\n\n") 272 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "set_and_check(INSTALL_DIR \"@PACKAGE_INSTALL_DIR@\")\n\n") 273 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "include(CMakeFindDependencyMacro)\n\n") 274 | endif() 275 | 276 | endfunction() 277 | 278 | function(deploy_export_dependency name) 279 | deploy_export_init() 280 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "find_dependency(${name} ${ARGN})\n\n") 281 | endfunction() 282 | 283 | function(deploy_export name) 284 | 285 | include(CMakeParseArguments) 286 | 287 | set(options INTERFACE LIBRARY STATIC SHARED EXECUTABLE) 288 | set(oneValueArgs CONFIGURATION IMPORTED_LOCATION IMPORTED_IMPLIB) 289 | set(multiValueArgs INTERFACE_INCLUDE_DIRECTORIES INTERFACE_SOURCES INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_FEATURES INTERFACE_COMPILE_OPTIONS INTERFACE_LINK_LIBRARIES PROPERTIES) 290 | cmake_parse_arguments(_ "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) 291 | 292 | deploy_export_init() 293 | 294 | set(target_flags) 295 | if(__STATIC) 296 | set(target_flags "${target_flags} STATIC") 297 | endif() 298 | if(__SHARED) 299 | set(target_flags "${target_flags} SHARED") 300 | endif() 301 | if(__INTERFACE) 302 | set(target_flags "${target_flags} INTERFACE") 303 | endif() 304 | 305 | set(target_config) 306 | if(__CONFIGURATION) 307 | string(TOUPPER "${__CONFIGURATION}" __CONFIGURATION) 308 | set(target_config "_${__CONFIGURATION}") 309 | endif() 310 | 311 | set(target_properties) 312 | if(__IMPORTED_LOCATION) 313 | set(target_properties "${target_properties} IMPORTED_LOCATION${target_config} \"\${INSTALL_DIR}/${__IMPORTED_LOCATION}\"") 314 | endif() 315 | if(__IMPORTED_IMPLIB) 316 | set(target_properties "${target_properties} IMPORTED_IMPLIB${target_config} \"\${INSTALL_DIR}/${__IMPORTED_IMPLIB}\"") 317 | endif() 318 | if(__INTERFACE_INCLUDE_DIRECTORIES) 319 | set(target_properties "${target_properties} INTERFACE_INCLUDE_DIRECTORIES \"") 320 | foreach(dir ${__INTERFACE_INCLUDE_DIRECTORIES}) 321 | set(target_properties "${target_properties}\${INSTALL_DIR}/${dir};") 322 | endforeach() 323 | set(target_properties "${target_properties}\"") 324 | endif() 325 | if(__INTERFACE_SOURCES) 326 | set(target_properties "${target_properties} INTERFACE_SOURCES \"") 327 | foreach(file ${__INTERFACE_SOURCES}) 328 | set(target_properties "${target_properties}\${INSTALL_DIR}/${file};") 329 | endforeach() 330 | set(target_properties "${target_properties}\"") 331 | endif() 332 | foreach(property INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_FEATURES INTERFACE_COMPILE_OPTIONS INTERFACE_LINK_LIBRARIES) 333 | if(__${property}) 334 | set(target_properties "${target_properties} ${property} \"") 335 | foreach(arg ${__${property}}) 336 | set(target_properties "${target_properties}${arg};") 337 | endforeach() 338 | set(target_properties "${target_properties}\"") 339 | endif() 340 | endforeach() 341 | if(__PROPERTIES) 342 | foreach(arg ${__PROPERTIES}) 343 | set(target_properties "${target_properties} ${arg}") 344 | endforeach() 345 | endif() 346 | 347 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "if(NOT TARGET ${PROJECT_NAME}::${name})\n") 348 | if(__LIBRARY OR __INTERFACE) 349 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" " add_library(${PROJECT_NAME}::${name} ${target_flags} IMPORTED GLOBAL)\n") 350 | else() 351 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" " add_executable(${PROJECT_NAME}::${name} IMPORTED GLOBAL)\n") 352 | endif() 353 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "endif()\n") 354 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "set_target_properties(${PROJECT_NAME}::${name}\n") 355 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" " PROPERTIES\n") 356 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" " ${target_properties}\n") 357 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" ")\n") 358 | if(__CONFIGURATION) 359 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "set_property(TARGET ${PROJECT_NAME}::${name} APPEND PROPERTY IMPORTED_CONFIGURATIONS ${__CONFIGURATION})\n") 360 | endif() 361 | file(APPEND "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "\n") 362 | 363 | endfunction() 364 | 365 | function(install_deploy_export) 366 | include(CMakePackageConfigHelpers) 367 | if(EXISTS "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in") 368 | set(INSTALL_DIR .) 369 | configure_package_config_file("${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake.in" "${PROJECT_NAME}Config.cmake" 370 | INSTALL_DESTINATION "lib/cmake/${PROJECT_NAME}" 371 | PATH_VARS 372 | INSTALL_DIR 373 | ) 374 | install(FILES "${CMAKE_BINARY_DIR}/${PROJECT_NAME}Config.cmake" DESTINATION "lib/cmake/${PROJECT_NAME}") 375 | else() 376 | install(EXPORT ${PROJECT_NAME}Config 377 | DESTINATION "lib/cmake/${PROJECT_NAME}" 378 | NAMESPACE ${PROJECT_NAME}:: 379 | ) 380 | endif() 381 | write_basic_package_version_file("${PROJECT_NAME}ConfigVersion.cmake" COMPATIBILITY ExactVersion) 382 | install(FILES "${CMAKE_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" DESTINATION "lib/cmake/${PROJECT_NAME}") 383 | endfunction() 384 | 385 | --------------------------------------------------------------------------------