2 // This file is part of the aMule Project.
4 // Parts of this file are based on work from pan One (http://home-3.tiscali.nl/~meost/pms/)
6 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
7 // Copyright (c) 2002-2008 Merkur ( devs@emule-project.net / http://www.emule-project.net )
9 // Any parts of this program derived from the xMule, lMule or eMule project,
10 // or contributed by third-party developers are copyrighted by their
11 // respective authors.
13 // This program is free software; you can redistribute it and/or modify
14 // it under the terms of the GNU General Public License as published by
15 // the Free Software Foundation; either version 2 of the License, or
16 // (at your option) any later version.
18 // This program is distributed in the hope that it will be useful,
19 // but WITHOUT ANY WARRANTY; without even the implied warranty of
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 // GNU General Public License for more details.
23 // You should have received a copy of the GNU General Public License
24 // along with this program; if not, write to the Free Software
25 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
29 #include "KnownFile.h" // Do_not_auto_remove
32 #include <protocol/kad/Constants.h>
33 #include <protocol/ed2k/Client2Client/TCP.h>
34 #include <protocol/Protocols.h>
35 #include <tags/FileTags.h>
38 #include <wx/config.h>
41 #include "MemFile.h" // Needed for CMemFile
42 #include "updownclient.h" // Needed for CUpDownClient
43 #include "Packet.h" // Needed for CPacket
44 #include "Preferences.h" // Needed for CPreferences
45 #include "KnownFileList.h" // Needed for CKnownFileList
46 #include "amule.h" // Needed for theApp
47 #include "PartFile.h" // Needed for SavePartFile
48 #include "ClientList.h" // Needed for clientlist (buddy support)
50 #include "ScopedPtr.h" // Needed for CScopedArray and CScopedPtr
51 #include "GuiEvents.h" // Needed for Notify_*
52 #include "SearchFile.h" // Needed for CSearchFile
53 #include "FileArea.h" // Needed for CFileArea
54 #include "FileAutoClose.h" // Needed for CFileAutoClose
56 #include "CryptoPP_Inc.h" // Needed for MD4
58 #include <common/Format.h>
60 CFileStatistic::CFileStatistic() :
65 alltimetransferred(0),
72 void CFileStatistic::AddRequest(){
75 theApp
->knownfiles
->requested
++;
76 theApp
->sharedfiles
->UpdateItem(fileParent
);
79 void CFileStatistic::AddAccepted(){
82 theApp
->knownfiles
->accepted
++;
83 theApp
->sharedfiles
->UpdateItem(fileParent
);
86 void CFileStatistic::AddTransferred(uint64 bytes
){
88 alltimetransferred
+= bytes
;
89 theApp
->knownfiles
->transferred
+= bytes
;
90 theApp
->sharedfiles
->UpdateItem(fileParent
);
96 /* Abstract File (base class)*/
98 CAbstractFile::CAbstractFile()
108 CAbstractFile::CAbstractFile(const CAbstractFile
& other
)
110 m_abyFileHash(other
.m_abyFileHash
),
111 m_strComment(other
.m_strComment
),
112 m_iRating(other
.m_iRating
),
113 m_hasComment(other
.m_hasComment
),
114 m_iUserRating(other
.m_iUserRating
),
115 m_taglist(other
.m_taglist
),
116 m_nFileSize(other
.m_nFileSize
),
117 m_fileName(other
.m_fileName
)
119 /* // TODO: Currently it's not safe to duplicate the entries, but isn't needed either.
120 CKadEntryPtrList::const_iterator it = other.m_kadNotes.begin();
121 for (; it != other.m_kadNotes.end(); ++it) {
122 m_kadNotes.push_back(new Kademlia::CEntry(**it));
128 void CAbstractFile::SetFileName(const CPath
& fileName
)
130 m_fileName
= fileName
;
133 uint32
CAbstractFile::GetIntTagValue(uint8 tagname
) const
135 ArrayOfCTag::const_iterator it
= m_taglist
.begin();
136 for (; it
!= m_taglist
.end(); ++it
){
137 if (((*it
).GetNameID() == tagname
) && (*it
).IsInt()) {
138 return (*it
).GetInt();
144 bool CAbstractFile::GetIntTagValue(uint8 tagname
, uint32
& ruValue
) const
146 ArrayOfCTag::const_iterator it
= m_taglist
.begin();
147 for (; it
!= m_taglist
.end(); ++it
){
148 if (((*it
).GetNameID() == tagname
) && (*it
).IsInt()){
149 ruValue
= (*it
).GetInt();
156 uint32
CAbstractFile::GetIntTagValue(const wxString
& tagname
) const
158 ArrayOfCTag::const_iterator it
= m_taglist
.begin();
159 for (; it
!= m_taglist
.end(); ++it
){
160 if ((*it
).IsInt() && ((*it
).GetName() == tagname
)) {
161 return (*it
).GetInt();
167 const wxString
& CAbstractFile::GetStrTagValue(uint8 tagname
) const
169 ArrayOfCTag::const_iterator it
= m_taglist
.begin();
170 for (; it
!= m_taglist
.end(); ++it
){
171 if ((*it
).GetNameID() == tagname
&& (*it
).IsStr()) {
172 return (*it
).GetStr();
178 const wxString
& CAbstractFile::GetStrTagValue(const wxString
& tagname
) const
180 ArrayOfCTag::const_iterator it
= m_taglist
.begin();
181 for (; it
!= m_taglist
.end(); ++it
){
182 if ((*it
).IsStr() && ((*it
).GetName() == tagname
)) {
183 return (*it
).GetStr();
189 const CTag
*CAbstractFile::GetTag(uint8 tagname
, uint8 tagtype
) const
191 ArrayOfCTag::const_iterator it
= m_taglist
.begin();
192 for (; it
!= m_taglist
.end(); ++it
){
193 if ((*it
).GetNameID() == tagname
&& (*it
).GetType() == tagtype
) {
200 const CTag
*CAbstractFile::GetTag(const wxString
& tagname
, uint8 tagtype
) const
202 ArrayOfCTag::const_iterator it
= m_taglist
.begin();
203 for (; it
!= m_taglist
.end(); ++it
){
204 if ((*it
).GetType() == tagtype
&& (*it
).GetName() == tagname
) {
211 const CTag
*CAbstractFile::GetTag(uint8 tagname
) const
213 ArrayOfCTag::const_iterator it
= m_taglist
.begin();
214 for (; it
!= m_taglist
.end(); ++it
){
215 if ((*it
).GetNameID() == tagname
) {
222 const CTag
*CAbstractFile::GetTag(const wxString
& tagname
) const
224 ArrayOfCTag::const_iterator it
= m_taglist
.begin();
225 for (; it
!= m_taglist
.end(); ++it
){
226 if ((*it
).GetName() == tagname
) {
233 void CAbstractFile::AddTagUnique(const CTag
&rTag
)
235 ArrayOfCTag::iterator it
= m_taglist
.begin();
236 for (; it
!= m_taglist
.end(); ++it
) {
237 if ( ( ((*it
).GetNameID() != 0 &&
238 (*it
).GetNameID() == rTag
.GetNameID()) ||
239 (!(*it
).GetName().IsEmpty() &&
240 !rTag
.GetName().IsEmpty() &&
241 (*it
).GetName() == rTag
.GetName()) ) &&
242 (*it
).GetType() == rTag
.GetType()){
244 m_taglist
.insert(it
, rTag
);
248 m_taglist
.push_back(rTag
);
252 void CAbstractFile::AddNote(Kademlia::CEntry
*pEntry
)
254 CKadEntryPtrList::iterator it
= m_kadNotes
.begin();
255 for (; it
!= m_kadNotes
.end(); ++it
) {
256 Kademlia::CEntry
* entry
= *it
;
257 if(entry
->m_uIP
== pEntry
->m_uIP
|| entry
->m_uSourceID
== pEntry
->m_uSourceID
) {
262 m_kadNotes
.push_front(pEntry
);
265 void CAbstractFile::AddNote(Kademlia::CEntry
*)
273 CKnownFile::CKnownFile()
278 CKnownFile::CKnownFile(uint32 ecid
) : CECID(ecid
)
284 //#warning Experimental: Construct a CKnownFile from a CSearchFile
285 CKnownFile::CKnownFile(const CSearchFile
&searchFile
)
287 // This will copy the file hash
288 CAbstractFile(static_cast<const CAbstractFile
&>(searchFile
))
292 // Use CKnownFile::SetFileName()
293 SetFileName(searchFile
.GetFileName());
295 // Use CKnownFile::SetFileSize()
296 SetFileSize(searchFile
.GetFileSize());
300 void CKnownFile::Init()
302 m_showSources
= false;
304 m_nCompleteSourcesTime
= time(NULL
);
305 m_nCompleteSourcesCount
= 0;
306 m_nCompleteSourcesCountLo
= 0;
307 m_nCompleteSourcesCountHi
= 0;
308 m_bCommentLoaded
= false;
310 m_iED2KPartCount
= 0;
311 m_iED2KPartHashCount
= 0;
312 m_PublishedED2K
= false;
314 m_lastPublishTimeKadSrc
= 0;
315 m_lastPublishTimeKadNotes
= 0;
317 m_lastDateChanged
= 0;
318 m_bAutoUpPriority
= thePrefs::GetNewAutoUp();
319 m_iUpPriority
= ( m_bAutoUpPriority
) ? PR_HIGH
: PR_NORMAL
;
321 statistic
.fileParent
= this;
324 m_pAICHHashSet
= new CAICHHashSet(this);
329 void CKnownFile::SetFileSize(uint64 nFileSize
)
331 CAbstractFile::SetFileSize(nFileSize
);
333 m_pAICHHashSet
->SetFileSize(nFileSize
);
336 // Examples of parthashs, hashsets and filehashs for different filesizes
337 // according the ed2k protocol
338 //----------------------------------------------------------------------
341 //File hash: 2D55E87D0E21F49B9AD25F98531F3724
345 //File size: 1*PARTSIZE
346 //File hash: A72CA8DF7F07154E217C236C89C17619
348 //Hash[ 0]: 4891ED2E5C9C49F442145A3A5F608299
349 //Hash[ 1]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
352 //File size: 1*PARTSIZE + 1 byte
353 //File hash: 2F620AE9D462CBB6A59FE8401D2B3D23
355 //Hash[ 0]: 121795F0BEDE02DDC7C5426D0995F53F
356 //Hash[ 1]: C329E527945B8FE75B3C5E8826755747
359 //File size: 2*PARTSIZE
360 //File hash: A54C5E562D5E03CA7D77961EB9A745A4
362 //Hash[ 0]: B3F5CE2A06BF403BFB9BFFF68BDDC4D9
363 //Hash[ 1]: 509AA30C9EA8FC136B1159DF2F35B8A9
364 //Hash[ 2]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
367 //File size: 3*PARTSIZE
368 //File hash: 5E249B96F9A46A18FC2489B005BF2667
370 //Hash[ 0]: 5319896A2ECAD43BF17E2E3575278E72
371 //Hash[ 1]: D86EF157D5E49C5ED502EDC15BB5F82B
372 //Hash[ 2]: 10F2D5B1FCB95C0840519C58D708480F
373 //Hash[ 3]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
376 //File size: 3*PARTSIZE + 1 byte
377 //File hash: 797ED552F34380CAFF8C958207E40355
379 //Hash[ 0]: FC7FD02CCD6987DCF1421F4C0AF94FB8
380 //Hash[ 1]: 2FE466AF8A7C06DA3365317B75A5ACFE
381 //Hash[ 2]: 873D3BF52629F7C1527C6E8E473C1C30
382 //Hash[ 3]: BCE50BEE7877BB07BB6FDA56BFE142FB
385 // File size Data parts ED2K parts ED2K part hashs
386 // ---------------------------------------------------------------
387 // 1..PARTSIZE-1 1 1 0(!)
388 // PARTSIZE 1 2(!) 2(!)
390 // PARTSIZE*2 2 3(!) 3(!)
391 // PARTSIZE*2+1 3 3 3
394 //wxFAIL; // Kry - Why commented out by lemonfan? it can never be 0
396 m_iED2KPartCount
= 0;
397 m_iED2KPartHashCount
= 0;
403 m_iPartCount
= nFileSize
/ PARTSIZE
+ 1;
405 m_sizeLastPart
= nFileSize
% PARTSIZE
;
406 // file with size of n * PARTSIZE
407 if (m_sizeLastPart
== 0) {
408 m_sizeLastPart
= PARTSIZE
;
412 // nr. of parts to be used with OP_FILESTATUS
413 m_iED2KPartCount
= nFileSize
/ PARTSIZE
+ 1;
415 // nr. of parts to be used with OP_HASHSETANSWER
416 m_iED2KPartHashCount
= nFileSize
/ PARTSIZE
;
417 if (m_iED2KPartHashCount
!= 0) {
418 m_iED2KPartHashCount
+= 1;
423 void CKnownFile::AddUploadingClient(CUpDownClient
* client
)
425 m_ClientUploadList
.insert(client
);
427 SourceItemType type
= UNAVAILABLE_SOURCE
;
428 switch (client
->GetUploadState()) {
430 case US_ONUPLOADQUEUE
:
431 type
= AVAILABLE_SOURCE
;
434 // Any other state is UNAVAILABLE_SOURCE by default.
438 Notify_SharedCtrlAddClient(this, client
, type
);
440 UpdateAutoUpPriority();
444 void CKnownFile::RemoveUploadingClient(CUpDownClient
* client
)
446 if (m_ClientUploadList
.erase(client
)) {
447 Notify_SharedCtrlRemoveClient(this, client
);
448 UpdateAutoUpPriority();
455 CKnownFile::CKnownFile(CEC_SharedFile_Tag
*tag
) : CECID(tag
->ID())
459 m_abyFileHash
= tag
->FileHash();
460 SetFileSize(tag
->SizeFull());
461 m_AvailPartFrequency
.insert(m_AvailPartFrequency
.end(), m_iPartCount
, 0);
465 CKnownFile::~CKnownFile()
469 void CKnownFile::UpdateAutoUpPriority()
474 #else // ! CLIENT_GUI
476 CKnownFile::~CKnownFile()
478 SourceSet::iterator it
= m_ClientUploadList
.begin();
479 for ( ; it
!= m_ClientUploadList
.end(); ++it
) {
480 (*it
)->ClearUploadFileID();
483 delete m_pAICHHashSet
;
487 void CKnownFile::SetFilePath(const CPath
& filePath
)
489 m_filePath
= filePath
;
493 // needed for memfiles. its probably better to switch everything to CFile...
494 bool CKnownFile::LoadHashsetFromFile(const CFileDataIO
* file
, bool checkhash
)
496 CMD4Hash checkid
= file
->ReadHash();
498 uint16 parts
= file
->ReadUInt16();
499 for (uint16 i
= 0; i
< parts
; ++i
){
500 CMD4Hash cur_hash
= file
->ReadHash();
501 m_hashlist
.push_back(cur_hash
);
504 // SLUGFILLER: SafeHash - always check for valid m_hashlist
506 m_abyFileHash
= checkid
;
507 if (parts
<= 1) { // nothing to check
511 if ( m_abyFileHash
!= checkid
) {
512 return false; // wrong file?
514 if (parts
!= GetED2KPartHashCount()) {
519 // SLUGFILLER: SafeHash
522 // lol, useless comment but made me lmao
523 // wtf you guys are weird.
525 if (!m_hashlist
.empty()) {
526 CreateHashFromHashlist(m_hashlist
, &checkid
);
529 if ( m_abyFileHash
== checkid
) {
538 bool CKnownFile::LoadTagsFromFile(const CFileDataIO
* file
)
540 uint32 tagcount
= file
->ReadUInt32();
541 for (uint32 j
= 0; j
!= tagcount
; ++j
) {
542 CTag
newtag(*file
, true);
543 switch(newtag
.GetNameID()){
545 if (GetFileName().IsOk()) {
546 // Unlike eMule, we actually prefer the second
547 // filename tag, since we use it to specify the
548 // 'universial' filename (see CPath::ToUniv).
549 CPath path
= CPath::FromUniv(newtag
.GetStr());
551 // May be invalid, if from older versions where
552 // unicoded filenames be saved as empty-strings.
557 SetFileName(CPath(newtag
.GetStr()));
562 SetFileSize(newtag
.GetInt());
563 m_AvailPartFrequency
.clear();
564 m_AvailPartFrequency
.insert(
565 m_AvailPartFrequency
.begin(),
569 case FT_ATTRANSFERRED
:
570 statistic
.alltimetransferred
+= newtag
.GetInt();
573 case FT_ATTRANSFERREDHI
:
574 statistic
.alltimetransferred
=
575 (((uint64
)newtag
.GetInt()) << 32) +
576 ((uint64
)statistic
.alltimetransferred
);
580 statistic
.alltimerequested
= newtag
.GetInt();
584 statistic
.alltimeaccepted
= newtag
.GetInt();
588 m_iUpPriority
= newtag
.GetInt();
589 if( m_iUpPriority
== PR_AUTO
){
590 m_iUpPriority
= PR_HIGH
;
591 m_bAutoUpPriority
= true;
593 if ( m_iUpPriority
!= PR_VERYLOW
&&
594 m_iUpPriority
!= PR_LOW
&&
595 m_iUpPriority
!= PR_NORMAL
&&
596 m_iUpPriority
!= PR_HIGH
&&
597 m_iUpPriority
!= PR_VERYHIGH
&&
598 m_iUpPriority
!= PR_POWERSHARE
) {
599 m_iUpPriority
= PR_NORMAL
;
602 m_bAutoUpPriority
= false;
607 // Ignore it, it's not used anymore.
613 hash
.DecodeBase32(newtag
.GetStr()) == CAICHHash::GetHashSize();
614 wxASSERT(hashSizeOk
);
616 m_pAICHHashSet
->SetMasterHash(hash
, AICH_HASHSETCOMPLETE
);
621 case FT_KADLASTPUBLISHSRC
:
622 SetLastPublishTimeKadSrc( newtag
.GetInt(), 0 );
624 if(GetLastPublishTimeKadSrc() > (uint32
)time(NULL
)+KADEMLIAREPUBLISHTIMES
) {
625 //There may be a posibility of an older client that saved a random number here.. This will check for that..
626 SetLastPublishTimeKadSrc(0, 0);
630 case FT_KADLASTPUBLISHNOTES
:
631 SetLastPublishTimeKadNotes( newtag
.GetInt() );
634 case FT_KADLASTPUBLISHKEY
:
636 wxASSERT( newtag
.IsInt() );
640 // Store them here and write them back on saving.
641 m_taglist
.push_back(newtag
);
649 bool CKnownFile::LoadDateFromFile(const CFileDataIO
* file
)
651 m_lastDateChanged
= file
->ReadUInt32();
657 bool CKnownFile::LoadFromFile(const CFileDataIO
* file
)
659 // SLUGFILLER: SafeHash - load first, verify later
660 bool ret1
= LoadDateFromFile(file
);
661 bool ret2
= LoadHashsetFromFile(file
,false);
662 bool ret3
= LoadTagsFromFile(file
);
664 // Final hash-count verification, needs to be done after the tags are loaded.
665 return ret1
&& ret2
&& ret3
&& GetED2KPartHashCount()==GetHashCount();
666 // SLUGFILLER: SafeHash
670 bool CKnownFile::WriteToFile(CFileDataIO
* file
)
672 wxCHECK(!IsPartFile(), false);
675 file
->WriteUInt32(m_lastDateChanged
);
677 file
->WriteHash(m_abyFileHash
);
679 uint16 parts
= m_hashlist
.size();
680 file
->WriteUInt16(parts
);
682 for (int i
= 0; i
< parts
; ++i
)
683 file
->WriteHash(m_hashlist
[i
]);
686 const int iFixedTags
= 8;
687 uint32 tagcount
= iFixedTags
;
688 if (HasProperAICHHashSet()) {
691 // Float meta tags are currently not written. All older eMule versions < 0.28a have
692 // a bug in the meta tag reading+writing code. To achive maximum backward
693 // compatibility for met files with older eMule versions we just don't write float
694 // tags. This is OK, because we (eMule) do not use float tags. The only float tags
695 // we may have to handle is the '# Sent' tag from the Hybrid, which is pretty
696 // useless but may be received from us via the servers.
698 // The code for writing the float tags SHOULD BE ENABLED in SOME MONTHS (after most
699 // people are using the newer eMule versions which do not write broken float tags).
700 for (size_t j
= 0; j
< m_taglist
.size(); ++j
){
701 if (m_taglist
[j
].IsInt() || m_taglist
[j
].IsStr()) {
706 if (m_lastPublishTimeKadSrc
) {
710 if (m_lastPublishTimeKadNotes
){
716 file
->WriteUInt32(tagcount
);
718 // We still save the unicoded filename, for backwards
719 // compatibility with pre-2.2 and other clients.
720 CTagString
nametag_unicode(FT_FILENAME
, GetFileName().GetRaw());
721 // We write it with BOM to kep eMule compatibility
722 nametag_unicode
.WriteTagToFile(file
,utf8strOptBOM
);
724 // The non-unicoded filename is written in an 'universial'
725 // format, which allows us to identify files, even if the
726 // system locale changes.
727 CTagString
nametag(FT_FILENAME
, CPath::ToUniv(GetFileName()));
728 nametag
.WriteTagToFile(file
);
730 CTagIntSized
sizetag(FT_FILESIZE
, GetFileSize(), IsLargeFile() ? 64 : 32);
731 sizetag
.WriteTagToFile(file
);
735 tran
=statistic
.alltimetransferred
& 0xFFFFFFFF;
736 CTagInt32
attag1(FT_ATTRANSFERRED
, tran
);
737 attag1
.WriteTagToFile(file
);
739 tran
=statistic
.alltimetransferred
>>32;
740 CTagInt32
attag4(FT_ATTRANSFERREDHI
, tran
);
741 attag4
.WriteTagToFile(file
);
743 CTagInt32
attag2(FT_ATREQUESTED
, statistic
.GetAllTimeRequests());
744 attag2
.WriteTagToFile(file
);
746 CTagInt32
attag3(FT_ATACCEPTED
, statistic
.GetAllTimeAccepts());
747 attag3
.WriteTagToFile(file
);
749 // priority N permission
750 CTagInt32
priotag(FT_ULPRIORITY
, IsAutoUpPriority() ? PR_AUTO
: m_iUpPriority
);
751 priotag
.WriteTagToFile(file
);
754 if (HasProperAICHHashSet()) {
755 CTagString
aichtag(FT_AICH_HASH
, m_pAICHHashSet
->GetMasterHash().GetString());
756 aichtag
.WriteTagToFile(file
);
760 if (m_lastPublishTimeKadSrc
){
761 CTagInt32
kadLastPubSrc(FT_KADLASTPUBLISHSRC
, m_lastPublishTimeKadSrc
);
762 kadLastPubSrc
.WriteTagToFile(file
);
766 if (m_lastPublishTimeKadNotes
){
767 CTagInt32
kadLastPubNotes(FT_KADLASTPUBLISHNOTES
, m_lastPublishTimeKadNotes
);
768 kadLastPubNotes
.WriteTagToFile(file
);
772 for (size_t j
= 0; j
< m_taglist
.size(); ++j
){
773 if (m_taglist
[j
].IsInt() || m_taglist
[j
].IsStr()) {
774 m_taglist
[j
].WriteTagToFile(file
);
781 void CKnownFile::CreateHashFromHashlist(const ArrayOfCMD4Hash
& hashes
, CMD4Hash
* Output
)
783 wxCHECK_RET(hashes
.size(), wxT("No input to hash from in CreateHashFromHashlist"));
785 std::vector
<byte
> buffer(hashes
.size() * MD4HASH_LENGTH
);
786 std::vector
<byte
>::iterator it
= buffer
.begin();
788 for (size_t i
= 0; i
< hashes
.size(); ++i
) {
789 it
= STLCopy_n(hashes
[i
].GetHash(), MD4HASH_LENGTH
, it
);
792 CreateHashFromInput(&buffer
[0], buffer
.size(), Output
, NULL
);
796 void CKnownFile::CreateHashFromFile(CFileAutoClose
& file
, uint64 offset
, uint32 Length
, CMD4Hash
* Output
, CAICHHashTree
* pShaHashOut
)
798 wxCHECK_RET(Length
, wxT("No input to hash from in CreateHashFromFile"));
801 area
.ReadAt(file
, offset
, Length
);
803 CreateHashFromInput(area
.GetBuffer(), Length
, Output
, pShaHashOut
);
808 void CKnownFile::CreateHashFromInput(const byte
* input
, uint32 Length
, CMD4Hash
* Output
, CAICHHashTree
* pShaHashOut
)
810 wxASSERT_MSG(Output
|| pShaHashOut
, wxT("Nothing to do in CreateHashFromInput"));
811 wxCHECK_RET(input
, wxT("No input to hash from in CreateHashFromInput"));
812 wxASSERT(Length
<= PARTSIZE
); // We never hash more than one PARTSIZE
814 CMemFile
data(input
, Length
);
816 uint32 Required
= Length
;
819 uint32 posCurrentEMBlock
= 0;
821 CScopedPtr
<CAICHHashAlgo
> pHashAlg(CAICHHashSet::GetNewHashAlgo());
824 while (Required
>= 64) {
825 uint32 len
= Required
/ 64;
826 if (len
> sizeof(X
)/(64 * sizeof(X
[0]))) {
827 len
= sizeof(X
)/(64 * sizeof(X
[0]));
830 data
.Read(&X
, len
* 64);
832 // SHA hash needs 180KB blocks
834 if (nIACHPos
+ len
*64 >= EMBLOCKSIZE
) {
835 uint32 nToComplete
= EMBLOCKSIZE
- nIACHPos
;
836 pHashAlg
->Add(X
, nToComplete
);
837 wxASSERT( nIACHPos
+ nToComplete
== EMBLOCKSIZE
);
838 pShaHashOut
->SetBlockHash(EMBLOCKSIZE
, posCurrentEMBlock
, pHashAlg
.get());
839 posCurrentEMBlock
+= EMBLOCKSIZE
;
841 pHashAlg
->Add(X
+nToComplete
,(len
*64) - nToComplete
);
842 nIACHPos
= (len
*64) - nToComplete
;
845 pHashAlg
->Add(X
, len
*64);
853 Required
= Length
% 64;
855 data
.Read(&X
,Required
);
857 if (pShaHashOut
!= NULL
){
858 if (nIACHPos
+ Required
>= EMBLOCKSIZE
){
859 uint32 nToComplete
= EMBLOCKSIZE
- nIACHPos
;
860 pHashAlg
->Add(X
, nToComplete
);
861 wxASSERT( nIACHPos
+ nToComplete
== EMBLOCKSIZE
);
862 pShaHashOut
->SetBlockHash(EMBLOCKSIZE
, posCurrentEMBlock
, pHashAlg
.get());
863 posCurrentEMBlock
+= EMBLOCKSIZE
;
865 pHashAlg
->Add(X
+nToComplete
, Required
- nToComplete
);
866 nIACHPos
= Required
- nToComplete
;
869 pHashAlg
->Add(X
, Required
);
870 nIACHPos
+= Required
;
874 if (pShaHashOut
!= NULL
){
876 pShaHashOut
->SetBlockHash(nIACHPos
, posCurrentEMBlock
, pHashAlg
.get());
877 posCurrentEMBlock
+= nIACHPos
;
879 wxASSERT( posCurrentEMBlock
== Length
);
880 wxCHECK2( pShaHashOut
->ReCalculateHash(pHashAlg
.get(), false), );
884 #ifdef __WEAK_CRYPTO__
885 CryptoPP::Weak::MD4 md4_hasher
;
887 CryptoPP::MD4 md4_hasher
;
889 md4_hasher
.CalculateDigest(Output
->GetHash(), input
, Length
);
894 const CMD4Hash
& CKnownFile::GetPartHash(uint16 part
) const {
895 wxASSERT( part
< m_hashlist
.size() );
897 return m_hashlist
[part
];
900 CPacket
* CKnownFile::CreateSrcInfoPacket(const CUpDownClient
* forClient
, uint8 byRequestedVersion
, uint16 nRequestedOptions
)
904 if (m_ClientUploadList
.empty()) {
908 if ((((CKnownFile
*)forClient
->GetRequestFile() != this)
909 && ((CKnownFile
*)forClient
->GetUploadFile() != this)) || forClient
->GetUploadFileID() != GetFileHash()) {
910 wxString file1
= _("Unknown");
911 if (forClient
->GetRequestFile() && forClient
->GetRequestFile()->GetFileName().IsOk()) {
912 file1
= forClient
->GetRequestFile()->GetFileName().GetPrintable();
913 } else if (forClient
->GetUploadFile() && forClient
->GetUploadFile()->GetFileName().IsOk()) {
914 file1
= forClient
->GetUploadFile()->GetFileName().GetPrintable();
916 wxString file2
= _("Unknown");
917 if (GetFileName().IsOk()) {
918 file2
= GetFileName().GetPrintable();
920 AddDebugLogLineN(logKnownFiles
, wxT("File mismatch on source packet (K) Sending: ") + file1
+ wxT(" From: ") + file2
);
924 const BitVector
& rcvstatus
= forClient
->GetUpPartStatus();
925 bool SupportsUploadChunksState
= !rcvstatus
.empty();
926 //wxASSERT(rcvstatus.size() == GetPartCount()); // Obviously!
927 if (rcvstatus
.size() != GetPartCount()) {
928 // Yuck. Same file but different part count? Seriously fucked up.
929 AddDebugLogLineN(logKnownFiles
, CFormat(wxT("Impossible situation: different partcounts for the same known file: %i (client) and %i (file)")) % rcvstatus
.size() % GetPartCount());
937 if (forClient
->SupportsSourceExchange2() && byRequestedVersion
> 0){
938 // the client uses SourceExchange2 and requested the highest version he knows
939 // and we send the highest version we know, but of course not higher than his request
940 byUsedVersion
= std::min(byRequestedVersion
, (uint8
)SOURCEEXCHANGE2_VERSION
);
942 data
.WriteUInt8(byUsedVersion
);
944 // we don't support any special SX2 options yet, reserved for later use
945 if (nRequestedOptions
!= 0) {
946 AddDebugLogLineN(logKnownFiles
, CFormat(wxT("Client requested unknown options for SourceExchange2: %u")) % nRequestedOptions
);
949 byUsedVersion
= forClient
->GetSourceExchange1Version();
950 bIsSX2Packet
= false;
951 if (forClient
->SupportsSourceExchange2()) {
952 AddDebugLogLineN(logKnownFiles
, wxT("Client which announced to support SX2 sent SX1 packet instead"));
958 data
.WriteHash(forClient
->GetUploadFileID());
959 data
.WriteUInt16(nCount
);
960 uint32 cDbgNoSrc
= 0;
962 SourceSet::iterator it
= m_ClientUploadList
.begin();
963 for ( ; it
!= m_ClientUploadList
.end(); it
++ ) {
964 const CUpDownClient
*cur_src
= *it
;
966 if ( cur_src
->HasLowID() ||
967 cur_src
== forClient
||
968 !( cur_src
->GetUploadState() == US_UPLOADING
||
969 cur_src
->GetUploadState() == US_ONUPLOADQUEUE
)) {
973 bool bNeeded
= false;
975 if ( SupportsUploadChunksState
) {
976 const BitVector
& srcstatus
= cur_src
->GetUpPartStatus();
977 if ( !srcstatus
.empty() ) {
978 //wxASSERT(srcstatus.size() == GetPartCount()); // Obviously!
979 if (srcstatus
.size() != GetPartCount()) {
982 if ( cur_src
->GetUpPartCount() == forClient
->GetUpPartCount() ) {
983 for (int x
= 0; x
< GetPartCount(); x
++ ) {
984 if ( srcstatus
.get(x
) && !rcvstatus
.get(x
) ) {
985 // We know the receiving client needs
986 // a chunk from this client.
994 // This client doesn't support upload chunk status.
995 // So just send it and hope for the best.
999 // remote client does not support upload chunk status,
1000 // search sources which have at least one complete part
1001 // we could even sort the list of sources by available
1002 // chunks to return as much sources as possible which
1003 // have the most available chunks. but this could be
1004 // a noticeable performance problem.
1005 const BitVector
& srcstatus
= cur_src
->GetUpPartStatus();
1006 if ( !srcstatus
.empty() ) {
1007 //wxASSERT(srcstatus.size() == GetPartCount());
1008 if (srcstatus
.size() != GetPartCount()) {
1011 for (int x
= 0; x
< GetPartCount(); x
++ ) {
1012 if ( srcstatus
.get(x
) ) {
1013 // this client has at least one chunk
1019 // This client doesn't support upload chunk status.
1020 // So just send it and hope for the best.
1028 if(byUsedVersion
>= 3) {
1029 dwID
= cur_src
->GetUserIDHybrid();
1031 dwID
= cur_src
->GetIP();
1033 data
.WriteUInt32(dwID
);
1034 data
.WriteUInt16(cur_src
->GetUserPort());
1035 data
.WriteUInt32(cur_src
->GetServerIP());
1036 data
.WriteUInt16(cur_src
->GetServerPort());
1038 if (byUsedVersion
>= 2) {
1039 data
.WriteHash(cur_src
->GetUserHash());
1042 if (byUsedVersion
>= 4){
1043 // CryptSettings - SourceExchange V4
1045 // 1 CryptLayer Required
1046 // 1 CryptLayer Requested
1047 // 1 CryptLayer Supported
1048 const uint8 uSupportsCryptLayer
= cur_src
->SupportsCryptLayer() ? 1 : 0;
1049 const uint8 uRequestsCryptLayer
= cur_src
->RequestsCryptLayer() ? 1 : 0;
1050 const uint8 uRequiresCryptLayer
= cur_src
->RequiresCryptLayer() ? 1 : 0;
1051 const uint8 byCryptOptions
= (uRequiresCryptLayer
<< 2) | (uRequestsCryptLayer
<< 1) | (uSupportsCryptLayer
<< 0);
1052 data
.WriteUInt8(byCryptOptions
);
1065 data
.Seek(bIsSX2Packet
? 17 : 16, wxFromStart
);
1066 data
.WriteUInt16(nCount
);
1068 CPacket
* result
= new CPacket(data
, OP_EMULEPROT
, bIsSX2Packet
? OP_ANSWERSOURCES2
: OP_ANSWERSOURCES
);
1070 if ( result
->GetPacketSize() > 354 ) {
1071 result
->PackPacket();
1078 // Updates priority of file if autopriority is activated
1079 void CKnownFile::UpdateAutoUpPriority()
1081 if (IsAutoUpPriority()) {
1082 uint32 queued
= GetQueuedCount();
1083 uint8 priority
= PR_NORMAL
;
1087 } else if (queued
> 1) {
1088 priority
= PR_NORMAL
;
1093 if (GetUpPriority() != priority
) {
1094 SetUpPriority(priority
, false);
1095 Notify_SharedFilesUpdateItem(this);
1100 void CKnownFile::SetFileComment(const wxString
& strNewComment
)
1102 if (m_strComment
!= strNewComment
) {
1103 SetLastPublishTimeKadNotes(0);
1104 wxString strCfgPath
= wxT("/") + m_abyFileHash
.Encode() + wxT("/");
1106 wxConfigBase
* cfg
= wxConfigBase::Get();
1107 cfg
->Write( strCfgPath
+ wxT("Comment"), strNewComment
);
1109 m_strComment
= strNewComment
;
1111 SourceSet::iterator it
= m_ClientUploadList
.begin();
1112 for ( ; it
!= m_ClientUploadList
.end(); it
++ ) {
1113 (*it
)->SetCommentDirty();
1120 void CKnownFile::SetFileRating(int8 iNewRating
)
1122 if (m_iRating
!= iNewRating
) {
1123 SetLastPublishTimeKadNotes(0);
1124 wxString strCfgPath
= wxT("/") + m_abyFileHash
.Encode() + wxT("/");
1125 wxConfigBase
* cfg
= wxConfigBase::Get();
1126 cfg
->Write( strCfgPath
+ wxT("Rate"), (int)iNewRating
);
1127 m_iRating
= iNewRating
;
1129 SourceSet::iterator it
= m_ClientUploadList
.begin();
1130 for ( ; it
!= m_ClientUploadList
.end(); it
++ ) {
1131 (*it
)->SetCommentDirty();
1137 void CKnownFile::SetUpPriority(uint8 iNewUpPriority
, bool m_bsave
){
1138 m_iUpPriority
= iNewUpPriority
;
1139 if( IsPartFile() && m_bsave
) {
1140 ((CPartFile
*)this)->SavePartFile();
1144 void CKnownFile::SetPublishedED2K(bool val
){
1145 m_PublishedED2K
= val
;
1146 Notify_SharedFilesUpdateItem(this);
1149 bool CKnownFile::PublishNotes()
1151 if(m_lastPublishTimeKadNotes
> (uint32
)time(NULL
)) {
1155 if(!GetFileComment().IsEmpty()) {
1156 m_lastPublishTimeKadNotes
= (uint32
)time(NULL
)+KADEMLIAREPUBLISHTIMEN
;
1160 if(GetFileRating() != 0) {
1161 m_lastPublishTimeKadNotes
= (uint32
)time(NULL
)+KADEMLIAREPUBLISHTIMEN
;
1168 bool CKnownFile::PublishSrc()
1170 uint32 lastBuddyIP
= 0;
1172 if( theApp
->IsFirewalled() ) {
1173 CUpDownClient
* buddy
= theApp
->clientlist
->GetBuddy();
1175 lastBuddyIP
= theApp
->clientlist
->GetBuddy()->GetIP();
1176 if( lastBuddyIP
!= m_lastBuddyIP
) {
1177 SetLastPublishTimeKadSrc( (uint32
)time(NULL
)+KADEMLIAREPUBLISHTIMES
, lastBuddyIP
);
1185 if(m_lastPublishTimeKadSrc
> (uint32
)time(NULL
)) {
1189 SetLastPublishTimeKadSrc((uint32
)time(NULL
)+KADEMLIAREPUBLISHTIMES
,lastBuddyIP
);
1194 void CKnownFile::UpdatePartsInfo()
1197 uint16 partcount
= GetPartCount();
1198 bool flag
= (time(NULL
) - m_nCompleteSourcesTime
> 0);
1200 // Ensure the frequency-list is ready
1201 if ( m_AvailPartFrequency
.size() != GetPartCount() ) {
1202 m_AvailPartFrequency
.clear();
1203 m_AvailPartFrequency
.insert(m_AvailPartFrequency
.begin(), GetPartCount(), 0);
1207 ArrayOfUInts16 count
;
1208 count
.reserve(m_ClientUploadList
.size());
1210 SourceSet::iterator it
= m_ClientUploadList
.begin();
1211 for ( ; it
!= m_ClientUploadList
.end(); it
++ ) {
1212 if ( !(*it
)->GetUpPartStatus().empty() && (*it
)->GetUpPartCount() == partcount
) {
1213 count
.push_back((*it
)->GetUpCompleteSourcesCount());
1217 m_nCompleteSourcesCount
= m_nCompleteSourcesCountLo
= m_nCompleteSourcesCountHi
= 0;
1219 if( partcount
> 0) {
1220 m_nCompleteSourcesCount
= m_AvailPartFrequency
[0];
1222 for (uint16 i
= 1; i
< partcount
; ++i
) {
1223 if( m_nCompleteSourcesCount
> m_AvailPartFrequency
[i
]) {
1224 m_nCompleteSourcesCount
= m_AvailPartFrequency
[i
];
1227 count
.push_back(m_nCompleteSourcesCount
);
1229 int32 n
= count
.size();
1231 std::sort(count
.begin(), count
.end(), std::less
<uint16
>());
1234 int i
= n
>> 1; // (n / 2)
1235 int j
= (n
* 3) >> 2; // (n * 3) / 4
1236 int k
= (n
* 7) >> 3; // (n * 7) / 8
1238 // For complete files, trust the people your uploading to more...
1240 // For low guess and normal guess count
1241 // - If we see more sources then the guessed low and
1242 // normal, use what we see.
1243 // - If we see less sources then the guessed low,
1244 // adjust network accounts for 100%, we account for
1245 // 0% with what we see and make sure we are still
1246 // above the normal.
1248 // Adjust 100% network and 0% what we see.
1250 if ( count
[i
] < m_nCompleteSourcesCount
) {
1251 m_nCompleteSourcesCountLo
= m_nCompleteSourcesCount
;
1253 m_nCompleteSourcesCountLo
= count
[i
];
1255 m_nCompleteSourcesCount
= m_nCompleteSourcesCountLo
;
1256 m_nCompleteSourcesCountHi
= count
[j
];
1257 if( m_nCompleteSourcesCountHi
< m_nCompleteSourcesCount
) {
1258 m_nCompleteSourcesCountHi
= m_nCompleteSourcesCount
;
1265 // Adjust network accounts for 100%, we account for
1266 // 0% with what we see and make sure we are still above the low.
1268 // Adjust network accounts for 100%, we account for 0%
1269 // with what we see and make sure we are still above the normal.
1271 m_nCompleteSourcesCountLo
= m_nCompleteSourcesCount
;
1272 m_nCompleteSourcesCount
= count
[j
];
1273 if( m_nCompleteSourcesCount
< m_nCompleteSourcesCountLo
) {
1274 m_nCompleteSourcesCount
= m_nCompleteSourcesCountLo
;
1276 m_nCompleteSourcesCountHi
= count
[k
];
1277 if( m_nCompleteSourcesCountHi
< m_nCompleteSourcesCount
) {
1278 m_nCompleteSourcesCountHi
= m_nCompleteSourcesCount
;
1282 m_nCompleteSourcesTime
= time(NULL
) + (60);
1285 Notify_SharedFilesUpdateItem(this);
1289 void CKnownFile::UpdateUpPartsFrequency( CUpDownClient
* client
, bool increment
)
1291 if ( m_AvailPartFrequency
.size() != GetPartCount() ) {
1292 m_AvailPartFrequency
.clear();
1293 m_AvailPartFrequency
.insert(m_AvailPartFrequency
.begin(), GetPartCount(), 0);
1299 const BitVector
& freq
= client
->GetUpPartStatus();
1300 unsigned int size
= freq
.size();
1301 if ( size
!= m_AvailPartFrequency
.size() ) {
1306 for ( unsigned int i
= 0; i
< size
; ++i
) {
1307 if ( freq
.get(i
) ) {
1308 m_AvailPartFrequency
[i
]++;
1312 for ( unsigned int i
= 0; i
< size
; ++i
) {
1313 if ( freq
.get(i
) ) {
1314 m_AvailPartFrequency
[i
]--;
1320 void CKnownFile::ClearPriority() {
1321 if ( !m_bAutoUpPriority
) return;
1322 m_iUpPriority
= ( m_bAutoUpPriority
) ? PR_HIGH
: PR_NORMAL
;
1323 UpdateAutoUpPriority();
1326 void GuessAndRemoveExt(CPath
& name
)
1328 wxString ext
= name
.GetExt();
1330 // Remove common two-part extensions, such as "tar.gz"
1331 if (ext
== wxT("gz") || ext
== wxT("bz2")) {
1332 name
= name
.RemoveExt();
1333 if (name
.GetExt() == wxT("tar")) {
1334 name
= name
.RemoveExt();
1336 // might be an extension if length == 3
1337 // and also remove some common non-three-character extensions
1338 } else if (ext
.Length() == 3 ||
1341 ext
== wxT("jpeg") ||
1344 name
= name
.RemoveExt();
1348 void CKnownFile::SetFileName(const CPath
& filename
)
1350 CAbstractFile::SetFileName(filename
);
1352 // Don't publish extension. That'd kill the node indexing e.g. "avi".
1353 CPath tmpName
= GetFileName();
1354 GuessAndRemoveExt(tmpName
);
1355 Kademlia::CSearchManager::GetWords(tmpName
.GetPrintable(), &wordlist
);
1358 #endif // CLIENT_GUI
1360 //For File Comment //
1361 void CKnownFile::LoadComment()
1364 wxString strCfgPath
= wxT("/") + m_abyFileHash
.Encode() + wxT("/");
1366 wxConfigBase
* cfg
= wxConfigBase::Get();
1368 m_strComment
= cfg
->Read( strCfgPath
+ wxT("Comment"), wxEmptyString
);
1369 m_iRating
= cfg
->Read( strCfgPath
+ wxT("Rate"), 0l);
1370 m_bCommentLoaded
= true;
1373 m_strComment
.Clear();
1374 m_bCommentLoaded
= true;
1381 wxString
CKnownFile::GetAICHMasterHash() const
1384 return m_AICHMasterHash
;
1386 if (HasProperAICHHashSet()) {
1387 return m_pAICHHashSet
->GetMasterHash().GetString();
1390 return wxEmptyString
;
1395 bool CKnownFile::HasProperAICHHashSet() const
1398 return m_AICHMasterHash
.Length() != 0;
1400 return m_pAICHHashSet
->HasValidMasterHash() &&
1401 (m_pAICHHashSet
->GetStatus() == AICH_HASHSETCOMPLETE
||
1402 m_pAICHHashSet
->GetStatus() == AICH_VERIFIED
);
1406 wxString
CKnownFile::GetFeedback() const
1408 return wxString(_("File name")) + wxT(": ") + GetFileName().GetPrintable() + wxT("\n")
1409 + _("File size") + wxT(": ") + CastItoXBytes(GetFileSize()) + wxT("\n")
1410 + _("Share ratio") + CFormat(wxT(": %.2f%%\n")) % (((double)statistic
.GetAllTimeTransferred() / (double)GetFileSize()) * 100.0)
1411 + _("Uploaded") + wxT(": ") + CastItoXBytes(statistic
.GetTransferred()) + wxT(" (") + CastItoXBytes(statistic
.GetAllTimeTransferred()) + wxT(")\n")
1412 + _("Requested") + CFormat(wxT(": %u (%u)\n")) % statistic
.GetRequests() % statistic
.GetAllTimeRequests()
1413 + _("Accepted") + CFormat(wxT(": %u (%u)\n")) % statistic
.GetAccepts() % statistic
.GetAllTimeAccepts()
1414 + _("On Queue") + CFormat(wxT(": %u\n")) % GetQueuedCount()
1415 + _("Complete sources") + CFormat(wxT(": %u\n")) % m_nCompleteSourcesCount
;
1418 // File_checked_for_headers