forked from irwir/eMule
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDownloadClient.cpp
2532 lines (2295 loc) · 93.5 KB
/
DownloadClient.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
//this file is part of eMule
//Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include "emule.h"
#include <zlib/zlib.h>
#include "UpDownClient.h"
#include "PartFile.h"
#include "OtherFunctions.h"
#include "ListenSocket.h"
#include "PeerCacheSocket.h"
#include "Preferences.h"
#include "SafeFile.h"
#include "Packets.h"
#include "Statistics.h"
#include "ClientCredits.h"
#include "DownloadQueue.h"
#include "ClientUDPSocket.h"
#include "emuledlg.h"
#include "TransferDlg.h"
#include "PeerCacheFinder.h"
#include "Exceptions.h"
#include "clientlist.h"
#include "Kademlia/Kademlia/Kademlia.h"
#include "Kademlia/Kademlia/Prefs.h"
#include "Kademlia/Kademlia/Search.h"
#include "SHAHashSet.h"
#include "SharedFileList.h"
#include "Log.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// members of CUpDownClient
// which are mainly used for downloading functions
CBarShader CUpDownClient::s_StatusBar(16);
void CUpDownClient::DrawStatusBar(CDC* dc, LPCRECT rect, bool onlygreyrect, bool bFlat) const
{
if (g_bLowColorDesktop)
bFlat = true;
COLORREF crNeither;
if (bFlat) {
if (g_bLowColorDesktop)
crNeither = RGB(192, 192, 192);
else
crNeither = RGB(224, 224, 224);
} else {
crNeither = RGB(240, 240, 240);
}
ASSERT(reqfile);
s_StatusBar.SetFileSize(reqfile->GetFileSize());
s_StatusBar.SetHeight(rect->bottom - rect->top);
s_StatusBar.SetWidth(rect->right - rect->left);
s_StatusBar.Fill(crNeither);
if (!onlygreyrect && reqfile && m_abyPartStatus)
{
COLORREF crBoth;
COLORREF crClientOnly;
COLORREF crPending;
COLORREF crNextPending;
if (g_bLowColorDesktop) {
crBoth = RGB(0, 0, 0);
crClientOnly = RGB(0, 0, 255);
crPending = RGB(0, 255, 0);
crNextPending = RGB(255, 255, 0);
} else if (bFlat) {
crBoth = RGB(0, 0, 0);
crClientOnly = RGB(0, 100, 255);
crPending = RGB(0, 150, 0);
crNextPending = RGB(255, 208, 0);
} else {
crBoth = RGB(104, 104, 104);
crClientOnly = RGB(0, 100, 255);
crPending = RGB(0, 150, 0);
crNextPending = RGB(255, 208, 0);
}
char* pcNextPendingBlks = NULL;
if (m_nDownloadState == DS_DOWNLOADING){
pcNextPendingBlks = new char[m_nPartCount];
memset(pcNextPendingBlks, 'N', m_nPartCount); // do not use '_strnset' for uninitialized memory!
for (POSITION pos = m_PendingBlocks_list.GetHeadPosition(); pos != 0; ){
UINT uPart = (UINT)(m_PendingBlocks_list.GetNext(pos)->block->StartOffset / PARTSIZE);
if (uPart < m_nPartCount)
pcNextPendingBlks[uPart] = 'Y';
}
}
for (UINT i = 0; i < m_nPartCount; i++){
if (m_abyPartStatus[i]){
uint64 uEnd;
if ( PARTSIZE*(uint64)(i+1) > reqfile->GetFileSize())
uEnd = reqfile->GetFileSize();
else
uEnd = PARTSIZE*(uint64)(i+1);
if (reqfile->IsComplete(PARTSIZE*(uint64)i,PARTSIZE*(uint64)(i+1)-1, false))
s_StatusBar.FillRange(PARTSIZE*(uint64)i, uEnd, crBoth);
else if (GetSessionDown() > 0 && m_nDownloadState == DS_DOWNLOADING && m_nLastBlockOffset >= PARTSIZE*(uint64)i && m_nLastBlockOffset < uEnd)
s_StatusBar.FillRange(PARTSIZE*(uint64)i, uEnd, crPending);
else if (pcNextPendingBlks != NULL && pcNextPendingBlks[i] == 'Y')
s_StatusBar.FillRange(PARTSIZE*(uint64)i, uEnd, crNextPending);
else
s_StatusBar.FillRange(PARTSIZE*(uint64)i, uEnd, crClientOnly);
}
}
delete[] pcNextPendingBlks;
}
s_StatusBar.Draw(dc, rect->left, rect->top, bFlat);
}
bool CUpDownClient::Compare(const CUpDownClient* tocomp, bool bIgnoreUserhash) const
{
//Compare only the user hash..
if(!bIgnoreUserhash && HasValidHash() && tocomp->HasValidHash())
return !md4cmp(this->GetUserHash(), tocomp->GetUserHash());
if (HasLowID())
{
//User is firewalled.. Must do two checks..
if (GetIP()!=0 && GetIP() == tocomp->GetIP())
{
//The IP of both match
if (GetUserPort()!=0 && GetUserPort() == tocomp->GetUserPort())
//IP-UserPort matches
return true;
if (GetKadPort()!=0 && GetKadPort() == tocomp->GetKadPort())
//IP-KadPort Matches
return true;
}
if (GetUserIDHybrid()!=0
&& GetUserIDHybrid() == tocomp->GetUserIDHybrid()
&& GetServerIP()!=0
&& GetServerIP() == tocomp->GetServerIP()
&& GetServerPort()!=0
&& GetServerPort() == tocomp->GetServerPort())
//Both have the same lowID, Same serverIP and Port..
return true;
#if defined(_DEBUG)
if ( HasValidBuddyID() && tocomp->HasValidBuddyID() )
{
//JOHNTODO: This is for future use to see if this will be needed...
if(!md4cmp(GetBuddyID(), tocomp->GetBuddyID()))
return true;
}
#endif
//Both IP, and Server do not match..
return false;
}
//User is not firewalled.
if (GetUserPort()!=0)
{
//User has a Port, lets check the rest.
if (GetIP() != 0 && tocomp->GetIP() != 0)
{
//Both clients have a verified IP..
if(GetIP() == tocomp->GetIP() && GetUserPort() == tocomp->GetUserPort())
//IP and UserPort match..
return true;
}
else
{
//One of the two clients do not have a verified IP
if (GetUserIDHybrid() == tocomp->GetUserIDHybrid() && GetUserPort() == tocomp->GetUserPort())
//ID and Port Match..
return true;
}
}
if(GetKadPort()!=0)
{
//User has a Kad Port.
if(GetIP() != 0 && tocomp->GetIP() != 0)
{
//Both clients have a verified IP.
if(GetIP() == tocomp->GetIP() && GetKadPort() == tocomp->GetKadPort())
//IP and KadPort Match..
return true;
}
else
{
//One of the users do not have a verified IP.
if (GetUserIDHybrid() == tocomp->GetUserIDHybrid() && GetKadPort() == tocomp->GetKadPort())
//ID and KadProt Match..
return true;
}
}
//No Matches..
return false;
}
// Return bool is not if you asked or not..
// false = Client was deleted!
// true = client was not deleted!
bool CUpDownClient::AskForDownload()
{
if (m_bUDPPending)
{
m_nFailedUDPPackets++;
theApp.downloadqueue->AddFailedUDPFileReasks();
}
m_bUDPPending = false;
if (!(socket && socket->IsConnected())) // already connected, skip all the special checks
{
if (theApp.listensocket->TooManySockets())
{
if (GetDownloadState() != DS_TOOMANYCONNS)
SetDownloadState(DS_TOOMANYCONNS);
return true;
}
m_dwLastTriedToConnect = ::GetTickCount();
// if its a lowid client which is on our queue we may delay the reask up to 20 min, to give the lowid the chance to
// connect to us for its own reask
if (HasLowID() && GetUploadState() == US_ONUPLOADQUEUE && !m_bReaskPending && GetLastAskedTime() > 0){
SetDownloadState(DS_ONQUEUE);
m_bReaskPending = true;
return true;
}
// if we are lowid <-> lowid but contacted the source before already, keep it in the hope that we might turn highid again
if (HasLowID() && !theApp.CanDoCallback(this) && GetLastAskedTime() > 0){
if (GetDownloadState() != DS_LOWTOLOWIP)
SetDownloadState(DS_LOWTOLOWIP);
m_bReaskPending = true;
return true;
}
}
m_dwLastTriedToConnect = ::GetTickCount();
SwapToAnotherFile(_T("A4AF check before tcp file reask. CUpDownClient::AskForDownload()"), true, false, false, NULL, true, true);
SetDownloadState(DS_CONNECTING);
return TryToConnect();
}
bool CUpDownClient::IsSourceRequestAllowed() const
{
return IsSourceRequestAllowed(reqfile);
}
bool CUpDownClient::IsSourceRequestAllowed(CPartFile* partfile, bool sourceExchangeCheck) const
{
DWORD dwTickCount = ::GetTickCount() + CONNECTION_LATENCY;
unsigned int nTimePassedClient = dwTickCount - GetLastSrcAnswerTime();
unsigned int nTimePassedFile = dwTickCount - partfile->GetLastAnsweredTime();
bool bNeverAskedBefore = GetLastAskedForSources() == 0;
UINT uSources = partfile->GetSourceCount();
UINT uValidSources = partfile->GetValidSourcesCount();
if (partfile != reqfile) {
uSources++;
uValidSources++;
}
UINT uReqValidSources = reqfile->GetValidSourcesCount();
return (
//if client has the correct extended protocol
ExtProtocolAvailable() && (SupportsSourceExchange2() || GetSourceExchange1Version() > 1) &&
//AND if we need more sources
reqfile->GetMaxSourcePerFileSoft() > uSources &&
//AND if...
(
//source is not complete and file is very rare
( !m_bCompleteSource
&& (bNeverAskedBefore || nTimePassedClient > SOURCECLIENTREASKS)
&& (uSources <= RARE_FILE/5)
&& (!sourceExchangeCheck || partfile == reqfile || uValidSources < uReqValidSources && uReqValidSources > 3)
) ||
//source is not complete and file is rare
( !m_bCompleteSource
&& (bNeverAskedBefore || nTimePassedClient > SOURCECLIENTREASKS)
&& (uSources <= RARE_FILE || (!sourceExchangeCheck || partfile == reqfile) && uSources <= RARE_FILE / 2 + uValidSources)
&& (nTimePassedFile > SOURCECLIENTREASKF)
&& (!sourceExchangeCheck || partfile == reqfile || uValidSources < SOURCECLIENTREASKS/SOURCECLIENTREASKF && uValidSources < uReqValidSources)
) ||
// OR if file is not rare
( (bNeverAskedBefore || nTimePassedClient > (unsigned)(SOURCECLIENTREASKS * MINCOMMONPENALTY))
&& (nTimePassedFile > (unsigned)(SOURCECLIENTREASKF * MINCOMMONPENALTY))
&& (!sourceExchangeCheck || partfile == reqfile || uValidSources < SOURCECLIENTREASKS/SOURCECLIENTREASKF && uValidSources < uReqValidSources)
)
)
);
}
void CUpDownClient::SendFileRequest()
{
// normally asktime has already been reset here, but then SwapToAnotherFile will return without much work, so check to make sure
SwapToAnotherFile(_T("A4AF check before tcp file reask. CUpDownClient::SendFileRequest()"), true, false, false, NULL, true, true);
ASSERT(reqfile != NULL);
if (!reqfile)
return;
AddAskedCountDown();
if (SupportMultiPacket() || SupportsFileIdentifiers())
{
CSafeMemFile dataFileReq(96);
if (SupportsFileIdentifiers())
{
reqfile->GetFileIdentifier().WriteIdentifier(&dataFileReq);
if (thePrefs.GetDebugClientTCPLevel() > 0)
DebugSend("OP__MultiPacket_Ext2", this, reqfile->GetFileHash());
}
else
{
dataFileReq.WriteHash16(reqfile->GetFileHash());
if (SupportExtMultiPacket()){
dataFileReq.WriteUInt64(reqfile->GetFileSize());
if (thePrefs.GetDebugClientTCPLevel() > 0)
DebugSend("OP__MultiPacket_Ext", this, reqfile->GetFileHash());
}
else{
if (thePrefs.GetDebugClientTCPLevel() > 0)
DebugSend("OP__MultiPacket", this, reqfile->GetFileHash());
}
}
// OP_REQUESTFILENAME + ExtInfo
if (thePrefs.GetDebugClientTCPLevel() > 0)
DebugSend("OP__MPReqFileName", this, reqfile->GetFileHash());
dataFileReq.WriteUInt8(OP_REQUESTFILENAME);
if (GetExtendedRequestsVersion() > 0)
reqfile->WritePartStatus(&dataFileReq);
if (GetExtendedRequestsVersion() > 1)
reqfile->WriteCompleteSourcesCount(&dataFileReq);
// OP_SETREQFILEID
if (thePrefs.GetDebugClientTCPLevel() > 0)
DebugSend("OP__MPSetReqFileID", this, reqfile->GetFileHash());
if (reqfile->GetPartCount() > 1)
dataFileReq.WriteUInt8(OP_SETREQFILEID);
if (IsEmuleClient())
{
SetRemoteQueueFull(true);
SetRemoteQueueRank(0);
}
// OP_REQUESTSOURCES // OP_REQUESTSOURCES2
if (IsSourceRequestAllowed())
{
if (thePrefs.GetDebugClientTCPLevel() > 0) {
DebugSend("OP__MPReqSources", this, reqfile->GetFileHash());
if (GetLastAskedForSources() == 0)
Debug(_T(" first source request\n"));
else
Debug(_T(" last source request was before %s\n"), CastSecondsToHM((GetTickCount() - GetLastAskedForSources())/1000));
}
if (SupportsSourceExchange2()){
dataFileReq.WriteUInt8(OP_REQUESTSOURCES2);
dataFileReq.WriteUInt8(SOURCEEXCHANGE2_VERSION);
const uint16 nOptions = 0; // 16 ... Reserved
dataFileReq.WriteUInt16(nOptions);
}
else{
dataFileReq.WriteUInt8(OP_REQUESTSOURCES);
}
reqfile->SetLastAnsweredTimeTimeout();
SetLastAskedForSources();
if (thePrefs.GetDebugSourceExchange())
AddDebugLogLine(false, _T("SXSend (%s): Client source request; %s, File=\"%s\""),SupportsSourceExchange2() ? _T("Version 2") : _T("Version 1"), DbgGetClientInfo(), reqfile->GetFileName());
}
// OP_AICHFILEHASHREQ - deprecated with fileidentifiers
if (IsSupportingAICH() && !SupportsFileIdentifiers())
{
if (thePrefs.GetDebugClientTCPLevel() > 0)
DebugSend("OP__MPAichFileHashReq", this, reqfile->GetFileHash());
dataFileReq.WriteUInt8(OP_AICHFILEHASHREQ);
}
Packet* packet = new Packet(&dataFileReq, OP_EMULEPROT);
if (SupportsFileIdentifiers())
packet->opcode = OP_MULTIPACKET_EXT2;
else if (SupportExtMultiPacket())
packet->opcode = OP_MULTIPACKET_EXT;
else
packet->opcode = OP_MULTIPACKET;
theStats.AddUpDataOverheadFileRequest(packet->size);
SendPacket(packet, true);
}
else
{
CSafeMemFile dataFileReq(96);
dataFileReq.WriteHash16(reqfile->GetFileHash());
//This is extended information
if (GetExtendedRequestsVersion() > 0)
reqfile->WritePartStatus(&dataFileReq);
if (GetExtendedRequestsVersion() > 1)
reqfile->WriteCompleteSourcesCount(&dataFileReq);
if (thePrefs.GetDebugClientTCPLevel() > 0)
DebugSend("OP__FileRequest", this, reqfile->GetFileHash());
Packet* packet = new Packet(&dataFileReq);
packet->opcode = OP_REQUESTFILENAME;
theStats.AddUpDataOverheadFileRequest(packet->size);
SendPacket(packet, true);
// 26-Jul-2003: removed requesting the file status for files <= PARTSIZE for better compatibility with ed2k protocol (eDonkeyHybrid).
// if the remote client answers the OP_REQUESTFILENAME with OP_REQFILENAMEANSWER the file is shared by the remote client. if we
// know that the file is shared, we know also that the file is complete and don't need to request the file status.
if (reqfile->GetPartCount() > 1)
{
if (thePrefs.GetDebugClientTCPLevel() > 0)
DebugSend("OP__SetReqFileID", this, reqfile->GetFileHash());
CSafeMemFile dataSetReqFileID(16);
dataSetReqFileID.WriteHash16(reqfile->GetFileHash());
packet = new Packet(&dataSetReqFileID);
packet->opcode = OP_SETREQFILEID;
theStats.AddUpDataOverheadFileRequest(packet->size);
SendPacket(packet, true);
}
if (IsEmuleClient())
{
SetRemoteQueueFull(true);
SetRemoteQueueRank(0);
}
if (IsSourceRequestAllowed())
{
if (thePrefs.GetDebugClientTCPLevel() > 0) {
DebugSend("OP__RequestSources", this, reqfile->GetFileHash());
if (GetLastAskedForSources() == 0)
Debug(_T(" first source request\n"));
else
Debug(_T(" last source request was before %s\n"), CastSecondsToHM((GetTickCount() - GetLastAskedForSources())/1000));
}
reqfile->SetLastAnsweredTimeTimeout();
Packet* packet;
if (SupportsSourceExchange2()){
packet = new Packet(OP_REQUESTSOURCES2,19,OP_EMULEPROT);
PokeUInt8(&packet->pBuffer[0], SOURCEEXCHANGE2_VERSION);
const uint16 nOptions = 0; // 16 ... Reserved
PokeUInt16(&packet->pBuffer[1], nOptions);
md4cpy(&packet->pBuffer[3],reqfile->GetFileHash());
}
else{
packet = new Packet(OP_REQUESTSOURCES,16,OP_EMULEPROT);
md4cpy(packet->pBuffer,reqfile->GetFileHash());
}
theStats.AddUpDataOverheadSourceExchange(packet->size);
SendPacket(packet, true);
SetLastAskedForSources();
if (thePrefs.GetDebugSourceExchange())
AddDebugLogLine(false, _T("SXSend (%s): Client source request; %s, File=\"%s\""),SupportsSourceExchange2() ? _T("Version 2") : _T("Version 1"), DbgGetClientInfo(), reqfile->GetFileName());
}
if (IsSupportingAICH())
{
if (thePrefs.GetDebugClientTCPLevel() > 0)
DebugSend("OP__AichFileHashReq", this, reqfile->GetFileHash());
Packet* packet = new Packet(OP_AICHFILEHASHREQ,16,OP_EMULEPROT);
md4cpy(packet->pBuffer,reqfile->GetFileHash());
theStats.AddUpDataOverheadFileRequest(packet->size);
SendPacket(packet, true);
}
}
SetLastAskedTime();
}
void CUpDownClient::SendStartupLoadReq()
{
if (socket==NULL || reqfile==NULL)
{
ASSERT(0);
return;
}
m_fQueueRankPending = 1;
m_fUnaskQueueRankRecv = 0;
if (thePrefs.GetDebugClientTCPLevel() > 0)
DebugSend("OP__StartupLoadReq", this);
CSafeMemFile dataStartupLoadReq(16);
dataStartupLoadReq.WriteHash16(reqfile->GetFileHash());
Packet* packet = new Packet(&dataStartupLoadReq);
packet->opcode = OP_STARTUPLOADREQ;
theStats.AddUpDataOverheadFileRequest(packet->size);
SetDownloadState(DS_ONQUEUE);
SendPacket(packet, true);
}
void CUpDownClient::ProcessFileInfo(CSafeMemFile* data, CPartFile* file)
{
if (file==NULL)
throw GetResString(IDS_ERR_WRONGFILEID) + _T(" (ProcessFileInfo; file==NULL)");
if (reqfile==NULL)
throw GetResString(IDS_ERR_WRONGFILEID) + _T(" (ProcessFileInfo; reqfile==NULL)");
if (file != reqfile)
throw GetResString(IDS_ERR_WRONGFILEID) + _T(" (ProcessFileInfo; reqfile!=file)");
m_strClientFilename = data->ReadString(GetUnicodeSupport()!=utf8strNone);
if (thePrefs.GetDebugClientTCPLevel() > 0)
Debug(_T(" Filename=\"%s\"\n"), m_strClientFilename);
// 26-Jul-2003: removed requesting the file status for files <= PARTSIZE for better compatibility with ed2k protocol (eDonkeyHybrid).
// if the remote client answers the OP_REQUESTFILENAME with OP_REQFILENAMEANSWER the file is shared by the remote client. if we
// know that the file is shared, we know also that the file is complete and don't need to request the file status.
if (reqfile->GetPartCount() == 1)
{
delete[] m_abyPartStatus;
m_abyPartStatus = NULL;
m_nPartCount = reqfile->GetPartCount();
m_abyPartStatus = new uint8[m_nPartCount];
memset(m_abyPartStatus,1,m_nPartCount);
m_bCompleteSource = true;
if (thePrefs.GetDebugClientTCPLevel() > 0)
{
int iNeeded = 0;
UINT i;
for (i = 0; i < m_nPartCount; i++) {
if (!reqfile->IsComplete((uint64)i*PARTSIZE, ((uint64)(i+1)*PARTSIZE)-1, false))
iNeeded++;
}
char* psz = new char[m_nPartCount + 1];
for (i = 0; i < m_nPartCount; i++)
psz[i] = m_abyPartStatus[i] ? '#' : '.';
psz[i] = '\0';
Debug(_T(" Parts=%u %hs Needed=%u\n"), m_nPartCount, psz, iNeeded);
delete[] psz;
}
UpdateDisplayedInfo();
reqfile->UpdateAvailablePartsCount();
// even if the file is <= PARTSIZE, we _may_ need the hashset for that file (if the file size == PARTSIZE)
if (reqfile->m_bMD4HashsetNeeded || (reqfile->IsAICHPartHashSetNeeded() && SupportsFileIdentifiers()
&& GetReqFileAICHHash() != NULL && *GetReqFileAICHHash() == reqfile->GetFileIdentifier().GetAICHHash()))
SendHashSetRequest();
else
SendStartupLoadReq();
reqfile->UpdatePartsInfo();
}
}
void CUpDownClient::ProcessFileStatus(bool bUdpPacket, CSafeMemFile* data, CPartFile* file)
{
if ( !reqfile || file != reqfile )
{
if (reqfile==NULL)
throw GetResString(IDS_ERR_WRONGFILEID) + _T(" (ProcessFileStatus; reqfile==NULL)");
throw GetResString(IDS_ERR_WRONGFILEID) + _T(" (ProcessFileStatus; reqfile!=file)");
}
if (file->GetStatus() == PS_COMPLETE || file->GetStatus() == PS_COMPLETING)
return;
uint16 nED2KPartCount = data->ReadUInt16();
delete[] m_abyPartStatus;
m_abyPartStatus = NULL;
bool bPartsNeeded = false;
int iNeeded = 0;
if (!nED2KPartCount)
{
m_nPartCount = reqfile->GetPartCount();
m_abyPartStatus = new uint8[m_nPartCount];
memset(m_abyPartStatus, 1, m_nPartCount);
bPartsNeeded = true;
m_bCompleteSource = true;
if (bUdpPacket ? (thePrefs.GetDebugClientUDPLevel() > 0) : (thePrefs.GetDebugClientTCPLevel() > 0))
{
for (UINT i = 0; i < m_nPartCount; i++)
{
if (!reqfile->IsComplete((uint64)i*PARTSIZE, ((uint64)(i+1)*PARTSIZE)-1, false))
iNeeded++;
}
}
}
else
{
if (reqfile->GetED2KPartCount() != nED2KPartCount) {
if (thePrefs.GetVerbose()) {
DebugLogWarning(_T("FileName: \"%s\""), m_strClientFilename);
DebugLogWarning(_T("FileStatus: %s"), DbgGetFileStatus(nED2KPartCount, data));
}
CString strError;
strError.Format(_T("ProcessFileStatus - wrong part number recv=%u expected=%u %s"), nED2KPartCount, reqfile->GetED2KPartCount(), DbgGetFileInfo(reqfile->GetFileHash()));
m_nPartCount = 0;
throw strError;
}
m_nPartCount = reqfile->GetPartCount();
m_bCompleteSource = false;
m_abyPartStatus = new uint8[m_nPartCount];
UINT done = 0;
while (done != m_nPartCount)
{
uint8 toread = data->ReadUInt8();
for (UINT i = 0; i != 8; i++)
{
m_abyPartStatus[done] = ((toread>>i)&1)? 1:0;
if (m_abyPartStatus[done])
{
if (!reqfile->IsComplete((uint64)done*PARTSIZE, ((uint64)(done+1)*PARTSIZE)-1, false)){
bPartsNeeded = true;
iNeeded++;
}
}
done++;
if (done == m_nPartCount)
break;
}
}
}
if (bUdpPacket ? (thePrefs.GetDebugClientUDPLevel() > 0) : (thePrefs.GetDebugClientTCPLevel() > 0))
{
TCHAR* psz = new TCHAR[m_nPartCount + 1];
UINT i;
for (i = 0; i < m_nPartCount; i++)
psz[i] = m_abyPartStatus[i] ? _T('#') : _T('.');
psz[i] = _T('\0');
Debug(_T(" Parts=%u %s Needed=%u\n"), m_nPartCount, psz, iNeeded);
delete[] psz;
}
UpdateDisplayedInfo(bUdpPacket);
reqfile->UpdateAvailablePartsCount();
// NOTE: This function is invoked from TCP and UDP socket!
if (!bUdpPacket)
{
if (!bPartsNeeded)
{
SetDownloadState(DS_NONEEDEDPARTS);
SwapToAnotherFile(_T("A4AF for NNP file. CUpDownClient::ProcessFileStatus() TCP"), true, false, false, NULL, true, true);
}
else if (reqfile->m_bMD4HashsetNeeded || (reqfile->IsAICHPartHashSetNeeded() && SupportsFileIdentifiers()
&& GetReqFileAICHHash() != NULL && *GetReqFileAICHHash() == reqfile->GetFileIdentifier().GetAICHHash())) //If we are using the eMule filerequest packets, this is taken care of in the Multipacket!
SendHashSetRequest();
else
SendStartupLoadReq();
}
else
{
if (!bPartsNeeded)
{
SetDownloadState(DS_NONEEDEDPARTS);
//SwapToAnotherFile(_T("A4AF for NNP file. CUpDownClient::ProcessFileStatus() UDP"), true, false, false, NULL, true, false);
}
else
SetDownloadState(DS_ONQUEUE);
}
reqfile->UpdatePartsInfo();
}
bool CUpDownClient::AddRequestForAnotherFile(CPartFile* file){
for (POSITION pos = m_OtherNoNeeded_list.GetHeadPosition();pos != 0;){
if (m_OtherNoNeeded_list.GetNext(pos) == file)
return false;
}
for (POSITION pos = m_OtherRequests_list.GetHeadPosition();pos != 0;){
if (m_OtherRequests_list.GetNext(pos) == file)
return false;
}
m_OtherRequests_list.AddTail(file);
file->A4AFsrclist.AddTail(this); // [enkeyDEV(Ottavio84) -A4AF-]
return true;
}
void CUpDownClient::ClearDownloadBlockRequests()
{
for (POSITION pos = m_PendingBlocks_list.GetHeadPosition();pos != 0;){
Pending_Block_Struct *pending = m_PendingBlocks_list.GetNext(pos);
if (reqfile){
reqfile->RemoveBlockFromList(pending->block->StartOffset, pending->block->EndOffset);
}
delete pending->block;
// Not always allocated
if (pending->zStream){
inflateEnd(pending->zStream);
delete pending->zStream;
}
delete pending;
}
m_PendingBlocks_list.RemoveAll();
}
void CUpDownClient::SetDownloadState(EDownloadState nNewState, LPCTSTR pszReason){
if (m_nDownloadState != nNewState){
switch( nNewState )
{
case DS_CONNECTING:
m_dwLastTriedToConnect = ::GetTickCount();
break;
case DS_TOOMANYCONNSKAD:
//This client had already been set to DS_CONNECTING.
//So we reset this time so it isn't stuck at TOOMANYCONNS for 20mins.
m_dwLastTriedToConnect = ::GetTickCount()-20*60*1000;
break;
case DS_WAITCALLBACKKAD:
case DS_WAITCALLBACK:
break;
case DS_NONEEDEDPARTS:
// Since tcp asks never sets reask time if the result is DS_NONEEDEDPARTS
// If we set this, we will not reask for that file until some time has passed.
SetLastAskedTime();
//DontSwapTo(reqfile);
/*default:
switch( m_nDownloadState )
{
case DS_WAITCALLBACK:
case DS_WAITCALLBACKKAD:
break;
default:
m_dwLastTriedToConnect = ::GetTickCount()-20*60*1000;
break;
}
break;*/
}
if (reqfile){
if(nNewState == DS_DOWNLOADING){
if(thePrefs.GetLogUlDlEvents())
AddDebugLogLine(DLP_VERYLOW, false, _T("Download session started. User: %s in SetDownloadState(). New State: %i"), DbgGetClientInfo(), nNewState);
reqfile->AddDownloadingSource(this);
}
else if(m_nDownloadState == DS_DOWNLOADING){
reqfile->RemoveDownloadingSource(this);
}
}
if(nNewState == DS_DOWNLOADING && socket){
socket->SetTimeOut(CONNECTION_TIMEOUT*4);
}
if (m_nDownloadState == DS_DOWNLOADING ){
if(socket)
socket->SetTimeOut(CONNECTION_TIMEOUT);
if (thePrefs.GetLogUlDlEvents()) {
switch( nNewState )
{
case DS_NONEEDEDPARTS:
pszReason = _T("NNP. You don't need any parts from this client.");
}
if(thePrefs.GetLogUlDlEvents())
AddDebugLogLine(DLP_VERYLOW, false, _T("Download session ended: %s User: %s in SetDownloadState(). New State: %i, Length: %s, Payload: %s, Transferred: %s, Req blocks not yet completed: %i."), pszReason, DbgGetClientInfo(), nNewState, CastSecondsToHM(GetDownTimeDifference(false)/1000), CastItoXBytes(GetSessionPayloadDown(), false, false), CastItoXBytes(GetSessionDown(), false, false), m_PendingBlocks_list.GetCount());
}
ResetSessionDown();
// -khaos--+++> Extended Statistics (Successful/Failed Download Sessions)
if ( m_bTransferredDownMini && nNewState != DS_ERROR )
thePrefs.Add2DownSuccessfulSessions(); // Increment our counters for successful sessions (Cumulative AND Session)
else
thePrefs.Add2DownFailedSessions(); // Increment our counters failed sessions (Cumulative AND Session)
thePrefs.Add2DownSAvgTime(GetDownTimeDifference()/1000);
// <-----khaos-
m_nDownloadState = (_EDownloadState)nNewState;
ClearDownloadBlockRequests();
m_nDownDatarate = 0;
m_AvarageDDR_list.RemoveAll();
m_nSumForAvgDownDataRate = 0;
if (nNewState == DS_NONE){
delete[] m_abyPartStatus;
m_abyPartStatus = NULL;
m_nPartCount = 0;
}
if (socket && nNewState != DS_ERROR )
socket->DisableDownloadLimit();
}
m_nDownloadState = (_EDownloadState)nNewState;
if( GetDownloadState() == DS_DOWNLOADING ){
if ( IsEmuleClient() )
SetRemoteQueueFull(false);
SetRemoteQueueRank(0);
SetAskedCountDown(0);
}
UpdateDisplayedInfo(true);
}
}
void CUpDownClient::ProcessHashSet(const uchar* packet, uint32 size, bool bFileIdentifiers)
{
CSafeMemFile data(packet, size);
if (bFileIdentifiers)
{
if (!m_fHashsetRequestingMD4 && !m_fHashsetRequestingAICH)
throw CString(_T("unwanted hashset2"));
CFileIdentifierSA fileIdent;
if (!fileIdent.ReadIdentifier(&data))
throw CString(_T("Invalid FileIdentifier"));
if (reqfile == NULL || !reqfile->GetFileIdentifier().CompareRelaxed(fileIdent))
{
CheckFailedFileIdReqs(packet);
throw GetResString(IDS_ERR_WRONGFILEID) + _T(" (ProcessHashSet2)");
}
bool bMD4 = m_fHashsetRequestingMD4 != 0;
bool bAICH = m_fHashsetRequestingAICH != 0;
if (!reqfile->GetFileIdentifier().ReadHashSetsFromPacket(&data, bMD4, bAICH))
{
if (m_fHashsetRequestingMD4)
reqfile->m_bMD4HashsetNeeded = true;
if (m_fHashsetRequestingAICH)
reqfile->SetAICHHashSetNeeded(true);
m_fHashsetRequestingMD4 = 0;
m_fHashsetRequestingAICH = 0;
throw GetResString(IDS_ERR_BADHASHSET);
}
if (m_fHashsetRequestingMD4 && !bMD4)
{
DebugLogWarning(_T("Client was unable to deliver requested MD4 hashset (shouldn't happen) - %s, file: %s"), DbgGetClientInfo(), reqfile->GetFileName());
reqfile->m_bMD4HashsetNeeded = true;
}
else if (m_fHashsetRequestingMD4)
DebugLog(_T("Received valid MD4 Hashset (FileIdentifiers) form %s, file: %s"), DbgGetClientInfo(), reqfile->GetFileName());
if (m_fHashsetRequestingAICH && !bAICH)
{
DebugLogWarning(_T("Client was unable to deliver requested AICH part hashset, asking other clients - %s, file: %s"), DbgGetClientInfo(), reqfile->GetFileName());
reqfile->SetAICHHashSetNeeded(true);
}
else if (m_fHashsetRequestingAICH)
DebugLog(_T("Received valid AICH Part Hashset form %s, file: %s"), DbgGetClientInfo(), reqfile->GetFileName());
m_fHashsetRequestingMD4 = 0;
m_fHashsetRequestingAICH = 0;
}
else
{
if (!m_fHashsetRequestingMD4)
throw CString(_T("unwanted hashset"));
if ( (!reqfile) || md4cmp(packet,reqfile->GetFileHash()))
{
CheckFailedFileIdReqs(packet);
throw GetResString(IDS_ERR_WRONGFILEID) + _T(" (ProcessHashSet)");
}
m_fHashsetRequestingMD4 = 0;
if (!reqfile->GetFileIdentifier().LoadMD4HashsetFromFile(&data, true))
{
reqfile->m_bMD4HashsetNeeded = true;
throw GetResString(IDS_ERR_BADHASHSET);
}
}
SendStartupLoadReq();
}
void CUpDownClient::CreateBlockRequests(int iMinBlocks, int iMaxBlocks)
{
ASSERT( iMinBlocks >= 1 && iMaxBlocks >= iMinBlocks/*&& iMaxBlocks <= 3*/ );
uint16 count;
if(iMinBlocks > m_PendingBlocks_list.GetCount())
{
count = (uint16)(iMaxBlocks - m_PendingBlocks_list.GetCount());
}
else
return;
Requested_Block_Struct** toadd = new Requested_Block_Struct*[count];
if (reqfile->GetNextRequestedBlock(this, toadd, &count)){
for (UINT i = 0; i < count; i++)
{
Pending_Block_Struct* pblock = new Pending_Block_Struct;
pblock->block = toadd[i];
m_PendingBlocks_list.AddTail(pblock);
ASSERT( m_PendingBlocks_list.GetCount() <= iMaxBlocks );
}
}
delete[] toadd;
}
void CUpDownClient::SendBlockRequests()
{
m_dwLastBlockReceived = ::GetTickCount();
if (!reqfile)
return;
// prevent locking of too many blocks when we are on a slow (probably standby/trickle) slot
int blockCount = 3; // max pending block requests
int maxBlockDelta = 1; // blockcount - maxBlockDelta = minPendingBlockRequests
if(IsEmuleClient() && m_byCompatibleClient==0 && reqfile->GetFileSize()-reqfile->GetCompletedSize() <= (uint64)PARTSIZE*4) {
// if there's less than two chunks left, request fewer blocks for
// slow downloads, so they don't lock blocks from faster clients.
// Only trust eMule clients to be able to handle less blocks than three
if(GetDownloadDatarate() < 600 || GetSessionPayloadDown() < 40*1024) {
blockCount = 1;
maxBlockDelta = 0;
} else if(GetDownloadDatarate() < 1200) {
blockCount = 2;
maxBlockDelta = 0;
}
}
else if (GetDownloadDatarate() > 1024*75)
{
blockCount = 6;
maxBlockDelta = 2;
}
CreateBlockRequests(blockCount - maxBlockDelta, blockCount);
int queued = 0;
for (POSITION pos = m_PendingBlocks_list.GetHeadPosition(); pos != NULL; )
{
Pending_Block_Struct* pending = m_PendingBlocks_list.GetNext(pos);
if (pending->fQueued)
queued++;
}
if (m_PendingBlocks_list.IsEmpty()){
SendCancelTransfer();
SetDownloadState(DS_NONEEDEDPARTS);
SwapToAnotherFile(_T("A4AF for NNP file. CUpDownClient::SendBlockRequests()"), true, false, false, NULL, true, true);
return;
}
CTypedPtrList<CPtrList, Pending_Block_Struct*> listToRequest;
bool bI64Offsets = false;
for (POSITION pos = m_PendingBlocks_list.GetHeadPosition(); pos != NULL; )
{
Pending_Block_Struct* pending = m_PendingBlocks_list.GetNext(pos);
if (pending->fQueued)
continue;
ASSERT( pending->block->StartOffset <= pending->block->EndOffset );
if (pending->block->StartOffset > 0xFFFFFFFF || pending->block->EndOffset >= 0xFFFFFFFF){
bI64Offsets = true;
if (!SupportsLargeFiles()){
ASSERT( false );
SendCancelTransfer();
SetDownloadState(DS_ERROR);
return;
}
}
listToRequest.AddTail(pending);
if (listToRequest.GetCount() >= 3)
break;
}
if (!IsEmuleClient() && listToRequest.GetCount() < 3)
{
for (POSITION pos = m_PendingBlocks_list.GetHeadPosition(); pos != NULL; )
{
Pending_Block_Struct* pending = m_PendingBlocks_list.GetNext(pos);
if (!pending->fQueued)
continue;
ASSERT( pending->block->StartOffset <= pending->block->EndOffset );
if (pending->block->StartOffset > 0xFFFFFFFF || pending->block->EndOffset >= 0xFFFFFFFF){
bI64Offsets = true;
if (!SupportsLargeFiles()){
ASSERT( false );
SendCancelTransfer();
SetDownloadState(DS_ERROR);
return;
}
}
listToRequest.AddTail(pending);
if (listToRequest.GetCount() >= 3)
break;
}
}
else if (listToRequest.IsEmpty())
{
// do not rerequest blocks, at least eMule clients don't need expect this tow ork properly so its
// just overhead (and its not protocol standard, but we used to do so since forever)
// by adding a range of min to max pending blocks this means we do not send a request after every received
// packet anymore
return;
}
Packet* packet;
if (bI64Offsets){
const int iPacketSize = 16+(3*8)+(3*8); // 64
packet = new Packet(OP_REQUESTPARTS_I64, iPacketSize, OP_EMULEPROT);
CSafeMemFile data((const BYTE*)packet->pBuffer, iPacketSize);
data.WriteHash16(reqfile->GetFileHash());
POSITION pos = listToRequest.GetHeadPosition();
for (uint32 i = 0; i != 3; i++){
if (pos){
Pending_Block_Struct* pending = listToRequest.GetNext(pos);
ASSERT( pending->block->StartOffset <= pending->block->EndOffset );
//ASSERT( pending->zStream == NULL );
//ASSERT( pending->totalUnzipped == 0 );
pending->fZStreamError = 0;
pending->fRecovered = 0;
pending->fQueued = 1;