-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvpsmc_lib.cpp
More file actions
708 lines (642 loc) · 27.5 KB
/
vpsmc_lib.cpp
File metadata and controls
708 lines (642 loc) · 27.5 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
#include "vpsmc_lib.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdio>
#include <array>
#include <wordexp.h>
#include <sys/stat.h>
#include <chrono>
#include <iomanip>
#include <cstring>
#include <algorithm>
#include <unistd.h>
#include "nlohmann/json.hpp"
using json = nlohmann::json;
// --- Global Mutex for Logging ---
std::mutex log_mutex;
// --- Function Implementations ---
std::string expand_path(const std::string& path) {
if (path.empty() || path[0] != '~') {
return path;
}
wordexp_t p;
wordexp(path.c_str(), &p, 0);
std::string res = p.we_wordv[0];
wordfree(&p);
return res;
}
bool load_config(Config& config) {
std::string path1 = "./vpsmc.conf.json";
std::string path2 = expand_path("~/vpsmc/vpsmc.conf.json");
std::ifstream file;
std::string found_path;
file.open(path1);
if (file.is_open()) {
found_path = path1;
} else {
file.open(path2);
if (file.is_open()) {
found_path = path2;
} else {
std::cerr << "Error: Configuration file not found." << std::endl;
std::cerr << "Please create 'vpsmc.conf.json' in the current directory or in ~/vpsmc/" << std::endl;
return false;
}
}
try {
json data = json::parse(file);
const auto& cfg = data["vpsmc_config"];
config.servers_json_path = expand_path(cfg["paths"].value("servers_json", ""));
config.log_directory_path = expand_path(cfg["paths"].value("log_directory", ""));
config.exchange_rates_path = expand_path(cfg["paths"].value("exchange_rates_json", ""));
config.default_base_currency = cfg["settings"].value("default_base_currency", "USD");
config.ssh_timeout = cfg["settings"].value("ssh_connect_timeout_seconds", 10);
config.config_file_location = found_path;
} catch (json::exception& e) {
std::cerr << "Error parsing config file '" << found_path << "': " << e.what() << std::endl;
return false;
}
return true;
}
std::vector<Server> loadServers(const std::string& path) {
std::vector<Server> servers;
std::ifstream file(path);
if (!file.is_open()) {
return servers;
}
try {
json data = json::parse(file);
const auto& machines = data["vpsmc"]["machines"];
for (const auto& machine : machines) {
Server s;
s.id = machine.value("id", -1);
s.nick = machine.value("nick", "N/A");
s.canonical_name = machine.value("canonical_name", "Fetching...");
s.purpose = machine.value("purpose", "N/A");
s.provider = machine.value("ISP", "N/A");
s.hpa = machine.value("ISP_code", "??");
s.monthly_cost_cents = machine.value("monthly_cost_cents", 0);
s.cost_currency = machine.value("cost_currency", "USD");
s.jump_host = machine.value("jump_host", "");
s.reboot_required = machine.value("reboot_required", false);
s.status = machine.value("status", "unknown");
s.last_checked = machine.value("last_checked", "");
if (machine.contains("public_keys") && machine["public_keys"].is_array()) {
for (const auto& key_obj : machine["public_keys"]) {
PublicKey pk;
pk.type = key_obj.value("type", "");
if (key_obj.contains("MD5") && key_obj.at("MD5").is_string()) {
pk.md5 = key_obj.at("MD5");
}
if (key_obj.contains("SHA-256") && key_obj.at("SHA-256").is_string()) {
pk.sha256 = key_obj.at("SHA-256");
}
s.public_keys.push_back(pk);
}
}
if (machine.contains("network")) {
s.network.ipv4 = machine["network"].value("ipv4", "0.0.0.0");
s.network.ipv6 = machine["network"].value("ipv6", "");
}
if (machine.contains("specs")) {
s.specs.cpu_cores = machine["specs"].value("cpu_cores", 0);
s.specs.memory_gb = machine["specs"].value("memory_gb", 0.0);
s.specs.swap_gb = machine["specs"].value("swap_gb", 0.0);
// Support old JSON files that stored the field as "disk_free_percent" (percent free, not used)
if (machine["specs"].contains("disk_used_percent"))
s.specs.disk_used_percent = machine["specs"]["disk_used_percent"].get<double>();
else if (machine["specs"].contains("disk_free_percent"))
s.specs.disk_used_percent = 100.0 - machine["specs"]["disk_free_percent"].get<double>();
else
s.specs.disk_used_percent = -1.0;
s.specs.disk2_used_percent = machine["specs"].value("disk2_used_percent", -1.0);
s.specs.disk3_used_percent = machine["specs"].value("disk3_used_percent", -1.0);
s.specs.disk1_device = machine["specs"].value("disk1_device", std::string(""));
s.specs.disk1_mount = machine["specs"].value("disk1_mount", std::string(""));
s.specs.disk2_device = machine["specs"].value("disk2_device", std::string(""));
s.specs.disk2_mount = machine["specs"].value("disk2_mount", std::string(""));
s.specs.disk3_device = machine["specs"].value("disk3_device", std::string(""));
s.specs.disk3_mount = machine["specs"].value("disk3_mount", std::string(""));
}
if (machine.contains("os")) {
s.os.name = machine["os"].value("name", "N/A");
s.os.version = machine["os"].value("version", "N/A");
}
if (machine.contains("flags")) {
s.flags.c4 = machine["flags"].value("c4", false);
s.flags.o2 = machine["flags"].value("o2", false);
s.flags.s3 = machine["flags"].value("s3", false);
}
if (machine.contains("updates")) {
s.updates.count = machine["updates"].value("count", 0);
s.updates.status = machine["updates"].value("status", "none");
}
if (machine.contains("tags") && machine["tags"].is_array()) {
for(const auto& tag : machine["tags"]) {
s.tags.push_back(tag);
}
}
s.uptime_seconds = -1.0;
s.idle_seconds = -1.0;
s.cpu_load_percent = -1.0;
s.is_checking = false;
servers.push_back(s);
}
} catch (json::parse_error& e) {
std::cerr << "JSON parse error in " << path << ": " << e.what() << std::endl;
} catch (json::type_error& e) {
std::cerr << "JSON type error in " << path << ": " << e.what() << std::endl;
}
return servers;
}
void save_servers(const std::string& path, const std::vector<Server>& servers) {
// Archive the current file as path.v1, path.v2, … before overwriting
if (std::ifstream(path).good()) {
int v = 1;
while (std::ifstream(path + ".v" + std::to_string(v)).good()) ++v;
std::rename(path.c_str(), (path + ".v" + std::to_string(v)).c_str());
}
json j;
j["vpsmc"]["title"] = "Virtual Private Server Master Control";
json machines = json::array();
for(const auto& s : servers) {
json machine_obj;
machine_obj["id"] = s.id;
machine_obj["nick"] = s.nick;
machine_obj["canonical_name"] = s.canonical_name;
machine_obj["network"]["ipv4"] = s.network.ipv4;
machine_obj["network"]["ipv6"] = s.network.ipv6;
machine_obj["ISP"] = s.provider;
machine_obj["ISP_code"] = s.hpa;
machine_obj["monthly_cost_cents"] = s.monthly_cost_cents;
machine_obj["cost_currency"] = s.cost_currency;
if (!s.jump_host.empty()) {
machine_obj["jump_host"] = s.jump_host;
}
machine_obj["purpose"] = s.purpose;
machine_obj["specs"]["cpu_cores"] = s.specs.cpu_cores;
machine_obj["specs"]["memory_gb"] = s.specs.memory_gb;
machine_obj["specs"]["swap_gb"] = s.specs.swap_gb;
machine_obj["specs"]["disk_used_percent"] = s.specs.disk_used_percent;
machine_obj["specs"]["disk2_used_percent"] = s.specs.disk2_used_percent;
machine_obj["specs"]["disk3_used_percent"] = s.specs.disk3_used_percent;
machine_obj["specs"]["disk1_device"] = s.specs.disk1_device;
machine_obj["specs"]["disk1_mount"] = s.specs.disk1_mount;
machine_obj["specs"]["disk2_device"] = s.specs.disk2_device;
machine_obj["specs"]["disk2_mount"] = s.specs.disk2_mount;
machine_obj["specs"]["disk3_device"] = s.specs.disk3_device;
machine_obj["specs"]["disk3_mount"] = s.specs.disk3_mount;
machine_obj["os"]["name"] = s.os.name;
machine_obj["os"]["version"] = s.os.version;
machine_obj["flags"]["c4"] = s.flags.c4;
machine_obj["flags"]["o2"] = s.flags.o2;
machine_obj["flags"]["s3"] = s.flags.s3;
machine_obj["reboot_required"] = s.reboot_required;
machine_obj["updates"]["count"] = s.updates.count;
machine_obj["updates"]["status"] = s.updates.status;
machine_obj["status"] = s.status;
machine_obj["tags"] = s.tags;
machine_obj["last_checked"] = s.last_checked;
json keys = json::array();
for(const auto& pk : s.public_keys) {
json key_obj;
key_obj["type"] = pk.type;
key_obj["MD5"] = pk.md5;
key_obj["SHA-256"] = pk.sha256;
keys.push_back(key_obj);
}
machine_obj["public_keys"] = keys;
machines.push_back(machine_obj);
}
j["vpsmc"]["machines"] = machines;
std::ofstream file(path);
file << j.dump(4);
}
std::map<std::string, double> load_exchange_rates(const std::string& path, const Config& config) {
std::map<std::string, double> rates_map;
std::ifstream file(path);
if (!file.is_open()) {
log_message(config.log_directory_path, "EXCHANGE_RATE_ERROR", "Could not open " + path);
return rates_map;
}
try {
json data = json::parse(file);
if (data.contains("rates")) {
const auto& rates = data["rates"];
for (auto& [key, val] : rates.items()) {
if (val.is_number()) {
rates_map[key] = val;
}
}
}
} catch (json::parse_error& e) {
log_message(config.log_directory_path, "EXCHANGE_RATE_ERROR", "JSON parse error: " + std::string(e.what()));
} catch (json::type_error& e) {
log_message(config.log_directory_path, "EXCHANGE_RATE_ERROR", "JSON type error: " + std::string(e.what()));
}
return rates_map;
}
std::string get_timestamp() {
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
ss << std::put_time(std::localtime(&in_time_t), "[%Y-%m-%d %X]");
return ss.str();
}
void log_message(const std::string& log_dir, const std::string& server_nick, const std::string& message) {
std::lock_guard<std::mutex> lock(log_mutex);
std::string log_file_path = log_dir + "/vpsmc.log";
std::ofstream log_file(log_file_path, std::ios_base::app);
if(log_file.is_open()){
log_file << get_timestamp() << " [" << server_nick << "] " << message << std::endl;
}
}
static bool is_local_server(const Server& server) {
char buf[256] = {};
if (gethostname(buf, sizeof(buf)) != 0) return false;
std::string h = buf;
if (server.nick == h || server.canonical_name == h) return true;
// Also match when gethostname returns short name and canonical_name is FQDN
auto dot = server.canonical_name.find('.');
if (dot != std::string::npos && server.canonical_name.substr(0, dot) == h) return true;
return false;
}
std::string get_ssh_command_prefix(const Server& server) {
if (is_local_server(server)) return "sh -c";
if (server.jump_host.empty()) {
return "ssh -o ConnectTimeout=10 " + server.nick;
}
return "ssh -J " + server.jump_host + " -o ConnectTimeout=10 " + server.nick;
}
std::string get_status_check_command(const Server& server, bool verbose) {
std::string cmd;
std::string os_name_lower = server.os.name;
for (char &c : os_name_lower) { c = tolower(c); }
std::string sudo_prefix = (server.ssh_user == "root") ? "" : "sudo ";
const std::string redirect = verbose ? "" : " 2>/dev/null";
std::string ssh_prefix = get_ssh_command_prefix(server);
if (os_name_lower.find("ubuntu") != std::string::npos ||
os_name_lower.find("debian") != std::string::npos ||
os_name_lower.find("raspbian") != std::string::npos) {
cmd = ssh_prefix + " 'REBOOT_STATUS=0; if [ -f /var/run/reboot-required ]; then REBOOT_STATUS=1; fi; UPDATE_COUNT=$(apt list --upgradable 2>/dev/null | grep -vc \"Listing...\"); echo \"$REBOOT_STATUS;$UPDATE_COUNT\"'" + redirect;
} else if (os_name_lower.find("rocky") != std::string::npos ||
os_name_lower.find("almalinux") != std::string::npos ||
os_name_lower.find("centos") != std::string::npos) {
cmd = ssh_prefix + " '" + sudo_prefix + "needs-restarting -r >/dev/null; REBOOT_STATUS=$?; UPDATE_COUNT=$( " + sudo_prefix + "dnf check-update --quiet | wc -l); echo \"$REBOOT_STATUS;$UPDATE_COUNT\"'" + redirect;
}
return cmd;
}
void fetch_ssh_user(Server* server, std::mutex* mtx) {
std::string user = "default";
std::string cmd = "ssh -G " + server->nick + " | awk '/^user / { print $2 }' 2>/dev/null";
std::array<char, 128> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
if (pipe) {
if (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
user = buffer.data();
if (!user.empty() && user.back() == '\n') user.pop_back();
}
pclose(pipe);
}
if (user == "default" || user.empty()){
const char* current_user = getenv("USER");
if(current_user != nullptr) user = current_user;
else user = "unknown";
}
std::lock_guard<std::mutex> lock(*mtx);
server->ssh_user = user;
}
void fetch_uptime(Server* server, std::mutex* mtx) {
double uptime_val = -2.0;
double idle_val = -2.0;
std::string cmd = get_ssh_command_prefix(*server) + " \"cat /proc/uptime\" 2>/dev/null";
std::array<char, 128> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
if (pipe) {
if (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
std::stringstream ss(buffer.data());
ss >> uptime_val >> idle_val;
}
pclose(pipe);
}
std::lock_guard<std::mutex> lock(*mtx);
server->uptime_seconds = uptime_val;
server->idle_seconds = idle_val;
}
void fetch_cpu_cores(Server* server, std::mutex* mtx) {
int cores = 0;
std::string cmd = get_ssh_command_prefix(*server) + " \"nproc\" 2>/dev/null";
std::array<char, 64> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
if (pipe) {
if (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
try { cores = std::stoi(buffer.data()); } catch (...) { cores = 0; }
}
pclose(pipe);
}
std::lock_guard<std::mutex> lock(*mtx);
if (cores > 0) server->specs.cpu_cores = cores;
}
void fetch_os_info(Server* server, std::mutex* mtx) {
std::string name, version;
std::string cmd = get_ssh_command_prefix(*server) + " \"cat /etc/os-release\" 2>/dev/null";
std::array<char, 256> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
if (pipe) {
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
std::string line = buffer.data();
if (!line.empty() && line.back() == '\n') line.pop_back();
// Strip surrounding quotes from value
auto strip_quotes = [](std::string s) {
if (s.size() >= 2 && s.front() == '"' && s.back() == '"')
return s.substr(1, s.size() - 2);
return s;
};
if (line.substr(0, 5) == "NAME=")
name = strip_quotes(line.substr(5));
else if (line.substr(0, 11) == "VERSION_ID=")
version = strip_quotes(line.substr(11));
}
pclose(pipe);
}
if (name.empty()) return;
std::lock_guard<std::mutex> lock(*mtx);
server->os.name = name;
server->os.version = version;
}
void fetch_canonical_name(Server* server, std::mutex* mtx) {
if (!server->canonical_name.empty() && server->canonical_name != "Fetching...") {
return; // Do not fetch if already populated
}
std::string result = "DNS Failed";
std::string cmd = "dig -x " + server->network.ipv4 + " +short 2>/dev/null";
std::array<char, 256> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
if(pipe) {
if (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
result = buffer.data();
if (!result.empty() && result.back() == '\n') result.pop_back();
if (!result.empty() && result.back() == '.') result.pop_back();
}
pclose(pipe);
}
if (result.empty()) { result = "No rDNS Record"; }
std::lock_guard<std::mutex> lock(*mtx);
server->canonical_name = result;
}
void fetch_swap_info(Server* server, std::mutex* mtx) {
double swap_gb = 0.0;
std::string cmd = get_ssh_command_prefix(*server) + " \"free -b | awk 'NR==3{printf \\\"%.3f\\\", \\$2/1073741824}'\" 2>/dev/null";
std::array<char, 128> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
if(pipe) {
if(fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
try { swap_gb = std::stod(buffer.data()); } catch(...) { /* keep 0.0 */ }
}
pclose(pipe);
}
std::lock_guard<std::mutex> lock(*mtx);
server->specs.swap_gb = swap_gb;
}
void fetch_disk_info(Server* server, std::mutex* mtx) {
double pct[3] = {-1.0, -1.0, -1.0};
std::string devices[3], mounts[3];
int count = 0;
// -P: POSIX format (no line-wrapping for long device names).
// Filter real block devices; exclude loop devices (snap packages show as /dev/loop*
// and are always 100% full since they are read-only squashfs images).
std::string cmd = get_ssh_command_prefix(*server) +
" \"df -P | grep '^/dev/' | grep -v '^/dev/loop' | awk '{print \\$1, \\$(NF-1), \\$NF}'\" 2>/dev/null";
std::array<char, 256> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
if (pipe) {
while (count < 3 && fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
char dev[128], pct_str[16], mnt[128];
if (sscanf(buffer.data(), "%127s %15s %127s", dev, pct_str, mnt) == 3) {
// Strip trailing '%' from Use% field
char* p = strchr(pct_str, '%');
if (p) *p = '\0';
try {
pct[count] = std::stod(pct_str);
devices[count] = dev;
mounts[count] = mnt;
count++;
} catch (...) { /* skip unparseable lines */ }
}
}
pclose(pipe);
}
if (count > 0) {
std::lock_guard<std::mutex> lock(*mtx);
server->specs.disk_used_percent = pct[0];
server->specs.disk2_used_percent = pct[1];
server->specs.disk3_used_percent = pct[2];
server->specs.disk1_device = devices[0]; server->specs.disk1_mount = mounts[0];
server->specs.disk2_device = devices[1]; server->specs.disk2_mount = mounts[1];
server->specs.disk3_device = devices[2]; server->specs.disk3_mount = mounts[2];
}
}
void check_server_status(Server* server, std::mutex* mtx, const Config& config) {
std::string cmd = get_status_check_command(*server, false);
if(cmd.empty()) {
std::lock_guard<std::mutex> lock(*mtx);
server->is_checking = false;
return;
}
bool found_reboot = false;
int update_count = 0;
std::array<char, 256> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
if (pipe) {
if (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
std::string line = buffer.data();
size_t separator_pos = line.find(';');
if (separator_pos != std::string::npos) {
try {
found_reboot = (std::stoi(line.substr(0, separator_pos)) == 1);
update_count = std::stoi(line.substr(separator_pos + 1));
} catch (...) {
log_message(config.log_directory_path, server->nick, "Failed to parse status: " + line);
}
} else {
log_message(config.log_directory_path, server->nick, "Unexpected status output: " + line);
}
}
pclose(pipe);
}
{
std::lock_guard<std::mutex> lock(*mtx);
server->reboot_required = found_reboot;
server->updates.count = update_count;
server->updates.status = (update_count > 0) ? "pending" : "none";
server->is_checking = false;
}
}
void fetch_logged_in_users(Server& server, const Config& config, bool force_refresh) {
std::string cache_path = config.log_directory_path + "/w." + server.nick + ".log";
server.reboot_checks.logged_in_users_cache.clear();
if (!force_refresh) {
std::ifstream cache_file(cache_path);
if (cache_file.is_open()) {
std::string line;
while (std::getline(cache_file, line)) {
server.reboot_checks.logged_in_users_cache.push_back(line);
}
return;
}
}
// If cache doesn't exist or refresh is forced, fetch live data
std::string cmd = get_ssh_command_prefix(server) + " \"w\" 2>/dev/null";
std::array<char, 256> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
std::ofstream new_cache_file(cache_path);
if (pipe) {
int line_count = 0;
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
line_count++;
if(line_count <= 2) continue; // Skip the header of 'w' command
std::string line = buffer.data();
if (!line.empty() && line.back() == '\n') {
line.pop_back();
}
if(!line.empty()) {
server.reboot_checks.logged_in_users_cache.push_back(line);
if (new_cache_file.is_open()) {
new_cache_file << line << std::endl;
}
}
}
pclose(pipe);
}
}
void fetch_user_count(Server* server, std::mutex* mtx) {
int count = -1;
std::string cmd = get_ssh_command_prefix(*server) + " \"who | wc -l\" 2>/dev/null";
std::array<char, 128> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
if(pipe) {
if(fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
try { count = std::stoi(buffer.data()); } catch(...) { /* keep -1 */ }
}
pclose(pipe);
}
std::lock_guard<std::mutex> lock(*mtx);
server->reboot_checks.user_count = count;
}
void fetch_open_files(Server& server, const Config& config, bool force_refresh) {
std::string cache_path = config.log_directory_path + "/ofl." + server.nick + ".log";
server.reboot_checks.open_files_cache.clear();
int count = 0;
if (!force_refresh) {
std::ifstream cache_file(cache_path);
if (cache_file.is_open()) {
std::string line;
while (std::getline(cache_file, line)) {
server.reboot_checks.open_files_cache.push_back(line);
}
server.reboot_checks.open_files_count = server.reboot_checks.open_files_cache.size();
return;
}
}
std::string cmd = get_ssh_command_prefix(server) + " \"find / -xdev -name '*.swp' 2>/dev/null\"";
std::array<char, 256> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
std::ofstream new_cache_file(cache_path);
if (pipe) {
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
std::string line = buffer.data();
if (!line.empty() && line.back() == '\n') {
line.pop_back();
}
if(!line.empty()) {
server.reboot_checks.open_files_cache.push_back(line);
if (new_cache_file.is_open()) {
new_cache_file << line << std::endl;
}
count++;
}
}
pclose(pipe);
}
server.reboot_checks.open_files_count = count;
}
void fetch_user_reboot_locks(Server& server, const Config& config, bool force_refresh) {
std::string cache_path = config.log_directory_path + "/ulk." + server.nick + ".log";
server.reboot_checks.user_locks_cache.clear();
int count = 0;
if (!force_refresh) {
std::ifstream cache_file(cache_path);
if (cache_file.is_open()) {
std::string line;
while (std::getline(cache_file, line)) {
server.reboot_checks.user_locks_cache.push_back(line);
}
server.reboot_checks.user_reboot_locks = server.reboot_checks.user_locks_cache.size();
return;
}
}
std::string cmd = get_ssh_command_prefix(server) + " \"find /home -name NOREBOOT 2>/dev/null\"";
std::array<char, 256> buffer;
FILE* pipe = popen(cmd.c_str(), "r");
std::ofstream new_cache_file(cache_path);
if (pipe) {
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
std::string line = buffer.data();
if (!line.empty() && line.back() == '\n') {
line.pop_back();
}
if(!line.empty()) {
server.reboot_checks.user_locks_cache.push_back(line);
if (new_cache_file.is_open()) {
new_cache_file << line << std::endl;
}
count++;
}
}
pclose(pipe);
}
server.reboot_checks.user_reboot_locks = count;
}
void fetch_data_saved_flag(Server* server, std::mutex* mtx) {
std::string cmd = get_ssh_command_prefix(*server) + " '[ -f ~/.vpsmc/data_saved.flag ] && echo 1 || echo 0' 2>/dev/null";
std::array<char, 128> buffer;
bool saved = false;
FILE* pipe = popen(cmd.c_str(), "r");
if(pipe) {
if(fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
try { saved = (std::stoi(buffer.data()) == 1); } catch(...) { /* keep false */ }
}
pclose(pipe);
}
std::lock_guard<std::mutex> lock(*mtx);
server->reboot_checks.data_saved = saved;
}
void fetch_history_saved_flag(Server* server, std::mutex* mtx) {
std::string cmd = get_ssh_command_prefix(*server) + " '[ -f ~/.vpsmc/history_saved.flag ] && echo 1 || echo 0' 2>/dev/null";
std::array<char, 128> buffer;
bool saved = false;
FILE* pipe = popen(cmd.c_str(), "r");
if(pipe) {
if(fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
try { saved = (std::stoi(buffer.data()) == 1); } catch(...) { /* keep false */ }
}
pclose(pipe);
}
std::lock_guard<std::mutex> lock(*mtx);
server->reboot_checks.history_saved = saved;
}
void fetch_log_uploaded_flag(Server* server, std::mutex* mtx) {
std::string cmd = get_ssh_command_prefix(*server) + " '[ -f ~/.vpsmc/uplog.completed ] && echo 1 || echo 0' 2>/dev/null";
std::array<char, 128> buffer;
bool uploaded = false;
FILE* pipe = popen(cmd.c_str(), "r");
if(pipe) {
if(fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
try { uploaded = (std::stoi(buffer.data()) == 1); } catch(...) { /* keep false */ }
}
pclose(pipe);
}
std::lock_guard<std::mutex> lock(*mtx);
server->reboot_checks.log_uploaded = uploaded;
}