forked from libswift/libswift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sendrecv.cpp
2348 lines (2023 loc) · 82.8 KB
/
sendrecv.cpp
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
/*
* sendrecv.cpp
* most of the swift's state machine
*
* Created by Victor Grishchenko on 3/6/09.
* Copyright 2009-2016 TECHNISCHE UNIVERSITEIT DELFT. All rights reserved.
*
*/
// Arno, 2013-06-11: Must come first to ensure SIZE_MAX etc are defined
#include "compat.h"
#include "bin_utils.h"
#include "swift.h"
#include <algorithm> // kill it
#include <cassert>
#include <cfloat>
#include <sstream>
using namespace swift;
using namespace std;
struct event_base *Channel::evbase;
struct event Channel::evrecv;
#define DEBUGTRAFFIC 0
/** Arno: Victor's design allows a sender to choose some data to push to
* a receiver, if that receiver is not HINTing at data. Should be disabled
* when the receiver has a download rate limit.
*/
#define ENABLE_SENDERSIZE_PUSH 0
#define ENABLE_CANCEL 0
/** Arno, 2011-11-24: When rate limit is on and the download is in progress
* we send HINTs for 2 chunks at the moment. This constant can be used to
* get greater granularity. Set to 0 for original behavior.
* Ric: set to 2, it should be smaller than 4 or we need to change the hint
* strategy first
* Ric: 2013-05: We need to always send out at least one req. for each channel.
* Otherwise, if the link between two peers is heavily congested or has a high
* pkt loss rate, ledbat will close the connection. (short explanation)
*/
#define HINT_GRANULARITY 1 // chunks
/** Arno, 2012-03-16: Swift can now tunnel data from CMDGW over UDP to
* CMDGW at another swift instance. This is the default channel ID on UDP
* for that traffic (cf. overlay swarm).
*/
#define CMDGW_TUNNEL_DEFAULT_CHANNEL_ID 0xffffffff
void Channel::AddRequiredHashes(struct evbuffer *evb, bin_t pos, bool isretransmit)
{
// We're either seeder or know what content integrity protection method
// is because seeder told us, so hs_out_ is guiding here so we can
// send peak hashes in first datagram.
// TODO: adjust DefaultHandshake from which hs_out_ is derived when
// an authoritative source proves the CIPM is UNIFIED_MERKLE.
//
if (transfer()->ttype() == FILE_TRANSFER)
{
// Arno, 2013-02-25: Need to send peak bins always (also CIPM None)
// to cold clients to communicate tree size
if (ack_in_.is_empty() && hashtree() != NULL && hashtree()->peak_count() > 0)
{
AddUnsignedPeakHashes(evb);
}
if (hs_in_->cont_int_prot_ == POPT_CONT_INT_PROT_MERKLE)
{
if (pos != bin_t::NONE)
AddFileUncleHashes(evb,pos);
}
}
else
{
// LIVE
if (PeerIsSource())
return;
// See if there is a first, or new signed munro to send
bin_t munro = bin_t::NONE;
if (hs_out_->cont_int_prot_ == POPT_CONT_INT_PROT_NONE)
{
// No content integrity protection, so just report current pos as
// source pos == munro
LivePiecePicker *lpp = (LivePiecePicker *)transfer()->picker();
if (lpp == NULL)
{
// I am source
LiveTransfer *lt = (LiveTransfer *)transfer();
munro = lt->GetSourceCurrentPos();
}
else
munro = lpp->GetCurrentPos();
}
else //POPT_CONT_INT_PROT_UNIFIED_MERKLE
{
LiveHashTree *umt = (LiveHashTree *)hashtree();
if (pos == bin_t::NONE)
{
// Initially send last signed munro
munro = umt->GetLastMunro();
}
else
{
// After, send munro required for pos
munro = umt->GetMunro(pos);
if (munro == bin_t::NONE)
return;
}
}
if (pos == bin_t::NONE)
{
// Initially send last signed munro
dprintf("%s #%" PRIu32 " last munro %s\n",tintstr(),id_,munro.str().c_str() );
bool ahead=false;
if (ack_in_right_basebin_ != bin_t::NONE)
{
if (ack_in_right_basebin_ > munro.base_right())
ahead = true;
}
// Don't send when peer has chunks in range, or when it's downloading from us (e.g. chunks earlier than munro)
if (munro != bin_t::NONE && ack_in_.is_empty(munro) && !munro_ack_rcvd_ && !ahead)
{
AddLiveSignedMunroHash(evb,munro);
last_sent_munro_ = munro;
}
}
else
{
// After, send munro required for pos
// Don't repeat if same and not retransmit
bool diff = (munro != last_sent_munro_);
last_sent_munro_ = munro;
dprintf("%s #%" PRIu32 " munro for %s is %s\n",tintstr(),id_,pos.str().c_str(), munro.str().c_str());
if (isretransmit || diff)
AddLiveSignedMunroHash(evb,munro);
if (hs_in_->cont_int_prot_ == POPT_CONT_INT_PROT_UNIFIED_MERKLE)
AddLiveUncleHashes(evb,pos,munro,isretransmit);
}
}
}
void Channel::AddUnsignedPeakHashes(struct evbuffer *evb)
{
for(int i=0; i<hashtree()->peak_count(); i++) {
bin_t peak = hashtree()->peak(i);
evbuffer_add_8(evb, SWIFT_INTEGRITY);
evbuffer_add_chunkaddr(evb,peak,hs_out_->chunk_addr_);
evbuffer_add_hash(evb, hashtree()->peak_hash(i));
dprintf("%s #%" PRIu32 " +phash %s\n",tintstr(),id_,peak.str().c_str());
}
}
// SIGNPEAK
void Channel::AddLiveSignedMunroHash(struct evbuffer *evb, bin_t munro)
{
BinHashSigTuple bhst = BinHashSigTuple::NOBULL;
if (hs_out_->cont_int_prot_ == POPT_CONT_INT_PROT_NONE)
{
// No content integrity protection, create dummy signature tuple to send
uint8_t dummysigdata[SWIFT_CIPM_NONE_SIGLEN];
memset(dummysigdata,0,SWIFT_CIPM_NONE_SIGLEN);
Signature sig(dummysigdata, SWIFT_CIPM_NONE_SIGLEN);
SigTintTuple sigtint(sig, NOW);
bhst = BinHashSigTuple(munro,Sha1Hash::ZERO,sigtint);
}
else
{
// Send signed munro hash
LiveHashTree *umt = (LiveHashTree *)hashtree();
bhst = umt->GetSignedMunro(munro);
}
if (bhst.bin() == bin_t::NONE)
{
dprintf("%s #%" PRIu32 " !mhash %s\n",tintstr(),id_,munro.str().c_str());
return;
}
if (hs_out_->cont_int_prot_ != POPT_CONT_INT_PROT_NONE)
{
evbuffer_add_8(evb, SWIFT_INTEGRITY);
evbuffer_add_chunkaddr(evb,bhst.bin(),hs_out_->chunk_addr_);
evbuffer_add_hash(evb, bhst.hash());
}
dprintf("%s #%" PRIu32 " +mhash %s\n",tintstr(),id_,bhst.bin().str().c_str());
//fprintf(stderr,"AddLiveSignedMunroHash: speak %s %s\n", bhst.bin().str().c_str(), bhst.hash().hex().c_str() );
evbuffer_add_8(evb, SWIFT_SIGNED_INTEGRITY);
evbuffer_add_chunkaddr(evb,bhst.bin(),hs_out_->chunk_addr_);
evbuffer_add_64be(evb, bhst.sigtint().time());
evbuffer_add(evb, bhst.sigtint().sig().bits(), bhst.sigtint().sig().length() );
dprintf("%s #%" PRIu32 " +sigh %s %d\n",tintstr(),id_,bhst.bin().str().c_str(), bhst.sigtint().sig().length() );
}
void Channel::AddFileUncleHashes (struct evbuffer *evb, bin_t pos) {
bin_t peak = hashtree()->peak_for(pos);
// Ric: TODO check (remove data_out_cap??)
// For the moment lets keep the old behaviour
binvector bv;
while (pos!=peak && ((NOW&3)==3 || !pos.parent().contains(data_out_cap_)) &&
ack_in_.is_empty(pos.parent()) ) {
//while (pos!=peak && ack_in_.is_empty(pos.parent()) ) {
bin_t uncle = pos.sibling();
bv.push_back(uncle);
pos = pos.parent();
}
// PPSP -04: Send in descending layer order
binvector::reverse_iterator iter;
for (iter=bv.rbegin(); iter != bv.rend(); iter++) {
bin_t uncle = *iter;
evbuffer_add_8(evb, SWIFT_INTEGRITY);
evbuffer_add_chunkaddr(evb,uncle,hs_out_->chunk_addr_);
evbuffer_add_hash(evb, hashtree()->hash(uncle) );
dprintf("%s #%" PRIu32 " +hash %s\n",tintstr(),id_,uncle.str().c_str());
}
}
//SIGNPEAK
void Channel::AddLiveUncleHashes (struct evbuffer *evb, bin_t pos, bin_t munro, bool isretransmit)
{
binvector bv;
if (isretransmit)
{
// Select all uncles
while (pos!=munro) {
bin_t uncle = pos.sibling();
bv.push_back(uncle);
pos = pos.parent();
}
}
else
{
// Select only unsent uncles
// Ric: TODO check (remove data_out_cap??)
// For the moment lets keep the old behaviour
while (pos!=munro && ((NOW&3)==3 || !pos.parent().contains(data_out_cap_)) &&
ack_in_.is_empty(pos.parent()) ) {
//while (pos!=munro && ack_in_.is_empty(pos.parent()) ) {
bin_t uncle = pos.sibling();
bv.push_back(uncle);
pos = pos.parent();
}
}
// PPSP -04: Send in descending layer order
binvector::reverse_iterator iter;
for (iter=bv.rbegin(); iter != bv.rend(); iter++) {
bin_t uncle = *iter;
evbuffer_add_8(evb, SWIFT_INTEGRITY);
evbuffer_add_chunkaddr(evb,uncle,hs_out_->chunk_addr_);
Sha1Hash h = hashtree()->hash(uncle);
if (h == Sha1Hash::ZERO)
{
// TEMP SIGNPEAKTODO
fprintf(stderr,"SENDING ZERO HASH %s. PRESS\n", uncle.str().c_str() );
fflush(stderr);
}
evbuffer_add_hash(evb,h);
dprintf("%s #%" PRIu32 " +hash %s\n",tintstr(),id_,uncle.str().c_str());
pos = pos.parent();
}
}
bin_t Channel::ImposeHint () {
uint64_t twist = hs_in_->peer_channel_id_; // got no hints, send something randomly
twist &= hashtree()->peak(0).toUInt(); // FIXME may make it semi-seq here
bin_t my_pick = binmap_t::find_complement(ack_in_, *(transfer()->ack_out()), twist);
my_pick.to_twisted(twist);
while (my_pick.base_length()>max(1,(int)cwnd_))
my_pick = my_pick.left();
return my_pick.twisted(twist);
}
bin_t Channel::DequeueHint (bool *retransmitptr) {
bin_t send = bin_t::NONE;
// Arno, 2012-01-23: Extra protection against channel loss, don't send DATA
if (last_recv_time_ < NOW-(3*TINT_SEC))
{
dprintf("%s #%" PRIu32 " dequeue hint aborted, long time no recv %s\n",tintstr(),id_, tintstr(last_recv_time_) );
return bin_t::NONE;
}
// Arno, 2012-07-27: Reenable Victor's retransmit, check for ACKs
*retransmitptr = false;
while (!data_out_tmo_.empty()) {
tintbin tb = data_out_tmo_.front();
data_out_tmo_.pop_front();
if (ack_in_.is_filled(tb.bin)) {
// chunk was acknowledged in meantime
continue;
}
else {
send = tb.bin;
dprintf("%s #%" PRIu32 " dequeuing timed-out %s\n",tintstr(),id_, send.str().c_str() );
*retransmitptr = true;
break;
}
}
if (ENABLE_SENDERSIZE_PUSH && send.is_none() && hint_in_.empty() && last_recv_time_>NOW-rtt_avg_-TINT_SEC) {
bin_t my_pick = ImposeHint(); // FIXME move to the loop
if (!my_pick.is_none()) {
hint_in_size_ += my_pick.base_offset();
hint_in_.push_back(my_pick);
dprintf("%s #%" PRIu32 " *hint %s\n",tintstr(),id_,my_pick.str().c_str());
}
}
dprintf("%s #%" PRIu32 " dequeue empty %d\n",tintstr(),id_, (int)hint_in_.empty() );
while (!hint_in_.empty() && send.is_none()) {
bin_t hint = hint_in_.front().bin;
dprintf("%s #%" PRIu32 " dequeuing cand %s\n",tintstr(),id_, hint.str().c_str() );
tint time = hint_in_.front().time;
hint_in_size_ -= hint_in_.front().bin.base_length();
hint_in_.pop_front();
while (!hint.is_base()) { // FIXME optimize; possible attack
hint_in_.push_front(tintbin(time,hint.right()));
hint_in_size_ += hint_in_.front().bin.base_length();
hint = hint.left();
}
//if (time < NOW-TINT_SEC*3/2 )
// continue; bad idea
if (!ack_in_.is_filled(hint))
send = hint;
}
dprintf("%s #%" PRIu32 " dequeued %s [%" PRIu64 "]\n",tintstr(),id_,send.str().c_str(),hint_in_size_);
return send;
}
void Channel::AddHandshake (struct evbuffer *evb)
{
// If peer not responding, try legacy swift protocol
#if ENABLE_FALLBACK_TO_LEGACY_PROTO == 1
if (sent_since_recv_ >= 3 && last_recv_time_ == 0)
hs_out_->ResetToLegacy();
#endif
int encoded = -1;
if (hs_out_->version_ == VER_SWIFT_LEGACY)
{
//dprintf("%s #%" PRIu32 " +hs swift legacy\n",tintstr(),id_ );
if (hs_in_ == NULL) { // initiating
evbuffer_add_8(evb, SWIFT_INTEGRITY);
evbuffer_add_32be(evb, bin_toUInt32(bin_t::ALL));
evbuffer_add_hash(evb, transfer()->swarm_id().roothash());
dprintf("%s #%" PRIu32 " +hash ALL %s\n",
tintstr(),id_,transfer()->swarm_id().hex().c_str());
}
evbuffer_add_8(evb, SWIFT_HANDSHAKE);
if (send_control_==CLOSE_CONTROL) {
encoded = 0;
}
else
encoded = EncodeID(id_);
evbuffer_add_32be(evb, encoded);
dprintf("%s #%" PRIu32 " +hs %x swift\n",tintstr(),id_,encoded);
}
else // IETF PPSP compliant
{
//dprintf("%s #%" PRIu32 " +hs ppsp\n",tintstr(),id_ );
evbuffer_add_8(evb, SWIFT_HANDSHAKE);
if (send_control_==CLOSE_CONTROL) {
encoded = 0;
}
else
encoded = EncodeID(id_);
evbuffer_add_32be(evb, encoded);
// Send protocol options
std::ostringstream cross;
if (send_control_ !=CLOSE_CONTROL) {
evbuffer_add_8(evb, POPT_VERSION);
evbuffer_add_8(evb, hs_out_->version_);
cross << "v" << hs_out_->version_ << " ";
evbuffer_add_8(evb, POPT_MIN_VERSION);
evbuffer_add_8(evb, hs_out_->min_version_);
cross << "nv" << hs_out_->version_ << " ";
if (hs_in_ == NULL) { // initiating, send swarm ID
evbuffer_add_8(evb, POPT_SWARMID);
if (transfer()->ttype() == FILE_TRANSFER)
{
evbuffer_add_16be(evb, Sha1Hash::SIZE);
evbuffer_add_hash(evb, transfer()->swarm_id().roothash() );
}
else
{
SwarmPubKey spubkey = transfer()->swarm_id().spubkey();
evbuffer_add_16be(evb, spubkey.length() );
evbuffer_add(evb,spubkey.bits(),spubkey.length());
}
cross << "sid " << transfer()->swarm_id().hex() << " ";
}
evbuffer_add_8(evb, POPT_CONT_INT_PROT);
evbuffer_add_8(evb, hs_out_->cont_int_prot_);
cross << "cipm " << hs_out_->cont_int_prot_ << " ";
if (hs_out_->cont_int_prot_ == POPT_CONT_INT_PROT_MERKLE)
{
evbuffer_add_8(evb, POPT_MERKLE_HASH_FUNC);
evbuffer_add_8(evb, hs_out_->merkle_func_);
cross << "mhf " << hs_out_->merkle_func_ << " ";
}
if (transfer()->ttype() == LIVE_TRANSFER && hs_out_->cont_int_prot_ != POPT_CONT_INT_PROT_NONE)
{
evbuffer_add_8(evb, POPT_LIVE_SIG_ALG);
evbuffer_add_8(evb, hs_out_->live_sig_alg_);
cross << "lsa " << hs_out_->live_sig_alg_ << " ";
}
evbuffer_add_8(evb, POPT_CHUNK_ADDR);
evbuffer_add_8(evb, hs_out_->chunk_addr_);
cross << "cam " << hs_out_->chunk_addr_ << " ";
if (transfer()->ttype() == LIVE_TRANSFER)
{
evbuffer_add_8(evb, POPT_LIVE_DISC_WND);
// For POPT_CHUNK_ADDR_CHUNK32, saves all chunks
// PPSPTODO forget
if (hs_out_->chunk_addr_ == POPT_CHUNK_ADDR_BIN32 || hs_out_->chunk_addr_ == POPT_CHUNK_ADDR_CHUNK32)
evbuffer_add_32be(evb, (uint32_t)hs_out_->live_disc_wnd_);
else
evbuffer_add_64be(evb, hs_out_->live_disc_wnd_);
cross << "ldw " << std::hex << hs_out_->live_disc_wnd_ << std::dec << " ";
}
}
dprintf("%s #%" PRIu32 " +hs %x ppsp %s\n",tintstr(),id_,encoded, cross.str().c_str() );
evbuffer_add_8(evb, POPT_END);
}
have_out_.clear();
}
void Channel::Send () {
dprintf("%s #%" PRIu32 " Send called \n",tintstr(),id_);
struct evbuffer *evb = evbuffer_new();
uint32_t pcid = 0;
if (hs_in_ != NULL)
pcid = hs_in_->peer_channel_id_;
evbuffer_add_32be(evb,pcid);
bin_t data = bin_t::NONE;
int evbnonadplen = 0;
if (send_control_==CLOSE_CONTROL) // Arno: send explicit close
AddHandshake(evb);
else
{
if (is_established()) {
// FIXME: seeder check
AddHave(evb);
AddAck(evb);
//LIVE
if (hashtree() == NULL || !hashtree()->is_complete()) {
AddHint(evb);
/* Gertjan fix: 7aeea65f3efbb9013f601b22a57ee4a423f1a94d
"Only call Reschedule for 'reverse PEX' if the channel is in keep-alive mode"
*/
AddPexReq(evb);
if (ENABLE_CANCEL)
AddCancel(evb);
}
AddPex(evb);
TimeoutDataOut();
data = AddData(evb);
} else {
AddHandshake(evb);
AddHave(evb); // Arno, 2011-10-28: from AddHandShake. Why double?
AddHave(evb);
AddAck(evb);
}
}
lastsendwaskeepalive_ = (evbuffer_get_length(evb) == 4);
if (evbuffer_get_length(evb)==4) {// only the channel id; bare keep-alive
data = bin_t::ALL;
}
dprintf("%s #%" PRIu32 " sent %ib %s:%x\n",
tintstr(),id_,(int)evbuffer_get_length(evb),peer().str().c_str(),
pcid);
int r = SendTo(socket_,peer(),evb);
if (r==-1)
print_error("swift can't send datagram");
else
raw_bytes_up_ += r;
last_send_time_ = NOW;
sent_since_recv_++;
dgrams_sent_++;
evbuffer_free(evb);
Reschedule();
}
void Channel::AddHint (struct evbuffer *evb) {
// LIVE source
if (transfer()->picker() == NULL)
return;
// RATELIMIT
// Policy is to not send hints when we are above speed limit
if (transfer()->GetCurrentSpeed(DDIR_DOWNLOAD) > transfer()->GetMaxSpeed(DDIR_DOWNLOAD)) {
if (DEBUGTRAFFIC)
fprintf(stderr,"hint: forbidden#");
return;
}
FileTransfer * ft = (FileTransfer *)transfer();
if (ft->hashtree()->is_complete())
return;
// 1. Calc max of what we are allowed to request, uncongested bandwidth wise
tint plan_for = max(TINT_SEC*HINT_TIME,rtt_avg_*4);
tint timed_out = NOW - plan_for*2;
std::deque<bin_t> tbc;
while ( !hint_out_.empty() && hint_out_.front().time < timed_out ) {
bin_t hint = hint_out_.front().bin;
hint_out_size_ -= hint.base_length();
hint_out_.pop_front();
// Ric: keep track of what we want to remove
tbc.push_back(hint);
dprintf("%s #%" PRIu32 " remove hint %s\n",tintstr(),id_,hint.str().c_str());
}
int first_plan_pck = max ( (tint)1, plan_for / dip_avg_ );
// Riccardo, 2012-04-04: Actually allowed is max minus what we already asked for
int queue_allowed_hints = max(0,first_plan_pck-(int)hint_out_size_);
// RATELIMIT
// 2. Calc max of what is allowed by the rate limiter
int rate_allowed_hints = INT_MAX;
uint64_t rough_global_hint_out_size = 0; // rough estimate, as hint_out_ clean up is not done for all channels
bool count_hints = false;
if (transfer()->GetMaxSpeed(DDIR_DOWNLOAD) < DBL_MAX)
{
channels_t::iterator iter;
for (iter=transfer()->GetChannels()->begin(); iter!=transfer()->GetChannels()->end(); iter++)
{
Channel *c = *iter;
if (c != NULL)
rough_global_hint_out_size += c->hint_out_size_;
}
// Policy: this channel is allowed to hint at the limit - global_hinted_at
// Handle MaxSpeed = unlimited
double rate_hints_limit_float = HINT_TIME*transfer()->GetMaxSpeed(DDIR_DOWNLOAD)/((double)transfer()->chunk_size());
// Ric: slow down if we just started the connection
double slowStart = (double)LONG_MAX;
tint running = now_t::now-start;
// It takes ~3 sec to get a stable DL speed estimation
if (running<TINT_SEC*3) {// && hint_out_size_>1) {
count_hints = true;
slowStart = rate_hints_limit_float*running/TINT_SEC;
if (slowStart>transfer()->GetSlowStartHints())
slowStart = slowStart-transfer()->GetSlowStartHints();
else
slowStart = 0;
if (DEBUGTRAFFIC)
fprintf(stderr, "slowStart: %lf [%" PRIu32 "]\n", slowStart, transfer()->GetSlowStartHints());
}
int rate_hints_limit = (int)min(slowStart,rate_hints_limit_float);
// Actually allowed is max minus what we already asked for, globally (=all channels)
rate_allowed_hints = max(0,rate_hints_limit-(int)rough_global_hint_out_size);
}
if (DEBUGTRAFFIC)
fprintf(stderr,"hint c%" PRIu32 ": %lf want %d qallow %d rallow %d chanout %" PRIu64 " globout %" PRIu64 "\n", id(), transfer()->GetCurrentSpeed(DDIR_DOWNLOAD), first_plan_pck, queue_allowed_hints, rate_allowed_hints, hint_out_size_, rough_global_hint_out_size );
// 3. Take the smallest allowance from rate and queue limit
uint64_t plan_pck = (uint64_t)min(rate_allowed_hints,queue_allowed_hints);
// 4. Ask allowance in blocks of chunks to get pipelining going from serving peer.
// Arno, 2012-10-30: not HINT_GRANULARITY for LIVE
if (hint_out_size_ == 0 || plan_pck >= HINT_GRANULARITY || transfer()->ttype() == LIVE_TRANSFER)
{
bin_t hint = bin_t::NONE;
if (transfer()->ttype() == LIVE_TRANSFER)
hint = transfer()->picker()->Pick(ack_in_,plan_pck,NOW+plan_for*2,id_);
else {
uint64_t max_hints = 32;
if (hint_out_size_<max_hints && plan_pck > 0) {
int want = min(max_hints-hint_out_size_, plan_pck);
//fprintf(stderr, "want %d\tplan %d\n", want, plan_pck);
hint = DequeueHintOut(want);
if (hint.is_none()) {
bin_t res = transfer()->picker()->Pick(ack_in_,plan_pck,NOW+plan_for*2,id_);
if (!res.is_none()) {
hint_queue_out_.push_back( tintbin(NOW,res));
hint_queue_out_size_ += res.base_length();
hint = DequeueHintOut(max_hints-hint_out_size_);
}
}
}
}
if (!hint.is_none()) {
if (DEBUGTRAFFIC)
{
fprintf(stderr,"hint c%d: ask %s\n", id(), hint.str().c_str() );
}
evbuffer_add_8(evb, SWIFT_REQUEST);
evbuffer_add_chunkaddr(evb,hint,hs_out_->chunk_addr_);
dprintf("%s #%" PRIu32 " +hint %s [%" PRIi64 "]\n",tintstr(),id_,hint.str().c_str(),hint_out_size_);
dprintf("%s #%" PRIu32 " +hint base %s width %d\n",tintstr(),id_,hint.base_left().str().c_str(), (int)hint.base_length() );
//fprintf(stderr,"send c%d: HINTLEN %i\n", id(), hint.base_length());
//fprintf(stderr,"HL %i ", hint.base_length());
#if ENABLE_CANCEL == 1
// Ric: final cancel the hints that have been removed
while (!tbc.empty()) {
bin_t c = tbc.front();
if (!c.contains(hint) && !hint.contains(c))
cancel_out_.push_back(c);
else if (c.contains(hint))
while (c.contains(hint) && c!=hint) {
if (c>hint)
c.to_left();
else
c.to_right();
cancel_out_.push_back(c.sibling());
}
else if (c == hint)
break;
tbc.pop_front();
}
#endif
hint_out_.push_back(hint);
hint_out_size_ += hint.base_length();
// Ric: keep track of the outstanding hints
if (count_hints)
transfer()->SetSlowStartHints(hint.base_length());
// RTTFIX
if (rtt_hint_tintbin_.bin == bin_t::NONE)
{
rtt_hint_tintbin_.bin = hint.base_left();
rtt_hint_tintbin_.time = NOW;
}
return;
}
else
dprintf("%s #%" PRIu32 " Xhint\n",tintstr(),id_);
}
#if ENABLE_CANCEL == 1
// add the temporary cancel bin to the actual cancel queue
while (!tbc.empty()) {
cancel_out_.push_back(tbc.front());
tbc.pop_front();
}
#endif
}
static int ChunkAddrSize(popt_chunk_addr_t ca)
{
switch(ca)
{
case POPT_CHUNK_ADDR_BIN32:
return 4;
case POPT_CHUNK_ADDR_BYTE64:
return 2*8;
case POPT_CHUNK_ADDR_CHUNK32:
return 2*4;
case POPT_CHUNK_ADDR_BIN64:
return 8;
case POPT_CHUNK_ADDR_CHUNK64:
return 2*8;
}
return 0;
}
void Channel::AddCancel (struct evbuffer *evb) {
// SIGNPEAKTODO
return;
// Arno, 2013-01-15: take into account chunk addressing scheme
while (SWIFT_MAX_NONDATA_DGRAM_SIZE-evbuffer_get_length(evb) >= 1+ChunkAddrSize(hs_out_->chunk_addr_) && !cancel_out_.empty()) {
bin_t cancel = cancel_out_.front();
cancel_out_.pop_front();
evbuffer_add_8(evb, SWIFT_CANCEL);
evbuffer_add_chunkaddr(evb,cancel,hs_out_->chunk_addr_);
dprintf("%s #%" PRIu32 " +cancel %s\n",
tintstr(),id_,cancel.str().c_str());
}
}
bin_t Channel::AddData (struct evbuffer *evb) {
// RATELIMIT
if (transfer()->GetCurrentSpeed(DDIR_UPLOAD) > transfer()->GetMaxSpeed(DDIR_UPLOAD)) {
transfer()->OnSendNoData();
return bin_t::NONE;
}
//LIVE
if (transfer()->ttype() == FILE_TRANSFER && !hashtree()->size()) // know nothing
return bin_t::NONE;
// Arno: If we are serving content, keep activated
swift::Touch(transfer()->td());
bin_t tosend = bin_t::NONE;
bool isretransmit = false;
tint luft = send_interval_>>4; // may wake up a bit earlier
if (data_out_.size()<cwnd_ &&
last_data_out_time_+send_interval_<=NOW+luft) {
tosend = DequeueHint(&isretransmit);
if (tosend.is_none()) {
dprintf("%s #%" PRIu32 " sendctrl no idea what data to send\n",tintstr(),id_);
if (send_control_!=KEEP_ALIVE_CONTROL && send_control_!=CLOSE_CONTROL)
SwitchSendControl(KEEP_ALIVE_CONTROL);
}
} else
dprintf("%s #%" PRIu32 " sendctrl wait cwnd %f data_out %i next %s\n",
tintstr(),id_,cwnd_,(int)data_out_.size(),tintstr(last_data_out_time_+send_interval_));
// Add required hashes. Also for initial peaks and munros
// Note this is called always, not just when there are requests pending.
AddRequiredHashes(evb,tosend,isretransmit);
if (tosend.is_none()) {// && (last_data_out_time_>NOW-TINT_SEC || data_out_.empty()))
transfer()->OnSendNoData();
return bin_t::NONE; // once in a while, empty data is sent just to check rtt FIXED
}
if (!ack_in_.is_empty()) // TODO: cwnd_>1
data_out_cap_ = tosend;
// Send hashes in separate datagram if first would get too big
SendIfTooBig(evb);
// Add chunk
evbuffer_add_8(evb, SWIFT_DATA);
evbuffer_add_chunkaddr(evb,tosend,hs_out_->chunk_addr_);
// PPSPTODO LEDBAT current system time 64-bit
if (hs_in_ != NULL && hs_in_->version_ == VER_PPSPP_v1)
{
// NOTE: Time updates NOW, so customary behavior where NOW is not
// updated during the handling of a message (just at start) is no longer
// there. Not sure if this matters.
evbuffer_add_64be(evb, Time() );
}
struct evbuffer_iovec vec;
if (evbuffer_reserve_space(evb, transfer()->chunk_size(), &vec, 1) < 0) {
print_error("error on evbuffer_reserve_space");
return bin_t::NONE;
}
dprintf("%s #%" PRIu32 " ?data reading swarm %llu\n",tintstr(),id_, tosend.base_offset()*transfer()->chunk_size() );
ssize_t r = transfer()->GetStorage()->Read((char *)vec.iov_base,
transfer()->chunk_size(),tosend.base_offset()*transfer()->chunk_size());
// TODO: corrupted data, retries, caching
if (r <= 0) {
print_error("error on reading");
dprintf("%s #%" PRIu32 " !data %s\n",tintstr(),id_,tosend.str().c_str());
vec.iov_len = 0;
evbuffer_commit_space(evb, &vec, 1);
return bin_t::NONE;
}
// assert(dgram.space()>=r+4+1);
vec.iov_len = r;
if (evbuffer_commit_space(evb, &vec, 1) < 0) {
print_error("error on evbuffer_commit_space");
return bin_t::NONE;
}
last_data_out_time_ = NOW;
data_out_.push_back(tosend);
bytes_up_ += r;
global_bytes_up += r;
dprintf("%s #%" PRIu32 " +data %s\n",tintstr(),id_,tosend.str().c_str());
// RATELIMIT
// ARNOSMPTODO: count overhead bytes too? Move to Send() then.
transfer_->OnSendData(transfer()->chunk_size());
return tosend;
}
void Channel::SendIfTooBig(struct evbuffer *evb)
{
// Arno, 2011-11-03: May happen when first data packet is sent to empty
// leech, then peak + uncle hashes may be so big that they don't fit in eth
// frame with DATA. Send 2 datagrams then, one with peaks so they have
// a better chance of arriving. Optimistic violation of atomic datagram
// principle.
// Arno, 2013-05-14: Don't work if this is first msg, as peer_channel_id
// will be unknown. Then just continue adding to the first datagram and
// hope for the best.
if (is_established() && transfer()->chunk_size() == SWIFT_DEFAULT_CHUNK_SIZE && evbuffer_get_length(evb) > SWIFT_MAX_NONDATA_DGRAM_SIZE) {
dprintf("%s #%" PRIu32 " fsent %ib %s:%x\n",
tintstr(),id_,(int)evbuffer_get_length(evb),peer().str().c_str(),
hs_in_->peer_channel_id_);
int ret = Channel::SendTo(socket_,peer(),evb); // kind of fragmentation
if (ret > 0)
raw_bytes_up_ += ret;
evbuffer_add_32be(evb, hs_in_->peer_channel_id_);
}
}
void Channel::AddAck (struct evbuffer *evb) {
if (data_in_==tintbin())
//if (data_in_.bin==bin64_t::NONE)
return;
// sometimes, we send a HAVE (e.g. in case the peer did repetitive send)
evbuffer_add_8(evb, data_in_.time==TINT_NEVER?SWIFT_HAVE:SWIFT_ACK);
evbuffer_add_chunkaddr(evb,data_in_.bin,hs_out_->chunk_addr_);
// PPSPTODO LEDBAT one-way delay
if (data_in_.time!=TINT_NEVER)
evbuffer_add_64be(evb, data_in_.time);
if (DEBUGTRAFFIC)
fprintf(stderr,"send c%d: ACK %i\n", id(), bin_toUInt32(data_in_.bin));
have_out_.set(data_in_.bin);
dprintf("%s #%" PRIu32 " +ack %s %" PRIi64 "\n",
tintstr(),id_,data_in_.bin.str().c_str(),data_in_.time);
if (data_in_.bin.layer()>2)
data_in_dbl_ = data_in_.bin;
#if ENABLE_CANCEL == 1
// Ric: check that we are not sending a cancel msg for data_in_
std::deque<bin_t>::iterator it;
bin_t b = data_in_.bin;
for (it=cancel_out_.begin(); it!=cancel_out_.end(); it++) {
bin_t c = *it;
if (c == b) {
cancel_out_.erase(it);
break;
}
// b is always a single chunk :-)
else if (c.contains(b)) {
while (c.contains(b) && c!=b) {
if (c>b) {
cancel_out_.insert(it+1,c.right());
c.to_left();
}
else {
cancel_out_.insert(it+1,c.left());
c.to_right();
}
}
assert (c==b);
cancel_out_.erase(it);
}
}
#endif
data_in_ = tintbin();
//data_in_ = tintbin(NOW,bin64_t::NONE);
}
void Channel::AddHave (struct evbuffer *evb) {
if (!data_in_dbl_.is_none()) { // TODO: do redundancy better
evbuffer_add_8(evb, SWIFT_HAVE);
evbuffer_add_chunkaddr(evb,data_in_dbl_,hs_out_->chunk_addr_);
data_in_dbl_=bin_t::NONE;
}
if (DEBUGTRAFFIC)
fprintf(stderr,"send c%d: HAVE ",id() );
// ZEROSTATE
if (transfer()->ttype() == FILE_TRANSFER && ((FileTransfer *)transfer())->IsZeroState())
{
if (is_established())
return;
// Say we have peaks
for(int i=0; i<hashtree()->peak_count(); i++) {
bin_t peak = hashtree()->peak(i);
evbuffer_add_8(evb, SWIFT_HAVE);
evbuffer_add_chunkaddr(evb,peak,hs_out_->chunk_addr_);
dprintf("%s #%" PRIu32 " +have %s\n",tintstr(),id_,peak.str().c_str());
}
return;
}
// SIGNPEAK
binmap_t *transfer_ack_out_ptr = transfer()->ack_out();
if (hs_in_ != NULL && hs_in_->cont_int_prot_ == POPT_CONT_INT_PROT_UNIFIED_MERKLE )
{
// Arno, 2013-02-26: LIVE SIGNPEAK Cannot send HAVEs not covered by
// signed peak when source. Non-source peers will consequently only
// see and receive chunks covered by signed peaks.
LiveTransfer *lt = (LiveTransfer *)transfer();
if (lt->am_source())
transfer_ack_out_ptr = lt->ack_out_signed();
}
for(int count=0; count<4; count++) {
bin_t ack = binmap_t::find_complement(have_out_, *(transfer_ack_out_ptr), 0); // FIXME: do rotating queue
if (ack.is_none())
break;
ack = transfer_ack_out_ptr->cover(ack);
have_out_.set(ack);
evbuffer_add_8(evb, SWIFT_HAVE);
evbuffer_add_chunkaddr(evb,ack,hs_out_->chunk_addr_);
if (DEBUGTRAFFIC)
fprintf(stderr," %i", bin_toUInt32(ack));
dprintf("%s #%" PRIu32 " +have %s\n",tintstr(),id_,ack.str().c_str());
}
if (DEBUGTRAFFIC)
fprintf(stderr,"\n");
}
void Channel::Recv (struct evbuffer *evb) {
dprintf("%s #%" PRIu32 " recvd %ib\n",tintstr(),id_,(int)evbuffer_get_length(evb)+4);
dgrams_rcvd_++;
if (!transfer()->IsOperational()) {
dprintf("%s #%" PRIu32 " recvd on broken transfer %d \n",tintstr(),id_, transfer()->td() );
CloseOnError();
return;
}
lastrecvwaskeepalive_ = (evbuffer_get_length(evb) == 0);
if (lastrecvwaskeepalive_)
// Update speed measurements such that they decrease when DL stops
transfer()->OnRecvData(0);
if (last_send_time_ && rtt_avg_==TINT_SEC && dev_avg_==0) {
rtt_avg_ = NOW - last_send_time_;
dev_avg_ = rtt_avg_;
dip_avg_ = rtt_avg_;
dprintf("%s #%" PRIu32 " sendctrl rtt init %" PRIi64 "\n",tintstr(),id_,rtt_avg_);
fprintf(stderr,"%s #%" PRIu32 " sendctrl rtt init %" PRIi64 "\n",tintstr(),id_,rtt_avg_);
}
bin_t data = evbuffer_get_length(evb) ? bin_t::NONE : bin_t::ALL;
if (DEBUGTRAFFIC)
fprintf(stderr,"recv c%" PRIu32 ": size " PRISIZET "\n", id(), evbuffer_get_length(evb));
Handshake *hishs = NULL;
if (hs_in_ == NULL) { // first reply from client
if (hs_out_->version_ == VER_SWIFT_LEGACY) // I sent PPSPP_v1 HS, did not respond, now trying legacy
hishs = StaticOnHandshake(peer_,id(),true,VER_SWIFT_LEGACY,evb);
else
hishs = StaticOnHandshake(peer_,id(),false,VER_PPSPP_v1,evb);
if (hishs == NULL)
return;
else
OnHandshake(hishs);
}
while (evbuffer_get_length(evb) && send_control_!=CLOSE_CONTROL) {