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 "FileAutoClose.h" // Needed for CFileAutoClose
33 #include "OtherStructs.h" // Needed for Requested_Block_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 // Ok, eMule and aMule are building incompatible backup files because
48 // of the different name. aMule was using ".BAK" and eMule ".bak".
49 // This should fix it.
50 #define PARTMET_BAK_EXT wxT(".bak")
52 enum EPartFileFormat
{
70 SFileRating(const wxString
&u
, const wxString
&f
, sint16 r
, const wxString
&c
);
71 SFileRating(const SFileRating
&fr
);
72 SFileRating(const CUpDownClient
&client
);
76 typedef std::list
<SFileRating
> FileRatingList
;
84 SourcenameItem(const wxString
&n
= EmptyString
, int c
= 0)
89 typedef std::map
<uint32
,SourcenameItem
> SourcenameItemMap
;
91 class CPartFile
: public CKnownFile
{
93 typedef std::list
<Requested_Block_Struct
*> CReqBlockPtrList
;
97 CPartFile(CEC_PartFile_Tag
*tag
);
99 virtual void SetFileName(const CPath
& filename
);
101 CPartFile(CSearchFile
* searchresult
); //used when downloading a new file
102 CPartFile(const CED2KFileLink
* fileLink
);
103 virtual ~CPartFile();
105 bool CreateFromFile(wxString
WXUNUSED(directory
), wxString
WXUNUSED(filename
), void* WXUNUSED(pvProgressParam
)) {return false;}// not supported in this class
106 virtual bool LoadFromFile(const CFileDataIO
* WXUNUSED(file
)) { return false; }
107 bool WriteToFile(CFileDataIO
* WXUNUSED(file
)) { return false; }
109 // virtual functions for CKnownFile and CPartFile:
110 bool IsPartFile() const { return status
!= PS_COMPLETE
; } // true if not completed
111 bool IsCompleted() const { return status
== PS_COMPLETE
; } // true if completed
112 bool IsCPartFile() const { return true; } // true if it's a CPartFile
114 uint32
Process(uint32 reducedownload
, uint8 m_icounter
);
115 uint8
LoadPartFile(const CPath
& in_directory
, const CPath
& filename
, bool from_backup
= false, bool getsizeonly
= false);
116 bool SavePartFile(bool Initial
= false);
117 void PartFileHashFinished(CKnownFile
* result
);
118 bool HashSinglePart(uint16 partnumber
); // true = ok , false = corrupted
120 bool CheckShowItemInGivenCat(int inCategory
);
122 bool IsComplete(uint64 start
, uint64 end
) { return m_gaplist
.IsComplete(start
, end
); }
123 bool IsComplete(uint16 part
) { return m_gaplist
.IsComplete(part
); }
125 void UpdateCompletedInfos();
127 bool GetNextRequestedBlock(CUpDownClient
* sender
, std::vector
<Requested_Block_Struct
*>& toadd
, uint16
& count
);
128 void WritePartStatus(CMemFile
* file
);
129 void WriteCompleteSourcesCount(CMemFile
* file
);
130 static bool CanAddSource(uint32 userid
, uint16 port
, uint32 serverip
, uint16 serverport
, uint8
* pdebug_lowiddropped
= NULL
, bool ed2kID
= true);
131 void AddSources(CMemFile
& sources
, uint32 serverip
, uint16 serverport
, unsigned origin
, bool bWithObfuscationAndHash
);
133 uint8
GetStatus() const { return status
; }
134 uint8
GetStatus(bool /*ignorepause = false*/) const { return status
; }
136 uint8
GetStatus(bool ignorepause
= false) const;
138 virtual void UpdatePartsInfo();
139 const CPath
& GetPartMetFileName() const { return m_partmetfilename
; }
140 uint16
GetPartMetNumber() const;
141 uint64
GetTransferred() const { return transferred
; }
142 const CPath
& GetFullName() const { return m_fullname
; }
143 float GetKBpsDown() const { return kBpsDown
; }
144 double GetPercentCompleted() const { return percentcompleted
; }
147 uint16
GetSourceCount() const { return (uint16
)m_SrcList
.size(); }
148 uint16
GetSrcA4AFCount() const { return (uint16
)m_A4AFsrclist
.size(); }
150 uint16 m_source_count
, m_a4af_source_count
;
151 uint16
GetSourceCount() const { return m_source_count
; }
152 uint16
GetSrcA4AFCount() const { return m_a4af_source_count
; }
154 uint16
GetTransferingSrcCount() const { return transferingsrc
; }
155 uint16
GetNotCurrentSourcesCount() const { return m_notCurrentSources
; };
156 //void SetNotCurrentSourcesCount(uint16 new_count) { m_notCurrentSources = new_count; };
157 uint16
GetValidSourcesCount() const { return m_validSources
; };
159 uint64
GetNeededSpace();
161 virtual wxString
GetFeedback() const;
163 wxString
getPartfileStatus() const; //<<--9/21/02
164 sint32
getTimeRemaining() const; //<<--9/21/02
165 time_t lastseencomplete
;
166 int getPartfileStatusRang() const;
168 // Barry - Added as replacement for BlockReceived to buffer data before writing to disk
169 uint32
WriteToBuffer(uint32 transize
, byte
*data
, uint64 start
, uint64 end
, Requested_Block_Struct
*block
, const CUpDownClient
* client
);
170 void FlushBuffer(bool fromAICHRecoveryDataAvailable
= false);
172 // Barry - Is archive recovery in progress
173 volatile bool m_bRecoveringArchive
;
175 // Barry - Added to prevent list containing deleted blocks on shutdown
176 void RemoveAllRequestedBlocks(void);
178 void RemoveBlockFromList(uint64 start
,uint64 end
);
179 void RemoveAllSources(bool bTryToSwap
);
181 void StopFile(bool bCancel
= false);
182 void PauseFile(bool bInsufficient
= false);
185 virtual CPacket
* CreateSrcInfoPacket(const CUpDownClient
* forClient
, uint8 byRequestedVersion
, uint16 nRequestedOptions
);
186 void AddClientSources(CMemFile
* sources
, unsigned nSourceFrom
, uint8 uClientSXVersion
, bool bSourceExchange2
, const CUpDownClient
* pClient
= NULL
);
188 bool PreviewAvailable();
189 uint16
GetAvailablePartCount() const { return m_availablePartsCount
; }
190 uint32
GetLastAnsweredTime() const { return m_ClientSrcAnswered
; }
191 void SetLastAnsweredTime();
192 void SetLastAnsweredTimeTimeout();
193 uint64
GetLostDueToCorruption() const { return m_iLostDueToCorruption
; }
194 uint64
GetGainDueToCompression() const { return m_iGainDueToCompression
; }
195 uint32
TotalPacketsSavedDueToICH()const{ return m_iTotalPacketsSavedDueToICH
; }
196 bool IsStopped() const { return this ? m_stopped
: true; }
197 bool IsPaused() const { return m_paused
; }
198 void UpdateFileRatingCommentAvail();
200 int GetCommonFilePenalty();
201 void UpdateDisplayedInfo(bool force
= false);
203 uint8
GetCategory() const { return m_category
; }
204 void SetCategory(uint8 cat
);
205 void RemoveCategory(uint8 cat
);
207 volatile bool m_bPreviewing
;
208 void SetDownPriority(uint8 newDownPriority
, bool bSave
= true, bool bRefresh
= true);
209 bool IsAutoDownPriority() const { return m_bAutoDownPriority
; }
210 void SetAutoDownPriority(bool flag
) { m_bAutoDownPriority
= flag
; }
211 void UpdateAutoDownPriority();
212 uint8
GetDownPriority() const { return m_iDownPriority
; }
213 void SetActive(bool bActive
);
214 uint32
GetDlActiveTime() const;
215 bool GetInsufficient() const { return m_insufficient
; }
217 void CompleteFileEnded(bool errorOccured
, const CPath
& newname
);
219 bool RemoveSource(CUpDownClient
* toremove
, bool updatewindow
= true, bool bDoStatsUpdate
= true);
221 void RequestAICHRecovery(uint16 nPart
);
222 void AICHRecoveryDataAvailable(uint16 nPart
);
225 * This function is used to update source-counts.
227 * @param oldState The old state of the client, or -1 to ignore.
228 * @param newState The new state of the client, or -1 to ignore.
230 * Call this function for a client belonging to this file, which has changed
231 * its state. The value -1 can be used to make the function ignore one of
234 * AddSource and DelSource takes care of calling this function when a source is
235 * removed, so there's no need to call this function when calling either of those.
237 void ClientStateChanged( int oldState
, int newState
);
239 bool AddSource( CUpDownClient
* client
);
240 bool DelSource( CUpDownClient
* client
);
243 * Updates the requency of avilable parts from with the data the client provides.
245 * @param client The clients whoose available parts should be considered.
246 * @param increment If true, the counts are incremented, otherwise they are decremented.
248 * This functions updates the frequency list of file-parts, using the clients
249 * parts-status. This function should be called by clients every time they update their
250 * parts-status, or when they are added or removed from the file.
252 void UpdatePartsFrequency( CUpDownClient
* client
, bool increment
);
254 ArrayOfUInts16 m_SrcpartFrequency
;
256 const SourceSet
& GetSourceList() const { return m_SrcList
; }
257 const SourceSet
& GetA4AFList() const { return m_A4AFsrclist
; }
258 void ClearA4AFList() { m_A4AFsrclist
.clear(); }
260 const CReqBlockPtrList
GetRequestedBlockList() const { return m_requestedblocks_list
; }
262 const CGapList
& GetGapList() const { return m_gaplist
; }
265 * Adds a source to the list of dead sources.
267 * @param client The source to be recorded as dead for this file.
269 void AddDeadSource(const CUpDownClient
* client
);
272 * Checks if a source is recorded as being dead for this file.
274 * @param client The client to evaluate.
275 * @return True if dead, false otherwise.
277 * Sources that are dead are not to be considered valid
278 * sources and should not be added to the partfile.
280 bool IsDeadSource(const CUpDownClient
* client
);
283 uint16
GetMaxSources() const;
284 uint16
GetMaxSourcePerFileSoft() const;
285 uint16
GetMaxSourcePerFileUDP() const;
287 void GetRatingAndComments(FileRatingList
& list
) const;
289 void AllocationFinished();
292 // partfile handle (opened on demand)
293 CFileAutoClose m_hpartfile
;
294 //! A local list of sources that are invalid for this file.
295 CDeadSourceList m_deadSources
;
297 class CCorruptionBlackBox
* m_CorruptionBlackBox
;
300 uint16 m_notCurrentSources
;
302 uint32 m_validSources
;
304 void AddGap(uint64 start
, uint64 end
);
305 void AddGap(uint16 part
);
306 void FillGap(uint64 start
, uint64 end
);
307 void FillGap(uint16 part
);
308 bool GetNextEmptyBlockInPart(uint16 partnumber
,Requested_Block_Struct
* result
);
309 bool IsAlreadyRequested(uint64 start
, uint64 end
);
310 void CompleteFile(bool hashingdone
);
311 void CreatePartFile();
314 bool CheckFreeDiskSpace( uint64 neededSpace
= 0 );
316 bool IsCorruptedPart(uint16 partnumber
);
318 uint32 m_iLastPausePurge
;
320 uint16 transferingsrc
;
321 uint64 completedsize
;
324 uint64 m_iLostDueToCorruption
;
325 uint64 m_iGainDueToCompression
;
326 uint32 m_iTotalPacketsSavedDueToICH
;
328 CPath m_fullname
; // path/name of the met file
329 CPath m_partmetfilename
; // name of the met file
330 CPath m_PartPath
; // path/name of the partfile
334 uint8 m_iDownPriority
;
335 bool m_bAutoDownPriority
;
337 uint32 lastpurgetime
;
338 uint32 m_LastNoNeededCheck
;
340 CReqBlockPtrList m_requestedblocks_list
;
341 double percentcompleted
;
342 std::list
<uint16
> m_corrupted_list
;
343 uint16 m_availablePartsCount
;
344 uint32 m_ClientSrcAnswered
;
345 bool m_bPercentUpdated
;
347 void PerformFileComplete();
349 uint32 m_lastRefreshedDLDisplay
;
351 // Buffered data to be written
352 std::list
<class PartFileBufferedData
*> m_BufferedData_list
;
354 uint32 m_nTotalBufferData
;
355 uint32 m_nLastBufferFlushTime
;
358 uint32 m_nDlActiveTime
;
363 SourceSet m_A4AFsrclist
;
364 bool m_hashsetneeded
;
365 uint32 m_lastsearchtime
;
366 bool m_localSrcReqQueued
;
369 FileRatingList m_FileRatingList
;
370 const FileRatingList
&GetFileRatingList() { return m_FileRatingList
; }
371 void ClearFileRatingList() { m_FileRatingList
.clear(); }
372 void AddFileRatingList(const wxString
& u
, const wxString
& f
, sint16 r
, const wxString
& c
) {
373 m_FileRatingList
.push_back(SFileRating(u
, f
, r
, c
)); }
376 uint8 m_iDownPriorityEC
;
378 SourcenameItemMap m_SourcenameItemMap
;
380 ListOfUInts32 m_A4AFClientIDs
;
381 ListOfUInts32
& GetA4AFClientIDs() { return m_A4AFClientIDs
; }
383 bool IsShared() const { return m_isShared
; }
384 SourcenameItemMap
&GetSourcenameItemMap() { return m_SourcenameItemMap
; }
385 PartFileEncoderData m_PartFileEncoderData
;
388 bool IsHashSetNeeded() const { return m_hashsetneeded
; }
389 void SetHashSetNeeded(bool value
) { m_hashsetneeded
= value
; }
391 uint64
GetCompletedSize() const { return completedsize
; }
392 void SetCompletedSize(uint64 size
) { completedsize
= size
; }
394 bool IsLocalSrcRequestQueued() const { return m_localSrcReqQueued
; }
395 void SetLocalSrcRequestQueued(bool value
) { m_localSrcReqQueued
= value
; }
397 void AddA4AFSource(CUpDownClient
* src
) { m_A4AFsrclist
.insert(src
); }
398 bool RemoveA4AFSource(CUpDownClient
* src
) { return (m_A4AFsrclist
.erase(src
) > 0); }
400 uint32
GetLastSearchTime() const { return m_lastsearchtime
; }
401 void SetLastSearchTime(uint32 time
) { m_lastsearchtime
= time
; }
403 // void CleanUpSources( bool noNeeded, bool fullQueue = false, bool highQueue = false );
405 void AddDownloadingSource(CUpDownClient
* client
);
407 void RemoveDownloadingSource(CUpDownClient
* client
);
408 void SetStatus(uint8 in
);
409 void StopPausedFile();
411 // [sivka / Tarod] Imported from eMule 0.30c (Creteil) ...
412 void SetA4AFAuto(bool in
) { m_is_A4AF_auto
= in
; }
413 bool IsA4AFAuto() const { return m_is_A4AF_auto
; }
415 // Kry -Sources seeds
416 void SaveSourceSeeds();
417 void LoadSourceSeeds();
419 // Dropping slow sources
420 CUpDownClient
* GetSlowerDownloadingClient(uint32 speed
, CUpDownClient
* caller
);
422 // Read data for sharing
423 bool ReadData(class CFileArea
& area
, uint64 offset
, uint32 toread
);
426 /* downloading sources list */
427 CClientPtrList m_downloadingSourcesList
;
430 uint32 m_LastSearchTimeKad
;
431 uint8 m_TotalSearchesKad
;
433 friend class CKnownFilesRem
;
434 friend class CPartFileConvert
;
438 // File_checked_for_headers