Fix NOMINMAX usage
[amule.git] / src / KnownFile.cpp
blob4a7740ef092d6c2577282adbafff33cbe29665e8
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-2011 aMule Team ( admin@amule.org / http://www.amule.org )
7 // Copyright (c) 2002-2011 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.
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
31 #include <protocol/kad/Constants.h>
32 #include <protocol/ed2k/Client2Client/TCP.h>
33 #include <protocol/ed2k/ClientSoftware.h>
34 #include <protocol/Protocols.h>
35 #include <tags/FileTags.h>
37 #include <wx/config.h>
39 #ifdef CLIENT_GUI
40 #include "UpDownClientEC.h" // Needed for CUpDownClient
41 #else
42 #include "updownclient.h" // Needed for CUpDownClient
43 #endif
45 #include "MemFile.h" // Needed for CMemFile
46 #include "Packet.h" // Needed for CPacket
47 #include "Preferences.h" // Needed for CPreferences
48 #include "KnownFileList.h" // Needed for CKnownFileList
49 #include "amule.h" // Needed for theApp
50 #include "PartFile.h" // Needed for SavePartFile
51 #include "ClientList.h" // Needed for clientlist (buddy support)
52 #include "Logger.h"
53 #include "ScopedPtr.h" // Needed for CScopedArray and CScopedPtr
54 #include "GuiEvents.h" // Needed for Notify_*
55 #include "SearchFile.h" // Needed for CSearchFile
56 #include "FileArea.h" // Needed for CFileArea
57 #include "FileAutoClose.h" // Needed for CFileAutoClose
58 #include "Server.h" // Needed for CServer
60 #include "CryptoPP_Inc.h" // Needed for MD4
62 #include <common/Format.h>
64 CFileStatistic::CFileStatistic() :
65 requested(0),
66 transferred(0),
67 accepted(0),
68 alltimerequested(0),
69 alltimetransferred(0),
70 alltimeaccepted(0)
74 #ifndef CLIENT_GUI
76 void CFileStatistic::AddRequest(){
77 requested++;
78 alltimerequested++;
79 theApp->knownfiles->requested++;
80 theApp->sharedfiles->UpdateItem(fileParent);
83 void CFileStatistic::AddAccepted(){
84 accepted++;
85 alltimeaccepted++;
86 theApp->knownfiles->accepted++;
87 theApp->sharedfiles->UpdateItem(fileParent);
90 void CFileStatistic::AddTransferred(uint64 bytes){
91 transferred += bytes;
92 alltimetransferred += bytes;
93 theApp->knownfiles->transferred += bytes;
94 theApp->sharedfiles->UpdateItem(fileParent);
97 #endif // CLIENT_GUI
100 /* Abstract File (base class)*/
102 CAbstractFile::CAbstractFile()
104 m_iRating(0),
105 m_hasComment(false),
106 m_iUserRating(0),
107 m_nFileSize(0)
112 CAbstractFile::CAbstractFile(const CAbstractFile& other)
114 m_abyFileHash(other.m_abyFileHash),
115 m_strComment(other.m_strComment),
116 m_iRating(other.m_iRating),
117 m_hasComment(other.m_hasComment),
118 m_iUserRating(other.m_iUserRating),
119 m_taglist(other.m_taglist),
120 m_nFileSize(other.m_nFileSize),
121 m_fileName(other.m_fileName)
123 /* // TODO: Currently it's not safe to duplicate the entries, but isn't needed either.
124 CKadEntryPtrList::const_iterator it = other.m_kadNotes.begin();
125 for (; it != other.m_kadNotes.end(); ++it) {
126 m_kadNotes.push_back(new Kademlia::CEntry(**it));
132 void CAbstractFile::SetFileName(const CPath& fileName)
134 m_fileName = fileName;
137 uint32 CAbstractFile::GetIntTagValue(uint8 tagname) const
139 ArrayOfCTag::const_iterator it = m_taglist.begin();
140 for (; it != m_taglist.end(); ++it){
141 if (((*it).GetNameID() == tagname) && (*it).IsInt()) {
142 return (*it).GetInt();
145 return 0;
148 bool CAbstractFile::GetIntTagValue(uint8 tagname, uint32& ruValue) const
150 ArrayOfCTag::const_iterator it = m_taglist.begin();
151 for (; it != m_taglist.end(); ++it){
152 if (((*it).GetNameID() == tagname) && (*it).IsInt()){
153 ruValue = (*it).GetInt();
154 return true;
157 return false;
160 uint32 CAbstractFile::GetIntTagValue(const wxString& tagname) const
162 ArrayOfCTag::const_iterator it = m_taglist.begin();
163 for (; it != m_taglist.end(); ++it){
164 if ((*it).IsInt() && ((*it).GetName() == tagname)) {
165 return (*it).GetInt();
168 return 0;
171 const wxString& CAbstractFile::GetStrTagValue(uint8 tagname) const
173 ArrayOfCTag::const_iterator it = m_taglist.begin();
174 for (; it != m_taglist.end(); ++it){
175 if ((*it).GetNameID() == tagname && (*it).IsStr()) {
176 return (*it).GetStr();
179 return EmptyString;
182 const wxString& CAbstractFile::GetStrTagValue(const wxString& tagname) const
184 ArrayOfCTag::const_iterator it = m_taglist.begin();
185 for (; it != m_taglist.end(); ++it){
186 if ((*it).IsStr() && ((*it).GetName() == tagname)) {
187 return (*it).GetStr();
190 return EmptyString;
193 const CTag *CAbstractFile::GetTag(uint8 tagname, uint8 tagtype) const
195 ArrayOfCTag::const_iterator it = m_taglist.begin();
196 for (; it != m_taglist.end(); ++it){
197 if ((*it).GetNameID() == tagname && (*it).GetType() == tagtype) {
198 return &(*it);
201 return NULL;
204 const CTag *CAbstractFile::GetTag(const wxString& tagname, uint8 tagtype) const
206 ArrayOfCTag::const_iterator it = m_taglist.begin();
207 for (; it != m_taglist.end(); ++it){
208 if ((*it).GetType() == tagtype && (*it).GetName() == tagname) {
209 return &(*it);
212 return NULL;
215 const CTag *CAbstractFile::GetTag(uint8 tagname) const
217 ArrayOfCTag::const_iterator it = m_taglist.begin();
218 for (; it != m_taglist.end(); ++it){
219 if ((*it).GetNameID() == tagname) {
220 return &(*it);
223 return NULL;
226 const CTag *CAbstractFile::GetTag(const wxString& tagname) const
228 ArrayOfCTag::const_iterator it = m_taglist.begin();
229 for (; it != m_taglist.end(); ++it){
230 if ((*it).GetName() == tagname) {
231 return &(*it);
234 return NULL;
237 void CAbstractFile::AddTagUnique(const CTag &rTag)
239 ArrayOfCTag::iterator it = m_taglist.begin();
240 for (; it != m_taglist.end(); ++it) {
241 if ( ( ((*it).GetNameID() != 0 &&
242 (*it).GetNameID() == rTag.GetNameID()) ||
243 (!(*it).GetName().IsEmpty() &&
244 !rTag.GetName().IsEmpty() &&
245 (*it).GetName() == rTag.GetName()) ) &&
246 (*it).GetType() == rTag.GetType()){
247 m_taglist.erase(it);
248 m_taglist.insert(it, rTag);
249 return;
252 m_taglist.push_back(rTag);
255 #ifndef CLIENT_GUI
256 void CAbstractFile::AddNote(Kademlia::CEntry *pEntry)
258 CKadEntryPtrList::iterator it = m_kadNotes.begin();
259 for (; it != m_kadNotes.end(); ++it) {
260 Kademlia::CEntry* entry = *it;
261 if(entry->m_uIP == pEntry->m_uIP || entry->m_uSourceID == pEntry->m_uSourceID) {
262 delete pEntry;
263 return;
266 m_kadNotes.push_front(pEntry);
268 #else
269 void CAbstractFile::AddNote(Kademlia::CEntry *)
272 #endif
275 /* Known File */
277 CKnownFile::CKnownFile()
279 Init();
282 CKnownFile::CKnownFile(uint32 ecid) : CECID(ecid)
284 Init();
288 //#warning Experimental: Construct a CKnownFile from a CSearchFile
289 CKnownFile::CKnownFile(const CSearchFile &searchFile)
291 // This will copy the file hash
292 CAbstractFile(static_cast<const CAbstractFile &>(searchFile))
294 Init();
296 // Use CKnownFile::SetFileName()
297 SetFileName(searchFile.GetFileName());
299 // Use CKnownFile::SetFileSize()
300 SetFileSize(searchFile.GetFileSize());
304 void CKnownFile::Init()
306 m_showSources = false;
307 m_showPeers = false;
308 m_nCompleteSourcesTime = time(NULL);
309 m_nCompleteSourcesCount = 0;
310 m_nCompleteSourcesCountLo = 0;
311 m_nCompleteSourcesCountHi = 0;
312 m_bCommentLoaded = false;
313 m_iPartCount = 0;
314 m_iED2KPartCount = 0;
315 m_iED2KPartHashCount = 0;
316 m_PublishedED2K = false;
317 kadFileSearchID = 0;
318 m_lastPublishTimeKadSrc = 0;
319 m_lastPublishTimeKadNotes = 0;
320 m_lastBuddyIP = 0;
321 m_lastDateChanged = 0;
322 m_bAutoUpPriority = thePrefs::GetNewAutoUp();
323 m_iUpPriority = ( m_bAutoUpPriority ) ? PR_HIGH : PR_NORMAL;
324 m_hashingProgress = 0;
326 statistic.fileParent = this;
328 #ifndef CLIENT_GUI
329 m_pAICHHashSet = new CAICHHashSet(this);
330 #endif
334 void CKnownFile::SetFileSize(uint64 nFileSize)
336 CAbstractFile::SetFileSize(nFileSize);
337 #ifndef CLIENT_GUI
338 m_pAICHHashSet->SetFileSize(nFileSize);
339 #endif
341 // Examples of parthashs, hashsets and filehashs for different filesizes
342 // according the ed2k protocol
343 //----------------------------------------------------------------------
345 //File size: 3 bytes
346 //File hash: 2D55E87D0E21F49B9AD25F98531F3724
347 //Nr. hashs: 0
350 //File size: 1*PARTSIZE
351 //File hash: A72CA8DF7F07154E217C236C89C17619
352 //Nr. hashs: 2
353 //Hash[ 0]: 4891ED2E5C9C49F442145A3A5F608299
354 //Hash[ 1]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
357 //File size: 1*PARTSIZE + 1 byte
358 //File hash: 2F620AE9D462CBB6A59FE8401D2B3D23
359 //Nr. hashs: 2
360 //Hash[ 0]: 121795F0BEDE02DDC7C5426D0995F53F
361 //Hash[ 1]: C329E527945B8FE75B3C5E8826755747
364 //File size: 2*PARTSIZE
365 //File hash: A54C5E562D5E03CA7D77961EB9A745A4
366 //Nr. hashs: 3
367 //Hash[ 0]: B3F5CE2A06BF403BFB9BFFF68BDDC4D9
368 //Hash[ 1]: 509AA30C9EA8FC136B1159DF2F35B8A9
369 //Hash[ 2]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
372 //File size: 3*PARTSIZE
373 //File hash: 5E249B96F9A46A18FC2489B005BF2667
374 //Nr. hashs: 4
375 //Hash[ 0]: 5319896A2ECAD43BF17E2E3575278E72
376 //Hash[ 1]: D86EF157D5E49C5ED502EDC15BB5F82B
377 //Hash[ 2]: 10F2D5B1FCB95C0840519C58D708480F
378 //Hash[ 3]: 31D6CFE0D16AE931B73C59D7E0C089C0 *special part hash*
381 //File size: 3*PARTSIZE + 1 byte
382 //File hash: 797ED552F34380CAFF8C958207E40355
383 //Nr. hashs: 4
384 //Hash[ 0]: FC7FD02CCD6987DCF1421F4C0AF94FB8
385 //Hash[ 1]: 2FE466AF8A7C06DA3365317B75A5ACFE
386 //Hash[ 2]: 873D3BF52629F7C1527C6E8E473C1C30
387 //Hash[ 3]: BCE50BEE7877BB07BB6FDA56BFE142FB
390 // File size Data parts ED2K parts ED2K part hashs
391 // ---------------------------------------------------------------
392 // 1..PARTSIZE-1 1 1 0(!)
393 // PARTSIZE 1 2(!) 2(!)
394 // PARTSIZE+1 2 2 2
395 // PARTSIZE*2 2 3(!) 3(!)
396 // PARTSIZE*2+1 3 3 3
398 if (nFileSize == 0){
399 //wxFAIL; // Kry - Why commented out by lemonfan? it can never be 0
400 m_iPartCount = 0;
401 m_iED2KPartCount = 0;
402 m_iED2KPartHashCount = 0;
403 m_sizeLastPart = 0;
404 return;
407 // nr. of data parts
408 m_iPartCount = nFileSize / PARTSIZE + 1;
409 // size of last part
410 m_sizeLastPart = nFileSize % PARTSIZE;
411 // file with size of n * PARTSIZE
412 if (m_sizeLastPart == 0) {
413 m_sizeLastPart = PARTSIZE;
414 m_iPartCount--;
417 // nr. of parts to be used with OP_FILESTATUS
418 m_iED2KPartCount = nFileSize / PARTSIZE + 1;
420 // nr. of parts to be used with OP_HASHSETANSWER
421 m_iED2KPartHashCount = nFileSize / PARTSIZE;
422 if (m_iED2KPartHashCount != 0) {
423 m_iED2KPartHashCount += 1;
428 void CKnownFile::AddUploadingClient(CUpDownClient* client)
430 m_ClientUploadList.insert(CCLIENTREF(client, wxT("CKnownFile::AddUploadingClient m_ClientUploadList")));
432 SourceItemType type = UNAVAILABLE_SOURCE;
433 switch (client->GetUploadState()) {
434 case US_UPLOADING:
435 case US_ONUPLOADQUEUE:
436 type = AVAILABLE_SOURCE;
437 break;
438 default: {
439 // Any other state is UNAVAILABLE_SOURCE by default.
443 Notify_SharedCtrlAddClient(this, CCLIENTREF(client, wxT("CKnownFile::AddUploadingClient Notify_SharedCtrlAddClient")), type);
445 UpdateAutoUpPriority();
449 void CKnownFile::RemoveUploadingClient(CUpDownClient* client)
451 if (m_ClientUploadList.erase(CCLIENTREF(client, wxEmptyString))) {
452 Notify_SharedCtrlRemoveClient(client->ECID(), this);
453 UpdateAutoUpPriority();
458 #ifdef CLIENT_GUI
460 CKnownFile::CKnownFile(CEC_SharedFile_Tag *tag) : CECID(tag->ID())
462 Init();
464 m_abyFileHash = tag->FileHash();
465 SetFileSize(tag->SizeFull());
466 m_AvailPartFrequency.insert(m_AvailPartFrequency.end(), m_iPartCount, 0);
467 m_queuedCount = 0;
470 CKnownFile::~CKnownFile()
474 void CKnownFile::UpdateAutoUpPriority()
479 #else // ! CLIENT_GUI
481 CKnownFile::~CKnownFile()
483 SourceSet::iterator it = m_ClientUploadList.begin();
484 for ( ; it != m_ClientUploadList.end(); ++it ) {
485 it->ClearUploadFileID();
488 delete m_pAICHHashSet;
492 void CKnownFile::SetFilePath(const CPath& filePath)
494 m_filePath = filePath;
498 // needed for memfiles. its probably better to switch everything to CFile...
499 bool CKnownFile::LoadHashsetFromFile(const CFileDataIO* file, bool checkhash)
501 CMD4Hash checkid = file->ReadHash();
503 uint16 parts = file->ReadUInt16();
504 m_hashlist.clear();
505 for (uint16 i = 0; i < parts; ++i){
506 CMD4Hash cur_hash = file->ReadHash();
507 m_hashlist.push_back(cur_hash);
510 // SLUGFILLER: SafeHash - always check for valid m_hashlist
511 if (!checkhash){
512 m_abyFileHash = checkid;
513 if (parts <= 1) { // nothing to check
514 return true;
516 } else {
517 if ( m_abyFileHash != checkid ) {
518 return false; // wrong file?
519 } else {
520 if (parts != GetED2KPartHashCount()) {
521 return false;
525 // SLUGFILLER: SafeHash
527 // trust noone ;-)
528 // lol, useless comment but made me lmao
529 // wtf you guys are weird.
531 if (!m_hashlist.empty()) {
532 CreateHashFromHashlist(m_hashlist, &checkid);
535 if ( m_abyFileHash == checkid ) {
536 return true;
537 } else {
538 m_hashlist.clear();
539 return false;
544 bool CKnownFile::LoadTagsFromFile(const CFileDataIO* file)
546 uint32 tagcount = file->ReadUInt32();
547 m_taglist.clear();
548 for (uint32 j = 0; j != tagcount; ++j) {
549 CTag newtag(*file, true);
550 switch(newtag.GetNameID()){
551 case FT_FILENAME:
552 if (GetFileName().IsOk()) {
553 // Unlike eMule, we actually prefer the second
554 // filename tag, since we use it to specify the
555 // 'universial' filename (see CPath::ToUniv).
556 CPath path = CPath::FromUniv(newtag.GetStr());
558 // May be invalid, if from older versions where
559 // unicoded filenames be saved as empty-strings.
560 if (path.IsOk()) {
561 SetFileName(path);
563 } else {
564 SetFileName(CPath(newtag.GetStr()));
566 break;
568 case FT_FILESIZE:
569 SetFileSize(newtag.GetInt());
570 m_AvailPartFrequency.clear();
571 m_AvailPartFrequency.insert(
572 m_AvailPartFrequency.begin(),
573 GetPartCount(), 0);
574 break;
576 case FT_ATTRANSFERRED:
577 statistic.alltimetransferred += newtag.GetInt();
578 break;
580 case FT_ATTRANSFERREDHI:
581 statistic.alltimetransferred =
582 (((uint64)newtag.GetInt()) << 32) +
583 ((uint64)statistic.alltimetransferred);
584 break;
586 case FT_ATREQUESTED:
587 statistic.alltimerequested = newtag.GetInt();
588 break;
590 case FT_ATACCEPTED:
591 statistic.alltimeaccepted = newtag.GetInt();
592 break;
594 case FT_ULPRIORITY:
595 m_iUpPriority = newtag.GetInt();
596 if( m_iUpPriority == PR_AUTO ){
597 m_iUpPriority = PR_HIGH;
598 m_bAutoUpPriority = true;
599 } else {
600 if ( m_iUpPriority != PR_VERYLOW &&
601 m_iUpPriority != PR_LOW &&
602 m_iUpPriority != PR_NORMAL &&
603 m_iUpPriority != PR_HIGH &&
604 m_iUpPriority != PR_VERYHIGH &&
605 m_iUpPriority != PR_POWERSHARE) {
606 m_iUpPriority = PR_NORMAL;
609 m_bAutoUpPriority = false;
611 break;
613 case FT_PERMISSIONS:
614 // Ignore it, it's not used anymore.
615 break;
617 case FT_AICH_HASH: {
618 CAICHHash hash;
619 bool hashSizeOk =
620 hash.DecodeBase32(newtag.GetStr()) == CAICHHash::GetHashSize();
621 wxASSERT(hashSizeOk);
622 if (hashSizeOk) {
623 m_pAICHHashSet->SetMasterHash(hash, AICH_HASHSETCOMPLETE);
625 break;
628 case FT_KADLASTPUBLISHSRC:
629 SetLastPublishTimeKadSrc( newtag.GetInt(), 0 );
631 if(GetLastPublishTimeKadSrc() > (uint32)time(NULL)+KADEMLIAREPUBLISHTIMES) {
632 //There may be a posibility of an older client that saved a random number here.. This will check for that..
633 SetLastPublishTimeKadSrc(0, 0);
635 break;
637 case FT_KADLASTPUBLISHNOTES:
638 SetLastPublishTimeKadNotes( newtag.GetInt() );
639 break;
641 case FT_KADLASTPUBLISHKEY:
642 // Just purge it
643 wxASSERT( newtag.IsInt() );
644 break;
646 default:
647 // Store them here and write them back on saving.
648 m_taglist.push_back(newtag);
652 return true;
656 bool CKnownFile::LoadDateFromFile(const CFileDataIO* file)
658 m_lastDateChanged = file->ReadUInt32();
660 return true;
664 bool CKnownFile::LoadFromFile(const CFileDataIO* file)
666 // SLUGFILLER: SafeHash - load first, verify later
667 bool ret1 = LoadDateFromFile(file);
668 bool ret2 = LoadHashsetFromFile(file,false);
669 bool ret3 = LoadTagsFromFile(file);
670 UpdatePartsInfo();
671 // Final hash-count verification, needs to be done after the tags are loaded.
672 return ret1 && ret2 && ret3 && GetED2KPartHashCount()==GetHashCount();
673 // SLUGFILLER: SafeHash
677 bool CKnownFile::WriteToFile(CFileDataIO* file)
679 wxCHECK(!IsPartFile(), false);
681 // date
682 file->WriteUInt32(m_lastDateChanged);
683 // hashset
684 file->WriteHash(m_abyFileHash);
686 uint16 parts = m_hashlist.size();
687 file->WriteUInt16(parts);
689 for (int i = 0; i < parts; ++i)
690 file->WriteHash(m_hashlist[i]);
692 //tags
693 const int iFixedTags = 8;
694 uint32 tagcount = iFixedTags;
695 if (HasProperAICHHashSet()) {
696 tagcount++;
698 // Float meta tags are currently not written. All older eMule versions < 0.28a have
699 // a bug in the meta tag reading+writing code. To achive maximum backward
700 // compatibility for met files with older eMule versions we just don't write float
701 // tags. This is OK, because we (eMule) do not use float tags. The only float tags
702 // we may have to handle is the '# Sent' tag from the Hybrid, which is pretty
703 // useless but may be received from us via the servers.
705 // The code for writing the float tags SHOULD BE ENABLED in SOME MONTHS (after most
706 // people are using the newer eMule versions which do not write broken float tags).
707 for (size_t j = 0; j < m_taglist.size(); ++j){
708 if (m_taglist[j].IsInt() || m_taglist[j].IsStr()) {
709 ++tagcount;
713 if (m_lastPublishTimeKadSrc) {
714 ++tagcount;
717 if (m_lastPublishTimeKadNotes){
718 ++tagcount;
721 // standard tags
723 file->WriteUInt32(tagcount);
725 // We still save the unicoded filename, for backwards
726 // compatibility with pre-2.2 and other clients.
727 CTagString nametag_unicode(FT_FILENAME, GetFileName().GetRaw());
728 // We write it with BOM to kep eMule compatibility
729 nametag_unicode.WriteTagToFile(file,utf8strOptBOM);
731 // The non-unicoded filename is written in an 'universial'
732 // format, which allows us to identify files, even if the
733 // system locale changes.
734 CTagString nametag(FT_FILENAME, CPath::ToUniv(GetFileName()));
735 nametag.WriteTagToFile(file);
737 CTagIntSized sizetag(FT_FILESIZE, GetFileSize(), IsLargeFile() ? 64 : 32);
738 sizetag.WriteTagToFile(file);
740 // statistic
741 uint32 tran;
742 tran=statistic.alltimetransferred & 0xFFFFFFFF;
743 CTagInt32 attag1(FT_ATTRANSFERRED, tran);
744 attag1.WriteTagToFile(file);
746 tran=statistic.alltimetransferred>>32;
747 CTagInt32 attag4(FT_ATTRANSFERREDHI, tran);
748 attag4.WriteTagToFile(file);
750 CTagInt32 attag2(FT_ATREQUESTED, statistic.GetAllTimeRequests());
751 attag2.WriteTagToFile(file);
753 CTagInt32 attag3(FT_ATACCEPTED, statistic.GetAllTimeAccepts());
754 attag3.WriteTagToFile(file);
756 // priority N permission
757 CTagInt32 priotag(FT_ULPRIORITY, IsAutoUpPriority() ? PR_AUTO : m_iUpPriority);
758 priotag.WriteTagToFile(file);
760 //AICH Filehash
761 if (HasProperAICHHashSet()) {
762 CTagString aichtag(FT_AICH_HASH, m_pAICHHashSet->GetMasterHash().GetString());
763 aichtag.WriteTagToFile(file);
766 // Kad sources
767 if (m_lastPublishTimeKadSrc){
768 CTagInt32 kadLastPubSrc(FT_KADLASTPUBLISHSRC, m_lastPublishTimeKadSrc);
769 kadLastPubSrc.WriteTagToFile(file);
772 // Kad notes
773 if (m_lastPublishTimeKadNotes){
774 CTagInt32 kadLastPubNotes(FT_KADLASTPUBLISHNOTES, m_lastPublishTimeKadNotes);
775 kadLastPubNotes.WriteTagToFile(file);
778 //other tags
779 for (size_t j = 0; j < m_taglist.size(); ++j){
780 if (m_taglist[j].IsInt() || m_taglist[j].IsStr()) {
781 m_taglist[j].WriteTagToFile(file);
784 return true;
788 void CKnownFile::CreateHashFromHashlist(const ArrayOfCMD4Hash& hashes, CMD4Hash* Output)
790 wxCHECK_RET(hashes.size(), wxT("No input to hash from in CreateHashFromHashlist"));
792 std::vector<byte> buffer(hashes.size() * MD4HASH_LENGTH);
793 std::vector<byte>::iterator it = buffer.begin();
795 for (size_t i = 0; i < hashes.size(); ++i) {
796 it = STLCopy_n(hashes[i].GetHash(), MD4HASH_LENGTH, it);
799 CreateHashFromInput(&buffer[0], buffer.size(), Output, NULL);
803 void CKnownFile::CreateHashFromFile(CFileAutoClose& file, uint64 offset, uint32 Length, CMD4Hash* Output, CAICHHashTree* pShaHashOut)
805 wxCHECK_RET(Length, wxT("No input to hash from in CreateHashFromFile"));
807 CFileArea area;
808 area.ReadAt(file, offset, Length);
810 CreateHashFromInput(area.GetBuffer(), Length, Output, pShaHashOut);
811 area.CheckError();
815 void CKnownFile::CreateHashFromInput(const byte* input, uint32 Length, CMD4Hash* Output, CAICHHashTree* pShaHashOut )
817 wxASSERT_MSG(Output || pShaHashOut, wxT("Nothing to do in CreateHashFromInput"));
818 { wxCHECK_RET(input, wxT("No input to hash from in CreateHashFromInput")); }
819 wxASSERT(Length <= PARTSIZE); // We never hash more than one PARTSIZE
821 CMemFile data(input, Length);
823 uint32 Required = Length;
824 byte X[64*128];
826 uint32 posCurrentEMBlock = 0;
827 uint32 nIACHPos = 0;
828 CScopedPtr<CAICHHashAlgo> pHashAlg(CAICHHashSet::GetNewHashAlgo());
830 // This is all AICH.
831 while (Required >= 64) {
832 uint32 len = Required / 64;
833 if (len > sizeof(X)/(64 * sizeof(X[0]))) {
834 len = sizeof(X)/(64 * sizeof(X[0]));
837 data.Read(&X, len * 64);
839 // SHA hash needs 180KB blocks
840 if (pShaHashOut) {
841 if (nIACHPos + len*64 >= EMBLOCKSIZE) {
842 uint32 nToComplete = EMBLOCKSIZE - nIACHPos;
843 pHashAlg->Add(X, nToComplete);
844 wxASSERT( nIACHPos + nToComplete == EMBLOCKSIZE );
845 pShaHashOut->SetBlockHash(EMBLOCKSIZE, posCurrentEMBlock, pHashAlg.get());
846 posCurrentEMBlock += EMBLOCKSIZE;
847 pHashAlg->Reset();
848 pHashAlg->Add(X+nToComplete,(len*64) - nToComplete);
849 nIACHPos = (len*64) - nToComplete;
851 else{
852 pHashAlg->Add(X, len*64);
853 nIACHPos += len*64;
857 Required -= len*64;
859 // bytes to read
860 Required = Length % 64;
861 if (Required != 0){
862 data.Read(&X,Required);
864 if (pShaHashOut != NULL){
865 if (nIACHPos + Required >= EMBLOCKSIZE){
866 uint32 nToComplete = EMBLOCKSIZE - nIACHPos;
867 pHashAlg->Add(X, nToComplete);
868 wxASSERT( nIACHPos + nToComplete == EMBLOCKSIZE );
869 pShaHashOut->SetBlockHash(EMBLOCKSIZE, posCurrentEMBlock, pHashAlg.get());
870 posCurrentEMBlock += EMBLOCKSIZE;
871 pHashAlg->Reset();
872 pHashAlg->Add(X+nToComplete, Required - nToComplete);
873 nIACHPos = Required - nToComplete;
875 else{
876 pHashAlg->Add(X, Required);
877 nIACHPos += Required;
881 if (pShaHashOut != NULL){
882 if(nIACHPos > 0){
883 pShaHashOut->SetBlockHash(nIACHPos, posCurrentEMBlock, pHashAlg.get());
884 posCurrentEMBlock += nIACHPos;
886 wxASSERT( posCurrentEMBlock == Length );
887 wxCHECK2( pShaHashOut->ReCalculateHash(pHashAlg.get(), false), );
890 if (Output != NULL){
891 #ifdef __WEAK_CRYPTO__
892 CryptoPP::Weak::MD4 md4_hasher;
893 #else
894 CryptoPP::MD4 md4_hasher;
895 #endif
896 md4_hasher.CalculateDigest(Output->GetHash(), input, Length);
901 const CMD4Hash& CKnownFile::GetPartHash(uint16 part) const {
902 wxASSERT( part < m_hashlist.size() );
904 return m_hashlist[part];
907 CPacket* CKnownFile::CreateSrcInfoPacket(const CUpDownClient* forClient, uint8 byRequestedVersion, uint16 nRequestedOptions)
909 // Kad reviewed
911 if (m_ClientUploadList.empty()) {
912 return NULL;
915 if ((((CKnownFile*)forClient->GetRequestFile() != this)
916 && ((CKnownFile*)forClient->GetUploadFile() != this)) || forClient->GetUploadFileID() != GetFileHash()) {
917 wxString file1 = _("Unknown");
918 if (forClient->GetRequestFile() && forClient->GetRequestFile()->GetFileName().IsOk()) {
919 file1 = forClient->GetRequestFile()->GetFileName().GetPrintable();
920 } else if (forClient->GetUploadFile() && forClient->GetUploadFile()->GetFileName().IsOk()) {
921 file1 = forClient->GetUploadFile()->GetFileName().GetPrintable();
923 wxString file2 = _("Unknown");
924 if (GetFileName().IsOk()) {
925 file2 = GetFileName().GetPrintable();
927 AddDebugLogLineN(logKnownFiles, wxT("File mismatch on source packet (K) Sending: ") + file1 + wxT(" From: ") + file2);
928 return NULL;
931 const BitVector& rcvstatus = forClient->GetUpPartStatus();
932 bool SupportsUploadChunksState = !rcvstatus.empty();
933 //wxASSERT(rcvstatus.size() == GetPartCount()); // Obviously!
934 if (rcvstatus.size() != GetPartCount()) {
935 // Yuck. Same file but different part count? Seriously fucked up.
936 AddDebugLogLineN(logKnownFiles, CFormat(wxT("Impossible situation: different partcounts for the same known file: %i (client) and %i (file)")) % rcvstatus.size() % GetPartCount());
937 return NULL;
940 CMemFile data(1024);
942 uint8 byUsedVersion;
943 bool bIsSX2Packet;
944 if (forClient->SupportsSourceExchange2() && byRequestedVersion > 0){
945 // the client uses SourceExchange2 and requested the highest version he knows
946 // and we send the highest version we know, but of course not higher than his request
947 byUsedVersion = std::min(byRequestedVersion, (uint8)SOURCEEXCHANGE2_VERSION);
948 bIsSX2Packet = true;
949 data.WriteUInt8(byUsedVersion);
951 // we don't support any special SX2 options yet, reserved for later use
952 if (nRequestedOptions != 0) {
953 AddDebugLogLineN(logKnownFiles, CFormat(wxT("Client requested unknown options for SourceExchange2: %u")) % nRequestedOptions);
955 } else {
956 byUsedVersion = forClient->GetSourceExchange1Version();
957 bIsSX2Packet = false;
958 if (forClient->SupportsSourceExchange2()) {
959 AddDebugLogLineN(logKnownFiles, wxT("Client which announced to support SX2 sent SX1 packet instead"));
963 uint16 nCount = 0;
965 data.WriteHash(forClient->GetUploadFileID());
966 data.WriteUInt16(nCount);
967 uint32 cDbgNoSrc = 0;
969 SourceSet::iterator it = m_ClientUploadList.begin();
970 for ( ; it != m_ClientUploadList.end(); it++ ) {
971 const CUpDownClient *cur_src = it->GetClient();
973 if ( cur_src->HasLowID() ||
974 cur_src == forClient ||
975 !( cur_src->GetUploadState() == US_UPLOADING ||
976 cur_src->GetUploadState() == US_ONUPLOADQUEUE)) {
977 continue;
980 bool bNeeded = false;
982 if ( SupportsUploadChunksState ) {
983 const BitVector& srcstatus = cur_src->GetUpPartStatus();
984 if ( !srcstatus.empty() ) {
985 //wxASSERT(srcstatus.size() == GetPartCount()); // Obviously!
986 if (srcstatus.size() != GetPartCount()) {
987 continue;
989 if ( cur_src->GetUpPartCount() == forClient->GetUpPartCount() ) {
990 for (int x = 0; x < GetPartCount(); x++ ) {
991 if ( srcstatus.get(x) && !rcvstatus.get(x) ) {
992 // We know the receiving client needs
993 // a chunk from this client.
994 bNeeded = true;
995 break;
999 } else {
1000 cDbgNoSrc++;
1001 // This client doesn't support upload chunk status.
1002 // So just send it and hope for the best.
1003 bNeeded = true;
1005 } else {
1006 // remote client does not support upload chunk status,
1007 // search sources which have at least one complete part
1008 // we could even sort the list of sources by available
1009 // chunks to return as much sources as possible which
1010 // have the most available chunks. but this could be
1011 // a noticeable performance problem.
1012 const BitVector& srcstatus = cur_src->GetUpPartStatus();
1013 if ( !srcstatus.empty() ) {
1014 //wxASSERT(srcstatus.size() == GetPartCount());
1015 if (srcstatus.size() != GetPartCount()) {
1016 continue;
1018 for (int x = 0; x < GetPartCount(); x++ ) {
1019 if ( srcstatus.get(x) ) {
1020 // this client has at least one chunk
1021 bNeeded = true;
1022 break;
1025 } else {
1026 // This client doesn't support upload chunk status.
1027 // So just send it and hope for the best.
1028 bNeeded = true;
1032 if ( bNeeded ) {
1033 nCount++;
1034 uint32 dwID;
1035 if(byUsedVersion >= 3) {
1036 dwID = cur_src->GetUserIDHybrid();
1037 } else {
1038 dwID = cur_src->GetIP();
1040 data.WriteUInt32(dwID);
1041 data.WriteUInt16(cur_src->GetUserPort());
1042 data.WriteUInt32(cur_src->GetServerIP());
1043 data.WriteUInt16(cur_src->GetServerPort());
1045 if (byUsedVersion >= 2) {
1046 data.WriteHash(cur_src->GetUserHash());
1049 if (byUsedVersion >= 4){
1050 // CryptSettings - SourceExchange V4
1051 // 5 Reserved (!)
1052 // 1 CryptLayer Required
1053 // 1 CryptLayer Requested
1054 // 1 CryptLayer Supported
1055 const uint8 uSupportsCryptLayer = cur_src->SupportsCryptLayer() ? 1 : 0;
1056 const uint8 uRequestsCryptLayer = cur_src->RequestsCryptLayer() ? 1 : 0;
1057 const uint8 uRequiresCryptLayer = cur_src->RequiresCryptLayer() ? 1 : 0;
1058 const uint8 byCryptOptions = (uRequiresCryptLayer << 2) | (uRequestsCryptLayer << 1) | (uSupportsCryptLayer << 0);
1059 data.WriteUInt8(byCryptOptions);
1062 if (nCount > 500) {
1063 break;
1068 if (!nCount) {
1069 return 0;
1072 data.Seek(bIsSX2Packet ? 17 : 16, wxFromStart);
1073 data.WriteUInt16(nCount);
1075 CPacket* result = new CPacket(data, OP_EMULEPROT, bIsSX2Packet ? OP_ANSWERSOURCES2 : OP_ANSWERSOURCES);
1077 if ( result->GetPacketSize() > 354 ) {
1078 result->PackPacket();
1081 return result;
1085 void CKnownFile::CreateOfferedFilePacket(
1086 CMemFile *files,
1087 CServer *pServer,
1088 CUpDownClient *pClient) {
1090 // This function is used for offering files to the local server and for sending
1091 // shared files to some other client. In each case we send our IP+Port only, if
1092 // we have a HighID.
1094 wxASSERT(!(pClient && pServer));
1096 SetPublishedED2K(true);
1097 files->WriteHash(GetFileHash());
1099 uint32 nClientID = 0;
1100 uint16 nClientPort = 0;
1102 if (pServer) {
1103 if (pServer->GetTCPFlags() & SRV_TCPFLG_COMPRESSION) {
1104 #define FILE_COMPLETE_ID 0xfbfbfbfb
1105 #define FILE_COMPLETE_PORT 0xfbfb
1106 #define FILE_INCOMPLETE_ID 0xfcfcfcfc
1107 #define FILE_INCOMPLETE_PORT 0xfcfc
1108 // complete file: ip 251.251.251 (0xfbfbfbfb) port 0xfbfb
1109 // incomplete file: op 252.252.252 (0xfcfcfcfc) port 0xfcfc
1110 if (GetStatus() == PS_COMPLETE) {
1111 nClientID = FILE_COMPLETE_ID;
1112 nClientPort = FILE_COMPLETE_PORT;
1113 } else {
1114 nClientID = FILE_INCOMPLETE_ID;
1115 nClientPort = FILE_INCOMPLETE_PORT;
1117 } else {
1118 if (theApp->IsConnectedED2K() && !::IsLowID(theApp->GetED2KID())){
1119 nClientID = theApp->GetID();
1120 nClientPort = thePrefs::GetPort();
1123 } else {
1124 // Do not merge this with the above case - this one
1125 // also checks Kad status.
1126 if (theApp->IsConnected() && !theApp->IsFirewalled()) {
1127 nClientID = theApp->GetID();
1128 nClientPort = thePrefs::GetPort();
1132 files->WriteUInt32(nClientID);
1133 files->WriteUInt16(nClientPort);
1135 TagPtrList tags;
1137 // The printable filename is used because it's destined for another user.
1138 tags.push_back(new CTagString(FT_FILENAME, GetFileName().GetPrintable()));
1140 if (pClient && pClient->GetVBTTags()) {
1141 tags.push_back(new CTagVarInt(FT_FILESIZE, GetFileSize()));
1142 } else {
1143 if (!IsLargeFile()){
1144 tags.push_back(new CTagInt32(FT_FILESIZE, GetFileSize()));
1145 } else {
1146 // Large file
1147 // we send 2*32 bit tags to servers, but a real 64 bit tag to other clients.
1148 if (pServer) {
1149 if (!pServer->SupportsLargeFilesTCP()){
1150 wxFAIL;
1151 tags.push_back(new CTagInt32(FT_FILESIZE, 0));
1152 } else {
1153 tags.push_back(new CTagInt32(FT_FILESIZE, (uint32)GetFileSize()));
1154 tags.push_back(new CTagInt32(FT_FILESIZE_HI, (uint32)(GetFileSize() >> 32)));
1156 } else {
1157 if (!pClient->SupportsLargeFiles()) {
1158 wxFAIL;
1159 tags.push_back(new CTagInt32(FT_FILESIZE, 0));
1160 } else {
1161 tags.push_back(new CTagInt64(FT_FILESIZE, GetFileSize()));
1167 if (GetFileRating()) {
1168 tags.push_back(new CTagVarInt(FT_FILERATING, GetFileRating(), (pClient && pClient->GetVBTTags()) ? 0 : 32));
1171 // NOTE: Archives and CD-Images are published+searched with file type "Pro"
1172 bool bAddedFileType = false;
1173 if (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_TYPETAGINTEGER)) {
1174 // Send integer file type tags to newer servers
1175 EED2KFileType eFileType = GetED2KFileTypeSearchID(GetED2KFileTypeID(GetFileName()));
1176 if (eFileType >= ED2KFT_AUDIO && eFileType <= ED2KFT_CDIMAGE) {
1177 tags.push_back(new CTagInt32(FT_FILETYPE, eFileType));
1178 bAddedFileType = true;
1181 if (!bAddedFileType) {
1182 // Send string file type tags to:
1183 // - newer servers, in case there is no integer type available for the file type (e.g. emulecollection)
1184 // - older servers
1185 // - all clients
1186 wxString strED2KFileType(GetED2KFileTypeSearchTerm(GetED2KFileTypeID(GetFileName())));
1187 if (!strED2KFileType.IsEmpty()) {
1188 tags.push_back(new CTagString(FT_FILETYPE, strED2KFileType));
1192 // There, we could add MetaData info, if we ever get to have that.
1194 EUtf8Str eStrEncode;
1196 bool unicode_support =
1197 // eservers that support UNICODE.
1198 (pServer && (pServer->GetUnicodeSupport()))
1200 // clients that support unicode
1201 (pClient && pClient->GetUnicodeSupport());
1202 eStrEncode = unicode_support ? utf8strRaw : utf8strNone;
1204 files->WriteUInt32(tags.size());
1206 // Sadly, eMule doesn't use a MISCOPTIONS flag on hello packet for this, so we
1207 // have to identify the support for new tags by version.
1208 bool new_ed2k =
1209 // eMule client > 0.42f
1210 (pClient && pClient->IsEmuleClient() && pClient->GetVersion() >= MAKE_CLIENT_VERSION(0,42,7))
1212 // aMule >= 2.0.0rc8. Sadly, there's no way to check the rcN number, so I checked
1213 // the rc8 changelog. On rc8 OSInfo was introduced, so...
1214 (pClient && pClient->GetClientSoft() == SO_AMULE && !pClient->GetClientOSInfo().IsEmpty())
1216 // eservers use a flag for this, at least.
1217 (pServer && (pServer->GetTCPFlags() & SRV_TCPFLG_NEWTAGS));
1219 for (TagPtrList::iterator it = tags.begin(); it != tags.end(); ++it ) {
1220 CTag* pTag = *it;
1221 if (new_ed2k) {
1222 pTag->WriteNewEd2kTag(files, eStrEncode);
1223 } else {
1224 pTag->WriteTagToFile(files, eStrEncode);
1226 delete pTag;
1231 // Updates priority of file if autopriority is activated
1232 void CKnownFile::UpdateAutoUpPriority()
1234 if (IsAutoUpPriority()) {
1235 uint32 queued = GetQueuedCount();
1236 uint8 priority = PR_NORMAL;
1238 if (queued > 20) {
1239 priority = PR_LOW;
1240 } else if (queued > 1) {
1241 priority = PR_NORMAL;
1242 } else {
1243 priority = PR_HIGH;
1246 if (GetUpPriority() != priority) {
1247 SetUpPriority(priority, false);
1248 Notify_SharedFilesUpdateItem(this);
1253 void CKnownFile::SetFileCommentRating(const wxString& strNewComment, int8 iNewRating)
1255 if (m_strComment != strNewComment || m_iRating != iNewRating) {
1256 SetLastPublishTimeKadNotes(0);
1257 wxString strCfgPath = wxT("/") + m_abyFileHash.Encode() + wxT("/");
1259 wxConfigBase* cfg = wxConfigBase::Get();
1260 if (strNewComment.IsEmpty() && iNewRating == 0) {
1261 cfg->DeleteGroup(strCfgPath);
1262 } else {
1263 cfg->Write( strCfgPath + wxT("Comment"), strNewComment);
1264 cfg->Write( strCfgPath + wxT("Rate"), (int)iNewRating);
1267 m_strComment = strNewComment;
1268 m_iRating = iNewRating;
1270 SourceSet::iterator it = m_ClientUploadList.begin();
1271 for ( ; it != m_ClientUploadList.end(); it++ ) {
1272 it->SetCommentDirty();
1278 void CKnownFile::SetUpPriority(uint8 iNewUpPriority, bool m_bsave){
1279 m_iUpPriority = iNewUpPriority;
1280 if( IsPartFile() && m_bsave ) {
1281 ((CPartFile*)this)->SavePartFile();
1285 void CKnownFile::SetPublishedED2K(bool val){
1286 m_PublishedED2K = val;
1287 Notify_SharedFilesUpdateItem(this);
1290 bool CKnownFile::PublishNotes()
1292 if(m_lastPublishTimeKadNotes > (uint32)time(NULL)) {
1293 return false;
1296 if(!GetFileComment().IsEmpty()) {
1297 m_lastPublishTimeKadNotes = (uint32)time(NULL)+KADEMLIAREPUBLISHTIMEN;
1298 return true;
1301 if(GetFileRating() != 0) {
1302 m_lastPublishTimeKadNotes = (uint32)time(NULL)+KADEMLIAREPUBLISHTIMEN;
1303 return true;
1306 return false;
1309 bool CKnownFile::PublishSrc()
1311 uint32 lastBuddyIP = 0;
1313 if( theApp->IsFirewalled() ) {
1314 CUpDownClient* buddy = theApp->clientlist->GetBuddy();
1315 if( buddy ) {
1316 lastBuddyIP = theApp->clientlist->GetBuddy()->GetIP();
1317 if( lastBuddyIP != m_lastBuddyIP ) {
1318 SetLastPublishTimeKadSrc( (uint32)time(NULL)+KADEMLIAREPUBLISHTIMES, lastBuddyIP );
1319 return true;
1321 } else {
1322 return false;
1326 if(m_lastPublishTimeKadSrc > (uint32)time(NULL)) {
1327 return false;
1330 SetLastPublishTimeKadSrc((uint32)time(NULL)+KADEMLIAREPUBLISHTIMES,lastBuddyIP);
1331 return true;
1335 void CKnownFile::UpdatePartsInfo()
1337 // Cache part count
1338 uint16 partcount = GetPartCount();
1339 bool flag = (time(NULL) - m_nCompleteSourcesTime > 0);
1341 // Ensure the frequency-list is ready
1342 if ( m_AvailPartFrequency.size() != GetPartCount() ) {
1343 m_AvailPartFrequency.clear();
1344 m_AvailPartFrequency.insert(m_AvailPartFrequency.begin(), GetPartCount(), 0);
1347 if (flag) {
1348 ArrayOfUInts16 count;
1349 count.reserve(m_ClientUploadList.size());
1351 SourceSet::iterator it = m_ClientUploadList.begin();
1352 for ( ; it != m_ClientUploadList.end(); it++ ) {
1353 CUpDownClient* client = it->GetClient();
1354 if ( !client->GetUpPartStatus().empty() && client->GetUpPartCount() == partcount ) {
1355 count.push_back(client->GetUpCompleteSourcesCount());
1359 m_nCompleteSourcesCount = m_nCompleteSourcesCountLo = m_nCompleteSourcesCountHi = 0;
1361 if( partcount > 0) {
1362 m_nCompleteSourcesCount = m_AvailPartFrequency[0];
1364 for (uint16 i = 1; i < partcount; ++i) {
1365 if( m_nCompleteSourcesCount > m_AvailPartFrequency[i]) {
1366 m_nCompleteSourcesCount = m_AvailPartFrequency[i];
1369 count.push_back(m_nCompleteSourcesCount);
1371 int32 n = count.size();
1372 if (n > 0) {
1373 std::sort(count.begin(), count.end(), std::less<uint16>());
1375 // calculate range
1376 int i = n >> 1; // (n / 2)
1377 int j = (n * 3) >> 2; // (n * 3) / 4
1378 int k = (n * 7) >> 3; // (n * 7) / 8
1380 // For complete files, trust the people your uploading to more...
1382 // For low guess and normal guess count
1383 // - If we see more sources then the guessed low and
1384 // normal, use what we see.
1385 // - If we see less sources then the guessed low,
1386 // adjust network accounts for 100%, we account for
1387 // 0% with what we see and make sure we are still
1388 // above the normal.
1389 // For high guess
1390 // Adjust 100% network and 0% what we see.
1391 if (n < 20) {
1392 if ( count[i] < m_nCompleteSourcesCount ) {
1393 m_nCompleteSourcesCountLo = m_nCompleteSourcesCount;
1394 } else {
1395 m_nCompleteSourcesCountLo = count[i];
1397 m_nCompleteSourcesCount= m_nCompleteSourcesCountLo;
1398 m_nCompleteSourcesCountHi = count[j];
1399 if( m_nCompleteSourcesCountHi < m_nCompleteSourcesCount ) {
1400 m_nCompleteSourcesCountHi = m_nCompleteSourcesCount;
1402 } else {
1403 // Many sources..
1404 // For low guess
1405 // Use what we see.
1406 // For normal guess
1407 // Adjust network accounts for 100%, we account for
1408 // 0% with what we see and make sure we are still above the low.
1409 // For high guess
1410 // Adjust network accounts for 100%, we account for 0%
1411 // with what we see and make sure we are still above the normal.
1413 m_nCompleteSourcesCountLo = m_nCompleteSourcesCount;
1414 m_nCompleteSourcesCount = count[j];
1415 if( m_nCompleteSourcesCount < m_nCompleteSourcesCountLo ) {
1416 m_nCompleteSourcesCount = m_nCompleteSourcesCountLo;
1418 m_nCompleteSourcesCountHi= count[k];
1419 if( m_nCompleteSourcesCountHi < m_nCompleteSourcesCount ) {
1420 m_nCompleteSourcesCountHi = m_nCompleteSourcesCount;
1424 m_nCompleteSourcesTime = time(NULL) + (60);
1427 Notify_SharedFilesUpdateItem(this);
1431 void CKnownFile::UpdateUpPartsFrequency( CUpDownClient* client, bool increment )
1433 if ( m_AvailPartFrequency.size() != GetPartCount() ) {
1434 m_AvailPartFrequency.clear();
1435 m_AvailPartFrequency.insert(m_AvailPartFrequency.begin(), GetPartCount(), 0);
1436 if ( !increment ) {
1437 return;
1441 const BitVector& freq = client->GetUpPartStatus();
1442 unsigned int size = freq.size();
1443 if ( size != m_AvailPartFrequency.size() ) {
1444 return;
1447 if ( increment ) {
1448 for ( unsigned int i = 0; i < size; ++i ) {
1449 if ( freq.get(i) ) {
1450 m_AvailPartFrequency[i]++;
1453 } else {
1454 for ( unsigned int i = 0; i < size; ++i ) {
1455 if ( freq.get(i) ) {
1456 m_AvailPartFrequency[i]--;
1462 void CKnownFile::ClearPriority() {
1463 if ( !m_bAutoUpPriority ) return;
1464 m_iUpPriority = ( m_bAutoUpPriority ) ? PR_HIGH : PR_NORMAL;
1465 UpdateAutoUpPriority();
1468 void GuessAndRemoveExt(CPath& name)
1470 wxString ext = name.GetExt();
1472 // Remove common two-part extensions, such as "tar.gz"
1473 if (ext == wxT("gz") || ext == wxT("bz2")) {
1474 name = name.RemoveExt();
1475 if (name.GetExt() == wxT("tar")) {
1476 name = name.RemoveExt();
1478 // might be an extension if length == 3
1479 // and also remove some common non-three-character extensions
1480 } else if (ext.Length() == 3 ||
1481 ext == wxT("7z") ||
1482 ext == wxT("rm") ||
1483 ext == wxT("jpeg") ||
1484 ext == wxT("mpeg")
1486 name = name.RemoveExt();
1490 void CKnownFile::SetFileName(const CPath& filename)
1492 CAbstractFile::SetFileName(filename);
1493 wordlist.clear();
1494 // Don't publish extension. That'd kill the node indexing e.g. "avi".
1495 CPath tmpName = GetFileName();
1496 GuessAndRemoveExt(tmpName);
1497 Kademlia::CSearchManager::GetWords(tmpName.GetPrintable(), &wordlist);
1500 #endif // CLIENT_GUI
1502 //For File Comment //
1503 void CKnownFile::LoadComment() const
1505 #ifndef CLIENT_GUI
1506 wxString strCfgPath = wxT("/") + m_abyFileHash.Encode() + wxT("/");
1508 wxConfigBase* cfg = wxConfigBase::Get();
1510 m_strComment = cfg->Read( strCfgPath + wxT("Comment"), wxEmptyString);
1511 m_iRating = cfg->Read( strCfgPath + wxT("Rate"), 0l);
1512 #endif
1514 m_bCommentLoaded = true;
1518 wxString CKnownFile::GetAICHMasterHash() const
1520 #ifdef CLIENT_GUI
1521 return m_AICHMasterHash;
1522 #else
1523 if (HasProperAICHHashSet()) {
1524 return m_pAICHHashSet->GetMasterHash().GetString();
1527 return wxEmptyString;
1528 #endif
1532 bool CKnownFile::HasProperAICHHashSet() const
1534 #ifdef CLIENT_GUI
1535 return m_AICHMasterHash.Length() != 0;
1536 #else
1537 return m_pAICHHashSet->HasValidMasterHash() &&
1538 (m_pAICHHashSet->GetStatus() == AICH_HASHSETCOMPLETE ||
1539 m_pAICHHashSet->GetStatus() == AICH_VERIFIED);
1540 #endif
1543 wxString CKnownFile::GetFeedback() const
1545 return wxString(_("File name")) + wxT(": ") + GetFileName().GetPrintable() + wxT("\n")
1546 + _("File size") + wxT(": ") + CastItoXBytes(GetFileSize()) + wxT("\n")
1547 + _("Share ratio") + CFormat(wxT(": %.2f%%\n")) % (((double)statistic.GetAllTimeTransferred() / (double)GetFileSize()) * 100.0)
1548 + _("Uploaded") + wxT(": ") + CastItoXBytes(statistic.GetTransferred()) + wxT(" (") + CastItoXBytes(statistic.GetAllTimeTransferred()) + wxT(")\n")
1549 + _("Requested") + CFormat(wxT(": %u (%u)\n")) % statistic.GetRequests() % statistic.GetAllTimeRequests()
1550 + _("Accepted") + CFormat(wxT(": %u (%u)\n")) % statistic.GetAccepts() % statistic.GetAllTimeAccepts()
1551 + _("On Queue") + CFormat(wxT(": %u\n")) % GetQueuedCount()
1552 + _("Complete sources") + CFormat(wxT(": %u\n")) % m_nCompleteSourcesCount;
1555 // File_checked_for_headers