#ifndef FRP_UTIL_H #define FRP_UTIL_H #include #include #include #include #include #include #include "Application.h" #include "Poco/JSON/Object.h" #include "util/SystemInfo.h" namespace Util { class FrpUtil { private: public: static constexpr const char* frpcConfigPathName = "/customer/frp/frpc.toml"; static constexpr const char* frpcPathName = "/customer/frp/frpc"; public: static int getFrpcPid() { return Util::SystemInfo::getProcessPID(frpcPathName); } static void startFrpc(std::string serialNum, Poco::JSON::Object::Ptr service_ports, bool forceRestart) { int http_local_port = service_ports->get("http_port"); int http_remote_port = service_ports->get("http_port_nat_port"); int http_api_local_port = service_ports->get("http_api_port"); int http_api_remote_port = service_ports->get("http_api_port_nat_port"); int rtmp_local_port = service_ports->get("rtmp_port"); int rtmp_remote_port = service_ports->get("rtmp_port_nat_port"); int rtsp_local_port = service_ports->get("rtsp_port"); int rtsp_remote_port = service_ports->get("rtsp_port_nat_port"); int srt_local_port = service_ports->get("srt_port"); int srt_remote_port = service_ports->get("srt_port_nat_port"); int nat_frp_enable = service_ports->get("nat_frp_enable"); try { int pid = getFrpcPid(); if (nat_frp_enable == 0) { if (pid > 0) { stopFrpc(pid); } return; } if (pid > 0) { if (forceRestart) { stopFrpc(pid); } else { return; } } pid_t child = fork(); if (child < 0) { logger().information("frpc fork failed"); return; } if (child > 0) { logger().information("frpc daemon starting..."); return; } setsid(); for (int i = 3; i < 1024; ++i) { close(i); } int fd = open("/dev/null", O_RDWR); if (fd >= 0) { dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); close(fd); } setenv("FRP_SERIAL_NUM", serialNum.c_str(), 1); setenv("FRP_HTTP_LOCAL_PORT", std::to_string(http_local_port).c_str(), 1); setenv("FRP_HTTP_REMOTE_PORT", std::to_string(http_remote_port).c_str(), 1); setenv("FRP_HTTP_API_LOCAL_PORT", std::to_string(http_api_local_port).c_str(), 1); setenv("FRP_HTTP_API_REMOTE_PORT", std::to_string(http_api_remote_port).c_str(), 1); setenv("FRP_RTMP_LOCAL_PORT", std::to_string(rtmp_local_port).c_str(), 1); setenv("FRP_RTMP_REMOTE_PORT", std::to_string(rtmp_remote_port).c_str(), 1); setenv("FRP_RTSP_LOCAL_PORT", std::to_string(rtsp_local_port).c_str(), 1); setenv("FRP_RTSP_REMOTE_PORT", std::to_string(rtsp_remote_port).c_str(), 1); setenv("FRP_SRT_LOCAL_PORT", std::to_string(srt_local_port).c_str(), 1); setenv("FRP_SRT_REMOTE_PORT", std::to_string(srt_remote_port).c_str(), 1); execlp(frpcPathName, frpcPathName, "-c", frpcConfigPathName, (char*)NULL); exit(EXIT_FAILURE); } catch (const std::exception& e) { logger().information("doStartFrpc,error: %s", std::string(e.what())); } } static void stopFrpc(int pid) { if (pid > 0) { Util::SystemInfo::executeCommand("kill -9 " + std::to_string(pid)); logger().information("frpc stoped,pid=%d........", pid); } } }; } #endif