diff --git a/src/cgproxy.cpp b/src/cgproxy.cpp index 45936e0..9fa5aca 100644 --- a/src/cgproxy.cpp +++ b/src/cgproxy.cpp @@ -33,7 +33,7 @@ int main(int argc, char *argv[]) { int shift = 1; processArgs(argc, argv, shift); - if (argc==shift||print_help) { + if (argc == shift || print_help) { print_usage(); exit(0); } diff --git a/src/cgproxyd.cpp b/src/cgproxyd.cpp index 72f4639..b8cd624 100644 --- a/src/cgproxyd.cpp +++ b/src/cgproxyd.cpp @@ -3,6 +3,7 @@ #include "config.hpp" #include "socket_server.hpp" #include +#include #include #include #include @@ -11,6 +12,7 @@ #include #include #include +#include using namespace std; using json = nlohmann::json; @@ -33,6 +35,7 @@ class cgproxyd { } return instance->handle_msg(msg); } + static void signalHandler(int signum) { debug("Signal %d received.", signum); if (!instance) { @@ -43,6 +46,26 @@ class cgproxyd { exit(signum); } + // single process instance + int lock_fd; + void lock() { + lock_fd = open(PID_LOCK_FILE, O_CREAT | O_RDWR, 0666); + int rc = flock(lock_fd, LOCK_EX | LOCK_NB); + if (rc == -1) { + perror(PID_LOCK_FILE); + error("maybe another cgproxyd is running"); + exit(EXIT_FAILURE); + } else { + ofstream ofs(PID_LOCK_FILE); + ofs << getpid() << endl; + ofs.close(); + } + } + void unlock() { + close(lock_fd); + unlink(PID_LOCK_FILE); + } + int handle_msg(char *msg) { debug("received msg: %s", msg); json j; @@ -97,6 +120,7 @@ class cgproxyd { public: int start() { + lock(); signal(SIGINT, &signalHandler); signal(SIGTERM, &signalHandler); signal(SIGHUP, &signalHandler); @@ -120,6 +144,7 @@ public: void stop() { debug("stopping"); system(TPROXY_IPTABLS_CLEAN); + unlock(); } ~cgproxyd() { stop(); } @@ -147,6 +172,13 @@ int main(int argc, char *argv[]) { print_usage(); exit(0); } + + if (getuid() != 0) { + error("permission denied, need root"); + print_usage(); + exit(EXIT_FAILURE); + } + CGPROXY::cgproxyd d; return d.start(); } \ No newline at end of file diff --git a/src/common.hpp b/src/common.hpp index 2758b03..49efdd5 100644 --- a/src/common.hpp +++ b/src/common.hpp @@ -4,6 +4,7 @@ #define TPROXY_IPTABLS_START "sh /usr/share/cgproxy/scripts/cgroup-tproxy.sh" #define TPROXY_IPTABLS_CLEAN "sh /usr/share/cgproxy/scripts/cgroup-tproxy.sh stop" +#define PID_LOCK_FILE "/var/run/cgproxyd.pid" #define SOCKET_PATH "/tmp/cgproxy_unix_socket" #define LISTEN_BACKLOG 64 #define DEFAULT_CONFIG_FILE "/etc/cgproxy/config.json"