auto
      auto
  6   ˆl—ß=¿Jõ4Ÿº‚ œP.\—}LZ7ÿ�þB g Ùl,È28çÂƒh¹ÁÀ¿      ˆÃ‘äÇò 8à$ån6†ÔŸÏÂƒh¹ÁÀ¿      tty0 ttyS0
      disabled
      ˆÃ‘äÇò 8à$ån6†ÔŸÏÂƒh¹ÁÀ¿      disabled
  B   ˆl–Ðz¾”Šj"Tâ‚À½q¶”Å£�þDÆ³�”�ÆèdzW�üÿÃƒyÇ™Â_ŠI|¥�+Wé3ž¯ÂÁ !ë    from __future__ import annotations

import os
import socket
import sys
import time
from contextlib import suppress
from errno import EACCES, EEXIST, EPERM, ESRCH
from pathlib import Path

from ._api import BaseFileLock
from ._util import ensure_directory_exists, raise_on_not_writable_file

_WIN_SYNCHRONIZE = 0x100000
_WIN_ERROR_INVALID_PARAMETER = 87
_WIN_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
_MALFORMED_LOCK_AGE_THRESHOLD = 2.0
_MAX_LOCK_FILE_SIZE = 1024


class SoftFileLock(BaseFileLock):
    """
    Portable file lock based on file existence.

    Unlike :class:`UnixFileLock <filelock.UnixFileLock>` and :class:`WindowsFileLock <filelock.WindowsFileLock>`, this
    lock does not use OS-level locking primitives. Instead, it creates the lock file with ``O_CREAT | O_EXCL`` and
    treats its existence as the lock indicator. This makes it work on any filesystem but leaves stale lock files behind
    if the process crashes without releasing the lock.

    To mitigate stale locks, the lock file contains the PID and hostname of the holding process. On contention, if the
    holder is on the same host and its PID no longer exists, the stale lock is broken automatically.

    """

    def _acquire(self) -> None:
        raise_on_not_writable_file(self.lock_file)
        ensure_directory_exists(self.lock_file)
        flags = (
            os.O_WRONLY  # open for writing only
            | os.O_CREAT
            | os.O_EXCL  # together with above raise EEXIST if the file specified by filename exists
            | os.O_TRUNC  # truncate the file to zero byte
        )
        if (o_nofollow := getattr(os, "O_NOFOLLOW", None)) is not None:
            flags |= o_nofollow
        try:
            file_handler = os.open(self.lock_file, flags, self._open_mode())
        except OSError as exception:
            if not (
                exception.errno == EEXIST or (exception.errno == EACCES and sys.platform == "win32")
            ):  # pragma: win32 no cover
                raise
            self._try_break_stale_lock()
        else:
            self._write_lock_info(file_handler)
            self._context.lock_file_fd = file_handler

    def _try_break_stale_lock(self) -> None:
        with suppress(OSError, ValueError):
            content, mtime = _read_lock_file(self.lock_file)
            lines = content.strip().splitlines() if content else []

            if len(lines) not in {2, 3}:
                if time.time() - mtime >= _MALFORMED_LOCK_AGE_THRESHOLD:
                    self._evict_lock_file()
                return

            pid_str, hostname = lines[0], lines[1]
            creation_time_str = lines[2] if len(lines) == 3 else None  # noqa: PLR2004

            if hostname != socket.gethostname():
                return

            pid = int(pid_str)

            if self._is_process_alive(pid):
                if sys.platform == "win32" and creation_time_str is not None:  # pragma: win32 cover
                    stored = int(creation_time_str)
                    actual = self._get_process_creation_time(pid)
                    if actual is not None and actual != stored:
                        pass  # PID recycled, fall through to evict
                    else:
                        return  # same process or can't verify â€” don't evict
                else:
                    return

            self._evict_lock_file()

    def _evict_lock_file(self) -> None:
        break_path = f"{self.lock_file}.break.{os.getpid()}"
        Path(self.lock_file).rename(break_path)
        Path(break_path).unlink()

    @staticmethod
    def _is_process_alive(pid: int) -> bool:
        if sys.platform == "win32":  # pragma: win32 cover
            import ctypes  # noqa: PLC0415

            kernel32 = ctypes.windll.kernel32
