diff --git a/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt b/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt new file mode 100644 index 00000000..cd7f0f15 --- /dev/null +++ b/contrib/oads_hb/FILE_LOCKS_MTFIX85.txt @@ -0,0 +1,75 @@ +OpenADS FS byte locks - mtfix85 +Pritpal Bedi +2026-11-15 11:01 + +Remote ownership choice for review: each client connection is a separate +lock owner, like a separate Harbour process. Within that connection, file +opens share the merged registry. Different clients can share read locks, +and WAIT can wait for a different client. They do not all become one +owner merely because one server process handles them. + +OAds_FLock( hFile, nStart, nLen, nType ) -> lOk +OAds_FUnlock( hFile, nStart, nLen ) -> lOk +OAds_FLockTest( hFile, nStart, nLen, nType ) -> nResult + +hFile comes from OAds_FOpen or OAds_FCreate. These are file-system +byte-range locks, not RDD record locks. No RDD/CDX lock code is changed. +They use the host OS byte locks, visible across processes. Windows I/O +and locks use the same native handle. EnableFileFunc and jail rules apply. + +nType flags, combined with hb_bitOr(): + 0x0000 = exclusive, no wait (default) + 0x0100 = shared + 0x0200 = wait until success + 0x0300 = shared, wait until success + +NO_WAIT makes one attempt. WAIT repeats after OS contention until success +or error. Each server request makes one non-blocking OS attempt, never +sleeps, and returns. The client retries every 10 ms without holding the +file/connection/registry mutexes between requests. The Harbour wrapper +releases the VM. Connection failure or a closed handle ends the call. +A caller can wait indefinitely if an external owner never releases. + +Harbour filebuf.c behavior preserved: +- Opens of the same physical file within one owner share a merged range + registry and native file. Each public handle keeps its own position. +- An overlapping lock already in that registry fails immediately, + including with WAIT. An identical re-lock is not recursive/idempotent. +- Adjacent registrations merge. Unlock removes/splits a contained range + after the native OS unlock succeeds. +- LockTest reports an overlapping own registration as locked. Otherwise + Unix queries return the external owner PID where the OS supplies one; + OFD locks have no PID, so they return 1. Windows returns 1 for + conflict. Both return 0 for free, -1 for error. It never waits. +- Closing one reference does not release shared native-file locks while + another reference remains. Last close releases the OS locks. +- Unix read-only opens request shared OS locks, as Harbour does. +- POSIX uses OFD locks so separate client connections retain independent + ownership and closing one cannot drop another's locks. This differs + from Harbour's process-owned fcntl locks. OS-reported classic-lock PIDs + are returned when available; an OFD owner has no PID and returns 1. + +OS behavior is preserved, including: +- Unix partial unlock and zero-length-to-EOF ranges work through fcntl. +- Windows UnlockFileEx requires the exact native acquired range. A + partial unlock or one spanning distinct acquisitions can fail, just as + Harbour's Windows backend does. Zero length has Windows native meaning, + not the Unix to-EOF meaning. +- Windows locks affect I/O. Unix locks are advisory. Other programs must + cooperate. + +Nonnegative file offsets and ranges must fit the signed 64-bit offset +space used by the cross-platform API. No virtual-file/socket drivers are +implemented by these OAds handles. Error reporting is through OAds return +values, not Harbour FError(). + +DirSpace correction in mtfix85 (supersedes mtfix84 custom values): + HB_DISK_AVAIL = 0, HB_DISK_FREE = 1, HB_DISK_USED = 2, + HB_DISK_TOTAL = 3, matching Harbour include/fileio.ch. +Do not carry mtfix84's 1=capacity or 2=free meanings into this kit. + +Reference source: +https://github.com/harbour/core/blob/master/src/rtl/vfile.c +https://github.com/harbour/core/blob/master/src/rtl/filebuf.c +https://github.com/harbour/core/blob/master/src/rtl/filesys.c +https://github.com/harbour/core/blob/master/include/fileio.ch diff --git a/contrib/oads_hb/oads_hb.c b/contrib/oads_hb/oads_hb.c index 47068a60..8311e9a8 100644 --- a/contrib/oads_hb/oads_hb.c +++ b/contrib/oads_hb/oads_hb.c @@ -708,6 +708,43 @@ HB_FUNC( OADS_SETFILETIME ) /* ------------------------------------------------------------------ */ /* OADS_FTrunc( hFile, nSize ) -> lOk */ /* ------------------------------------------------------------------ */ +/* FS byte locks only, independent of RDD record locks. + * nType: 0 exclusive/no-wait, 0x100 shared, 0x200 wait until success. + * LockTest: 0 free, POSIX PID (Windows 1) locked, -1 error. + * WAIT releases the Harbour VM so another Harbour thread can unlock. + */ +HB_FUNC( OADS_FLOCK ) +{ + ADSHANDLE h = ( ADSHANDLE ) hb_parnint( 1 ); + HB_MAXINT start = hb_parnint( 2 ), len = hb_parnint( 3 ); + UNSIGNED16 type = ( UNSIGNED16 ) hb_parni( 4 ); + UNSIGNED32 rc = 5000; + if( h && start >= 0 && len >= 0 ) + { + hb_vmUnlock(); + rc = oads_FLock( h, ( UNSIGNED64 ) start, ( UNSIGNED64 ) len, type ); + hb_vmLock(); + } + hb_retl( rc == 0 ); +} +HB_FUNC( OADS_FUNLOCK ) +{ + ADSHANDLE h = ( ADSHANDLE ) hb_parnint( 1 ); + HB_MAXINT start = hb_parnint( 2 ), len = hb_parnint( 3 ); + hb_retl( h && start >= 0 && len >= 0 && + oads_FUnlock( h, ( UNSIGNED64 ) start, ( UNSIGNED64 ) len ) == 0 ); +} +HB_FUNC( OADS_FLOCKTEST ) +{ + ADSHANDLE h = ( ADSHANDLE ) hb_parnint( 1 ); + HB_MAXINT start = hb_parnint( 2 ), len = hb_parnint( 3 ); + SIGNED32 result = -1; + if( h && start >= 0 && len >= 0 ) + oads_FLockTest( h, ( UNSIGNED64 ) start, ( UNSIGNED64 ) len, + ( UNSIGNED16 ) hb_parni( 4 ), &result ); + hb_retni( result ); +} + HB_FUNC( OADS_FTRUNC ) { ADSHANDLE hFile = ( ADSHANDLE ) hb_parnint( 1 ); @@ -757,7 +794,7 @@ HB_FUNC( OADS_TEMPFILE ) /* ------------------------------------------------------------------ */ /* OADS_DirSpace( hConn, cDir, nType ) -> nBytes */ /* OADS_DirSpace( cDir, nType ) -> nBytes (default conn) */ -/* nType: 0 = free available, 1 = total capacity, 2 = free. */ +/* nType: 0 = available, 1 = free, 2 = used, 3 = total. */ /* ------------------------------------------------------------------ */ HB_FUNC( OADS_DIRSPACE ) { diff --git a/include/openads/ace.h b/include/openads/ace.h index f9062e6e..aaf97350 100644 --- a/include/openads/ace.h +++ b/include/openads/ace.h @@ -127,6 +127,9 @@ UNSIGNED32 ENTRYPOINT AdsSetFileTime (ADSHANDLE hConnect, UNSIGNED8* pucName, UNSIGNED16 usYear, UNSIGNED8 ucMon, UNSIGNED8 ucDay, UNSIGNED8 ucHour, UNSIGNED8 ucMin, UNSIGNED8 ucSec); +UNSIGNED32 ENTRYPOINT AdsFLock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType); +UNSIGNED32 ENTRYPOINT AdsFUnlock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen); +UNSIGNED32 ENTRYPOINT AdsFLockTest(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType, SIGNED32* plResult); UNSIGNED32 ENTRYPOINT AdsFTrunc (ADSHANDLE hFile, UNSIGNED64 ullSize); // Creates an empty uniquely named file under pucDir; the name lands in @@ -134,7 +137,7 @@ UNSIGNED32 ENTRYPOINT AdsFTrunc (ADSHANDLE hFile, UNSIGNED32 ENTRYPOINT AdsTempFile (ADSHANDLE hConnect, UNSIGNED8* pucDir, UNSIGNED8* pucPrefix, UNSIGNED8* pucName, UNSIGNED16* pusNameLen); -// ucType: 0 = free available, 1 = total capacity, 2 = free. +// ucType: 0 = available, 1 = free, 2 = used, 3 = total. UNSIGNED32 ENTRYPOINT AdsDirSpace (ADSHANDLE hConnect, UNSIGNED8* pucDir, UNSIGNED8 ucType, UNSIGNED64* pullBytes); UNSIGNED32 ENTRYPOINT AdsGetFileSize (ADSHANDLE hConnect, UNSIGNED8* pucName, @@ -237,6 +240,9 @@ UNSIGNED32 OADSAPI oads_SetFileTime (ADSHANDLE hConnect, UNSIGNED8* pucName, UNSIGNED16 usYear, UNSIGNED8 ucMon, UNSIGNED8 ucDay, UNSIGNED8 ucHour, UNSIGNED8 ucMin, UNSIGNED8 ucSec); +UNSIGNED32 OADSAPI oads_FLock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType); +UNSIGNED32 OADSAPI oads_FUnlock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen); +UNSIGNED32 OADSAPI oads_FLockTest(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType, SIGNED32* plResult); UNSIGNED32 OADSAPI oads_FTrunc (ADSHANDLE hFile, UNSIGNED64 ullSize); UNSIGNED32 OADSAPI oads_TempFile (ADSHANDLE hConnect, UNSIGNED8* pucDir, diff --git a/src/abi/ace_exports.cpp b/src/abi/ace_exports.cpp index 7ad9dae7..2ed8562f 100644 --- a/src/abi/ace_exports.cpp +++ b/src/abi/ace_exports.cpp @@ -11560,6 +11560,56 @@ UNSIGNED32 ENTRYPOINT AdsSetFileTime(ADSHANDLE hConn, UNSIGNED8* pucName, return ok(); } +// Each invocation makes one non-blocking attempt. Never sleep while holding +// the ABI registry mutex or the per-file/connection mutex. +extern "C++" { +static openads::util::Result oads_fs_lock_once(ADSHANDLE hFile, + UNSIGNED64 start, UNSIGNED64 len, UNSIGNED16 type, std::uint8_t op) { + auto& s = state(); + std::unique_lock lk(s.mu); + if (auto it = remote_files_map().find(hFile); it != remote_files_map().end()) { + auto rf = it->second; + lk.unlock(); + std::lock_guard file_lk(rf->mu); + if (rf->closed) return openads::util::Error{5000, 0, "closed file", ""}; + return rf->conn->file_lock_step(rf->file_id, start, len, type, op); + } + if (auto* lf = s.registry.lookup( + hFile, openads::session::HandleKind::LocalFile)) + return openads::engine::fs_lock_step(*lf, start, len, type, op); + return openads::util::Error{5000, 0, "bad file handle", ""}; +} +} + +UNSIGNED32 ENTRYPOINT AdsFLock(ADSHANDLE hFile, UNSIGNED64 ullStart, + UNSIGNED64 ullLen, UNSIGNED16 usType) { + arc2_trace("AdsFLock"); + for (;;) { + auto v = oads_fs_lock_once(hFile, ullStart, ullLen, usType, 0); + if (!v) return fail(v.error()); + if (v.value()) return ok(); + if ((usType & 0x0200u) == 0) return fail(5012, "file lock busy"); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } +} +UNSIGNED32 ENTRYPOINT AdsFUnlock(ADSHANDLE hFile, UNSIGNED64 ullStart, + UNSIGNED64 ullLen) { + arc2_trace("AdsFUnlock"); + auto v = oads_fs_lock_once(hFile, ullStart, ullLen, 0, 1); + if (!v) return fail(v.error()); + return ok(); +} +UNSIGNED32 ENTRYPOINT AdsFLockTest(ADSHANDLE hFile, UNSIGNED64 ullStart, + UNSIGNED64 ullLen, UNSIGNED16 usType, SIGNED32* plResult) { + arc2_trace("AdsFLockTest"); + if (!plResult) return fail(5000, "null lock-test result"); + *plResult = -1; + auto v = oads_fs_lock_once(hFile, ullStart, ullLen, usType, 2); + if (!v) return fail(v.error()); + *plResult = v.value(); + return ok(); +} + UNSIGNED32 ENTRYPOINT AdsFTrunc(ADSHANDLE hFile, UNSIGNED64 ullSize) { arc2_trace("AdsFTrunc"); auto& s = state(); diff --git a/src/abi/adsfunc.c b/src/abi/adsfunc.c index ca2f28b8..0c309646 100644 --- a/src/abi/adsfunc.c +++ b/src/abi/adsfunc.c @@ -240,3 +240,12 @@ UNSIGNED32 OADSAPI oads_Directory( ADSHANDLE hConnect, { return AdsDirectory( hConnect, pucMask, usAttr, pucBuffer, pulBufLen ); } + +UNSIGNED32 OADSAPI oads_FLock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType) +{ return AdsFLock(hFile, ullStart, ullLen, usType); } + +UNSIGNED32 OADSAPI oads_FUnlock(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen) +{ return AdsFUnlock(hFile, ullStart, ullLen); } + +UNSIGNED32 OADSAPI oads_FLockTest(ADSHANDLE hFile, UNSIGNED64 ullStart, UNSIGNED64 ullLen, UNSIGNED16 usType, SIGNED32* plResult) +{ return AdsFLockTest(hFile, ullStart, ullLen, usType, plResult); } diff --git a/src/engine/server_fs.cpp b/src/engine/server_fs.cpp index 89287c0e..07ff06ac 100644 --- a/src/engine/server_fs.cpp +++ b/src/engine/server_fs.cpp @@ -10,11 +10,18 @@ #include #include #include +#include +#include +#include +#include #if defined(_WIN32) #include +#define WIN32_LEAN_AND_MEAN +#include #include #else #include +#include #endif namespace fs = std::filesystem; @@ -162,21 +169,21 @@ util::Result fs_copy(const std::string& abs_src, if (!ec && same) return io_err(static_cast(openads::AE_INTERNAL_ERROR), "source and target are the same file", abs_src); - // Plain stream copy: MinGW's fs::copy_file is unreliable when the - // target already exists, and truncate-on-open is the wanted overwrite. - std::ifstream in(abs_src, std::ios::binary); - if (!in) - return io_err(static_cast(openads::AE_INTERNAL_ERROR), - "open source failed", abs_src); - std::ofstream out(abs_dst, std::ios::binary | std::ios::trunc); - if (!out) - return io_err(static_cast(openads::AE_INTERNAL_ERROR), - "open target failed", abs_dst); - out << in.rdbuf(); - out.flush(); - if (!out || in.bad()) - return io_err(static_cast(openads::AE_INTERNAL_ERROR), - "copy failed", abs_src); + auto src = fs_open(abs_src, ADS_FO_READ, false); + if (!src) return src.error(); + auto dst = fs_open(abs_dst, ADS_FO_READWRITE, true); + if (!dst) return dst.error(); + std::vector chunk(65536); + for (;;) { + src.value()->stream.read(chunk.data(), static_cast(chunk.size())); + if (!src.value()->stream) return io_err(5000, "copy read failed", abs_src); + auto n = src.value()->stream.gcount(); + if (n == 0) break; + dst.value()->stream.write(chunk.data(), n); + if (!dst.value()->stream) return io_err(5000, "copy write failed", abs_dst); + } + dst.value()->stream.flush(); + if (!dst.value()->stream) return io_err(5000, "copy flush failed", abs_dst); return {}; } @@ -192,15 +199,14 @@ util::Result> fs_load(const std::string& abs_path) { if (sz > kMaxFsWholeFile) return io_err(static_cast(openads::AE_INTERNAL_ERROR), "file too large for one call", abs_path); - std::ifstream in(abs_path, std::ios::binary); - if (!in) - return io_err(static_cast(openads::AE_NO_FILE_FOUND), - "open failed", abs_path); + auto handle = fs_open(abs_path, ADS_FO_READ, false); + if (!handle) return handle.error(); + auto& in = handle.value()->stream; std::vector out(static_cast(sz)); if (sz) in.read(reinterpret_cast(out.data()), static_cast(sz)); - if (in.bad() || static_cast(in.gcount()) != sz) + if (!in || static_cast(in.gcount()) != sz) return io_err(static_cast(openads::AE_INTERNAL_ERROR), "read failed", abs_path); return out; @@ -211,10 +217,9 @@ util::Result fs_save(const std::string& abs_path, if (size > kMaxFsWholeFile) return io_err(static_cast(openads::AE_INTERNAL_ERROR), "too large for one call", abs_path); - std::ofstream out(abs_path, std::ios::binary | std::ios::trunc); - if (!out) - return io_err(static_cast(openads::AE_ACCESS_DENIED), - "open failed", abs_path); + auto handle = fs_open(abs_path, ADS_FO_READWRITE, true); + if (!handle) return handle.error(); + auto& out = handle.value()->stream; if (size) out.write(reinterpret_cast(data), static_cast(size)); @@ -301,7 +306,9 @@ util::Result fs_truncate(FsFile& file, std::uint64_t size) { if (!file.stream) return io_err(static_cast(openads::AE_INTERNAL_ERROR), "flush failed", file.path); - auto r = fs_truncate(file.path, size); + auto native = file.stream.native; + std::lock_guard guard(native->mu); + auto r = native->file.truncate(size); if (!r) return r; file.stream.clear(); if (pos >= 0) { @@ -352,8 +359,10 @@ util::Result fs_dir_space(const std::string& abs_dir, if (ec) return io_err(static_cast(openads::AE_NO_FILE_FOUND), "space query failed", abs_dir); - if (type == 1) return static_cast(sp.capacity); - if (type == 2) return static_cast(sp.free); + // Harbour fileio.ch HB_DISK_* values, not a private numbering. + if (type == 1) return static_cast(sp.free); + if (type == 2) return static_cast(sp.capacity - sp.free); + if (type == 3) return static_cast(sp.capacity); return static_cast(sp.available); } @@ -462,40 +471,233 @@ util::Result fs_dir_remove(const std::string& abs_path) { return {}; } +void FsStream::read(char* data, std::streamsize n) { + count_ = 0; + if (!good_ || n < 0) { good_ = false; return; } + std::lock_guard guard(native->mu); + auto v = native->file.read_at(static_cast(pos_), data, static_cast(n)); + if (!v) { good_ = false; return; } + count_ = static_cast(v.value()); + pos_ += static_cast(v.value()); +} +void FsStream::write(const char* data, std::streamsize n) { + if (!good_ || !writable || n < 0) { good_ = false; return; } + std::lock_guard guard(native->mu); + auto v = native->file.write_at(static_cast(pos_), data, static_cast(n)); + if (!v) { good_ = false; return; } + pos_ += static_cast(v.value()); + good_ = v.value() == static_cast(n); +} +void FsStream::flush() { + // Native positional I/O is unbuffered at this layer. Flush is not + // Commit: like hb_vfFlush, it does not promise a durable disk sync. +} +void FsStream::seekg(std::streamoff off, std::ios::seekdir way) { + std::streamoff base = 0; + if (way == std::ios::cur) base = pos_; + else if (way == std::ios::end) { + std::lock_guard guard(native->mu); + auto n = native->file.size(); + if (!n || n.value() > 0x7FFFFFFFFFFFFFFFULL) { good_ = false; return; } + base = static_cast(n.value()); + } + if ((off > 0 && base > 0x7FFFFFFFFFFFFFFFLL - off) || + (off < 0 && off < -base)) { good_ = false; return; } + pos_ = base + off; +} + +namespace { +thread_local std::uint64_t fs_current_owner = 0; +std::mutex fs_files_mu; +std::unordered_map> fs_files; +std::string fs_identity(const std::string& path) { +#if defined(_WIN32) + HANDLE h = ::CreateFileA(path.c_str(), FILE_READ_ATTRIBUTES, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return {}; + BY_HANDLE_FILE_INFORMATION i{}; + bool ok = ::GetFileInformationByHandle(h, &i) != 0; + ::CloseHandle(h); + if (!ok) return {}; + return std::to_string(i.dwVolumeSerialNumber) + ":" + + std::to_string(i.nFileIndexHigh) + ":" + std::to_string(i.nFileIndexLow); +#else + struct stat st{}; + if (::stat(path.c_str(), &st) != 0) return {}; + return std::to_string(st.st_dev) + ":" + std::to_string(st.st_ino); +#endif +} +std::int32_t own_lock_pid() { +#if defined(_WIN32) + return 1; +#else + return static_cast(::getpid()); +#endif +} +util::Error native_lock_error(const char* msg, const std::string& path) { +#if defined(_WIN32) + auto code = static_cast(::GetLastError()); +#else + auto code = errno; +#endif + return util::Error{5013, code, msg, path}; +} +} + +FsOwnerScope::FsOwnerScope(std::uint64_t owner) : previous_(fs_current_owner) { + fs_current_owner = owner; +} +FsOwnerScope::~FsOwnerScope() { fs_current_owner = previous_; } + +util::Result fs_lock_step(FsFile& f, std::uint64_t start, + std::uint64_t len, std::uint16_t type, + std::uint8_t op) { + if (op > 2 || (type & ~0x0300u) != 0 || start > 0x7FFFFFFFFFFFFFFFULL || + len > 0x7FFFFFFFFFFFFFFFULL - start) + return io_err(5000, "invalid lock range or flags", f.path); + auto state = f.stream.native; + std::lock_guard guard(state->mu); + const auto end = len == 0 ? 0x8000000000000000ULL : start + len; + auto overlap = [&](const FsRange& h) { + const auto he = h.len == 0 ? 0x8000000000000000ULL : h.start + h.len; + return start < he && h.start < end; + }; + auto& ranges = state->ranges; + // Like Harbour filebuf.c: test the merged process-local registrations + // first. Re-locking an owned overlap is an error, even with WAIT. + if (op != 1 && std::any_of(ranges.begin(), ranges.end(), overlap)) { + if (op == 2) return own_lock_pid(); + return io_err(5012, "range already locked by this process", f.path); + } + auto containing = ranges.end(); + if (op == 1) { + containing = std::find_if(ranges.begin(), ranges.end(), [&](const FsRange& h) { + auto he = h.len == 0 ? 0x8000000000000000ULL : h.start + h.len; + return start >= h.start && end <= he; + }); + if (containing == ranges.end()) return io_err(5012, "unlock range not held", f.path); + } + bool shared = (type & 0x0100u) != 0; +#if !defined(_WIN32) + // Harbour's Unix backend forces read-only opens to shared locks. + if (!f.writable) shared = true; +#endif +#if defined(_WIN32) + OVERLAPPED ov{}; + ov.Offset = static_cast(start); + ov.OffsetHigh = static_cast(start >> 32); + auto h = reinterpret_cast(state->file.native_handle()); + auto lo = static_cast(len), hi = static_cast(len >> 32); + if (op == 1) { + if (!::UnlockFileEx(h, 0, lo, hi, &ov)) return native_lock_error("UnlockFileEx", f.path); + } else { + DWORD flags = LOCKFILE_FAIL_IMMEDIATELY | (shared ? 0 : LOCKFILE_EXCLUSIVE_LOCK); + if (!::LockFileEx(h, flags, 0, lo, hi, &ov)) { + if (::GetLastError() == ERROR_LOCK_VIOLATION) return op == 2 ? 1 : 0; + return native_lock_error("LockFileEx", f.path); + } + if (op == 2) { + if (!::UnlockFileEx(h, 0, lo, hi, &ov)) return native_lock_error("UnlockFileEx test", f.path); + return 0; + } + } +#else + int fd = static_cast(reinterpret_cast(state->file.native_handle()) - 1); + struct flock fl{}; + fl.l_whence = SEEK_SET; + fl.l_start = static_cast(start); + fl.l_len = static_cast(len); + fl.l_type = op == 1 ? F_UNLCK : shared ? F_RDLCK : F_WRLCK; + fl.l_pid = 0; + // OFD locks preserve ownership for separate clients in one server + // process, and closing another client's descriptor cannot drop them. +#if defined(F_OFD_SETLK) && defined(F_OFD_GETLK) + constexpr int set_cmd = F_OFD_SETLK; + constexpr int get_cmd = F_OFD_GETLK; +#else +#error "FS client-owned locks require OFD byte-range lock support on this POSIX platform" +#endif + if (op == 2) { + if (::fcntl(fd, get_cmd, &fl) != 0) return native_lock_error("F_OFD_GETLK", f.path); + // POSIX reports -1 for an OFD owner: no process ID exists there. + return fl.l_type == F_UNLCK ? 0 : fl.l_pid > 0 ? static_cast(fl.l_pid) : 1; + } + if (::fcntl(fd, set_cmd, &fl) != 0) { + if (op == 0 && (errno == EAGAIN || errno == EACCES)) return 0; + return native_lock_error("F_SETLK", f.path); + } +#endif + if (op == 1) { + const auto hs = containing->start; + const auto he = containing->len == 0 ? 0x8000000000000000ULL : hs + containing->len; + auto idx = static_cast(containing - ranges.begin()); + ranges.erase(containing); + if (hs < start) ranges.insert(ranges.begin() + static_cast(idx++), {hs, start-hs}); + if (end < he) ranges.insert(ranges.begin() + static_cast(idx), + {end, he == 0x8000000000000000ULL ? 0 : he-end}); + } else { + ranges.push_back({start,len}); + std::sort(ranges.begin(), ranges.end(), [](const FsRange& a, const FsRange& b) { return a.start < b.start; }); + for (std::size_t i = 1; i < ranges.size();) { + auto& prev = ranges[i-1]; + if (prev.len != 0 && prev.start + prev.len == ranges[i].start) { + prev.len = ranges[i].len == 0 ? 0 : prev.len + ranges[i].len; + ranges.erase(ranges.begin() + static_cast(i)); + } else ++i; + } + } + return 1; +} + util::Result> fs_open(const std::string& abs_path, - std::uint16_t mode, - bool create) { + std::uint16_t mode, bool create) { auto f = std::make_unique(); f->path = abs_path; f->writable = create || (mode != ADS_FO_READ && mode != 3); - std::ios::openmode om = std::ios::binary; - if (create) { - om |= std::ios::in | std::ios::out | std::ios::trunc; - } else if (mode == ADS_FO_READ || mode == 3 /*ADS_READONLY*/) { - // Two conventions reach here: Harbour-style FO_READ (0) and the - // SAP ace.h ADS_READONLY (3) that oads_FOpen callers pass. Both - // must open read-only so FWrite on the handle fails. - om |= std::ios::in; - } else if (mode == ADS_FO_WRITE) { - om |= std::ios::in | std::ios::out; - } else { - om |= std::ios::in | std::ios::out; - } - f->stream.open(abs_path, om); - if (!f->stream) { - // Try create parent path for FCreate. + std::lock_guard global(fs_files_mu); + auto owner_key = [&](const std::string& identity) { + return identity.empty() ? identity : identity + ":owner:" + std::to_string(fs_current_owner); + }; + auto key = owner_key(fs_identity(abs_path)); + std::shared_ptr state; + if (!key.empty()) state = fs_files[key].lock(); + if (state) { + std::lock_guard guard(state->mu); + if (f->writable && !state->writable) { + // Win32 lock ownership is per native handle. Never switch away + // from a handle that still holds byte ranges. + if (!state->ranges.empty()) return io_err(5012, "locked read-only file cannot upgrade", abs_path); + auto upgraded = platform::File::open(abs_path, platform::OpenMode::ReadWrite); + if (!upgraded) return upgraded.error(); + state->retained.push_back(std::move(state->file)); + state->file = std::move(upgraded.value()); + state->writable = true; + } if (create) { + auto v = state->file.truncate(0); + if (!v) return v.error(); + } + } else { + auto native = platform::File::open(abs_path, create ? platform::OpenMode::CreateRW : + f->writable ? platform::OpenMode::ReadWrite : platform::OpenMode::ReadOnly); + if (!native && create) { std::error_code ec; fs::create_directories(fs::path(abs_path).parent_path(), ec); - f->stream.clear(); - f->stream.open(abs_path, om); + native = platform::File::open(abs_path, platform::OpenMode::CreateRW); } + if (!native) return native.error(); + state = std::make_shared(); + state->file = std::move(native.value()); + state->writable = f->writable; + key = owner_key(fs_identity(abs_path)); + if (!key.empty()) fs_files[key] = state; + // Remove expired weak entries so file churn does not retain names. + for (auto it = fs_files.begin(); it != fs_files.end();) + if (it->second.expired()) it = fs_files.erase(it); else ++it; } - if (!f->stream) - return io_err(static_cast( - create ? openads::AE_INTERNAL_ERROR - : openads::AE_NO_FILE_FOUND), - create ? "create failed" : "open failed", abs_path); + f->stream.native = std::move(state); + f->stream.writable = f->writable; return f; } diff --git a/src/engine/server_fs.h b/src/engine/server_fs.h index 66b24526..3096d693 100644 --- a/src/engine/server_fs.h +++ b/src/engine/server_fs.h @@ -1,6 +1,8 @@ #pragma once #include "util/result.h" +#include "platform/file.h" +#include #include #include @@ -57,7 +59,7 @@ util::Result fs_truncate(const std::string& abs_path, // with prefix; returns the file name (not the full path). util::Result fs_tempfile(const std::string& abs_dir, const std::string& prefix); -// type 0 = free available, 1 = total capacity, 2 = free. +// type 0 = available, 1 = free, 2 = used, 3 = total. util::Result fs_dir_space(const std::string& abs_dir, std::uint8_t type); util::Result fs_size(const std::string& abs_path); @@ -70,11 +72,55 @@ util::Result fs_dir_exist(const std::string& abs_path); util::Result fs_dir_make(const std::string& abs_path); util::Result fs_dir_remove(const std::string& abs_path); +// Remote connections own separate native lock state, like separate Harbour +// processes; within an owner opens share Harbour-style merged byte ranges. +class FsOwnerScope { +public: + explicit FsOwnerScope(std::uint64_t owner); + ~FsOwnerScope(); +private: + std::uint64_t previous_; +}; +// FS-only native state and merged byte ranges, separate from RDD locks. +struct FsRange { std::uint64_t start, len; }; +struct FsNative { + platform::File file; + // Keep prior descriptors alive through a read-only to read/write upgrade; + // no upgrade is allowed while this owner's file holds byte ranges. + std::vector retained; + std::mutex mu; + std::vector ranges; + bool writable = false; +}; +class FsStream { +public: + std::shared_ptr native; + bool writable = false; + void clear() { good_ = true; } + explicit operator bool() const { return good_ && native && native->file.is_open(); } + void read(char* data, std::streamsize n); + void write(const char* data, std::streamsize n); + void flush(); + std::streamsize gcount() const { return count_; } + std::streampos tellg() const { return good_ ? std::streampos(pos_) : std::streampos(-1); } + void seekg(std::streamoff off, std::ios::seekdir way = std::ios::beg); + void seekg(std::streampos pos) { seekg(static_cast(pos)); } + void seekp(std::streampos pos) { seekg(pos); } +private: + std::streamoff pos_ = 0; + std::streamsize count_ = 0; + bool good_ = true; +}; struct FsFile { - std::fstream stream; - std::string path; + FsStream stream; + std::string path; bool writable = false; }; +// One non-blocking native attempt. op 0 lock, 1 unlock, 2 query. +// Lock result 0 busy, 1 success. Query 0 free, positive owner, -1 error. +util::Result fs_lock_step(FsFile& file, std::uint64_t start, + std::uint64_t len, std::uint16_t type, + std::uint8_t op); util::Result fs_truncate(FsFile& file, std::uint64_t size); // create=true → create/truncate (FCreate). mode uses ADS_FO_*. diff --git a/src/network/client.cpp b/src/network/client.cpp index 8e6e47db..59024a3c 100644 --- a/src/network/client.cpp +++ b/src/network/client.cpp @@ -3117,6 +3117,23 @@ RemoteConnection::file_set_time(const std::string& path, std::uint16_t year, return {}; } +util::Result +RemoteConnection::file_lock_step(std::uint32_t id, std::uint64_t start, + std::uint64_t len, std::uint16_t type, std::uint8_t op) { + Frame req; + req.opcode = Opcode::FileLockOp; + write_u32_le(id, req.payload); + write_u64_le(start, req.payload); + write_u64_le(len, req.payload); + write_u16_le(type, req.payload); + req.payload.push_back(op); + auto rep = request(req); + if (!rep) return rep.error(); + if (rep.value().opcode != Opcode::FileLockOp || rep.value().payload.size() != 4) + return fs_wire_err(rep.value(), "FileLockOp"); + return static_cast(read_u32_le(rep.value().payload.data())); +} + util::Result RemoteConnection::ftruncate(std::uint32_t file_id, std::uint64_t size) { Frame req; diff --git a/src/network/client.h b/src/network/client.h index 2601693f..982b9597 100644 --- a/src/network/client.h +++ b/src/network/client.h @@ -450,6 +450,8 @@ class RemoteConnection { std::uint8_t hh, std::uint8_t mm, std::uint8_t ss); + util::Result file_lock_step(std::uint32_t file_id, std::uint64_t start, + std::uint64_t len, std::uint16_t type, std::uint8_t op); util::Result ftruncate(std::uint32_t file_id, std::uint64_t size); util::Result file_temp(const std::string& dir, diff --git a/src/network/session.cpp b/src/network/session.cpp index 34d9c671..d1b5475f 100644 --- a/src/network/session.cpp +++ b/src/network/session.cpp @@ -1658,6 +1658,8 @@ void Session::append_open_warm_sections(std::vector& out, } DispatchResult Session::dispatch(const Frame& f) { + // Distinct remote connections behave as distinct Harbour processes. + openads::engine::FsOwnerScope fs_owner(reinterpret_cast(this)); Frame reply; if (srv_->auth_required() && (f.opcode == Opcode::Connect || f.opcode == Opcode::MgConnect)) return {err("Challenge authentication required", openads::AE_LOGIN_FAILED), true}; @@ -1712,6 +1714,7 @@ DispatchResult Session::dispatch(const Frame& f) { case Opcode::FRead: case Opcode::FWrite: case Opcode::FSeek: case Opcode::FileReadAt: case Opcode::FileWriteAt: case Opcode::FileFlush: case Opcode::FileEof: + case Opcode::FileLockOp: case Opcode::FileTrunc: case Opcode::ZipArchive: case Opcode::UnzipArchive: case Opcode::ZipList: if (!admin) return denied(); @@ -4259,6 +4262,7 @@ DispatchResult Session::dispatch(const Frame& f) { case Opcode::FileWriteAt: case Opcode::FileFlush: case Opcode::FileEof: + case Opcode::FileLockOp: case Opcode::FileTrunc: { if (!srv_->enable_file_func()) { reply = err("file functions disabled", @@ -4789,6 +4793,22 @@ DispatchResult Session::dispatch(const Frame& f) { reply.opcode = Opcode::FileEofAck; reply.payload.push_back( (cur < 0 || (end >= 0 && cur >= end)) ? 1 : 0); + } else if (f.opcode == Opcode::FileLockOp) { + if (f.payload.size() != 23) { reply = err("FileLockOp: bad payload"); break; } + auto id = read_u32_le(f.payload.data()); + auto it = files_.find(id); + if (it == files_.end()) { reply = err("FileLockOp: bad handle"); break; } + std::uint64_t start = 0, len = 0; + for (std::size_t i = 0; i < 8; ++i) { + start |= static_cast(f.payload[4+i]) << (8*i); + len |= static_cast(f.payload[12+i]) << (8*i); + } + auto type = static_cast(f.payload[20] | + (static_cast(f.payload[21]) << 8)); + auto v = openads::engine::fs_lock_step(*it->second, start, len, type, f.payload[22]); + if (!v) { reply = err("FileLockOp", static_cast(v.error().code)); break; } + reply.opcode = Opcode::FileLockOp; + write_u32_le(static_cast(v.value()), reply.payload); } else if (f.opcode == Opcode::FileTrunc) { if (f.payload.size() < 12) { reply = err("FileTrunc: short payload"); break; diff --git a/src/network/wire.cpp b/src/network/wire.cpp index e7b8ecc0..49c2f01d 100644 --- a/src/network/wire.cpp +++ b/src/network/wire.cpp @@ -228,6 +228,7 @@ bool valid_opcode(std::uint8_t opcode) noexcept { case static_cast(Opcode::FileSetAttrAck): case static_cast(Opcode::FileSetTime): case static_cast(Opcode::FileSetTimeAck): + case static_cast(Opcode::FileLockOp): case static_cast(Opcode::FileTrunc): case static_cast(Opcode::FileTruncAck): case static_cast(Opcode::FileTemp): diff --git a/src/network/wire.h b/src/network/wire.h index b30d115d..355e4e83 100644 --- a/src/network/wire.h +++ b/src/network/wire.h @@ -72,6 +72,10 @@ enum class Opcode : std::uint8_t { FileSetTime = 0x36, FileSetTimeAck = 0x37, // FileTrunc: [u32 file_id][u64 size] -> empty ack + // FileLockOp request: [u32 id][u64 start][u64 len][u16 type][u8 op] + // op=0 lock, 1 unlock, 2 conflict test. Same-opcode reply: [i32 result/PID]. + // Server always makes ONE non-blocking OS attempt. WAIT belongs to client. + FileLockOp = 0x0F, FileTrunc = 0x38, FileTruncAck = 0x39, // FileTemp: [u16 dirLen][dir][u16 prefixLen][prefix] @@ -79,7 +83,7 @@ enum class Opcode : std::uint8_t { FileTemp = 0x3A, FileTempAck = 0x3B, // DirSpace: [u16 dirLen][dir][u8 type] -> [u64 bytes] - // type 0 = free available, 1 = total capacity, 2 = free + // type 0 = available, 1 = free, 2 = used, 3 = total DirSpace = 0x3C, DirSpaceAck = 0x1F, // 0x3D+ is taken; last free slot below 0x20 ExecuteSQL = 0x30, diff --git a/src/openads_ace.def b/src/openads_ace.def index bf174331..72defd14 100644 --- a/src/openads_ace.def +++ b/src/openads_ace.def @@ -130,6 +130,9 @@ EXPORTS AdsSetFileAttr AdsSetFileTime AdsFTrunc + AdsFLockTest + AdsFUnlock + AdsFLock AdsTempFile AdsDirSpace AdsGetFileSize @@ -167,6 +170,9 @@ EXPORTS oads_SetFileAttr oads_SetFileTime oads_FTrunc + oads_FLockTest + oads_FUnlock + oads_FLock oads_TempFile oads_DirSpace oads_GetFileSize diff --git a/src/openads_ace_x86_stdcall.def b/src/openads_ace_x86_stdcall.def index 7a2b8627..93a20edb 100644 --- a/src/openads_ace_x86_stdcall.def +++ b/src/openads_ace_x86_stdcall.def @@ -37,6 +37,9 @@ EXPORTS oads_SetFileAttr oads_SetFileTime oads_FTrunc + oads_FLockTest + oads_FUnlock + oads_FLock oads_TempFile oads_DirSpace oads_GetFileSize diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f4dd2698..c4587713 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -621,3 +621,11 @@ if(UNIX AND TARGET auth_mutual_probe) "${CMAKE_BINARY_DIR}/tools/serverd/mutual-test-only.hrb") set_tests_properties(auth_mutual_v2 PROPERTIES TIMEOUT 120 RUN_SERIAL TRUE) endif() + +# mtfix85: independent-process FS byte-range lock proof, no RDD dependency. +add_executable(openads_fs_lock85_probe fs_lock85_probe.cpp) +target_link_libraries(openads_fs_lock85_probe PRIVATE openads_core) +target_include_directories(openads_fs_lock85_probe PRIVATE ${PROJECT_SOURCE_DIR}/src) +add_dependencies(openads_unit_tests openads_fs_lock85_probe) +add_test(NAME fs_lock85_process COMMAND openads_fs_lock85_probe) +set_tests_properties(fs_lock85_process PROPERTIES TIMEOUT 20) diff --git a/tests/fs_lock85_probe.cpp b/tests/fs_lock85_probe.cpp new file mode 100644 index 00000000..5b687760 --- /dev/null +++ b/tests/fs_lock85_probe.cpp @@ -0,0 +1,62 @@ +// Independent processes must contend through real OS byte-range locks. +#include "engine/server_fs.h" +#include +#include +#include +#include +#include +#include +#include +using namespace openads::engine; +namespace fs = std::filesystem; +int main(int argc, char** argv) { + if (argc == 4 && std::string(argv[1]) == "hold") { + auto f = fs_open(argv[2], 2, false); + if (!f) return 20; + auto v = fs_lock_step(*f.value(), 128, 16, 0, 0); + if (!v || !v.value()) return 21; + std::ofstream marker(argv[3]); marker << "ready"; marker.close(); + std::this_thread::sleep_for(std::chrono::milliseconds(2000)); + return 0; + } + if (argc == 5 && std::string(argv[1]) == "child") { + auto f = fs_open(argv[2], 2, false); + if (!f) return 10; + const auto type = std::string(argv[3]) == "shared" ? 0x100 : 0; + auto r = fs_lock_step(*f.value(), 0, 16, static_cast(type), 0); + if (!r) return 11; + const bool want = std::string(argv[4]) == "free"; + return ( r.value() != 0 ) == want ? 0 : 12; + } + auto dir = fs::temp_directory_path() / ("openads-lock85-" + std::to_string( + std::chrono::steady_clock::now().time_since_epoch().count())); + fs::create_directories(dir); + auto path = dir / "lock.bin"; + auto f = fs_open(path.string(), 2, true); + if (!f) return 1; + auto child = [&](const char* kind, const char* expected) { + // ctest registers the binary with forward slashes; cmd.exe rejects + // that in the child command line, so use native separators. + std::string cmd = "\"" + fs::absolute(argv[0]).make_preferred().string() + "\" child \"" + + path.string() + "\" " + kind + " " + expected; +#if defined(_WIN32) + // cmd.exe strips a leading quote plus the last quote on the line, + // mangling the inner paths; an outer quote pair keeps them intact + // (same pattern as the holder spawn in abi_oads_file_funcs_test). + cmd = "\"" + cmd + "\""; +#endif + return std::system(cmd.c_str()) == 0; + }; + auto locked = fs_lock_step(*f.value(),0,16,0,0); + if (!locked || !locked.value() || !child("exclusive","busy") || + !child("shared","busy")) return 2; + if (!fs_lock_step(*f.value(),0,16,0,1) || !child("exclusive","free")) return 3; + auto shared = fs_lock_step(*f.value(),0,16,0x100,0); + if (!shared || !shared.value() || !child("shared","free") || + !child("exclusive","busy")) return 4; + f.value().reset(); + if (!child("exclusive","free")) return 5; + fs::remove_all(dir); + std::cout << "FS-LOCK85-CROSS-PROCESS-PASS\n"; + return 0; +} diff --git a/tests/unit/abi_oads_file_funcs_test.cpp b/tests/unit/abi_oads_file_funcs_test.cpp index 668cd2f9..fca24bd7 100644 --- a/tests/unit/abi_oads_file_funcs_test.cpp +++ b/tests/unit/abi_oads_file_funcs_test.cpp @@ -31,8 +31,11 @@ #include "openads/ace.h" #include "openads/error.h" #include "network/server.h" +#include "platform/path.h" #include +#include +#include #include #include #include @@ -637,6 +640,120 @@ TEST_CASE( "oads_* local: Load Save ReadAt WriteAt Flush Eof" ) fs::remove_all( dir, ec ); } +static fs::path lock85_probe_path() +{ + // Resolve before any case changes the working directory: dladdr can + // return a relative loader path when the test binary is invoked by a + // relative path, and absolute() would then anchor at the wrong cwd. + auto module = openads::platform::module_directory(); + REQUIRE( module.has_value() ); + fs::path probe = fs::absolute( fs::path( *module ) ) / "openads_fs_lock85_probe"; +#if defined(_WIN32) + probe += ".exe"; +#endif + return probe; +} + +static void lock_round_trip( ADSHANDLE h, const fs::path& dir, const fs::path& probe ) +{ + ADSHANDLE a = 0, b = 0, c = 0; + REQUIRE( oads_FCreate( h, (UNSIGNED8*)"locks.bin", 0, &a ) == 0 ); + REQUIRE( oads_FOpen( h, (UNSIGNED8*)"locks.bin", 2, &b ) == 0 ); + REQUIRE( oads_FOpen( h, (UNSIGNED8*)"locks.bin", 2, &c ) == 0 ); + REQUIRE( oads_FLock( a, 0, 16, 0 ) == 0 ); + CHECK( oads_FLock( b, 0, 16, 0 ) == 5012 ); + CHECK( oads_FLock( b, 0, 16, 0x100 ) == 5012 ); + SIGNED32 result = -1; + REQUIRE( oads_FLockTest( b, 0, 16, 0, &result ) == 0 ); + CHECK( result > 0 ); + // Locking must not block I/O through the owning native handle. + UNSIGNED32 wrote = 0, got = 0; + REQUIRE( oads_FWriteAt( a, 0, "owned", 5, &wrote ) == 0 ); + CHECK( wrote == 5 ); + char buf[8] = {}; + REQUIRE( oads_FReadAt( a, 0, buf, 5, &got ) == 0 ); + CHECK( std::string( buf, got ) == "owned" ); + // A disjoint range can be held concurrently. + REQUIRE( oads_FLock( b, 64, 16, 0 ) == 0 ); + REQUIRE( oads_FUnlock( b, 64, 16 ) == 0 ); + + CHECK( oads_FLock( b, 0, 16, 1 ) != 0 ); + CHECK( oads_FLock( b, 0x7FFFFFFFFFFFFFFFULL, 1, 0 ) != 0 ); + // Harbour refuses own/process-local overlapping relocks, even WAIT. + CHECK( oads_FLock( b, 0, 16, 0x200 ) == 5012 ); + REQUIRE( oads_FUnlock( a, 0, 16 ) == 0 ); + REQUIRE( oads_FLock( a, 0, 16, 0x100 ) == 0 ); + CHECK( oads_FLock( b, 0, 16, 0x100 ) == 5012 ); + REQUIRE( oads_FUnlock( a, 0, 16 ) == 0 ); + // Adjacent locks merge in the registry. Unix can split that merged + // range with partial unlock; Windows preserves native exact unlock. + REQUIRE( oads_FLock( a, 0, 8, 0 ) == 0 ); + REQUIRE( oads_FLock( a, 8, 8, 0 ) == 0 ); +#if defined(_WIN32) + CHECK( oads_FUnlock( a, 4, 4 ) != 0 ); + REQUIRE( oads_FUnlock( a, 0, 8 ) == 0 ); + REQUIRE( oads_FUnlock( a, 8, 8 ) == 0 ); +#else + REQUIRE( oads_FUnlock( a, 4, 4 ) == 0 ); + REQUIRE( oads_FLockTest( b, 4, 4, 0, &result ) == 0 ); + CHECK( result == 0 ); + REQUIRE( oads_FUnlock( a, 0, 4 ) == 0 ); + REQUIRE( oads_FUnlock( a, 8, 8 ) == 0 ); + REQUIRE( oads_FLock( a, 64, 0, 0 ) == 0 ); // to EOF on Unix + REQUIRE( oads_FUnlock( a, 64, 0 ) == 0 ); +#endif + // A real other process holds byte 128 until it exits. WAIT must + // complete after that release, without blocking the server thread. + REQUIRE( fs::exists(probe) ); + auto marker = dir / "holder-ready"; + fs::remove(marker); + std::string command = "\"" + probe.string() + "\" hold \"" + + (dir / "locks.bin").string() + "\" \"" + marker.string() + "\""; +#if defined(_WIN32) + command = "\"" + command + "\""; +#endif + std::atomic child_rc{-1}; + std::thread holder([&] { child_rc.store(std::system(command.c_str())); }); + bool ready = false; + for (int i = 0; i < 300; ++i) { + if (fs::exists(marker)) { ready = true; break; } + if (child_rc.load() != -1) break; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + UNSIGNED32 wait_rc = 999; + if (ready) { + CHECK( oads_FLock( a, 128, 16, 0 ) == 5012 ); + CHECK( oads_FLockTest( a, 128, 16, 0, &result ) == 0 ); + CHECK( result > 0 ); // POSIX PID, Windows 1 + wait_rc = oads_FLock( a, 128, 16, 0x200 ); + if (wait_rc == 0) oads_FUnlock( a, 128, 16 ); + } + holder.join(); + CHECK( ready ); + CHECK( child_rc.load() == 0 ); + CHECK( wait_rc == 0 ); + REQUIRE( oads_FLock( a, 32, 16, 0 ) == 0 ); + REQUIRE( oads_FClose(a) == 0 ); // other references retain merged locks + CHECK( oads_FLock( b, 32, 16, 0 ) == 5012 ); + REQUIRE( oads_FUnlock( b, 32, 16 ) == 0 ); + REQUIRE( oads_FLockTest( c, 0, 16, 0, &result ) == 0 ); + CHECK( result == 0 ); + REQUIRE( oads_FClose(b) == 0 ); + REQUIRE( oads_FClose(c) == 0 ); + CHECK( oads_FLock( b, 0, 16, 0 ) != 0 ); +} + +TEST_CASE( "oads_* local: FS byte locks shared exclusive wait and owner IO" ) +{ + auto dir = fs::temp_directory_path() / "oads_file_g4"; + fs::remove_all(dir); + fs::create_directories(dir); + auto h = local_connect(dir); + lock_round_trip(h, dir, lock85_probe_path()); + REQUIRE( AdsDisconnect(h) == 0 ); + fs::remove_all(dir); +} + static void metadata_round_trip( ADSHANDLE h, const fs::path& dir ) { REQUIRE( oads_SaveFile( h, (UNSIGNED8*)"m.txt", "0123456789", 10 ) == 0 ); @@ -706,12 +823,18 @@ static void metadata_round_trip( ADSHANDLE h, const fs::path& dir ) // DirSpace: capacity positive, available/free no more than capacity UNSIGNED64 ullCap = 0, ullAvail = 0, ullFree = 0; - REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 1, &ullCap ) == 0 ); + REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 3, &ullCap ) == 0 ); REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 0, &ullAvail ) == 0 ); - REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 2, &ullFree ) == 0 ); + REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 1, &ullFree ) == 0 ); CHECK( ullCap > 0 ); CHECK( ullAvail <= ullCap ); CHECK( ullFree <= ullCap ); + UNSIGNED64 ullUsed = 0; + REQUIRE( oads_DirSpace( h, (UNSIGNED8*)"", 2, &ullUsed ) == 0 ); + CHECK( ullUsed <= ullCap ); + // Disk use can move between requests; allow 64 MiB of runner activity. + auto sum = ullUsed + ullFree; + CHECK( (sum > ullCap ? sum - ullCap : ullCap - sum) < 64ull*1024ull*1024ull ); CHECK( oads_SetFileAttr( h, (UNSIGNED8*)"../outside.txt", 1 ) != 0 ); CHECK( oads_SetFileTime( h, (UNSIGNED8*)"../outside.txt", 2021, 3, 4, 5, 6, 7 ) != 0 ); @@ -880,11 +1003,46 @@ TEST_CASE( "oads_* remote embedded: full round-trip" ) REQUIRE( srv.start( "127.0.0.1", 0 ).has_value() ); auto prev = fs::current_path(); + const fs::path probe85 = lock85_probe_path(); fs::current_path( app ); ADSHANDLE h = remote_connect_embedded( data, srv.port() ); oads_round_trip( h, "remote-embedded" ); metadata_round_trip( h, data ); + lock_round_trip( h, data, probe85 ); + + // Different client connections are separate lock owners, like two + // Harbour processes. Same-client opens still share merged ranges. + auto peer = remote_connect_embedded(data, srv.port()); + ADSHANDLE left = 0, right = 0; + REQUIRE( oads_FOpen(h, (UNSIGNED8*)"locks.bin", 2, &left) == 0 ); + REQUIRE( oads_FOpen(peer, (UNSIGNED8*)"locks.bin", 2, &right) == 0 ); + REQUIRE( oads_FLock(left, 0, 16, 0x100) == 0 ); + REQUIRE( oads_FLock(right, 0, 16, 0x100) == 0 ); + REQUIRE( oads_FUnlock(left, 0, 16) == 0 ); + REQUIRE( oads_FUnlock(right, 0, 16) == 0 ); + REQUIRE( oads_FLock(left, 0, 16, 0) == 0 ); + CHECK( oads_FLock(right, 0, 16, 0) == 5012 ); + std::atomic done{false}; + std::atomic wait_rc{999}; + std::thread waiter([&] { wait_rc.store(oads_FLock(right,0,16,0x200)); done.store(true); }); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + CHECK_FALSE(done.load()); + CHECK( oads_FUnlock(left,0,16) == 0 ); + for (int i=0; i<300 && !done.load(); ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + if (!done.load()) oads_FClose(right); + waiter.join(); + CHECK(wait_rc.load() == 0); + CHECK(oads_FUnlock(right,0,16) == 0); + CHECK(oads_FLock(left,32,16,0) == 0); + CHECK(oads_FClose(left) == 0); + REQUIRE(AdsDisconnect(h) == 0); + CHECK(oads_FLock(right,32,16,0) == 0); + CHECK(oads_FUnlock(right,32,16) == 0); + CHECK(oads_FClose(right) == 0); + REQUIRE(AdsDisconnect(peer) == 0); + h = remote_connect_embedded(data,srv.port()); // verify file lands in server data dir, not client cwd CHECK_FALSE( fs::exists( app / "oads_test.txt" ) ); diff --git a/tests/unit/network_server_test.cpp b/tests/unit/network_server_test.cpp index f8c18dfa..33515ee7 100644 --- a/tests/unit/network_server_test.cpp +++ b/tests/unit/network_server_test.cpp @@ -162,11 +162,8 @@ TEST_CASE("M12.3 server unknown opcode returns Error frame") { Socket cs = cli.value(); Frame req; - // Pick a value outside every defined op so the server's - // default-case path is what answers. 0xFE was claimed by the - // Mutex service (M12.32); 0x0F sits in a gap between FindRecordAck - // (0x0E) and Connect (0x10) with nothing defined. - req.opcode = static_cast(0x0F); // truly unknown + // 0x0F is now FileLockOp. 0x00 remains unassigned. + req.opcode = static_cast(0x00); REQUIRE(write_frame(cs, req).has_value()); auto reply = read_frame(cs); REQUIRE(reply.has_value());