-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
520 lines (441 loc) · 22.6 KB
/
Copy pathserver.cpp
File metadata and controls
520 lines (441 loc) · 22.6 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
#include "helpers.h"
using namespace std;
// Structure for a subscriber
struct Client {
int fd;
string id;
bool connected;
// Map of topic -> is_pattern (not strictly used for "subscribe <topic>" checking if we iterate, but good for O(1) in exact match)
// Actually, we need to store subscriptions.
// Let's use a set of strings for exact topics and a list for wildcards?
// Or just a vector of Subscription structs.
// For simplicity and to handle "subscribe topic" vs "subscribe topic *" we might just store strings.
// The requirements say topics are strings. Wildcards are just patterns.
// A client subscribes to a "topic". If the topic contains wildcards, we treat it as such during matching.
set<string> subscriptions;
};
// Global map of ID -> Client info (to handle reconnections)
map<string, Client> clients_map;
// Map of FD -> Client ID (for fast lookup during poll)
map<int, string> fd_to_id;
void usage(char *file)
{
fprintf(stderr, "Usage: %s <PORT_SERVER>\n", file);
exit(0);
}
// UDP Message Structure
struct udp_msg {
char topic[50];
uint8_t type;
char payload[1500];
};
// Helper to check if a topic matches a pattern (handling + and *)
bool match_topic(const string& topic, const string& pattern) {
// If pattern matches topic exactly
if (topic == pattern) return true;
// Split topic and pattern by '/'
vector<string> topic_parts;
vector<string> pattern_parts;
size_t pos = 0;
string s = topic;
while ((pos = s.find("/")) != string::npos) {
topic_parts.push_back(s.substr(0, pos));
s.erase(0, pos + 1);
}
topic_parts.push_back(s);
pos = 0;
string p = pattern;
while ((pos = p.find("/")) != string::npos) {
pattern_parts.push_back(p.substr(0, pos));
p.erase(0, pos + 1);
}
pattern_parts.push_back(p);
// * wildcard handling logic
// * matches any number of levels
// + matches exactly one level
// If we have no wildcards, we already checked exact match (though we should double check for safety/robustness)
int t_idx = 0;
int p_idx = 0;
int t_len = topic_parts.size();
int p_len = pattern_parts.size();
// Iterate through pattern
while (p_idx < p_len && t_idx < t_len) {
if (pattern_parts[p_idx] == "+") {
// Matches exactly one
t_idx++;
p_idx++;
} else if (pattern_parts[p_idx] == "*") {
// Matches 0 or more.
// If it's the last part of pattern, it matches everything remaining
if (p_idx + 1 == p_len) return true;
// Otherwise, we need to backtrack/try to match the NEXT pattern part against future topic parts.
// Simple approach: advance topic index until we find a match for the next pattern part
string next_part = pattern_parts[p_idx + 1];
// bool found = false;
// Since * can match 0 items, we start checking from current t_idx
// Optimization for the provided tests:
// "upb/precis/elevator/*/floor" vs "upb/precis/elevator/1/floor"
// "upb/precis/*"
// Let's try recursive check or simple loop?
// "*/pressure" vs "upb/ec/100/pressure"
// Let's increment t_idx until the end or until we recursively match the rest
// This is basically regex .*
// Simplification: Try to match the rest of the pattern with the rest of the topic
// We can skip 0..N parts of topic
for (int k = t_idx; k < t_len; k++) {
// But wait, the recursive call needs to handle the rest of parts.
// It's cleaner to implement a recursive helper for the whole vectors
// But let's stick to this loop with a "future match" check logic
// If we match match_parts(rest_topic, rest_pattern_after_star)
// Then valid.
// This function is becoming complex inside a single loop.
// Let's delegate to a recursive function instead
return false; // Should not reach here if I allow recursion below
}
} else {
if (topic_parts[t_idx] != pattern_parts[p_idx]) return false;
t_idx++;
p_idx++;
}
}
// Exact length match checks
if (p_idx < p_len && pattern_parts[p_idx] == "*") {
return p_idx + 1 == p_len; // * at the end matches 0 remaining
}
return (p_idx == p_len && t_idx == t_len);
}
bool is_match_recursive(const vector<string>& t_parts, const vector<string>& p_parts, int t_idx, int p_idx) {
// Base cases
if (p_idx == (int)p_parts.size() && t_idx == (int)t_parts.size()) return true;
if (p_idx == (int)p_parts.size()) return false;
// If pattern part is "*"
if (p_parts[p_idx] == "*") {
// If * is the last part, it matches everything remaining
if (p_idx + 1 == (int)p_parts.size()) return true;
// Try skipping k parts of topic (consuming 0 to N parts)
for (int k = t_idx; k < (int)t_parts.size(); k++) {
if (is_match_recursive(t_parts, p_parts, k, p_idx + 1)) return true;
}
return false;
}
if (t_idx == (int)t_parts.size()) return false; // Pattern remaining but no topic parts
if (p_parts[p_idx] == "+" || p_parts[p_idx] == t_parts[t_idx]) {
return is_match_recursive(t_parts, p_parts, t_idx + 1, p_idx + 1);
}
return false;
}
bool match_wrapper(const string& topic, const string& pattern) {
vector<string> topic_parts;
vector<string> pattern_parts;
size_t pos = 0;
string s = topic;
while ((pos = s.find("/")) != string::npos) {
topic_parts.push_back(s.substr(0, pos));
s.erase(0, pos + 1);
}
topic_parts.push_back(s);
pos = 0;
string p = pattern;
while ((pos = p.find("/")) != string::npos) {
pattern_parts.push_back(p.substr(0, pos));
p.erase(0, pos + 1);
}
pattern_parts.push_back(p);
return is_match_recursive(topic_parts, pattern_parts, 0, 0);
}
int main(int argc, char *argv[])
{
if (argc != 2) {
usage(argv[0]);
}
// Disable buffering
setvbuf(stdout, NULL, _IONBF, BUFSIZ);
int port = atoi(argv[1]);
int ret;
// UDP Socket
int udp_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
DIE(udp_sockfd < 0, "socket udp");
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
server_addr.sin_addr.s_addr = INADDR_ANY;
ret = bind(udp_sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
DIE(ret < 0, "bind udp");
// TCP Socket
int tcp_sockfd = socket(AF_INET, SOCK_STREAM, 0);
DIE(tcp_sockfd < 0, "socket tcp");
ret = bind(tcp_sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
DIE(ret < 0, "bind tcp");
ret = listen(tcp_sockfd, MAX_CLIENTS);
DIE(ret < 0, "listen");
// Poll Setup
// Initial size enough for UDP, TCP listener, stdin, and some clients
// We'll dynamically resize or just make it large enough?
// Vectors are better.
vector<struct pollfd> poll_fds;
// Add stdin [0]
struct pollfd p;
p.fd = STDIN_FILENO;
p.events = POLLIN;
poll_fds.push_back(p);
// Add UDP [1]
p.fd = udp_sockfd;
p.events = POLLIN;
poll_fds.push_back(p);
// Add TCP Listener [2]
p.fd = tcp_sockfd;
p.events = POLLIN;
poll_fds.push_back(p);
while (1) {
ret = poll(poll_fds.data(), poll_fds.size(), -1);
DIE(ret < 0, "poll");
// Check Stdin
if (poll_fds[0].revents & POLLIN) {
char buf[100];
fgets(buf, 100, stdin);
if (strncmp(buf, "exit", 4) == 0) {
break;
}
}
// Check UDP
if (poll_fds[1].revents & POLLIN) {
char buffer[BUFLEN];
struct sockaddr_in client_addr;
socklen_t clen = sizeof(client_addr);
int n = recvfrom(udp_sockfd, buffer, BUFLEN, 0, (struct sockaddr*)&client_addr, &clen);
// Don't DIE on recvfrom error, just continue? Or DIE?
if (n > 0) {
// Parse UDP
struct udp_msg *msg = (struct udp_msg*)buffer;
// Topic is 50 bytes. Careful with null termination.
// It might not be null terminated if it fills 50 bytes.
// Let's force it for safety in logic, but protocol says "topic: 50 bytes".
// We shouldn't modify the buffer directly if we interpret it struct-wise,
// but we can copy it.
string topic_str(msg->topic, strnlen(msg->topic, 50));
// Determine value
string data_type;
string value_str;
char *payload_ptr = buffer + 51; // 50 bytes topic + 1 byte type
switch(msg->type) {
case 0: // INT
{
data_type = "INT";
uint8_t sign = payload_ptr[0];
uint32_t val = ntohl(*(uint32_t*)(payload_ptr + 1));
if (sign == 1 && val != 0) {
value_str = "-" + to_string(val);
} else {
value_str = to_string(val);
}
break;
}
case 1: // SHORT_REAL
{
data_type = "SHORT_REAL";
uint16_t val = ntohs(*(uint16_t*)(payload_ptr));
// format with 2 decimals
char tmp[20];
sprintf(tmp, "%.2f", val / 100.0);
value_str = string(tmp);
break;
}
case 2: // FLOAT
{
data_type = "FLOAT";
uint8_t sign = payload_ptr[0];
uint32_t val_i = ntohl(*(uint32_t*)(payload_ptr + 1));
uint8_t exp = payload_ptr[5];
double val = (double)val_i;
// divide by 10^exp
for(int k=0; k<exp; k++) val /= 10.0;
if (sign == 1) val = -val;
char tmp[50];
sprintf(tmp, "%.*f", (int)exp > 4 ? (int)exp : 4, val);
// The test expects specific formatting usually, let's just use standard stream formatting or printf
// "1234.4321" "0.042"
// Protocol says "precision is exp" but sometimes standard %f is cleaner.
// Let's try to match exactly: printf should work but trailing zeros?
// Let's preserve logic from test.py expected outputs if possible.
// "17" for float 17.
// Refine Float formatting
sprintf(tmp, "%.10f", val); // large precision
string s(tmp);
// trim trailing zeros
s.erase(s.find_last_not_of('0') + 1, string::npos);
if(s.back() == '.') s.pop_back(); // remove trailing dot if integer
value_str = s;
break;
}
case 3: // STRING
{
data_type = "STRING";
value_str = string(payload_ptr); // assumes null terminated or valid
break;
}
}
string final_msg = string(inet_ntoa(client_addr.sin_addr)) + ":" + to_string(ntohs(client_addr.sin_port)) +
" - " + topic_str + " - " + data_type + " - " + value_str + "\n";
// Forward to subscribers
// Structure message for subscribers matches what `test.py` expects?
// test.py expects: `topic.print()` -> `name + " - " + category + " - " + value`
// BUT server SHOULD send `ip:port - topic - type - value`?
// Wait, `test.py` line 290: `server.get_output` when checking C1 startup.
// Line 312 `check_subscriber_output`.
// Line 344 `target = topic.print()`. `Topic.print()` returns `name - category - value`.
// So the SUBSCRIBER receives `ip:port - topic - type - value` BUT the subscriber checks ONLY `topic - type - value`?
// No, `check_subscriber_output` checks if `target` is IN `outc`.
// If the server sends `IP:PORT - TOPIC - TYPE - VALUE`, and target is `TOPIC - TYPE - VALUE`, it works.
// The requirements usually ask for the full UDP source info.
string message_to_send = final_msg; // The UDP sender info + Payload
for(auto &kv : clients_map) {
if (!kv.second.connected) continue;
bool matches = false;
for (const string &sub : kv.second.subscriptions) {
if (match_wrapper(topic_str, sub)) {
matches = true;
break;
}
}
if (matches) {
send(kv.second.fd, message_to_send.c_str(), message_to_send.size(), 0);
}
}
}
}
// Check TCP Listener [2]
if (poll_fds[2].revents & POLLIN) {
struct sockaddr_in cli_addr;
socklen_t cli_len = sizeof(cli_addr);
int new_fd = accept(tcp_sockfd, (struct sockaddr*)&cli_addr, &cli_len);
if (new_fd > 0) {
// Disable buffering/Nagle if needed (already handled by defaults often)
// Read ID
char id_buf[100];
int n = recv(new_fd, id_buf, 100, 0);
if (n > 0) {
id_buf[n] = 0;
string id(id_buf);
if (clients_map.count(id) && clients_map[id].connected) {
cout << "Client " << id << " already connected." << endl;
close(new_fd);
} else {
// Accept
clients_map[id].fd = new_fd;
clients_map[id].id = id;
clients_map[id].connected = true;
fd_to_id[new_fd] = id;
// Add to poll
struct pollfd p;
p.fd = new_fd;
p.events = POLLIN;
poll_fds.push_back(p);
cout << "New client " << id << " connected from " << inet_ntoa(cli_addr.sin_addr) << ":" << ntohs(cli_addr.sin_port) << "." << endl;
}
} else {
close(new_fd);
}
}
}
// Check Clients
for (size_t i = 3; i < poll_fds.size(); i++) {
if (poll_fds[i].revents & POLLIN) {
int fd = poll_fds[i].fd;
char buf[200];
int n = recv(fd, buf, 200, 0);
if (n <= 0) {
// Disconnected
string id = fd_to_id[fd];
cout << "Client " << id << " disconnected." << endl;
clients_map[id].connected = false;
clients_map[id].fd = -1;
fd_to_id.erase(fd);
close(fd);
// Remove from poll_fds
poll_fds.erase(poll_fds.begin() + i);
i--; // adjust index
} else {
buf[n] = 0;
// Handle subscribe/unsubscribe
// Format: "subscribe topic" or "unsubscribe topic"
// Buffering commands: assuming one command per packet or simple structure?
// Test sends "subscribe topic"
// Need to handle potential buffering or split messages?
// For this assignment, it's usually simple.
// Beware of newlines
string cmd_line(buf);
// trim newline
if (!cmd_line.empty() && cmd_line.back() == '\n') cmd_line.pop_back();
// Split space
size_t sp_pos = cmd_line.find(' ');
if (sp_pos != string::npos) {
string type = cmd_line.substr(0, sp_pos);
string topic = cmd_line.substr(sp_pos + 1);
string id = fd_to_id[fd];
if (type == "subscribe") {
clients_map[id].subscriptions.insert(topic);
// No Ack required by protocol spec?
// Wait, test.py line 352: expects "Subscribed to topic"
// Wait, line 311 `check_subscriber_output`.
// Line 349 `subscribe_to_topic` sends "subscribe ...".
// Line 352 `check "Subscribed to topic"`.
// THE CLIENT (Subscriber) might NOT be printing "Subscribed to topic".
// The SERVER might not send it.
// The SUBSCRIBER process sends "subscribe".
// Does the Subscriber process print "Subscribed..." locally or does the Server send it back?
// Usually in these homeworks, the subscriber prints feedback locally or receives Ack.
// `test.py` calls `c.get_output`. `c` is the Subscriber Process.
// If `udp_client.py` sends traffic, `server` fwds to `c`.
// If `c` sends `subscribe`, `c` output expects "Subscribed...".
// The implementation of `subscriber` I wrote just forwards stdin to socket.
// So the SERVER must send back "Subscribed to topic" or the SUBSCRIBER prints it?
// "Subscribed to topic" is likely feedback.
// Looking at `run_test_c2_subscribe` in `test.py`:
// `c2.send_input("subscribe " + topic.name)`
// `outc2 = c2.get_output_timeout(1)`
// `startswith("Subscribed to topic")`.
// My subscriber code: `send(sockfd, buffer)` then checks `poll` for `recv`.
// If I don't print "Subscribed to topic" in subscriber.cpp immediately, the server must.
// OR subscriber.cpp prints it.
// Let's assume subscriber.cpp prints it since it's user feedback.
// EDIT: I will modify subscriber.cpp to print feedback OR make server send it.
// Let's check `test.py`: `check_subscriber_output(c1, "1", target)`.
// When data arrives, it prints "IP:PORT ...".
// When command sent, it prints "Subscribed...".
// It's safer if the subscriber prints "Subscribed to topic" after sending the command?
// Or the server sends an ACK.
// If I look at similar assignments (PCom), usually the Client prints "Subscribed to topic." immediately after parsing input,
// OR the Server sends a text "Subscribed to topic".
// But `test.py` checks the output of `subscriber` STDOUT.
// If I implement it in `subscriber.cpp` it is instant.
// If I implement in `server`, it confirms receipt.
// Let's check `subscriber` implementation again.
// I should probably add print in `subscriber` for feedback.
// However, let's keep server logic clean.
// NOTE: I missed the feedback print in `subscriber.cpp`.
// I will add it to `subscriber.cpp` in a fix if needed, or update `subscriber.cpp` now?
// I can't update `subscriber.cpp` easily while writing `server.cpp`.
// I'll assume for now I need to update `subscriber.cpp` to print "Subscribed to topic".
// Re-reading `test.py`:
// `c.send_input("subscribe...")` -> `c.get_output...`
// If I add printf in subscriber it works.
} else if (type == "unsubscribe") {
clients_map[id].subscriptions.erase(topic);
// Client should print "Unsubscribed from topic" maybe?
// test.py: `c2_subscribe_plus_wildcard` -> `c2.send_input("unsubscribe " ...)` -> `c2.get_output_timeout`.
// It consumes output but doesn't strictly check "Unsubscribed".
}
}
}
}
}
}
// Close all
close(udp_sockfd);
close(tcp_sockfd);
for(auto &p : poll_fds) {
if (p.fd > 0) close(p.fd);
}
return 0;
}