2 // This file is part of the aMule Project.
4 // Copyright (c) 2003-2008 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2008 Merkur ( devs@emule-project.net / http://www.emule-project.net )
7 // Any parts of this program derived from the xMule, lMule or eMule project,
8 // or contributed by third-party developers are copyrighted by their
11 // This program is free software; you can redistribute it and/or modify
12 // it under the terms of the GNU General Public License as published by
13 // the Free Software Foundation; either version 2 of the License, or
14 // (at your option) any later version.
16 // This program is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 // GNU General Public License for more details.
21 // You should have received a copy of the GNU General Public License
22 // along with this program; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
30 #include "KnownFile.h" // Needed for CKnownFile
31 #include "CFile.h" // Needed for CFile
33 #include "OtherStructs.h" // Needed for Gap_Struct
34 #include "DeadSourceList.h" // Needed for CDeadSourceList
44 //#define BUFFER_SIZE_LIMIT 500000 // Max bytes before forcing a flush
45 #define BUFFER_TIME_LIMIT 60000 // Max milliseconds before forcing a flush
47 #define STATES_COUNT 13
49 // Ok, eMule and aMule are building incompatible backup files because
50 // of the different name. aMule was using ".BAK" and eMule ".bak".
51 // This should fix it.
52 #define PARTMET_BAK_EXT wxT(".bak")
54 enum EPartFileFormat
{
72 SFileRating(const wxString
&u
, const wxString
&f
, sint16 r
, const wxString
&c
);
73 SFileRating(const SFileRating
&fr
);
74 SFileRating(const CUpDownClient
&client
);
78 typedef std::list
<SFileRating
> FileRatingList
;
86 SourcenameItem(const wxString
&n
, long c
)
91 typedef std::list
<SourcenameItem
> SourcenameItemList
;
93 class CPartFile
: public CKnownFile
{
95 typedef std::list
<Requested_Block_Struct
*> CReqBlockPtrList
;
99 CPartFile(CEC_PartFile_Tag
*tag
);
101 virtual void SetFileName(const CPath
& filename
);
103 CPartFile(CSearchFile
* searchresult
); //used when downloading a new file
104 CPartFile(const CED2KFileLink
* fileLink
);
105 virtual ~CPartFile();
107 bool CreateFromFile(wxString
WXUNUSED(directory
), wxString
WXUNUSED(filename
), void* WXUNUSED(pvProgressParam
)) {return false;}// not supported in this class
108 void SetPartFileStatus(uint8 newstatus
);
109 virtual bool LoadFromFile(const CFileDataIO
* WXUNUSED(file
)) { return false; }
110 bool WriteToFile(CFileDataIO
* WXUNUSED(file
)) { return false; }
111 bool IsPartFile() const { return !(status
== PS_COMPLETE
); }
112 uint32
Process(uint32 reducedownload
, uint8 m_icounter
);
113 uint8
LoadPartFile(const CPath
& in_directory
, const CPath
& filename
, bool from_backup
= false, bool getsizeonly
= false);
114 bool SavePartFile(bool Initial
= false);
115 void PartFileHashFinished(CKnownFile
* result
);
116 bool HashSinglePart(uint16 partnumber
); // true = ok , false = corrupted
118 bool CheckShowItemInGivenCat(int inCategory
);
120 bool IsComplete(uint64 start
, uint64 end
) { return m_gaplist
.IsComplete(start
, end
); }
121 bool IsComplete(uint16 part
) { return m_gaplist
.IsComplete(part
); }
123 void UpdateCompletedInfos();
125 bool GetNextRequestedBlock(CUpDownClient
* sender
, std::vector
<Requested_Block_Struct
*>& toadd
, uint16
& count
);
126 void WritePartStatus(CMemFile
* file
);
127 void WriteCompleteSourcesCount(CMemFile
* file
);
128 static bool CanAddSource(uint32 userid
, uint16 port
, uint32 serverip
, uint16 serverport
, uint8
* pdebug_lowiddropped
= NULL
, bool ed2kID
= true);
129 void AddSources(CMemFile
& sources
, uint32 serverip
, uint16 serverport
, unsigned origin
, bool bWithObfuscationAndHash
);
131 uint8
GetStatus() const { return status
; }
132 uint8
GetStatus(bool /*ignorepause = false*/) const { return status
; }
134 uint8
GetStatus(bool ignorepause
= false) const;
136 virtual void UpdatePartsInfo();
137 const CPath
& GetPartMetFileName() const { return m_partmetfilename
; }
138 uint64
GetTransferred() const { return transferred
; }
139 const CPath
& GetFullName() const { return m_fullname
; }
140 float GetKBpsDown() const { return kBpsDown
; }
141 double GetPercentCompleted() const { return percentcompleted
; }
144 uint16
GetSourceCount() const { return (uint16
)m_SrcList
.size(); }
145 uint16
GetSrcA4AFCount() const { return (uint16
)m_A4AFsrclist
.size(); }
147 uint16 m_source_count
, m_a4af_source_count
;
148 uint16
GetSourceCount() const { return m_source_count
; }
149 uint16
GetSrcA4AFCount() const { return m_a4af_source_count
; }
151 uint16
GetTransferingSrcCount() const { return transferingsrc
; }
152 uint16
GetNotCurrentSourcesCount() const { return m_notCurrentSources
; };
153 void SetNotCurrentSourcesCount(uint16 new_count
) { m_notCurrentSources
= new_count
; };
154 uint16
GetValidSourcesCount() const { return m_validSources
; };
156 uint64
GetNeededSpace();
158 virtual wxString
GetFeedback() const;
160 wxString
getPartfileStatus() const; //<<--9/21/02
161 sint32
getTimeRemaining() const; //<<--9/21/02
162 time_t lastseencomplete
;
163 int getPartfileStatusRang() const;
165 // Barry - Added as replacement for BlockReceived to buffer data before writing to disk
166 uint32
WriteToBuffer(uint32 transize
, byte
*data
, uint64 start
, uint64 end
, Requested_Block_Struct
*block
);
167 void FlushBuffer(bool fromAICHRecoveryDataAvailable
= false);
169 // Barry - Is archive recovery in progress
170 volatile bool m_bRecoveringArchive
;
172 // Barry - Added to prevent list containing deleted blocks on shutdown
173 void RemoveAllRequestedBlocks(void);
175 void RemoveBlockFromList(uint64 start
,uint64 end
);
176 void RemoveAllSources(bool bTryToSwap
);
178 void StopFile(bool bCancel
= false);
179 void PauseFile(bool bInsufficient
= false);
182 virtual CPacket
* CreateSrcInfoPacket(const CUpDownClient
* forClient
, uint8 byRequestedVersion
, uint16 nRequestedOptions
);
183 void AddClientSources(CMemFile
* sources
, unsigned nSourceFrom
, uint8 uClientSXVersion
, bool bSourceExchange2
, const CUpDownClient
* pClient
= NULL
);
185 bool PreviewAvailable();
186 uint16
GetAvailablePartCount() const { return m_availablePartsCount
; }
187 uint32
GetLastAnsweredTime() const { return m_ClientSrcAnswered
; }
188 void SetLastAnsweredTime();
189 void SetLastAnsweredTimeTimeout();
190 uint64
GetLostDueToCorruption() const { return m_iLostDueToCorruption
; }
191 uint64
GetGainDueToCompression() const { return m_iGainDueToCompression
; }
192 uint32
TotalPacketsSavedDueToICH()const{ return m_iTotalPacketsSavedDueToICH
; }
193 bool IsStopped() const { return this ? m_stopped
: true; }
194 bool IsPaused() const { return m_paused
; }
195 void UpdateFileRatingCommentAvail();
196 bool m_CommentUpdated
;
198 int GetCommonFilePenalty();
199 void UpdateDisplayedInfo(bool force
= false);
201 uint8
GetCategory() const { return m_category
; }
202 void SetCategory(uint8 cat
);
204 volatile bool m_bPreviewing
;
205 void SetDownPriority(uint8 newDownPriority
, bool bSave
= true, bool bRefresh
= true);
206 bool IsAutoDownPriority() const { return m_bAutoDownPriority
; }
207 void SetAutoDownPriority(bool flag
) { m_bAutoDownPriority
= flag
; }
208 void UpdateAutoDownPriority();
209 uint8
GetDownPriority() const { return m_iDownPriority
; }
210 void SetActive(bool bActive
);
211 uint32
GetDlActiveTime() const;
212 bool GetInsufficient() const { return m_insufficient
; }
214 void CompleteFileEnded(bool errorOccured
, const CPath
& newname
);
216 bool RemoveSource(CUpDownClient
* toremove
, bool updatewindow
= true, bool bDoStatsUpdate
= true);
218 void RequestAICHRecovery(uint16 nPart
);
219 void AICHRecoveryDataAvailable(uint16 nPart
);
222 * This function is used to update source-counts.
224 * @param oldState The old state of the client, or -1 to ignore.
225 * @param newState The new state of the client, or -1 to ignore.
227 * Call this function for a client belonging to this file, which has changed
228 * its state. The value -1 can be used to make the function ignore one of
231 * AddSource and DelSource takes care of calling this function when a source is
232 * removed, so there's no need to call this function when calling either of those.
234 void ClientStateChanged( int oldState
, int newState
);
236 bool AddSource( CUpDownClient
* client
);
237 bool DelSource( CUpDownClient
* client
);
240 * Updates the requency of avilable parts from with the data the client provides.
242 * @param client The clients whoose available parts should be considered.
243 * @param increment If true, the counts are incremented, otherwise they are decremented.
245 * This functions updates the frequency list of file-parts, using the clients
246 * parts-status. This function should be called by clients every time they update their
247 * parts-status, or when they are added or removed from the file.
249 void UpdatePartsFrequency( CUpDownClient
* client
, bool increment
);
251 ArrayOfUInts16 m_SrcpartFrequency
;
253 void SetShowSources( bool val
) { m_showSources
= val
; }
254 bool ShowSources() const { return m_showSources
; }
256 typedef std::set
<CUpDownClient
*> SourceSet
;
258 const SourceSet
& GetSourceList() const { return m_SrcList
; }
259 const SourceSet
& GetA4AFList() const { return m_A4AFsrclist
; }
261 const CReqBlockPtrList
GetRequestedBlockList() const { return m_requestedblocks_list
; }
263 // LEGACY - to be removed when possible
266 void Init(const CGapList
* gaplist
) { m_gaplist
= gaplist
; }
267 class const_iterator
{
268 CGapList::const_iterator m_it
;
272 const_iterator(const CGapList::const_iterator
& it
) { m_it
= it
; };
273 bool operator != (const const_iterator
& it
) { return m_it
!= it
.m_it
; }
274 const_iterator
& operator ++ () { ++ m_it
; return *this; }
275 Gap_Struct
* operator * () {
276 m_gap
.start
= m_it
.start();
277 m_gap
.end
= m_it
.end();
281 const_iterator
begin() const { return const_iterator(m_gaplist
->begin()); }
282 const_iterator
end() const { return const_iterator(m_gaplist
->end()); }
283 bool empty() const { return m_gaplist
->IsComplete(); }
284 uint32
size() const { return m_gaplist
->size(); }
287 const CGapList
* m_gaplist
;
289 // this function must stay, but return the m_gaplist instead
290 const CGapPtrList
& GetGapList() const { return m_gapptrlist
; }
292 const CGapList
& GetNewGapList() const { return m_gaplist
; }
294 CGapPtrList m_gapptrlist
;
299 * Adds a source to the list of dead sources.
301 * @param client The source to be recorded as dead for this file.
303 void AddDeadSource(const CUpDownClient
* client
);
306 * Checks if a source is recorded as being dead for this file.
308 * @param client The client to evaluate.
309 * @return True if dead, false otherwise.
311 * Sources that are dead are not to be considered valid
312 * sources and should not be added to the partfile.
314 bool IsDeadSource(const CUpDownClient
* client
);
317 uint16
GetMaxSources() const;
318 uint16
GetMaxSourcePerFileSoft() const;
319 uint16
GetMaxSourcePerFileUDP() const;
321 const FileRatingList
&GetRatingAndComments();
323 void AllocationFinished();
325 CFile m_hpartfile
; //permanent opened handle to avoid write conflicts
326 //! A local list of sources that are invalid for this file.
328 CDeadSourceList m_deadSources
;
331 uint16 m_notCurrentSources
;
335 uint32 m_validSources
;
337 void AddGap(uint64 start
, uint64 end
);
338 void AddGap(uint16 part
);
339 void FillGap(uint64 start
, uint64 end
);
340 void FillGap(uint16 part
);
341 bool GetNextEmptyBlockInPart(uint16 partnumber
,Requested_Block_Struct
* result
);
342 bool IsAlreadyRequested(uint64 start
, uint64 end
);
343 void CompleteFile(bool hashingdone
);
344 void CreatePartFile();
347 bool CheckFreeDiskSpace( uint64 neededSpace
= 0 );
349 bool IsCorruptedPart(uint16 partnumber
);
351 uint32 m_iLastPausePurge
;
353 uint16 m_anStates
[STATES_COUNT
];
354 uint16 transferingsrc
;
355 uint64 completedsize
;
358 uint64 m_iLostDueToCorruption
;
359 uint64 m_iGainDueToCompression
;
360 uint32 m_iTotalPacketsSavedDueToICH
;
362 CPath m_fullname
; // path/name of the met file
363 CPath m_partmetfilename
; // name of the met file
364 CPath m_PartPath
; // path/name of the partfile
368 uint8 m_iDownPriority
;
369 bool m_bAutoDownPriority
;
371 uint32 lastpurgetime
;
372 uint32 m_LastNoNeededCheck
;
374 CReqBlockPtrList m_requestedblocks_list
;
375 double percentcompleted
;
376 std::list
<uint16
> m_corrupted_list
;
377 uint16 m_availablePartsCount
;
378 uint32 m_ClientSrcAnswered
;
379 bool m_bPercentUpdated
;
381 void PerformFileComplete();
383 uint32 m_lastRefreshedDLDisplay
;
385 // Buffered data to be written
386 std::list
<class PartFileBufferedData
*> m_BufferedData_list
;
388 uint32 m_nTotalBufferData
;
389 uint32 m_nLastBufferFlushTime
;
392 uint32 m_nDlActiveTime
;
397 SourceSet m_A4AFsrclist
;
398 bool m_hashsetneeded
;
399 uint32 m_lastsearchtime
;
400 bool m_localSrcReqQueued
;
402 FileRatingList m_FileRatingList
;
404 SourcenameItemList m_SourcenameItem_list
;
406 const SourcenameItemList
&GetSourcenameItemList() { return m_SourcenameItem_list
; }
407 void ClearSourcenameItemList() { m_SourcenameItem_list
.clear(); }
408 void AddSourcenameItemList(const wxString
&name
, long count
) { m_SourcenameItem_list
.push_back(SourcenameItem(name
, count
)); }
411 const FileRatingList
&GetFileRatingList() { return m_FileRatingList
; }
412 void ClearFileRatingList() { m_FileRatingList
.clear(); }
413 void AddFileRatingList(const wxString
& u
, const wxString
& f
, sint16 r
, const wxString
& c
) {
414 m_FileRatingList
.push_back(SFileRating(u
, f
, r
, c
)); }
416 bool IsHashSetNeeded() const { return m_hashsetneeded
; }
417 void SetHashSetNeeded(bool value
) { m_hashsetneeded
= value
; }
419 uint64
GetCompletedSize() const { return completedsize
; }
420 void SetCompletedSize(uint64 size
) { completedsize
= size
; }
422 bool IsLocalSrcRequestQueued() const { return m_localSrcReqQueued
; }
423 void SetLocalSrcRequestQueued(bool value
) { m_localSrcReqQueued
= value
; }
425 void AddA4AFSource(CUpDownClient
* src
) { m_A4AFsrclist
.insert(src
); }
426 bool RemoveA4AFSource(CUpDownClient
* src
) { return (m_A4AFsrclist
.erase(src
) > 0); }
428 uint32
GetLastSearchTime() const { return m_lastsearchtime
; }
429 void SetLastSearchTime(uint32 time
) { m_lastsearchtime
= time
; }
431 // void CleanUpSources( bool noNeeded, bool fullQueue = false, bool highQueue = false );
433 void AddDownloadingSource(CUpDownClient
* client
);
435 void RemoveDownloadingSource(CUpDownClient
* client
);
436 void SetStatus(uint8 in
);
437 void StopPausedFile();
439 // [sivka / Tarod] Imported from eMule 0.30c (Creteil) ...
440 void SetA4AFAuto(bool in
) { m_is_A4AF_auto
= in
; }
441 bool IsA4AFAuto() const { return m_is_A4AF_auto
; }
443 // Kry -Sources seeds
444 void SaveSourceSeeds();
445 void LoadSourceSeeds();
447 // Dropping slow sources
448 CUpDownClient
* GetSlowerDownloadingClient(uint32 speed
, CUpDownClient
* caller
);
450 // Read data for sharing
451 bool ReadData(class CFileArea
& area
, uint64 offset
, uint32 toread
);
454 /* downloading sources list */
455 CClientPtrList m_downloadingSourcesList
;
458 uint32 m_LastSearchTimeKad
;
459 uint8 m_TotalSearchesKad
;
461 friend class CDownQueueRem
;
462 friend class CPartFileConvert
;
466 // File_checked_for_headers