-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_utils.cpp
More file actions
563 lines (490 loc) · 15.1 KB
/
server_utils.cpp
File metadata and controls
563 lines (490 loc) · 15.1 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
#include "server_utils.h"
#include <algorithm>
#include <cerrno>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pwd.h>
#include <grp.h>
#include <netdb.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctime>
#include <sstream>
#include <iostream>
#include <ifaddrs.h>
#include <net/if.h>
#include <deque>
namespace fs = std::filesystem;
namespace srv {
void to_upper(std::string& s) {
for (auto& ch : s) {
if (ch >= 'a' && ch <= 'z')
ch = static_cast<char>(ch - 'a' + 'A');
}
}
void rtrim_crlf(std::string& s) {
while (!s.empty() && (s.back() == '\r' || s.back() == '\n'))
s.pop_back();
}
std::vector<std::string> split_ws(const std::string& s) {
std::vector<std::string> out;
std::string cur;
bool in_token = false;
for (char c : s) {
if (c == ' ' || c == '\t') {
if (in_token) {
out.push_back(cur);
cur.clear();
in_token = false;
}
} else {
cur.push_back(c);
in_token = true;
}
}
if (in_token)
out.push_back(cur);
return out;
}
std::string with_crlf(const std::string& s) {
if (s.size() >= 2 && s[s.size()-2]=='\r' && s[s.size()-1]=='\n')
return s;
return s + "\r\n";
}
std::optional<std::string> recv_line(int fd) {
std::string buf;
char c;
while (true) {
ssize_t n = ::recv(fd, &c, 1, 0);
if (n == 0) {
return std::nullopt; // EOF
} else if (n < 0) {
if (errno == EINTR)
continue;
return std::nullopt;
}
buf.push_back(c);
if (c == '\n')
break;
if (buf.size() > 8192)
break; // arb hard cap
}
return buf;
}
int send_all(int fd, const void* buf, size_t len) {
const char* p = static_cast<const char*>(buf);
size_t left = len;
while (left > 0) {
ssize_t n = ::send(fd, p, left, 0);
if (n < 0) {
if (errno == EINTR)
continue;
return -1;
}
left -= (size_t)n;
p += n;
}
return 0;
}
int send_reply(int fd, const std::string& line) {
std::string out = with_crlf(line);
return send_all(fd, out.data(), out.size());
}
std::optional<uint32_t> get_local_ipv4(int fd) {
sockaddr_in addr{};
socklen_t len = sizeof(addr);
if (::getsockname(fd, (sockaddr*)&addr, &len) < 0)
return std::nullopt;
return ntohl(addr.sin_addr.s_addr);
}
std::string ipv4_to_tuple(uint32_t ip) {
uint8_t h1 = (ip >> 24) & 0xFF;
uint8_t h2 = (ip >> 16) & 0xFF;
uint8_t h3 = (ip >> 8) & 0xFF;
uint8_t h4 = (ip) & 0xFF;
std::ostringstream oss;
oss << (int)h1 << "," << (int)h2 << "," << (int)h3 << "," << (int)h4;
return oss.str();
}
std::pair<int, uint16_t> open_passive_listener(int control_fd) {
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
return {-1, 0};
// Bind to the same local address family
// port 0 for ephemeral port
sockaddr_in local{};
local.sin_family = AF_INET;
// Prefer binding to the same address as control socket if possible
sockaddr_in ctrl{};
socklen_t len = sizeof(ctrl);
if (::getsockname(control_fd, (sockaddr*)&ctrl, &len) == 0) {
local.sin_addr = ctrl.sin_addr;
} else {
local.sin_addr.s_addr = htonl(INADDR_ANY);
}
local.sin_port = 0;
int opt = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if (::bind(fd, (sockaddr*)&local, sizeof(local)) < 0) {
::close(fd);
return {-1, 0};
}
if (::listen(fd, 1) < 0) {
::close(fd);
return {-1, 0};
}
sockaddr_in bound{};
socklen_t blen = sizeof(bound);
if (::getsockname(fd, (sockaddr*)&bound, &blen) < 0) {
::close(fd);
return {-1, 0};
}
return {fd, ntohs(bound.sin_port)};
}
int accept_one(int listen_fd) {
sockaddr_in peer{};
socklen_t plen = sizeof(peer);
int dfd = ::accept(listen_fd, (sockaddr*)&peer, &plen);
return dfd;
}
void close_fd(int fd) {
if (fd >= 0)
::close(fd);
}
static bool starts_with(const std::string& s, const std::string& p) {
return s.size() >= p.size() && std::equal(p.begin(), p.end(), s.begin());
}
std::optional<std::string> resolve_path_in_jail(const std::string& jail_root, const std::string& cwd_rel, const std::string& input_path) {
try {
fs::path jail = fs::weakly_canonical(fs::path(jail_root));
if (!fs::exists(jail))
return std::nullopt;
fs::path base = jail;
if (!cwd_rel.empty() && cwd_rel != "/")
base /= fs::path(cwd_rel).relative_path();
fs::path candidate;
if (input_path.empty()) {
candidate = base;
} else {
if (!input_path.empty() && input_path[0] == '/') {
candidate = jail / fs::path(input_path.substr(1)).relative_path();
} else {
candidate = base / fs::path(input_path).relative_path();
}
}
fs::path resolved = fs::weakly_canonical(candidate);
std::string jail_str = jail.string();
std::string resolved_str = resolved.string();
// Ensure trailing slash logic for jail
std::string jail_pref = jail_str;
if (!jail_pref.empty() && jail_pref.back() != '/')
jail_pref.push_back('/');
if (resolved_str == jail_str || starts_with(resolved_str + "/", jail_pref)) {
return resolved_str;
} else {
return std::nullopt;
}
} catch (...) {
return std::nullopt;
}
}
static std::string perms_string(mode_t m) {
std::string s(10, '-');
// file type
if (S_ISDIR(m)) s[0]='d';
else if (S_ISLNK(m)) s[0]='l';
else if (S_ISCHR(m)) s[0]='c';
else if (S_ISBLK(m)) s[0]='b';
else if (S_ISSOCK(m)) s[0]='s';
else if (S_ISFIFO(m)) s[0]='p';
// rwx portions
const char rwx[9] = {
(m & S_IRUSR)?'r':'-', (m & S_IWUSR)?'w':'-', (m & S_IXUSR)?'x':'-',
(m & S_IRGRP)?'r':'-', (m & S_IWGRP)?'w':'-', (m & S_IXGRP)?'x':'-',
(m & S_IROTH)?'r':'-', (m & S_IWOTH)?'w':'-', (m & S_IXOTH)?'x':'-'
};
for (int i=0;i<9;i++)
s[1+i]=rwx[i];
// setuid/setgid/sticky
if (m & S_ISUID) s[3] = (s[3]=='x')?'s':'S';
if (m & S_ISGID) s[6] = (s[6]=='x')?'s':'S';
if (m & S_ISVTX) s[9] = (s[9]=='x')?'t':'T';
return s;
}
std::string ls_long_entry(const std::string& abs_path, const std::string& name) {
struct stat st{};
if (::lstat(abs_path.c_str(), &st) < 0)
return "";
std::ostringstream oss;
// normalize perms display to match sample dir: drwxr-xr-x or file: -rw-r--r--
const bool is_dir = S_ISDIR(st.st_mode);
oss << (is_dir ? "drwxr-xr-x" : "-rw-r--r--") << ' ';
// force link count to 1 to match sample output format
oss << 1 << ' ';
// owner column must be "local" but we rewrite with peer/local later
// so just put placeholder here
oss << "local" << ' ';
// directory size should be shown as 0
// keep real size for files
oss << (is_dir ? 0 : static_cast<long long>(st.st_size)) << ' ';
// time
char tbuf[64];
std::tm tm{};
std::time_t tt = st.st_mtime;
localtime_r(&tt, &tm);
// kept "Mon DD HH:MM" like coded before
if (std::strftime(tbuf, sizeof(tbuf), "%b %e %H:%M", &tm) == 0) {
std::strncpy(tbuf, "Jan 1 00:00", sizeof(tbuf));
}
oss << tbuf << ' ';
oss << name;
return oss.str();
}
std::string ls_long_directory(const std::string& abs_dir) {
try {
if (!fs::is_directory(abs_dir))
return "";
std::ostringstream oss;
for (auto& entry : fs::directory_iterator(abs_dir)) {
std::string name = entry.path().filename().string();
std::string line = ls_long_entry(entry.path().string(), name);
if (line.empty())
continue;
oss << line << "\r\n";
}
std::string out = oss.str();
if (!out.empty() && out.size()>=2 && out.substr(out.size()-2)=="\r\n") {
out.erase(out.size()-2);
}
return out;
} catch (...) {
return "";
}
}
int stream_file_to_fd(const std::string& abs_path, int out_fd) {
int fd = ::open(abs_path.c_str(), O_RDONLY);
if (fd < 0)
return -1;
char buf[64 * 1024];
while (true) {
ssize_t n = ::read(fd, buf, sizeof(buf));
if (n == 0)
break;
if (n < 0) {
::close(fd);
return -1;
}
if (send_all(out_fd, buf, (size_t)n) < 0) {
::close(fd);
return -1;
}
}
::close(fd);
return 0;
}
uint16_t read_port_from_config(const std::string& conf_path, uint16_t default_port) {
std::ifstream f(conf_path);
if (!f)
return default_port;
std::string line;
while (std::getline(f, line)) {
// trim
auto poshash = line.find('#');
if (poshash != std::string::npos)
line = line.substr(0, poshash);
auto eq = line.find('=');
if (eq == std::string::npos)
continue;
std::string key = line.substr(0, eq);
std::string val = line.substr(eq+1);
auto trim = [](std::string& s){
while(!s.empty() && (s.back()==' '||s.back()=='\t'||s.back()=='\r'||s.back()=='\n'))
s.pop_back();
size_t i=0;
while (i<s.size() && (s[i]==' '||s[i]=='\t'))
i++;
if (i>0)
s.erase(0,i);
};
trim(key); trim(val);
if (key == "PORT") {
try {
int p = std::stoi(val);
if (p>0 && p<65536)
return (uint16_t)p;
} catch (...) {}
}
}
return default_port;
}
std::string read_string_from_config(const std::string& conf_path, const std::string& key, const std::string& defv) {
std::ifstream f(conf_path);
if (!f)
return defv;
std::string line;
auto trim = [](std::string& s) {
while(!s.empty() && (s.back()==' '||s.back()=='\t'||s.back()=='\r'||s.back()=='\n'))
s.pop_back();
size_t i=0;
while (i<s.size()&&(s[i]==' '||s[i]=='\t'))
i++;
if (i)
s.erase(0,i);
};
// trim(lines);
while (std::getline(f, line)) {
auto poshash = line.find('#');
if (poshash != std::string::npos)
line = line.substr(0, poshash);
auto eq = line.find('=');
if (eq == std::string::npos)
continue;
std::string k = line.substr(0, eq), v = line.substr(eq+1);
trim(k);
trim(v);
if (k == key)
return v;
}
return defv;
}
int read_int_from_config(const std::string& conf_path, const std::string& key, int defv) {
std::string s = read_string_from_config(conf_path, key, "");
if (s.empty())
return defv;
try {
return std::stoi(s);
} catch (...) {
return defv;
}
}
static bool is_loopback(const ifaddrs* ifa) {
return (ifa->ifa_flags & IFF_LOOPBACK) != 0;
}
static bool is_up(const ifaddrs* ifa) {
return (ifa->ifa_flags & IFF_UP) != 0;
}
// Prefer an IP inside your PEER_SUBNET if passed
std::string get_primary_ipv4_guess_from_interfaces(/*optional*/ const std::string& prefer_cidr = "") {
struct ifaddrs* ifs = nullptr;
if (getifaddrs(&ifs) != 0)
return "127.0.0.1";
auto free_ifs = [&]{
if (ifs)
freeifaddrs(ifs);
};
// Helper
// check if ip is in CIDR
auto in_cidr = [](const std::string& ip, const std::string& cidr)->bool {
auto slash = cidr.find('/');
if (slash == std::string::npos)
return false;
std::string net_s = cidr.substr(0, slash);
int bits = std::stoi(cidr.substr(slash+1));
in_addr ip_a{}, net_a{};
if (inet_pton(AF_INET, ip.c_str(), &ip_a) != 1)
return false;
if (inet_pton(AF_INET, net_s.c_str(), &net_a) != 1)
return false;
uint32_t ip_h = ntohl(ip_a.s_addr);
uint32_t net_h = ntohl(net_a.s_addr);
uint32_t mask = (bits==0) ? 0 : (0xFFFFFFFFu << (32-bits));
return (ip_h & mask) == (net_h & mask);
};
std::string preferred, nonloopback, loopback;
for (auto* ifa = ifs; ifa; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr)
continue;
if (ifa->ifa_addr->sa_family != AF_INET)
continue;
if (!is_up(ifa))
continue;
char buf[INET_ADDRSTRLEN]{};
auto* sa = reinterpret_cast<sockaddr_in*>(ifa->ifa_addr);
if (!inet_ntop(AF_INET, &sa->sin_addr, buf, sizeof(buf)))
continue;
std::string ip = buf;
if (is_loopback(ifa)) {
if (loopback.empty())
loopback = ip; // usually 127.0.0.1
continue;
}
if (!prefer_cidr.empty() && in_cidr(ip, prefer_cidr)) {
preferred = ip;
break; // best match so stop early
}
if (nonloopback.empty())
nonloopback = ip;
}
free_ifs();
if (!preferred.empty())
return preferred;
if (!nonloopback.empty())
return nonloopback;
if (!loopback.empty())
return loopback;
// fallback
return "127.0.0.1";
}
std::string normalize_rel_path(const std::string& base, const std::string& target) {
auto join = [&](const std::string& a, const std::string& b){
if (b.empty())
return a;
if (!a.empty() && a.back() == '/')
return a + b;
if (b.front() == '/')
return b;
return a.empty() ? ("/" + b) : (a + "/" + b);
};
std::string raw = target.size() && target.front() == '/' ? target : join(base, target);
// split + resolve "." and ".."
std::deque<std::string> stack;
std::string part;
for (size_t i = 0; i <= raw.size(); ++i) {
if (i == raw.size() || raw[i] == '/') {
if (!part.empty()) {
if (part == ".") { /*TODO*/ }
else if (part == "..") {
if (!stack.empty())
stack.pop_back();
} else {
stack.push_back(part);
}
part.clear();
}
} else {
part.push_back(raw[i]);
}
}
std::string out = "/";
bool first = true;
for (auto& s : stack) {
if (!first)
out += "/";
out += s;
first = false;
}
return out;
}
bool send_line(int fd, const std::string& line) {
std::string buf = line;
if (buf.empty() || buf.back() != '\n')
buf += "\r\n";
const char* p = buf.data();
size_t n = buf.size();
while (n) {
ssize_t w = ::send(fd, p, n, 0);
if (w < 0) {
if (errno == EINTR)
continue;
return false;
}
p += w;
n -= size_t(w);
}
return true;
}
} // namespace srv