//
// This file is part of the aMule Project.
//
// Copyright (c) 2003-2026 aMule Team ( https://amule-org.github.io )
// Copyright (c) 1998-2011 Vadim Zeitlin ( zeitlin@dptmaths.ens-cachan.fr )
//
// Any parts of this program derived from the xMule, lMule or eMule project,
// or contributed by third-party developers are copyrighted by their
// respective authors.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
//

#ifndef CFILE_H
#define CFILE_H

#include <common/Path.h>	// Needed for CPath
#include "SafeFile.h"		// Needed for CFileDataIO

#include <wx/file.h>		// Needed for constants

#include <memory>		// Needed for std::unique_ptr
#include <mutex>		// Needed for std::recursive_mutex

#ifdef _MSC_VER  // silly warnings about deprecated functions
#pragma warning(disable:4996)
#endif

/**
 * This class is a modified version of the wxFile class.
 *
 * In addition to implementing the CFileDataIO interface,
 * it offers improved support for UTF8 filenames and 64b
 * file-IO on both windows and unix-like systems.
 *
 * @see wxFile
 */
class CFile : public CFileDataIO
{
public:
	//! Standard values for file descriptor
	enum { fd_invalid = -1, fd_stdin, fd_stdout, fd_stderr };

	/** @see wxFile::OpenMode */
	enum OpenMode { read, write, read_write, write_append, write_excl, write_safe };


	/**
	 * Creates a closed file.
	 */
	CFile();

	/**
	 * Constructor, calls Open on the specified file.
	 *
	 * To check if the file was successfully opened, a
	 * call to IsOpened() is required.
	 */
	CFile(const CPath& path, OpenMode mode = read);
	CFile(const wxString& path, OpenMode mode = read);

	/**
	 * Destructor, closes the file if opened.
	 */
	virtual ~CFile();


	/**
	 * Opens a file.
	 *
	 * @param path The full or relative path to the file.
	 * @param mode The opening mode.
	 * @param accessMode The permissions in case a new file is created.
	 * @return True if the file was opened, false otherwise.
	 *
	 * Calling Open with the openmodes 'write' or 'write_append' will
	 * create the specified file if it does not already exist.
	 *
	 * Calling Open with the openmode 'write_safe' will append ".new"
	 * to the file name and otherwise work like 'write'.
	 * On close it will be renamed to the original name.
	 * Close() has to be called manually - destruct won't rename the file!
	 *
	 * If an accessMode is not explicitly specified, the accessmode
	 * specified via CPreferences::GetFilePermissions will be used.
	 */
	bool Open(const CPath& path, OpenMode mode = read, int accessMode = wxS_DEFAULT);
	bool Open(const wxString& path, OpenMode mode = read, int accessMode = wxS_DEFAULT);

	/**
	 * Reopens a file which was opened and closed before.
	 *
	 * @param mode The opening mode.
	 *
	 * The filename used for last open is used again.
	 * No return value - function throws on failure.
	 */
	void Reopen(OpenMode mode);

	/**
	 * Calling Create is equivalent of calling open with OpenMode 'write'.
	 *
	 * @param overwrite Specifies if the target file should be overwritten,
	 *                  in case that it already exists.
	 *
	 * @see CFile::Open
	 */
	bool Create(const CPath& path, bool overwrite = false, int accessMode = wxS_DEFAULT);
	bool Create(const wxString& path, bool overwrite = false, int accessMode = wxS_DEFAULT);

	/**
	 * Closes the file.
	 *
	 * Note that calling Close on an closed file
	 * is an illegal operation.
	 */
	bool Close();


	/**
	 * Returns the file descriptor associated with the file.
	 *
	 * Note that direct manipulation of the descriptor should
	 * be avoided! That's what this class is for.
	 */
	int  fd() const;

	/**
	 * Flushes data not yet written.
	 *
	 * Note that calling Flush on an closed file
	 * is an illegal operation.
	 */
	bool Flush();


	/**
	 * @see CSafeFileIO::GetLength
	 *
	 * Note that calling GetLength on a closed file
	 * is an illegal operation.
	 */
	virtual uint64 GetLength() const;

	/**
	 * Resizes the file to the specified length.
	 */
	bool SetLength(uint64 newLength);

	/**
	 * @see CSafeFileIO::GetPosition
	 *
	 * Note that calling GetPosition on a closed file
	 * is an illegal operation.
	 */
	virtual uint64 GetPosition() const;

	/**
	 * Returns the current available bytes to read on the file before EOF
	 *
	 */
	virtual uint64 GetAvailable() const;

	/**
	 * Returns the path of the currently opened file.
	 *
	 */
	const CPath& GetFilePath() const;


	/**
	 * Returns true if the file is opened, false otherwise.
	 */
	bool IsOpened() const;

protected:
	/** @see CFileDataIO::doRead **/
	virtual sint64 doRead(void* buffer, size_t count) const;
	/** @see CFileDataIO::doWrite **/
	virtual sint64 doWrite(const void* buffer, size_t count);
	/** @see CFileDataIO::doSeek **/
	virtual sint64 doSeek(sint64 offset) const;

private:
	//! A CFile is neither copyable nor assignable.
	//@{
	CFile(const CFile&);
	CFile& operator=(const CFile&);
	//@}

	//! Flush any data in the userspace write buffer to the kernel.
	//! No-op when the buffer is empty (e.g. read-only files). Called
	//! from any path that needs the file's on-disk state to reflect
	//! preceding writes — Close, Flush, doSeek, doRead, GetPosition,
	//! GetLength.
	void DrainWriteBuffer() const;

	//! File descriptor or 'fd_invalid' if not opened
	int m_fd;

	//! The full path to the current file.
	CPath m_filePath;

	//! Are we using safe write mode?
	bool m_safeWrite;

	//! Userspace write buffer. CFile::doWrite was previously a thin
	//! wrapper over ::write(), which made every CFileDataIO::WriteTag
	//! call (and its many small WriteString / Write underneath) round-
	//! trip through the kernel. CKnownFileList::Save() with hundreds
	//! of thousands of files emitted ~26k write() syscalls per second
	//! and stalled shutdown for many minutes (#562 — slrslr's report).
	//! Buffering doWrite into 64 KB chunks collapses millions of
	//! syscalls into a few thousand. Members are mutable so the const-
	//! qualified read / seek / position / length paths can drain the
	//! buffer transparently.
	//!
	//! Heap-allocated (lazy) rather than embedded as a fixed array,
	//! because CFile is regularly stack-allocated inside worker-thread
	//! call chains (e.g. CHashingTask → CAICHHashSet::SaveHashSet
	//! stack-allocates two CFile-shaped objects). musl's default
	//! pthread stack is 128 KiB; two embedded 64 KiB buffers consume
	//! the whole stack and the next stack-using call (in practice the
	//! wxString → char conversion inside wxFile::Exists) crosses the
	//! guard page and SIGSEGVs. The unique_ptr brings sizeof(CFile)
	//! back to ~32 bytes and pays the 64 KiB only on first write,
	//! which means read-only opens stay free.
	enum { kWriteBufferSize = 64 * 1024 };
	mutable std::unique_ptr<char[]> m_writeBuffer;
	mutable size_t m_writeBufferPending;

	//! True when the file was opened in a write-capable mode and
	//! buffering is safe. Read-only files bypass the buffer so that
	//! a stray write() through doWrite still fails immediately at
	//! the call site (preserves CFileDataIO's error contract — see
	//! FileDataIOTest's CFile.Constructor "ASSERT_RAISES(...,
	//! file.WriteUInt8(0))" for a read-only fd).
	bool m_canBuffer;

	//! Serializes access to the userspace write buffer + fd state.
	//! Without it, paths that drain the buffer (Close, Flush, doSeek,
	//! doRead, GetPosition, GetLength, SetLength) can race against
	//! concurrent doWrite/drain calls: two threads both pass the
	//! `pending != 0` check before either resets pending to 0, and
	//! since ::write advances the fd offset atomically per call, the
	//! same N bytes end up written at fd_pos AND fd_pos + N — the
	//! second write clobbers whatever lived there (typically the
	//! previously-written block's data).
	//!
	//! Hit in production on CPartFile::m_hpartfile: CPartFile::FlushBuffer
	//! calls m_hpartfile.GetLength()/SetLength() and CPartFile::
	//! GetNeededSpace() calls GetLength(), all from the main thread
	//! without taking m_hpartfileMutex. Pre-#562 this was safe because
	//! GetLength was just fstat — independent of fd position. After
	//! #562 it drains the buffer, which is what triggers the race
	//! against CPartFileWriteThread's FlushAt (held under
	//! m_hpartfileMutex but contending against unlocked main-thread
	//! drains). Manifests as 1-3 corrupt blocks per part, with AICH
	//! recovering ~98% of each part.
	//!
	//! Recursive so Open() → Close() (and Reopen → Open → Close) don't
	//! deadlock. Cost is ~30-50 ns per public-method call versus the
	//! ~1 µs floor of any I/O syscall it's serializing — well within
	//! noise. Mutable because const-qualified methods (doRead, doSeek,
	//! GetLength, GetPosition) need to lock it.
	mutable std::recursive_mutex m_mutex;
};


/**
 * This exception is thrown by CFile if a seek or tell fails.
 */
struct CSeekFailureException : public CIOFailureException {
	CSeekFailureException(const wxString& desc);
};


#endif // CFILE_H
// File_checked_for_headers
