-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpeer_client.cpp
More file actions
387 lines (320 loc) · 9.96 KB
/
peer_client.cpp
File metadata and controls
387 lines (320 loc) · 9.96 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
#include "peer_client.h"
#include "server_utils.h"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sstream>
#include <cstdio>
#include <poll.h>
#include <fcntl.h>
using namespace srv;
// static int connect_tcp(const std::string& ip, uint16_t port) { // Depecrated
// int fd = ::socket(AF_INET, SOCK_STREAM, 0);
// if (fd < 0) {
// return -1;
// }
// sockaddr_in addr{};
// addr.sin_family = AF_INET;
// addr.sin_port = htons(port);
// if (inet_pton(AF_INET, ip.c_str(), &addr.sin_addr) != 1) {
// ::close(fd);
// return -1;
// }
// if (::connect(fd, (sockaddr*)&addr, sizeof(addr)) < 0) {
// ::close(fd);
// return -1;
// }
// return fd;
// }
int PeerClient::connect_with_timeout_ipv4(const std::string& ip, uint16_t port, int ms_timeout) {
int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
return -1;
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (inet_pton(AF_INET, ip.c_str(), &addr.sin_addr) != 1) {
::close(fd);
return -1;
}
int rc = ::connect(fd, (sockaddr*)&addr, sizeof(addr));
if (rc == 0) {
fcntl(fd, F_SETFL, flags);
return fd;
}
if (rc < 0 && errno != EINPROGRESS) {
::close(fd);
return -1;
}
pollfd pfd{fd, POLLOUT, 0};
rc = ::poll(&pfd, 1, ms_timeout); // Timeout
if (rc == 1 && (pfd.revents & POLLOUT)) {
int err = 0;
socklen_t len = sizeof(err);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len);
if (err == 0) {
fcntl(fd, F_SETFL, flags);
return fd;
}
}
::close(fd);
return -1;
}
PeerClient::PeerClient(const std::string& ip, uint16_t port, const std::string& our_advertised_ip)
: cfd(-1), peer_ip(ip), peer_port(port + 200/*Adding 200 to peer port like seen in p2 handout*/), our_ip(our_advertised_ip) {
cfd = connect_with_timeout_ipv4(peer_ip, peer_port, /*ms*/ 120); // 0.12s
if (cfd < 0) return;
if (cfd >= 0 && expect_greeting() && login_peer()) {
// ok
} else {
if (cfd >= 0) {
::close(cfd);
}
cfd = -1;
}
}
PeerClient::~PeerClient() {
if (cfd >= 0) {
send_line("QUIT\r\n");
::close(cfd);
}
}
PeerClient::Reply PeerClient::read_reply() {
if (cfd < 0)
return {};
std::string line;
char ch;
while (true) {
ssize_t r = ::recv(cfd, &ch, 1, 0);
if (r == 1) {
if (ch == '\r')
continue;
if (ch == '\n')
break;
line.push_back(ch);
} else {
// timeout or disconnect
break;
}
}
PeerClient::Reply out;
out.raw = line;
parse_reply_code(line, out.code);
return out;
}
bool PeerClient::send_cmd(const std::string& line) {
if (cfd < 0)
return false;
std::string buf = line; buf += "\r\n";
const char* p = buf.data();
size_t n = buf.size();
while (n) {
ssize_t w = ::send(cfd, p, n, 0);
if (w < 0) { if (errno == EINTR)
continue;
return false;
}
p += w; n -= size_t(w);
}
return true;
}
bool PeerClient::send_line(const std::string& s) {
return send_all(cfd, s.data(), s.size()) == 0;
}
std::optional<std::string> PeerClient::recv_line() {
return srv::recv_line(cfd);
}
bool PeerClient::expect_greeting() {
auto line = recv_line();
if (!line)
return false;
srv::rtrim_crlf(*line);
return line->rfind("220", 0) == 0;
}
bool PeerClient::login_peer() {
std::string cmd = "USER peer@" + our_ip + "\r\n";
if (!send_line(cmd))
return false;
auto line = recv_line();
if (!line)
return false;
srv::rtrim_crlf(*line);
// expect 230
return line->rfind("230", 0) == 0;
}
bool PeerClient::cwd(const std::string& path_rel) {
std::string cmd = "CWD " + path_rel + "\r\n";
if (!send_line(cmd))
return false;
auto line = recv_line();
if (!line)
return false;
srv::rtrim_crlf(*line);
// good if 250 or 200
return line->rfind("250", 0) == 0 || line->rfind("200", 0) == 0;
}
std::optional<std::tuple<std::string,int,int>> PeerClient::pasv() {
if (!send_line("PASV\r\n"))
return std::nullopt;
auto line = recv_line();
if (!line)
return std::nullopt;
srv::rtrim_crlf(*line);
if (line->rfind("227", 0) != 0)
return std::nullopt;
auto l = *line;
auto lp = l.find('(');
auto rp = l.find(')');
if (lp == std::string::npos || rp == std::string::npos || rp <= lp+1)
return std::nullopt;
std::string inner = l.substr(lp+1, rp-lp-1);
int h1,h2,h3,h4,p1,p2;
if (sscanf(inner.c_str(), "%d,%d,%d,%d,%d,%d", &h1,&h2,&h3,&h4,&p1,&p2) != 6)
return std::nullopt;
std::ostringstream ipt;
ipt << h1 << "," << h2 << "," << h3 << "," << h4;
return std::make_tuple(ipt.str(), p1, p2);
}
std::vector<std::string> PeerClient::list(const std::string& opt_path) {
auto pasv_info = pasv();
if (!pasv_info)
return {};
auto [ip_tuple, p1, p2] = *pasv_info;
int h1,h2,h3,h4;
sscanf(ip_tuple.c_str(), "%d,%d,%d,%d", &h1,&h2,&h3,&h4);
char ipbuf[64];
snprintf(ipbuf, sizeof(ipbuf), "%d.%d.%d.%d", h1,h2,h3,h4);
uint16_t port = (uint16_t)(p1*256 + p2);
int dfd = ::socket(AF_INET, SOCK_STREAM, 0);
if (dfd < 0)
return {};
sockaddr_in a{}; a.sin_family=AF_INET; a.sin_port=htons(port);
inet_pton(AF_INET, ipbuf, &a.sin_addr);
if (::connect(dfd, (sockaddr*)&a, sizeof(a)) < 0) {
::close(dfd);
return {};
}
std::string cmd = opt_path.empty() ? "LIST\r\n" : ("LIST " + opt_path + "\r\n");
if (!send_line(cmd)) {
::close(dfd);
return {};
}
// skip pre data
auto pre = recv_line();
(void)pre;
std::string payload;
char buf[4096];
while (true) {
ssize_t n = ::recv(dfd, buf, sizeof(buf), 0);
if (n <= 0)
break;
payload.append(buf, buf+n);
}
::close(dfd);
// skip post data
auto post = recv_line();
(void)post;
std::vector<std::string> lines;
std::string cur;
for (char c : payload) {
if (c == '\r')
continue;
if (c == '\n') {
if (!cur.empty()) {
lines.push_back(cur);
cur.clear();
}
}
else
cur.push_back(c);
}
if (!cur.empty())
lines.push_back(cur);
// Rewrite lines to match local 'ls -l' format:
// perms, nlink(=1), owner="peer", size(dir=0 else keep), time, name
// This makes peer output symmetrical with local formatting for easier merging later
for (std::string& s : lines) {
// split on spaces
std::vector<std::string> tok;
tok.reserve(12);
std::string t;
for (size_t i = 0; i < s.size(); ++i) {
if (s[i] == ' ') {
if (!t.empty()) {
tok.push_back(t);
t.clear();
}
// skip consecutive spaces
while (i+1 < s.size() && s[i+1] == ' ')
++i;
} else {
t.push_back(s[i]);
}
}
if (!t.empty())
tok.push_back(t);
// Expect at least: perms, nlink, owner, group, size, Mon, DD, HH:MM, name
if (tok.size() >= 9) {
const bool is_dir = !tok[0].empty() && tok[0][0] == 'd';
const std::string perms = is_dir ? "drwxr-xr-x" : "-rw-r--r--"; // normalize perms to sample
const std::string nlink = "1"; // force link count to 1
const std::string owner = "peer"; // owner label "peer"
const std::string size = is_dir ? "0" : tok[4]; // dir size 0; keep file size
const std::string mon = tok[5];
const std::string day = tok[6];
const std::string hm = tok[7];
// rejoin name (in case it contains spacest)
std::string name;
for (size_t i = 8; i < tok.size(); ++i) {
if (!name.empty()) name.push_back(' ');
name += tok[i];
}
// build the rewritten line
s = perms + " " + nlink + " " + owner + " " + size + " " + mon + " " + day + " " + hm + " " + name; // rebuild in required layout
}
// else leave the line as is if it didn't parse
}
return lines;
}
bool PeerClient::file_exists(const std::string& rel_path) {
auto lines = list(rel_path);
return !lines.empty();
}
int PeerClient::retr_forward(const std::string& rel_path, std::string* first_line, std::string* final_line) {
std::string cmd = "RETR " + rel_path + "\r\n";
if (!send_line(cmd))
return -1;
auto l1 = recv_line();
if (!l1)
return -1;
srv::rtrim_crlf(*l1);
if (first_line)
*first_line = *l1;
int code = 0;
sscanf(l1->c_str(), "%d", &code);
if (code >= 400) {
if (final_line) *final_line = *l1;
return code;
}
auto l2 = recv_line();
if (!l2)
return -1;
srv::rtrim_crlf(*l2);
if (final_line)
*final_line = *l2;
int final_code = 0;
sscanf(l2->c_str(), "%d", &final_code);
return final_code;
}
bool PeerClient::parse_reply_code(const std::string& line, int& code_out) {
if (line.size() >= 3 && std::isdigit((unsigned char)line[0]) &&
std::isdigit((unsigned char)line[1]) && std::isdigit((unsigned char)line[2])) {
code_out = (line[0]-'0')*100 + (line[1]-'0')*10 + (line[2]-'0');
return true;
}
code_out = 0;
return false;
}