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()
277 m_bAutoUpPriority
= thePrefs::GetNewAutoUp();
278 m_iUpPriority
= ( m_bAutoUpPriority
) ? PR_HIGH
: PR_NORMAL
;
282 //#warning Experimental: Construct a CKnownFile from a CSearchFile
283 CKnownFile::CKnownFile(const CSearchFile
&searchFile
)
285 // This will copy the file hash
286 CAbstractFile(static_cast<const CAbstractFile
&>(searchFile
))
290 // Use CKnownFile::SetFileName()
291 SetFileName(searchFile
.GetFileName());
293 // Use CKnownFile::SetFileSize()
294 SetFileSize(searchFile
.GetFileSize());
296 m_bAutoUpPriority
= thePrefs::GetNewAutoUp();
297 m_iUpPriority
= ( m_bAutoUpPriority
) ? PR_HIGH
: PR_NORMAL
;
301 void CKnownFile::Init()
303 m_nCompleteSourcesTime
= time(NULL
);
304 m_nCompleteSourcesCount
= 0;
305 m_nCompleteSourcesCountLo
= 0;
306 m_nCompleteSourcesCountHi
= 0;
307 m_bCommentLoaded
= false;
309 m_iED2KPartCount
= 0;
310 m_iED2KPartHashCount
= 0;
311 m_PublishedED2K
= false;
313 m_lastPublishTimeKadSrc
= 0;
314 m_lastPublishTimeKadNotes
= 0;
316 m_lastDateChanged
= 0;
318 statistic
.fileParent
= this;
321 m_pAICHHashSet
= new CAICHHashSet(this);
326 void CKnownFile::SetFileSize(uint64 nFileSize
)
328 CAbstractFile::SetFileSize(nFileSize
);
330 m_pAICHHashSet
->SetFileSize(nFileSize
);
333 // Examples of parthashs, hashsets and filehashs for different filesizes
334 // according the ed2k protocol
335 //----------------------------------------------------------------------
338 //File hash: 2D55E87D0E21F49B9AD25F98531F3724
342 //File size: 1*PARTSIZE
343 //File hash: A72CA8DF7F07154E217C236C89C17619
345 //Hash[ 0]: 4891ED2E5C9C49F442145A3A5F608299
346 //Hash[ 1]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
349 //File size: 1*PARTSIZE + 1 byte
350 //File hash: 2F620AE9D462CBB6A59FE8401D2B3D23
352 //Hash[ 0]: 121795F0BEDE02DDC7C5426D0995F53F
353 //Hash[ 1]: C329E527945B8FE75B3C5E8826755747
356 //File size: 2*PARTSIZE
357 //File hash: A54C5E562D5E03CA7D77961EB9A745A4
359 //Hash[ 0]: B3F5CE2A06BF403BFB9BFFF68BDDC4D9
360 //Hash[ 1]: 509AA30C9EA8FC136B1159DF2F35B8A9
361 //Hash[ 2]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
364 //File size: 3*PARTSIZE
365 //File hash: 5E249B96F9A46A18FC2489B005BF2667
367 //Hash[ 0]: 5319896A2ECAD43BF17E2E3575278E72
368 //Hash[ 1]: D86EF157D5E49C5ED502EDC15BB5F82B
369 //Hash[ 2]: 10F2D5B1FCB95C0840519C58D708480F
370 //Hash[ 3]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
373 //File size: 3*PARTSIZE + 1 byte
374 //File hash: 797ED552F34380CAFF8C958207E40355
376 //Hash[ 0]: FC7FD02CCD6987DCF1421F4C0AF94FB8
377 //Hash[ 1]: 2FE466AF8A7C06DA3365317B75A5ACFE
378 //Hash[ 2]: 873D3BF52629F7C1527C6E8E473C1C30
379 //Hash[ 3]: BCE50BEE7877BB07BB6FDA56BFE142FB
382 // File size Data parts ED2K parts ED2K part hashs
383 // ---------------------------------------------------------------
384 // 1..PARTSIZE-1 1 1 0(!)
385 // PARTSIZE 1 2(!) 2(!)
387 // PARTSIZE*2 2 3(!) 3(!)
388 // PARTSIZE*2+1 3 3 3
391 //wxFAIL; // Kry - Why commented out by lemonfan? it can never be 0
393 m_iED2KPartCount
= 0;
394 m_iED2KPartHashCount
= 0;
400 m_iPartCount
= nFileSize
/ PARTSIZE
+ 1;
402 m_sizeLastPart
= nFileSize
% PARTSIZE
;
403 // file with size of n * PARTSIZE
404 if (m_sizeLastPart
== 0) {
405 m_sizeLastPart
= PARTSIZE
;
409 // nr. of parts to be used with OP_FILESTATUS
410 m_iED2KPartCount
= nFileSize
/ PARTSIZE
+ 1;
412 // nr. of parts to be used with OP_HASHSETANSWER
413 m_iED2KPartHashCount
= nFileSize
/ PARTSIZE
;
414 if (m_iED2KPartHashCount
!= 0) {
415 m_iED2KPartHashCount
+= 1;
422 CKnownFile::CKnownFile(CEC_SharedFile_Tag
*tag
)
426 SetFileName(CPath(tag
->FileName()));
427 m_abyFileHash
= tag
->ID();
428 SetFileSize(tag
->SizeFull());
429 m_AvailPartFrequency
.insert(m_AvailPartFrequency
.end(), m_iPartCount
, 0);
430 m_iUpPriority
= tag
->Prio();
431 if ( m_iUpPriority
>= 10 ) {
433 m_bAutoUpPriority
= true;
435 m_bAutoUpPriority
= false;
438 m_AICHMasterHash
= tag
->GetAICHHash();
441 CKnownFile::~CKnownFile()
445 #else // ! CLIENT_GUI
447 CKnownFile::~CKnownFile()
449 SourceSet::iterator it
= m_ClientUploadList
.begin();
450 for ( ; it
!= m_ClientUploadList
.end(); ++it
) {
451 (*it
)->ClearUploadFileID();
454 delete m_pAICHHashSet
;
457 void CKnownFile::AddUploadingClient(CUpDownClient
* client
)
459 m_ClientUploadList
.insert(client
);
461 UpdateAutoUpPriority();
465 void CKnownFile::RemoveUploadingClient(CUpDownClient
* client
)
467 if (m_ClientUploadList
.erase(client
)) {
468 UpdateAutoUpPriority();
473 void CKnownFile::SetFilePath(const CPath
& filePath
)
475 m_filePath
= filePath
;
479 // needed for memfiles. its probably better to switch everything to CFile...
480 bool CKnownFile::LoadHashsetFromFile(const CFileDataIO
* file
, bool checkhash
)
482 CMD4Hash checkid
= file
->ReadHash();
484 uint16 parts
= file
->ReadUInt16();
485 for (uint16 i
= 0; i
< parts
; ++i
){
486 CMD4Hash cur_hash
= file
->ReadHash();
487 m_hashlist
.push_back(cur_hash
);
490 // SLUGFILLER: SafeHash - always check for valid m_hashlist
492 m_abyFileHash
= checkid
;
493 if (parts
<= 1) { // nothing to check
497 if ( m_abyFileHash
!= checkid
) {
498 return false; // wrong file?
500 if (parts
!= GetED2KPartHashCount()) {
505 // SLUGFILLER: SafeHash
508 // lol, useless comment but made me lmao
509 // wtf you guys are weird.
511 if (!m_hashlist
.empty()) {
512 CreateHashFromHashlist(m_hashlist
, &checkid
);
515 if ( m_abyFileHash
== checkid
) {
524 bool CKnownFile::LoadTagsFromFile(const CFileDataIO
* file
)
526 uint32 tagcount
= file
->ReadUInt32();
527 for (uint32 j
= 0; j
!= tagcount
; ++j
) {
528 CTag
newtag(*file
, true);
529 switch(newtag
.GetNameID()){
531 if (GetFileName().IsOk()) {
532 // Unlike eMule, we actually prefer the second
533 // filename tag, since we use it to specify the
534 // 'universial' filename (see CPath::ToUniv).
535 CPath path
= CPath::FromUniv(newtag
.GetStr());
537 // May be invalid, if from older versions where
538 // unicoded filenames be saved as empty-strings.
543 SetFileName(CPath(newtag
.GetStr()));
548 SetFileSize(newtag
.GetInt());
549 m_AvailPartFrequency
.clear();
550 m_AvailPartFrequency
.insert(
551 m_AvailPartFrequency
.begin(),
555 case FT_ATTRANSFERRED
:
556 statistic
.alltimetransferred
+= newtag
.GetInt();
559 case FT_ATTRANSFERREDHI
:
560 statistic
.alltimetransferred
=
561 (((uint64
)newtag
.GetInt()) << 32) +
562 ((uint64
)statistic
.alltimetransferred
);
566 statistic
.alltimerequested
= newtag
.GetInt();
570 statistic
.alltimeaccepted
= newtag
.GetInt();
574 m_iUpPriority
= newtag
.GetInt();
575 if( m_iUpPriority
== PR_AUTO
){
576 m_iUpPriority
= PR_HIGH
;
577 m_bAutoUpPriority
= true;
579 if ( m_iUpPriority
!= PR_VERYLOW
&&
580 m_iUpPriority
!= PR_LOW
&&
581 m_iUpPriority
!= PR_NORMAL
&&
582 m_iUpPriority
!= PR_HIGH
&&
583 m_iUpPriority
!= PR_VERYHIGH
&&
584 m_iUpPriority
!= PR_POWERSHARE
) {
585 m_iUpPriority
= PR_NORMAL
;
588 m_bAutoUpPriority
= false;
593 // Ignore it, it's not used anymore.
599 hash
.DecodeBase32(newtag
.GetStr()) == CAICHHash::GetHashSize();
600 wxASSERT(hashSizeOk
);
602 m_pAICHHashSet
->SetMasterHash(hash
, AICH_HASHSETCOMPLETE
);
607 case FT_KADLASTPUBLISHSRC
:
608 SetLastPublishTimeKadSrc( newtag
.GetInt(), 0 );
610 if(GetLastPublishTimeKadSrc() > (uint32
)time(NULL
)+KADEMLIAREPUBLISHTIMES
) {
611 //There may be a posibility of an older client that saved a random number here.. This will check for that..
612 SetLastPublishTimeKadSrc(0, 0);
616 case FT_KADLASTPUBLISHNOTES
:
617 SetLastPublishTimeKadNotes( newtag
.GetInt() );
620 case FT_KADLASTPUBLISHKEY
:
622 wxASSERT( newtag
.IsInt() );
626 // Store them here and write them back on saving.
627 m_taglist
.push_back(newtag
);
635 bool CKnownFile::LoadDateFromFile(const CFileDataIO
* file
)
637 m_lastDateChanged
= file
->ReadUInt32();
643 bool CKnownFile::LoadFromFile(const CFileDataIO
* file
)
645 // SLUGFILLER: SafeHash - load first, verify later
646 bool ret1
= LoadDateFromFile(file
);
647 bool ret2
= LoadHashsetFromFile(file
,false);
648 bool ret3
= LoadTagsFromFile(file
);
650 // Final hash-count verification, needs to be done after the tags are loaded.
651 return ret1
&& ret2
&& ret3
&& GetED2KPartHashCount()==GetHashCount();
652 // SLUGFILLER: SafeHash
656 bool CKnownFile::WriteToFile(CFileDataIO
* file
)
658 wxCHECK(!IsPartFile(), false);
661 file
->WriteUInt32(m_lastDateChanged
);
663 file
->WriteHash(m_abyFileHash
);
665 uint16 parts
= m_hashlist
.size();
666 file
->WriteUInt16(parts
);
668 for (int i
= 0; i
< parts
; ++i
)
669 file
->WriteHash(m_hashlist
[i
]);
672 const int iFixedTags
= 8;
673 uint32 tagcount
= iFixedTags
;
674 if (HasProperAICHHashSet()) {
677 // Float meta tags are currently not written. All older eMule versions < 0.28a have
678 // a bug in the meta tag reading+writing code. To achive maximum backward
679 // compatibility for met files with older eMule versions we just don't write float
680 // tags. This is OK, because we (eMule) do not use float tags. The only float tags
681 // we may have to handle is the '# Sent' tag from the Hybrid, which is pretty
682 // useless but may be received from us via the servers.
684 // The code for writing the float tags SHOULD BE ENABLED in SOME MONTHS (after most
685 // people are using the newer eMule versions which do not write broken float tags).
686 for (size_t j
= 0; j
< m_taglist
.size(); ++j
){
687 if (m_taglist
[j
].IsInt() || m_taglist
[j
].IsStr()) {
692 if (m_lastPublishTimeKadSrc
) {
696 if (m_lastPublishTimeKadNotes
){
702 file
->WriteUInt32(tagcount
);
704 // We still save the unicoded filename, for backwards
705 // compatibility with pre-2.2 and other clients.
706 CTagString
nametag_unicode(FT_FILENAME
, GetFileName().GetRaw());
707 // We write it with BOM to kep eMule compatibility
708 nametag_unicode
.WriteTagToFile(file
,utf8strOptBOM
);
710 // The non-unicoded filename is written in an 'universial'
711 // format, which allows us to identify files, even if the
712 // system locale changes.
713 CTagString
nametag(FT_FILENAME
, CPath::ToUniv(GetFileName()));
714 nametag
.WriteTagToFile(file
);
716 CTagIntSized
sizetag(FT_FILESIZE
, GetFileSize(), IsLargeFile() ? 64 : 32);
717 sizetag
.WriteTagToFile(file
);
721 tran
=statistic
.alltimetransferred
& 0xFFFFFFFF;
722 CTagInt32
attag1(FT_ATTRANSFERRED
, tran
);
723 attag1
.WriteTagToFile(file
);
725 tran
=statistic
.alltimetransferred
>>32;
726 CTagInt32
attag4(FT_ATTRANSFERREDHI
, tran
);
727 attag4
.WriteTagToFile(file
);
729 CTagInt32
attag2(FT_ATREQUESTED
, statistic
.GetAllTimeRequests());
730 attag2
.WriteTagToFile(file
);
732 CTagInt32
attag3(FT_ATACCEPTED
, statistic
.GetAllTimeAccepts());
733 attag3
.WriteTagToFile(file
);
735 // priority N permission
736 CTagInt32
priotag(FT_ULPRIORITY
, IsAutoUpPriority() ? PR_AUTO
: m_iUpPriority
);
737 priotag
.WriteTagToFile(file
);
740 if (HasProperAICHHashSet()) {
741 CTagString
aichtag(FT_AICH_HASH
, m_pAICHHashSet
->GetMasterHash().GetString());
742 aichtag
.WriteTagToFile(file
);
746 if (m_lastPublishTimeKadSrc
){
747 CTagInt32
kadLastPubSrc(FT_KADLASTPUBLISHSRC
, m_lastPublishTimeKadSrc
);
748 kadLastPubSrc
.WriteTagToFile(file
);
752 if (m_lastPublishTimeKadNotes
){
753 CTagInt32
kadLastPubNotes(FT_KADLASTPUBLISHNOTES
, m_lastPublishTimeKadNotes
);
754 kadLastPubNotes
.WriteTagToFile(file
);
758 for (size_t j
= 0; j
< m_taglist
.size(); ++j
){
759 if (m_taglist
[j
].IsInt() || m_taglist
[j
].IsStr()) {
760 m_taglist
[j
].WriteTagToFile(file
);
767 void CKnownFile::CreateHashFromHashlist(const ArrayOfCMD4Hash
& hashes
, CMD4Hash
* Output
)
769 wxCHECK_RET(hashes
.size(), wxT("No input to hash from in CreateHashFromHashlist"));
771 std::vector
<byte
> buffer(hashes
.size() * MD4HASH_LENGTH
);
772 std::vector
<byte
>::iterator it
= buffer
.begin();
774 for (size_t i
= 0; i
< hashes
.size(); ++i
) {
775 it
= STLCopy_n(hashes
[i
].GetHash(), MD4HASH_LENGTH
, it
);
778 CreateHashFromInput(&buffer
[0], buffer
.size(), Output
, NULL
);
782 void CKnownFile::CreateHashFromFile(CFileAutoClose
& file
, uint64 offset
, uint32 Length
, CMD4Hash
* Output
, CAICHHashTree
* pShaHashOut
)
784 wxCHECK_RET(Length
, wxT("No input to hash from in CreateHashFromFile"));
787 area
.ReadAt(file
, offset
, Length
);
789 CreateHashFromInput(area
.GetBuffer(), Length
, Output
, pShaHashOut
);
794 void CKnownFile::CreateHashFromInput(const byte
* input
, uint32 Length
, CMD4Hash
* Output
, CAICHHashTree
* pShaHashOut
)
796 wxASSERT_MSG(Output
|| pShaHashOut
, wxT("Nothing to do in CreateHashFromInput"));
797 wxCHECK_RET(input
, wxT("No input to hash from in CreateHashFromInput"));
798 wxASSERT(Length
<= PARTSIZE
); // We never hash more than one PARTSIZE
800 CMemFile
data(input
, Length
);
802 uint32 Required
= Length
;
805 uint32 posCurrentEMBlock
= 0;
807 CScopedPtr
<CAICHHashAlgo
> pHashAlg(CAICHHashSet::GetNewHashAlgo());
810 while (Required
>= 64) {
811 uint32 len
= Required
/ 64;
812 if (len
> sizeof(X
)/(64 * sizeof(X
[0]))) {
813 len
= sizeof(X
)/(64 * sizeof(X
[0]));
816 data
.Read(&X
, len
* 64);
818 // SHA hash needs 180KB blocks
820 if (nIACHPos
+ len
*64 >= EMBLOCKSIZE
) {
821 uint32 nToComplete
= EMBLOCKSIZE
- nIACHPos
;
822 pHashAlg
->Add(X
, nToComplete
);
823 wxASSERT( nIACHPos
+ nToComplete
== EMBLOCKSIZE
);
824 pShaHashOut
->SetBlockHash(EMBLOCKSIZE
, posCurrentEMBlock
, pHashAlg
.get());
825 posCurrentEMBlock
+= EMBLOCKSIZE
;
827 pHashAlg
->Add(X
+nToComplete
,(len
*64) - nToComplete
);
828 nIACHPos
= (len
*64) - nToComplete
;
831 pHashAlg
->Add(X
, len
*64);
839 Required
= Length
% 64;
841 data
.Read(&X
,Required
);
843 if (pShaHashOut
!= NULL
){
844 if (nIACHPos
+ Required
>= EMBLOCKSIZE
){
845 uint32 nToComplete
= EMBLOCKSIZE
- nIACHPos
;
846 pHashAlg
->Add(X
, nToComplete
);
847 wxASSERT( nIACHPos
+ nToComplete
== EMBLOCKSIZE
);
848 pShaHashOut
->SetBlockHash(EMBLOCKSIZE
, posCurrentEMBlock
, pHashAlg
.get());
849 posCurrentEMBlock
+= EMBLOCKSIZE
;
851 pHashAlg
->Add(X
+nToComplete
, Required
- nToComplete
);
852 nIACHPos
= Required
- nToComplete
;
855 pHashAlg
->Add(X
, Required
);
856 nIACHPos
+= Required
;
860 if (pShaHashOut
!= NULL
){
862 pShaHashOut
->SetBlockHash(nIACHPos
, posCurrentEMBlock
, pHashAlg
.get());
863 posCurrentEMBlock
+= nIACHPos
;
865 wxASSERT( posCurrentEMBlock
== Length
);
866 wxCHECK2( pShaHashOut
->ReCalculateHash(pHashAlg
.get(), false), );
870 #ifdef __WEAK_CRYPTO__
871 CryptoPP::Weak::MD4 md4_hasher
;
873 CryptoPP::MD4 md4_hasher
;
875 md4_hasher
.CalculateDigest(Output
->GetHash(), input
, Length
);
880 const CMD4Hash
& CKnownFile::GetPartHash(uint16 part
) const {
881 wxASSERT( part
< m_hashlist
.size() );
883 return m_hashlist
[part
];
886 CPacket
* CKnownFile::CreateSrcInfoPacket(const CUpDownClient
* forClient
, uint8 byRequestedVersion
, uint16 nRequestedOptions
)
890 if (m_ClientUploadList
.empty()) {
894 if ((((CKnownFile
*)forClient
->GetRequestFile() != this)
895 && ((CKnownFile
*)forClient
->GetUploadFile() != this)) || forClient
->GetUploadFileID() != GetFileHash()) {
896 wxString file1
= _("Unknown");
897 if (forClient
->GetRequestFile() && forClient
->GetRequestFile()->GetFileName().IsOk()) {
898 file1
= forClient
->GetRequestFile()->GetFileName().GetPrintable();
899 } else if (forClient
->GetUploadFile() && forClient
->GetUploadFile()->GetFileName().IsOk()) {
900 file1
= forClient
->GetUploadFile()->GetFileName().GetPrintable();
902 wxString file2
= _("Unknown");
903 if (GetFileName().IsOk()) {
904 file2
= GetFileName().GetPrintable();
906 AddDebugLogLineM(false, logKnownFiles
, wxT("File missmatch on source packet (K) Sending: ") + file1
+ wxT(" From: ") + file2
);
910 const BitVector
& rcvstatus
= forClient
->GetUpPartStatus();
911 bool SupportsUploadChunksState
= !rcvstatus
.empty();
912 //wxASSERT(rcvstatus.size() == GetPartCount()); // Obviously!
913 if (rcvstatus
.size() != GetPartCount()) {
914 // Yuck. Same file but different part count? Seriously fucked up.
915 AddDebugLogLineM(false, logKnownFiles
, CFormat(wxT("Impossible situation: different partcounts for the same known file: %i (client) and %i (file)")) % rcvstatus
.size() % GetPartCount());
923 if (forClient
->SupportsSourceExchange2() && byRequestedVersion
> 0){
924 // the client uses SourceExchange2 and requested the highest version he knows
925 // and we send the highest version we know, but of course not higher than his request
926 byUsedVersion
= std::min(byRequestedVersion
, (uint8
)SOURCEEXCHANGE2_VERSION
);
928 data
.WriteUInt8(byUsedVersion
);
930 // we don't support any special SX2 options yet, reserved for later use
931 if (nRequestedOptions
!= 0) {
932 AddDebugLogLineM(false, logKnownFiles
, CFormat(wxT("Client requested unknown options for SourceExchange2: %u")) % nRequestedOptions
);
935 byUsedVersion
= forClient
->GetSourceExchange1Version();
936 bIsSX2Packet
= false;
937 if (forClient
->SupportsSourceExchange2()) {
938 AddDebugLogLineM(false, logKnownFiles
, wxT("Client which announced to support SX2 sent SX1 packet instead"));
944 data
.WriteHash(forClient
->GetUploadFileID());
945 data
.WriteUInt16(nCount
);
946 uint32 cDbgNoSrc
= 0;
948 SourceSet::iterator it
= m_ClientUploadList
.begin();
949 for ( ; it
!= m_ClientUploadList
.end(); it
++ ) {
950 const CUpDownClient
*cur_src
= *it
;
952 if ( cur_src
->HasLowID() ||
953 cur_src
== forClient
||
954 !( cur_src
->GetUploadState() == US_UPLOADING
||
955 cur_src
->GetUploadState() == US_ONUPLOADQUEUE
)) {
959 bool bNeeded
= false;
961 if ( SupportsUploadChunksState
) {
962 const BitVector
& srcstatus
= cur_src
->GetUpPartStatus();
963 if ( !srcstatus
.empty() ) {
964 //wxASSERT(srcstatus.size() == GetPartCount()); // Obviously!
965 if (srcstatus
.size() != GetPartCount()) {
968 if ( cur_src
->GetUpPartCount() == forClient
->GetUpPartCount() ) {
969 for (int x
= 0; x
< GetPartCount(); x
++ ) {
970 if ( srcstatus
.at(x
) && !rcvstatus
.at(x
) ) {
971 // We know the receiving client needs
972 // a chunk from this client.
980 // This client doesn't support upload chunk status.
981 // So just send it and hope for the best.
985 // remote client does not support upload chunk status,
986 // search sources which have at least one complete part
987 // we could even sort the list of sources by available
988 // chunks to return as much sources as possible which
989 // have the most available chunks. but this could be
990 // a noticeable performance problem.
991 const BitVector
& srcstatus
= cur_src
->GetUpPartStatus();
992 if ( !srcstatus
.empty() ) {
993 //wxASSERT(srcstatus.size() == GetPartCount());
994 if (srcstatus
.size() != GetPartCount()) {
997 for (int x
= 0; x
< GetPartCount(); x
++ ) {
998 if ( srcstatus
.at(x
) ) {
999 // this client has at least one chunk
1005 // This client doesn't support upload chunk status.
1006 // So just send it and hope for the best.
1014 if(byUsedVersion
>= 3) {
1015 dwID
= cur_src
->GetUserIDHybrid();
1017 dwID
= cur_src
->GetIP();
1019 data
.WriteUInt32(dwID
);
1020 data
.WriteUInt16(cur_src
->GetUserPort());
1021 data
.WriteUInt32(cur_src
->GetServerIP());
1022 data
.WriteUInt16(cur_src
->GetServerPort());
1024 if (byUsedVersion
>= 2) {
1025 data
.WriteHash(cur_src
->GetUserHash());
1028 if (byUsedVersion
>= 4){
1029 // CryptSettings - SourceExchange V4
1031 // 1 CryptLayer Required
1032 // 1 CryptLayer Requested
1033 // 1 CryptLayer Supported
1034 const uint8 uSupportsCryptLayer
= cur_src
->SupportsCryptLayer() ? 1 : 0;
1035 const uint8 uRequestsCryptLayer
= cur_src
->RequestsCryptLayer() ? 1 : 0;
1036 const uint8 uRequiresCryptLayer
= cur_src
->RequiresCryptLayer() ? 1 : 0;
1037 const uint8 byCryptOptions
= (uRequiresCryptLayer
<< 2) | (uRequestsCryptLayer
<< 1) | (uSupportsCryptLayer
<< 0);
1038 data
.WriteUInt8(byCryptOptions
);
1051 data
.Seek(bIsSX2Packet
? 17 : 16, wxFromStart
);
1052 data
.WriteUInt16(nCount
);
1054 CPacket
* result
= new CPacket(data
, OP_EMULEPROT
, bIsSX2Packet
? OP_ANSWERSOURCES2
: OP_ANSWERSOURCES
);
1056 if ( result
->GetPacketSize() > 354 ) {
1057 result
->PackPacket();
1064 // Updates priority of file if autopriority is activated
1065 void CKnownFile::UpdateAutoUpPriority()
1067 if (IsAutoUpPriority()) {
1068 uint32 queued
= GetQueuedCount();
1069 uint8 priority
= PR_NORMAL
;
1073 } else if (queued
> 1) {
1074 priority
= PR_NORMAL
;
1079 if (GetUpPriority() != priority
) {
1080 SetUpPriority(priority
, false);
1081 Notify_SharedFilesUpdateItem(this);
1086 void CKnownFile::SetFileComment(const wxString
& strNewComment
)
1088 if (m_strComment
!= strNewComment
) {
1089 SetLastPublishTimeKadNotes(0);
1090 wxString strCfgPath
= wxT("/") + m_abyFileHash
.Encode() + wxT("/");
1092 wxConfigBase
* cfg
= wxConfigBase::Get();
1093 cfg
->Write( strCfgPath
+ wxT("Comment"), strNewComment
);
1095 m_strComment
= strNewComment
;
1097 SourceSet::iterator it
= m_ClientUploadList
.begin();
1098 for ( ; it
!= m_ClientUploadList
.end(); it
++ ) {
1099 (*it
)->SetCommentDirty();
1106 void CKnownFile::SetFileRating(int8 iNewRating
)
1108 if (m_iRating
!= iNewRating
) {
1109 SetLastPublishTimeKadNotes(0);
1110 wxString strCfgPath
= wxT("/") + m_abyFileHash
.Encode() + wxT("/");
1111 wxConfigBase
* cfg
= wxConfigBase::Get();
1112 cfg
->Write( strCfgPath
+ wxT("Rate"), (int)iNewRating
);
1113 m_iRating
= iNewRating
;
1115 SourceSet::iterator it
= m_ClientUploadList
.begin();
1116 for ( ; it
!= m_ClientUploadList
.end(); it
++ ) {
1117 (*it
)->SetCommentDirty();
1123 void CKnownFile::SetUpPriority(uint8 iNewUpPriority
, bool m_bsave
){
1124 m_iUpPriority
= iNewUpPriority
;
1125 if( IsPartFile() && m_bsave
) {
1126 ((CPartFile
*)this)->SavePartFile();
1130 void CKnownFile::SetPublishedED2K(bool val
){
1131 m_PublishedED2K
= val
;
1132 Notify_SharedFilesUpdateItem(this);
1135 bool CKnownFile::PublishNotes()
1137 if(m_lastPublishTimeKadNotes
> (uint32
)time(NULL
)) {
1141 if(!GetFileComment().IsEmpty()) {
1142 m_lastPublishTimeKadNotes
= (uint32
)time(NULL
)+KADEMLIAREPUBLISHTIMEN
;
1146 if(GetFileRating() != 0) {
1147 m_lastPublishTimeKadNotes
= (uint32
)time(NULL
)+KADEMLIAREPUBLISHTIMEN
;
1154 bool CKnownFile::PublishSrc()
1156 uint32 lastBuddyIP
= 0;
1158 if( theApp
->IsFirewalled() ) {
1159 CUpDownClient
* buddy
= theApp
->clientlist
->GetBuddy();
1161 lastBuddyIP
= theApp
->clientlist
->GetBuddy()->GetIP();
1162 if( lastBuddyIP
!= m_lastBuddyIP
) {
1163 SetLastPublishTimeKadSrc( (uint32
)time(NULL
)+KADEMLIAREPUBLISHTIMES
, lastBuddyIP
);
1171 if(m_lastPublishTimeKadSrc
> (uint32
)time(NULL
)) {
1175 SetLastPublishTimeKadSrc((uint32
)time(NULL
)+KADEMLIAREPUBLISHTIMES
,lastBuddyIP
);
1180 void CKnownFile::UpdatePartsInfo()
1183 uint16 partcount
= GetPartCount();
1184 bool flag
= (time(NULL
) - m_nCompleteSourcesTime
> 0);
1186 // Ensure the frequency-list is ready
1187 if ( m_AvailPartFrequency
.size() != GetPartCount() ) {
1188 m_AvailPartFrequency
.clear();
1189 m_AvailPartFrequency
.insert(m_AvailPartFrequency
.begin(), GetPartCount(), 0);
1193 ArrayOfUInts16 count
;
1194 count
.reserve(m_ClientUploadList
.size());
1196 SourceSet::iterator it
= m_ClientUploadList
.begin();
1197 for ( ; it
!= m_ClientUploadList
.end(); it
++ ) {
1198 if ( !(*it
)->GetUpPartStatus().empty() && (*it
)->GetUpPartCount() == partcount
) {
1199 count
.push_back((*it
)->GetUpCompleteSourcesCount());
1203 m_nCompleteSourcesCount
= m_nCompleteSourcesCountLo
= m_nCompleteSourcesCountHi
= 0;
1205 if( partcount
> 0) {
1206 m_nCompleteSourcesCount
= m_AvailPartFrequency
[0];
1208 for (uint16 i
= 1; i
< partcount
; ++i
) {
1209 if( m_nCompleteSourcesCount
> m_AvailPartFrequency
[i
]) {
1210 m_nCompleteSourcesCount
= m_AvailPartFrequency
[i
];
1213 count
.push_back(m_nCompleteSourcesCount
);
1215 int32 n
= count
.size();
1217 std::sort(count
.begin(), count
.end(), std::less
<uint16
>());
1220 int i
= n
>> 1; // (n / 2)
1221 int j
= (n
* 3) >> 2; // (n * 3) / 4
1222 int k
= (n
* 7) >> 3; // (n * 7) / 8
1224 // For complete files, trust the people your uploading to more...
1226 // For low guess and normal guess count
1227 // - If we see more sources then the guessed low and
1228 // normal, use what we see.
1229 // - If we see less sources then the guessed low,
1230 // adjust network accounts for 100%, we account for
1231 // 0% with what we see and make sure we are still
1232 // above the normal.
1234 // Adjust 100% network and 0% what we see.
1236 if ( count
[i
] < m_nCompleteSourcesCount
) {
1237 m_nCompleteSourcesCountLo
= m_nCompleteSourcesCount
;
1239 m_nCompleteSourcesCountLo
= count
[i
];
1241 m_nCompleteSourcesCount
= m_nCompleteSourcesCountLo
;
1242 m_nCompleteSourcesCountHi
= count
[j
];
1243 if( m_nCompleteSourcesCountHi
< m_nCompleteSourcesCount
) {
1244 m_nCompleteSourcesCountHi
= m_nCompleteSourcesCount
;
1251 // Adjust network accounts for 100%, we account for
1252 // 0% with what we see and make sure we are still above the low.
1254 // Adjust network accounts for 100%, we account for 0%
1255 // with what we see and make sure we are still above the normal.
1257 m_nCompleteSourcesCountLo
= m_nCompleteSourcesCount
;
1258 m_nCompleteSourcesCount
= count
[j
];
1259 if( m_nCompleteSourcesCount
< m_nCompleteSourcesCountLo
) {
1260 m_nCompleteSourcesCount
= m_nCompleteSourcesCountLo
;
1262 m_nCompleteSourcesCountHi
= count
[k
];
1263 if( m_nCompleteSourcesCountHi
< m_nCompleteSourcesCount
) {
1264 m_nCompleteSourcesCountHi
= m_nCompleteSourcesCount
;
1268 m_nCompleteSourcesTime
= time(NULL
) + (60);
1271 Notify_SharedFilesUpdateItem(this);
1275 void CKnownFile::UpdateUpPartsFrequency( CUpDownClient
* client
, bool increment
)
1277 if ( m_AvailPartFrequency
.size() != GetPartCount() ) {
1278 m_AvailPartFrequency
.clear();
1279 m_AvailPartFrequency
.insert(m_AvailPartFrequency
.begin(), GetPartCount(), 0);
1285 const BitVector
& freq
= client
->GetUpPartStatus();
1286 unsigned int size
= freq
.size();
1287 if ( size
!= m_AvailPartFrequency
.size() ) {
1292 for ( unsigned int i
= 0; i
< size
; ++i
) {
1294 m_AvailPartFrequency
[i
]++;
1298 for ( unsigned int i
= 0; i
< size
; ++i
) {
1300 m_AvailPartFrequency
[i
]--;
1306 void CKnownFile::ClearPriority() {
1307 if ( !m_bAutoUpPriority
) return;
1308 m_iUpPriority
= ( m_bAutoUpPriority
) ? PR_HIGH
: PR_NORMAL
;
1309 UpdateAutoUpPriority();
1312 void CKnownFile::SetFileName(const CPath
& filename
)
1314 CAbstractFile::SetFileName(filename
);
1317 Kademlia::CSearchManager::GetWords(GetFileName().GetPrintable(), &wordlist
);
1321 #endif // CLIENT_GUI
1323 //For File Comment //
1324 void CKnownFile::LoadComment()
1327 wxString strCfgPath
= wxT("/") + m_abyFileHash
.Encode() + wxT("/");
1329 wxConfigBase
* cfg
= wxConfigBase::Get();
1331 m_strComment
= cfg
->Read( strCfgPath
+ wxT("Comment"), wxEmptyString
);
1332 m_iRating
= cfg
->Read( strCfgPath
+ wxT("Rate"), 0l);
1333 m_bCommentLoaded
= true;
1336 m_strComment
= wxT("Comments are not allowed on remote gui yet");
1337 m_bCommentLoaded
= true;
1344 wxString
CKnownFile::GetAICHMasterHash() const
1347 return m_AICHMasterHash
;
1349 if (HasProperAICHHashSet()) {
1350 return m_pAICHHashSet
->GetMasterHash().GetString();
1353 return wxEmptyString
;
1358 bool CKnownFile::HasProperAICHHashSet() const
1361 return m_AICHMasterHash
.Length() != 0;
1363 return m_pAICHHashSet
->HasValidMasterHash() &&
1364 (m_pAICHHashSet
->GetStatus() == AICH_HASHSETCOMPLETE
||
1365 m_pAICHHashSet
->GetStatus() == AICH_VERIFIED
);
1369 wxString
CKnownFile::GetFeedback() const
1371 return wxString(_("File name")) + wxT(": ") + GetFileName().GetPrintable() + wxT("\n")
1372 + _("File size") + wxT(": ") + CastItoXBytes(GetFileSize()) + wxT("\n")
1373 + _("Share ratio") + wxString::Format(wxT(": %.2f%%\n"), (((double)statistic
.GetAllTimeTransferred() / (double)GetFileSize()) * 100.0))
1374 + _("Uploaded") + wxT(": ") + CastItoXBytes(statistic
.GetTransferred()) + wxT(" (") + CastItoXBytes(statistic
.GetAllTimeTransferred()) + wxT(")\n")
1375 + _("Requested") + CFormat(wxT(": %u (%u)\n")) % statistic
.GetRequests() % statistic
.GetAllTimeRequests()
1376 + _("Accepted") + CFormat(wxT(": %u (%u)\n")) % statistic
.GetAccepts() % statistic
.GetAllTimeAccepts()
1377 + _("On Queue") + CFormat(wxT(": %u\n")) % GetQueuedCount()
1378 + _("Complete sources") + CFormat(wxT(": %u\n")) % m_nCompleteSourcesCount
;
1380 // File_checked_for_headers