Upstream tarball 10184
[amule.git] / src / CFile.cpp
blob7c006c5e9b6987dc015eec3144eaff5d60838829
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) 1998-2008 Vadim Zeitlin ( zeitlin@dptmaths.ens-cachan.fr )
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
27 #include "CFile.h" // Interface declarations.
28 #include "Logger.h" // Needed for AddDebugLogLineM
29 #include <common/Path.h> // Needed for CPath
32 #ifdef HAVE_CONFIG_H
33 #include "config.h" // Needed for HAVE_SYS_PARAM_H
34 #endif
37 #ifdef HAVE_SYS_PARAM_H
38 #include <sys/param.h>
39 #endif
41 // standard
42 #if defined(__WXMSW__) && !defined(__GNUWIN32__) && !defined(__WXWINE__) && !defined(__WXMICROWIN__)
43 # include <io.h>
44 # ifndef __SALFORDC__
45 # define WIN32_LEAN_AND_MEAN
46 # define NOSERVICE
47 # define NOIME
48 # define NOATOM
49 # define NOGDI
50 # define NOGDICAPMASKS
51 # define NOMETAFILE
52 # define NOMINMAX
53 # define NOMSG
54 # define NOOPENFILE
55 # define NORASTEROPS
56 # define NOSCROLL
57 # define NOSOUND
58 # define NOSYSMETRICS
59 # define NOTEXTMETRIC
60 # define NOWH
61 # define NOCOMM
62 # define NOKANJI
63 # define NOCRYPT
64 # define NOMCX
65 # endif
66 #elif (defined(__UNIX__) || defined(__GNUWIN32__))
67 # ifdef __GNUWIN32__
68 # include <windows.h>
69 # endif
70 #elif (defined(__WXPM__))
71 # include <io.h>
72 #elif (defined(__WXSTUBS__))
73 // Have to ifdef this for different environments
74 # include <io.h>
75 #elif (defined(__WXMAC__))
76 #if __MSL__ < 0x6000
77 int access( const char *path, int mode ) { return 0 ; }
78 #else
79 int _access( const char *path, int mode ) { return 0 ; }
80 #endif
81 char* mktemp( char * path ) { return path ;}
82 # include <stat.h>
83 #else
84 # error "Please specify the header with file functions declarations."
85 #endif //Win/UNIX
87 // there is no distinction between text and binary files under Unix, so define
88 // O_BINARY as 0 if the system headers don't do it already
89 #if defined(__UNIX__) && !defined(O_BINARY)
90 # define O_BINARY (0)
91 #endif //__UNIX__
93 #ifdef __WXMSW__
94 #include <wx/msw/mslu.h>
95 #endif
98 // The following defines handle different names across platforms,
99 // and ensures that we use 64b IO on windows (only 32b by default).
100 #ifdef __WXMSW__
101 #define FLUSH_FD(x) _commit(x)
102 #define SEEK_FD(x, y, z) _lseeki64(x, y, z)
103 #define TELL_FD(x) _telli64(x)
105 #if (__MSVCRT_VERSION__ < 0x0601)
106 //#warning MSCVRT-Version smaller than 6.01
107 #define STAT_FD(x, y) _fstati64(x, y)
108 #define STAT_STRUCT struct _stati64
109 #else
110 #define STAT_FD(x, y) _fstat64(x, y)
111 #define STAT_STRUCT struct __stat64
112 #endif
113 #else
115 // We don't need to sync all meta-data, just the contents,
116 // so use fdatasync when possible (see man fdatasync).
117 #if defined(_POSIX_SYNCHRONIZED_IO) && (_POSIX_SYNCHRONIZED_IO > 0)
118 #define FLUSH_FD(x) fdatasync(x)
119 #else
120 #define FLUSH_FD(x) fsync(x)
121 #endif
123 #define SEEK_FD(x, y, z) lseek(x, y, z)
124 #define TELL_FD(x) wxTell(x)
125 #define STAT_FD(x, y) fstat(x, y)
126 #define STAT_STRUCT struct stat
127 #endif
130 // This function is used to check if a syscall failed, in that case
131 // log an appropriate message containing the errno string.
132 inline void syscall_check(
133 bool check,
134 const CPath& filePath,
135 const wxString& what)
137 if (!check) {
138 AddDebugLogLineM(true, logCFile,
139 CFormat(wxT("Error when %s (%s): %s"))
140 % what % filePath % wxSysErrorMsg());
145 CSeekFailureException::CSeekFailureException(const wxString& desc)
146 : CIOFailureException(wxT("SeekFailure"), desc)
150 CFile::CFile()
151 : m_fd(fd_invalid)
155 CFile::CFile(const CPath& fileName, OpenMode mode)
156 : m_fd(fd_invalid)
158 Open(fileName, mode);
162 CFile::CFile(const wxString& fileName, OpenMode mode)
163 : m_fd(fd_invalid)
165 Open(fileName, mode);
169 CFile::~CFile()
171 if (IsOpened()) {
172 Close();
177 int CFile::fd() const
179 return m_fd;
183 bool CFile::IsOpened() const
185 return m_fd != fd_invalid;
189 const CPath& CFile::GetFilePath() const
191 return m_filePath;
195 bool CFile::Create(const CPath& path, bool overwrite, int accessMode)
197 if (!overwrite && path.FileExists()) {
198 return false;
201 return Open(path, write, accessMode);
204 bool CFile::Create(const wxString& path, bool overwrite, int accessMode)
206 return Create(CPath(path), overwrite, accessMode);
210 bool CFile::Open(const wxString& fileName, OpenMode mode, int accessMode)
212 MULE_VALIDATE_PARAMS(fileName.Length(), wxT("CFile: Cannot open, empty path."));
214 return Open(CPath(fileName), mode, accessMode);
218 bool CFile::Open(const CPath& fileName, OpenMode mode, int accessMode)
220 MULE_VALIDATE_PARAMS(fileName.IsOk(), wxT("CFile: Cannot open, empty path."));
222 #ifdef __linux__
223 int flags = O_BINARY | O_LARGEFILE;
224 #else
225 int flags = O_BINARY;
226 #endif
227 switch ( mode ) {
228 case read:
229 flags |= O_RDONLY;
230 break;
232 case write_append:
233 if (fileName.FileExists())
235 flags |= O_WRONLY | O_APPEND;
236 break;
238 //else: fall through as write_append is the same as write if the
239 // file doesn't exist
241 case write:
242 flags |= O_WRONLY | O_CREAT | O_TRUNC;
243 break;
245 case write_excl:
246 flags |= O_WRONLY | O_CREAT | O_EXCL;
247 break;
249 case read_write:
250 flags |= O_RDWR;
251 break;
254 if (IsOpened()) {
255 Close();
258 m_filePath = fileName;
260 // Windows needs wide character file names
261 #ifdef __WXMSW__
262 m_fd = _wopen(fileName.GetRaw().c_str(), flags, accessMode);
263 #else
264 Unicode2CharBuf tmpFileName = filename2char(fileName.GetRaw());
265 wxASSERT_MSG(tmpFileName, wxT("Convertion failed in CFile::Open"));
266 m_fd = open(tmpFileName, flags, accessMode);
267 #endif
268 syscall_check(m_fd != fd_invalid, m_filePath, wxT("opening file"));
270 return IsOpened();
274 void CFile::Reopen(OpenMode mode)
276 if (!Open(m_filePath, mode)) {
277 throw CIOFailureException(wxString(wxT("Error reopening file")));
282 bool CFile::Close()
284 MULE_VALIDATE_STATE(IsOpened(), wxT("CFile: Cannot close closed file."));
286 bool closed = (close(m_fd) != -1);
287 syscall_check(closed, m_filePath, wxT("closing file"));
289 m_fd = fd_invalid;
291 return closed;
295 bool CFile::Flush()
297 MULE_VALIDATE_STATE(IsOpened(), wxT("CFile: Cannot flush closed file."));
299 bool flushed = (FLUSH_FD(m_fd) != -1);
300 syscall_check(flushed, m_filePath, wxT("flushing file"));
302 return flushed;
306 sint64 CFile::doRead(void* buffer, size_t count) const
308 MULE_VALIDATE_PARAMS(buffer, wxT("CFile: Invalid buffer in read operation."));
309 MULE_VALIDATE_STATE(IsOpened(), wxT("CFile: Cannot read from closed file."));
311 size_t totalRead = 0;
312 while (totalRead < count) {
313 int current = ::read(m_fd, (char*)buffer + totalRead, count - totalRead);
315 if (current == -1) {
316 // Read error, nothing we can do other than abort.
317 throw CIOFailureException(wxString(wxT("Error reading from file: ")) + wxSysErrorMsg());
318 } else if ((totalRead + current < count) && Eof()) {
319 // We may fail to read the specified count in a couple
320 // of situations: EOF and interrupts. The check for EOF
321 // is needed to avoid inf. loops.
322 break;
325 totalRead += current;
328 return totalRead;
332 sint64 CFile::doWrite(const void* buffer, size_t nCount)
334 MULE_VALIDATE_PARAMS(buffer, wxT("CFile: Invalid buffer in write operation."));
335 MULE_VALIDATE_STATE(IsOpened(), wxT("CFile: Cannot write to closed file."));
337 sint64 result = ::write(m_fd, buffer, nCount);
339 if (result != (sint64)nCount) {
340 throw CIOFailureException(wxString(wxT("Error writing to file: ")) + wxSysErrorMsg());
343 return result;
347 sint64 CFile::doSeek(sint64 offset) const
349 MULE_VALIDATE_STATE(IsOpened(), wxT("Cannot seek on closed file."));
350 MULE_VALIDATE_PARAMS(offset >= 0, wxT("Invalid position, must be positive."));
352 sint64 result = SEEK_FD(m_fd, offset, SEEK_SET);
354 if (result == offset) {
355 return result;
356 } else if (result == wxInvalidOffset) {
357 throw CSeekFailureException(wxString(wxT("Seeking failed: ")) + wxSysErrorMsg());
358 } else {
359 throw CSeekFailureException(wxT("Seeking returned incorrect position"));
364 uint64 CFile::GetPosition() const
366 MULE_VALIDATE_STATE(IsOpened(), wxT("Cannot get position in closed file."));
368 sint64 pos = TELL_FD(m_fd);
369 if (pos == wxInvalidOffset) {
370 throw CSeekFailureException(wxString(wxT("Failed to retrieve position in file: ")) + wxSysErrorMsg());
373 return pos;
377 uint64 CFile::GetLength() const
379 MULE_VALIDATE_STATE(IsOpened(), wxT("CFile: Cannot get length of closed file."));
381 STAT_STRUCT buf;
382 if (STAT_FD(m_fd, &buf) == -1) {
383 throw CIOFailureException(wxString(wxT("Failed to retrieve length of file: ")) + wxSysErrorMsg());
386 return buf.st_size;
390 uint64 CFile::GetAvailable() const
392 const uint64 length = GetLength();
393 const uint64 position = GetPosition();
395 // Safely handle seeking past EOF
396 if (position < length) {
397 return length - position;
400 // File is at or after EOF
401 return 0;
405 bool CFile::SetLength(uint64 new_len)
407 MULE_VALIDATE_STATE(IsOpened(), wxT("CFile: Cannot set length when no file is open."));
409 #ifdef __WXMSW__
410 #ifdef _MSC_VER
411 // MSVC has a 64bit version
412 bool result = _chsize_s(m_fd, new_len) == 0;
413 #else
414 // MingW has an old runtime without it
415 bool result = chsize(m_fd, new_len) == 0;
416 #endif
417 #else
418 bool result = ftruncate(m_fd, new_len) != -1;
419 #endif
421 syscall_check(result, m_filePath, wxT("truncating file"));
423 return result;
425 // File_checked_for_headers