Upstream tarball 20080414
[amule.git] / src / KnownFile.cpp
blobd2b3bdb0799d7c2ebf599bae464e8ef29580d34a
1 //
2 // This file is part of the aMule Project.
3 //
4 // Parts of this file are based on work from pan One (http://home-3.tiscali.nl/~meost/pms/)
5 //
6 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
7 // Copyright (c) 2002 Merkur ( devs@emule-project.net / http://www.emule-project.net )
8 //
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.
22 //
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)
49 #include "Logger.h"
50 #include "ScopedPtr.h" // Needed for CScopedArray and CScopedPtr
51 #include "GuiEvents.h" // Needed for Notify_*
52 #include "SearchFile.h" // Needed for CSearchFile
54 #include "CryptoPP_Inc.h" // Needed for MD4
56 #include <common/Format.h>
58 CFileStatistic::CFileStatistic() :
59 requested(0),
60 transferred(0),
61 accepted(0),
62 alltimerequested(0),
63 alltimetransferred(0),
64 alltimeaccepted(0)
68 #ifndef CLIENT_GUI
70 void CFileStatistic::AddRequest(){
71 requested++;
72 alltimerequested++;
73 theApp->knownfiles->requested++;
74 theApp->sharedfiles->UpdateItem(fileParent);
77 void CFileStatistic::AddAccepted(){
78 accepted++;
79 alltimeaccepted++;
80 theApp->knownfiles->accepted++;
81 theApp->sharedfiles->UpdateItem(fileParent);
84 void CFileStatistic::AddTransferred(uint64 bytes){
85 transferred += bytes;
86 alltimetransferred += bytes;
87 theApp->knownfiles->transferred += bytes;
88 theApp->sharedfiles->UpdateItem(fileParent);
91 #endif // CLIENT_GUI
94 /* Abstract File (base class)*/
96 CAbstractFile::CAbstractFile()
98 m_iRating(0),
99 m_hasComment(false),
100 m_iUserRating(0),
101 m_nFileSize(0)
106 CAbstractFile::CAbstractFile(const CAbstractFile& other)
108 m_abyFileHash(other.m_abyFileHash),
109 m_strComment(other.m_strComment),
110 m_iRating(other.m_iRating),
111 m_hasComment(other.m_hasComment),
112 m_iUserRating(other.m_iUserRating),
113 m_taglist(other.m_taglist),
114 m_nFileSize(other.m_nFileSize),
115 m_fileName(other.m_fileName)
117 /* // TODO: Currently it's not safe to duplicate the entries, but isn't needed either.
118 CKadEntryPtrList::const_iterator it = other.m_kadNotes.begin();
119 for (; it != other.m_kadNotes.end(); ++it) {
120 m_kadNotes.push_back(new Kademlia::CEntry(**it));
126 void CAbstractFile::SetFileName(const CPath& fileName)
128 m_fileName = fileName;
131 uint32 CAbstractFile::GetIntTagValue(uint8 tagname) const
133 ArrayOfCTag::const_iterator it = m_taglist.begin();
134 for (; it != m_taglist.end(); ++it){
135 if (((*it).GetNameID() == tagname) && (*it).IsInt()) {
136 return (*it).GetInt();
139 return 0;
142 bool CAbstractFile::GetIntTagValue(uint8 tagname, uint32& ruValue) const
144 ArrayOfCTag::const_iterator it = m_taglist.begin();
145 for (; it != m_taglist.end(); ++it){
146 if (((*it).GetNameID() == tagname) && (*it).IsInt()){
147 ruValue = (*it).GetInt();
148 return true;
151 return false;
154 uint32 CAbstractFile::GetIntTagValue(const wxString& tagname) const
156 ArrayOfCTag::const_iterator it = m_taglist.begin();
157 for (; it != m_taglist.end(); ++it){
158 if ((*it).IsInt() && ((*it).GetName() == tagname)) {
159 return (*it).GetInt();
162 return 0;
165 const wxString& CAbstractFile::GetStrTagValue(uint8 tagname) const
167 ArrayOfCTag::const_iterator it = m_taglist.begin();
168 for (; it != m_taglist.end(); ++it){
169 if ((*it).GetNameID() == tagname && (*it).IsStr()) {
170 return (*it).GetStr();
173 return EmptyString;
176 const wxString& CAbstractFile::GetStrTagValue(const wxString& tagname) const
178 ArrayOfCTag::const_iterator it = m_taglist.begin();
179 for (; it != m_taglist.end(); ++it){
180 if ((*it).IsStr() && ((*it).GetName() == tagname)) {
181 return (*it).GetStr();
184 return EmptyString;
187 const CTag *CAbstractFile::GetTag(uint8 tagname, uint8 tagtype) const
189 ArrayOfCTag::const_iterator it = m_taglist.begin();
190 for (; it != m_taglist.end(); ++it){
191 if ((*it).GetNameID() == tagname && (*it).GetType() == tagtype) {
192 return &(*it);
195 return NULL;
198 const CTag *CAbstractFile::GetTag(const wxString& tagname, uint8 tagtype) const
200 ArrayOfCTag::const_iterator it = m_taglist.begin();
201 for (; it != m_taglist.end(); ++it){
202 if ((*it).GetType() == tagtype && (*it).GetName() == tagname) {
203 return &(*it);
206 return NULL;
209 const CTag *CAbstractFile::GetTag(uint8 tagname) const
211 ArrayOfCTag::const_iterator it = m_taglist.begin();
212 for (; it != m_taglist.end(); ++it){
213 if ((*it).GetNameID() == tagname) {
214 return &(*it);
217 return NULL;
220 const CTag *CAbstractFile::GetTag(const wxString& tagname) const
222 ArrayOfCTag::const_iterator it = m_taglist.begin();
223 for (; it != m_taglist.end(); ++it){
224 if ((*it).GetName() == tagname) {
225 return &(*it);
228 return NULL;
231 void CAbstractFile::AddTagUnique(const CTag &rTag)
233 ArrayOfCTag::iterator it = m_taglist.begin();
234 for (; it != m_taglist.end(); ++it) {
235 if ( ( ((*it).GetNameID() != 0 &&
236 (*it).GetNameID() == rTag.GetNameID()) ||
237 (!(*it).GetName().IsEmpty() &&
238 !rTag.GetName().IsEmpty() &&
239 (*it).GetName() == rTag.GetName()) ) &&
240 (*it).GetType() == rTag.GetType()){
241 m_taglist.erase(it);
242 m_taglist.insert(it, rTag);
243 return;
246 m_taglist.push_back(rTag);
249 #ifndef CLIENT_GUI
250 void CAbstractFile::AddNote(Kademlia::CEntry *pEntry)
252 CKadEntryPtrList::iterator it = m_kadNotes.begin();
253 for (; it != m_kadNotes.end(); ++it) {
254 Kademlia::CEntry* entry = *it;
255 if(entry->m_iIP == pEntry->m_iIP ||
256 !entry->m_iSourceID.CompareTo(pEntry->m_iSourceID)) {
257 delete pEntry;
258 return;
261 m_kadNotes.push_front(pEntry);
263 #else
264 void CAbstractFile::AddNote(Kademlia::CEntry *)
267 #endif
270 /* Known File */
272 CKnownFile::CKnownFile()
274 Init();
276 m_bAutoUpPriority = thePrefs::GetNewAutoUp();
277 m_iUpPriority = ( m_bAutoUpPriority ) ? PR_HIGH : PR_NORMAL;
281 //#warning Experimental: Construct a CKnownFile from a CSearchFile
282 CKnownFile::CKnownFile(const CSearchFile &searchFile)
284 // This will copy the file hash
285 CAbstractFile(static_cast<const CAbstractFile &>(searchFile))
287 Init();
289 // Use CKnownFile::SetFileName()
290 SetFileName(searchFile.GetFileName());
292 // Use CKnownFile::SetFileSize()
293 SetFileSize(searchFile.GetFileSize());
295 m_bAutoUpPriority = thePrefs::GetNewAutoUp();
296 m_iUpPriority = ( m_bAutoUpPriority ) ? PR_HIGH : PR_NORMAL;
300 void CKnownFile::Init()
302 m_nCompleteSourcesTime = time(NULL);
303 m_nCompleteSourcesCount = 0;
304 m_nCompleteSourcesCountLo = 0;
305 m_nCompleteSourcesCountHi = 0;
306 m_bCommentLoaded = false;
307 m_iPartCount = 0;
308 m_iED2KPartCount = 0;
309 m_iED2KPartHashCount = 0;
310 m_PublishedED2K = false;
311 kadFileSearchID = 0;
312 m_lastPublishTimeKadSrc = 0;
313 m_lastPublishTimeKadNotes = 0;
314 m_lastBuddyIP = 0;
315 m_lastDateChanged = 0;
317 statistic.fileParent = this;
319 #ifndef CLIENT_GUI
320 m_pAICHHashSet = new CAICHHashSet(this);
321 #endif
325 #ifdef CLIENT_GUI
327 CKnownFile::CKnownFile(CEC_SharedFile_Tag *tag)
329 Init();
331 SetFileName(CPath(tag->FileName()));
332 m_abyFileHash = tag->ID();
333 SetFileSize(tag->SizeFull());
334 m_iPartCount = (GetFileSize() + (PARTSIZE - 1)) / PARTSIZE;
335 m_AvailPartFrequency.insert(m_AvailPartFrequency.end(), m_iPartCount, 0);
336 m_iUpPriority = tag->Prio();
337 if ( m_iUpPriority >= 10 ) {
338 m_iUpPriority-= 10;
339 m_bAutoUpPriority = true;
340 } else {
341 m_bAutoUpPriority = false;
344 m_AICHMasterHash = tag->GetAICHHash();
347 CKnownFile::~CKnownFile()
351 #else // ! CLIENT_GUI
353 CKnownFile::~CKnownFile()
355 SourceSet::iterator it = m_ClientUploadList.begin();
356 for ( ; it != m_ClientUploadList.end(); ++it ) {
357 (*it)->ClearUploadFileID();
360 delete m_pAICHHashSet;
363 void CKnownFile::AddUploadingClient(CUpDownClient* client)
365 m_ClientUploadList.insert(client);
367 UpdateAutoUpPriority();
371 void CKnownFile::RemoveUploadingClient(CUpDownClient* client)
373 if (m_ClientUploadList.erase(client)) {
374 UpdateAutoUpPriority();
379 void CKnownFile::SetFilePath(const CPath& filePath)
381 m_filePath = filePath;
385 void CKnownFile::SetFileSize(uint64 nFileSize)
387 CAbstractFile::SetFileSize(nFileSize);
388 m_pAICHHashSet->SetFileSize(nFileSize);
390 // Examples of parthashs, hashsets and filehashs for different filesizes
391 // according the ed2k protocol
392 //----------------------------------------------------------------------
394 //File size: 3 bytes
395 //File hash: 2D55E87D0E21F49B9AD25F98531F3724
396 //Nr. hashs: 0
399 //File size: 1*PARTSIZE
400 //File hash: A72CA8DF7F07154E217C236C89C17619
401 //Nr. hashs: 2
402 //Hash[ 0]: 4891ED2E5C9C49F442145A3A5F608299
403 //Hash[ 1]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
406 //File size: 1*PARTSIZE + 1 byte
407 //File hash: 2F620AE9D462CBB6A59FE8401D2B3D23
408 //Nr. hashs: 2
409 //Hash[ 0]: 121795F0BEDE02DDC7C5426D0995F53F
410 //Hash[ 1]: C329E527945B8FE75B3C5E8826755747
413 //File size: 2*PARTSIZE
414 //File hash: A54C5E562D5E03CA7D77961EB9A745A4
415 //Nr. hashs: 3
416 //Hash[ 0]: B3F5CE2A06BF403BFB9BFFF68BDDC4D9
417 //Hash[ 1]: 509AA30C9EA8FC136B1159DF2F35B8A9
418 //Hash[ 2]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
421 //File size: 3*PARTSIZE
422 //File hash: 5E249B96F9A46A18FC2489B005BF2667
423 //Nr. hashs: 4
424 //Hash[ 0]: 5319896A2ECAD43BF17E2E3575278E72
425 //Hash[ 1]: D86EF157D5E49C5ED502EDC15BB5F82B
426 //Hash[ 2]: 10F2D5B1FCB95C0840519C58D708480F
427 //Hash[ 3]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
430 //File size: 3*PARTSIZE + 1 byte
431 //File hash: 797ED552F34380CAFF8C958207E40355
432 //Nr. hashs: 4
433 //Hash[ 0]: FC7FD02CCD6987DCF1421F4C0AF94FB8
434 //Hash[ 1]: 2FE466AF8A7C06DA3365317B75A5ACFE
435 //Hash[ 2]: 873D3BF52629F7C1527C6E8E473C1C30
436 //Hash[ 3]: BCE50BEE7877BB07BB6FDA56BFE142FB
439 // File size Data parts ED2K parts ED2K part hashs
440 // ---------------------------------------------------------------
441 // 1..PARTSIZE-1 1 1 0(!)
442 // PARTSIZE 1 2(!) 2(!)
443 // PARTSIZE+1 2 2 2
444 // PARTSIZE*2 2 3(!) 3(!)
445 // PARTSIZE*2+1 3 3 3
447 if (nFileSize == 0){
448 //wxASSERT(0); // Kry - Why commented out by lemonfan? it can never be 0
449 m_iPartCount = 0;
450 m_iED2KPartCount = 0;
451 m_iED2KPartHashCount = 0;
452 return;
455 // nr. of data parts
456 m_iPartCount = (nFileSize + (PARTSIZE - 1)) / PARTSIZE;
458 // nr. of parts to be used with OP_FILESTATUS
459 m_iED2KPartCount = nFileSize / PARTSIZE + 1;
461 // nr. of parts to be used with OP_HASHSETANSWER
462 m_iED2KPartHashCount = nFileSize / PARTSIZE;
463 if (m_iED2KPartHashCount != 0) {
464 m_iED2KPartHashCount += 1;
469 // needed for memfiles. its probably better to switch everything to CFile...
470 bool CKnownFile::LoadHashsetFromFile(const CFileDataIO* file, bool checkhash)
472 CMD4Hash checkid = file->ReadHash();
474 uint16 parts = file->ReadUInt16();
475 for (uint16 i = 0; i < parts; ++i){
476 CMD4Hash cur_hash = file->ReadHash();
477 m_hashlist.push_back(cur_hash);
480 // SLUGFILLER: SafeHash - always check for valid m_hashlist
481 if (!checkhash){
482 m_abyFileHash = checkid;
483 if (parts <= 1) { // nothing to check
484 return true;
486 } else {
487 if ( m_abyFileHash != checkid ) {
488 return false; // wrong file?
489 } else {
490 if (parts != GetED2KPartHashCount()) {
491 return false;
495 // SLUGFILLER: SafeHash
497 // trust noone ;-)
498 // lol, useless comment but made me lmao
499 // wtf you guys are weird.
501 if (!m_hashlist.empty()) {
502 CreateHashFromHashlist(m_hashlist, &checkid);
505 if ( m_abyFileHash == checkid ) {
506 return true;
507 } else {
508 m_hashlist.clear();
509 return false;
514 bool CKnownFile::LoadTagsFromFile(const CFileDataIO* file)
516 uint32 tagcount = file->ReadUInt32();
517 for (uint32 j = 0; j != tagcount; ++j) {
518 CTag newtag(*file, true);
519 switch(newtag.GetNameID()){
520 case FT_FILENAME:
521 if (GetFileName().IsOk()) {
522 // Unlike eMule, we actually prefer the second
523 // filename tag, since we use it to specify the
524 // 'universial' filename (see CPath::ToUniv).
525 CPath path = CPath::FromUniv(newtag.GetStr());
527 // May be invalid, if from older versions where
528 // unicoded filenames be saved as empty-strings.
529 if (path.IsOk()) {
530 SetFileName(path);
532 } else {
533 SetFileName(CPath(newtag.GetStr()));
535 break;
537 case FT_FILESIZE:
538 SetFileSize(newtag.GetInt());
539 m_AvailPartFrequency.clear();
540 m_AvailPartFrequency.insert(
541 m_AvailPartFrequency.begin(),
542 GetPartCount(), 0);
543 break;
545 case FT_ATTRANSFERRED:
546 statistic.alltimetransferred += newtag.GetInt();
547 break;
549 case FT_ATTRANSFERREDHI:
550 statistic.alltimetransferred =
551 (((uint64)newtag.GetInt()) << 32) +
552 ((uint64)statistic.alltimetransferred);
553 break;
555 case FT_ATREQUESTED:
556 statistic.alltimerequested = newtag.GetInt();
557 break;
559 case FT_ATACCEPTED:
560 statistic.alltimeaccepted = newtag.GetInt();
561 break;
563 case FT_ULPRIORITY:
564 m_iUpPriority = newtag.GetInt();
565 if( m_iUpPriority == PR_AUTO ){
566 m_iUpPriority = PR_HIGH;
567 m_bAutoUpPriority = true;
568 } else {
569 if ( m_iUpPriority != PR_VERYLOW &&
570 m_iUpPriority != PR_LOW &&
571 m_iUpPriority != PR_NORMAL &&
572 m_iUpPriority != PR_HIGH &&
573 m_iUpPriority != PR_VERYHIGH &&
574 m_iUpPriority != PR_POWERSHARE) {
575 m_iUpPriority = PR_NORMAL;
578 m_bAutoUpPriority = false;
580 break;
582 case FT_PERMISSIONS:
583 // Ignore it, it's not used anymore.
584 break;
586 case FT_AICH_HASH: {
587 CAICHHash hash;
588 bool hashSizeOk =
589 hash.DecodeBase32(newtag.GetStr()) == CAICHHash::GetHashSize();
590 wxASSERT(hashSizeOk);
591 if (hashSizeOk) {
592 m_pAICHHashSet->SetMasterHash(hash, AICH_HASHSETCOMPLETE);
594 break;
597 case FT_KADLASTPUBLISHSRC:
598 SetLastPublishTimeKadSrc( newtag.GetInt(), 0 );
600 if(GetLastPublishTimeKadSrc() > (uint32)time(NULL)+KADEMLIAREPUBLISHTIMES) {
601 //There may be a posibility of an older client that saved a random number here.. This will check for that..
602 SetLastPublishTimeKadSrc(0, 0);
604 break;
606 case FT_KADLASTPUBLISHNOTES:
607 SetLastPublishTimeKadNotes( newtag.GetInt() );
608 break;
610 case FT_KADLASTPUBLISHKEY:
611 // Just purge it
612 wxASSERT( newtag.IsInt() );
613 break;
615 default:
616 // Store them here and write them back on saving.
617 m_taglist.push_back(newtag);
621 return true;
625 bool CKnownFile::LoadDateFromFile(const CFileDataIO* file)
627 m_lastDateChanged = file->ReadUInt32();
629 return true;
633 bool CKnownFile::LoadFromFile(const CFileDataIO* file)
635 // SLUGFILLER: SafeHash - load first, verify later
636 bool ret1 = LoadDateFromFile(file);
637 bool ret2 = LoadHashsetFromFile(file,false);
638 bool ret3 = LoadTagsFromFile(file);
639 UpdatePartsInfo();
640 // Final hash-count verification, needs to be done after the tags are loaded.
641 return ret1 && ret2 && ret3 && GetED2KPartHashCount()==GetHashCount();
642 // SLUGFILLER: SafeHash
646 bool CKnownFile::WriteToFile(CFileDataIO* file)
648 wxCHECK(!IsPartFile(), false);
650 // date
651 file->WriteUInt32(m_lastDateChanged);
652 // hashset
653 file->WriteHash(m_abyFileHash);
655 uint16 parts = m_hashlist.size();
656 file->WriteUInt16(parts);
658 for (int i = 0; i < parts; ++i)
659 file->WriteHash(m_hashlist[i]);
661 //tags
662 const int iFixedTags = 8;
663 uint32 tagcount = iFixedTags;
664 if (HasProperAICHHashSet()) {
665 tagcount++;
667 // Float meta tags are currently not written. All older eMule versions < 0.28a have
668 // a bug in the meta tag reading+writing code. To achive maximum backward
669 // compatibility for met files with older eMule versions we just don't write float
670 // tags. This is OK, because we (eMule) do not use float tags. The only float tags
671 // we may have to handle is the '# Sent' tag from the Hybrid, which is pretty
672 // useless but may be received from us via the servers.
674 // The code for writing the float tags SHOULD BE ENABLED in SOME MONTHS (after most
675 // people are using the newer eMule versions which do not write broken float tags).
676 for (size_t j = 0; j < m_taglist.size(); ++j){
677 if (m_taglist[j].IsInt() || m_taglist[j].IsStr()) {
678 ++tagcount;
682 if (m_lastPublishTimeKadSrc) {
683 ++tagcount;
686 if (m_lastPublishTimeKadNotes){
687 ++tagcount;
690 // standard tags
692 file->WriteUInt32(tagcount);
694 // We still save the unicoded filename, for backwards
695 // compatibility with pre-2.2 and other clients.
696 CTagString nametag_unicode(FT_FILENAME, GetFileName().GetRaw());
697 // We write it with BOM to kep eMule compatibility
698 nametag_unicode.WriteTagToFile(file,utf8strOptBOM);
700 // The non-unicoded filename is written in an 'universial'
701 // format, which allows us to identify files, even if the
702 // system locale changes.
703 CTagString nametag(FT_FILENAME, CPath::ToUniv(GetFileName()));
704 nametag.WriteTagToFile(file);
706 CTagIntSized sizetag(FT_FILESIZE, GetFileSize(), IsLargeFile() ? 64 : 32);
707 sizetag.WriteTagToFile(file);
709 // statistic
710 uint32 tran;
711 tran=statistic.alltimetransferred & 0xFFFFFFFF;
712 CTagInt32 attag1(FT_ATTRANSFERRED, tran);
713 attag1.WriteTagToFile(file);
715 tran=statistic.alltimetransferred>>32;
716 CTagInt32 attag4(FT_ATTRANSFERREDHI, tran);
717 attag4.WriteTagToFile(file);
719 CTagInt32 attag2(FT_ATREQUESTED, statistic.GetAllTimeRequests());
720 attag2.WriteTagToFile(file);
722 CTagInt32 attag3(FT_ATACCEPTED, statistic.GetAllTimeAccepts());
723 attag3.WriteTagToFile(file);
725 // priority N permission
726 CTagInt32 priotag(FT_ULPRIORITY, IsAutoUpPriority() ? PR_AUTO : m_iUpPriority);
727 priotag.WriteTagToFile(file);
729 //AICH Filehash
730 if (HasProperAICHHashSet()) {
731 CTagString aichtag(FT_AICH_HASH, m_pAICHHashSet->GetMasterHash().GetString());
732 aichtag.WriteTagToFile(file);
735 // Kad sources
736 if (m_lastPublishTimeKadSrc){
737 CTagInt32 kadLastPubSrc(FT_KADLASTPUBLISHSRC, m_lastPublishTimeKadSrc);
738 kadLastPubSrc.WriteTagToFile(file);
741 // Kad notes
742 if (m_lastPublishTimeKadNotes){
743 CTagInt32 kadLastPubNotes(FT_KADLASTPUBLISHNOTES, m_lastPublishTimeKadNotes);
744 kadLastPubNotes.WriteTagToFile(file);
747 //other tags
748 for (size_t j = 0; j < m_taglist.size(); ++j){
749 if (m_taglist[j].IsInt() || m_taglist[j].IsStr()) {
750 m_taglist[j].WriteTagToFile(file);
753 return true;
757 void CKnownFile::CreateHashFromHashlist(const ArrayOfCMD4Hash& hashes, CMD4Hash* Output)
759 wxCHECK_RET(hashes.size(), wxT("No input to hash from in CreateHashFromHashlist"));
761 std::vector<byte> buffer(hashes.size() * MD4HASH_LENGTH);
762 std::vector<byte>::iterator it = buffer.begin();
764 for (size_t i = 0; i < hashes.size(); ++i) {
765 it = STLCopy_n(hashes[i].GetHash(), MD4HASH_LENGTH, it);
768 CreateHashFromInput(&buffer[0], buffer.size(), Output, NULL);
772 void CKnownFile::CreateHashFromFile(CFileDataIO* file, uint32 Length, CMD4Hash* Output, CAICHHashTree* pShaHashOut)
774 wxCHECK_RET(file && Length, wxT("No input to hash from in CreateHashFromFile"));
776 std::vector<byte> buffer(Length);
777 file->Read(&buffer[0], Length);
779 CreateHashFromInput(&buffer[0], Length, Output, pShaHashOut);
783 void CKnownFile::CreateHashFromInput(const byte* input, uint32 Length, CMD4Hash* Output, CAICHHashTree* pShaHashOut )
785 wxASSERT_MSG(Output || pShaHashOut, wxT("Nothing to do in CreateHashFromInput"));
786 wxCHECK_RET(input, wxT("No input to hash from in CreateHashFromInput"));
787 wxASSERT(Length <= PARTSIZE); // We never hash more than one PARTSIZE
789 CMemFile data(input, Length);
791 uint32 Required = Length;
792 byte X[64*128];
794 uint32 posCurrentEMBlock = 0;
795 uint32 nIACHPos = 0;
796 CScopedPtr<CAICHHashAlgo> pHashAlg(CAICHHashSet::GetNewHashAlgo());
798 // This is all AICH.
799 while (Required >= 64) {
800 uint32 len = Required / 64;
801 if (len > sizeof(X)/(64 * sizeof(X[0]))) {
802 len = sizeof(X)/(64 * sizeof(X[0]));
805 data.Read(&X, len * 64);
807 // SHA hash needs 180KB blocks
808 if (pShaHashOut) {
809 if (nIACHPos + len*64 >= EMBLOCKSIZE) {
810 uint32 nToComplete = EMBLOCKSIZE - nIACHPos;
811 pHashAlg->Add(X, nToComplete);
812 wxASSERT( nIACHPos + nToComplete == EMBLOCKSIZE );
813 pShaHashOut->SetBlockHash(EMBLOCKSIZE, posCurrentEMBlock, pHashAlg.get());
814 posCurrentEMBlock += EMBLOCKSIZE;
815 pHashAlg->Reset();
816 pHashAlg->Add(X+nToComplete,(len*64) - nToComplete);
817 nIACHPos = (len*64) - nToComplete;
819 else{
820 pHashAlg->Add(X, len*64);
821 nIACHPos += len*64;
825 Required -= len*64;
827 // bytes to read
828 Required = Length % 64;
829 if (Required != 0){
830 data.Read(&X,Required);
832 if (pShaHashOut != NULL){
833 if (nIACHPos + Required >= EMBLOCKSIZE){
834 uint32 nToComplete = EMBLOCKSIZE - nIACHPos;
835 pHashAlg->Add(X, nToComplete);
836 wxASSERT( nIACHPos + nToComplete == EMBLOCKSIZE );
837 pShaHashOut->SetBlockHash(EMBLOCKSIZE, posCurrentEMBlock, pHashAlg.get());
838 posCurrentEMBlock += EMBLOCKSIZE;
839 pHashAlg->Reset();
840 pHashAlg->Add(X+nToComplete, Required - nToComplete);
841 nIACHPos = Required - nToComplete;
843 else{
844 pHashAlg->Add(X, Required);
845 nIACHPos += Required;
849 if (pShaHashOut != NULL){
850 if(nIACHPos > 0){
851 pShaHashOut->SetBlockHash(nIACHPos, posCurrentEMBlock, pHashAlg.get());
852 posCurrentEMBlock += nIACHPos;
854 wxASSERT( posCurrentEMBlock == Length );
855 wxCHECK2( pShaHashOut->ReCalculateHash(pHashAlg.get(), false), );
858 if (Output != NULL){
859 #ifdef __WEAK_CRYPTO__
860 CryptoPP::Weak::MD4 md4_hasher;
861 #else
862 CryptoPP::MD4 md4_hasher;
863 #endif
864 md4_hasher.CalculateDigest(Output->GetHash(), input, Length);
869 const CMD4Hash& CKnownFile::GetPartHash(uint16 part) const {
870 wxASSERT( part < m_hashlist.size() );
872 return m_hashlist[part];
875 CPacket* CKnownFile::CreateSrcInfoPacket(const CUpDownClient* forClient, uint8 byRequestedVersion, uint16 nRequestedOptions)
877 // Kad reviewed
879 if (m_ClientUploadList.empty()) {
880 return NULL;
883 if ((((CKnownFile*)forClient->GetRequestFile() != this)
884 && ((CKnownFile*)forClient->GetUploadFile() != this)) || forClient->GetUploadFileID() != GetFileHash()) {
885 wxString file1 = _("Unknown");
886 if (forClient->GetRequestFile() && forClient->GetRequestFile()->GetFileName().IsOk()) {
887 file1 = forClient->GetRequestFile()->GetFileName().GetPrintable();
888 } else if (forClient->GetUploadFile() && forClient->GetUploadFile()->GetFileName().IsOk()) {
889 file1 = forClient->GetUploadFile()->GetFileName().GetPrintable();
891 wxString file2 = _("Unknown");
892 if (GetFileName().IsOk()) {
893 file2 = GetFileName().GetPrintable();
895 AddDebugLogLineM(false, logKnownFiles, wxT("File missmatch on source packet (K) Sending: ") + file1 + wxT(" From: ") + file2);
896 return NULL;
899 const BitVector& rcvstatus = forClient->GetUpPartStatus();
900 bool SupportsUploadChunksState = !rcvstatus.empty();
901 //wxASSERT(rcvstatus.size() == GetPartCount()); // Obviously!
902 if (rcvstatus.size() != GetPartCount()) {
903 // Yuck. Same file but different part count? Seriously fucked up.
904 AddDebugLogLineM(false, logKnownFiles, wxString::Format(wxT("Impossible situation: different partcounts for the same known file: %i (client) and %i (file)"),rcvstatus.size(),GetPartCount()));
905 return NULL;
908 CMemFile data(1024);
910 uint8 byUsedVersion;
911 bool bIsSX2Packet;
912 if (forClient->SupportsSourceExchange2() && byRequestedVersion > 0){
913 // the client uses SourceExchange2 and requested the highest version he knows
914 // and we send the highest version we know, but of course not higher than his request
915 byUsedVersion = std::min(byRequestedVersion, (uint8)SOURCEEXCHANGE2_VERSION);
916 bIsSX2Packet = true;
917 data.WriteUInt8(byUsedVersion);
919 // we don't support any special SX2 options yet, reserved for later use
920 if (nRequestedOptions != 0) {
921 AddDebugLogLineM(false, logKnownFiles, CFormat(wxT("Client requested unknown options for SourceExchange2: %u")) % nRequestedOptions);
923 } else {
924 byUsedVersion = forClient->GetSourceExchange1Version();
925 bIsSX2Packet = false;
926 if (forClient->SupportsSourceExchange2()) {
927 AddDebugLogLineM(false, logKnownFiles, wxT("Client which announced to support SX2 sent SX1 packet instead"));
931 uint16 nCount = 0;
933 data.WriteHash(forClient->GetUploadFileID());
934 data.WriteUInt16(nCount);
935 uint32 cDbgNoSrc = 0;
937 SourceSet::iterator it = m_ClientUploadList.begin();
938 for ( ; it != m_ClientUploadList.end(); it++ ) {
939 const CUpDownClient *cur_src = *it;
941 if ( cur_src->HasLowID() ||
942 cur_src == forClient ||
943 !( cur_src->GetUploadState() == US_UPLOADING ||
944 cur_src->GetUploadState() == US_ONUPLOADQUEUE)) {
945 continue;
948 bool bNeeded = false;
950 if ( SupportsUploadChunksState ) {
951 const BitVector& srcstatus = cur_src->GetUpPartStatus();
952 if ( !srcstatus.empty() ) {
953 //wxASSERT(srcstatus.size() == GetPartCount()); // Obviously!
954 if (srcstatus.size() != GetPartCount()) {
955 continue;
957 if ( cur_src->GetUpPartCount() == forClient->GetUpPartCount() ) {
958 for (int x = 0; x < GetPartCount(); x++ ) {
959 if ( srcstatus.at(x) && !rcvstatus.at(x) ) {
960 // We know the receiving client needs
961 // a chunk from this client.
962 bNeeded = true;
963 break;
967 } else {
968 cDbgNoSrc++;
969 // This client doesn't support upload chunk status.
970 // So just send it and hope for the best.
971 bNeeded = true;
973 } else {
974 // remote client does not support upload chunk status,
975 // search sources which have at least one complete part
976 // we could even sort the list of sources by available
977 // chunks to return as much sources as possible which
978 // have the most available chunks. but this could be
979 // a noticeable performance problem.
980 const BitVector& srcstatus = cur_src->GetUpPartStatus();
981 if ( !srcstatus.empty() ) {
982 //wxASSERT(srcstatus.size() == GetPartCount());
983 if (srcstatus.size() != GetPartCount()) {
984 continue;
986 for (int x = 0; x < GetPartCount(); x++ ) {
987 if ( srcstatus.at(x) ) {
988 // this client has at least one chunk
989 bNeeded = true;
990 break;
993 } else {
994 // This client doesn't support upload chunk status.
995 // So just send it and hope for the best.
996 bNeeded = true;
1000 if ( bNeeded ) {
1001 nCount++;
1002 uint32 dwID;
1003 if(byUsedVersion >= 3) {
1004 dwID = cur_src->GetUserIDHybrid();
1005 } else {
1006 dwID = cur_src->GetIP();
1008 data.WriteUInt32(dwID);
1009 data.WriteUInt16(cur_src->GetUserPort());
1010 data.WriteUInt32(cur_src->GetServerIP());
1011 data.WriteUInt16(cur_src->GetServerPort());
1013 if (byUsedVersion >= 2) {
1014 data.WriteHash(cur_src->GetUserHash());
1017 if (byUsedVersion >= 4){
1018 // CryptSettings - SourceExchange V4
1019 // 5 Reserved (!)
1020 // 1 CryptLayer Required
1021 // 1 CryptLayer Requested
1022 // 1 CryptLayer Supported
1023 const uint8 uSupportsCryptLayer = cur_src->SupportsCryptLayer() ? 1 : 0;
1024 const uint8 uRequestsCryptLayer = cur_src->RequestsCryptLayer() ? 1 : 0;
1025 const uint8 uRequiresCryptLayer = cur_src->RequiresCryptLayer() ? 1 : 0;
1026 const uint8 byCryptOptions = (uRequiresCryptLayer << 2) | (uRequestsCryptLayer << 1) | (uSupportsCryptLayer << 0);
1027 data.WriteUInt8(byCryptOptions);
1030 if (nCount > 500) {
1031 break;
1036 if (!nCount) {
1037 return 0;
1040 data.Seek(bIsSX2Packet ? 17 : 16, wxFromStart);
1041 data.WriteUInt16(nCount);
1043 CPacket* result = new CPacket(data, OP_EMULEPROT, bIsSX2Packet ? OP_ANSWERSOURCES2 : OP_ANSWERSOURCES);
1045 if ( result->GetPacketSize() > 354 ) {
1046 result->PackPacket();
1049 return result;
1053 // Updates priority of file if autopriority is activated
1054 void CKnownFile::UpdateAutoUpPriority()
1056 if (IsAutoUpPriority()) {
1057 uint32 queued = GetQueuedCount();
1058 uint8 priority = PR_NORMAL;
1060 if (queued > 20) {
1061 priority = PR_LOW;
1062 } else if (queued > 1) {
1063 priority = PR_NORMAL;
1064 } else {
1065 priority = PR_HIGH;
1068 if (GetUpPriority() != priority) {
1069 SetUpPriority(priority, false);
1070 Notify_SharedFilesUpdateItem(this);
1075 void CKnownFile::SetFileComment(const wxString& strNewComment)
1077 if (m_strComment != strNewComment) {
1078 SetLastPublishTimeKadNotes(0);
1079 wxString strCfgPath = wxT("/") + m_abyFileHash.Encode() + wxT("/");
1081 wxConfigBase* cfg = wxConfigBase::Get();
1082 cfg->Write( strCfgPath + wxT("Comment"), strNewComment);
1084 m_strComment = strNewComment;
1086 SourceSet::iterator it = m_ClientUploadList.begin();
1087 for ( ; it != m_ClientUploadList.end(); it++ ) {
1088 (*it)->SetCommentDirty();
1094 // For File rate
1095 void CKnownFile::SetFileRating(int8 iNewRating)
1097 if (m_iRating != iNewRating) {
1098 SetLastPublishTimeKadNotes(0);
1099 wxString strCfgPath = wxT("/") + m_abyFileHash.Encode() + wxT("/");
1100 wxConfigBase* cfg = wxConfigBase::Get();
1101 cfg->Write( strCfgPath + wxT("Rate"), iNewRating);
1102 m_iRating = iNewRating;
1104 SourceSet::iterator it = m_ClientUploadList.begin();
1105 for ( ; it != m_ClientUploadList.end(); it++ ) {
1106 (*it)->SetCommentDirty();
1112 void CKnownFile::SetUpPriority(uint8 iNewUpPriority, bool m_bsave){
1113 m_iUpPriority = iNewUpPriority;
1114 if( IsPartFile() && m_bsave ) {
1115 ((CPartFile*)this)->SavePartFile();
1119 void CKnownFile::SetPublishedED2K(bool val){
1120 m_PublishedED2K = val;
1121 Notify_SharedFilesUpdateItem(this);
1124 bool CKnownFile::PublishNotes()
1126 if(m_lastPublishTimeKadNotes > (uint32)time(NULL)) {
1127 return false;
1130 if(!GetFileComment().IsEmpty()) {
1131 m_lastPublishTimeKadNotes = (uint32)time(NULL)+KADEMLIAREPUBLISHTIMEN;
1132 return true;
1135 if(GetFileRating() != 0) {
1136 m_lastPublishTimeKadNotes = (uint32)time(NULL)+KADEMLIAREPUBLISHTIMEN;
1137 return true;
1140 return false;
1143 bool CKnownFile::PublishSrc()
1145 uint32 lastBuddyIP = 0;
1147 if( theApp->IsFirewalled() ) {
1148 CUpDownClient* buddy = theApp->clientlist->GetBuddy();
1149 if( buddy ) {
1150 lastBuddyIP = theApp->clientlist->GetBuddy()->GetIP();
1151 if( lastBuddyIP != m_lastBuddyIP ) {
1152 SetLastPublishTimeKadSrc( (uint32)time(NULL)+KADEMLIAREPUBLISHTIMES, lastBuddyIP );
1153 return true;
1155 } else {
1156 return false;
1160 if(m_lastPublishTimeKadSrc > (uint32)time(NULL)) {
1161 return false;
1164 SetLastPublishTimeKadSrc((uint32)time(NULL)+KADEMLIAREPUBLISHTIMES,lastBuddyIP);
1165 return true;
1169 void CKnownFile::UpdatePartsInfo()
1171 // Cache part count
1172 uint16 partcount = GetPartCount();
1173 bool flag = (time(NULL) - m_nCompleteSourcesTime > 0);
1175 // Ensure the frequency-list is ready
1176 if ( m_AvailPartFrequency.size() != GetPartCount() ) {
1177 m_AvailPartFrequency.clear();
1178 m_AvailPartFrequency.insert(m_AvailPartFrequency.begin(), GetPartCount(), 0);
1181 if (flag) {
1182 ArrayOfUInts16 count;
1183 count.reserve(m_ClientUploadList.size());
1185 SourceSet::iterator it = m_ClientUploadList.begin();
1186 for ( ; it != m_ClientUploadList.end(); it++ ) {
1187 if ( !(*it)->GetUpPartStatus().empty() && (*it)->GetUpPartCount() == partcount ) {
1188 count.push_back((*it)->GetUpCompleteSourcesCount());
1192 m_nCompleteSourcesCount = m_nCompleteSourcesCountLo = m_nCompleteSourcesCountHi = 0;
1194 if( partcount > 0) {
1195 m_nCompleteSourcesCount = m_AvailPartFrequency[0];
1197 for (uint16 i = 1; i < partcount; ++i) {
1198 if( m_nCompleteSourcesCount > m_AvailPartFrequency[i]) {
1199 m_nCompleteSourcesCount = m_AvailPartFrequency[i];
1202 count.push_back(m_nCompleteSourcesCount);
1204 int32 n = count.size();
1205 if (n > 0) {
1206 std::sort(count.begin(), count.end(), std::less<uint16>());
1208 // calculate range
1209 int i = n >> 1; // (n / 2)
1210 int j = (n * 3) >> 2; // (n * 3) / 4
1211 int k = (n * 7) >> 3; // (n * 7) / 8
1213 // For complete files, trust the people your uploading to more...
1215 // For low guess and normal guess count
1216 // - If we see more sources then the guessed low and
1217 // normal, use what we see.
1218 // - If we see less sources then the guessed low,
1219 // adjust network accounts for 100%, we account for
1220 // 0% with what we see and make sure we are still
1221 // above the normal.
1222 // For high guess
1223 // Adjust 100% network and 0% what we see.
1224 if (n < 20) {
1225 if ( count[i] < m_nCompleteSourcesCount ) {
1226 m_nCompleteSourcesCountLo = m_nCompleteSourcesCount;
1227 } else {
1228 m_nCompleteSourcesCountLo = count[i];
1230 m_nCompleteSourcesCount= m_nCompleteSourcesCountLo;
1231 m_nCompleteSourcesCountHi = count[j];
1232 if( m_nCompleteSourcesCountHi < m_nCompleteSourcesCount ) {
1233 m_nCompleteSourcesCountHi = m_nCompleteSourcesCount;
1235 } else {
1236 // Many sources..
1237 // For low guess
1238 // Use what we see.
1239 // For normal guess
1240 // Adjust network accounts for 100%, we account for
1241 // 0% with what we see and make sure we are still above the low.
1242 // For high guess
1243 // Adjust network accounts for 100%, we account for 0%
1244 // with what we see and make sure we are still above the normal.
1246 m_nCompleteSourcesCountLo = m_nCompleteSourcesCount;
1247 m_nCompleteSourcesCount = count[j];
1248 if( m_nCompleteSourcesCount < m_nCompleteSourcesCountLo ) {
1249 m_nCompleteSourcesCount = m_nCompleteSourcesCountLo;
1251 m_nCompleteSourcesCountHi= count[k];
1252 if( m_nCompleteSourcesCountHi < m_nCompleteSourcesCount ) {
1253 m_nCompleteSourcesCountHi = m_nCompleteSourcesCount;
1257 m_nCompleteSourcesTime = time(NULL) + (60);
1260 Notify_SharedFilesUpdateItem(this);
1264 void CKnownFile::UpdateUpPartsFrequency( CUpDownClient* client, bool increment )
1266 if ( m_AvailPartFrequency.size() != GetPartCount() ) {
1267 m_AvailPartFrequency.clear();
1268 m_AvailPartFrequency.insert(m_AvailPartFrequency.begin(), GetPartCount(), 0);
1269 if ( !increment ) {
1270 return;
1274 const BitVector& freq = client->GetUpPartStatus();
1275 unsigned int size = freq.size();
1276 if ( size != m_AvailPartFrequency.size() ) {
1277 return;
1280 if ( increment ) {
1281 for ( unsigned int i = 0; i < size; ++i ) {
1282 if ( freq[i] ) {
1283 m_AvailPartFrequency[i]++;
1286 } else {
1287 for ( unsigned int i = 0; i < size; ++i ) {
1288 if ( freq[i] ) {
1289 m_AvailPartFrequency[i]--;
1295 void CKnownFile::ClearPriority() {
1296 if ( !m_bAutoUpPriority ) return;
1297 m_iUpPriority = ( m_bAutoUpPriority ) ? PR_HIGH : PR_NORMAL;
1298 UpdateAutoUpPriority();
1301 void CKnownFile::SetFileName(const CPath& filename)
1303 CAbstractFile::SetFileName(filename);
1304 #ifndef CLIENT_GUI
1305 wordlist.clear();
1306 Kademlia::CSearchManager::GetWords(GetFileName().GetPrintable(), &wordlist);
1307 #endif
1310 #endif // CLIENT_GUI
1312 //For File Comment //
1313 void CKnownFile::LoadComment()
1315 #ifndef CLIENT_GUI
1316 wxString strCfgPath = wxT("/") + m_abyFileHash.Encode() + wxT("/");
1318 wxConfigBase* cfg = wxConfigBase::Get();
1320 m_strComment = cfg->Read( strCfgPath + wxT("Comment"), wxEmptyString);
1321 m_iRating = cfg->Read( strCfgPath + wxT("Rate"), 0l);
1322 m_bCommentLoaded = true;
1324 #else
1325 m_strComment = wxT("Comments are not allowed on remote gui yet");
1326 m_bCommentLoaded = true;
1327 m_iRating =0;
1328 #endif
1333 wxString CKnownFile::GetAICHMasterHash() const
1335 #ifdef CLIENT_GUI
1336 return m_AICHMasterHash;
1337 #else
1338 if (HasProperAICHHashSet()) {
1339 return m_pAICHHashSet->GetMasterHash().GetString();
1342 return wxEmptyString;
1343 #endif
1347 bool CKnownFile::HasProperAICHHashSet() const
1349 #ifdef CLIENT_GUI
1350 return m_AICHMasterHash.Length();
1351 #else
1352 return m_pAICHHashSet->HasValidMasterHash() &&
1353 (m_pAICHHashSet->GetStatus() == AICH_HASHSETCOMPLETE ||
1354 m_pAICHHashSet->GetStatus() == AICH_VERIFIED);
1355 #endif
1358 // File_checked_for_headers