-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
636 lines (599 loc) Β· 27.5 KB
/
server.cpp
File metadata and controls
636 lines (599 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
/*
* messenger-server
* Build: g++ -std=c++17 -Wall -Wextra -O2 -pthread -o messenger-server server.cpp
* Run: ./messenger-server [port] (default: 7777)
*
* Protocol: newline-delimited JSON over TCP
*
* Client β Server:
* {"type":"register","username":"u","password":"sha256hex"}
* {"type":"login","username":"u","password":"sha256hex"}
* {"type":"msg","to":"peer","text":"...","id":"...","ts":"..."}
* {"type":"msg","to":"@world","text":"...","id":"...","ts":"..."}
* {"type":"read","id":"...","from":"sender"}
* {"type":"get_history","peer":"username_or_@world"}
* {"type":"search","query":"prefix"}
* {"type":"file_start","to":"peer","id":"...","filename":"...","size":"12345"}
* {"type":"file_chunk","id":"...","seq":"0","data":"base64..."}
* {"type":"file_end","id":"..."}
* {"type":"ping"}
*
* Server β Client:
* {"type":"register_ok","username":"u"}
* {"type":"register_err","reason":"..."}
* {"type":"login_ok","username":"u"}
* {"type":"login_err","reason":"..."}
* {"type":"msg","from":"u","to":"peer","text":"...","id":"...","ts":"..."}
* {"type":"ack","id":"...","status":"sent|delivered|read"}
* {"type":"online","username":"u","online":"true|false"}
* {"type":"online_list","users":["a","b"]}
* {"type":"history_msg","from":"u","to":"v","text":"...","id":"...","ts":"...","status":"..."}
* {"type":"history_end","peer":"..."}
* {"type":"search_result","users":["a","b"]}
* {"type":"file_start","from":"u","id":"...","filename":"...","size":"..."}
* {"type":"file_chunk","id":"...","seq":"...","data":"base64..."}
* {"type":"file_end","id":"..."}
* {"type":"file_progress","id":"...","percent":"42"} β to sender
* {"type":"pong"}
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <mutex>
#include <thread>
#include <atomic>
#include <algorithm>
#include <filesystem>
#include <ctime>
#include <cstring>
#include <csignal>
#include <cstdint>
#include <functional>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/select.h>
// ββ Paths βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
static const std::string DATA_DIR = "./server_data";
static const std::string USERS_FILE = DATA_DIR + "/users.txt";
static const std::string HIST_DIR = DATA_DIR + "/history";
static const std::string FILES_DIR = DATA_DIR + "/files";
static const int DEFAULT_PORT = 7777;
static const size_t MAX_LINE = 1 << 20; // 1 MB per line (for file chunks)
static const size_t HIST_KEEP = 500;
static const std::string WORLD_PEER = "@world";
// ββ SHA-256 (self-contained, no openssl) ββββββββββββββββββββββββββββββββββββββ
static uint32_t rotr32(uint32_t x, int n){ return (x>>n)|(x<<(32-n)); }
static std::string sha256(const std::string& msg) {
static const uint32_t K[64]={
0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,
0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,
0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,
0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,
0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,
0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,
0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,
0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,
0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
};
uint32_t h[8]={0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,
0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19};
std::vector<uint8_t> data(msg.begin(),msg.end());
uint64_t bitlen=(uint64_t)data.size()*8;
data.push_back(0x80);
while(data.size()%64!=56) data.push_back(0);
for(int i=7;i>=0;--i) data.push_back((bitlen>>(i*8))&0xff);
for(size_t chunk=0;chunk<data.size();chunk+=64){
uint32_t w[64]={};
for(int i=0;i<16;++i)
w[i]=((uint32_t)data[chunk+i*4]<<24)|((uint32_t)data[chunk+i*4+1]<<16)|
((uint32_t)data[chunk+i*4+2]<<8)|(uint32_t)data[chunk+i*4+3];
for(int i=16;i<64;++i){
uint32_t s0=rotr32(w[i-15],7)^rotr32(w[i-15],18)^(w[i-15]>>3);
uint32_t s1=rotr32(w[i-2],17)^rotr32(w[i-2],19)^(w[i-2]>>10);
w[i]=w[i-16]+s0+w[i-7]+s1;
}
uint32_t a=h[0],b=h[1],c=h[2],d=h[3],e=h[4],f=h[5],g=h[6],hh=h[7];
for(int i=0;i<64;++i){
uint32_t S1=rotr32(e,6)^rotr32(e,11)^rotr32(e,25);
uint32_t ch=(e&f)^(~e&g);
uint32_t tmp1=hh+S1+ch+K[i]+w[i];
uint32_t S0=rotr32(a,2)^rotr32(a,13)^rotr32(a,22);
uint32_t maj=(a&b)^(a&c)^(b&c);
uint32_t tmp2=S0+maj;
hh=g;g=f;f=e;e=d+tmp1;d=c;c=b;b=a;a=tmp1+tmp2;
}
h[0]+=a;h[1]+=b;h[2]+=c;h[3]+=d;h[4]+=e;h[5]+=f;h[6]+=g;h[7]+=hh;
}
char hex[65];
for(int i=0;i<8;++i)
snprintf(hex+i*8,9,"%08x",h[i]);
return std::string(hex,64);
}
// ββ Base64 (for file transfer) ββββββββββββββββββββββββββββββββββββββββββββββββ
static const std::string B64_CHARS=
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static std::string b64encode(const std::vector<uint8_t>& in){
std::string out; int val=0,valb=-6;
for(uint8_t c:in){
val=(val<<8)+c; valb+=8;
while(valb>=0){out.push_back(B64_CHARS[(val>>valb)&0x3F]);valb-=6;}
}
if(valb>-6)out.push_back(B64_CHARS[((val<<8)>>(valb+8))&0x3F]);
while(out.size()%4)out.push_back('=');
return out;
}
static std::vector<uint8_t> b64decode(const std::string& in){
std::vector<int> T(256,-1);
for(int i=0;i<64;++i)T[(uint8_t)B64_CHARS[i]]=i;
std::vector<uint8_t> out; int val=0,valb=-8;
for(char c:in){
if(T[(uint8_t)c]==-1)break;
val=(val<<6)+T[(uint8_t)c]; valb+=6;
if(valb>=0){out.push_back((val>>valb)&0xFF);valb-=8;}
}
return out;
}
// ββ JSON helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
static std::string jesc(const std::string& s){
std::string r;
for(char c:s){
if(c=='"')r+="\\\"";
else if(c=='\\')r+="\\\\";
else if(c=='\n')r+="\\n";
else r+=c;
}
return r;
}
static std::string jget(const std::string& j,const std::string& k){
std::string needle="\""+k+"\"";
size_t pos=j.find(needle); if(pos==std::string::npos)return "";
pos+=needle.size();
while(pos<j.size()&&(j[pos]==' '||j[pos]=='\t'||j[pos]==':'))++pos;
if(pos>=j.size())return "";
if(j[pos]=='"'){
++pos;std::string val;bool esc=false;
while(pos<j.size()){
char c=j[pos++];
if(esc){
if(c=='"')val+='"';
else if(c=='\\')val+='\\';
else if(c=='n')val+='\n';
else{val+='\\';val+=c;}
esc=false;
} else if(c=='\\')esc=true;
else if(c=='"')break;
else val+=c;
}
return val;
}
size_t end=pos;
while(end<j.size()&&j[end]!=','&&j[end]!='}'&&j[end]!=']')++end;
std::string val=j.substr(pos,end-pos);
while(!val.empty()&&(val.back()==' '||val.back()=='\t'))val.pop_back();
return val;
}
static std::string jbuild(std::initializer_list<std::pair<std::string,std::string>> kv){
std::string r="{";bool first=true;
for(const auto& p:kv){
if(!first)r+=",";
r+="\""+p.first+"\":\""+jesc(p.second)+"\"";
first=false;
}
return r+"}";
}
// ββ User store ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Format: username\tsha256(password)\n
static std::mutex g_usersMu;
static std::map<std::string,std::string> g_users; // username β passhash
static void loadUsers(){
std::lock_guard<std::mutex> lk(g_usersMu);
std::ifstream f(USERS_FILE); if(!f.is_open())return;
std::string line;
while(std::getline(f,line)){
auto tab=line.find('\t'); if(tab==std::string::npos)continue;
g_users[line.substr(0,tab)]=line.substr(tab+1);
}
}
static void saveUsers(){
// called under g_usersMu
std::ofstream f(USERS_FILE,std::ios::trunc); if(!f.is_open())return;
for(const auto& [u,h]:g_users) f<<u<<'\t'<<h<<'\n';
}
static bool registerUser(const std::string& u,const std::string& ph){
std::lock_guard<std::mutex> lk(g_usersMu);
if(g_users.count(u))return false;
g_users[u]=ph; saveUsers(); return true;
}
static bool checkUser(const std::string& u,const std::string& ph){
std::lock_guard<std::mutex> lk(g_usersMu);
auto it=g_users.find(u); return it!=g_users.end()&&it->second==ph;
}
static bool userExists(const std::string& u){
std::lock_guard<std::mutex> lk(g_usersMu);
return g_users.count(u)>0;
}
static std::vector<std::string> searchUsers(const std::string& prefix){
std::lock_guard<std::mutex> lk(g_usersMu);
std::vector<std::string> res;
for(const auto& [u,_]:g_users)
if(u.find(prefix)!=std::string::npos)res.push_back(u);
// Also add @world always
if(std::string("@world").find(prefix)!=std::string::npos)
res.push_back("@world");
return res;
}
// ββ History βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
static std::string histFile(const std::string& a,const std::string& b){
if(a==WORLD_PEER||b==WORLD_PEER)
return HIST_DIR+"/world.log";
std::string lo=a<b?a:b,hi=a<b?b:a;
return HIST_DIR+"/"+lo+"__"+hi+".log";
}
static void appendHist(const std::string& a,const std::string& b,const std::string& line){
std::ofstream f(histFile(a,b),std::ios::app);
if(f.is_open())f<<line<<"\n";
}
static std::vector<std::string> loadHist(const std::string& a,const std::string& b,size_t max=HIST_KEEP){
std::vector<std::string> lines;
std::ifstream f(histFile(a,b)); if(!f.is_open())return lines;
std::string line;
while(std::getline(f,line))if(!line.empty())lines.push_back(line);
if(lines.size()>max)lines.erase(lines.begin(),lines.begin()+(lines.size()-max));
return lines;
}
// ββ In-flight file transfers ββββββββββββββββββββββββββββββββββββββββββββββββββ
struct FileXfer {
std::string id,from,to,filename;
size_t totalSize=0,recvSize=0;
std::vector<uint8_t> data;
};
static std::mutex g_xferMu;
static std::map<std::string,FileXfer> g_xfers;
// ββ Client ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
struct Client {
int fd=-1;
std::string username;
bool authed=false;
std::string recvBuf;
std::deque<std::string> sendQ;
std::mutex sendMu;
void enqueue(const std::string& line){
std::lock_guard<std::mutex> lk(sendMu);
sendQ.push_back(line+"\n");
}
};
static std::mutex g_mu;
static std::map<int,std::shared_ptr<Client>> g_clients;
static std::map<std::string,int> g_userFd;
static std::atomic<bool> g_running{true};
static std::atomic<uint64_t> g_counter{0};
static std::shared_ptr<Client> findByUser(const std::string& u){
auto it=g_userFd.find(u); if(it==g_userFd.end())return nullptr;
auto ci=g_clients.find(it->second); if(ci==g_clients.end())return nullptr;
return ci->second;
}
static std::string makeId(int fd){
char buf[64];
snprintf(buf,sizeof(buf),"%llx-%d-%llx",
(unsigned long long)std::time(nullptr),fd,(unsigned long long)(++g_counter));
return buf;
}
static std::string serverTs(){
std::time_t t=std::time(nullptr); char buf[16];
std::strftime(buf,sizeof(buf),"%H:%M",std::localtime(&t)); return buf;
}
static void broadcastPresence(const std::string& u,bool on,int skipFd=-1){
std::string msg=jbuild({{"type","online"},{"username",u},{"online",on?"true":"false"}});
std::lock_guard<std::mutex> lk(g_mu);
for(auto& [fd,c]:g_clients){
if(fd==skipFd||!c->authed)continue;
c->enqueue(msg);
}
}
// ββ Message handling ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
static void handleLine(std::shared_ptr<Client> cl,const std::string& line){
std::string type=jget(line,"type");
// ββ REGISTER ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if(type=="register"){
std::string u=jget(line,"username"),ph=jget(line,"password");
if(u.size()<3){cl->enqueue(jbuild({{"type","register_err"},{"reason","username too short"}}));return;}
for(char c:u)if(!std::isalnum((unsigned char)c)&&c!='_'){
cl->enqueue(jbuild({{"type","register_err"},{"reason","invalid chars in username"}}));return;}
if(ph.size()!=64){cl->enqueue(jbuild({{"type","register_err"},{"reason","bad password hash"}}));return;}
if(!registerUser(u,ph)){cl->enqueue(jbuild({{"type","register_err"},{"reason","username taken"}}));return;}
cl->enqueue(jbuild({{"type","register_ok"},{"username",u}}));
std::cout<<"[REG] "<<u<<"\n";
return;
}
// ββ LOGIN βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if(type=="login"){
std::string u=jget(line,"username"),ph=jget(line,"password");
if(!userExists(u)){cl->enqueue(jbuild({{"type","login_err"},{"reason","user not found"}}));return;}
if(!checkUser(u,ph)){cl->enqueue(jbuild({{"type","login_err"},{"reason","wrong password"}}));return;}
{
std::lock_guard<std::mutex> lk(g_mu);
if(g_userFd.count(u)){
cl->enqueue(jbuild({{"type","login_err"},{"reason","already logged in"}}));return;
}
cl->username=u; cl->authed=true; g_userFd[u]=cl->fd;
}
cl->enqueue(jbuild({{"type","login_ok"},{"username",u}}));
// Send online list
{
std::lock_guard<std::mutex> lk(g_mu);
std::string arr="[";bool first=true;
for(auto& [ou,ofd]:g_userFd){
if(ou==u)continue;
if(!first)arr+=",";
arr+="\""+jesc(ou)+"\""; first=false;
}
arr+="]";
cl->enqueue("{\"type\":\"online_list\",\"users\":"+arr+"}");
}
std::cout<<"[LOGIN] "<<u<<" fd="<<cl->fd<<"\n";
return; // presence broadcast after this returns
}
if(!cl->authed){cl->enqueue(jbuild({{"type","error"},{"reason","not authenticated"}}));return;}
// ββ MSG βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if(type=="msg"){
std::string to=jget(line,"to"),text=jget(line,"text");
std::string id=jget(line,"id"),ts=jget(line,"ts");
std::string replyTo=jget(line,"replyTo"),replyAuth=jget(line,"replyAuth");
if(id.empty())id=makeId(cl->fd);
if(ts.empty())ts=serverTs();
if(to.empty()||text.empty())return;
std::string msg=jbuild({{"type","msg"},{"from",cl->username},{"to",to},
{"text",text},{"id",id},{"ts",ts},
{"replyTo",replyTo},{"replyAuth",replyAuth}});
appendHist(cl->username,to,msg);
if(to==WORLD_PEER){
// Broadcast to all authed clients including sender
std::lock_guard<std::mutex> lk(g_mu);
for(auto& [fd,c]:g_clients)
if(c->authed) c->enqueue(msg);
cl->enqueue(jbuild({{"type","ack"},{"id",id},{"status","delivered"}}));
} else {
std::lock_guard<std::mutex> lk(g_mu);
auto recip=findByUser(to);
if(recip){
recip->enqueue(msg);
cl->enqueue(jbuild({{"type","ack"},{"id",id},{"status","delivered"}}));
} else {
cl->enqueue(jbuild({{"type","ack"},{"id",id},{"status","sent"}}));
}
}
return;
}
// ββ READ ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if(type=="read"){
std::string id=jget(line,"id"),from=jget(line,"from");
if(id.empty()||from.empty())return;
std::lock_guard<std::mutex> lk(g_mu);
auto sender=findByUser(from);
if(sender) sender->enqueue(jbuild({{"type","ack"},{"id",id},{"status","read"}}));
return;
}
// ββ GET_HISTORY βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if(type=="get_history"){
std::string peer=jget(line,"peer");
if(peer.empty())return;
auto hist=loadHist(cl->username,peer);
for(const auto& h:hist){
// Re-tag as history_msg so client can distinguish
// Just forward as-is β client treats them the same
cl->enqueue(h);
}
cl->enqueue(jbuild({{"type","history_end"},{"peer",peer}}));
return;
}
// ββ SEARCH ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if(type=="search"){
std::string q=jget(line,"query");
auto res=searchUsers(q);
std::string arr="[";bool first=true;
for(const auto& u:res){
if(!first)arr+=",";
arr+="\""+jesc(u)+"\""; first=false;
}
arr+="]";
cl->enqueue("{\"type\":\"search_result\",\"users\":"+arr+"}");
return;
}
// ββ FILE START ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if(type=="file_start"){
std::string id=jget(line,"id"),to=jget(line,"to");
std::string fname=jget(line,"filename"),sizeStr=jget(line,"size");
if(id.empty()||to.empty()||fname.empty())return;
std::string ts=serverTs();
size_t sz=sizeStr.empty()?0:std::stoull(sizeStr);
{
std::lock_guard<std::mutex> lk(g_xferMu);
FileXfer fx; fx.id=id; fx.from=cl->username; fx.to=to;
fx.filename=fname; fx.totalSize=sz;
g_xfers[id]=std::move(fx);
}
std::string notify=jbuild({{"type","file_start"},{"from",cl->username},
{"to",to},{"id",id},{"filename",fname},{"size",sizeStr},{"ts",ts}});
std::lock_guard<std::mutex> lk(g_mu);
if(to==WORLD_PEER){
for(auto&[fd,c]:g_clients)
if(c->authed&&c->fd!=cl->fd) c->enqueue(notify);
} else {
auto recip=findByUser(to);
if(recip) recip->enqueue(notify);
}
return;
}
// ββ FILE CHUNK ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if(type=="file_chunk"){
std::string id=jget(line,"id"),data=jget(line,"data"),seq=jget(line,"seq");
std::string to;
{
std::lock_guard<std::mutex> lk(g_xferMu);
auto it=g_xfers.find(id); if(it==g_xfers.end())return;
FileXfer& fx=it->second;
auto decoded=b64decode(data);
fx.data.insert(fx.data.end(),decoded.begin(),decoded.end());
fx.recvSize+=decoded.size();
to=fx.to;
if(fx.totalSize>0){
int pct=(int)(fx.recvSize*100/fx.totalSize);
cl->enqueue(jbuild({{"type","file_progress"},{"id",id},
{"percent",std::to_string(pct)}}));
}
}
std::string chunk=jbuild({{"type","file_chunk"},{"id",id},{"seq",seq},{"data",data}});
std::lock_guard<std::mutex> lk(g_mu);
if(to==WORLD_PEER){
for(auto&[fd,c]:g_clients)
if(c->authed&&c->fd!=cl->fd) c->enqueue(chunk);
} else {
auto recip=findByUser(to);
if(recip) recip->enqueue(chunk);
}
return;
}
// ββ FILE END ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if(type=="file_end"){
std::string id=jget(line,"id");
std::string to;
{
std::lock_guard<std::mutex> lk(g_xferMu);
auto it=g_xfers.find(id); if(it==g_xfers.end())return;
FileXfer& fx=it->second;
to=fx.to;
std::string savePath=FILES_DIR+"/"+id+"_"+fx.filename;
std::ofstream sf(savePath,std::ios::binary);
if(sf.is_open()) sf.write((char*)fx.data.data(),fx.data.size());
g_xfers.erase(it);
}
std::string notify=jbuild({{"type","file_end"},{"id",id}});
cl->enqueue(jbuild({{"type","file_progress"},{"id",id},{"percent","100"}}));
std::lock_guard<std::mutex> lk(g_mu);
if(to==WORLD_PEER){
for(auto&[fd,c]:g_clients)
if(c->authed&&c->fd!=cl->fd) c->enqueue(notify);
} else {
auto recip=findByUser(to);
if(recip) recip->enqueue(notify);
}
return;
}
// ββ GET_FILE ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if(type=="get_file"){
std::string id=jget(line,"id"),fn=jget(line,"filename");
if(id.empty())return;
std::string path=FILES_DIR+"/"+id+"_"+fn;
std::ifstream f(path,std::ios::binary);
if(!f.is_open()){
cl->enqueue(jbuild({{"type","error"},{"reason","file not found: "+fn}}));
return;
}
std::vector<uint8_t>data((std::istreambuf_iterator<char>(f)),{});
cl->enqueue("{\"type\":\"file_data\",\"id\":\""+jesc(id)+"\","
"\"filename\":\""+jesc(fn)+"\","
"\"data\":\""+b64encode(data)+"\"}");
return;
}
// ββ PING ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if(type=="ping"){cl->enqueue(jbuild({{"type","pong"}}));return;}
}
// ββ Client thread βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
static void clientThread(std::shared_ptr<Client> cl){
int fd=cl->fd;
char buf[8192];
while(g_running){
fd_set rset,wset;
FD_ZERO(&rset);FD_ZERO(&wset);
FD_SET(fd,&rset);
bool hasSend=false;
{std::lock_guard<std::mutex> lk(cl->sendMu);hasSend=!cl->sendQ.empty();}
if(hasSend)FD_SET(fd,&wset);
struct timeval tv{1,0};
int sel=select(fd+1,&rset,hasSend?&wset:nullptr,nullptr,&tv);
if(sel<0)break;
if(FD_ISSET(fd,&wset)){
std::lock_guard<std::mutex> lk(cl->sendMu);
while(!cl->sendQ.empty()){
const std::string& msg=cl->sendQ.front();
ssize_t sent=send(fd,msg.data(),msg.size(),MSG_NOSIGNAL);
if(sent<=0)goto disc;
cl->sendQ.pop_front();
}
}
if(FD_ISSET(fd,&rset)){
ssize_t n=recv(fd,buf,sizeof(buf)-1,0);
if(n<=0)break;
buf[n]='\0';
cl->recvBuf+=std::string(buf,n);
size_t pos;
while((pos=cl->recvBuf.find('\n'))!=std::string::npos){
std::string ln=cl->recvBuf.substr(0,pos);
cl->recvBuf.erase(0,pos+1);
if(!ln.empty()&&ln.back()=='\r')ln.pop_back();
if(ln.empty()||ln.size()>MAX_LINE)continue;
bool wasAuthed=cl->authed;
handleLine(cl,ln);
if(!wasAuthed&&cl->authed)
broadcastPresence(cl->username,true,fd);
}
}
}
disc:
std::string u;
{std::lock_guard<std::mutex> lk(g_mu);
u=cl->username;
if(!u.empty())g_userFd.erase(u);
g_clients.erase(fd);}
close(fd);
if(!u.empty()){std::cout<<"[-] "<<u<<" disconnected\n";broadcastPresence(u,false,fd);}
}
// ββ Main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
static void sigHandler(int){g_running=false;}
int main(int argc,char* argv[]){
int port=DEFAULT_PORT;
if(argc>=2)port=std::atoi(argv[1]);
std::filesystem::create_directories(DATA_DIR);
std::filesystem::create_directories(HIST_DIR);
std::filesystem::create_directories(FILES_DIR);
loadUsers();
signal(SIGPIPE,SIG_IGN);
signal(SIGINT,sigHandler);
signal(SIGTERM,sigHandler);
int sfd=socket(AF_INET,SOCK_STREAM,0); if(sfd<0){perror("socket");return 1;}
int opt=1; setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
sockaddr_in addr{}; addr.sin_family=AF_INET;
addr.sin_addr.s_addr=INADDR_ANY; addr.sin_port=htons((uint16_t)port);
if(bind(sfd,(sockaddr*)&addr,sizeof(addr))<0){perror("bind");return 1;}
if(listen(sfd,32)<0){perror("listen");return 1;}
std::cout<<"=== Terminal Messenger Server ===\n"
<<"Port: "<<port<<"\n"
<<"Data: "<<std::filesystem::absolute(DATA_DIR)<<"\n"
<<"Ctrl+C to stop\n\n";
while(g_running){
fd_set rset;FD_ZERO(&rset);FD_SET(sfd,&rset);
struct timeval tv{1,0};
if(select(sfd+1,&rset,nullptr,nullptr,&tv)<=0)continue;
sockaddr_in ca{};socklen_t cl=sizeof(ca);
int cfd=accept(sfd,(sockaddr*)&ca,&cl); if(cfd<0)continue;
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET,&ca.sin_addr,ip,sizeof(ip));
std::cout<<"[?] "<<ip<<":"<<ntohs(ca.sin_port)<<" fd="<<cfd<<"\n";
auto c=std::make_shared<Client>(); c->fd=cfd;
{std::lock_guard<std::mutex> lk(g_mu);g_clients[cfd]=c;}
std::thread(clientThread,c).detach();
}
close(sfd);
std::cout<<"Server stopped.\n";
return 0;
}