aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Server/CertificateReloader.h
blob: e4db674c1409f4a50181184c697a35806ab9220e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#pragma once

#include "clickhouse_config.h"

#if USE_SSL

#include <string>
#include <filesystem>

#include <Poco/Logger.h>
#include <Poco/Util/AbstractConfiguration.h>
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include <Poco/Crypto/RSAKey.h>
#include <Poco/Crypto/X509Certificate.h>
#include <Common/MultiVersion.h>


namespace DB
{

/// The CertificateReloader singleton performs 2 functions:
/// 1. Dynamic reloading of TLS key-pair when requested by server:
///   Server config reloader notifies CertificateReloader when the config changes.
///   On changed config, CertificateReloader reloads certs from disk.
/// 2. Implement `SSL_CTX_set_cert_cb` to set certificate for a new connection:
///   OpenSSL invokes a callback to setup a connection.
class CertificateReloader
{
public:
    using stat_t = struct stat;

    /// Singleton
    CertificateReloader(CertificateReloader const &) = delete;
    void operator=(CertificateReloader const &) = delete;
    static CertificateReloader & instance()
    {
        static CertificateReloader instance;
        return instance;
    }

    /// Initialize the callback and perform the initial cert loading
    void init();

    /// Handle configuration reload
    void tryLoad(const Poco::Util::AbstractConfiguration & config);

    /// A callback for OpenSSL
    int setCertificate(SSL * ssl);

private:
    CertificateReloader() = default;

    Poco::Logger * log = &Poco::Logger::get("CertificateReloader");

    struct File
    {
        const char * description;
        explicit File(const char * description_) : description(description_) {}

        std::string path;
        std::filesystem::file_time_type modification_time;

        bool changeIfModified(std::string new_path, Poco::Logger * logger);
    };

    File cert_file{"certificate"};
    File key_file{"key"};

    struct Data
    {
        Poco::Crypto::X509Certificate cert;
        Poco::Crypto::EVPPKey key;

        Data(std::string cert_path, std::string key_path, std::string pass_phrase);
    };

    MultiVersion<Data> data;
    bool init_was_not_made = true;
};

}

#endif