Safe write for nodes.dat
[amule.git] / src / PartFile.h
blob257afbd6c689696aa22a4b67606e91acfb51c10a
1 //
2 // This file is part of the aMule Project.
3 //
4 // Copyright (c) 2003-2011 aMule Team ( admin@amule.org / http://www.amule.org )
5 // Copyright (c) 2002-2011 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 Requested_Block_Struct
34 #include "DeadSourceList.h" // Needed for CDeadSourceList
35 #include "GapList.h"
37 class CSearchFile;
38 class CMemFile;
39 class CFileDataIO;
40 class CED2KFileLink;
42 //#define BUFFER_SIZE_LIMIT 500000 // Max bytes before forcing a flush
43 #define BUFFER_TIME_LIMIT 60000 // Max milliseconds before forcing a flush
45 // Ok, eMule and aMule are building incompatible backup files because
46 // of the different name. aMule was using ".BAK" and eMule ".bak".
47 // This should fix it.
48 #define PARTMET_BAK_EXT wxT(".bak")
50 enum EPartFileFormat {
51 PMT_UNKNOWN = 0,
52 PMT_DEFAULTOLD,
53 PMT_SPLITTED,
54 PMT_NEWOLD,
55 PMT_SHAREAZA,
56 PMT_BADFORMAT
60 class SFileRating
62 public:
63 wxString UserName;
64 wxString FileName;
65 sint16 Rating;
66 wxString Comment;
67 public:
68 SFileRating(const wxString &u, const wxString &f, sint16 r, const wxString &c);
69 SFileRating(const SFileRating &fr);
70 SFileRating(const CUpDownClient &client);
71 ~SFileRating();
74 typedef std::list<SFileRating> FileRatingList;
76 class SourcenameItem
78 public:
79 wxString name;
80 int count;
81 public:
82 SourcenameItem(const wxString &n = EmptyString, int c = 0)
84 name(n), count(c) {}
87 typedef std::map<uint32,SourcenameItem> SourcenameItemMap;
89 class CPartFile : public CKnownFile {
90 public:
91 typedef std::list<Requested_Block_Struct*> CReqBlockPtrList;
93 CPartFile();
94 #ifdef CLIENT_GUI
95 CPartFile(CEC_PartFile_Tag *tag);
96 #else
97 virtual void SetFileName(const CPath& filename);
98 #endif
99 CPartFile(CSearchFile* searchresult); //used when downloading a new file
100 CPartFile(const CED2KFileLink* fileLink);
101 virtual ~CPartFile();
103 virtual bool LoadFromFile(const CFileDataIO* WXUNUSED(file)) { return false; }
104 bool WriteToFile(CFileDataIO* WXUNUSED(file)) { return false; }
106 // virtual functions for CKnownFile and CPartFile:
107 bool IsPartFile() const { return status != PS_COMPLETE; } // true if not completed
108 bool IsCompleted() const { return status == PS_COMPLETE; } // true if completed
109 bool IsCPartFile() const { return true; } // true if it's a CPartFile
111 uint32 Process(uint32 reducedownload, uint8 m_icounter);
112 uint8 LoadPartFile(const CPath& in_directory, const CPath& filename, bool from_backup = false, bool getsizeonly = false);
113 bool SavePartFile(bool Initial = false);
114 void PartFileHashFinished(CKnownFile* result);
115 bool HashSinglePart(uint16 partnumber); // true = ok , false = corrupted
117 bool CheckShowItemInGivenCat(int inCategory);
119 bool IsComplete(uint64 start, uint64 end) { return m_gaplist.IsComplete(start, end); }
120 bool IsComplete(uint16 part) { return m_gaplist.IsComplete(part); }
122 void UpdateCompletedInfos();
124 bool GetNextRequestedBlock(CUpDownClient* sender, std::vector<Requested_Block_Struct*>& toadd, uint16& count);
125 void WritePartStatus(CMemFile* file);
126 void WriteCompleteSourcesCount(CMemFile* file);
127 static bool CanAddSource(uint32 userid, uint16 port, uint32 serverip, uint16 serverport, uint8* pdebug_lowiddropped = NULL, bool ed2kID = true);
128 void AddSources(CMemFile& sources, uint32 serverip, uint16 serverport, unsigned origin, bool bWithObfuscationAndHash);
129 #ifdef CLIENT_GUI
130 uint8 GetStatus() const { return status; }
131 uint8 GetStatus(bool /*ignorepause = false*/) const { return status; }
132 #else
133 uint8 GetStatus(bool ignorepause = false) const;
134 #endif
135 virtual void UpdatePartsInfo();
136 const CPath& GetPartMetFileName() const { return m_partmetfilename; }
137 uint16 GetPartMetNumber() const;
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();
197 int GetCommonFilePenalty();
198 void UpdateDisplayedInfo(bool force = false);
200 uint8 GetCategory() const { return m_category; }
201 void SetCategory(uint8 cat);
202 void RemoveCategory(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 const SourceSet& GetSourceList() const { return m_SrcList; }
254 const SourceSet& GetA4AFList() const { return m_A4AFsrclist; }
255 void ClearA4AFList() { m_A4AFsrclist.clear(); }
257 const CReqBlockPtrList GetRequestedBlockList() const { return m_requestedblocks_list; }
259 const CGapList& GetGapList() const { return m_gaplist; }
262 * Adds a source to the list of dead sources.
264 * @param client The source to be recorded as dead for this file.
266 void AddDeadSource(const CUpDownClient* client);
269 * Checks if a source is recorded as being dead for this file.
271 * @param client The client to evaluate.
272 * @return True if dead, false otherwise.
274 * Sources that are dead are not to be considered valid
275 * sources and should not be added to the partfile.
277 bool IsDeadSource(const CUpDownClient* client);
279 /* Kad Stuff */
280 uint16 GetMaxSources() const;
281 uint16 GetMaxSourcePerFileSoft() const;
282 uint16 GetMaxSourcePerFileUDP() const;
284 void GetRatingAndComments(FileRatingList & list) const;
286 void AllocationFinished();
287 private:
288 #ifndef CLIENT_GUI
289 // partfile handle (opened on demand)
290 CFileAutoClose m_hpartfile;
291 //! A local list of sources that are invalid for this file.
292 CDeadSourceList m_deadSources;
294 class CCorruptionBlackBox* m_CorruptionBlackBox;
295 #endif
297 uint16 m_notCurrentSources;
299 uint32 m_validSources;
301 void AddGap(uint64 start, uint64 end);
302 void AddGap(uint16 part);
303 void FillGap(uint64 start, uint64 end);
304 void FillGap(uint16 part);
305 bool GetNextEmptyBlockInPart(uint16 partnumber,Requested_Block_Struct* result);
306 bool IsAlreadyRequested(uint64 start, uint64 end);
307 void CompleteFile(bool hashingdone);
308 void CreatePartFile();
309 void Init();
311 bool CheckFreeDiskSpace( uint64 neededSpace = 0 );
313 bool IsCorruptedPart(uint16 partnumber);
315 uint32 m_iLastPausePurge;
316 uint16 m_count;
317 uint16 transferingsrc;
318 uint64 completedsize;
319 uint64 transferred;
321 uint64 m_iLostDueToCorruption;
322 uint64 m_iGainDueToCompression;
323 uint32 m_iTotalPacketsSavedDueToICH;
324 float kBpsDown;
325 CPath m_fullname; // path/name of the met file
326 CPath m_partmetfilename; // name of the met file
327 CPath m_PartPath; // path/name of the partfile
328 bool m_paused;
329 bool m_stopped;
330 bool m_insufficient;
331 uint8 m_iDownPriority;
332 bool m_bAutoDownPriority;
333 uint8 status;
334 uint32 lastpurgetime;
335 uint32 m_LastNoNeededCheck;
336 CGapList m_gaplist;
337 CReqBlockPtrList m_requestedblocks_list;
338 double percentcompleted;
339 std::list<uint16> m_corrupted_list;
340 uint16 m_availablePartsCount;
341 uint32 m_ClientSrcAnswered;
342 bool m_bPercentUpdated;
344 void PerformFileComplete();
346 uint32 m_lastRefreshedDLDisplay;
348 // Buffered data to be written
349 std::list<class PartFileBufferedData*> m_BufferedData_list;
351 uint32 m_nTotalBufferData;
352 uint32 m_nLastBufferFlushTime;
354 uint8 m_category;
355 uint32 m_nDlActiveTime;
356 time_t m_tActivated;
357 bool m_is_A4AF_auto;
359 SourceSet m_SrcList;
360 SourceSet m_A4AFsrclist;
361 bool m_hashsetneeded;
362 uint32 m_lastsearchtime;
363 bool m_localSrcReqQueued;
365 #ifdef CLIENT_GUI
366 FileRatingList m_FileRatingList;
367 const FileRatingList &GetFileRatingList() { return m_FileRatingList; }
368 void ClearFileRatingList() { m_FileRatingList.clear(); }
369 void AddFileRatingList(const wxString & u, const wxString & f, sint16 r, const wxString & c) {
370 m_FileRatingList.push_back(SFileRating(u, f, r, c)); }
372 uint32 m_kbpsDown;
373 uint8 m_iDownPriorityEC;
374 bool m_isShared;
375 SourcenameItemMap m_SourcenameItemMap;
377 ListOfUInts32 m_A4AFClientIDs;
378 ListOfUInts32 & GetA4AFClientIDs() { return m_A4AFClientIDs; }
379 public:
380 bool IsShared() const { return m_isShared; }
381 SourcenameItemMap &GetSourcenameItemMap() { return m_SourcenameItemMap; }
382 PartFileEncoderData m_PartFileEncoderData;
383 #endif
384 public:
385 bool IsHashSetNeeded() const { return m_hashsetneeded; }
386 void SetHashSetNeeded(bool value) { m_hashsetneeded = value; }
388 uint64 GetCompletedSize() const { return completedsize; }
389 void SetCompletedSize(uint64 size) { completedsize = size; }
391 bool IsLocalSrcRequestQueued() const { return m_localSrcReqQueued; }
392 void SetLocalSrcRequestQueued(bool value) { m_localSrcReqQueued = value; }
394 void AddA4AFSource(CUpDownClient* src) { m_A4AFsrclist.insert(CCLIENTREF(src, wxT("A4AFSource"))); }
395 bool RemoveA4AFSource(CUpDownClient* src) { return (m_A4AFsrclist.erase(CCLIENTREF(src, wxEmptyString)) > 0); }
397 uint32 GetLastSearchTime() const { return m_lastsearchtime; }
398 void SetLastSearchTime(uint32 time) { m_lastsearchtime = time; }
400 // void CleanUpSources( bool noNeeded, bool fullQueue = false, bool highQueue = false );
402 void AddDownloadingSource(CUpDownClient* client);
404 void RemoveDownloadingSource(CUpDownClient* client);
405 void SetStatus(uint8 in);
406 void StopPausedFile();
408 // [sivka / Tarod] Imported from eMule 0.30c (Creteil) ...
409 void SetA4AFAuto(bool in) { m_is_A4AF_auto = in; }
410 bool IsA4AFAuto() const { return m_is_A4AF_auto; }
412 // Kry -Sources seeds
413 void SaveSourceSeeds();
414 void LoadSourceSeeds();
416 // Dropping slow sources
417 CUpDownClient* GetSlowerDownloadingClient(uint32 speed, CUpDownClient* caller);
419 // Read data for sharing
420 bool ReadData(class CFileArea & area, uint64 offset, uint32 toread);
422 private:
423 /* downloading sources list */
424 CClientRefList m_downloadingSourcesList;
426 /* Kad Stuff */
427 uint32 m_LastSearchTimeKad;
428 uint8 m_TotalSearchesKad;
430 friend class CKnownFilesRem;
431 friend class CPartFileConvert;
434 #endif // PARTFILE_H
435 // File_checked_for_headers