Upstream tarball 9614
[amule.git] / src / PartFile.h
blob1369a8c5ea6447c6480d93b1c99901c816e5f98e
1 //
2 // This file is part of the aMule Project.
3 //
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 )
6 //
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
9 // respective authors.
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.
20 //
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
26 #ifndef PARTFILE_H
27 #define PARTFILE_H
30 #include "KnownFile.h" // Needed for CKnownFile
31 #include "FileAutoClose.h" // Needed for CFileAutoClose
33 #include "OtherStructs.h" // Needed for Gap_Struct
34 #include "DeadSourceList.h" // Needed for CDeadSourceList
35 #include "GapList.h"
38 class CSearchFile;
39 class CUpDownClient;
40 class CMemFile;
41 class CFileDataIO;
42 class CED2KFileLink;
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 {
55 PMT_UNKNOWN = 0,
56 PMT_DEFAULTOLD,
57 PMT_SPLITTED,
58 PMT_NEWOLD,
59 PMT_SHAREAZA,
60 PMT_BADFORMAT
64 class SFileRating
66 public:
67 wxString UserName;
68 wxString FileName;
69 sint16 Rating;
70 wxString Comment;
71 public:
72 SFileRating(const wxString &u, const wxString &f, sint16 r, const wxString &c);
73 SFileRating(const SFileRating &fr);
74 SFileRating(const CUpDownClient &client);
75 ~SFileRating();
78 typedef std::list<SFileRating> FileRatingList;
80 class SourcenameItem
82 public:
83 wxString name;
84 long count;
85 public:
86 SourcenameItem(const wxString &n, long c)
88 name(n), count(c) {}
91 typedef std::list<SourcenameItem> SourcenameItemList;
93 class CPartFile : public CKnownFile {
94 public:
95 typedef std::list<Requested_Block_Struct*> CReqBlockPtrList;
97 CPartFile();
98 #ifdef CLIENT_GUI
99 CPartFile(CEC_PartFile_Tag *tag);
100 #else
101 virtual void SetFileName(const CPath& filename);
102 #endif
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);
130 #ifdef CLIENT_GUI
131 uint8 GetStatus() const { return status; }
132 uint8 GetStatus(bool /*ignorepause = false*/) const { return status; }
133 #else
134 uint8 GetStatus(bool ignorepause = false) const;
135 #endif
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; }
143 #ifndef CLIENT_GUI
144 uint16 GetSourceCount() const { return (uint16)m_SrcList.size(); }
145 uint16 GetSrcA4AFCount() const { return (uint16)m_A4AFsrclist.size(); }
146 #else
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; }
150 #endif
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, const CUpDownClient* client);
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);
177 void Delete();
178 void StopFile(bool bCancel = false);
179 void PauseFile(bool bInsufficient = false);
180 void ResumeFile();
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
229 * the two states.
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
264 class CGapPtrList {
265 public:
266 void Init(const CGapList * gaplist) { m_gaplist = gaplist; }
267 class const_iterator {
268 CGapList::const_iterator m_it;
269 Gap_Struct m_gap;
270 public:
271 const_iterator() {};
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();
278 return & m_gap;
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(); }
286 private:
287 const CGapList * m_gaplist;
289 // this function must stay, but return the m_gaplist instead
290 const CGapPtrList& GetGapList() const { return m_gapptrlist; }
291 // meanwhile use
292 const CGapList& GetNewGapList() const { return m_gaplist; }
293 private:
294 CGapPtrList m_gapptrlist;
295 public:
296 // END LEGACY
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);
316 /* Kad Stuff */
317 uint16 GetMaxSources() const;
318 uint16 GetMaxSourcePerFileSoft() const;
319 uint16 GetMaxSourcePerFileUDP() const;
321 const FileRatingList &GetRatingAndComments();
323 void AllocationFinished();
324 private:
325 #ifndef CLIENT_GUI
326 // partfile handle (opened on demand)
327 CFileAutoClose m_hpartfile;
328 //! A local list of sources that are invalid for this file.
329 CDeadSourceList m_deadSources;
331 class CCorruptionBlackBox* m_CorruptionBlackBox;
332 #endif
334 uint16 m_notCurrentSources;
336 bool m_showSources;
338 uint32 m_validSources;
340 void AddGap(uint64 start, uint64 end);
341 void AddGap(uint16 part);
342 void FillGap(uint64 start, uint64 end);
343 void FillGap(uint16 part);
344 bool GetNextEmptyBlockInPart(uint16 partnumber,Requested_Block_Struct* result);
345 bool IsAlreadyRequested(uint64 start, uint64 end);
346 void CompleteFile(bool hashingdone);
347 void CreatePartFile();
348 void Init();
350 bool CheckFreeDiskSpace( uint64 neededSpace = 0 );
352 bool IsCorruptedPart(uint16 partnumber);
354 uint32 m_iLastPausePurge;
355 uint16 m_count;
356 uint16 m_anStates[STATES_COUNT];
357 uint16 transferingsrc;
358 uint64 completedsize;
359 uint64 transferred;
361 uint64 m_iLostDueToCorruption;
362 uint64 m_iGainDueToCompression;
363 uint32 m_iTotalPacketsSavedDueToICH;
364 float kBpsDown;
365 CPath m_fullname; // path/name of the met file
366 CPath m_partmetfilename; // name of the met file
367 CPath m_PartPath; // path/name of the partfile
368 bool m_paused;
369 bool m_stopped;
370 bool m_insufficient;
371 uint8 m_iDownPriority;
372 bool m_bAutoDownPriority;
373 uint8 status;
374 uint32 lastpurgetime;
375 uint32 m_LastNoNeededCheck;
376 CGapList m_gaplist;
377 CReqBlockPtrList m_requestedblocks_list;
378 double percentcompleted;
379 std::list<uint16> m_corrupted_list;
380 uint16 m_availablePartsCount;
381 uint32 m_ClientSrcAnswered;
382 bool m_bPercentUpdated;
384 void PerformFileComplete();
386 uint32 m_lastRefreshedDLDisplay;
388 // Buffered data to be written
389 std::list<class PartFileBufferedData*> m_BufferedData_list;
391 uint32 m_nTotalBufferData;
392 uint32 m_nLastBufferFlushTime;
394 uint8 m_category;
395 uint32 m_nDlActiveTime;
396 time_t m_tActivated;
397 bool m_is_A4AF_auto;
399 SourceSet m_SrcList;
400 SourceSet m_A4AFsrclist;
401 bool m_hashsetneeded;
402 uint32 m_lastsearchtime;
403 bool m_localSrcReqQueued;
405 FileRatingList m_FileRatingList;
406 #ifdef CLIENT_GUI
407 SourcenameItemList m_SourcenameItem_list;
408 public:
409 const SourcenameItemList &GetSourcenameItemList() { return m_SourcenameItem_list; }
410 void ClearSourcenameItemList() { m_SourcenameItem_list.clear(); }
411 void AddSourcenameItemList(const wxString &name, long count) { m_SourcenameItem_list.push_back(SourcenameItem(name, count)); }
412 #endif
413 public:
414 const FileRatingList &GetFileRatingList() { return m_FileRatingList; }
415 void ClearFileRatingList() { m_FileRatingList.clear(); }
416 void AddFileRatingList(const wxString & u, const wxString & f, sint16 r, const wxString & c) {
417 m_FileRatingList.push_back(SFileRating(u, f, r, c)); }
419 bool IsHashSetNeeded() const { return m_hashsetneeded; }
420 void SetHashSetNeeded(bool value) { m_hashsetneeded = value; }
422 uint64 GetCompletedSize() const { return completedsize; }
423 void SetCompletedSize(uint64 size) { completedsize = size; }
425 bool IsLocalSrcRequestQueued() const { return m_localSrcReqQueued; }
426 void SetLocalSrcRequestQueued(bool value) { m_localSrcReqQueued = value; }
428 void AddA4AFSource(CUpDownClient* src) { m_A4AFsrclist.insert(src); }
429 bool RemoveA4AFSource(CUpDownClient* src) { return (m_A4AFsrclist.erase(src) > 0); }
431 uint32 GetLastSearchTime() const { return m_lastsearchtime; }
432 void SetLastSearchTime(uint32 time) { m_lastsearchtime = time; }
434 // void CleanUpSources( bool noNeeded, bool fullQueue = false, bool highQueue = false );
436 void AddDownloadingSource(CUpDownClient* client);
438 void RemoveDownloadingSource(CUpDownClient* client);
439 void SetStatus(uint8 in);
440 void StopPausedFile();
442 // [sivka / Tarod] Imported from eMule 0.30c (Creteil) ...
443 void SetA4AFAuto(bool in) { m_is_A4AF_auto = in; }
444 bool IsA4AFAuto() const { return m_is_A4AF_auto; }
446 // Kry -Sources seeds
447 void SaveSourceSeeds();
448 void LoadSourceSeeds();
450 // Dropping slow sources
451 CUpDownClient* GetSlowerDownloadingClient(uint32 speed, CUpDownClient* caller);
453 // Read data for sharing
454 bool ReadData(class CFileArea & area, uint64 offset, uint32 toread);
456 private:
457 /* downloading sources list */
458 CClientPtrList m_downloadingSourcesList;
460 /* Kad Stuff */
461 uint32 m_LastSearchTimeKad;
462 uint8 m_TotalSearchesKad;
464 friend class CDownQueueRem;
465 friend class CPartFileConvert;
468 #endif // PARTFILE_H
469 // File_checked_for_headers