Skip to content
Permalink
Browse files

Add reloading certificate and private key gracefully

  • Loading branch information
GreaterFire committed Apr 11, 2019
1 parent 7d9ffda commit 53ca5f80fcd6239c28c8520886692e9186e3fcf6
Showing with 42 additions and 19 deletions.
  1. +27 −19 src/main.cpp
  2. +14 −0 src/service.cpp
  3. +1 −0 src/service.h
@@ -36,6 +36,31 @@ namespace po = boost::program_options;
#define DEFAULT_CONFIG "config.json"
#endif // DEFAULT_CONFIG

void signal_async_wait(signal_set &sig, Service &service, bool &restart) {
sig.async_wait([&](const boost::system::error_code error, int signum) {
if (error) {
return;
}
Log::log_with_date_time("got signal: " + to_string(signum), Log::WARN);
switch (signum) {
case SIGINT:
case SIGTERM:
service.stop();
break;
#ifndef _WIN32
case SIGHUP:
restart = true;
service.stop();
break;
case SIGUSR1:
service.reload_cert();
signal_async_wait(sig, service, restart);
break;
#endif // _WIN32
}
});
}

int main(int argc, const char *argv[]) {
try {
Log::log("Welcome to trojan " + Version::get_version(), Log::FATAL);
@@ -111,26 +136,9 @@ int main(int argc, const char *argv[]) {
sig.add(SIGTERM);
#ifndef _WIN32
sig.add(SIGHUP);
sig.add(SIGUSR1);
#endif // _WIN32
auto sig_cb = [&](const boost::system::error_code error, int signum) {
if (error) {
return;
}
Log::log_with_date_time("got signal: " + to_string(signum), Log::WARN);
switch (signum) {
case SIGINT:
case SIGTERM:
service.stop();
break;
#ifndef _WIN32
case SIGHUP:
restart = true;
service.stop();
break;
#endif // _WIN32
}
};
sig.async_wait(sig_cb);
signal_async_wait(sig, service, restart);
service.run();
if (restart) {
Log::log_with_date_time("trojan service restarting. . . ", Log::WARN);
@@ -295,6 +295,20 @@ boost::asio::io_service &Service::service() {
return io_service;
}

void Service::reload_cert() {
if (config.run_type == Config::SERVER) {
Log::log_with_date_time("reloading certificate and private key. . . ", Log::WARN);
ssl_context.use_certificate_chain_file(config.ssl.cert);
ssl_context.use_private_key_file(config.ssl.key, context::pem);
boost::system::error_code ec;
socket_acceptor.cancel(ec);
async_accept();
Log::log_with_date_time("certificate and private key reloaded", Log::WARN);
} else {
Log::log_with_date_time("cannot reload certificate and private key: wrong run_type", Log::ERROR);
}
}

Service::~Service() {
if (auth) {
delete auth;
@@ -49,6 +49,7 @@ class Service {
void run();
void stop();
boost::asio::io_service &service();
void reload_cert();
~Service();
};

0 comments on commit 53ca5f8

Please sign in to comment.
You can’t perform that action at this time.