Upstream tarball 10110
[amule.git] / src / KnownFile.cpp
blob71b64e49f7edb4000fac861c4409944e2a47fbd9
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-2008 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
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() :
61 requested(0),
62 transferred(0),
63 accepted(0),
64 alltimerequested(0),
65 alltimetransferred(0),
66 alltimeaccepted(0)
70 #ifndef CLIENT_GUI
72 void CFileStatistic::AddRequest(){
73 requested++;
74 alltimerequested++;
75 theApp->knownfiles->requested++;
76 theApp->sharedfiles->UpdateItem(fileParent);
79 void CFileStatistic::AddAccepted(){
80 accepted++;
81 alltimeaccepted++;
82 theApp->knownfiles->accepted++;
83 theApp->sharedfiles->UpdateItem(fileParent);
86 void CFileStatistic::AddTransferred(uint64 bytes){
87 transferred += bytes;
88 alltimetransferred += bytes;
89 theApp->knownfiles->transferred += bytes;
90 theApp->sharedfiles->UpdateItem(fileParent);
93 #endif // CLIENT_GUI
96 /* Abstract File (base class)*/
98 CAbstractFile::CAbstractFile()
100 m_iRating(0),
101 m_hasComment(false),
102 m_iUserRating(0),
103 m_nFileSize(0)
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();
141 return 0;
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();
150 return true;
153 return false;
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();
164 return 0;
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();
175 return EmptyString;
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();
186 return EmptyString;
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) {
194 return &(*it);
197 return NULL;
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) {
205 return &(*it);
208 return NULL;
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) {
216 return &(*it);
219 return NULL;
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) {
227 return &(*it);
230 return NULL;
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()){
243 m_taglist.erase(it);
244 m_taglist.insert(it, rTag);
245 return;
248 m_taglist.push_back(rTag);
251 #ifndef CLIENT_GUI
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) {
258 delete pEntry;
259 return;
262 m_kadNotes.push_front(pEntry);
264 #else
265 void CAbstractFile::AddNote(Kademlia::CEntry *)
268 #endif
271 /* Known File */
273 CKnownFile::CKnownFile()
275 Init();
278 CKnownFile::CKnownFile(uint32 ecid) : CECID(ecid)
280 Init();
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))
290 Init();
292 // Use CKnownFile::SetFileName()
293 SetFileName(searchFile.GetFileName());
295 // Use CKnownFile::SetFileSize()
296 SetFileSize(searchFile.GetFileSize());
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;
316 m_bAutoUpPriority = thePrefs::GetNewAutoUp();
317 m_iUpPriority = ( m_bAutoUpPriority ) ? PR_HIGH : PR_NORMAL;
319 statistic.fileParent = this;
321 #ifndef CLIENT_GUI
322 m_pAICHHashSet = new CAICHHashSet(this);
323 #endif
327 void CKnownFile::SetFileSize(uint64 nFileSize)
329 CAbstractFile::SetFileSize(nFileSize);
330 #ifndef CLIENT_GUI
331 m_pAICHHashSet->SetFileSize(nFileSize);
332 #endif
334 // Examples of parthashs, hashsets and filehashs for different filesizes
335 // according the ed2k protocol
336 //----------------------------------------------------------------------
338 //File size: 3 bytes
339 //File hash: 2D55E87D0E21F49B9AD25F98531F3724
340 //Nr. hashs: 0
343 //File size: 1*PARTSIZE
344 //File hash: A72CA8DF7F07154E217C236C89C17619
345 //Nr. hashs: 2
346 //Hash[ 0]: 4891ED2E5C9C49F442145A3A5F608299
347 //Hash[ 1]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
350 //File size: 1*PARTSIZE + 1 byte
351 //File hash: 2F620AE9D462CBB6A59FE8401D2B3D23
352 //Nr. hashs: 2
353 //Hash[ 0]: 121795F0BEDE02DDC7C5426D0995F53F
354 //Hash[ 1]: C329E527945B8FE75B3C5E8826755747
357 //File size: 2*PARTSIZE
358 //File hash: A54C5E562D5E03CA7D77961EB9A745A4
359 //Nr. hashs: 3
360 //Hash[ 0]: B3F5CE2A06BF403BFB9BFFF68BDDC4D9
361 //Hash[ 1]: 509AA30C9EA8FC136B1159DF2F35B8A9
362 //Hash[ 2]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
365 //File size: 3*PARTSIZE
366 //File hash: 5E249B96F9A46A18FC2489B005BF2667
367 //Nr. hashs: 4
368 //Hash[ 0]: 5319896A2ECAD43BF17E2E3575278E72
369 //Hash[ 1]: D86EF157D5E49C5ED502EDC15BB5F82B
370 //Hash[ 2]: 10F2D5B1FCB95C0840519C58D708480F
371 //Hash[ 3]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
374 //File size: 3*PARTSIZE + 1 byte
375 //File hash: 797ED552F34380CAFF8C958207E40355
376 //Nr. hashs: 4
377 //Hash[ 0]: FC7FD02CCD6987DCF1421F4C0AF94FB8
378 //Hash[ 1]: 2FE466AF8A7C06DA3365317B75A5ACFE
379 //Hash[ 2]: 873D3BF52629F7C1527C6E8E473C1C30
380 //Hash[ 3]: BCE50BEE7877BB07BB6FDA56BFE142FB
383 // File size Data parts ED2K parts ED2K part hashs
384 // ---------------------------------------------------------------
385 // 1..PARTSIZE-1 1 1 0(!)
386 // PARTSIZE 1 2(!) 2(!)
387 // PARTSIZE+1 2 2 2
388 // PARTSIZE*2 2 3(!) 3(!)
389 // PARTSIZE*2+1 3 3 3
391 if (nFileSize == 0){
392 //wxFAIL; // Kry - Why commented out by lemonfan? it can never be 0
393 m_iPartCount = 0;
394 m_iED2KPartCount = 0;
395 m_iED2KPartHashCount = 0;
396 m_sizeLastPart = 0;
397 return;
400 // nr. of data parts
401 m_iPartCount = nFileSize / PARTSIZE + 1;
402 // size of last part
403 m_sizeLastPart = nFileSize % PARTSIZE;
404 // file with size of n * PARTSIZE
405 if (m_sizeLastPart == 0) {
406 m_sizeLastPart = PARTSIZE;
407 m_iPartCount--;
410 // nr. of parts to be used with OP_FILESTATUS
411 m_iED2KPartCount = nFileSize / PARTSIZE + 1;
413 // nr. of parts to be used with OP_HASHSETANSWER
414 m_iED2KPartHashCount = nFileSize / PARTSIZE;
415 if (m_iED2KPartHashCount != 0) {
416 m_iED2KPartHashCount += 1;
421 #ifdef CLIENT_GUI
423 CKnownFile::CKnownFile(CEC_SharedFile_Tag *tag) : CECID(tag->ID())
425 Init();
427 SetFileName(CPath(tag->FileName()));
428 m_abyFileHash = tag->FileHash();
429 SetFileSize(tag->SizeFull());
430 m_AvailPartFrequency.insert(m_AvailPartFrequency.end(), m_iPartCount, 0);
431 m_iUpPriorityEC = tag->UpPrio();
432 m_AICHMasterHash = tag->GetAICHHash();
433 m_filePath = CPath(tag->FilePath());
434 m_queuedCount = 0;
437 CKnownFile::~CKnownFile()
441 #else // ! CLIENT_GUI
443 CKnownFile::~CKnownFile()
445 SourceSet::iterator it = m_ClientUploadList.begin();
446 for ( ; it != m_ClientUploadList.end(); ++it ) {
447 (*it)->ClearUploadFileID();
450 delete m_pAICHHashSet;
453 void CKnownFile::AddUploadingClient(CUpDownClient* client)
455 m_ClientUploadList.insert(client);
457 UpdateAutoUpPriority();
461 void CKnownFile::RemoveUploadingClient(CUpDownClient* client)
463 if (m_ClientUploadList.erase(client)) {
464 UpdateAutoUpPriority();
469 void CKnownFile::SetFilePath(const CPath& filePath)
471 m_filePath = filePath;
475 // needed for memfiles. its probably better to switch everything to CFile...
476 bool CKnownFile::LoadHashsetFromFile(const CFileDataIO* file, bool checkhash)
478 CMD4Hash checkid = file->ReadHash();
480 uint16 parts = file->ReadUInt16();
481 for (uint16 i = 0; i < parts; ++i){
482 CMD4Hash cur_hash = file->ReadHash();
483 m_hashlist.push_back(cur_hash);
486 // SLUGFILLER: SafeHash - always check for valid m_hashlist
487 if (!checkhash){
488 m_abyFileHash = checkid;
489 if (parts <= 1) { // nothing to check
490 return true;
492 } else {
493 if ( m_abyFileHash != checkid ) {
494 return false; // wrong file?
495 } else {
496 if (parts != GetED2KPartHashCount()) {
497 return false;
501 // SLUGFILLER: SafeHash
503 // trust noone ;-)
504 // lol, useless comment but made me lmao
505 // wtf you guys are weird.
507 if (!m_hashlist.empty()) {
508 CreateHashFromHashlist(m_hashlist, &checkid);
511 if ( m_abyFileHash == checkid ) {
512 return true;
513 } else {
514 m_hashlist.clear();
515 return false;
520 bool CKnownFile::LoadTagsFromFile(const CFileDataIO* file)
522 uint32 tagcount = file->ReadUInt32();
523 for (uint32 j = 0; j != tagcount; ++j) {
524 CTag newtag(*file, true);
525 switch(newtag.GetNameID()){
526 case FT_FILENAME:
527 if (GetFileName().IsOk()) {
528 // Unlike eMule, we actually prefer the second
529 // filename tag, since we use it to specify the
530 // 'universial' filename (see CPath::ToUniv).
531 CPath path = CPath::FromUniv(newtag.GetStr());
533 // May be invalid, if from older versions where
534 // unicoded filenames be saved as empty-strings.
535 if (path.IsOk()) {
536 SetFileName(path);
538 } else {
539 SetFileName(CPath(newtag.GetStr()));
541 break;
543 case FT_FILESIZE:
544 SetFileSize(newtag.GetInt());
545 m_AvailPartFrequency.clear();
546 m_AvailPartFrequency.insert(
547 m_AvailPartFrequency.begin(),
548 GetPartCount(), 0);
549 break;
551 case FT_ATTRANSFERRED:
552 statistic.alltimetransferred += newtag.GetInt();
553 break;
555 case FT_ATTRANSFERREDHI:
556 statistic.alltimetransferred =
557 (((uint64)newtag.GetInt()) << 32) +
558 ((uint64)statistic.alltimetransferred);
559 break;
561 case FT_ATREQUESTED:
562 statistic.alltimerequested = newtag.GetInt();
563 break;
565 case FT_ATACCEPTED:
566 statistic.alltimeaccepted = newtag.GetInt();
567 break;
569 case FT_ULPRIORITY:
570 m_iUpPriority = newtag.GetInt();
571 if( m_iUpPriority == PR_AUTO ){
572 m_iUpPriority = PR_HIGH;
573 m_bAutoUpPriority = true;
574 } else {
575 if ( m_iUpPriority != PR_VERYLOW &&
576 m_iUpPriority != PR_LOW &&
577 m_iUpPriority != PR_NORMAL &&
578 m_iUpPriority != PR_HIGH &&
579 m_iUpPriority != PR_VERYHIGH &&
580 m_iUpPriority != PR_POWERSHARE) {
581 m_iUpPriority = PR_NORMAL;
584 m_bAutoUpPriority = false;
586 break;
588 case FT_PERMISSIONS:
589 // Ignore it, it's not used anymore.
590 break;
592 case FT_AICH_HASH: {
593 CAICHHash hash;
594 bool hashSizeOk =
595 hash.DecodeBase32(newtag.GetStr()) == CAICHHash::GetHashSize();
596 wxASSERT(hashSizeOk);
597 if (hashSizeOk) {
598 m_pAICHHashSet->SetMasterHash(hash, AICH_HASHSETCOMPLETE);
600 break;
603 case FT_KADLASTPUBLISHSRC:
604 SetLastPublishTimeKadSrc( newtag.GetInt(), 0 );
606 if(GetLastPublishTimeKadSrc() > (uint32)time(NULL)+KADEMLIAREPUBLISHTIMES) {
607 //There may be a posibility of an older client that saved a random number here.. This will check for that..
608 SetLastPublishTimeKadSrc(0, 0);
610 break;
612 case FT_KADLASTPUBLISHNOTES:
613 SetLastPublishTimeKadNotes( newtag.GetInt() );
614 break;
616 case FT_KADLASTPUBLISHKEY:
617 // Just purge it
618 wxASSERT( newtag.IsInt() );
619 break;
621 default:
622 // Store them here and write them back on saving.
623 m_taglist.push_back(newtag);
627 return true;
631 bool CKnownFile::LoadDateFromFile(const CFileDataIO* file)
633 m_lastDateChanged = file->ReadUInt32();
635 return true;
639 bool CKnownFile::LoadFromFile(const CFileDataIO* file)
641 // SLUGFILLER: SafeHash - load first, verify later
642 bool ret1 = LoadDateFromFile(file);
643 bool ret2 = LoadHashsetFromFile(file,false);
644 bool ret3 = LoadTagsFromFile(file);
645 UpdatePartsInfo();
646 // Final hash-count verification, needs to be done after the tags are loaded.
647 return ret1 && ret2 && ret3 && GetED2KPartHashCount()==GetHashCount();
648 // SLUGFILLER: SafeHash
652 bool CKnownFile::WriteToFile(CFileDataIO* file)
654 wxCHECK(!IsPartFile(), false);
656 // date
657 file->WriteUInt32(m_lastDateChanged);
658 // hashset
659 file->WriteHash(m_abyFileHash);
661 uint16 parts = m_hashlist.size();
662 file->WriteUInt16(parts);
664 for (int i = 0; i < parts; ++i)
665 file->WriteHash(m_hashlist[i]);
667 //tags
668 const int iFixedTags = 8;
669 uint32 tagcount = iFixedTags;
670 if (HasProperAICHHashSet()) {
671 tagcount++;
673 // Float meta tags are currently not written. All older eMule versions < 0.28a have
674 // a bug in the meta tag reading+writing code. To achive maximum backward
675 // compatibility for met files with older eMule versions we just don't write float
676 // tags. This is OK, because we (eMule) do not use float tags. The only float tags
677 // we may have to handle is the '# Sent' tag from the Hybrid, which is pretty
678 // useless but may be received from us via the servers.
680 // The code for writing the float tags SHOULD BE ENABLED in SOME MONTHS (after most
681 // people are using the newer eMule versions which do not write broken float tags).
682 for (size_t j = 0; j < m_taglist.size(); ++j){
683 if (m_taglist[j].IsInt() || m_taglist[j].IsStr()) {
684 ++tagcount;
688 if (m_lastPublishTimeKadSrc) {
689 ++tagcount;
692 if (m_lastPublishTimeKadNotes){
693 ++tagcount;
696 // standard tags
698 file->WriteUInt32(tagcount);
700 // We still save the unicoded filename, for backwards
701 // compatibility with pre-2.2 and other clients.
702 CTagString nametag_unicode(FT_FILENAME, GetFileName().GetRaw());
703 // We write it with BOM to kep eMule compatibility
704 nametag_unicode.WriteTagToFile(file,utf8strOptBOM);
706 // The non-unicoded filename is written in an 'universial'
707 // format, which allows us to identify files, even if the
708 // system locale changes.
709 CTagString nametag(FT_FILENAME, CPath::ToUniv(GetFileName()));
710 nametag.WriteTagToFile(file);
712 CTagIntSized sizetag(FT_FILESIZE, GetFileSize(), IsLargeFile() ? 64 : 32);
713 sizetag.WriteTagToFile(file);
715 // statistic
716 uint32 tran;
717 tran=statistic.alltimetransferred & 0xFFFFFFFF;
718 CTagInt32 attag1(FT_ATTRANSFERRED, tran);
719 attag1.WriteTagToFile(file);
721 tran=statistic.alltimetransferred>>32;
722 CTagInt32 attag4(FT_ATTRANSFERREDHI, tran);
723 attag4.WriteTagToFile(file);
725 CTagInt32 attag2(FT_ATREQUESTED, statistic.GetAllTimeRequests());
726 attag2.WriteTagToFile(file);
728 CTagInt32 attag3(FT_ATACCEPTED, statistic.GetAllTimeAccepts());
729 attag3.WriteTagToFile(file);
731 // priority N permission
732 CTagInt32 priotag(FT_ULPRIORITY, IsAutoUpPriority() ? PR_AUTO : m_iUpPriority);
733 priotag.WriteTagToFile(file);
735 //AICH Filehash
736 if (HasProperAICHHashSet()) {
737 CTagString aichtag(FT_AICH_HASH, m_pAICHHashSet->GetMasterHash().GetString());
738 aichtag.WriteTagToFile(file);
741 // Kad sources
742 if (m_lastPublishTimeKadSrc){
743 CTagInt32 kadLastPubSrc(FT_KADLASTPUBLISHSRC, m_lastPublishTimeKadSrc);
744 kadLastPubSrc.WriteTagToFile(file);
747 // Kad notes
748 if (m_lastPublishTimeKadNotes){
749 CTagInt32 kadLastPubNotes(FT_KADLASTPUBLISHNOTES, m_lastPublishTimeKadNotes);
750 kadLastPubNotes.WriteTagToFile(file);
753 //other tags
754 for (size_t j = 0; j < m_taglist.size(); ++j){
755 if (m_taglist[j].IsInt() || m_taglist[j].IsStr()) {
756 m_taglist[j].WriteTagToFile(file);
759 return true;
763 void CKnownFile::CreateHashFromHashlist(const ArrayOfCMD4Hash& hashes, CMD4Hash* Output)
765 wxCHECK_RET(hashes.size(), wxT("No input to hash from in CreateHashFromHashlist"));
767 std::vector<byte> buffer(hashes.size() * MD4HASH_LENGTH);
768 std::vector<byte>::iterator it = buffer.begin();
770 for (size_t i = 0; i < hashes.size(); ++i) {
771 it = STLCopy_n(hashes[i].GetHash(), MD4HASH_LENGTH, it);
774 CreateHashFromInput(&buffer[0], buffer.size(), Output, NULL);
778 void CKnownFile::CreateHashFromFile(CFileAutoClose& file, uint64 offset, uint32 Length, CMD4Hash* Output, CAICHHashTree* pShaHashOut)
780 wxCHECK_RET(Length, wxT("No input to hash from in CreateHashFromFile"));
782 CFileArea area;
783 area.ReadAt(file, offset, Length);
785 CreateHashFromInput(area.GetBuffer(), Length, Output, pShaHashOut);
786 area.CheckError();
790 void CKnownFile::CreateHashFromInput(const byte* input, uint32 Length, CMD4Hash* Output, CAICHHashTree* pShaHashOut )
792 wxASSERT_MSG(Output || pShaHashOut, wxT("Nothing to do in CreateHashFromInput"));
793 wxCHECK_RET(input, wxT("No input to hash from in CreateHashFromInput"));
794 wxASSERT(Length <= PARTSIZE); // We never hash more than one PARTSIZE
796 CMemFile data(input, Length);
798 uint32 Required = Length;
799 byte X[64*128];
801 uint32 posCurrentEMBlock = 0;
802 uint32 nIACHPos = 0;
803 CScopedPtr<CAICHHashAlgo> pHashAlg(CAICHHashSet::GetNewHashAlgo());
805 // This is all AICH.
806 while (Required >= 64) {
807 uint32 len = Required / 64;
808 if (len > sizeof(X)/(64 * sizeof(X[0]))) {
809 len = sizeof(X)/(64 * sizeof(X[0]));
812 data.Read(&X, len * 64);
814 // SHA hash needs 180KB blocks
815 if (pShaHashOut) {
816 if (nIACHPos + len*64 >= EMBLOCKSIZE) {
817 uint32 nToComplete = EMBLOCKSIZE - nIACHPos;
818 pHashAlg->Add(X, nToComplete);
819 wxASSERT( nIACHPos + nToComplete == EMBLOCKSIZE );
820 pShaHashOut->SetBlockHash(EMBLOCKSIZE, posCurrentEMBlock, pHashAlg.get());
821 posCurrentEMBlock += EMBLOCKSIZE;
822 pHashAlg->Reset();
823 pHashAlg->Add(X+nToComplete,(len*64) - nToComplete);
824 nIACHPos = (len*64) - nToComplete;
826 else{
827 pHashAlg->Add(X, len*64);
828 nIACHPos += len*64;
832 Required -= len*64;
834 // bytes to read
835 Required = Length % 64;
836 if (Required != 0){
837 data.Read(&X,Required);
839 if (pShaHashOut != NULL){
840 if (nIACHPos + Required >= EMBLOCKSIZE){
841 uint32 nToComplete = EMBLOCKSIZE - nIACHPos;
842 pHashAlg->Add(X, nToComplete);
843 wxASSERT( nIACHPos + nToComplete == EMBLOCKSIZE );
844 pShaHashOut->SetBlockHash(EMBLOCKSIZE, posCurrentEMBlock, pHashAlg.get());
845 posCurrentEMBlock += EMBLOCKSIZE;
846 pHashAlg->Reset();
847 pHashAlg->Add(X+nToComplete, Required - nToComplete);
848 nIACHPos = Required - nToComplete;
850 else{
851 pHashAlg->Add(X, Required);
852 nIACHPos += Required;
856 if (pShaHashOut != NULL){
857 if(nIACHPos > 0){
858 pShaHashOut->SetBlockHash(nIACHPos, posCurrentEMBlock, pHashAlg.get());
859 posCurrentEMBlock += nIACHPos;
861 wxASSERT( posCurrentEMBlock == Length );
862 wxCHECK2( pShaHashOut->ReCalculateHash(pHashAlg.get(), false), );
865 if (Output != NULL){
866 #ifdef __WEAK_CRYPTO__
867 CryptoPP::Weak::MD4 md4_hasher;
868 #else
869 CryptoPP::MD4 md4_hasher;
870 #endif
871 md4_hasher.CalculateDigest(Output->GetHash(), input, Length);
876 const CMD4Hash& CKnownFile::GetPartHash(uint16 part) const {
877 wxASSERT( part < m_hashlist.size() );
879 return m_hashlist[part];
882 CPacket* CKnownFile::CreateSrcInfoPacket(const CUpDownClient* forClient, uint8 byRequestedVersion, uint16 nRequestedOptions)
884 // Kad reviewed
886 if (m_ClientUploadList.empty()) {
887 return NULL;
890 if ((((CKnownFile*)forClient->GetRequestFile() != this)
891 && ((CKnownFile*)forClient->GetUploadFile() != this)) || forClient->GetUploadFileID() != GetFileHash()) {
892 wxString file1 = _("Unknown");
893 if (forClient->GetRequestFile() && forClient->GetRequestFile()->GetFileName().IsOk()) {
894 file1 = forClient->GetRequestFile()->GetFileName().GetPrintable();
895 } else if (forClient->GetUploadFile() && forClient->GetUploadFile()->GetFileName().IsOk()) {
896 file1 = forClient->GetUploadFile()->GetFileName().GetPrintable();
898 wxString file2 = _("Unknown");
899 if (GetFileName().IsOk()) {
900 file2 = GetFileName().GetPrintable();
902 AddDebugLogLineM(false, logKnownFiles, wxT("File missmatch on source packet (K) Sending: ") + file1 + wxT(" From: ") + file2);
903 return NULL;
906 const BitVector& rcvstatus = forClient->GetUpPartStatus();
907 bool SupportsUploadChunksState = !rcvstatus.empty();
908 //wxASSERT(rcvstatus.size() == GetPartCount()); // Obviously!
909 if (rcvstatus.size() != GetPartCount()) {
910 // Yuck. Same file but different part count? Seriously fucked up.
911 AddDebugLogLineM(false, logKnownFiles, CFormat(wxT("Impossible situation: different partcounts for the same known file: %i (client) and %i (file)")) % rcvstatus.size() % GetPartCount());
912 return NULL;
915 CMemFile data(1024);
917 uint8 byUsedVersion;
918 bool bIsSX2Packet;
919 if (forClient->SupportsSourceExchange2() && byRequestedVersion > 0){
920 // the client uses SourceExchange2 and requested the highest version he knows
921 // and we send the highest version we know, but of course not higher than his request
922 byUsedVersion = std::min(byRequestedVersion, (uint8)SOURCEEXCHANGE2_VERSION);
923 bIsSX2Packet = true;
924 data.WriteUInt8(byUsedVersion);
926 // we don't support any special SX2 options yet, reserved for later use
927 if (nRequestedOptions != 0) {
928 AddDebugLogLineM(false, logKnownFiles, CFormat(wxT("Client requested unknown options for SourceExchange2: %u")) % nRequestedOptions);
930 } else {
931 byUsedVersion = forClient->GetSourceExchange1Version();
932 bIsSX2Packet = false;
933 if (forClient->SupportsSourceExchange2()) {
934 AddDebugLogLineM(false, logKnownFiles, wxT("Client which announced to support SX2 sent SX1 packet instead"));
938 uint16 nCount = 0;
940 data.WriteHash(forClient->GetUploadFileID());
941 data.WriteUInt16(nCount);
942 uint32 cDbgNoSrc = 0;
944 SourceSet::iterator it = m_ClientUploadList.begin();
945 for ( ; it != m_ClientUploadList.end(); it++ ) {
946 const CUpDownClient *cur_src = *it;
948 if ( cur_src->HasLowID() ||
949 cur_src == forClient ||
950 !( cur_src->GetUploadState() == US_UPLOADING ||
951 cur_src->GetUploadState() == US_ONUPLOADQUEUE)) {
952 continue;
955 bool bNeeded = false;
957 if ( SupportsUploadChunksState ) {
958 const BitVector& srcstatus = cur_src->GetUpPartStatus();
959 if ( !srcstatus.empty() ) {
960 //wxASSERT(srcstatus.size() == GetPartCount()); // Obviously!
961 if (srcstatus.size() != GetPartCount()) {
962 continue;
964 if ( cur_src->GetUpPartCount() == forClient->GetUpPartCount() ) {
965 for (int x = 0; x < GetPartCount(); x++ ) {
966 if ( srcstatus.at(x) && !rcvstatus.at(x) ) {
967 // We know the receiving client needs
968 // a chunk from this client.
969 bNeeded = true;
970 break;
974 } else {
975 cDbgNoSrc++;
976 // This client doesn't support upload chunk status.
977 // So just send it and hope for the best.
978 bNeeded = true;
980 } else {
981 // remote client does not support upload chunk status,
982 // search sources which have at least one complete part
983 // we could even sort the list of sources by available
984 // chunks to return as much sources as possible which
985 // have the most available chunks. but this could be
986 // a noticeable performance problem.
987 const BitVector& srcstatus = cur_src->GetUpPartStatus();
988 if ( !srcstatus.empty() ) {
989 //wxASSERT(srcstatus.size() == GetPartCount());
990 if (srcstatus.size() != GetPartCount()) {
991 continue;
993 for (int x = 0; x < GetPartCount(); x++ ) {
994 if ( srcstatus.at(x) ) {
995 // this client has at least one chunk
996 bNeeded = true;
997 break;
1000 } else {
1001 // This client doesn't support upload chunk status.
1002 // So just send it and hope for the best.
1003 bNeeded = true;
1007 if ( bNeeded ) {
1008 nCount++;
1009 uint32 dwID;
1010 if(byUsedVersion >= 3) {
1011 dwID = cur_src->GetUserIDHybrid();
1012 } else {
1013 dwID = cur_src->GetIP();
1015 data.WriteUInt32(dwID);
1016 data.WriteUInt16(cur_src->GetUserPort());
1017 data.WriteUInt32(cur_src->GetServerIP());
1018 data.WriteUInt16(cur_src->GetServerPort());
1020 if (byUsedVersion >= 2) {
1021 data.WriteHash(cur_src->GetUserHash());
1024 if (byUsedVersion >= 4){
1025 // CryptSettings - SourceExchange V4
1026 // 5 Reserved (!)
1027 // 1 CryptLayer Required
1028 // 1 CryptLayer Requested
1029 // 1 CryptLayer Supported
1030 const uint8 uSupportsCryptLayer = cur_src->SupportsCryptLayer() ? 1 : 0;
1031 const uint8 uRequestsCryptLayer = cur_src->RequestsCryptLayer() ? 1 : 0;
1032 const uint8 uRequiresCryptLayer = cur_src->RequiresCryptLayer() ? 1 : 0;
1033 const uint8 byCryptOptions = (uRequiresCryptLayer << 2) | (uRequestsCryptLayer << 1) | (uSupportsCryptLayer << 0);
1034 data.WriteUInt8(byCryptOptions);
1037 if (nCount > 500) {
1038 break;
1043 if (!nCount) {
1044 return 0;
1047 data.Seek(bIsSX2Packet ? 17 : 16, wxFromStart);
1048 data.WriteUInt16(nCount);
1050 CPacket* result = new CPacket(data, OP_EMULEPROT, bIsSX2Packet ? OP_ANSWERSOURCES2 : OP_ANSWERSOURCES);
1052 if ( result->GetPacketSize() > 354 ) {
1053 result->PackPacket();
1056 return result;
1060 // Updates priority of file if autopriority is activated
1061 void CKnownFile::UpdateAutoUpPriority()
1063 if (IsAutoUpPriority()) {
1064 uint32 queued = GetQueuedCount();
1065 uint8 priority = PR_NORMAL;
1067 if (queued > 20) {
1068 priority = PR_LOW;
1069 } else if (queued > 1) {
1070 priority = PR_NORMAL;
1071 } else {
1072 priority = PR_HIGH;
1075 if (GetUpPriority() != priority) {
1076 SetUpPriority(priority, false);
1077 Notify_SharedFilesUpdateItem(this);
1082 void CKnownFile::SetFileComment(const wxString& strNewComment)
1084 if (m_strComment != strNewComment) {
1085 SetLastPublishTimeKadNotes(0);
1086 wxString strCfgPath = wxT("/") + m_abyFileHash.Encode() + wxT("/");
1088 wxConfigBase* cfg = wxConfigBase::Get();
1089 cfg->Write( strCfgPath + wxT("Comment"), strNewComment);
1091 m_strComment = strNewComment;
1093 SourceSet::iterator it = m_ClientUploadList.begin();
1094 for ( ; it != m_ClientUploadList.end(); it++ ) {
1095 (*it)->SetCommentDirty();
1101 // For File rate
1102 void CKnownFile::SetFileRating(int8 iNewRating)
1104 if (m_iRating != iNewRating) {
1105 SetLastPublishTimeKadNotes(0);
1106 wxString strCfgPath = wxT("/") + m_abyFileHash.Encode() + wxT("/");
1107 wxConfigBase* cfg = wxConfigBase::Get();
1108 cfg->Write( strCfgPath + wxT("Rate"), (int)iNewRating);
1109 m_iRating = iNewRating;
1111 SourceSet::iterator it = m_ClientUploadList.begin();
1112 for ( ; it != m_ClientUploadList.end(); it++ ) {
1113 (*it)->SetCommentDirty();
1119 void CKnownFile::SetUpPriority(uint8 iNewUpPriority, bool m_bsave){
1120 m_iUpPriority = iNewUpPriority;
1121 if( IsPartFile() && m_bsave ) {
1122 ((CPartFile*)this)->SavePartFile();
1126 void CKnownFile::SetPublishedED2K(bool val){
1127 m_PublishedED2K = val;
1128 Notify_SharedFilesUpdateItem(this);
1131 bool CKnownFile::PublishNotes()
1133 if(m_lastPublishTimeKadNotes > (uint32)time(NULL)) {
1134 return false;
1137 if(!GetFileComment().IsEmpty()) {
1138 m_lastPublishTimeKadNotes = (uint32)time(NULL)+KADEMLIAREPUBLISHTIMEN;
1139 return true;
1142 if(GetFileRating() != 0) {
1143 m_lastPublishTimeKadNotes = (uint32)time(NULL)+KADEMLIAREPUBLISHTIMEN;
1144 return true;
1147 return false;
1150 bool CKnownFile::PublishSrc()
1152 uint32 lastBuddyIP = 0;
1154 if( theApp->IsFirewalled() ) {
1155 CUpDownClient* buddy = theApp->clientlist->GetBuddy();
1156 if( buddy ) {
1157 lastBuddyIP = theApp->clientlist->GetBuddy()->GetIP();
1158 if( lastBuddyIP != m_lastBuddyIP ) {
1159 SetLastPublishTimeKadSrc( (uint32)time(NULL)+KADEMLIAREPUBLISHTIMES, lastBuddyIP );
1160 return true;
1162 } else {
1163 return false;
1167 if(m_lastPublishTimeKadSrc > (uint32)time(NULL)) {
1168 return false;
1171 SetLastPublishTimeKadSrc((uint32)time(NULL)+KADEMLIAREPUBLISHTIMES,lastBuddyIP);
1172 return true;
1176 void CKnownFile::UpdatePartsInfo()
1178 // Cache part count
1179 uint16 partcount = GetPartCount();
1180 bool flag = (time(NULL) - m_nCompleteSourcesTime > 0);
1182 // Ensure the frequency-list is ready
1183 if ( m_AvailPartFrequency.size() != GetPartCount() ) {
1184 m_AvailPartFrequency.clear();
1185 m_AvailPartFrequency.insert(m_AvailPartFrequency.begin(), GetPartCount(), 0);
1188 if (flag) {
1189 ArrayOfUInts16 count;
1190 count.reserve(m_ClientUploadList.size());
1192 SourceSet::iterator it = m_ClientUploadList.begin();
1193 for ( ; it != m_ClientUploadList.end(); it++ ) {
1194 if ( !(*it)->GetUpPartStatus().empty() && (*it)->GetUpPartCount() == partcount ) {
1195 count.push_back((*it)->GetUpCompleteSourcesCount());
1199 m_nCompleteSourcesCount = m_nCompleteSourcesCountLo = m_nCompleteSourcesCountHi = 0;
1201 if( partcount > 0) {
1202 m_nCompleteSourcesCount = m_AvailPartFrequency[0];
1204 for (uint16 i = 1; i < partcount; ++i) {
1205 if( m_nCompleteSourcesCount > m_AvailPartFrequency[i]) {
1206 m_nCompleteSourcesCount = m_AvailPartFrequency[i];
1209 count.push_back(m_nCompleteSourcesCount);
1211 int32 n = count.size();
1212 if (n > 0) {
1213 std::sort(count.begin(), count.end(), std::less<uint16>());
1215 // calculate range
1216 int i = n >> 1; // (n / 2)
1217 int j = (n * 3) >> 2; // (n * 3) / 4
1218 int k = (n * 7) >> 3; // (n * 7) / 8
1220 // For complete files, trust the people your uploading to more...
1222 // For low guess and normal guess count
1223 // - If we see more sources then the guessed low and
1224 // normal, use what we see.
1225 // - If we see less sources then the guessed low,
1226 // adjust network accounts for 100%, we account for
1227 // 0% with what we see and make sure we are still
1228 // above the normal.
1229 // For high guess
1230 // Adjust 100% network and 0% what we see.
1231 if (n < 20) {
1232 if ( count[i] < m_nCompleteSourcesCount ) {
1233 m_nCompleteSourcesCountLo = m_nCompleteSourcesCount;
1234 } else {
1235 m_nCompleteSourcesCountLo = count[i];
1237 m_nCompleteSourcesCount= m_nCompleteSourcesCountLo;
1238 m_nCompleteSourcesCountHi = count[j];
1239 if( m_nCompleteSourcesCountHi < m_nCompleteSourcesCount ) {
1240 m_nCompleteSourcesCountHi = m_nCompleteSourcesCount;
1242 } else {
1243 // Many sources..
1244 // For low guess
1245 // Use what we see.
1246 // For normal guess
1247 // Adjust network accounts for 100%, we account for
1248 // 0% with what we see and make sure we are still above the low.
1249 // For high guess
1250 // Adjust network accounts for 100%, we account for 0%
1251 // with what we see and make sure we are still above the normal.
1253 m_nCompleteSourcesCountLo = m_nCompleteSourcesCount;
1254 m_nCompleteSourcesCount = count[j];
1255 if( m_nCompleteSourcesCount < m_nCompleteSourcesCountLo ) {
1256 m_nCompleteSourcesCount = m_nCompleteSourcesCountLo;
1258 m_nCompleteSourcesCountHi= count[k];
1259 if( m_nCompleteSourcesCountHi < m_nCompleteSourcesCount ) {
1260 m_nCompleteSourcesCountHi = m_nCompleteSourcesCount;
1264 m_nCompleteSourcesTime = time(NULL) + (60);
1267 Notify_SharedFilesUpdateItem(this);
1271 void CKnownFile::UpdateUpPartsFrequency( CUpDownClient* client, bool increment )
1273 if ( m_AvailPartFrequency.size() != GetPartCount() ) {
1274 m_AvailPartFrequency.clear();
1275 m_AvailPartFrequency.insert(m_AvailPartFrequency.begin(), GetPartCount(), 0);
1276 if ( !increment ) {
1277 return;
1281 const BitVector& freq = client->GetUpPartStatus();
1282 unsigned int size = freq.size();
1283 if ( size != m_AvailPartFrequency.size() ) {
1284 return;
1287 if ( increment ) {
1288 for ( unsigned int i = 0; i < size; ++i ) {
1289 if ( freq[i] ) {
1290 m_AvailPartFrequency[i]++;
1293 } else {
1294 for ( unsigned int i = 0; i < size; ++i ) {
1295 if ( freq[i] ) {
1296 m_AvailPartFrequency[i]--;
1302 void CKnownFile::ClearPriority() {
1303 if ( !m_bAutoUpPriority ) return;
1304 m_iUpPriority = ( m_bAutoUpPriority ) ? PR_HIGH : PR_NORMAL;
1305 UpdateAutoUpPriority();
1308 void GuessAndRemoveExt(CPath& name)
1310 wxString ext = name.GetExt();
1312 // Remove common two-part extensions, such as "tar.gz"
1313 if (ext == wxT("gz") || ext == wxT("bz2")) {
1314 name = name.RemoveExt();
1315 if (name.GetExt() == wxT("tar")) {
1316 name = name.RemoveExt();
1318 // might be an extension if length == 3
1319 // and also remove some common non-three-character extensions
1320 } else if (ext.Length() == 3 ||
1321 ext == wxT("7z") ||
1322 ext == wxT("rm") ||
1323 ext == wxT("jpeg") ||
1324 ext == wxT("mpeg")
1326 name = name.RemoveExt();
1330 void CKnownFile::SetFileName(const CPath& filename)
1332 CAbstractFile::SetFileName(filename);
1333 wordlist.clear();
1334 // Don't publish extension. That'd kill the node indexing e.g. "avi".
1335 CPath tmpName = GetFileName();
1336 GuessAndRemoveExt(tmpName);
1337 Kademlia::CSearchManager::GetWords(tmpName.GetPrintable(), &wordlist);
1340 #endif // CLIENT_GUI
1342 //For File Comment //
1343 void CKnownFile::LoadComment()
1345 #ifndef CLIENT_GUI
1346 wxString strCfgPath = wxT("/") + m_abyFileHash.Encode() + wxT("/");
1348 wxConfigBase* cfg = wxConfigBase::Get();
1350 m_strComment = cfg->Read( strCfgPath + wxT("Comment"), wxEmptyString);
1351 m_iRating = cfg->Read( strCfgPath + wxT("Rate"), 0l);
1352 m_bCommentLoaded = true;
1354 #else
1355 m_strComment = wxEmptyString;
1356 m_bCommentLoaded = true;
1357 m_iRating =0;
1358 #endif
1363 wxString CKnownFile::GetAICHMasterHash() const
1365 #ifdef CLIENT_GUI
1366 return m_AICHMasterHash;
1367 #else
1368 if (HasProperAICHHashSet()) {
1369 return m_pAICHHashSet->GetMasterHash().GetString();
1372 return wxEmptyString;
1373 #endif
1377 bool CKnownFile::HasProperAICHHashSet() const
1379 #ifdef CLIENT_GUI
1380 return m_AICHMasterHash.Length() != 0;
1381 #else
1382 return m_pAICHHashSet->HasValidMasterHash() &&
1383 (m_pAICHHashSet->GetStatus() == AICH_HASHSETCOMPLETE ||
1384 m_pAICHHashSet->GetStatus() == AICH_VERIFIED);
1385 #endif
1388 wxString CKnownFile::GetFeedback() const
1390 return wxString(_("File name")) + wxT(": ") + GetFileName().GetPrintable() + wxT("\n")
1391 + _("File size") + wxT(": ") + CastItoXBytes(GetFileSize()) + wxT("\n")
1392 + _("Share ratio") + wxString::Format(wxT(": %.2f%%\n"), (((double)statistic.GetAllTimeTransferred() / (double)GetFileSize()) * 100.0))
1393 + _("Uploaded") + wxT(": ") + CastItoXBytes(statistic.GetTransferred()) + wxT(" (") + CastItoXBytes(statistic.GetAllTimeTransferred()) + wxT(")\n")
1394 + _("Requested") + CFormat(wxT(": %u (%u)\n")) % statistic.GetRequests() % statistic.GetAllTimeRequests()
1395 + _("Accepted") + CFormat(wxT(": %u (%u)\n")) % statistic.GetAccepts() % statistic.GetAllTimeAccepts()
1396 + _("On Queue") + CFormat(wxT(": %u\n")) % GetQueuedCount()
1397 + _("Complete sources") + CFormat(wxT(": %u\n")) % m_nCompleteSourcesCount;
1399 // File_checked_for_headers