frp.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. //
  2. // Created by xcbosa on 2023/1/31.
  3. //
  4. #pragma once
  5. #include <string>
  6. #include "utils/utils.h"
  7. #include "webuiconf.h"
  8. #include "fs.hpp"
  9. #include <signal.h>
  10. #include <strstream>
  11. #include "frp.h"
  12. #include <iomanip>
  13. #include <chrono>
  14. #include <functional>
  15. #include <random>
  16. using namespace std;
  17. using namespace xc;
  18. using namespace xc::utils;
  19. namespace xc::frp {
  20. set<int> profileUsingPorts(string profile) {
  21. set<int> usingPorts;
  22. INIFile ini(conf::getFrpcDir() + "/" + profile);
  23. string value = ini.getMust("common")->get("webui_allowServerPorts");
  24. auto v = split(value, ",");
  25. int low(0), len(0);
  26. if (v.size() == 2) {
  27. try {
  28. low = stoi(v[0]);
  29. len = stoi(v[1]);
  30. } catch (...) { }
  31. }
  32. for (int i = low; i < low + len; i++) {
  33. usingPorts.insert(i);
  34. }
  35. return usingPorts;
  36. }
  37. set<int> serverUsingPorts(string serverIp) {
  38. set<int> usingPorts;
  39. for (string file : fs::contentsOfDirectory(conf::getFrpcDir())) {
  40. INIFile ini(conf::getFrpcDir() + "/" + file);
  41. if (ini.getMust("common")->get("server_addr") == serverIp) {
  42. auto profilePorts = profileUsingPorts(file);
  43. for (auto port : profilePorts) {
  44. usingPorts.insert(port);
  45. }
  46. }
  47. }
  48. return usingPorts;
  49. }
  50. void addProfile(string name, string ip, string port, string token) {
  51. INI ini;
  52. auto frpCommon = ini.getMust("common");
  53. frpCommon->set("server_addr", ip);
  54. frpCommon->set("server_port", port);
  55. frpCommon->set("token", token);
  56. frpCommon->set("tls_enable", "true");
  57. auto alreadyUsingPorts = serverUsingPorts(ip);
  58. int low = 0, len = conf::allowPortCountPerProfile;
  59. for (int i = 10000; i < 60000; i += len) {
  60. bool badPage = false;
  61. for (int j = i; j < i + len; j++) {
  62. if (alreadyUsingPorts.count(j)) {
  63. badPage = true;
  64. break;
  65. }
  66. }
  67. if (!badPage) {
  68. low = i;
  69. break;
  70. }
  71. }
  72. if (low == 0) {
  73. len = 0;
  74. }
  75. ostringstream oss;
  76. oss << low;
  77. oss << ",";
  78. oss << len;
  79. frpCommon->set("webui_allowServerPorts", oss.str());
  80. saveTextFile(conf::getFrpcDir() + "/" + name, ini.getINIString());
  81. }
  82. class FrpProcessWrapper {
  83. public:
  84. FrpProcessWrapper(string fileName, string filePath) {
  85. this->fileName = fileName;
  86. this->filePath = filePath;
  87. this->updated = false;
  88. }
  89. void startAndKeepRunning() {
  90. cout << "[FrpProcessWrapper] [" << fileName << "] Start" << endl;
  91. this->doKill();
  92. this->doStart();
  93. }
  94. void update() {
  95. struct stat buf;
  96. if (stat(this->filePath.c_str(), &buf) == 0) {
  97. if (this->mutationTime != buf.st_mtimespec.tv_nsec) {
  98. this->mutationTime = buf.st_mtimespec.tv_nsec;
  99. this->reloadConfig();
  100. return;
  101. }
  102. }
  103. if (getRunningPid() == 0) {
  104. cout << "[FrpProcessWrapper] [" << fileName << "] Exit unexpectedly, restarting..." << endl;
  105. this->doStart();
  106. }
  107. }
  108. int getRunningPid() {
  109. ::FILE *psStdoutFd = popen("ps -ef", "r");
  110. ostringstream oss;
  111. while (true) {
  112. int ch = ::fgetc(psStdoutFd);
  113. if (ch == -1) break;
  114. oss << (char) ch;
  115. }
  116. ::pclose(psStdoutFd);
  117. string str = oss.str();
  118. auto lines = split(str, "\n");
  119. for (auto line : lines) {
  120. if (line.find("frpc -c") != line.npos && line.find(this->filePath) != line.npos) {
  121. strstream ss;
  122. ss << line;
  123. string owner;
  124. int pid;
  125. ss >> owner;
  126. ss >> pid;
  127. return pid;
  128. }
  129. }
  130. return 0;
  131. }
  132. void stop() {
  133. cout << "[FrpProcessWrapper] [" << fileName << "] Stop" << endl;
  134. this->doKill();
  135. }
  136. void reloadConfig() {
  137. cout << "[FrpProcessWrapper] [" << fileName << "] Changes Detected, Reload..." << endl;
  138. this->doKill();
  139. this->doStart();
  140. }
  141. bool updated;
  142. string fileName;
  143. string filePath;
  144. long mutationTime;
  145. private:
  146. void doStart() {
  147. struct stat buf;
  148. if (stat(this->filePath.c_str(), &buf) == 0) {
  149. this->mutationTime = buf.st_mtimespec.tv_nsec;
  150. }
  151. ostringstream oss;
  152. oss << "frpc -c " << this->filePath << " &";
  153. string launchCmd = oss.str();
  154. ::system(launchCmd.c_str());
  155. }
  156. void doKill() {
  157. int pid = getRunningPid();
  158. if (pid > 0) {
  159. kill(pid, SIGKILL);
  160. }
  161. }
  162. };
  163. set<string> reloadConfigForFilePathRequests;
  164. mutex reloadConfigForFilePathRequestsLocker;
  165. void reloadProfileFilePath(string filePath) {
  166. reloadConfigForFilePathRequestsLocker.lock();
  167. reloadConfigForFilePathRequests.insert(filePath);
  168. reloadConfigForFilePathRequestsLocker.unlock();
  169. }
  170. void frpDaemon() {
  171. char readBuff[1024];
  172. vector<FrpProcessWrapper *> frpProcesses;
  173. while (true) {
  174. for (auto it : frpProcesses) {
  175. it->updated = false;
  176. }
  177. for (string file : fs::contentsOfDirectory(conf::getFrpcDir())) {
  178. string filePath = conf::getFrpcDir() + "/" + file;
  179. bool updated = false;
  180. for (auto process : frpProcesses) {
  181. if (process->filePath == filePath) {
  182. process->update();
  183. process->updated = true;
  184. updated = true;
  185. break;
  186. }
  187. }
  188. if (!updated) {
  189. auto newProcess = new FrpProcessWrapper(file, filePath);
  190. newProcess->startAndKeepRunning();
  191. newProcess->updated = true;
  192. frpProcesses.push_back(newProcess);
  193. }
  194. }
  195. for (auto it = frpProcesses.begin(); it != frpProcesses.end(); ) {
  196. FrpProcessWrapper *proc = *it;
  197. if (!proc->updated) {
  198. proc->stop();
  199. delete proc;
  200. it = frpProcesses.erase(it);
  201. } else {
  202. reloadConfigForFilePathRequestsLocker.lock();
  203. if (reloadConfigForFilePathRequests.count(proc->filePath)) {
  204. reloadConfigForFilePathRequests.erase(proc->filePath);
  205. reloadConfigForFilePathRequestsLocker.unlock();
  206. proc->reloadConfig();
  207. } else {
  208. reloadConfigForFilePathRequestsLocker.unlock();
  209. }
  210. it++;
  211. }
  212. }
  213. usleep(1000 * 1000);
  214. }
  215. }
  216. static string create_uuid() {
  217. ostringstream stream;
  218. auto random_seed = std::chrono::system_clock::now().time_since_epoch().count();
  219. std::mt19937 seed_engine(random_seed);
  220. std::uniform_int_distribution<std::size_t> random_gen;
  221. std::size_t value = random_gen(seed_engine);
  222. stream << hex << value;
  223. return stream.str();
  224. }
  225. ProfilePortInfo::ProfilePortInfo() { }
  226. ProfilePortInfo::ProfilePortInfo(string localIp, int localPort, int remotePort):
  227. localIp(localIp), localPort(localPort), remotePort(remotePort), uuid(create_uuid()) { }
  228. ProfilePortInfo::ProfilePortInfo(string localIp, int localPort, int remotePort, string uuid):
  229. localIp(localIp), localPort(localPort), remotePort(remotePort), uuid(uuid) { }
  230. ProfileInfo::ProfileInfo() { }
  231. ProfileInfo::ProfileInfo(string profileName) {
  232. this->profileName = profileName;
  233. INIFile file(conf::getFrpcDir() + "/" + profileName);
  234. bool needSave = false;
  235. for (auto &it : file.data) {
  236. if (it.getTitle() == "common") {
  237. this->serverAddr = it.get("server_addr");
  238. this->serverPort = to_int(it.get("server_port"), 0);
  239. this->token = it.get("token");
  240. string users = it.get("webui_availableForUsers");
  241. for (auto it : split(users, "/")) {
  242. trim(it);
  243. if (!it.empty()) {
  244. this->users.insert(it);
  245. }
  246. }
  247. string allowPortStr = it.get("webui_allowServerPorts");
  248. auto list = split(allowPortStr, ",");
  249. if (list.size() == 2) {
  250. this->allowPortLow = to_int(list[0], 0);
  251. this->allowPortCount = to_int(list[1], 0);
  252. }
  253. } else {
  254. string type = it.get("type");
  255. string localIp = it.get("local_ip");
  256. bool success;
  257. int localPort = to_int(it.get("local_port"), success);
  258. if (!success || !is_in(localPort, 0, 65536)) { continue; }
  259. int remotePort = to_int(it.get("remote_port"), success);
  260. if (!success || !is_in(localPort, 0, 65536)) { continue; }
  261. string id = it.get("id");
  262. if (id.empty()) {
  263. id = create_uuid();
  264. needSave = true;
  265. }
  266. it.set("id", id);
  267. if (type == "tcp" || type == "udp") {
  268. bool alreadyHave = false;
  269. for (auto v : this->ports) {
  270. if (v.remotePort == remotePort) {
  271. alreadyHave = true;
  272. }
  273. }
  274. if (alreadyHave) { continue; }
  275. this->ports.push_back(ProfilePortInfo(localIp, localPort, remotePort, id));
  276. }
  277. }
  278. }
  279. if (needSave) {
  280. file.save();
  281. }
  282. }
  283. int ProfileInfo::getFirstFreeRemotePort() {
  284. set<int> usingPorts;
  285. for (auto port : this->ports) {
  286. usingPorts.insert(port.remotePort);
  287. }
  288. for (int i = this->allowPortLow; i < this->allowPortLow + this->allowPortCount; i++) {
  289. if (!usingPorts.count(i)) {
  290. return i;
  291. }
  292. }
  293. return -1;
  294. }
  295. int ProfileInfo::getFirstFreeRemotePort(int ifNoneThenReturn) {
  296. int value = getFirstFreeRemotePort();
  297. if (value == -1) return ifNoneThenReturn;
  298. return value;
  299. }
  300. vector<int> ProfileInfo::getFreeRemotePorts() {
  301. return getFreeRemotePorts(65536);
  302. }
  303. vector<int> ProfileInfo::getFreeRemotePorts(int maxCnt) {
  304. set<int> usingPorts;
  305. vector<int> res;
  306. for (auto port : this->ports) {
  307. usingPorts.insert(port.remotePort);
  308. }
  309. int cnt = 0;
  310. for (int i = this->allowPortLow; i < this->allowPortLow + this->allowPortCount; i++) {
  311. if (!usingPorts.count(i)) {
  312. res.push_back(i);
  313. cnt++;
  314. if (cnt >= maxCnt) {
  315. break;
  316. }
  317. }
  318. }
  319. return res;
  320. }
  321. vector<int> ProfileInfo::getFreeRemotePortsAndAppend(int me) {
  322. vector<int> ports = getFreeRemotePorts();
  323. ports.push_back(me);
  324. std::sort(ports.begin(), ports.end());
  325. return ports;
  326. }
  327. void ProfileInfo::addPortInfo(ProfilePortInfo portInfo) {
  328. for (auto &port : this->ports) {
  329. if (port.remotePort == portInfo.remotePort) {
  330. port.localPort = portInfo.localPort;
  331. port.localIp = portInfo.localIp;
  332. return;
  333. }
  334. }
  335. this->ports.insert(this->ports.begin(), portInfo);
  336. }
  337. void ProfileInfo::removePort(int remotePort) {
  338. for (auto ptr = this->ports.begin(); ptr != this->ports.end(); ptr++) {
  339. if (ptr->remotePort == remotePort) {
  340. this->ports.erase(ptr);
  341. return;
  342. }
  343. }
  344. }
  345. string ProfileInfo::getServerAddr() { return this->serverAddr; }
  346. int ProfileInfo::getAllowPortLow() { return this->allowPortLow; }
  347. int ProfileInfo::getAllowPortCount() { return this->allowPortCount; }
  348. void ProfileInfo::save() const {
  349. string path = conf::getFrpcDir() + "/" + this->profileName;
  350. INIFile ini(path);
  351. ini.data.clear();
  352. ini.getMust("common")->set("server_addr", this->serverAddr);
  353. ini.getMust("common")->set("server_port", to_string(this->serverPort));
  354. ini.getMust("common")->set("token", this->token);
  355. ini.getMust("common")->set("tls_enable", "true");
  356. ostringstream usersOss;
  357. for (auto user : this->users) {
  358. usersOss << user;
  359. usersOss << "/";
  360. }
  361. ini.getMust("common")->set("webui_availableForUsers", usersOss.str());
  362. ostringstream oss;
  363. oss << this->allowPortLow << "," << this->allowPortCount;
  364. ini.getMust("common")->set("webui_allowServerPorts", oss.str());
  365. for (auto port : this->ports) {
  366. for (auto type : conf::supportTypes) {
  367. ostringstream titleOss;
  368. titleOss << "frpc-webui-" << port.remotePort << "-" << type;
  369. ini.getMust(titleOss.str())->set("type", type);
  370. ini.getMust(titleOss.str())->set("local_ip", port.localIp);
  371. ini.getMust(titleOss.str())->set("local_port", to_string(port.localPort));
  372. ini.getMust(titleOss.str())->set("remote_port", to_string(port.remotePort));
  373. ini.getMust(titleOss.str())->set("use_encryption", "true");
  374. ini.getMust(titleOss.str())->set("use_compression", "true");
  375. }
  376. }
  377. ini.save();
  378. }
  379. void ProfileInfo::addUser(string name) {
  380. this->users.insert(name);
  381. }
  382. void ProfileInfo::removeUser(string name) {
  383. this->users.erase(name);
  384. }
  385. bool ProfileInfo::availableForUser(string name) {
  386. return this->users.count(name) > 0;
  387. }
  388. vector<ProfileInfo> listUserAvailableProfiles(string user) {
  389. vector<ProfileInfo> profiles;
  390. for (auto profile : fs::contentsOfDirectory(conf::getFrpcDir())) {
  391. ProfileInfo profileInfo(profile);
  392. if (profileInfo.availableForUser(user)) {
  393. profiles.push_back(profileInfo);
  394. }
  395. }
  396. return profiles;
  397. }
  398. vector<string> listingAvailableServerAndPortForUser(string username) {
  399. auto profiles = listUserAvailableProfiles(username);
  400. vector<string> items;
  401. for (auto profile : profiles) {
  402. for (auto port : profile.getFreeRemotePorts()) {
  403. items.push_back(profile.getServerAddr() + ":" + to_string(port));
  404. }
  405. }
  406. return items;
  407. }
  408. }