This repository has been archived by the owner on Jun 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
peer.hpp
1893 lines (1836 loc) · 83.3 KB
/
peer.hpp
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifndef PEER_HPP
#define PEER_HPP
//class peer : public boost::enable_shared_from_this<peer>
class peer : public std::enable_shared_from_this<peer>
{
public:
peer(server& srv,bool in,servers& srvs,options& opts) :
svid(BANK_MAX),
do_sync(1), //remove, use peer_hs.do_sync
killme(false),
busy(0),
peer_io_service_(),
work_(peer_io_service_),
socket_(peer_io_service_),
iothp_(nullptr),
server_(srv),
incoming_(in),
srvs_(srvs),
opts_(opts),
addr(""),
port(0),
files_out(0),
files_in(0),
bytes_out(0),
bytes_in(0),
BLOCK_MODE(0),
BLOCK_SERV(false),
BLOCK_PEER(false)
{ read_msg_ = boost::make_shared<message>();
//iothp_= new boost::thread(boost::bind(&peer::iorun,this));
iothp_.reset(new boost::thread(boost::bind(&peer::iorun,this)));
struct timeval tv;
tv.tv_sec=8;
tv.tv_usec=0;
setsockopt(socket_.native(),SOL_SOCKET,SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(socket_.native(),SOL_SOCKET,SO_SNDTIMEO, &tv, sizeof(tv));
}
~peer()
{ if(port||1){
uint32_t ntime=time(NULL);
DLOG("%04X PEER destruct %s:%d @%08X log: blk/%03X/%05X/log.txt\n",svid,addr.c_str(),port,ntime,srvs_.now>>20,srvs_.now&0xFFFFF);
}
}
void iorun()
{ DLOG("%04X PEER IORUN START\n",svid);
try{
peer_io_service_.run();
} //Now we know the server is down.
catch (std::exception& e){
//FIXME, stop peer after Broken pipe (now does not stop if peer ends with 'assert')
//FIXME, wipe out inactive peers (better solution)
DLOG("%04X CATCH IORUN Service.Run error:%s\n",svid,e.what());
killme=true;}
DLOG("%04X PEER IORUN END\n",svid);
}
void stop() // by server only
{ boost::system::error_code errorcode;
//DLOG("%04X STOP start\n",svid);
killme=true;
//socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both,errorcode);
if(socket_.is_open()){
DLOG("%04X PEER KILL %d<->%d\n",svid,socket_.local_endpoint().port(),port);
socket_.cancel();
//DLOG("%04X CLOSE SOCKET\n",svid);
socket_.close();
boost::this_thread::sleep(boost::posix_time::milliseconds(999)); // mus sleep to let connect() fail
}
//DLOG("%04X RESET\n",svid);
//peer_io_service_.reset();
//DLOG("%04X STOP\n",svid);
peer_io_service_.stop();
//DLOG("%04X PEER INTERRUPT\n",svid);
//boost::this_thread::sleep(boost::posix_time::milliseconds(100));
//iothp_->interrupt();
//boost::this_thread::sleep(boost::posix_time::milliseconds(100));
//DLOG("%04X PEER JOIN\n",svid);
if(iothp_ != nullptr){
//DLOG("%04X IOTH CLOSING\n",svid);
iothp_->join(); //try joining yourself error
iothp_.reset(nullptr);}
//socket_.cancel();
//socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both,errorcode);
//socket_.close();
//socket_.release(NULL);
DLOG("%04X PEER CLOSED\n",svid);
}
void leave()
{ DLOG("%04X PEER LEAVING %d<->%d\n",svid,socket_.local_endpoint().port(),port);
//message_ptr msg=server_.write_handshake(0,sync_hs); // sets sync_hs
killme=true;
}
void accept() //only incoming connections
{ assert(incoming_);
//killme=false; //connection established
addr = socket_.remote_endpoint().address().to_string();
port = socket_.remote_endpoint().port();
DLOG("%04X PEER CONNECT OK %d<->%s:%d\n",svid,socket_.local_endpoint().port(),
socket_.remote_endpoint().address().to_string().c_str(),port);
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,message::header_length),
boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));
}
void connect(const boost::system::error_code& error) //only outgoing connection
{ if(error){
DLOG("%04X PEER ACCEPT ERROR\n",svid);
killme=true; // not needed, as now killme=true is initial state for outgoing connections
//peer_io_service_.stop();
return;}
killme=false; //connection established
assert(!incoming_);
addr = socket_.remote_endpoint().address().to_string();
port = socket_.remote_endpoint().port();
DLOG("%04X PEER ACCEPT OK %d<->%s:%d\n",svid,socket_.local_endpoint().port(),
socket_.remote_endpoint().address().to_string().c_str(),port);
message_ptr msg=server_.write_handshake(0,sync_hs); // sets sync_hs
msg->know_insert_(svid);
msg->sent.insert(svid);
msg->busy.insert(svid);
msg->print(" HANDSHAKE");
write_msgs_.push_back(msg);
boost::asio::async_write(socket_,boost::asio::buffer(msg->data,msg->len),
boost::bind(&peer::handle_write,shared_from_this(),boost::asio::placeholders::error));
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,message::header_length),
boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));
}
boost::asio::ip::tcp::socket& socket()
{ return socket_;
}
void print()
{ if(port){
DLOG("%04X Client on %s:%d\n",svid,addr.c_str(),port);} //LESZEK
else{
DLOG("%04X Client available\n",svid);}
}
void update(message_ptr msg)
{ if(killme){
DLOG("%04X KILL detected ! (UPDATE), leaving\n",svid);
return;}
assert(msg->len>4+64);
msg->print("; TRY UPDATE");
if(do_sync){
msg->print("; NO SYNC");
return;}
if(msg->peer == svid){
msg->print("; NO ECHO");
return;}
if(!msg->know_emplace(svid)){
msg->print("; NO UPDATE");
return;}
message_ptr put_msg(new message()); // gone ??? !!!
switch(msg->hashtype()){
case MSGTYPE_MSG:
put_msg->data[0]=MSGTYPE_PUT;
put_msg->data[1]=msg->hashval(svid); //msg->data[4+(svid%64)]; // convert to peer-specific hash
memcpy(put_msg->data+2,&msg->msid,4);
memcpy(put_msg->data+6,&msg->svid,2);
break;
case MSGTYPE_CND:
put_msg->data[0]=MSGTYPE_CNP;
put_msg->data[1]=msg->hashval(svid); //msg->data[4+(svid%64)]; // convert to peer-specific hash
memcpy(put_msg->data+2,&msg->msid,4);
memcpy(put_msg->data+6,&msg->svid,2);
break;
case MSGTYPE_BLK:
put_msg->data[0]=MSGTYPE_BLP;
put_msg->data[1]=msg->hashval(svid); //msg->data[4+(svid%64)]; // convert to peer-specific hash
memcpy(put_msg->data+2,&msg->msid,4);
memcpy(put_msg->data+6,&msg->svid,2);
break;
case MSGTYPE_DBL:
put_msg->data[0]=MSGTYPE_DBP;
put_msg->data[1]=0;
memcpy(put_msg->data+2,&msg->msid,4);
memcpy(put_msg->data+6,&msg->svid,2);
break;
default:
ELOG("%04X FATAL ERROR: bad message type\n",svid);
exit(-1);}
put_msg->svid=msg->svid;
put_msg->msid=msg->msid;
put_msg->hash.num=put_msg->dohash(put_msg->data);
put_msg->sent.insert(svid);
put_msg->busy.insert(svid);
DLOG("%04X HASH %016lX [%016lX] (update) %04X:%08X\n",svid,put_msg->hash.num,*((uint64_t*)put_msg->data),msg->svid,msg->msid);
pio_.lock(); //pio_.lock(); //boost::lock_guard<boost::mutex> lock(pio_); //pio_.lock();
if(BLOCK_MODE){
write_msgs_.push_back(put_msg);
pio_.unlock();
DLOG("%04X HASH %016lX [%016lX] (update in block mode, waiting) %04X:%08X\n",svid,put_msg->hash.num,*((uint64_t*)put_msg->data),msg->svid,msg->msid); // could be bad allignment
return;}
bool no_write_in_progress = write_msgs_.empty();
write_msgs_.push_back(put_msg);
if (no_write_in_progress) {
//int len=message_len(write_msgs_.front());
int len=write_msgs_.front()->len;
boost::asio::async_write(socket_,boost::asio::buffer(write_msgs_.front()->data,len),
boost::bind(&peer::handle_write,shared_from_this(),boost::asio::placeholders::error)); }
pio_.unlock();
}
/*int message_len(message_ptr msg) // shorten candidate vote messages if possible
{ if(do_sync){
return(msg->len);}
assert(msg->data!=NULL);
//if(msg->data[0]==MSGTYPE_CNG && msg->len>4+64+10+sizeof(hash_t)){//shorten message if peer knows this hash
if(msg->data[0]==MSGTYPE_CND && msg->len>4+64+10+sizeof(hash_t)){//shorten message if peer knows this hash
//hash_s cand;
//memcpy(cand.hash,msg->data+4+64+10,sizeof(hash_t));
//candidate_ptr c_ptr=server_.known_candidate(cand,0);
hash_s* cand=(hash_s*)(msg->data+4+64+10);
candidate_ptr c_ptr=server_.known_candidate(*cand,0);
if(c_ptr!=NULL && c_ptr->peers.find(svid)!=c_ptr->peers.end()){ // send only the hash, not the whole message
//FIXME, is this ok ?
DLOG("%04X WARNING, truncating cnd message\n",svid);
return(4+64+10+sizeof(hash_t));}}
//if(msg->data[0]==MSGTYPE_BLK && msg->len>4+64+10){
if(msg->data[0]==MSGTYPE_BLG && msg->len>4+64+10){ // probably only during sync
header_t* h=(header_t*)(msg->data+4+64+10);
if(peer_hs.head.now==h->now && !memcmp(peer_hs.head.nowhash,h->nowhash,SHA256_DIGEST_LENGTH)){
DLOG("%04X WARNING, truncating blk message\n",svid);
return(4+64+10);}}
return(msg->len);
}*/
void deliver(message_ptr msg)
{ extern candidate_ptr nullcnd;
if(killme){
DLOG("%04X KILL detected ! (DELIVER), leaving\n",svid);
return;}
if(do_sync){
return;}
busy=time(NULL);//set peer to busy, TODO, set this flag in other methods too
if(!msg->sent_emplace(svid)){
DLOG("%04X REJECTING download request for %0X4:%08X (late)\n",svid,msg->svid,msg->msid);
return;}
if(msg->len!=message::header_length && !msg->load(svid)){ // sets busy[svid] READONLY ok
DLOG("%04X ERROR failed to load message %0X4:%08X\n",svid,msg->svid,msg->msid);
return;}
assert(msg->data!=NULL);
//special handling of CND messages ... FIXME prevent slow search in candidates by each peer
if(msg->data[0]==MSGTYPE_CND && msg->len>4+64+10+sizeof(hash_t)){
// this is very innefficient !!! server_.condidates_ should be a map of messages that have peers[] ...
hash_s* cand=(hash_s*)(msg->data+4+64+10);
candidate_ptr c_ptr=server_.known_candidate(*cand,0);
if(c_ptr!=nullcnd && c_ptr->peers.find(svid)!=c_ptr->peers.end()){
// send only the hash, not the whole message
DLOG("%04X WARNING, truncating cnd message\n",svid);
message_ptr put_msg(new message(4+64+10+sizeof(hash_t),msg->data));
memcpy(put_msg->data+1,&put_msg->len,3); //FIXME, make this a change_length function in message.hpp
assert(msg->svid);
put_msg->svid=msg->svid; //just for reporting
put_msg->msid=msg->msid; //just for reporting
put_msg->sent.insert(svid);
put_msg->busy.insert(svid);
msg=put_msg;}
else{
//FIXME, create new message and remove msids that are identical to our last_msid list
}}
pio_.lock(); //pio_.lock(); //boost::lock_guard<boost::mutex> lock(pio_); //pio_.lock();
if(BLOCK_MODE){
write_msgs_.push_back(msg);
pio_.unlock();
return;}
if(msg->data[0]==MSGTYPE_STP){
DLOG("%04X SERV in block mode\n",svid);
BLOCK_MODE=srvs_.now;}
bool no_write_in_progress = write_msgs_.empty();
write_msgs_.push_back(msg);
if (no_write_in_progress){
//int len=message_len(write_msgs_.front());
int len=write_msgs_.front()->len;
boost::asio::async_write(socket_,boost::asio::buffer(write_msgs_.front()->data,len),
boost::bind(&peer::handle_write,shared_from_this(),boost::asio::placeholders::error));
}
pio_.unlock();
}
void send_sync(message_ptr put_msg)
{
/*
WAITING for headers 58B95160, maybe need more peers
REQUEST more headers from peer 0001
SENDING block header request for 58B95160
main: peer.hpp:203: void peer::send_sync(message_ptr): Assertion `do_sync' failed.
Aborted
*/
//assert(do_sync); //FIXME, failed !!!
//FIXME, brakes after handle_read_headers() if there are more headers to load
if(killme){
DLOG("%04X KILL detected ! (SEND SYNC), leaving\n",svid);
return;}
put_msg->load(svid);
busy=time(NULL);//set peer to busy, TODO, set this flag in other methods too
pio_.lock(); //boost::lock_guard<boost::mutex> lock(pio_); //pio_.lock(); //most likely no lock needed
try{
boost::asio::write(socket_,boost::asio::buffer(put_msg->data,put_msg->len));}
catch (std::exception& e){
DLOG("%04X CATCH asio error (send_sync): %s\n",svid,e.what());
leave();}
pio_.unlock();
if(put_msg->len!=message::header_length){
//FIXME, do not unload everything ...
put_msg->unload(svid);}
}
void handle_write(const boost::system::error_code& error) //TODO change this later, dont send each message separately if possible
{
if(killme){
DLOG("%04X KILL detected ! (HANDLE WRITE), leaving\n",svid);
return;}
if (!error) {
pio_.lock(); //boost::lock_guard<boost::mutex> lock(pio_); //pio_.lock();
message* msg=&(*(write_msgs_.front()));
assert(msg->data!=NULL);
assert(!msg->not_busy(svid));
bytes_out+=msg->len;
files_out++;
uint32_t dlen=msg->data_len();
if(dlen!=msg->len){
DLOG("%04X DELIVERED MESSAGE %04X:%08X %02X (len:%d<>%d) [total %lub %uf] LENGTH DIFFERS!\n",svid,
msg->svid,msg->msid,msg->data[0],msg->len,dlen,bytes_out,files_out);}
else{
DLOG("%04X DELIVERED MESSAGE %04X:%08X %02X (len:%d) [total %lub %uf]\n",svid,
msg->svid,msg->msid,msg->data[0],msg->len,bytes_out,files_out);}
if(msg->data[0]==MSGTYPE_STP){
DLOG("%04X SERV sent STOP\n",svid);
write_msgs_.pop_front();
pio_.unlock();
sync_start(true);
return;}
if(!server_.do_sync && !do_sync && (msg->data[0]==MSGTYPE_PUT || msg->data[0]==MSGTYPE_DBP)){
//FIXME, do not add messages that are in last block
if(svid_msid_new[msg->svid]<msg->msid){
svid_msid_new[msg->svid]=msg->msid; // maybe a lock on svid_msid_new would help
DLOG("%04X UPDATE PEER SVID_MSID: %04X:%08X\n",svid,msg->svid,msg->msid);}}
if(msg->len!=message::header_length){
msg->unload(svid);}
else{
msg->busy_erase(svid);}
write_msgs_.pop_front();
if (!write_msgs_.empty()) {
//FIXME, now load the message from db if needed !!! do not do this when inserting in write_msgs_, unless You do not worry about RAM but worry about speed
//int len=message_len(write_msgs_.front());
int len=write_msgs_.front()->len;
boost::asio::async_write(socket_,boost::asio::buffer(write_msgs_.front()->data,len),
boost::bind(&peer::handle_write,shared_from_this(),boost::asio::placeholders::error)); }
pio_.unlock(); }
else {
ELOG("%04X WRITE error %d %s\n",svid,error.value(),error.message().c_str());
leave();
return;}
}
void handle_read_header(const boost::system::error_code& error)
{ extern message_ptr nullmsg;
if(killme){
ELOG("%04X KILL detected ! (HANDLE READ HEADER), leaving\n",svid);
return;}
if(error){
ELOG("%04X READ error %d %s (HEADER)\n",svid,error.value(),error.message().c_str());
leave();
return;}
if(!read_msg_->header(svid)){
ELOG("%04X READ header error\n",svid);
leave();
return;}
if(svid==BANK_MAX && read_msg_->data[0]!=MSGTYPE_INI){ // READONLY ok
ELOG("%04X READ illegal header during startup (%d)\n",svid,(int)read_msg_->data[0]);
leave();
return;}
busy=0; // any incomming data resets the busy flag indicating a responsive peer
bytes_in+=read_msg_->len;
files_in++;
last_active=time(NULL); // protect from disconnect
read_msg_->know_insert_(svid);
if(read_msg_->data[0]==MSGTYPE_USR){ //len can be message::header_length in this case :-(
//FIXME, accept only if needed !!
DLOG("%04X READ bank %04X [len %08X]\n",svid,read_msg_->svid,read_msg_->len);
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data+message::header_length,read_msg_->len*sizeof(user_t)),
boost::bind(&peer::handle_read_bank,shared_from_this(),boost::asio::placeholders::error));
return;}
if(read_msg_->len==message::header_length){ //short ping message
if(srvs_.nodes.size()<=read_msg_->svid || server_.last_srvs_.nodes.size()<=read_msg_->svid){ // READONLY ok
ELOG("%04X ERROR message from unknown server %04X:%08X\n",svid,read_msg_->svid,read_msg_->msid);
leave();
return;}
if(read_msg_->data[0]==MSGTYPE_PUT || read_msg_->data[0]==MSGTYPE_CNP || read_msg_->data[0]==MSGTYPE_BLP || read_msg_->data[0]==MSGTYPE_DBP){
if(!read_msg_->svid){ // READONLY ok
ELOG("%04X ERROR illegal message from readonly server %04X:%08X\n",svid,read_msg_->svid,read_msg_->msid);
leave();
return;}
DLOG("%04X HASH %016lX [%016lX]\n",svid,read_msg_->hash.num,*((uint64_t*)read_msg_->data)); // could be bad allignment
if(read_msg_->data[0]==MSGTYPE_PUT){
read_msg_->data[0]=MSGTYPE_GET;}
if(read_msg_->data[0]==MSGTYPE_CNP){
read_msg_->data[0]=MSGTYPE_CNG;}
if(read_msg_->data[0]==MSGTYPE_BLP){
read_msg_->data[0]=MSGTYPE_BLG;}
if(read_msg_->data[0]==MSGTYPE_DBP){
read_msg_->data[0]=MSGTYPE_DBG;}
if(read_msg_->data[0]==MSGTYPE_GET || read_msg_->data[0]==MSGTYPE_DBG){
pio_.lock(); //boost::lock_guard<boost::mutex> lock(pio_); //pio_.lock();
if(svid_msid_new[read_msg_->svid]<read_msg_->msid){
svid_msid_new[read_msg_->svid]=read_msg_->msid;
DLOG("%04X UPDATE PEER SVID_MSID: %04X:%08X\n",svid,read_msg_->svid,read_msg_->msid);}
pio_.unlock();}
int ret=server_.message_insert(read_msg_);
if(ret){ //NEW, make sure to insert in correct containers
if((ret<0) ||
(read_msg_->data[0]==MSGTYPE_CNG && server_.last_srvs_.now+BLOCKSEC==read_msg_->msid ) ||
(read_msg_->data[0]==MSGTYPE_BLG && server_.last_srvs_.now>=read_msg_->msid && (server_.last_srvs_.nodes[read_msg_->svid].status & SERVER_VIP)) ||
read_msg_->data[0]==MSGTYPE_DBG ||
(read_msg_->data[0]==MSGTYPE_GET && srvs_.nodes[read_msg_->svid].msid==read_msg_->msid-1 && server_.check_msgs_size()<MAX_CHECKQUE)){
DLOG("%04X REQUESTING MESSAGE (%04X:%08X)\n",svid,read_msg_->svid,read_msg_->msid);
#ifdef DEBUG
if(!do_sync && !sync_hs.do_sync && !peer_hs.do_sync){
boost::this_thread::sleep(boost::posix_time::milliseconds(rand()%1000));}
#endif
deliver(read_msg_);}}} // request message if not known (inserted)
else if(read_msg_->data[0]==MSGTYPE_GET || read_msg_->data[0]==MSGTYPE_CNG || read_msg_->data[0]==MSGTYPE_BLG || read_msg_->data[0]==MSGTYPE_DBG){
if(!read_msg_->svid){ // READONLY ok
ELOG("%04X ERROR illegal message from readonly server %04X:%08X\n",svid,read_msg_->svid,read_msg_->msid);
leave();
return;}
DLOG("%04X HASH %016lX [%016lX]\n",svid,read_msg_->hash.num,*((uint64_t*)read_msg_->data)); // could be bad allignment
if(do_sync){
read_msg_->path=peer_path;
if(read_msg_->load(svid)){ //READONLY ok
DLOG("%04X PROVIDING MESSAGE %04X:%08X %02X (len:%d) (in sync)\n",svid,read_msg_->svid,read_msg_->msid,read_msg_->hash.dat[1],read_msg_->len);
send_sync(read_msg_);} //deliver will not work in do_sync mode
else{
DLOG("%04X FAILED answering request for %04X:%08X (not found in %08X)\n",svid,read_msg_->svid,read_msg_->msid,peer_path);}}
else{
message_ptr msg=server_.message_find(read_msg_,svid);
if(msg!=nullmsg){
if(msg->len>message::header_length){
if(msg->sent.find(svid)!=msg->sent.end()){
//TODO, after reconnecting peer missed messages :-(
DLOG("%04X REJECTING download request for %04X:%08X\n",svid,msg->svid,msg->msid);}
else{
DLOG("%04X PROVIDING MESSAGE %04X:%08X %02X (len:%d)\n",svid,msg->svid,msg->msid,msg->hash.dat[1],msg->len);
#ifdef DEBUG
if(!do_sync && !sync_hs.do_sync && !peer_hs.do_sync){
boost::this_thread::sleep(boost::posix_time::milliseconds(rand()%1000));}
#endif
deliver(msg);}} // must force deliver without checks
else{ // no real message available
DLOG("%04X BAD get request\n",svid);}}
else{// concider loading from db if available
DLOG("%04X MESSAGE %04X:%08X not found, concider loading from db\n\n\n",svid,
read_msg_->svid,read_msg_->msid);}}}
else if(read_msg_->data[0]==MSGTYPE_HEA){ // READONLY ok , accept svid==0 below
write_headers();}
else if(read_msg_->data[0]==MSGTYPE_NHR){
write_headers();}
else if(read_msg_->data[0]==MSGTYPE_SER){ //servers request
write_servers();}
else if(read_msg_->data[0]==MSGTYPE_MSL){ //msg list request
write_msglist();}
else if(read_msg_->data[0]==MSGTYPE_USG){
write_bank();}
else if(read_msg_->data[0]==MSGTYPE_PAT){ //set current sync block
memcpy(&peer_path,read_msg_->data+1,4);
DLOG("%04X DEBUG, got sync path %08X\n",svid,peer_path);}
else if(read_msg_->data[0]==MSGTYPE_SOK){
uint32_t now;
memcpy(&now,read_msg_->data+1,4);
ELOG("%04X Authenticated, peer in sync at %08X\n",svid,now);
update_sync();
do_sync=0;}
else{
int n=read_msg_->data[0];
ELOG("%04X ERROR message type %02X (%d) received (%016lX)\n",svid,n,n,*(uint64_t*)read_msg_->data);
leave();
return;}
read_msg_ = boost::make_shared<message>();
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,message::header_length),
boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));}
else{
if(read_msg_->data[0]==MSGTYPE_STP){
DLOG("%04X PEER in block mode\n",svid);
//could enter a different (sync) read sequence here;
//read_msg_->data=(uint8_t*)std::realloc(read_msg_->data,read_msg_->len);
assert(read_msg_->len==1+SHA256_DIGEST_LENGTH);
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data+message::header_length,read_msg_->len-message::header_length),
boost::bind(&peer::handle_read_stop,shared_from_this(),boost::asio::placeholders::error));
return;}
if(read_msg_->data[0]==MSGTYPE_MSP){
DLOG("%04X READ msglist header\n",svid);
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data+message::header_length,read_msg_->len-message::header_length),
boost::bind(&peer::handle_read_msglist,shared_from_this(),boost::asio::placeholders::error));
return;}
if(read_msg_->data[0]==MSGTYPE_BLK){
DLOG("%04X READ block header\n",svid);
assert(read_msg_->len==4+64+10+sizeof(header_t) || read_msg_->len==4+64+10);
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data+message::header_length,read_msg_->len-message::header_length),
boost::bind(&peer::handle_read_block,shared_from_this(),boost::asio::placeholders::error));
return;}
if(read_msg_->data[0]==MSGTYPE_NHD){
DLOG("%04X READ next header\n",svid);
assert(read_msg_->len==8+SHA256_DIGEST_LENGTH+sizeof(headlink_t));
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data+message::header_length,read_msg_->len-message::header_length),
boost::bind(&peer::handle_next_header,shared_from_this(),boost::asio::placeholders::error));
return;}
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data+message::header_length,read_msg_->len-message::header_length),
boost::bind(&peer::handle_read_body,shared_from_this(),boost::asio::placeholders::error));}
}
void update_sync(void) // send current inventory (all msg and dbl messages)
{ std::vector<uint64_t>txs;
std::vector<uint64_t>dbl;
std::vector<uint64_t>blk;
server_.update_list(txs,dbl,blk,svid);
std::string data;
pio_.lock(); //boost::lock_guard<boost::mutex> lock(pio_); //pio_.lock();
for(auto it=txs.begin();it!=txs.end();it++){
svid_msid_new[*(uint16_t*)(((char*)&(*it))+6)]=*(uint32_t*)(((char*)&(*it))+2); //assume txs sorted
data.append((const char*)&(*it),sizeof(uint64_t));}
pio_.unlock();
for(auto it=dbl.begin();it!=dbl.end();it++){
data.append((const char*)&(*it),sizeof(uint64_t));}
for(auto it=blk.begin();it!=blk.end();it++){
data.append((const char*)&(*it),sizeof(uint64_t));}
message_ptr put_msg(new message(data.size()));
memcpy(put_msg->data,data.c_str(),data.size());
DLOG("%04X SENDING update with %d bytes\n",svid,(int)data.size());
send_sync(put_msg);
}
void write_headers()
{ uint32_t from;
memcpy(&from,read_msg_->data+1,4);
uint32_t to=sync_hs.head.now;
if(from>to){ // expect _NHR
DLOG("%04X SENDING block header %08X\n",svid,from);
message_ptr put_msg(new message(8+SHA256_DIGEST_LENGTH+sizeof(headlink_t)));
headlink_t link;
servers linkservers;
linkservers.now=from;
if(!linkservers.header_get()){
//FIXME, new block possibly not ready yet, repeat (sleep) until block ready
ELOG("%04X ERROR, failed to provide header links\n",svid);
uint32_t now=time(NULL);
if(from < now-2*BLOCKSEC || from > now){
leave();} // consider updating client
return;}
put_msg->data[0]=MSGTYPE_NHD;
memcpy(put_msg->data+1,&from,4);
memcpy((char*)put_msg->data+8,(const char*)linkservers.oldhash,SHA256_DIGEST_LENGTH);
linkservers.filllink(link);
memcpy((char*)put_msg->data+8+SHA256_DIGEST_LENGTH,(const char*)&link,sizeof(headlink_t));
send_sync(put_msg);
return;}
uint32_t num=((to-from)/BLOCKSEC)-1;
if(num<=0){
ELOG("%04X ERROR, failed to provide correct request (from:%08X to:%08X)\n",svid,from,to);
leave(); // consider updateing client
return;}
DLOG("%04X SENDING block headers starting after %08X and ending before %08X (num:%d)\n",svid,from,to,num);
message_ptr put_msg(new message(SHA256_DIGEST_LENGTH+sizeof(headlink_t)*num));
char* data=(char*)put_msg->data;
for(uint32_t now=from+BLOCKSEC;now<to;now+=BLOCKSEC){
headlink_t link;
servers linkservers;
linkservers.now=now;
if(!linkservers.header_get()){
ELOG("%04X ERROR, failed to provide header links\n",svid);
uint32_t now=time(NULL);
if(from < now-2*BLOCKSEC || from > now){
leave();} // consider updating client
return;}
if(now==from+BLOCKSEC){
memcpy(data,(const char*)linkservers.oldhash,SHA256_DIGEST_LENGTH);
data+=SHA256_DIGEST_LENGTH;}
linkservers.filllink(link);
memcpy(data,(const char*)&link,sizeof(headlink_t));
data+=sizeof(headlink_t);}
assert(data==(char*)(put_msg->data+SHA256_DIGEST_LENGTH+sizeof(headlink_t)*num));
send_sync(put_msg);
}
void request_next_headers(uint32_t now) //WARNING, this requests a not validated header, FIXME !!!
{ if(killme){
return;}
if(peer_hs.head.now>=now){ // this peer should send this header anytime soon
return;}
DLOG("%04X SENDING block header request for %08X\n",svid,now);
message_ptr put_msg(new message());
put_msg->data[0]=MSGTYPE_NHR;
memcpy(put_msg->data+1,&now,4);
send_sync(put_msg);
}
//FIXME, this will fail because there is another read queued :-(
//must send a new message type (not _HEA)
/*
int len=SHA256_DIGEST_LENGTH+sizeof(headlink_t);
read_msg_ = boost::make_shared<message>(len);
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,len),
boost::bind(&peer::handle_next_headers,shared_from_this(),boost::asio::placeholders::error,now,nowhash));
//char* data=(char*)malloc(SHA256_DIGEST_LENGTH+sizeof(headlink_t));
//ERROR, this is blocking !!!
//int len=boost::asio::read(socket_,boost::asio::buffer(data,SHA256_DIGEST_LENGTH+sizeof(headlink_t)));
}
*/
//void handle_next_headers(const boost::system::error_code& error,uint32_t next_now,uint8_t* next_nowhash)
void handle_next_header(const boost::system::error_code& error)
{ if(error){
ELOG("%04X ERROR reading next headers\n",svid);
leave();
return;}
uint32_t from;
memcpy(&from,read_msg_->data+1,4);
char* data=(char*)read_msg_->data+8;
DLOG("%04X PROCESSING next header\n",svid);
servers peer_ls;
headlink_t* link=(headlink_t*)(data+SHA256_DIGEST_LENGTH);
peer_ls.loadlink(*link,from,data);
server_.add_next_header(from,peer_ls);
//server_.peer_.lock();
//if((!server_.headers.size() &&
// !memcmp(peer_ls.oldhash,server_.last_srvs_.nowhash,SHA256_DIGEST_LENGTH)) ||
// (server_.headers.back().now==from-BLOCKSEC &&
// !memcmp(peer_ls.oldhash,server_.headers.back().nowhash,SHA256_DIGEST_LENGTH))){
// server_.headers.insert(server_.headers.end(),peer_ls);}
//server_.peer_.unlock();
read_msg_ = boost::make_shared<message>(); // continue with a fresh message container
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,message::header_length),
boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));
return;
}
void handle_read_headers()
{ uint32_t to=peer_hs.head.now;
DLOG("%04X READ HEADERS\n",svid);
servers sync_ls; //FIXME, use only the header data not "servers"
server_.get_last_header(sync_ls,sync_hs);
//sync_ls.loadhead(sync_hs.head);
//server_.peer_.lock();
//if(server_.headers.size()){
// DLOG("%04X USE last header\n",svid);
// sync_ls=server_.headers.back();} // FIXME, use pointers/references maybe
//server_.peer_.unlock();
uint32_t from=sync_ls.now;
/*if(opts_.fast){
if(to!=from){
DLOG("%04X HEADERS loaded ? %08X!=%08X\n",svid,to,from);
return;}}
else if(to<=from){ //FIXME, this failes sometimes
DLOG("%04X HEADERS loaded ? %08X<=%08X\n",svid,to,from);
return;}*/
if(to<=from){ //FIXME, this failes sometimes
DLOG("%04X HEADERS loaded (%08X<=%08X)\n",svid,to,from);
return;}
uint32_t num=(to-from)/BLOCKSEC;
assert(num>0);
std::vector<servers> headers(num); //TODO, consider changing this to a list
if(num>1){
//if(server_.slow_sync(false,headers)<0){
// return;}
DLOG("%04X SENDING block headers request\n",svid);
message_ptr put_msg(new message());
put_msg->data[0]=MSGTYPE_HEA;
memcpy(put_msg->data+1,&from,4);
send_sync(put_msg);
DLOG("%04X READING block headers starting after %08X and ending before %08X (num:%d)\n",svid,from,to,num-1);
char* data=(char*)malloc(SHA256_DIGEST_LENGTH+sizeof(headlink_t)*(num-1)); assert(data!=NULL);
int len=0;
try{
len=boost::asio::read(socket_,boost::asio::buffer(data,SHA256_DIGEST_LENGTH+sizeof(headlink_t)*(num-1)));}
catch (std::exception& e){
DLOG("%04X CATCH asio error (handle_read_headers): %s\n",svid,e.what());
free(data);
leave();
return;}
if(len!=(int)(SHA256_DIGEST_LENGTH+sizeof(headlink_t)*(num-1))){
ELOG("%04X READ headers error\n",svid);
free(data);
leave();
return;}
char* d=data+SHA256_DIGEST_LENGTH;
//reed hashes and compare
for(uint32_t i=0,now=from+BLOCKSEC;now<to;now+=BLOCKSEC,i++){
headlink_t* link=(headlink_t*)d;
d+=sizeof(headlink_t);
if(!i){
headers[i].loadlink(*link,now,data);}
else{
headers[i].loadlink(*link,now,(char*)headers[i-1].nowhash);}
headers[i].header_print();
} //assert(i==num-1);
free(data);
if(memcmp(headers[num-2].nowhash,peer_hs.head.oldhash,SHA256_DIGEST_LENGTH)){
ELOG("%04X ERROR, hashing header chain :-(\n",svid);
char hash[2*SHA256_DIGEST_LENGTH];
ed25519_key2text(hash,headers[num-2].nowhash,SHA256_DIGEST_LENGTH);
ELOG("%04X NOWHASH nowhash %.*s\n",svid,2*SHA256_DIGEST_LENGTH,hash);
ed25519_key2text(hash,peer_hs.head.oldhash,SHA256_DIGEST_LENGTH);
ELOG("%04X NOWHASH oldhash %.*s\n",svid,2*SHA256_DIGEST_LENGTH,hash);
leave();
return;}}
headers[num-1].loadhead(peer_hs.head);
if(memcmp(headers[0].oldhash,sync_ls.nowhash,SHA256_DIGEST_LENGTH)){
ELOG("%04X ERROR, initial oldhash mismatch :-(\n",svid);
char hash[2*SHA256_DIGEST_LENGTH];
ed25519_key2text(hash,headers[0].oldhash,SHA256_DIGEST_LENGTH);
ELOG("%04X NOWHASH got %.*s\n",svid,2*SHA256_DIGEST_LENGTH,hash);
ed25519_key2text(hash,sync_ls.nowhash,SHA256_DIGEST_LENGTH);
ELOG("%04X NOWHASH have %.*s\n",svid,2*SHA256_DIGEST_LENGTH,hash);
ELOG("%04X Maybe start syncing from an older block (peer will disconnect)\n\n",svid);
leave();
return;}
DLOG("%04X HASHES loaded\n",svid);
//server_.slow_sync(true,headers);
server_.add_headers(headers);
// send current sync path
//server_.peer_.lock();
if(srvs_.now && server_.do_sync){
message_ptr put_msg(new message());
put_msg->data[0]=MSGTYPE_PAT;
memcpy(put_msg->data+1,&srvs_.now,4);
send_sync(put_msg);}
//server_.peer_.unlock();
return;
}
void write_msglist()
{ servers header;
assert(read_msg_->data!=NULL);
memcpy(&header.now,read_msg_->data+1,4);
if(!header.header_get()){
DLOG("%04X FAILED to read header %08X for svid: %04X\n",svid,header.now,svid); //TODO, send error
return;}
uint8_t *sigdata=NULL;
uint32_t nok=0;
header.get_signatures(header.now,sigdata,nok);
header.vok=(uint16_t)nok;
int len=12+header.vok*sizeof(svsi_t)+SHA256_DIGEST_LENGTH+header.msg*(2+4+SHA256_DIGEST_LENGTH);
message_ptr put_msg(new message(len));
put_msg->data[0]=MSGTYPE_MSP;
memcpy(put_msg->data+1,&len,3); //bigendian
if(sigdata!=NULL){
memcpy(put_msg->data+4,sigdata,8+header.vok*sizeof(svsi_t));
free(sigdata);}
else{
memcpy(put_msg->data+4,&header.now,4);
memcpy(put_msg->data+8,&nok,4);}
if(header.msgl_get((char*)(put_msg->data+12+header.vok*sizeof(svsi_t)))!=(int)(SHA256_DIGEST_LENGTH+header.msg*(2+4+SHA256_DIGEST_LENGTH))){
DLOG("%04X FAILED to read msglist %08X with %d signatures\n",svid,header.now,header.vok); //TODO, send error
return;}
DLOG("%04X SENDING block msglist %08X with %d signatures\n",svid,header.now,header.vok); //TODO, send error
send_sync(put_msg);
}
void handle_read_msglist(const boost::system::error_code& error)
{ if(error){
ELOG("%04X ERROR reading msglist\n",svid);
leave();
return;}
servers header;
assert(read_msg_->data!=NULL);
memcpy(&header.now,read_msg_->data+4,4);
if(server_.get_msglist!=header.now){
ELOG("%04X ERROR got wrong msglist id\n",svid); // consider updating server
read_msg_ = boost::make_shared<message>();
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,message::header_length),
boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));
return;}
header.header_get();
uint32_t nok;
memcpy(&nok,read_msg_->data+8,4);
header.vok=(uint16_t)nok;
if(read_msg_->len!=(12+header.vok*sizeof(svsi_t)+SHA256_DIGEST_LENGTH+header.msg*(2+4+SHA256_DIGEST_LENGTH))){
ELOG("%04X ERROR got wrong msglist length\n",svid); // consider updating server
read_msg_ = boost::make_shared<message>();
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,message::header_length),
boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));
return;}
if(memcmp(read_msg_->data+12+header.vok*sizeof(svsi_t),header.msghash,SHA256_DIGEST_LENGTH)){
ELOG("%04X ERROR got wrong msglist msghash\n",svid); // consider updating server
char hash[2*SHA256_DIGEST_LENGTH];
ed25519_key2text(hash,read_msg_->data+8,SHA256_DIGEST_LENGTH);
ELOG("%04X MSGHASH got %.*s\n",svid,2*SHA256_DIGEST_LENGTH,hash);
ed25519_key2text(hash,header.msghash,SHA256_DIGEST_LENGTH);
ELOG("%04X MSGHASH have %.*s\n",svid,2*SHA256_DIGEST_LENGTH,hash);
read_msg_ = boost::make_shared<message>();
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,message::header_length),
boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));
return;}
if(header.vok*2<server_.last_srvs_.vtot && header.vok<opts_.mins){
ELOG("%04X ERROR not enough signatures (%d<(%d/2&%d))\n",svid,header.vok,server_.last_srvs_.vtot,opts_.mins);
read_msg_ = boost::make_shared<message>();
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,message::header_length),
boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));
return;}
header_t head;
header.vno=0;
header.header(head);
server_.last_srvs_.check_signatures(head,(svsi_t*)(read_msg_->data+12),true);
if(head.vok*2<server_.last_srvs_.vtot && head.vok<opts_.mins){
ELOG("%04X ERROR not enough signatures after validation (%d<(%d/2&%d))\n",svid,head.vok,server_.last_srvs_.vtot,opts_.mins);
read_msg_ = boost::make_shared<message>();
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,message::header_length),
boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));
return;}
server_.msgl_process(header,read_msg_->data+12+header.vok*sizeof(svsi_t));
////FIXME, process check and save in one function
//std::map<uint64_t,message_ptr> map;
//header.msgl_map((char*)(read_msg_->data+8),map,opts_.svid);
//header.msgl_hash(map);
////if(!header.msg_check(map)){
//if(memcmp(read_msg_->data+8,header.msghash,SHA256_DIGEST_LENGTH)){ //check again after hash calculation
// ELOG("%04X ERROR msghash check failed\n",svid); // consider updating server
// read_msg_ = boost::make_shared<message>();
// boost::asio::async_read(socket_,
// boost::asio::buffer(read_msg_->data,message::header_length),
// boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));
// return;}
//server_.put_msglist(header.now,map, add message hashtree );
read_msg_ = boost::make_shared<message>();
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,message::header_length),
boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));
}
void write_bank()
{ uint32_t path=read_msg_->msid;
uint16_t bank=read_msg_->svid;
//FIXME !!!
//FIXME !!! check if the first undo directory is needed !!!
//FIXME !!! if peer starts at 'path' and receives messages in 'path' then it has to start from state before path
//FIXME !!! then the path/und files are needed to start in correct position
//FIXME !!!
if(1+(srvs_.now-path)/BLOCKSEC>MAX_UNDO){
ELOG("%04X ERROR, too old sync point\n",svid);
leave();
return;}
//check the numer of users at block time
servers s;
s.get(path);
if(bank>=s.nodes.size()){
ELOG("%04X ERROR, bad bank at sync point\n",svid);
leave();
return;}
std::vector<int> ud;
uint32_t users=s.nodes[bank].users;
//TODO, consider checking that the final hash is correct
char filename[64];
sprintf(filename,"usr/%04X.dat",bank);
int fd=open(filename,O_RDONLY);
int ld=0;
if(fd<0){
ELOG("%04X ERROR, failed to open bank, weird !!!\n",svid);
leave();
return;}
for(uint32_t block=path+BLOCKSEC;block<=srvs_.now;block++){
sprintf(filename,"blk/%03X/%05X/und/%04X.dat",block>>20,block&0xFFFFF,bank);
int uf=open(filename,O_RDONLY);
if(uf<0){
continue;}
DLOG("%04X USING bank %04X block %08X undo %s\n",svid,bank,path,filename);
ud.push_back(uf);}
if(ud.size()){
ld=ud.back();}
int msid=0;
int64_t weight=0;
//SHA256_CTX sha256;
//SHA256_Init(&sha256);
uint64_t csum[4]={0,0,0,0};
for(uint32_t user=0;user<users;msid++){
uint32_t end=user+MESSAGE_CHUNK;
if(end>users){
end=users;}
int len=end-user;
message_ptr put_msg(new message(8+len*sizeof(user_t))); //6Mb working space
put_msg->data[0]=MSGTYPE_USR;
memcpy(put_msg->data+1,&len,3); // this is number of users (max 0x10000)
memcpy(put_msg->data+4,&msid,2); // this is the chunk id
memcpy(put_msg->data+6,&bank,2); // this is the bank
user_t* u=(user_t*)(put_msg->data+8);
for(;user<end;user++,u++){
u->msid=0;
int junk=0;
for(auto it=ud.begin();it!=ud.end();it++,junk++){
read(*it,(char*)u,sizeof(user_t));
if(u->msid){
DLOG("%04X USING bank %04X undo user %08X file %d\n",svid,bank,user,junk);
lseek(fd,sizeof(user_t),SEEK_CUR);
for(it++;it!=ud.end();it++){
lseek(*it,sizeof(user_t),SEEK_CUR);}
goto NEXTUSER;}}
read(fd,u,sizeof(user_t));
if(ld){ //confirm again that the undo file has not changed
user_t v;
v.msid=0;
lseek(ld,-sizeof(user_t),SEEK_CUR);
read(ld,&v,sizeof(user_t));
if(v.msid){ //overwrite user info
memcpy((char*)u,&v,sizeof(user_t));}}
NEXTUSER:;
//print user
DLOG("%04X USER:%04X m:%04X t:%08X s:%04X b:%04X u:%04X l:%08X r:%08X v:%016lX h:%08X\n",svid,
user,u->msid,u->time,u->stat,u->node,u->user,u->lpath,u->rpath,u->weight,*((uint32_t*)(u->csum)));
weight+=u->weight;
//SHA256_Update(&sha256,u,sizeof(user_t));
//FIXME, debug only !!!
#ifndef NDEBUG
{ user_t n;
memcpy(&n,u,sizeof(user_t));
server_.last_srvs_.user_csum(n,bank,user);
if(memcmp(n.csum,u->csum,32)){
ELOG("%04X ERROR !!!, checksum mismatch for user %08X [%08X<>%08X]\n",svid,user,
*((uint32_t*)(n.csum)),*((uint32_t*)(u->csum)));
//exit(-1);
leave();
return;}
}
#endif
server_.last_srvs_.xor4(csum,u->csum);}
DLOG("%04X SENDING bank %04X block %08X chunk %X muser %X sum %016lX hash %08X head %016lX\n",svid,bank,path,msid,user,s.nodes[bank].weight,*((uint32_t*)csum),*(uint64_t*)put_msg->data);
send_sync(put_msg); // send even if we have errors
if(user==users){
//uint8_t hash[32];
//SHA256_Final(hash,&sha256);
//FIXME, should compare with previous hash !!!
if(s.nodes[bank].weight!=weight){
//unlink(filename); //TODO, enable this later
ELOG("%04X ERROR sending bank %04X bad sum %016lX<>%016lX\n",svid,bank,s.nodes[bank].weight,weight);
leave();
break;}
if(memcmp(s.nodes[bank].hash,csum,32)){
//unlink(filename); //TODO, enable this later
ELOG("%04X ERROR sending bank %04X (bad hash)\n",svid,bank);
leave();
break;}}}
close(fd);
for(auto fu : ud){
close(fu);}
}
void handle_read_bank(const boost::system::error_code& error)
{ static uint16_t last_bank=0;
static uint16_t last_msid=0;
static int64_t weight=0;
//static SHA256_CTX sha256;
static uint64_t csum[4]={0,0,0,0};
int fd;
if(error){
ELOG("%04X ERROR reading message\n",svid);
leave();
return;}
if(!server_.do_sync){
DLOG("%04X DEBUG ignore usr message\n",svid);
read_msg_ = boost::make_shared<message>();
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_->data,message::header_length),
boost::bind(&peer::handle_read_header,shared_from_this(),boost::asio::placeholders::error));
return;}
uint16_t bank=read_msg_->svid;
if(!bank || bank>=server_.last_srvs_.nodes.size()){
ELOG("%04X ERROR reading bank %04X (bad num)\n",svid,bank);
leave();
return;}
if(read_msg_->len+0x10000*read_msg_->msid>server_.last_srvs_.nodes[bank].users){
ELOG("%04X ERROR reading bank %04X (too many users)\n",svid,bank);
leave();
return;}
uint64_t hnum=server_.need_bank(bank);
if(!hnum){
DLOG("%04X NO NEED for bank %04X\n",svid,bank);
read_msg_ = boost::make_shared<message>();
boost::asio::async_read(socket_,