Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 57 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,28 @@
- 人类审查者是最终闸门;未获明确批准,Agent 不得进入下一阶段。
- “测试通过”不是全局属性的验收证据。
- Agent 不得隐瞒未覆盖项,不得让报告与 diff 不一致。
- Agent 无论在协定更改计划和拆分还是增量开发执行时一旦遇到边界模糊的情况不要盲猜,立即向人类审查者提问或停止等待人类审查者确认。

---

## 边界模糊处理(强制)

任何 Agent 在方案讨论/原子拆分和增量实现阶段,遇到以下任一情况,必须立即停止当前原子的修改,将状态标记为 BLOCKED,并向人类审查者提问,等待明确确认后才能继续:

- 验收标准不可验证,或存在多种合理解释;
- 接口契约、数据结构、公共行为未定义,或与现有代码事实冲突;
- 需要修改测试、文档、依赖、配置、数据库迁移或公共接口才能继续;
- 实现路径存在多个合理方案,且影响范围、风险或回滚成本不同;
- 发现计划描述与现有代码不一致;
- 涉及安全、权限、并发、数据一致性等高风险判断。

提问必须包含:阻塞点、已确认的事实、候选方案(如有)、受影响的文件和原子、需要人类决定的具体问题。禁止只问“这里模糊,怎么办”。

未获确认前,Agent 不得自行选择默认方案、猜测意图、扩大原子范围,也不得通过修改测试或文档来绕过模糊点。测试失败时,修正产品代码使测试通过,不得修改测试来适配实现。

非阻塞的局部实现细节(命名、格式、等价写法)可按仓库现有约定处理,但必须在输出中记录假设;不得把非阻塞问题伪装成阻塞,也不得把阻塞问题降级为假设继续做。

如果 Agent 不确定某个情况是否属于边界模糊,在增量实现阶段按“是”处理并停止提问;在方案讨论阶段可以提问并给出候选方案,但不自行拍板。

---

Expand Down Expand Up @@ -77,13 +99,18 @@ Agent 先不写代码,先交计划。人类明确批准后,才进入执行
6. 每条路径的验收命令/证据
7. 风险与明确未覆盖项
8. 是否触及 CI、测试策略、依赖、公共接口;如有,单独标注
9. 测试规格:每个原子对应的验收标准/契约断言,必须在计划阶段定稿;测试代码的实现放到独立流程,但测试断言的内容不得在看到产品代码实现后再改。
10. 文档更新清单:每个原子触及的文档(接口文档、运维说明、变更记录)逐条列出,作为原子审查通过后的独立提交依据。
```

### 拆分规则

- 划分依据是单一意图 / 单一执行路径,不是行数;
- 单提交建议不超过 300–500 行;超过是警报,说明混了多个意图,应退回重拆;
- 拆分方案必须在计划阶段定稿,不得“边写边拆”。
- 每个原子提交的变更范围仅限产品代码。测试文件和文档不在原子提交内,由提交后的独立流程处理。
- 拆分方案必须逐原子标注涉及的产品代码文件;如果某个原子需要先改接口契约或数据模型,契约变更单独成原子,不得把测试或文档夹带进去。
- 如果实现某个原子必须同步改测试才能验证,说明该原子的验收标准没有在计划阶段定清楚,退回“计划与拆分”修订,而不是在执行时顺手改测试。

### 通过标准

Expand All @@ -103,7 +130,7 @@ Agent 先不写代码,先交计划。人类明确批准后,才进入执行
改动内容:文件与关键变更点。
为什么这样改:对应需求卡哪条路径/约束。
局部验证:执行的命令/测试/检查及结果。
明确未覆盖:本提交刻意未覆盖的路径或场景。
明确未覆盖:本提交刻意未覆盖的路径或场景。测试与文档不在本提交范围内,由独立流程处理。
风险与待确认:需要人类注意的点。
```

Expand All @@ -121,6 +148,7 @@ Agent 先不写代码,先交计划。人类明确批准后,才进入执行
- 该路径的局部验证通过;
- 无红旗;
- 未覆盖项被明确接受或补完。
- 本提交 diff 不含测试文件和文档变更;如出现测试或文档修改,按“范围偏差”退回,不得以“顺手修正”为由放行。

未满足则退回,不得进入下一个提交。

Expand Down Expand Up @@ -151,6 +179,30 @@ Agent 先不写代码,先交计划。人类明确批准后,才进入执行

---

## 原子提交后的测试与文档更新

每个原子提交审查通过后,进入独立的测试与文档更新流程。该流程的变更单独提交,不回溯混入已审查的产品代码提交。

### 测试更新

- 测试代码由独立步骤实现,执行产品代码的 Agent 不得在同一原子提交中修改测试。
- 测试的断言内容必须来自计划阶段的“测试规格”,不得在看到产品代码实现后放宽、改写或删除断言来适配实现。
- 测试提交的审查重点:断言是否弱化、是否只覆盖 happy path、是否 mock 掉关键路径、是否与计划阶段的验收标准一致。
- 如果测试暴露出产品代码意图偏差,退回对应原子重新审查,不得只改测试来适配错误实现。

### 文档更新

- 文档更新按计划阶段的“文档更新清单”逐项执行,单独提交。
- 文档提交的审查重点:是否覆盖清单全部条目、是否与实际改动一致、是否留下“以后补”的占位。
- 文档更新不得集中拖到合并前闸门;每个原子审查通过后,对应文档更新应在下一个原子开始前完成提交。

### 局部验证的衔接

- 产品代码原子提交的“局部验证”,使用计划阶段的验收命令和仓库已有测试,不依赖本次独立流程新写的测试。
- 新写的测试在独立提交中验证通过后,才作为该原子“验收证据”的一部分,补入总体报告。

---

## 总体报告与总验收

### 总体报告(在总验收之前交付)
Expand Down Expand Up @@ -269,6 +321,8 @@ Agent 先不写代码,先交计划。人类明确批准后,才进入执行
- [ ] 局部验证通过
- [ ] 无红旗
- [ ] 人类能讲清数据流
- [ ] 本提交只含产品代码,未夹带测试或文档
- [ ] 对应原子的测试/文档独立提交已完成,或已排入下一原子开始前

**总报告与总验收**

Expand All @@ -283,6 +337,8 @@ Agent 先不写代码,先交计划。人类明确批准后,才进入执行
- [ ] 规则或检查已沉淀
- [ ] 文档收尾完成
- [ ] 人类最终确认
- [ ] 计划阶段的文档更新清单逐条有对应提交,无“以后补”占位
- [ ] 测试断言与计划阶段测试规格一致,未被实现反向拟合

**审计任务**
- [ ] 见 `docs/audit/AGENTS.audit.md` 的“审计验收”
Expand Down
184 changes: 150 additions & 34 deletions PyFlow/network_api/connect_tcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,11211 +138,11319 @@
10038, # WSAENOTSOCK (Windows)
)

def _is_local_port_conflict(exc):
"""Return whether an OSError means a fixed local port is unavailable.

Windows may report an occupied source port as WSAEADDRINUSE (10048) or
WSAEACCES (10013), depending on the socket state and reserved-port rules.
POSIX reports EADDRINUSE from bind. EACCES is accepted only on Windows;
callers must additionally confirm that the local port is fixed and nonzero.
"""
if not isinstance(exc, OSError):
return False
if exc.errno == errno.EADDRINUSE:
return True
if getattr(exc, "winerror", None) in (10048, 10013):
return True
return os.name == "nt" and exc.errno == errno.EACCES


def _should_fallback_local_port(port, exc):
"""Return true only for a conflict on a fixed, nonzero local port."""
return port not in (None, 0) and _is_local_port_conflict(exc)


def _bind_local_port_with_fallback(sock, local_address, log, port_label):
"""Bind a listener port, falling back to an OS-assigned port once."""
used_fallback = False
try:
try:
sock.bind(local_address)
except OSError as exc:
if not _should_fallback_local_port(local_address[1], exc):
raise
sock.bind((local_address[0], 0))
used_fallback = True
port = sock.getsockname()[1]
except Exception:
sock.close()
raise
if used_fallback:
log(
f"{port_label} port {local_address[1]} is not available; "
f"using OS-assigned port {port}"
)
return port



MAX_DECODE_FAILURES = 3 # circuit breaker: close after N consecutive decode failures (re-exchange storm / garbage injection)
SEND_WAIT_TIMEOUT = 30.0 # seconds a non-blocking client write waits for buffer room
LOG_MERGE_ATTEMPTS = 8 # a log flush re-merges while other instances keep publishing

NETWORK_SPEED_WINDOW = 1.0 # sample window of the real-time speed, in seconds
NETWORK_SPEED_MIN_SPAN = 0.1 # seconds floor, so one short burst is not extrapolated

# Transfer reconnect: an interrupted transfer keeps its progress entry and its
# partial file, and both sides persist the stores to .Flow when a connection
# drops (see _persist_transfer_progress). After a reconnect the receiver asks
# the sender to continue from the bytes it already holds (/resume_trans).
RESUME_LINE = "/resume_trans" # receiver -> sender: continue this transfer from an offset
_SECURE_TRANSFER_COMMANDS = ("/pause_trans", "/start_trans", RESUME_LINE)
RESUME_ACCEPT_TIMEOUT = 20.0 # seconds a resumed transfer waits for the sender to connect
RESUME_PORT_TIMEOUT = 20.0 # seconds a resumed sender waits for the receiver's transfer port
RESUME_SECURE_TIMEOUT = 10.0 # seconds a resume drive waits for the framed control channel
FILE_COMMAND_TOKENS = 3 # a ``/file <name> <fid>`` line carries this many tokens


def _requires_secure_transfer_frame(message):
"""Identify transfer-control text, not transfer body bytes or same-prefix commands."""
if not isinstance(message, str):
return False
parts = message.split(maxsplit=1)
return bool(parts) and parts[0].lower() in _SECURE_TRANSFER_COMMANDS


def _wait_writable(client_socket, timeout):
"""Wait until a non-blocking socket accepts more data.

Args:
client_socket (socket.socket): Socket to wait on; must be non-blocking.
timeout (float): Maximum seconds to wait. Must be > 0.

Raises:
TimeoutError: If the socket stays unwritable for ``timeout`` seconds.
OSError: If the socket is closed or cannot be polled.
"""
with selectors.DefaultSelector() as selector:
selector.register(client_socket, selectors.EVENT_WRITE)
if not selector.select(timeout):
raise TimeoutError(f"peer did not accept data within {timeout} seconds")


_LOG_MERGE_LOCKS = {} # log path -> RLock serialising that file's merges in this process
_LOG_MERGE_LOCKS_LOCK = threading.Lock()


def _log_merge_lock(path):
"""Return this process's lock for the log at ``path``.

Shared by every merge of that file in this process (see
`_publish_json_log`), so threads of one program never interleave their
read-merge-publish.

Args:
path (str): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
with _LOG_MERGE_LOCKS_LOCK:
return _LOG_MERGE_LOCKS.setdefault(os.path.abspath(path), threading.RLock())


def _log_content(path):
"""Read the exact bytes of the log at ``path``, or None when it is absent.

`_publish_json_log` compares the content it read against this before it
replaces the file: any publish by another process changes the bytes (an
entry is always added), so a match means nothing was published in between.

Args:
path (str): Value used by the operation.

Returns:
NoneType | object: Result produced by the operation.
"""
try:
with open(path, "rb") as f:
return f.read()
except FileNotFoundError:
return None


def _read_json_log(path):
"""Parse the JSON log at ``path``: ``(data, content)``.

``({}, None)`` while the file does not exist. A log that is empty (a
publish cut short) or carries a trailing fragment (a crash, or a publish
by the versions that shared one ``.tmp`` path) is read up to its first
document: what is left is dropped, and the next publish rewrites the file
without it, so a broken log cannot poison every later flush.

Args:
path (str): Value used by the operation.

Returns:
list | tuple: Result produced by the operation.
"""
content = _log_content(path)
if content is None:
return {}, None
text = content.decode("utf-8")
if not text.strip():
return {}, content # nothing to keep: the publish repairs the file
try:
return json.loads(text), content
except ValueError:
data, _end = json.JSONDecoder().raw_decode(text)
return data, content


def _publish_json_log(path, snapshot, record_key):
"""Merge one snapshot into the JSON log at ``path``.

The file is read, merged and published back atomically (``os.replace``),
so a reader never sees a truncated or partial log.

Two writers must not lose each other's entries, which is what one shared
``<path>.tmp`` used to produce: one of them renamed a half-written file
into place, the log no longer parsed (``Extra data``) and every later
flush was dropped. Hence, per writer:

* the temp file carries this writer's pid and thread id, so two writers
can never truncate or rename each other's file into place;
* ``_log_merge_lock`` serialises the merges of this process — several
instances in one program (or one test session) sharing a log lose
nothing;
* a merge whose file changed under it — another *process* published since
this writer read it — is redone from the new content instead of
clobbering that process's entries.

Args:
path (str): JSON log file to merge into.
snapshot (dict): Socket -> ``[[content, timestamp], ...]`` entries to add.
record_key (callable): Maps one socket to its key in the log.

Raises:
RuntimeError: When every attempt lost the race to another writer.
"""
with _log_merge_lock(path):
for _ in range(LOG_MERGE_ATTEMPTS):
existing, content = _read_json_log(path)
for sock, entries in snapshot.items():
key = record_key(sock)
existing.setdefault(key, []).extend(entries)
tmp_path = "{}.{}.{}.tmp".format(path, os.getpid(), threading.get_ident())
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(existing, f, ensure_ascii=False, indent=2)
if _log_content(path) == content: # no other process published meanwhile
for _ in range(5): # Windows: the log may be briefly open for reading
try:
os.replace(tmp_path, path)
return
except PermissionError:
time.sleep(0.05)
os.replace(tmp_path, path)
return
os.remove(tmp_path) # another process got there first: redo the merge
raise RuntimeError("the log kept changing under the merge")


def _log_line(enabled, parts):
"""Print one command/result line when ``is_print_log`` allows it.

Args:
enabled (bool): Value used by the operation.
parts (list | dict): Value used by the operation.
"""
if enabled:
print(*parts)


def _debug_line(enabled, is_debug, parts):
"""Print one execution-process line; needs ``is_print_log`` and ``is_debug``.

Args:
enabled (bool): Value used by the operation.
is_debug (bool): Value used by the operation.
parts (list | dict): Value used by the operation.
"""
if enabled and is_debug:
print(*parts)


def _parse_destination_path(command_part):
"""Extract the optional destination preceding a transfer's trailing FID."""
if len(command_part) < 3:
return None
if command_part[0].lower() == "/file_folder":
if len(command_part) == 3:
return command_part[-1] # creation + destination, no client id
if len(command_part) >= 4 and command_part[-2] != command_part[2]:
if not (command_part[-2].startswith("(") and command_part[-2].endswith(")")):
return command_part[-2]
elif len(command_part) >= 4:
if not (command_part[-2].startswith("(") and command_part[-2].endswith(")")):
return command_part[-2]
return None


def _transfer_fid(command_part):
"""Return the fid a sender stamped on its transfer command, or None.

Every user transfer command ends with the sender's transfer id
(``/file <path> <id>``, ``/file_folder <rel> <file> [<dest>] <id>``); it
keys that leg in ``file_recv_progress``/``file_upload_progress``. The
protocol-internal ``/crypto_pub_key`` push reports None: it is no user
file transfer.

Args:
command_part (object): Value used by the operation.

Returns:
NoneType | object: Result produced by the operation.
"""
if command_part and command_part[0] == "/crypto_pub_key":
return None
try:
return int(command_part[-1])
except (IndexError, TypeError, ValueError):
return None


def _peer_from_text(text):
"""Parse an ``"ip:port"`` peer string into an ``(ip, port)`` tuple.

Args:
text (object): Value used by the operation.

Returns:
tuple | None: The peer tuple, or None when the text carries none.
"""
if not text:
return None
host, sep, port = str(text).rpartition(":")
if not sep:
return None
try:
return (host, int(port))
except ValueError:
return None


def _peer_from_json(value):
"""Parse a persisted ``[ip, port]`` peer into an ``(ip, port)`` tuple.

Args:
value (object): Value used by the operation.

Returns:
tuple | None: The peer tuple, or None when the value is not a peer.
"""
if isinstance(value, (list, tuple)) and len(value) == 2:
try:
return (str(value[0]), int(value[1]))
except (TypeError, ValueError):
return None
return None


def _read_transfer_progress(path, *, server_routes=False):
"""Read scoped progress and, for servers, canonical relay route snapshots."""
with open(path, "r", encoding="utf-8") as source:
data = json.load(source)
if isinstance(data, dict):
for text in data.get("upload") or {}:
key = json.loads(text)
if not (
isinstance(key, list) and len(key) == 2
and _peer_from_json(key[0]) is not None and isinstance(key[1], int)
):
raise ValueError("unsupported upload progress key; archive the old progress file")
if server_routes:
try:
for fid, route in (data.get("relays") or {}).items():
int(fid)
if _peer_from_json(route["originator"]) is None or not route["targets"]:
raise ValueError
seen = set()
for target, child in route["targets"]:
peer = _peer_from_json(target)
if peer is None or peer in seen or not isinstance(child, int):
raise ValueError
seen.add(peer)
completed = [_peer_from_json(target) for target in route.get("completed", [])]
if any(target is None or target not in seen for target in completed):
raise ValueError
if len(set(completed)) != len(completed):
raise ValueError
except (TypeError, ValueError, KeyError, AttributeError):
raise ValueError("unsupported server relay progress; archive the old file") from None
elif data.get("relays"):
raise ValueError("unsupported client relay progress; archive the old file")
return data


def _transfer_progress_view(snapshot, *, speed_enabled, runtime=None):
"""Render an existing progress snapshot without merging scoped identities."""
if not isinstance(snapshot, dict):
raise ValueError("transfer progress must be an object")
view = {"uploading": [], "downloading": [], "relays": []}
for source, destination in (("upload", "uploading"), ("download", "downloading")):
entries = snapshot.get(source, {})
if not isinstance(entries, dict):
raise ValueError(f"{source} progress must be an object")
for text, entry in entries.items():
if not isinstance(entry, list) or len(entry) != 5:
raise ValueError("transfer progress rows must have five fields")
if source == "upload":
receiver, fid = json.loads(text)
receiver = _peer_from_json(receiver)
if receiver is None or not isinstance(fid, int):
raise ValueError("unsupported upload progress key")
key = (receiver, fid)
else:
receiver, fid = None, int(text)
key = fid
peer = _peer_from_json(entry[4]) if entry[4] is not None else None
if entry[4] is not None and peer is None:
raise ValueError("invalid progress peer")
view[destination].append({
"fid": fid,
"receiver": list(receiver) if receiver is not None else None,
"peer": list(peer) if peer is not None else None,
"name": os.path.basename(entry[3]), "path": entry[3],
"transferred": int(entry[0]), "total": int(entry[1]),
"speed": entry[2] if speed_enabled else None,
"active": key in runtime[0] if runtime is not None else None,
"socket_registered": key in runtime[1] if runtime is not None else None,
"paused": runtime[2].get(key, False)
if runtime is not None and receiver is not None else None,
})
relays = snapshot.get("relays", {})
if not isinstance(relays, dict) or any(not isinstance(row, dict) for row in relays.values()):
raise ValueError("relay progress must contain record objects")
view["relays"] = [{**row, "fid": int(fid)} for fid, row in relays.items()]
return view


def _get_transfer_progress(instance, *, include_persisted, server_routes=False):
"""Observe local stores and an optional file; never load or persist state."""
with instance._transfer_progress_lock:
snapshot = instance._transfer_progress_snapshot()
active = set(instance._active_transfer_fids)
sockets = set(instance._active_transfer_sockets)
paused = instance._transfer_controls.upload_pauses()
speed_enabled = bool(instance.is_enable_real_time_network_speed)
persisted = {
"path": os.fspath(instance.file_trans_progress_file),
"status": "not_requested", "snapshot": None, "error": None,
}
result = {
"progress_enabled": bool(instance.is_enable_file_transfer_progress_bar),
"speed_enabled": speed_enabled,
"memory": _transfer_progress_view(
snapshot, speed_enabled=speed_enabled, runtime=(active, sockets, paused)
),
"persisted": persisted,
}
if include_persisted:
try:
data = _read_transfer_progress(persisted["path"], server_routes=server_routes)
persisted["snapshot"] = _transfer_progress_view(data, speed_enabled=speed_enabled)
persisted["status"] = "ok"
except FileNotFoundError:
persisted["status"] = "missing"
except (OSError, ValueError, TypeError, KeyError, IndexError, AttributeError) as exc:
persisted["status"] = "error"
persisted["error"] = str(exc)
return result


def _config_lifecycle(*, starting):
"""Serialize deletion against startup and shutdown without locking their I/O."""
def decorate(method):
@wraps(method)
def run(self, *args, **kwargs):
with self._transfer_progress_lock:
if starting:
if self._progress_discarded:
raise RuntimeError("transfer progress was discarded; create a new instance")
self._config_started = True
self._config_busy += 1
self._config_closed = False
completed = False
try:
result = method(self, *args, **kwargs)
completed = True
return result
finally:
with self._transfer_progress_lock:
self._config_busy -= 1
if not starting:
self._config_closed = completed
return run
return decorate


_CONFIG_FILES = (
("file_trans_progress_file", None),
("messages_log_file", "messages"),
("events_log_file", "events"),
("sent_messages_log_file", "sent_messages"),
("sent_events_log_file", "sent_events"),
)


def _delete_config(instance, config_name, *, is_list_config):
"""List or unlink explicitly owned state files; never resolve user paths."""
files = {}
for attr, store in _CONFIG_FILES:
path = os.path.abspath(os.fspath(getattr(instance, attr)))
files.setdefault(os.path.basename(path), {}).setdefault(path, []).append(store)

def regular_file(path):
try:
return stat.S_ISREG(os.lstat(path).st_mode)
except FileNotFoundError:
return False

if is_list_config:
names = []
for name, paths in sorted(files.items()):
if len(paths) != 1:
raise ValueError(f"ambiguous configuration name: {name}")
if regular_file(next(iter(paths))):
names.append(name)
return names
if config_name is None:
raise ValueError("a configuration file name is required")
if not isinstance(config_name, str):
raise TypeError("config_name must be a file name string")
if (not config_name or config_name in (".", "..")
or any(char in config_name for char in "/\\\0*?[]") or config_name not in files):
raise ValueError("config_name must name an allowed local state file")
paths = files[config_name]
if len(paths) != 1:
raise ValueError(f"ambiguous configuration name: {config_name}")
path, stores = next(iter(paths.items()))
with instance._transfer_progress_lock:
if (instance.running or instance._config_busy
or (instance._config_started and not instance._config_closed)
or instance._active_transfer_fids or instance._active_transfer_sockets
or instance._resume_sends or instance._receive_transfers):
raise RuntimeError("stop the instance and finish active transfers before deletion")
if hasattr(instance, "_forward_relays"):
with instance._forward_relays_lock:
if instance._forward_relays or any(
state["active"] for state in instance._relay_recoveries.values()
):
raise RuntimeError("finish active relays before deletion")
with ExitStack() as locks:
for store in stores:
if store is not None:
locks.enter_context(getattr(instance, f"_{store}_dict_lock"))
if getattr(instance, f"{store}_dict"):
raise RuntimeError("flush pending records by closing before deletion")
try:
if not regular_file(path) and os.path.lexists(path):
raise ValueError("only regular configuration files may be deleted")
os.unlink(path)
deleted = True
except FileNotFoundError:
deleted = False
if None in stores:
instance._progress_discarded = True
return deleted


def _resume_offset_for(entry):
"""Bytes of an interrupted transfer's file already on the receiver's disk.

The length of the partial file is what the sender is asked to continue
from, so a missing (or unreadable) partial file restarts the transfer from
its first byte.

Args:
entry (list): Progress entry ``[received, total, speed, path, peer]``.

Returns:
int: Byte offset to continue from.
"""
try:
size = os.path.getsize(entry[3])
except (OSError, TypeError):
return 0
total = entry[1]
if isinstance(total, int) and size > total:
return 0 # not this transfer's partial file any more: start over
return size


def parse_resume_command(command):
"""Parse the numeric-offset resume command, or return None."""
try:
parts = shlex.split(command)
if len(parts) != 5 or parts[0].lower() != RESUME_LINE:
return None
fid, offset = int(parts[1]), int(parts[2])
endpoints = [ast.literal_eval(text) for text in parts[3:]]
if fid < 0 or offset < 0 or any(
not isinstance(peer, tuple) or len(peer) != 2
or not isinstance(peer[0], str) or not isinstance(peer[1], int)
for peer in endpoints
):
return None
return fid, offset, *endpoints
except (ValueError, SyntaxError, TypeError):
return None


def format_resume_line(fid, offset, origin, target):
"""Format a resume command with the required nonnegative integer offset.

Args:
fid (int): Stable transfer identifier.
offset (int): Bytes already present at the receiver; must be a nonnegative integer.
origin (tuple): Source endpoint identity.
target (tuple): Receiver endpoint identity.

Returns:
str: The five-token numeric resume command.

Raises:
ValueError: If ``offset`` is not an integer or is negative.
"""
if type(offset) is not int or offset < 0:
raise ValueError("resume offset must be a nonnegative integer")
return (f"{RESUME_LINE} {fid} {offset} "
f"{shlex.quote(repr(tuple(origin)))} {shlex.quote(repr(tuple(target)))}")


@contextmanager
def _sending_transfer(instance, key, *, control_socket=None):
"""Serialize sends for one scoped fid; release after the last in-flight user."""
with instance._transfer_progress_lock:
state = instance._resume_sends.get(key)
if state is None:
state = {"lock": threading.RLock(), "users": 0, "targets": set(),
"control_socket": control_socket}
instance._resume_sends[key] = state
state["users"] += 1
try:
with state["lock"]:
yield state
finally:
with instance._transfer_progress_changed:
state["users"] -= 1
if not state["users"] and not state["targets"]:
instance._resume_sends.pop(key, None)
instance._transfer_progress_changed.notify_all()


def _transfer_busy(instance, key, control_socket):
"""Called under the progress lock; closed owners still own final cleanup."""
if key in instance._active_transfer_fids or key in instance._active_transfer_sockets:
return True
if isinstance(key, tuple):
state = instance._resume_sends.get(key)
if state is not None and (state["users"] or state["targets"]):
return True
peer, fid = key
with instance._transfer_pause_cond:
if any((peer, fid, kind, 0) in instance._transfer_controls._legs for kind in (0, 1)):
return True
return instance._transfer_handshakes.occupied(control_socket, fid)
return False


def _claim_receive(instance, fid, control_socket, owner=None):
"""Reserve a resume request or adopt it into its sole receive listener."""
if fid is None:
return None
with instance._transfer_progress_lock:
if (instance._progress_discarded or instance._transfer_handshakes.closed(control_socket)
or _transfer_busy(instance, fid, control_socket)):
return None
record = instance._receive_transfers.get(fid)
if record is not None:
if record["owner"] is not None:
return None
if owner is not None and record["control_socket"] is control_socket:
record["owner"] = owner
instance._transfer_progress_changed.notify_all()
return record
if record["deadline"] > time.monotonic():
return None
record = {"control_socket": control_socket, "owner": owner,
"deadline": time.monotonic() + RESUME_ACCEPT_TIMEOUT}
instance._receive_transfers[fid] = record
instance._transfer_progress_changed.notify_all()
return record


def _release_receive(instance, fid, record):
with instance._transfer_progress_changed:
if instance._receive_transfers.get(fid) is record:
instance._receive_transfers.pop(fid, None)
instance._transfer_progress_changed.notify_all()


def _request_receive_resume(instance, fid, entry, control_socket, origin, target):
record = _claim_receive(instance, fid, control_socket)
if record is None:
return False
sent = False
try:
entry[0] = _resume_offset_for(entry)
sent = instance.send_message(control_socket, format_resume_line(fid, entry[0], origin, target))
return bool(sent)
finally:
if not sent or not instance.running or control_socket.fileno() < 0:
_release_receive(instance, fid, record)


def _discard_receive_requests(instance, control_socket):
with instance._transfer_progress_changed:
for fid, record in list(instance._receive_transfers.items()):
if record["control_socket"] is control_socket and record["owner"] is None:
del instance._receive_transfers[fid]
instance._transfer_progress_changed.notify_all()


def _retire_transfer_session(instance, control_socket):
"""Cancel only this socket's resources and capture its finalizing owners."""
instance._transfer_handshakes.cancel_socket(control_socket)
if hasattr(instance, "_forward_budget"):
# cancel_socket closed the owned data sockets. Readers waiting behind
# another route must recheck them even if no writer returns credit.
with instance._forward_budget.cond:
instance._forward_budget.cond.notify_all()
instance._transfer_controls.discard_socket(control_socket)
_discard_receive_requests(instance, control_socket)
if hasattr(instance, "_relay_recoveries"):
with instance._transfer_progress_changed, instance._forward_relays_lock:
for fid, state in instance._relay_recoveries.items():
for target, (sock, _) in list(state["pending"].items()):
if sock is control_socket:
del state["pending"][target]
for target, reservation in state["active"].items():
record = reservation["record"]
if reservation["target_socket"] is control_socket and record["owner"] is None:
_release_receive(instance, (target, fid), record)
instance._transfer_progress_changed.notify_all()
with instance._transfer_progress_lock:
sends = [(key, state) for key, state in instance._resume_sends.items()
if state.get("control_socket") is control_socket]
receives = [(fid, record) for fid, record in instance._receive_transfers.items()
if record["control_socket"] is control_socket]
return control_socket, sends, receives


def _wait_transfer_session(instance, retired):
"""Drain captured old owners off the control reader and outside global locks."""
if retired is None:
return
control_socket, sends, receives = retired
instance._transfer_handshakes.wait_socket(control_socket)
with instance._transfer_progress_changed:
instance._transfer_progress_changed.wait_for(lambda: all(
instance._resume_sends.get(key) is not state for key, state in sends
) and all(instance._receive_transfers.get(fid) is not record
for fid, record in receives))


def _start_resume_send(instance, key, target, send, *, control_socket, forward=False):
"""Reserve one ordinary owner or an independent forwarded Target owner."""
owner_key = (target, key[1]) if forward else key
with instance._transfer_progress_lock:
if instance._progress_discarded or key not in instance.file_upload_progress:
return False
if (control_socket.fileno() < 0 or instance._transfer_handshakes.closed(control_socket)
or not forward and _transfer_busy(instance, key, control_socket)):
return False
state = instance._resume_sends.get(owner_key)
if state is None:
state = {"lock": threading.RLock(), "users": 0, "targets": set(),
"control_socket": control_socket}
instance._resume_sends[owner_key] = state
if target in state["targets"] or state["control_socket"] is not control_socket:
return False
state["targets"].add(target)

def run():
try:
with _sending_transfer(instance, owner_key, control_socket=control_socket):
if forward:
with instance._transfer_progress_changed:
instance._transfer_progress_changed.wait_for(lambda:
(key not in instance._active_transfer_sockets
and key not in instance._active_transfer_fids
and key not in instance._resume_sends)
or instance._transfer_handshakes.closed(control_socket))
if instance._transfer_handshakes.closed(control_socket):
return
entry = instance.file_upload_progress.get(key)
if entry is not None:
send(entry)
finally:
with instance._transfer_progress_changed:
state["targets"].discard(target)
if not state["users"] and not state["targets"]:
instance._resume_sends.pop(owner_key, None)
instance._transfer_progress_changed.notify_all()

threading.Thread(target=run, daemon=True).start()
return True


def _validate_transfer_control_identity(fid, trans_type, direction):
"""Validate a file leg's id, transfer type and sender/receiver role."""
if type(fid) is not int or fid < 0:
raise ValueError("fid must be a nonnegative integer")
if type(trans_type) is not int or trans_type not in (0, 1):
raise ValueError("trans_type must be 0 (ordinary) or 1 (forwarded)")
if type(direction) is not int or direction not in (0, 1):
raise ValueError("direction must be 0 (sender) or 1 (receiver)")


def _parse_transfer_control_command(command):
"""Parse a four-token pause/start line, returning None for malformed input.

Return ``(paused, fid, trans_type, direction)``. The wire direction is the
command issuer's role; the receiving side's local role is ``1 - direction``.
This parser does not resolve a peer, register state or send a response.
"""
if not isinstance(command, str):
return None
try:
parts = shlex.split(command)
if len(parts) != 4:
return None
name = parts[0].lower()
if name not in ("/pause_trans", "/start_trans"):
return None
fid, trans_type, direction = map(int, parts[1:])
_validate_transfer_control_identity(fid, trans_type, direction)
return name == "/pause_trans", fid, trans_type, direction
except ValueError:
return None


def _transfer_control_key(peer, fid, trans_type, direction):
"""Build a runtime control key from a resolved peer and the local leg role.

Callers resolve configured/concrete endpoints before building the key and
invert incoming wire directions. Progress stores retain their existing keys.
"""
_validate_transfer_control_identity(fid, trans_type, direction)
return tuple(peer), fid, trans_type, direction


class _TransferControlRegistry:
"""Serialize each leg's decisions and control writes without blocking other legs.

Lock order is leg lock then pause condition; lookups release the condition
before taking a leg lock. Production operations append control frames under
that lock; one FIFO worker waits for leg/crypto readiness and sends them.
Explicit ``send(socket, line)`` callbacks are synchronous under the leg lock.
"""

def __init__(self, paused, condition, instance=None):
self._paused = paused
self._condition = condition
self._legs = {}
self._instance = instance

def register(self, key, control_socket, owner, *, relay=None, shared=False):
"""Bind an unclaimed identity, adopting only its sender's preset pause."""
if control_socket is None or owner is None:
raise ValueError("a control socket and leg owner are required")
with self._condition:
state = self._legs.get(key)
if state is not None:
if state["control_socket"] is not control_socket:
return None
if owner not in state["owners"] and not (shared and state["shared"]):
return None
state["owners"].add(owner)
return state
paused = key[3] == 0 and self._paused.get(key, False)
if relay is not None and key[3] == 0:
if paused:
relay["requested"] = True
paused = False
self._paused.pop(key, None)
state = {
"key": key, "control_socket": control_socket, "owner": owner,
"owners": {owner}, "shared": shared,
"lock": threading.RLock(), "confirmed_state": paused,
"last_requested_state": False, "initial_notification": paused,
"ready": self._instance is None or key[3] == 1,
}
if relay is not None:
state["relay"] = relay
self._legs[key] = state
return state

def _live(self, state):
with self._condition:
return self._legs.get(state["key"]) is state

def _confirm(self, state, paused):
with self._condition:
state["confirmed_state"] = paused
if state["key"][3] == 0:
if paused:
self._paused[state["key"]] = True
else:
self._paused.pop(state["key"], None)
self._condition.notify_all()

def _send(self, state, paused, send):
_, fid, trans_type, direction = state["key"]
name = "/pause_trans" if paused else "/start_trans"
try:
line = f"{name} {fid} {trans_type} {direction}"
sent = send(state["control_socket"], line) if send is not None else self._enqueue(state, line)
except Exception:
self.release(state)
raise
if not sent:
self.release(state)
return False
state["initial_notification"] = False
return True

def announce(self, state, send=None):
"""Publish an adopted pause once the peer can locate the new leg."""
with state["lock"]:
with self._condition:
state["ready"] = True
self._condition.notify_all()
if not self._live(state) or not state["initial_notification"]:
return False
return self._send(state, state["confirmed_state"], send)

def local(self, key, paused, send=None, *, owner=None):
"""Decide a sender state or submit a receiver intent, deduplicating both."""
with self._condition:
state = self._legs.get(key)
if owner is not None and (state is None or owner not in state["owners"]):
return False
if state is None:
if key[3] == 0:
if paused:
self._paused[key] = True
else:
self._paused.pop(key, None)
self._condition.notify_all()
return False
if "relay" in state:
return self._relay_control(state, paused, send, owner=owner)
with state["lock"]:
if not self._live(state):
return False
if owner is not None and owner not in state["owners"]:
return False
if key[3] == 0:
if state["confirmed_state"] == paused:
return False
self._confirm(state, paused)
else:
# Other relay participants may have an in-flight opposite intent.
if (key[2] != 1 and state["confirmed_state"] == paused
and state["last_requested_state"] == paused):
return False
state["last_requested_state"] = paused
return self._send(state, paused, send)

def receive(self, key, control_socket, paused, send=None):
"""Process a request at S or a notification at R; never create wire state."""
with self._condition:
state = self._legs.get(key)
if state is None:
return False
if "relay" in state:
return self._relay_control(state, paused, send, control_socket=control_socket)
with state["lock"]:
if not self._live(state) or state["control_socket"] is not control_socket:
return False
changed = state["confirmed_state"] != paused
self._confirm(state, paused)
if key[3] == 0:
# Even a same-state request needs the actual-state notification.
return self._send(state, paused, send)
return changed


def _relay_control(self, state, paused, send, *, control_socket=None, owner=None):
relay = state["relay"]
# Serialize request translation and notification fanout, not network I/O.
with relay["control_lock"]:
with state["lock"]:
if (not self._live(state)
or control_socket is not None and state["control_socket"] is not control_socket
or owner is not None and owner not in state["owners"]):
return False
if control_socket is None or state["key"][3] == 0:
state["last_requested_state"] = paused
upstream = relay.get("upstream")
if upstream is None or not self._live(upstream):
relay["requested"] = paused
return True
with upstream["lock"]:
upstream["last_requested_state"] = paused
return self._send(upstream, paused, send)
# Only a notification on the actual upstream session confirms state.
with state["lock"]:
self._confirm(state, paused)
for child in relay["controls"].values():
with child["lock"]:
if self._live(child):
self._confirm(child, paused)
self._send(child, paused, send)
return True

def release(self, state, *, owner=None):
"""Release one data owner; the last one retires shared task control."""
with state["lock"]:
with self._condition:
key = state["key"]
if self._legs.get(key) is not state:
return False
if owner is not None:
if owner not in state["owners"]:
return False
state["owners"].remove(owner)
if state["owners"]:
state["owner"] = next(iter(state["owners"]))
return True
state["owners"].clear()
del self._legs[key]
self._paused.pop(key, None)
if "outbox" in state:
state["outbox"].clear()
state["confirmed_state"] = False
state["last_requested_state"] = False
state["initial_notification"] = False
self._condition.notify_all()
return True

def discard_socket(self, control_socket):
"""Discard one control session without touching a replacement owner."""
with self._condition:
states = [state for state in self._legs.values()
if state["control_socket"] is control_socket]
return sum(self.release(state) for state in states)

def _enqueue(self, state, line):
"""Queue under the leg lock; crypto readiness never blocks its reader."""
if "outbox" not in state:
state["outbox"] = collections.deque()
state["outbox"].append(line)
if not state.get("sending", False):
state["sending"] = True
threading.Thread(target=self._flush, args=(state,), daemon=True).start()
return True

def _flush(self, state):
instance, sock = self._instance, state["control_socket"]
try:
while True:
with state["lock"]:
if not self._live(state) or not state["outbox"]:
state["sending"] = False
return
line = state["outbox"].popleft()
with self._condition:
self._condition.wait_for(lambda: state["ready"] or not self._live(state))
if not self._live(state):
return
if not instance._wait_control_secure(sock):
raise ConnectionError("control channel unavailable")
with state["lock"]:
if not self._live(state):
return
if not instance.send_message(sock, line):
raise ConnectionError("control write failed")
except Exception as exc:
if not self._live(state):
return
if not _is_closed_socket_error(exc):
instance._log(f"transfer control: {exc}")
_retire_transfer_session(instance, sock)
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass

def upload_pauses(self):
"""Project only active sender control state onto existing progress keys."""
with self._condition:
return {(peer, fid): True for (peer, fid, kind, role), state in self._legs.items()
if role == 0 and state["confirmed_state"]}

def release_owner(self, owner):
with self._condition:
states = [state for state in self._legs.values() if owner in state["owners"]]
for state in states:
self.release(state, owner=owner)


def _control_peer(instance, peer):
"""Resolve a public control peer into the existing connection namespace."""
if isinstance(instance, TCP_Client_Base):
configured = (instance.host, instance.port)
return configured if peer is None or _is_control_endpoint(
peer, configured, _socket_peer_endpoint(instance.client_socket)
) else None
if peer is None:
raise ValueError("control peer is required")
return tuple(peer)


def _control_key(instance, peer, fid, trans_type, direction):
key = _transfer_control_key(peer, fid, trans_type, direction)
if trans_type == 1 and direction == 0 and isinstance(instance, TCP_Server_Base):
with instance._forward_relays_lock:
if (peer, fid) in instance._forward_relays or (peer, fid) in instance._fid_route_index:
return key
candidates = [relay["controls"].get(peer)
for (target, child), relay in instance._forward_relays.items()
if target == peer and relay["fid"] == fid]
with instance._transfer_pause_cond:
if key in instance._transfer_controls._legs:
return key
matches = [state for state in candidates if state is not None
and instance._transfer_controls._legs.get(state["key"]) is state]
if len(matches) > 1:
return None
if matches:
return matches[0]["key"]
return key


def _set_transfer_control(instance, fid, peer, trans_type, direction, paused):
_validate_transfer_control_identity(fid, trans_type, direction)
peer = _control_peer(instance, peer)
if peer is None:
return False
key = _control_key(instance, peer, fid, trans_type, direction)
return instance._transfer_controls.local(key, paused) if key is not None else False


def _receive_transfer_control(instance, sock, peer, command):
parsed = _parse_transfer_control_command(command)
if parsed is None:
return
paused, fid, trans_type, direction = parsed
key = _control_key(instance, peer, fid, trans_type, 1 - direction)
if key is not None:
instance._transfer_controls.receive(key, sock, paused)


def _bind_transfer_control(instance, fid, sock, owner, trans_type, direction, *, relay=None, shared=False):
if fid is None or sock is None:
return None # public-key legs and standalone transfer sockets
peer = _control_peer(instance, _socket_peer_endpoint(sock))
state = instance._transfer_controls.register(
_transfer_control_key(peer, fid, trans_type, direction), sock, owner,
relay=relay, shared=shared,
)
if state is None:
raise RuntimeError("transfer control identity already owned")
return state


def _announce_transfer_control(instance, state):
if state is not None:
instance._transfer_controls.announce(state)


def _wait_transfer_control(instance, state, sock):
if state is None:
return
with instance._transfer_pause_cond:
while (instance._transfer_controls._legs.get(state["key"]) is state
and instance._transfer_pause.get(state["key"], False)):
if not instance.running or sock.fileno() < 0:
return
instance._transfer_pause_cond.wait(timeout=0.5)




def _open_transfer_target(path, offset):
"""Open a transfer's destination file, ready to write from ``offset``.

A resumed transfer continues a partial file: the file is opened for
update and positioned at the byte the sender continues from, so a late or
duplicated chunk overwrites its own place instead of corrupting the
stream. A fresh transfer (offset 0) truncates the file.

Args:
path (str): Destination path of the transfer.
offset (int): Byte offset the incoming stream starts at.

Returns:
file: Open binary file positioned at ``offset``.
"""
if offset <= 0:
return open(path, "wb")
mode = "r+b" if os.path.exists(path) else "w+b"
target = open(path, mode)
target.seek(offset)
return target


def _receive_dir_for(base_dir, new_save_path, destination_path):
"""Compose the receive directory of one folder command.

The single definition of where a folder command lands: an absolute
``destination_path`` replaces ``base_dir``, a relative one nests under
it, and the command's ``/``-separated relative path nests below that.
``setting_file_save_path`` and the folder-creation branch of
``file_folder_transfer_*_recv_*_start_thread`` both use it, so a create
command and the file legs under it always agree on the directory.

Args:
base_dir (str): Instance receive root (``file_transfer_dir``).
new_save_path (str | None): Command's relative folder path, ``/``-separated.
destination_path (str | None): Receiver-side destination directory.

Returns:
str: Directory the command names, without creating it.
"""
save_path = base_dir
if destination_path:
if os.path.isabs(destination_path):
save_path = destination_path
else:
save_path = os.path.join(save_path, destination_path)
if new_save_path:
path_list = new_save_path.split("/")
if path_list and path_list[0] == "":
del path_list[0]
for node in path_list:
save_path = os.path.join(save_path, node)
return save_path
def _rel_dirs_with_files(folder_path, base_path):
"""Relative paths of the directories under ``folder_path`` that have files.

A directory needs to exist at the receiver only when a file lands in it
or below it; an empty directory has nothing to receive. Each entry is in
``"/data/sub"`` form, and every ancestor of a directory that has files is
included, because a file leg creates only its own leaf directory.

Args:
folder_path (str): Folder being sent.
base_path (str): Parent directory the relative paths hang off.

Returns:
set: Relative folder paths, ``""`` for the transfer root.
"""
needed = set()
base = os.path.normpath(base_path)
for root, _dirs, files in os.walk(folder_path):
if not files:
continue
rel = os.path.relpath(os.path.normpath(root), base)
rel = "" if rel == "." else "/" + rel.replace(os.sep, "/")
while True:
needed.add(rel)
trimmed = rel.rstrip("/")
if not trimmed:
break
rel = trimmed.rsplit("/", 1)[0]
return needed

def _resumable_entry(progress, fid, peer, command_part):
"""Return the interrupted download a file or folder-item command continues.

The fid, original sender (``peer``) and file basename must all match;
anything else is a new transfer and never uses a path-only resume alias.

Args:
progress (dict): ``file_recv_progress`` store, fid -> entry.
fid (int | None): Transfer id the line carries.
peer (tuple | None): Sender ``(ip, port)`` the line arrived from.
command_part (list): Shell-split command tokens.

Returns:
list | None: The matching progress entry, or None.
"""
if fid is None or peer is None or len(command_part) < FILE_COMMAND_TOKENS:
return None
kind = command_part[0].lower()
if kind == "/file":
filename = command_part[1]
elif kind == "/file_folder" and len(command_part) >= 4:
filename = command_part[2]
else:
return None
entry = progress.get(fid)
if entry is None or entry[4] is None:
return None
if tuple(entry[4]) != tuple(peer):
return None
if os.path.basename(str(entry[3])) != os.path.basename(filename):
return None
return entry



def parse_forwarded_message(command):
"""Split a ``/send_msg_from <addr> <payload>`` relay envelope.

Args:
command (str): Received line, e.g.
``/send_msg_from ('127.0.0.1', 3000) hello``.

Returns:
tuple | None: ``(sender_id, payload)`` where ``sender_id`` is the
sender's ``"ip:port"``, or None when the line is not a well-formed
envelope.
"""
try:
parts = shlex.split(command)
except ValueError:
return None
if len(parts) < 3 or parts[0].lower() != "/send_msg_from":
return None
try:
sender = ast.literal_eval(parts[1])
except (ValueError, SyntaxError):
return None
if not (isinstance(sender, tuple) and len(sender) == 2 and isinstance(sender[0], str)):
return None
return f"{sender[0]}:{sender[1]}", " ".join(parts[2:])


def parse_forward_items_and_addrs(tokens):
"""Split forward-command tokens into items and destination addresses.

A token of the form ``('ip', port)`` is a destination, everything else is a
forwarded item (message text or a path). Used by the native message
forwarding (``/forward_send_msg``) and by the file/folder forward extension.

Args:
tokens (list[str]): Tokens after the command name.

Returns:
tuple: ``(items, addrs)`` in the order given; ``items`` holds texts and
paths, ``addrs`` holds ``(ip, port)`` tuples.
"""
items = []
addrs = []
for token in tokens:
if token.startswith("(") and token.endswith(")"):
try:
addr = ast.literal_eval(token)
except (ValueError, SyntaxError):
items.append(token)
continue
if isinstance(addr, tuple) and len(addr) == 2 and isinstance(addr[0], str):
addrs.append(addr)
else:
items.append(token)
else:
items.append(token)
return items, addrs


def forward_skip_message(target):
"""Build the console notice for a forward destination that cannot be served.

Args:
target (tuple): Destination ``(ip, port)`` that is unreachable or is the
server itself.

Returns:
str: One-line notice for the console.
"""
return f"forward: destination {target} is unreachable or is the server, skipped"


def parse_forward_originator(command, own_address=None):
"""Extract the originator's ``"ip:port"`` from a received transfer command.

The server's forward relay tags every pushed ``/file`` and ``/file_folder``
command with the forwarding client's address tuple; a direct send carries the
receiver's own address instead.

Args:
command (str): Received transfer command.
own_address (str | None): This instance's own ``"ip:port"``; a command
carrying it is a direct send and yields None.

Returns:
str | None: Originator ``"ip:port"``, or None when the command carries no
originator (direct send or non-transfer command).
"""
try:
parts = shlex.split(command)
except ValueError:
return None
if len(parts) < 4:
return None
for token in parts[1:-1]: # skip the command name and the trailing id
if token.startswith("(") and token.endswith(")"):
try:
addr = ast.literal_eval(token)
except (ValueError, SyntaxError):
continue
if isinstance(addr, tuple) and len(addr) == 2 and isinstance(addr[0], str):
originator = f"{addr[0]}:{addr[1]}"
if own_address and originator == own_address:
return None # direct send: the tuple is the receiver itself
return originator
return None


# ---- transfer ids ----------------------------------------------------------
#
# A transfer id keys the progress stores, the pause switches and the transfer
# socket registry, and it travels on the wire as the last token of ``/file``
# and ``/file_folder`` lines. One allocator per instance:
#
# fid = (counter << 32) | (epoch << 1)
#
# ``epoch`` is random per instance, reducing restart collisions; scoped progress
# keys, not random uniqueness, isolate receivers and directions. ``counter``
# only grows in the high bits. The low bit is reserved, always zero, and never
# selects a transfer's route or direction.
#
# The counters this replaced started at 0 in every instance and were also
# decremented when a leg ended, so an inbound fid from one peer and an outbound
# fid from this instance could be the same number: the shared registries
# (``_active_transfer_fids``, ``_active_transfer_sockets``, ``_transfer_pause``)
# then let one leg's cleanup tear down the other's socket.

FID_LOW_BITS = 32 # low 32 bits: epoch (31) plus one reserved zero bit


def format_fid(fid):
"""Render a transfer id for logs as ``e<epoch>.<counter>``.

Args:
fid (int): Transfer id.

Returns:
str: Readable form; the inverse of the allocator's packing.
"""
low = fid & 0xFFFFFFFF
return f"e{low >> 1}.{fid >> FID_LOW_BITS}"


def _socket_local_endpoint(sock):
"""Return the concrete local ``(ip, port)`` of a connected socket, or None.

The kernel reports the address it actually chose for the connection, so a
wildcard bind (``0.0.0.0``) or a host alias (``localhost``) yields the
address the peer resolved and connected to. A socket that is already closed
or unbound yields None.

Args:
sock (socket.socket | None): Control socket to inspect.

Returns:
tuple | None: ``(ip, port)`` the resume identity should use.
"""
if sock is None:
return None
try:
address = sock.getsockname()
except OSError:
return None
return (address[0], address[1]) if address else None


def _socket_peer_endpoint(sock):
"""Return the concrete remote ``(ip, port)`` of a connected socket, or None.

Args:
sock (socket.socket | None): Control socket to inspect.

Returns:
tuple | None: ``(ip, port)`` the peer is actually connected from.
"""
if sock is None:
return None
try:
address = sock.getpeername()
except OSError:
return None
return (address[0], address[1]) if address else None


def _is_control_endpoint(endpoint, configured_endpoint, connected_endpoint):
"""Match only the configured identity or this connection's actual endpoint.

``connected_endpoint`` comes from the appropriate local/peer socket helper;
None keeps only the configured fallback after a control socket is closed.
A wildcard configuration never makes unrelated same-port addresses match.
"""
endpoint = tuple(endpoint)
return endpoint == configured_endpoint or (
connected_endpoint is not None and endpoint == connected_endpoint
)


class _FidAllocator:
"""Hand out transfer ids that never collide with a live one.

``alloc`` skips a candidate that already keys one of the live tables. Those
tables are read under this allocator's own lock only; a caller must not
hold ``_transfer_progress_lock`` or ``_forward_relays_lock`` while
allocating, so the two lock families never nest.
"""

def __init__(self, live_tables):
"""Create an allocator for one instance.

Args:
live_tables (tuple): Dicts whose keys are ids still in use —
progress stores and server routes/indexes. Held by reference,
never copied.
"""
self._epoch = int.from_bytes(os.urandom(4), "big") & 0x7FFFFFFF
self._counter = 0
self._live_tables = live_tables
self._lock = threading.Lock()

def alloc(self, *, receiver=None):
"""Return an unused kindless transfer id.

Args:
receiver (tuple | None): Receiver namespace of an outbound progress key.

Returns:
int: Transfer id with the reserved low bit cleared.
"""
with self._lock:
while True:
self._counter += 1
fid = (self._counter << FID_LOW_BITS) | (self._epoch << 1)
scoped = (tuple(receiver), fid) if receiver is not None else None
if not any(fid in table or scoped in table for table in self._live_tables):
return fid


# ---- encrypted channel framing ---------------------------------------------
#
# On an encrypted socket every message travels as a frame:
#
# magic "\\x00PF" | type (1) | body length (4, big endian) | body
#
# The body starts with the sender's session nonce and a per-socket sequence
# number (``<nonce>|<seq>|``) covering both frame types, so replay and
# cross-type reordering are detected. Two payload algorithms are used:
#
# type 1 (RSA): small text payloads up to the RSA-OAEP block limit; the
# body carries the chunked base64 ciphertext (same wire
# encoding the line-based control channel used before).
# type 2 (ECDH): everything else, including all binary payloads; the body
# carries a ``pf_ecdh_seal`` blob (salt|iv|ciphertext|tag)
# keyed by the session's ephemeral ECDH keypair, with
# ``<nonce>|<seq>`` bound as AAD.
#
# The receiver reads the frame type instead of inferring the algorithm from
# the payload length: a length can be ambiguous (an ECDH frame for a specific
# plaintext length has the same size as an RSA block) and inferring an
# algorithm from attacker-controlled bytes is a classic confusion oracle.
#
# Plaintext protocol lines (handshake, re-exchange and transfer coordination)
# may still arrive on an encrypted socket: they are passed through when they
# belong to the known protocol set and dropped otherwise, so an encrypted
# channel never dispatches injected plaintext commands.

FRAME_MAGIC = b"\x00PF" # UTF-8 text lines never start with NUL, so a framed stream is unambiguous
FRAME_TYPE_RSA = 1
FRAME_TYPE_ECDH = 2
FRAME_HEADER_LEN = 8 # magic(3) + type(1) + length(4)
MAX_FRAME_PLAINTEXT = 1 << 20 # payload bytes per frame
MAX_FRAME_BODY = MAX_FRAME_PLAINTEXT + 8192 # sealed/rsa overhead slack
CRYPTO_FRAMES_START = "/crypto_frames_start" # plaintext line: peer may send frames now
CRYPTO_ECDH_PUB = "/crypto_ecdh_pub" # RSA-framed line carrying our ECDH public key
CRYPTO_FRAMES_TIMEOUT = 30.0 # seconds a framed send waits for the peer's frames-start
CRYPTO_PEER_KEY_TIMEOUT = 30.0 # seconds an ECDH frame waits for the peer's ECDH key
TRANSFER_KEY_TIMEOUT = 10.0 # seconds a transfer leg waits for its session key material

# Text payloads up to this size travel as a single RSA-OAEP block frame;
# 190 is pf_rsa_max_plaintext_len for the default 2048-bit key and the floor
# over the accepted key sizes (2048..16384), so the split is conservative.
RSA_SMALL_TEXT_LIMIT = 190

# Plaintext lines still tolerated on an encrypted socket: the crypto
# handshake/re-exchange lines, the frames-start announcement and the transfer
# port coordination message. Anything else plaintext is dropped, so an
# injected line can neither run commands nor substitute key material
# (``/crypto_ecdh_pub`` is only ever accepted inside an RSA frame).
_PLAINTEXT_LINE_PREFIXES = (
"/crypto_key_exchange", # covers the ack too
"/crypto_ready",
"/crypto_pub_key", # covers /crypto_pub_key_request
"/crypto_reject",
"/crypto_mode",
CRYPTO_FRAMES_START,
"/server_file_transfer_port",
)
# A plaintext handshake line means the peer reset its secure state
# (re-exchange): drop framing so the dance runs in raw mode again.
_PLAINTEXT_RESET_PREFIXES = _PLAINTEXT_LINE_PREFIXES[:-2]


class _FrameError(Exception):
"""A secure channel saw a malformed or undecryptable frame."""


def _pem_body_of(pem):
"""Return the one-line base64 body of a PEM text (armor lines dropped).

Args:
pem (object): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
body = "".join(
line.strip() for line in pem.splitlines() if line and not line.startswith("-----")
)
return body


TRANSFER_SIGN_BUFFER_LIMIT = 64 * 1024


class _TransferSignBuffer:
"""Bound protocol bytes and batch-scan complete records at the limit."""

def __init__(self, start_sign, ack_sign, error_sign):
self.start_sign = start_sign
self.ack_sign = ack_sign
self.error_sign = error_sign
self.lock = threading.Lock()
self.pending = []
self.pending_bytes = 0
self.partial = bytearray()
# Producer-side threshold scans and the caller consume under this lock.
self.start_seen = False
self.ack_seen = False
self.error_seen = False

def feed(self, data):
"""Queue complete lines and batch-scan when the byte quota is reached.

Raises:
ValueError: A single unterminated line reaches the limit.
"""
offset = 0
error_received = False
view = memoryview(data)
while offset < len(data):
with self.lock:
end = min(len(data), offset + TRANSFER_SIGN_BUFFER_LIMIT - len(self.partial))
newline = data.find(b"\n", offset, end)
stop = newline + 1 if newline >= 0 else end
wire_size = len(self.partial) + stop - offset
if newline < 0 and wire_size >= TRANSFER_SIGN_BUFFER_LIMIT:
raise ValueError("unterminated transfer sign reaches 64 KiB")
if self.pending_bytes + wire_size > TRANSFER_SIGN_BUFFER_LIMIT:
self._scan_pending_locked()
self.partial.extend(view[offset:stop])
offset = stop
if newline >= 0:
line = self.partial.decode("utf-8").strip()
if line:
self.pending.append((line, wire_size))
self.pending_bytes += wire_size
error_received |= line == self.error_sign
self.partial.clear()
if self.pending_bytes + len(self.partial) >= TRANSFER_SIGN_BUFFER_LIMIT:
self._scan_pending_locked()
return error_received

def _scan_pending_locked(self):
"""Latch every pending marker and release the entire scanned prefix."""
processed_count = 0
consumed_bytes = 0
for read_index in range(len(self.pending)):
line, wire_size = self.pending[read_index]
if line == self.start_sign:
self.start_seen = True
elif line == self.ack_sign:
self.ack_seen = True
elif line == self.error_sign:
self.error_seen = True
processed_count += 1
consumed_bytes += wire_size
del self.pending[:processed_count]
self.pending_bytes -= consumed_bytes

def consume(self):
"""Scan and delete queued records, returning a thread-safe result snapshot."""
with self.lock:
self._scan_pending_locked()
return self.start_seen, self.ack_seen, self.error_seen


def _pem_text_of(body):
"""Rebuild a standard PEM text from its one-line base64 body.

Args:
body (object): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
lines = [body[i : i + 64] for i in range(0, len(body), 64)]
return "-----BEGIN PUBLIC KEY-----\n" + "\n".join(lines) + "\n-----END PUBLIC KEY-----\n"


class _CryptoUnavailable(Exception):
"""A transfer leg was stamped encrypted but the session key is not ready."""


def _stamp_nonce(stamp):
"""Parse a transfer mode stamp ("plain" / "enc:<nonce>") -> nonce or None.

Args:
stamp (object): Value used by the operation.

Returns:
NoneType | object: Result produced by the operation.
"""
if stamp and stamp.startswith("enc:"):
nonce = stamp[4:].strip()
return nonce or None
return None


def _parse_transfer_port_announcement(command):
"""Parse the four-token listener reply; legacy UUID replies are rejected."""
try:
parts = shlex.split(command)
if len(parts) != 4 or parts[0].lower() != "/server_file_transfer_port":
return None
port, fid = int(parts[1]), int(parts[2])
if not (0 < port < 65536 and fid >= 0):
return None
return port, fid, parts[3]
except (ValueError, TypeError):
return None


def _transfer_port_announcement(port, fid, stamp):
"""Return one listener's port and encryption stamp for the sender's FID."""
return f"/server_file_transfer_port {port} {fid} {stamp}\n"


class _TransferHandshakeRegistry:
"""Own socket/FID negotiations and resources for each actual control session."""

def __init__(self):
self._changed = threading.Condition()
self._pending = {}
self._unresolved = set()
self._closed = weakref.WeakSet()
self._resources = {}
self._negotiating = set()

@contextmanager
def serialized(self, control_socket, fid):
"""Serialize only request/port pairs, not their data or ACK lifetimes."""
key = (control_socket, fid)
with self._changed:
self._changed.wait_for(lambda: key not in self._negotiating)
self._negotiating.add(key)
try:
yield
finally:
with self._changed:
self._negotiating.remove(key)
self._changed.notify_all()

def register(self, control_socket, fid):
key = (control_socket, fid)
with self._changed:
if (control_socket in self._closed or key in self._pending
or key in self._unresolved):
return None
record = {"key": key, "sent": False, "result": None, "cancelled": False}
self._pending[key] = record
return record

def mark_sent(self, record):
"""Reserve possible transmission before calling the control send path."""
with self._changed:
if (record is None or self._pending.get(record["key"]) is not record
or record["sent"]):
return False
record["sent"] = True
return True

def resolve_port(self, control_socket, fid, port, stamp):
return self._resolve((control_socket, fid), ("port", fid, port, stamp))

def resolve_error(self, control_socket, fid, message):
return self._resolve((control_socket, fid), ("error", message))

def pending(self, control_socket, fid):
with self._changed:
return self._pending.get((control_socket, fid))

def _resolve(self, key, result):
with self._changed:
record = self._pending.get(key)
if (record is None or not record["sent"] or record["cancelled"]
or record["result"] is not None or key in self._unresolved):
return False
record["result"] = result
self._changed.notify_all()
return True

def _retire(self, record):
key = record["key"]
if self._pending.get(key) is record:
del self._pending[key]
if (record["sent"] and record["result"] is None
and key[0] not in self._closed):
self._unresolved.add(key)

def wait(self, record, timeout):
results = self.wait_many((record,), timeout)
return results[record["key"]] if results is not None else None

def wait_many(self, records, timeout):
with self._changed:
if any(record is None for record in records):
return None
self._changed.wait_for(
lambda: any(record["cancelled"] for record in records)
or all(record["result"] is not None for record in records),
timeout=max(0, timeout),
)
# Decide result versus uncertainty under the same condition lock.
for record in records:
self._retire(record)
if any(record["cancelled"] or record["result"] is None for record in records):
return None
return {record["key"]: record["result"] for record in records}

def cancel(self, record):
if record is None:
return
with self._changed:
self._retire(record)
record["cancelled"] = True
self._changed.notify_all()

def closed(self, control_socket):
with self._changed:
return control_socket in self._closed

def track_socket(self, control_socket, transfer_socket):
"""Register listeners before announcing them, and accepted/data sockets."""
if control_socket is None:
return True
with self._changed:
if control_socket not in self._closed:
self._resources.setdefault(control_socket, set()).add(transfer_socket)
return True
self._close_socket(transfer_socket)
return False

def release_socket(self, control_socket, transfer_socket):
with self._changed:
resources = self._resources.get(control_socket)
if resources is not None:
resources.discard(transfer_socket)
if not resources:
del self._resources[control_socket]
self._changed.notify_all()

def wait_socket(self, control_socket):
"""Wait for the retired session's workers to release their resources."""
with self._changed:
self._changed.wait_for(lambda: not self._resources.get(control_socket))

def occupied(self, control_socket, fid):
"""Pending and uncertain negotiations both prevent a second same-FID leg."""
with self._changed:
key = (control_socket, fid)
return key in self._pending or key in self._unresolved

@staticmethod
def _close_socket(sock):
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
sock.close()

def cancel_socket(self, control_socket):
with self._changed:
self._closed.add(control_socket)
for key, record in list(self._pending.items()):
if key[0] is control_socket:
record["cancelled"] = True
del self._pending[key]
self._unresolved.difference_update(
key for key in tuple(self._unresolved) if key[0] is control_socket
)
resources = tuple(self._resources.get(control_socket, ()))
self._changed.notify_all()
for sock in resources:
self._close_socket(sock)


@contextmanager
def _transfer_handshake(instance, control_socket, fid):
"""Register before sending; an uncertain sent negotiation cannot be reused."""
record = instance._transfer_handshakes.register(control_socket, fid)
try:
yield record
finally:
instance._transfer_handshakes.cancel(record)


def _send_transfer_request(instance, record, message, *, is_send_raw=False):
if not instance._transfer_handshakes.mark_sent(record):
return False
return instance.send_message(record["key"][0], message, is_send_raw=is_send_raw)


def _crypto_is_protocol_line(message):
"""Return true for the protocol's own handshake/coordination lines.

True for the protocol's own handshake/coordination lines.

These must not reset the decode-failure streak: a re-exchange (and the
transfer-port coordination it needs) is not genuine peer traffic.

Args:
message (object): Value used by the operation.

Returns:
bool | object: Result produced by the operation.
"""
if message.startswith("/crypto"):
return True
return message.startswith("/server_file_transfer_port")


class _CryptoSession:
"""Per control-session crypto context shared by that session's sockets.

Holds the RSA identity and an ephemeral ECDH keypair; the public ECDH key
travels as a small RSA-framed ``/crypto_ecdh_pub`` line after the channel
flips, so the bulk (ECDH-sealed) key material is authenticated by the
RSA/TOFU handshake that already authenticated the session.
"""

def __init__(self, rsa_crypto_obj, role, log=None, debug=None):
self.rsa = rsa_crypto_obj
self.role = role
self.log = log
self.debug = debug
self.lock = threading.RLock()
self.ecdh = None
self.peer_ecdh = None
self.peer_ecdh_b64 = None
self.peer_ecdh_event = threading.Event()

def ensure_ecdh(self):
"""Handle the operation.

Returns:
object: Result produced by the operation.
"""
with self.lock:
if self.ecdh is None:
self.ecdh = rsa_crypto.EcdhKeyPair()
return self.ecdh

def reset_ecdh(self):
"""Session was re-keyed: drop the old ECDH material."""
with self.lock:
self.ecdh = None
self.peer_ecdh = None
self.peer_ecdh_b64 = None
self.peer_ecdh_event.clear()

def set_peer_ecdh_b64(self, body):
"""Handle the operation.

Args:
body (object): Value used by the operation.

Returns:
bool: Result produced by the operation.
"""
try:
peer = rsa_crypto.EcdhPubKey.from_pem(_pem_text_of(body.strip()))
except Exception:
return False
with self.lock:
self.peer_ecdh = peer
self.peer_ecdh_b64 = body.strip()
self.peer_ecdh_event.set()
return True

def peer_ecdh_pub(self, timeout=0):
"""Return the peer's ECDH public key, or None (waits up to ``timeout``).

The peer's ECDH public key, or None (waits up to ``timeout``).

Args:
timeout (float): Value used by the operation.

Returns:
NoneType | object: Result produced by the operation.
"""
if not self.peer_ecdh_event.wait(timeout=max(0.0, timeout)):
return None
with self.lock:
return self.peer_ecdh

def publish_pub(self, channel):
"""Send our session ECDH public key once frames are allowed both ways.

Args:
channel (object): Value used by the operation.
"""
if channel is None or not channel.claim_ecdh_pub_send():
return
try:
body = _pem_body_of(self.ensure_ecdh().public_pem())
channel.send(f"{CRYPTO_ECDH_PUB} {body}\n", force_rsa=True)
except Exception:
if self.log:
self.log("crypto: publishing the session ECDH key failed")

def transfer_stamp(self, channel, force_plain=False):
"""Mode+nonce announced to a transfer connector ("plain"/"enc:<nonce>").

Encrypted only when this side's channel flipped and both sides hold
the session ECDH material; key pushes force plaintext because they
carry the public keys themselves.

Args:
channel (object): Value used by the operation.
force_plain (bool): Value used by the operation.

Returns:
object | str: Result produced by the operation.
"""
if force_plain or self.rsa is None or channel is None or not channel.secure:
return "plain"
self.ensure_ecdh()
if self.peer_ecdh_pub(TRANSFER_KEY_TIMEOUT) is None:
if self.log:
self.log("crypto: peer ECDH key missing, transfer stays plaintext")
return "plain"
return "enc:" + secrets.token_hex(16)

def attach_transfer(self, sock, control_channel, stamp):
"""Channel for a stamped transfer leg, or None when it stays plaintext.

Raises `_CryptoUnavailable` when the stamp says encrypted but the
session key material is not ready: the caller aborts the transfer
instead of silently downgrading it.

Args:
sock (object): Value used by the operation.
control_channel (object): Value used by the operation.
stamp (object): Value used by the operation.

Returns:
NoneType | object: Result produced by the operation.

Raises:
_CryptoUnavailable: When the operation cannot complete.
"""
nonce = _stamp_nonce(stamp)
if nonce is None:
return None
self.ensure_ecdh()
peer_pem_path = control_channel.peer_pem_path if control_channel is not None else None
if peer_pem_path is None or self.peer_ecdh_pub(TRANSFER_KEY_TIMEOUT) is None:
raise _CryptoUnavailable("transfer stamped encrypted but the session key is not ready")
log = self.log or (lambda *parts: None)
debug = self.debug or (lambda *parts: None)
channel = _SecureChannel(sock, self, log, debug)
channel.enable(nonce, nonce, peer_pem_path)
channel.note_peer_frames_ready() # the stamp fixes the mode: no frames-start dance on transfer legs
return channel



def _connector_transfer_crypto(session, control_channel, stamp):
"""Return (session, peer_pem_path, nonce) for a connector-side transfer leg.

(session, peer_pem_path, nonce) for a connector-side transfer leg.

Returns None for a plaintext leg; raises `_CryptoUnavailable` when the
stamp promises encryption but the session key material is missing, so the
caller aborts the transfer instead of downgrading it silently.

Args:
session (object): Value used by the operation.
control_channel (object): Value used by the operation.
stamp (object): Value used by the operation.

Returns:
NoneType | list | tuple: Result produced by the operation.

Raises:
_CryptoUnavailable: When the operation cannot complete.
"""
nonce = _stamp_nonce(stamp)
if nonce is None:
return None
if session is None:
raise _CryptoUnavailable("no crypto session for the transfer leg")
session.ensure_ecdh()
peer_pem_path = control_channel.peer_pem_path if control_channel is not None else None
if peer_pem_path is None or session.peer_ecdh_pub(TRANSFER_KEY_TIMEOUT) is None:
raise _CryptoUnavailable("transfer key material is not ready")
return session, peer_pem_path, nonce


def _enable_connector_channel(sock, crypto):
"""Framing channel for a freshly connected transfer socket, or None.

Args:
sock (object): Value used by the operation.
crypto (object): Value used by the operation.

Returns:
NoneType | object: Result produced by the operation.
"""
if crypto is None:
return None
session, peer_pem_path, nonce = crypto
channel = _SecureChannel(
sock,
session,
session.log or (lambda *parts: None),
session.debug or (lambda *parts: None),
)
channel.enable(nonce, nonce, peer_pem_path)
channel.note_peer_frames_ready() # the stamp fixes the mode: no frames-start dance
return channel


def _magic_tail_len(buf):
"""Length of the proper ``FRAME_MAGIC`` prefix ``buf`` ends with (0..2).

A magic split across reads is held, never served as plaintext: the bytes
behind it belong to a frame, and frame bytes are not line traffic (see
`_SecureChannel.feed`).

Args:
buf (object): Value used by the operation.

Returns:
int | object: Result produced by the operation.
"""
for length in range(len(FRAME_MAGIC) - 1, 0, -1):
if buf.endswith(FRAME_MAGIC[:length]):
return length
return 0


class _SecureChannel:
"""Framed encryption for one socket.

Send: ``send`` chunks a payload into frames (RSA for a small text payload,
ECDH-sealed otherwise). Receive: ``feed`` parses socket bytes into the
plaintext buffer while the channel is framed (and reports the bytes
unparsed while it is not), ``take`` serves the byte stream the callers
read.

Lifecycle: raw -> ``enable`` -> [``disable`` -> raw]. ``peer_frames_ready``
must be set before frames may be sent (the peer announces it with a
plaintext ``/crypto_frames_start`` after it flipped), so a frame can never
reach a peer whose reader still expects raw bytes.
"""

def __init__(
self,
sock,
session,
log,
debug,
send_lock=None,
sendall=None,
on_decode_failure=None,
on_disable=None,
):
self.socket = sock
self.session = session
self._log = log
self._debug = debug
self._on_decode_failure = on_decode_failure
self._on_disable = on_disable # keep the owner's secure-socket set truthful
self._lock = threading.RLock() # buffers + sequence counters
self._send_lock = (
send_lock if send_lock is not None else threading.Lock()
) # shared with the plaintext send path: frame and raw writes never interleave
self._sendall = sendall if sendall is not None else sock.sendall
self.secure = False
self.peer_frames_ready = False
self.frames_allowed = threading.Event()
self.ecdh_pub_sent = False
self.local_nonce = None
self.peer_nonce = None
self.peer_pem_path = None
self.send_seq = 0
self.recv_seq = 0
self._raw = bytearray() # socket bytes not yet parsed
self._plain = bytearray() # decrypted bytes ready for the reader

def enable(self, local_nonce, peer_nonce, peer_pem_path=None):
"""Start speaking frames (flip completed on both sides).

Args:
local_nonce (object): Value used by the operation.
peer_nonce (object): Value used by the operation.
peer_pem_path (str): Value used by the operation.
"""
with self._lock:
self.local_nonce = local_nonce
self.peer_nonce = peer_nonce
self.peer_pem_path = peer_pem_path
self.send_seq = 0
self.recv_seq = 0
self.ecdh_pub_sent = False # a fresh session publishes its own key
self.secure = True
if self.peer_frames_ready:
self.frames_allowed.set()

def disable(self):
"""Drop back to raw mode (decode failure or peer re-exchange).

The next handshake must announce frame readiness again, so the
peer-ready flag is cleared with the mode, and the owner's secure-socket
set is updated through ``on_disable``.
"""
with self._lock:
was_secure = self.secure
self.secure = False
self.peer_frames_ready = False
self.ecdh_pub_sent = False
self.frames_allowed.clear()
if was_secure and self._on_disable is not None:
try:
self._on_disable()
except Exception:
pass

def note_peer_frames_ready(self):
"""Return the peer announced it may receive frames.

The peer announced it may receive frames.
"""
with self._lock:
self.peer_frames_ready = True
if self.secure:
self.frames_allowed.set()

def claim_ecdh_pub_send(self):
"""Return true exactly once per session, when the peer can receive frames.

True exactly once per session, when the peer can receive frames.

Returns:
bool: Result produced by the operation.
"""
with self._lock:
if self.ecdh_pub_sent or not self.frames_allowed.is_set():
return False
self.ecdh_pub_sent = True
return True

# -- send path -----------------------------------------------------------

def send(self, payload, force_rsa=False, *, require_secure=False):
"""Frame and send one payload (str or bytes) on this socket.

``force_rsa`` is used for the ECDH public-key line, which must travel
in an RSA frame even if it is longer than the single-block limit (an
ECDH frame would be circular: the peer key it needs is this payload).

Raises on failure; the caller logs and reports the send failure.

Args:
payload (bytes | str): Value used by the operation.
force_rsa (bool): Value used by the operation.
require_secure (bool): Reject a control frame if re-exchange disabled framing.

Raises:
RuntimeError: When the operation cannot complete.
"""
if isinstance(payload, str):
data = payload.encode("utf-8")
small_text = True
else:
data = bytes(payload)
small_text = False
use_rsa = force_rsa or (small_text and len(data) <= RSA_SMALL_TEXT_LIMIT)
peer = self.session.peer_ecdh_pub(0 if use_rsa else CRYPTO_PEER_KEY_TIMEOUT)
if not use_rsa and peer is None:
raise RuntimeError("encrypted channel has no peer ECDH key")
if not self.frames_allowed.wait(timeout=CRYPTO_FRAMES_TIMEOUT):
raise RuntimeError("encrypted channel not ready (peer never allowed frames)")
if use_rsa:
with self._send_lock:
if require_secure:
with self._lock:
if not self.secure or not self.frames_allowed.is_set():
raise RuntimeError("control framing changed before write")
self._sendall(self._rsa_frame(data))
else:
self._sendall(self._rsa_frame(data))
return
for start in range(0, max(len(data), 1), MAX_FRAME_PLAINTEXT):
chunk = data[start : start + MAX_FRAME_PLAINTEXT]
with self._send_lock:
if require_secure:
with self._lock:
if not self.secure or not self.frames_allowed.is_set():
raise RuntimeError("control framing changed before write")
self._sendall(self._ecdh_frame(chunk, peer))
else:
self._sendall(self._ecdh_frame(chunk, peer))

def _rsa_frame(self, text_bytes):
"""Handle the operation.

Args:
text_bytes (bytes | str): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
with self._lock:
nonce = self.local_nonce or ""
seq = self.send_seq
self.send_seq = seq + 1
body = "{}|{}|{}".format(
nonce,
seq,
self.session.rsa.encrypt_for_peer(self.peer_pem_path, text_bytes.decode("utf-8")),
).encode("ascii")
return self._wrap(FRAME_TYPE_RSA, body)

def _ecdh_frame(self, chunk, peer):
"""Handle the operation.

Args:
chunk (bytes | str): Value used by the operation.
peer (tuple): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
with self._lock:
nonce = self.local_nonce or ""
seq = self.send_seq
self.send_seq = seq + 1
aad = "{}|{}".format(nonce, seq).encode("ascii")
sealed = self.session.ecdh.seal(peer, chunk, aad)
return self._wrap(FRAME_TYPE_ECDH, aad + b"|" + sealed)

@staticmethod
def _wrap(frame_type, body):
"""Handle the operation.

Args:
frame_type (object): Value used by the operation.
body (object): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
return FRAME_MAGIC + bytes([frame_type]) + len(body).to_bytes(4, "big") + body

# -- receive path --------------------------------------------------------

def feed(self, data):
"""Parse received socket bytes; returns the bytes for the line reader.

While the channel is framed every byte is parsed into the plaintext
buffer and an empty result comes back; while it is not, plaintext
bytes are returned for the line reader. Frame bytes are consumed in
both modes: a peer that has not processed a re-exchange yet keeps
sending frames after this side dropped framing, and such a stale
frame cannot be authenticated any more — its bytes must never reach
the line reader, which would echo them as a message and reset the
decode-failure streak.

The parse shares the channel lock with ``enable``/``disable``, so a
flip that lands while the caller's read was in flight still
classifies the bytes by the state of that moment.

Args:
data (bytes | str): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
with self._lock:
self._raw += data
return self._parse_buffered()

def _parse_buffered(self):
"""Parse everything buffered; returns the bytes for the line reader.

Must be called under the channel lock. A ``disable`` performed while
parsing (the peer's re-exchange line) is honoured: the bytes behind
it belong to the peer's raw stream and are returned as such.

Returns:
object: Result produced by the operation.
"""
plain = bytearray()
while self._raw:
if (
self._raw[: min(len(self._raw), len(FRAME_MAGIC))]
== FRAME_MAGIC[: min(len(self._raw), len(FRAME_MAGIC))]
):
if len(self._raw) < len(FRAME_MAGIC):
break # a partial magic may still be a frame
if not self._consume_frame():
break
elif self.secure:
if not self._consume_plaintext_line():
break
else:
# raw: only the bytes ahead of a stale frame are line traffic;
# the frame behind them is consumed on the next turn — frame
# bytes must never reach the line reader, which would echo
# them as a message and reset the breaker (see feed)
start = self._raw.find(FRAME_MAGIC)
if start < 0: # hold a magic a split may still complete
start = len(self._raw) - _magic_tail_len(self._raw)
plain += self._raw[:start]
del self._raw[:start]
return bytes(plain)

def _consume_frame(self):
"""Consume one whole frame; False when more bytes are needed.

A framed channel decrypts the body; a raw one drops it, because the
session keys were torn down with the framing.

Returns:
bool: Result produced by the operation.

Raises:
_FrameError: When the operation cannot complete.
"""
if len(self._raw) < FRAME_HEADER_LEN:
return False
frame_type = self._raw[len(FRAME_MAGIC)]
length = int.from_bytes(self._raw[len(FRAME_MAGIC) + 1 : FRAME_HEADER_LEN], "big")
if frame_type not in (FRAME_TYPE_RSA, FRAME_TYPE_ECDH) or length > MAX_FRAME_BODY:
self._raw.clear() # a framed stream cannot be resynchronised
raise _FrameError("malformed frame header")
if len(self._raw) < FRAME_HEADER_LEN + length:
return False
body = bytes(self._raw[FRAME_HEADER_LEN : FRAME_HEADER_LEN + length])
del self._raw[: FRAME_HEADER_LEN + length]
if not self.secure:
self._debug("crypto: dropped a stale frame")
return True
if frame_type == FRAME_TYPE_RSA:
self._decode_rsa(body)
else:
self._decode_ecdh(body)
return True

def _consume_plaintext_line(self):
"""Pass known plaintext protocol lines through; drop anything else.

Returns False when the line is not complete yet.

Returns:
bool: Result produced by the operation.

Raises:
_FrameError: When the operation cannot complete.
"""
nl = self._raw.find(b"\n")
if nl < 0:
if len(self._raw) > MAX_FRAME_PLAINTEXT:
self._raw.clear()
raise _FrameError("unterminated plaintext line")
return False
line = bytes(self._raw[: nl + 1])
del self._raw[: nl + 1]
try:
stripped = line.decode("utf-8").strip()
except UnicodeDecodeError:
stripped = ""
if stripped.startswith(_PLAINTEXT_LINE_PREFIXES):
if stripped.startswith(_PLAINTEXT_RESET_PREFIXES):
# the peer restarted the handshake: framing is over until re-flip
self._debug("crypto: peer re-exchange line, dropping framed mode")
self.disable()
self._plain += line
else:
self._debug("crypto: dropped plaintext line on an encrypted channel")
return True

def _split_prefix(self, body):
"""Split ``<nonce>|<seq>|`` off a frame body -> (nonce, seq) or None.

Args:
body (object): Value used by the operation.

Returns:
NoneType | list | tuple: Result produced by the operation.
"""
first = body.find(b"|")
if first < 0:
return None
second = body.find(b"|", first + 1)
if second < 0:
return None
try:
nonce = body[:first].decode("ascii")
seq = int(body[first + 1 : second])
except (UnicodeDecodeError, ValueError):
return None
return nonce, seq, body[second + 1 :]

def _check_replay(self, nonce, seq):
"""Return true when the frame is fresh; a stale/duplicate frame is dropped.

True when the frame is fresh; a stale/duplicate frame is dropped.

Args:
nonce (object): Value used by the operation.
seq (object): Value used by the operation.

Returns:
bool: Result produced by the operation.
"""
if nonce != self.peer_nonce:
self._debug("crypto: replay dropped (nonce mismatch)")
return False
if seq != self.recv_seq:
self._debug(
"crypto: replay/out-of-order dropped (seq {}, expected {})".format(
seq, self.recv_seq
)
)
return False
return True

def _decode_rsa(self, body):
"""Handle the operation.

Args:
body (object): Value used by the operation.

Raises:
_FrameError: When the operation cannot complete.
"""
parts = self._split_prefix(body)
if parts is None:
raise _FrameError("malformed RSA frame")
nonce, seq, cipher = parts
if not self._check_replay(nonce, seq):
return
try:
ok, plain = self.session.rsa.decrypt_with_own(cipher.decode("ascii"))
except Exception:
ok, plain = False, None
if not ok:
raise _FrameError("RSA decryption failed")
self.recv_seq += 1
self._plain += plain.encode("utf-8") if isinstance(plain, str) else bytes(plain)

def _decode_ecdh(self, body):
"""Handle the operation.

Args:
body (object): Value used by the operation.

Raises:
_FrameError: When the operation cannot complete.
"""
parts = self._split_prefix(body)
if parts is None:
raise _FrameError("malformed ECDH frame")
nonce, seq, sealed = parts
if not self._check_replay(nonce, seq):
return
peer = self.session.peer_ecdh_pub(0)
if peer is None or self.session.ecdh is None:
raise _FrameError("ECDH frame without session key material")
aad = "{}|{}".format(nonce, seq).encode("ascii")
try:
plain = self.session.ecdh.open(peer, sealed, aad)
except Exception:
raise _FrameError("ECDH decryption failed")
self.recv_seq += 1
self._plain += plain

def take(self, n):
"""Up to ``n`` plaintext bytes; empty when none are buffered.

Args:
n (int): Value used by the operation.

Returns:
bytes | object: Result produced by the operation.
"""
with self._lock:
if not self._plain:
return b""
out = bytes(self._plain[:n])
del self._plain[: len(out)]
return out

def drain_plaintext(self):
"""Bytes the line reader still gets after framing failed.

The decrypted buffer plus the plaintext already buffered with the
frame that failed — the peer's re-exchange line, for example. Frame
bytes stay in the channel, where the stale-frame drop consumes them:
they must not be served as a line, and the channel may still need
them to resynchronise.

Returns:
object: Result produced by the operation.
"""
with self._lock:
plain = bytearray(self._plain)
self._plain.clear()
if not self.secure:
plain += self._parse_buffered()
return bytes(plain)


class CommandNotFoundError(Exception):
"""A command passed to `call_extension_functions` is not registered.

Raised when the first token of the command matches no handler registered
with `register_command`, on either instance class.
"""


def _custom_handler_for(command, handlers):
"""Return the extension handler one command line selects.

Args:
command (str): Command line whose first token names the handler.
handlers (list): The ``[{}, {}]`` registry, the console group and the inbound group.

Returns:
callable: The registered handler; with both groups registering the
name, the console group wins.

Raises:
CommandNotFoundError: If neither group registers the first token.
ValueError: If ``command`` cannot be split (unbalanced quotes).
"""
cmd_parts = shlex.split(command.strip())
cmd_name = cmd_parts[0].lower() if cmd_parts else ""
handler = handlers[1].get(cmd_name)
if handler is None:
handler = handlers[0].get(cmd_name)
if handler is None:
raise CommandNotFoundError(f"Unknown extension command: {command}")
return handler


class _CustomCommandExecutor(ThreadPoolExecutor):
"""Bound accepted Futures and coordinate terminal teardown for one endpoint."""

def __init__(self, limit):
self._worker = threading.local()
super().__init__(max_workers=limit, initializer=setattr,
initargs=(self._worker, "in_pool", True))
self._limit = limit
self._changed = threading.Condition()
self._in_flight = 0
self._state = "open"
self._retiring = self._retire_error = self._flush_on_idle = None

def submit(self, fn, /, *args, **kwargs):
with self._changed:
self._changed.wait_for(
lambda: self._state != "open" or self._in_flight < self._limit
)
if self._state != "open":
raise RuntimeError("cannot submit a custom task after shutdown has started")
self._in_flight += 1
try:
future = super().submit(fn, *args, **kwargs)
except BaseException:
self._in_flight -= 1
self._changed.notify()
raise
# The callback is the only release path for an accepted Future. It also
# runs for a Future cancelled by shutdown(cancel_futures=True).
future.add_done_callback(self._release_slot)
return future

def _release_slot(self, _future):
flush = None
with self._changed:
self._in_flight -= 1
if not self._in_flight:
flush, self._flush_on_idle = self._flush_on_idle, None
self._changed.notify()
if flush is not None:
self._finish(flush)

def close(self, retire, flush, *, join_receiver=None):
"""Retire resources once; only an external caller can join all workers."""
current = threading.current_thread()
worker = getattr(self._worker, "in_pool", False)
with self._changed:
if self._retiring is current:
return
if self._state == "stopped" and worker:
return
if self._state == "stopping":
# A pool handler must not wait for an external closer: that closer
# may be waiting for this handler to return.
if worker:
return
self._changed.wait_for(lambda: self._state != "stopping")
first = self._state == "open"
if first:
self._state, self._retiring = "stopping", current
self._changed.notify_all()

defer = False
if first:
try:
try:
retire() # close sockets before waiting on any endpoint thread
finally:
self.shutdown(wait=False, cancel_futures=True)
except BaseException as exc:
self._retire_error = exc
finally:
with self._changed:
defer = worker and self._in_flight != 0
if defer:
self._flush_on_idle = flush
self._state, self._retiring = "retired", None
self._changed.notify_all()

if not worker:
# External close owns the synchronous drain. A second external closer
# can arrive after the first one has retired resources and join here.
self.shutdown(wait=True)
if join_receiver is not None:
join_receiver()
if self._retire_error is not None:
raise self._retire_error
if not worker or (first and not defer):
self._finish(flush)

def _finish(self, flush):
with self._changed:
self._changed.wait_for(lambda: self._state != "flushing")
# Repeated external close must flush records appended after the
# first terminal close; resource retirement remains idempotent.
self._state = "flushing"
completed = False
try:
flush()
completed = True
finally:
with self._changed:
self._state = "stopped" if completed else "retired"
self._changed.notify_all()


class _ForwardBudget:
"""Plaintext bytes owed to downstream writers across one server's relays.

The caller holds ``cond`` for publication, return and queue retirement;
taking an item out of a queue does not release its credit.
"""

def __init__(self):
self.cond = threading.Condition()
self.used = 0
self.peak = 0

def publish(self, pending, chunk, offset, limit, state):
"""Publish the prefix that fits to one live queue; zero means wait."""
space = max(1, int(limit)) - self.used
if space <= 0:
return 0
part = chunk[offset:offset + space]
size = len(part)
self.used += size
state["buffered"] += size
self.peak = max(self.peak, self.used)
try:
pending.put_nowait(part)
except BaseException:
self.release(state, size) # ownership never passed to a writer
raise
return size

def release(self, state, size):
self.used -= size
state["buffered"] -= size
self.cond.notify_all()


class TCP_Server_Base: # TCP server class
"""TCP server: accept clients, dispatch commands, relay messages and files.

Each accepted connection is served by `handle_client`, either in its own
thread (the default) or by a coroutine on an asyncio event loop when
``is_asynic_clients_io`` is True: every inbound line is delivered to the
listeners registered with `add_message_listener` first; a line starting
with ``/`` then goes to `handle_command` (built-in commands plus the
handlers registered with `register_command`), any other line is a plain
message stored in ``messages_dict``.

Attributes:
host (str): Address the server socket binds to.
port (int): First port considered for binding and for allocation.
clients (dict): Accepted connections keyed by ``(ip, port)``; each value
holds ``socket``, ``address``, ``id`` and ``connected_time``.
running (bool): True while the accept loop runs.
is_asynic_clients_io (bool): Whether clients are served by coroutines on
an event loop instead of one thread per client.
is_enable_encrypto (bool): Whether the RSA channel is negotiated.
is_debug (bool): Whether execution-process lines are logged as well.
is_print_log (bool): Whether the instance logs anything at all.
is_enable_file_transfer_progress_bar (bool): Whether every running file
transfer is tracked in ``file_recv_progress``/``file_upload_progress``.
is_enable_real_time_network_speed (bool): Whether the real-time network
speed is measured into ``upload_network_speed``/``recv_network_speed``.
file_recv_progress (dict): Running downloads keyed by fid; each value is
``[received bytes, total bytes, current speed, file path, peer]``
(the speed is None until the transfer has moved its first chunk,
and while speed measurement is off; ``peer`` is the sender's
``(ip, port)``).
file_upload_progress (dict): Uploads keyed by ``(receiver, fid)``; each value is
``[sent bytes, total bytes, current speed, file path, peer]``, with
``peer`` the receiver's ``(ip, port)``. A forwarded transfer stores
the original peer on both sides, never the relay.
file_trans_progress_file (str): Path under the protocol's ``.Flow``
directory where the two stores are written when a connection drops
and read back on the next reconnect (``_request_resumes``).
upload_network_speed (float | None): Bytes per second sent, or None when
not measured.
recv_network_speed (float | None): Bytes per second received, or None
when not measured.
"""

def __init__(
self,
host="127.0.0.1",
port=65432,
max_clients=10,
port_add_step=1,
port_range_num=100,
max_file_transfer_thread_num=10,
is_hand_alloc_port=False,
is_input_command_in_console=True,
max_custom_workers=10,
is_extend_command=False,
is_enable_encrypto=True,
is_custom_keys=None,
max_mem_buff=2048,
recv_messages_chunk_len=4096,
file_transfer_chunk_len=65536,
is_asynic_clients_io=False,
is_debug=False,
is_print_log=True,
is_enable_file_transfer_progress_bar=True,
is_enable_real_time_network_speed=True,
):
"""Create the server and, unless extended, start accepting clients.

Args:
host (str): Address the server socket binds to. Defaults to
"127.0.0.1".
port (int): First port to bind; also the base of the allocation range.
max_clients (int): Maximum concurrent clients served in thread mode;
ignored when ``is_asynic_clients_io`` is True. Defaults to 10.
port_add_step (int): Step between candidate ports. Defaults to 1.
port_range_num (int): Number of ports per step. Defaults to 100.
max_file_transfer_thread_num (int): Concurrent file transfers allowed.
Defaults to 10.
is_hand_alloc_port (bool): Reserve a port range across processes, so
several instances on one host do not collide. Defaults to False.
is_input_command_in_console (bool): Start the console command thread.
Defaults to True.
max_custom_workers (int): Worker slots for `submit_task` and threaded
command handlers. Defaults to 10.
is_extend_command (bool): When True, do not call `start_TCP_Server`;
the caller starts the server when ready. Defaults to False.
is_enable_encrypto (bool): Negotiate the RSA-encrypted channel for
every connection. Defaults to True.
is_custom_keys (list | None): ``[pub_key_path, pvt_key_path]`` pair used
instead of the default key lookup; an invalid pair is ignored.
max_mem_buff (int): Shared budget in MiB for queued and in-flight
downstream bytes of all native relays. Defaults to 2048.
recv_messages_chunk_len (int): Bytes read per receive on the control
connection, covering commands and messages. Defaults to 4096.
file_transfer_chunk_len (int): Chunk size in bytes streamed when
sending or receiving a file or folder. Defaults to 65536 (64 KiB).
is_asynic_clients_io (bool): Serve clients with asyncio coroutines on
an event loop instead of one thread per client, so a single
server can hold thousands of concurrent connections. Defaults to
False.
is_debug (bool): Log execution-process lines in addition to command
and result lines. Defaults to False.
is_print_log (bool): Log at all; False silences every line this
instance would print. Defaults to True.
is_enable_file_transfer_progress_bar (bool): Track every running
file transfer in ``file_recv_progress`` (downloads) and
``file_upload_progress`` (uploads): each entry holds the bytes
transferred so far, the total size and the current speed (None
while ``is_enable_real_time_network_speed`` is False). An entry
appears when a transfer starts and is dropped when it ends.
Defaults to True.
is_enable_real_time_network_speed (bool): Measure the real-time
network speed of every send and receive — the control layer and
every temporary connection (file transfers included) — into
``upload_network_speed`` and ``recv_network_speed`` (bytes per
second, averaged over ``NETWORK_SPEED_WINDOW`` seconds). With
False nothing is measured and every speed value is None.
Defaults to True.

Raises:
OSError: If the ``.Flow`` directories or ``decode_command_table.json``
cannot be created or read.
"""
self.max_mem_buff = max_mem_buff * 1024 * 1024
self.recv_messages_chunk_len = recv_messages_chunk_len
self.file_transfer_chunk_len = file_transfer_chunk_len
self.is_enable_file_transfer_progress_bar = is_enable_file_transfer_progress_bar
self.is_enable_real_time_network_speed = is_enable_real_time_network_speed
# Per-transfer progress stores: fid -> [transferred bytes, total bytes,
# current speed, local file path, peer (ip, port)]. An entry appears
# when a transfer starts and is removed when it ends, so the stores
# hold exactly the transfers running now; iterate over a copy while
# transfers are in flight. A transfer interrupted by a disconnect
# keeps its entry (and its partial file) so it can be resumed once
# the peer is back (see `_request_resumes`).
self.file_recv_progress = {} # downloads: fid -> [received, total, speed, path, peer]
self.file_upload_progress = {} # (receiver, fid) -> [sent, total, speed, path, peer]
self.upload_network_speed = None # bytes/s over the last NETWORK_SPEED_WINDOW seconds
self.recv_network_speed = None
self._network_speed_lock = threading.Lock() # serialises the speed sample windows
self._upload_speed_samples = collections.deque() # (timestamp, bytes) samples
self._recv_speed_samples = collections.deque()
self._upload_speed_total = 0 # bytes held in the sample windows
self._recv_speed_total = 0
self._forward_budget = _ForwardBudget()
self._forward_relays = {}
self._forward_relays_lock = threading.Lock()
# One route per local upstream fid; downstream keys point to that fid.
self._fid_routes = {}
self._fid_route_index = {} # (receiver, downstream fid) -> upstream fid
self._relay_recoveries = {} # route requests and independent Target owners
# Transfer ids for the legs this instance sends (see `_FidAllocator`).
# Inbound ids use local integer keys; outbound ids use (receiver, fid).
# Equal numbers cannot share progress, pause state or sockets.
self._fid_alloc = _FidAllocator(
(self.file_upload_progress, self.file_recv_progress,
self._fid_routes, self._fid_route_index)
)
# Outbound-transfer pause switches (see `pause_trans`/`start_trans`):
# (receiver, fid) -> bool; a pause never affects a different receiver.
self._transfer_pause = {}
self._transfer_pause_cond = threading.Condition()
self._transfer_controls = _TransferControlRegistry(
self._transfer_pause, self._transfer_pause_cond, self
)
self._active_transfer_fids = set() # fids of the legs running right now
self._active_transfer_sockets = {} # receive fid / (receiver, fid) -> socket
self.project_dir = os.path.dirname(os.path.abspath(__file__))
self.project_info_dir = os.path.join(self.project_dir, ".Flow")
if os.path.exists(self.project_info_dir) == False:
os.mkdir(self.project_info_dir)
self.project_temp_info_dir = os.path.join(self.project_info_dir, "temp_info")
if os.path.exists(self.project_temp_info_dir) == False:
os.mkdir(self.project_temp_info_dir)
self.server_port_lock_file = os.path.join(
self.project_temp_info_dir, "server_port_lock.lock"
)
# Interrupted transfers are persisted here on a disconnect and read
# back when a peer returns (see `_persist_transfer_progress`).
self.file_trans_progress_file = os.path.join(
self.project_info_dir, "server_file_trans_progress.json"
)
self._transfer_progress_lock = threading.RLock() # serialises the persist/load pair
self._resume_sends = {} # transient locks and request sets; no file metadata
self._retired_transfer_sessions = {} # peer -> captured old session owners
self._transfer_progress_changed = threading.Condition(self._transfer_progress_lock)
self._receive_transfers = {} # request/listener/data owner until final cleanup
self._progress_discarded = False
self._config_started = False
self._config_closed = False
self._config_busy = 0
self.decode_command_table_file_path = os.path.join(
self.project_dir, "decode_command_table.json"
)
self.file_transfer_dir = os.path.join(self.project_dir, "received_files")
self.host = host
self.port = port
self.all_allocated_ports_list = [self.port]
self.max_clients = max_clients
self.is_hand_alloc_port = is_hand_alloc_port
self.is_input_command_in_console = is_input_command_in_console
# `running` must exist before alloc_port(): the port-range record
# reports it, and a manual-mode instance is live while it holds a range.
self.running = False
self._stopped = False # a stop() before start_TCP_Server() must stick
self.alloc_port(port_add_step, port_range_num)
self.server_socket = None
self.clients = {} # store client info
self._transfer_handshakes = _TransferHandshakeRegistry()
self.client_lock = threading.Lock() # add the threading lock
self.max_file_transfer_thread_num = max_file_transfer_thread_num
MAX_CONCURRENT_FILES = self.max_file_transfer_thread_num
self.file_semaphore = threading.Semaphore(MAX_CONCURRENT_FILES)
self.command_decode_table_str = None
with open(self.decode_command_table_file_path, "r", encoding="utf-8") as f:
self.command_decode_table_str = f.read()
self.command_decode_table = ast.literal_eval(self.command_decode_table_str)
self.send_file_header_sign = self.command_decode_table[0]["file_send_server_header"]
self.send_file_data_sign = self.command_decode_table[0]["file_send_server_data"]
self.server_received_file_header_sign = self.command_decode_table[0][
"file_receive_client_header"
]
self.server_received_file_data_sign = self.command_decode_table[0][
"file_receive_client_data"
]
self.server_start_file_transfer_sign = self.command_decode_table[0][
"file_send_server_start_file_transfer"
]
self.error_sign = self.command_decode_table[0]["file_send_receive_error"]
self._custom_handlers = [{}, {}]
self._custom_handler_threaded = [{}, {}]
self._custom_executor = ThreadPoolExecutor(max_workers=max_custom_workers)
self._task_semaphore = threading.Semaphore(max_custom_workers)
self._custom_executor = _CustomCommandExecutor(max_custom_workers)
# Inbound/outbound event listeners (see add_message_listener and
# add_file_listener). They run on the thread performing the relevant
# I/O; a listener must not block and its exceptions are swallowed by
# the notify helpers.
self._message_listeners = []
self._file_listeners = []
self._send_message_listeners = []
# Set by stop(); a stopped instance never invokes a listener again.
self._listeners_stopped = False
# Sockets carrying the control protocol; only these are recorded.
self._control_sockets = set()
self._event_listeners_lock = threading.Lock()
# Message/event stores: external code reads these instead of registering
# listeners. Keyed by the socket; each value is a list of [content,
# timestamp] pairs. messages_dict and sent_messages_dict hold plain text
# (inbound / outbound); events_dict and sent_events_dict hold "/" commands.
# When a store's total size reaches max_dict_size (64 KiB) it is flushed
# to its JSON log and cleared (see _append_record, _flush_record_stores).
self.messages_dict = {}
self.events_dict = {}
self.sent_messages_dict = {}
self.sent_events_dict = {}
self._messages_dict_lock = threading.Lock()
self._events_dict_lock = threading.Lock()
self._sent_messages_dict_lock = threading.Lock()
self._sent_events_dict_lock = threading.Lock()
self._socket_keys = {} # record key -> "ip:port", captured while it was alive
self._socket_keys_lock = threading.Lock()
self._messages_dict_size = 0
self._events_dict_size = 0
self._sent_messages_dict_size = 0
self._sent_events_dict_size = 0
self.max_dict_size = 64 * 1024
self.messages_log_file = os.path.join(self.project_info_dir, "messages_log.json")
self.events_log_file = os.path.join(self.project_info_dir, "events_log.json")
self.sent_messages_log_file = os.path.join(self.project_info_dir, "sent_messages_log.json")
self.sent_events_log_file = os.path.join(self.project_info_dir, "sent_events_log.json")
self.is_extend_command = is_extend_command
self.is_enable_encrypto = is_enable_encrypto
self.is_custom_keys = is_custom_keys
self.is_asynic_clients_io = is_asynic_clients_io
self.is_debug = is_debug
self.is_print_log = is_print_log
self._async_loop = None # event loop driving the client coroutines (asynic clients io only)
self._async_wakeup = None # future `stop` completes to release the async accept loop
self._crypto_lock = threading.RLock() # serialises the crypto collections below (no-GIL safe); held only around short ops, never across I/O
self._encrypted_sockets = set() # sockets currently speaking frames (see _SecureChannel)
self._channels = {} # socket -> _SecureChannel (control and transfer connections)
self._crypto_sessions = {} # client_address -> _CryptoSession (shared by a session's sockets)
self._crypto_peer = {} # socket -> (peer_role, peer_pem_path)
self._crypto_send_locks = {} # socket -> Lock: wire order must match seq allocation order
self._crypto_state = {} # client_address -> crypto handshake state
self._crypto_sock_addr = {} # socket -> client_address
self._crypto_push_active = set() # sockets with an in-flight key push
self.crypto = (
rsa_crypto.RsaCrypto("server", self.project_dir, custom_keys=is_custom_keys)
if is_enable_encrypto
else None
)
if self.is_extend_command:
pass
else:
self.start_TCP_Server()

def _log(self, *parts):
"""Print a command/result line, unless ``is_print_log`` is False.

Args:
*parts (Any): Values forwarded to ``print``.
"""
_log_line(self.is_print_log, parts)

def _debug(self, *parts):
"""Print an execution-process line; needs ``is_print_log`` and ``is_debug``.

Args:
*parts (Any): Values forwarded to ``print``.
"""
_debug_line(self.is_print_log, self.is_debug, parts)

def _log_exc(self):
"""Print the traceback of the exception being handled, in debug mode only."""
if self.is_print_log and self.is_debug:
traceback.print_exc()

def _measure_network_speed(self, payload, is_upload):
"""Fold just-sent/received traffic into the real-time speed estimate.

Every send and receive sample feeds this — control messages, file data
and relay traffic alike — so the speed attributes describe the
instance's current traffic as a rolling average over
``NETWORK_SPEED_WINDOW`` seconds.

Args:
payload (bytes | str | int): Bytes just written or read; a str counts as its UTF-8 length, an int is a byte count already.
is_upload (bool): True for sent bytes (``upload_network_speed``), False for received ones (``recv_network_speed``).

Returns:
float | None: The refreshed speed in bytes per second, or None when
``is_enable_real_time_network_speed`` is False; both speed
attributes are None then.
"""
if not self.is_enable_real_time_network_speed:
self.upload_network_speed = None
self.recv_network_speed = None
return None
if isinstance(payload, str):
byte_count = len(payload.encode("utf-8"))
elif isinstance(payload, int):
byte_count = payload
else:
byte_count = len(payload)
if not byte_count:
return None
now = time.monotonic()
with self._network_speed_lock:
if is_upload:
samples = self._upload_speed_samples
total = self._upload_speed_total + byte_count
else:
samples = self._recv_speed_samples
total = self._recv_speed_total + byte_count
samples.append((now, byte_count))
cutoff = now - NETWORK_SPEED_WINDOW
while samples[0][0] < cutoff: # only the current window counts
total -= samples.popleft()[1]
if is_upload:
self._upload_speed_total = total
else:
self._recv_speed_total = total
span = now - samples[0][0]
if span < NETWORK_SPEED_MIN_SPAN: # a single burst is not extrapolated
span = NETWORK_SPEED_MIN_SPAN
speed = total / span
if is_upload:
self.upload_network_speed = speed
else:
self.recv_network_speed = speed
return speed

def _file_progress_start(self, progress_dict, fid, total_bytes, path, peer=None, initial=0):
"""Register one file transfer in a progress store.

Args:
progress_dict (dict): ``self.file_recv_progress`` for an inbound transfer, ``self.file_upload_progress`` for an outbound one.
fid (int | tuple | None): Receive fid or upload ``(receiver, fid)`` key; None tracks no progress.
total_bytes (int): Size of the file being transferred.
path (str): Local path of the file: the source of an outbound transfer, the file being written for an inbound one.
peer (tuple | None): ``(ip, port)`` of the transfer's original peer — the sender for an inbound transfer, the receiver for an outbound one. A forwarded transfer stores the original peer on both sides, never the relay; None marks a leg that cannot be resumed (there is no peer to continue it with).
initial (int): Bytes already transferred when the leg starts; a resumed transfer continues a partially transferred file.

Returns:
list | None: The ``[transferred, total, speed, path, peer]`` entry
the transfer updates, or None when tracking is off
(``is_enable_file_transfer_progress_bar`` False, or no fid).
"""
if fid is None or not self.is_enable_file_transfer_progress_bar:
return None
entry = [initial, total_bytes, None, path, _peer_from_json(peer) if peer else None]
progress_dict[fid] = entry
with self._transfer_progress_lock:
self._active_transfer_fids.add(fid)
return entry

def _file_progress_update(self, entry, byte_count, is_upload):
"""Fold one transferred chunk into a progress entry.

Args:
entry (list | None): Entry from `_file_progress_start`, or None when the transfer is not tracked.
byte_count (int): Bytes of the chunk just sent or received.
is_upload (bool): True for sent chunks, False for received ones. The speed slot mirrors the live measurement, so it stays None while ``is_enable_real_time_network_speed`` is False.
"""
if entry is None:
return
entry[0] += byte_count
entry[2] = self.upload_network_speed if is_upload else self.recv_network_speed

def _file_progress_finish(self, progress_dict, fid, entry, keep=False):
"""Drop a finished transfer's progress entry, or keep it for a resume.

A resumed leg can replace an older session under the same scoped key.
Only the entry's owner is removed. ``keep`` preserves an interrupted
entry and its partial file for the next reconnect.

Args:
progress_dict (dict): Store the entry belongs to.
fid (int | tuple | None): Receive fid or upload ``(receiver, fid)`` key.
entry (list | None): Entry to drop; None tracks nothing.
keep (bool): Keep the entry (and persist the stores) instead of dropping it. Defaults to False.
"""
if entry is None:
return
with self._transfer_progress_lock:
if progress_dict.get(fid) is entry:
# a leg of an earlier session may finish after a newer leg
# took the fid over: only the owner releases it
self._active_transfer_fids.discard(fid)
if keep:
entry[2] = None # a stopped transfer has no live speed any more
self._persist_transfer_progress()
return
if progress_dict.get(fid) is entry:
del progress_dict[fid]
if os.path.exists(self.file_trans_progress_file):
# the persisted stores are only kept up to date while they exist:
# a transfer that ended must not be resumed on a later reconnect
self._persist_transfer_progress()

def _register_fid_route(self, fid, originator, targets, completed=(), *, receive_record=None):
"""Publish a route for a free FID (restore) or its exact receive reservation."""
targets = {tuple(target): child for target, child in targets.items()}
completed = {tuple(target) for target in completed}
route = {"originator": tuple(originator), "targets": targets, "completed": completed}
upstream_leg_keys = {(target, fid) for target in targets}
with self._transfer_progress_lock:
if self._receive_transfers.get(fid) is not receive_record:
return None
active_collision = (
fid in self._active_transfer_fids
or fid in self._active_transfer_sockets
or any(key in self._active_transfer_fids for key in upstream_leg_keys)
or any(key in self._active_transfer_sockets for key in upstream_leg_keys)
)
with self._transfer_pause_cond:
control_collision = any(
leg_fid == fid and isinstance(state["owner"], socket.socket)
and state["owner"].fileno() >= 0 and (
role == 0 and (peer, fid) in upstream_leg_keys
or role == 1 and peer == tuple(originator)
)
for (peer, leg_fid, kind, role), state in self._transfer_controls._legs.items()
)
with self._forward_relays_lock:
if (
not targets
or not completed.issubset(targets)
or fid in self._fid_routes
or fid in self.file_recv_progress
or any(key in self.file_upload_progress for key in upstream_leg_keys)
or active_collision
or control_collision
or any(key in self._forward_relays for key in upstream_leg_keys)
or any(key in self._fid_route_index for key in upstream_leg_keys)
or any(
(target, child) in self._fid_route_index
for target, child in targets.items() if target not in completed
)
):
return None
if receive_record is not None and (
any(key in self._forward_relays for key in targets.items())
or any(leg["fid"] == fid for leg in self._forward_relays.values())
):
return None
self._fid_routes[fid] = route
for target, child in targets.items():
if target not in completed:
self._fid_route_index[(target, child)] = fid
return route

def _admit_new_relay(self, relay, control_socket, originator, target_fids):
"""Reserve the upstream FID before making the new relay discoverable."""
fid = relay["fid"]
with self._transfer_progress_lock:
# Unlike recovery, a new relay must not adopt an ordinary resume
# request even if it came from the same control socket.
if fid in self._receive_transfers:
return None
record = _claim_receive(self, fid, control_socket, owner=relay)
if record is None:
return None
try:
relay["route"] = self._register_fid_route(
fid, originator, target_fids, receive_record=record
)
finally:
if relay["route"] is None:
_release_receive(self, fid, record)
if relay["route"] is None:
return None
with self._forward_relays_lock:
for key in target_fids.items():
self._forward_relays[key] = relay
return record

def _lookup_fid_route(self, peer, fid):
"""Find a local upstream or an exactly scoped downstream relay leg."""
with self._forward_relays_lock:
upstream = fid if peer is None else self._fid_route_index.get((tuple(peer), fid))
route = self._fid_routes.get(upstream)
return (upstream, route) if route is not None else None

def _drop_fid_route(self, fid, route):
"""Drop only the owning route and its derived downstream indexes."""
with self._forward_relays_lock:
if self._fid_routes.get(fid) is not route:
return False
del self._fid_routes[fid]
self._relay_recoveries.pop(fid, None)
for target, child in route["targets"].items():
key = (target, child)
if self._fid_route_index.get(key) == fid:
del self._fid_route_index[key]
if os.path.exists(self.file_trans_progress_file):
self._persist_transfer_progress()
return True

def _complete_fid_target(self, fid, route, target, child_fid):
"""Accept one final ACK without releasing any other target's identity."""
target = tuple(target)
with self._forward_relays_lock:
if (self._fid_routes.get(fid) is not route
or route["targets"].get(target) != child_fid
or target in route["completed"]
or self._fid_route_index.get((target, child_fid)) != fid):
return False
route["completed"].add(target)
del self._fid_route_index[(target, child_fid)]
self._persist_transfer_progress()
return True


def _transfer_progress_snapshot(self):
"""Return the JSON-ready form of every transfer still in play.

Returns:
dict: ``{"upload": ..., "download": ..., "relays": ...}``; fids
are string keys and every peer is an ``[ip, port]`` list.
"""

def entries(store):
"""Handle the operation.

Args:
store (list | dict): Value used by the operation.

Returns:
list | tuple: Result produced by the operation.
"""
return {
(json.dumps(fid, separators=(",", ":"))
if store is self.file_upload_progress else str(fid)): [
entry[0],
entry[1],
entry[2],
entry[3],
list(entry[4]) if entry[4] else None,
]
for fid, entry in list(store.items())
}

with self._forward_relays_lock:
relays = {
str(key): {
"originator": list(route["originator"]),
"targets": [[list(target), child] for target, child in route["targets"].items()],
"completed": [list(target) for target in sorted(route["completed"])],
}
for key, route in self._fid_routes.items()
}
return {
"upload": entries(self.file_upload_progress),
"download": entries(self.file_recv_progress),
"relays": relays,
}

def get_transfer_progress(self, *, include_persisted=True) -> dict:
"""Return a detached, local-only view of all retained transfer records.

Args:
include_persisted (bool): Read this instance's progress file too.
Defaults to True; never loads it into the live stores.

Returns:
dict: Flags, scoped memory rows and a separate persisted snapshot
with its path, read status and error. Disk runtime flags are
unknown (None). No completion or zombie status is inferred.
"""
return _get_transfer_progress(self, include_persisted=include_persisted, server_routes=True)

def delete_config(self, config_name=None, *, is_list_config=False) -> bool | list[str]:
"""List or delete a named local progress snapshot or message/event log.

Args:
config_name (str | None): Allowed file basename, not a path.
is_list_config (bool): Only list existing regular files, ignoring
config_name. Defaults to False; listing is allowed while running.

Returns:
bool | list[str]: Sorted file names in list mode; otherwise True
when deleted, False when absent. Discarding progress permanently
disables this object's reload/write/start; create a new instance.

Raises:
ValueError: Invalid/ambiguous name, directory or symlink.
TypeError: A deletion name is not a string.
RuntimeError: Instance not closed, operations active or logs buffered.
OSError: The filesystem refuses inspection or deletion.
"""
return _delete_config(self, config_name, is_list_config=is_list_config)

def _persist_transfer_progress(self):
"""Write the transfer stores to the protocol's ``.Flow`` directory.

Every in-flight transfer — uploads, downloads, and the relay records a
disconnected forward is resumed from — is written to
``server_file_trans_progress.json`` when a connection drops, and the
file is what the reconnect logic reads back. Once nothing is left to
transfer the file is emptied; it is only rewritten while it exists, so
a run without an interrupted transfer never creates it. A write
failure is logged, never raised.
"""
with self._transfer_progress_lock:
if self._progress_discarded:
return
snapshot = self._transfer_progress_snapshot()
if not any(snapshot.values()) and not os.path.exists(self.file_trans_progress_file):
return
tmp_path = f"{self.file_trans_progress_file}.{os.getpid()}.tmp"
try:
if os.path.exists(self.file_trans_progress_file):
_read_transfer_progress(self.file_trans_progress_file, server_routes=True)
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(snapshot, f, ensure_ascii=False, indent=2)
os.replace(tmp_path, self.file_trans_progress_file)
except (OSError, ValueError) as e:
self._log(f"transfer progress file update failed: {e}")
try:
os.remove(tmp_path)
except OSError:
pass

def _load_transfer_progress(self):
"""Read the persisted interrupted transfers back into the stores.

Every entry read back keeps the bytes it had already transferred, so
the reconnect logic can ask the sender to continue from there; every
relay record comes back so a disconnected forward can be routed again.
Entries a live transfer (or a relay) already owns are left alone.

Returns:
int: Number of transfer entries and relay records restored.
"""
with self._transfer_progress_lock:
if self._progress_discarded:
return 0
try:
data = _read_transfer_progress(self.file_trans_progress_file, server_routes=True)
except FileNotFoundError:
return 0
except (OSError, ValueError) as e:
self._log(f"transfer progress file unreadable ({e}), ignored")
return 0
if not isinstance(data, dict):
return 0
restored = 0
for key_text, record in (data.get("relays") or {}).items():
try:
fid = int(key_text)
targets = {tuple(target): child for target, child in record["targets"]}
except (TypeError, ValueError, KeyError):
continue
if self._register_fid_route(
fid, record["originator"], targets, record.get("completed", ())
) is not None:
restored += 1
for key, store in (
("download", self.file_recv_progress),
("upload", self.file_upload_progress),
):
for fid_text, row in (data.get(key) or {}).items():
try:
fid = int(fid_text) if key == "download" else json.loads(fid_text)
if key == "upload":
fid = (_peer_from_json(fid[0]), int(fid[1]))
if fid[0] is None:
continue
entry = [int(row[0]), int(row[1]), None, row[3], _peer_from_json(row[4])]
except (TypeError, ValueError, IndexError, KeyError):
continue
routed = self._lookup_fid_route(None if key == "download" else fid[0],
fid if key == "download" else fid[1])
if fid in store or routed is not None:
continue # preserve live progress and route-owned legs
store[fid] = entry
restored += 1
return restored


def pause_trans(self, fid, peer, *, trans_type, direction):
"""Request an ordinary leg pause or a Source-arbitrated relay-wide pause.

Args:
fid (int): Nonnegative transfer id.
peer (tuple): Control peer, required even for a preset sender pause.
trans_type (int): 0 ordinary, 1 forwarded.
direction (int): Local data role: 0 sender, 1 receiver.

Returns:
bool: Operation registered, not peer confirmation. Relay operations
are requests to Source; buffered bytes continue to all Targets.
A missing sender leg retains a preset pause and returns False.

Raises:
ValueError: Invalid fid/type/direction or missing peer.
"""
return _set_transfer_control(self, fid, peer, trans_type, direction, True)

def start_trans(self, fid, peer, *, trans_type, direction):
"""Continue the ordinary leg or whole relay on its existing data sockets.

Arguments and registration result match ``pause_trans``. No seek,
truncation or new handshake occurs; receivers continue reading throughout.
"""
return _set_transfer_control(self, fid, peer, trans_type, direction, False)

def _register_transfer_socket(self, fid, sock):
"""Record the socket of a leg, so a dead session can be cleared out.

Args:
fid (int | tuple): Receive fid or outgoing ``(receiver, fid)`` key.
sock (object): Value used by the operation.
"""
if fid is None:
return
with self._transfer_progress_lock:
self._active_transfer_sockets[fid] = sock

def _release_transfer_socket(self, fid, sock):
"""Forget a leg's socket once the leg is over (its own, not a newer one's).

Args:
fid (int | tuple): Receive fid or outgoing ``(receiver, fid)`` key.
sock (object): Value used by the operation.
"""
self._transfer_controls.release_owner(sock)
if fid is None:
return
with self._transfer_progress_changed:
if self._active_transfer_sockets.get(fid) is sock:
del self._active_transfer_sockets[fid]
self._active_transfer_fids.discard(fid)
record = self._receive_transfers.get(fid)
if record is not None and record["owner"] is sock:
del self._receive_transfers[fid]
self._transfer_progress_changed.notify_all()


def _wait_control_secure(self, control_socket, timeout=RESUME_SECURE_TIMEOUT):
"""Wait until a control channel may carry framed protocol lines.

A reconnect may precede the end of the handshake. Wait before issuing
the request; the writer still enforces framing if rekey begins later.

Args:
control_socket (socket.socket): Value used by the operation.
timeout (float): Value used by the operation.

Returns:
bool: True when the channel speaks frames (or encryption is off).
"""
if not self.is_enable_encrypto or self.crypto is None:
return True
deadline = time.time() + timeout
while time.time() < deadline:
if not self.running or control_socket.fileno() < 0:
return False
with self._crypto_lock:
channel = self._channels.get(control_socket)
if channel is not None and channel.secure and channel.frames_allowed.is_set():
return True
time.sleep(0.05)
self._log("control channel not framed yet; transfer control was not sent")
return False

def alloc_port(self, port_add_step, port_range_num):
"""Reserve this server's port range under the cross-process lock.

No-op unless ``is_hand_alloc_port`` is True.

Args:
port_add_step (int): Step between candidate ports.
port_range_num (int): Number of ports per step.
"""
if self.is_hand_alloc_port == True:
while self.is_server_port_temp_info_file_locked():
time.sleep(0.1)
self.server_port_temp_info_file_lock()
try:
self.hand_alloc_port(port_add_step, port_range_num)
finally:
# a failing allocation must not leave the lock behind: every
# later instance would wait for it forever
self.server_port_temp_info_file_unlock()

def free_port(self):
"""Release this server's reserved port range.

No-op unless ``is_hand_alloc_port`` is True.
"""
if self.is_hand_alloc_port == True:
while self.is_server_port_temp_info_file_locked():
time.sleep(0.1)
self.server_port_temp_info_file_lock()
try:
self.hand_free_port()
finally:
self.server_port_temp_info_file_unlock()

def server_port_temp_info_file_lock(self):
"""Create the lock file that reserves the server port range for this process."""
with open(self.server_port_lock_file, "w", encoding="utf-8") as f:
f.write("locked")

def is_server_port_temp_info_file_locked(self):
"""Report whether the server port range is reserved by some process.

Returns:
bool: True while the lock file exists.
"""
if os.path.exists(self.server_port_lock_file):
return True
else:
return False

def server_port_temp_info_file_unlock(self):
"""Remove the lock file that reserves the server port range."""
if os.path.exists(self.server_port_lock_file):
os.remove(self.server_port_lock_file)

def hand_alloc_port(self, port_add_step, port_range_num):
"""Allocate the next free server port range and record it on disk.

``port`` is moved past the ranges already recorded by other servers, so the
instance ends up with a range of its own.

Args:
port_add_step (int): Step between candidate ports.
port_range_num (int): Number of ports per step.

Raises:
OSError: If the server port info file cannot be read or written.
"""
self.port_temp_info_path = os.path.join(self.project_temp_info_dir, "server_port_info.log")
client_port_temp_info_file_path = os.path.join(
self.project_temp_info_dir, "clients_port_info.log"
)
if os.path.exists(client_port_temp_info_file_path):
self._log(
"Warning: client port info file exists, means the client has already allocated a port, may cause port conflict!"
)
self.port_add_step = port_add_step
self.port_range_num = port_range_num
self.add_latest_port = self.port + 1
self.minus_latest_port = self.port
self.alloc_add_port_lock = threading.Lock()
self.alloc_minus_port_lock = threading.Lock()
self.each_client_port_range = int(self.port_range_num / self.max_clients)
if os.path.exists(self.port_temp_info_path) == False:
self.server_num = 0
self.server_port_info = []
self.min_port = self.port - self.port_add_step * self.port_range_num
self.max_port = self.port + 1 + self.port_add_step * self.port_range_num
each_server_info = {
"server_id": self.server_num,
"host": self.host,
"port": self.port,
"min_port": self.min_port,
"max_port": self.max_port,
"is_running": True,
"pid": os.getpid(), # the sweep reclaims the range once it is gone
"started_at": time.time(),
}
self.server_port_info.append(each_server_info)
with open(self.port_temp_info_path, "w", encoding="utf-8") as f:
f.write(str(self.server_port_info))
else:
with open(self.port_temp_info_path, "r", encoding="utf-8") as f:
self.server_port_info = ast.literal_eval(f.read())
# drop the entries whose owning process is gone: a killed instance
# never reaches hand_free_port, and its range is free again
self.server_port_info = [
entry for entry in self.server_port_info if not _port_record_stale(entry)
]
if not self.server_port_info: # nobody holds a range: start over
os.remove(self.port_temp_info_path)
self.hand_alloc_port(port_add_step, port_range_num)
return
self.server_num = self.server_port_info[len(self.server_port_info) - 1]["server_id"] + 1
auto_port_add = (
self.server_port_info[len(self.server_port_info) - 1]["max_port"]
+ self.port_add_step * self.port_range_num
+ 1
)
auto_port_minus = (
self.server_port_info[len(self.server_port_info) - 1]["min_port"]
- self.port_add_step * self.port_range_num
- 1
)
if self.port > auto_port_minus and self.port < auto_port_add:
self.port = auto_port_add
self.min_port = self.port - self.port_add_step * self.port_range_num
self.max_port = self.port + 1 + self.port_add_step * self.port_range_num
each_server_info = {
"server_id": self.server_num,
"host": self.host,
"port": self.port,
"min_port": self.min_port,
"max_port": self.max_port,
# this instance is live while it holds the range: hand_free_port()
# drops the entry on a clean stop, and the pid lets a later
# instance reclaim the range of one that was killed
"is_running": True,
"pid": os.getpid(),
"started_at": time.time(),
}
self.server_port_info.append(each_server_info)
with open(self.port_temp_info_path, "w", encoding="utf-8") as f:
f.write(str(self.server_port_info))

def hand_free_port(self):
"""Drop this server's entry from the on-disk port range record."""
self.port_temp_info_path = os.path.join(self.project_temp_info_dir, "server_port_info.log")
if os.path.exists(self.port_temp_info_path):
with open(self.port_temp_info_path, "r", encoding="utf-8") as f:
self.server_port_info = ast.literal_eval(f.read())
# rebuild instead of deleting by index: other live instances keep
# their entries, so this one is not necessarily the last, and a
# shrinking list would make the next index run past its end
self.server_port_info = [
entry for entry in self.server_port_info if entry["server_id"] != self.server_num
]
if len(self.server_port_info) == 0:
os.remove(self.port_temp_info_path)
else:
with open(self.port_temp_info_path, "w", encoding="utf-8") as f:
f.write(str(self.server_port_info))

def palloc(self):
"""Allocate a transfer port, waiting until one is free.

Returns:
int: Allocated port, or 0 when allocation is disabled
(``is_hand_alloc_port`` False).
"""
alloc_port = 0
while True:
alloc_port = self.file_palloc()
if alloc_port is not None:
return alloc_port
alloc_port = self.spy_palloc()
if alloc_port is not None:
return alloc_port
# both directions are exhausted: wait for a port to come back
time.sleep(0.1)

def pfree(self, port):
"""Release a port obtained from `palloc`.

Args:
port (int): Port to release.
"""
self.file_pfree(port)
self.spy_pfree(port)

def file_palloc(self):
"""Allocate the next port above the base, or the first free one in range.

Returns:
int: Allocated port; None when the upward range is exhausted; 0 when
allocation is disabled (``is_hand_alloc_port`` False).
"""
if self.is_hand_alloc_port:
with self.alloc_add_port_lock:
if self.add_latest_port + self.port_add_step > self.max_port:
for step in range(self.port + 1, self.max_port, self.port_add_step):
if step in self.all_allocated_ports_list:
pass
else:
allocated_port = step
self.all_allocated_ports_list.append(allocated_port)
return allocated_port
return None
self.add_latest_port += self.port_add_step
self.all_allocated_ports_list.append(self.add_latest_port)
return self.add_latest_port
else:
return 0

def file_pfree(self, port):
"""Release a port obtained from `file_palloc` and step the cursor back.

Args:
port (int): Port to release. Ignored when allocation is disabled.
"""
if self.is_hand_alloc_port:
with self.alloc_add_port_lock:
if port in self.all_allocated_ports_list:
self.all_allocated_ports_list.remove(port)
self._debug("releasing file transfer port, current latest port:", port)
self.add_latest_port -= self.port_add_step
else:
pass

def spy_palloc(self):
"""Allocate the next port below the base, or the first free one in range.

Returns:
int: Allocated port; None when the downward range is exhausted; 0 when
allocation is disabled (``is_hand_alloc_port`` False).
"""
if self.is_hand_alloc_port:
with self.alloc_minus_port_lock:
if self.minus_latest_port - self.port_add_step < self.min_port:
for step in range(self.port, self.min_port, -self.port_add_step):
if step in self.all_allocated_ports_list:
pass
else:
allocated_port = step
self.all_allocated_ports_list.append(allocated_port)
return allocated_port
return None
self.minus_latest_port -= self.port_add_step
self.all_allocated_ports_list.append(self.minus_latest_port)
return self.minus_latest_port
else:
return 0

def spy_pfree(self, port):
"""Release a port obtained from `spy_palloc` and step the cursor back.

Args:
port (int): Port to release. Ignored when allocation is disabled.
"""
if self.is_hand_alloc_port:
with self.alloc_minus_port_lock:
if port in self.all_allocated_ports_list:
self.all_allocated_ports_list.remove(port)
self.minus_latest_port += self.port_add_step
else:
pass

def register_command(self, command_name, handler, where_to_run, run_in_thread=False):
"""Register a custom command handler.

Args:
command_name (str): Command to intercept, e.g. "/my_command"; matched
case-insensitively against the first token.
handler (callable): ``handler(client_socket, client_address, command)``
called with the raw line; a non-None return value is sent back to
the sender as the response.
where_to_run (str): "server" for commands arriving from clients,
"client" for commands typed on this instance's console.
run_in_thread (bool): Run the handler on the worker pool instead of the
reader thread. Defaults to False.

Returns:
bool | None: False when ``where_to_run`` is neither "server" nor
"client"; the handler is then not registered.
"""
registe_index = None
if where_to_run == "server":
registe_index = 0
elif where_to_run == "client":
registe_index = 1
else:
self._log(f"Invalid where_to_run value: {where_to_run}, must be 'server' or 'client'")
return False
self._custom_handlers[registe_index][command_name] = handler
self._custom_handler_threaded[registe_index][command_name] = run_in_thread


def call_extension_functions(self, command):
"""Call one registered extension command handler directly from code.

The handler is selected by the first token of ``command``, matched
case-insensitively against the names given to `register_command`: the
console group is searched first, then the group fed by the lines
clients send. The handler runs on the calling thread — ``run_in_thread``
only affects the console and inbound dispatch paths — and is called
with ``None`` for both ``client_socket`` and ``client_address``, since
a direct call names no peer.

Args:
command (str): Command line to run, e.g. ``"/my_command arg"``; the
handler receives it unchanged.

Returns:
object: Whatever the handler returns.

Raises:
CommandNotFoundError: If no registered handler matches the first
token of ``command``.
ValueError: If ``command`` cannot be split (unbalanced quotes).
"""
handler = _custom_handler_for(command, self._custom_handlers)
return handler(None, None, command)

def add_message_listener(self, listener):
"""Register ``listener(client_id, message)`` for inbound events.

Complete control lines are reported as ``str`` (commands and crypto
handshake lines included); raw chunks from a non-control socket
(file/folder transfer, forwarding, temporary connection) are reported
as ``bytes`` without line or frame alignment. ``client_id`` is the peer
endpoint of the socket that produced the event, so a side-channel event
names that temporary TCP connection, not the control client.

Control-line callbacks run on the receive thread (synchronous server)
or the ``asyncio.to_thread`` worker (asynchronous server); raw chunks
run on the thread reading that socket. Callbacks may run concurrently
and must be thread-safe, must not block, and exceptions raised inside
them are swallowed. ``stop()`` stops new delivery and clears the list.

Args:
listener (callable): ``listener(client_id, message)``.
"""
with self._event_listeners_lock:
if listener not in self._message_listeners:
self._message_listeners.append(listener)

def remove_message_listener(self, listener):
"""Unregister a listener previously added by `add_message_listener`.

Args:
listener (callable): Listener to remove; an unknown one is ignored.
"""
with self._event_listeners_lock:
try:
self._message_listeners.remove(listener)
except ValueError:
pass

def add_send_message_listener(self, listener):
"""Register ``listener(target_id, message)`` for successful sends.

Called synchronously on the sending thread after every payload that
`send_message` writes successfully, for ``str`` and ``bytes`` alike.
``str`` payloads are stripped; ``bytes`` are reported unchanged.
``target_id`` is the peer endpoint of the socket that wrote the
payload: the client's ``"ip:port"`` for a control socket, or the
temporary TCP connection's ``"ip:port"`` for a side channel.

``is_send_raw=True`` lines and internal protocol frames such as the
ECDH public-key publication are not reported. When several threads
send on one socket the writes stay serialized, but callback order is
not guaranteed to match wire order; this affects observation only.
The listener must not block, may run concurrently, and its exceptions
are swallowed. ``stop()`` stops new delivery.

Args:
listener (callable): ``listener(target_id, message)``.
"""
with self._event_listeners_lock:
if listener not in self._send_message_listeners:
self._send_message_listeners.append(listener)

def remove_send_message_listener(self, listener):
"""Unregister a listener previously added by `add_send_message_listener`.

Args:
listener (callable): Listener to remove; an unknown one is ignored.
"""
with self._event_listeners_lock:
try:
self._send_message_listeners.remove(listener)
except ValueError:
pass

def add_file_listener(self, listener):
"""Register ``listener(client_id, full_path, name, size, command)`` per saved file.

Fired once after a file uploaded by a client (a direct send or a
forwarded item staged on the server) is fully written to its
destination. ``client_id`` is the uploader's control-connection
``"ip:port"``; ``command`` is the wire command that triggered the
transfer, so pushes such as ``/crypto_pub_key`` can be recognised. The
callback runs on the transfer thread before the completion sign is sent
(it does not wait for an ACK); per-chunk data goes to the message
listeners as ``bytes`` instead. For ``/crypto_pub_key`` the key is not
registered yet, so the listener must not move or delete the file. It
must not block; exceptions are swallowed. ``stop()`` stops new delivery.

Args:
listener (callable): ``listener(client_id, full_path, name, size,
command)``.
"""
with self._event_listeners_lock:
if listener not in self._file_listeners:
self._file_listeners.append(listener)

def remove_file_listener(self, listener):
"""Unregister a listener previously added by `add_file_listener`.

Args:
listener (callable): Listener to remove; an unknown one is ignored.
"""
with self._event_listeners_lock:
try:
self._file_listeners.remove(listener)
except ValueError:
pass

def _stop_listeners(self):
"""Stop delivering listener events and release the callback lists."""
with self._event_listeners_lock:
self._listeners_stopped = True
self._message_listeners.clear()
self._file_listeners.clear()
self._send_message_listeners.clear()

def _listeners_are_stopped(self):
"""Return True once stop() has disabled listener delivery."""
with self._event_listeners_lock:
return self._listeners_stopped

def _notify_message_received(self, client_id, message):
"""Handle the operation.

Args:
client_id (object): Value used by the operation.
message (object): Value used by the operation.
"""
with self._event_listeners_lock:
if self._listeners_stopped:
return
listeners = list(self._message_listeners)
for listener in listeners:
if self._listeners_are_stopped():
return
try:
listener(client_id, message)
except Exception as e:
self._log(f"message listener error: {e}")
self._log_exc()

def _notify_transfer_chunk(self, client_socket, data):
"""Report one chunk read from a non-control socket to the message listeners.

Side-channel sockets (file/folder transfers, forwards) carry raw bytes and
``sign`` tokens, which belong to the transfer layer, so they are reported
to the listeners but never recorded in a store.
"""
if not data or client_socket in self._control_sockets:
return
with self._event_listeners_lock:
if self._listeners_stopped:
return
listeners = list(self._message_listeners)
for listener in listeners:
if self._listeners_are_stopped():
return
try:
listener(self._socket_key(client_socket), data)
except Exception as e:
self._log(f"message listener error: {e}")
self._log_exc()

def _notify_message_sent(self, client_socket, message):
"""Report one written payload to the send listeners."""
with self._event_listeners_lock:
if self._listeners_stopped:
return
listeners = list(self._send_message_listeners)
if not listeners:
return
target_id = self._socket_key(client_socket)
for listener in listeners:
if self._listeners_are_stopped():
return
try:
listener(target_id, message)
except Exception as e:
self._log(f"send message listener error: {e}")
self._log_exc()

def _notify_file_received(self, client_id, full_path, name, size, command):
"""Handle the operation.

Args:
client_id (object): Value used by the operation.
full_path (str): Value used by the operation.
name (object): Value used by the operation.
size (int): Value used by the operation.
command (object): Value used by the operation.
"""
with self._event_listeners_lock:
if self._listeners_stopped:
return
listeners = list(self._file_listeners)
for listener in listeners:
if self._listeners_are_stopped():
return
try:
listener(client_id, full_path, name, size, command)
except Exception as e:
self._log(f"file listener error: {e}")
self._log_exc()

def _socket_key(self, sock):
"""Serializable key for a sender socket (its peer address).

Forwarded records already carry the originator's address as a
string and are used as-is; a socket that cannot answer
``getpeername`` (already closed) falls back to its repr.

Args:
sock (object): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
if isinstance(sock, str):
return sock
try:
ip, port = sock.getpeername()[:2]
return f"{ip}:{port}"
except Exception:
return str(sock)

def _remember_socket_key(self, sock):
"""Capture the log key of ``sock`` while it is known to be alive.

A record stays buffered after its connection goes away, and the
flush that persists it must still file it under the sender's
address: by then the closed socket no longer answers
``getpeername`` and would be logged as ``str(sock)``. The key is
forgotten once nothing is buffered under it any more (see
``_flush_dict_locked``).

Args:
sock (object): Value used by the operation.
"""
with self._socket_keys_lock:
if sock not in self._socket_keys:
self._socket_keys[sock] = self._socket_key(sock)

def _record_key(self, sock):
"""Return the JSON-log key for ``sock``: the address captured when it was.

The JSON-log key for ``sock``: the address captured when it was

recorded, or the live peer address for a socket inserted without a
record.

Args:
sock (object): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
key = self._socket_keys.get(sock)
if key is not None:
return key
return self._socket_key(sock)

def _append_record(self, store, log_path, sock, content):
"""Append one ``[content, timestamp]`` pair under ``sock``; flush when full.

Args:
store (tuple): ``(dict, lock, size_attr)``; the dict maps socket to
a list of pairs, and ``size_attr`` names the byte-size attribute.
log_path (str): JSON log the store flushes into.
sock (object): Key socket.
content (str): Text to record.
"""
d, lock, size_attr = store
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with lock:
self._remember_socket_key(sock)
d.setdefault(sock, []).append([content, timestamp])
size = getattr(self, size_attr) + len(content.encode("utf-8", "replace"))
size += len(timestamp)
setattr(self, size_attr, size)
if size >= self.max_dict_size:
self._flush_dict_locked(d, size_attr, log_path)

def _record_message(self, sock, content):
"""Store one inbound plain-text message under the sender's socket."""
self._append_record(
(self.messages_dict, self._messages_dict_lock, "_messages_dict_size"),
self.messages_log_file, sock, content,
)

def _record_event(self, sock, command):
"""Store one inbound "/" command under the sender's socket."""
self._append_record(
(self.events_dict, self._events_dict_lock, "_events_dict_size"),
self.events_log_file, sock, command,
)

def _record_sent(self, sock, content):
"""Store one outbound text: a "/" line as a sent event, other text as a sent message."""
if content.startswith("/"):
self._append_record(
(self.sent_events_dict, self._sent_events_dict_lock, "_sent_events_dict_size"),
self.sent_events_log_file, sock, content,
)
else:
self._append_record(
(
self.sent_messages_dict,
self._sent_messages_dict_lock,
"_sent_messages_dict_size",
),
self.sent_messages_log_file, sock, content,
)

def _update_event_timestamp(self, sock, command, timestamp):
"""Stamp the completion time onto the recorded event for ``command``.

File transfers finish on a worker thread after the receive thread
recorded the command, so the event's timestamp is refreshed here with
the moment the transfer actually completed.

Args:
sock (object): Value used by the operation.
command (object): Value used by the operation.
timestamp (object): Value used by the operation.
"""
with self._events_dict_lock:
entries = self.events_dict.get(sock)
if entries:
for entry in reversed(entries):
if entry[0] == command:
entry[1] = timestamp
return

def _splice_event_command(self, command, **parts):
"""Return the command to record as an event.

The wire command is recorded verbatim whenever it is available. When
this end cannot see the original command (a transfer relayed by the
server, or a protocol-internal control line), splice a readable
command from the available parts so the event still identifies the
transfer.

Args:
command (object): Value used by the operation.
**parts (list | dict): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
if command:
return command
kind = parts.get("kind")
fname = parts.get("fname")
rel_dir = parts.get("rel_dir")
if kind == "folder" and fname:
if rel_dir:
return "/file_folder {} {}".format(shlex.quote(rel_dir), shlex.quote(fname))
return "/file_folder {}".format(shlex.quote(fname))
if fname:
return "/file {}".format(shlex.quote(fname))
return parts.get("fallback") or "/unknown"

def _flush_dict_locked(self, d, size_attr, path):
"""Flush ``d`` (socket -> [[content, ts], ...]) into its JSON log and

clear it. The caller must hold the dict's lock.

Args:
d (list | dict): Value used by the operation.
size_attr (object): Value used by the operation.
path (str): Value used by the operation.
"""
if not d:
return
snapshot = dict(d)
d.clear()
setattr(self, size_attr, 0)
self._merge_json_log(path, snapshot)
with self._socket_keys_lock: # a key is only kept while some store buffers it
for sock in snapshot:
if not any(sock in store for store in self._record_dicts()):
self._socket_keys.pop(sock, None)

def _record_dicts(self):
"""Return the four record stores, in flush order."""
return (
self.messages_dict,
self.events_dict,
self.sent_messages_dict,
self.sent_events_dict,
)

def _flush_messages_dict(self):
"""Flush the inbound messages store into its JSON log."""
with self._messages_dict_lock:
self._flush_dict_locked(
self.messages_dict, "_messages_dict_size", self.messages_log_file
)

def _flush_events_dict(self):
"""Flush the inbound events store into its JSON log."""
with self._events_dict_lock:
self._flush_dict_locked(self.events_dict, "_events_dict_size", self.events_log_file)

def _flush_record_stores(self):
"""Flush every record store into its JSON log (called on stop)."""
with self._messages_dict_lock:
self._flush_dict_locked(
self.messages_dict, "_messages_dict_size", self.messages_log_file
)
with self._events_dict_lock:
self._flush_dict_locked(self.events_dict, "_events_dict_size", self.events_log_file)
with self._sent_messages_dict_lock:
self._flush_dict_locked(
self.sent_messages_dict, "_sent_messages_dict_size", self.sent_messages_log_file
)
with self._sent_events_dict_lock:
self._flush_dict_locked(
self.sent_events_dict, "_sent_events_dict_size", self.sent_events_log_file
)

def _merge_json_log(self, path, snapshot):
"""Merge ``snapshot`` into the JSON log at ``path`` (append per socket).

Publishes through `_publish_json_log`: a temp file named after this
writer, and an optimistic re-merge when another instance published in
between, so concurrent flushes of several instances sharing one log
neither corrupt nor lose each other. A failure is logged, never raised
into the caller.

Args:
path (str): Value used by the operation.
snapshot (list | dict): Value used by the operation.
"""
try:
_publish_json_log(path, snapshot, self._record_key)
except Exception as e:
self._log(f"log file update failed: {e}")
self._log_exc()

def submit_task(self, func, *args, **kwargs):
"""Run a callable on the instance's worker pool.

Args:
func (callable): Callable to run.
*args (Any): Positional arguments forwarded to ``func``.
**kwargs (Any): Keyword arguments forwarded to ``func``.

Returns:
concurrent.futures.Future: Handle for the submitted call; its worker
slot is released when the call finishes.

Raises:
RuntimeError: If terminal shutdown has started, even while waiting for a slot.
"""
self._task_semaphore.acquire()
future = self._custom_executor.submit(func, *args, **kwargs)
future.add_done_callback(lambda f: self._task_semaphore.release())
return future
return self._custom_executor.submit(func, *args, **kwargs)

def create_temporary_server(self, handler, port=None, max_connections=1):
"""Start a temporary listener for a side channel (not the main protocol).

Args:
handler (callable): ``handler(client_socket, address)`` started in its
own thread for every accepted connection.
port (int | None): Port to bind; None allocates one with `palloc`.
max_connections (int): Listen backlog. Defaults to 1.

Returns:
tuple: ``(port, thread, stop_event)``; setting ``stop_event`` ends the
loop, which closes the socket and frees the port.

Raises:
RuntimeError: If ``port`` is None and no port can be allocated.
"""
if port is None:
port = self.palloc()
if port is None:
raise RuntimeError("No available port for temporary server")
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((self.host, port))
server_socket.listen(max_connections)
stop_event = threading.Event()

def server_loop():
"""Handle the operation."""
while not stop_event.is_set():
try:
server_socket.settimeout(1.0)
client_sock, addr = server_socket.accept()
threading.Thread(target=handler, args=(client_sock, addr), daemon=True).start()
except socket.timeout:
continue
except Exception as e:
if not stop_event.is_set():
self._log(f"Temporary server error: {e}")
break
server_socket.close()
self.pfree(port)

server_thread = threading.Thread(target=server_loop, daemon=True)
server_thread.start()
return port, server_thread, stop_event

def create_temporary_client(self, server_host, server_port, bind_port=None, on_data=None):
"""Open a temporary outbound connection for a side channel.

Args:
server_host (str): Host to connect to.
server_port (int): Port to connect to.
bind_port (int | None): Local port to bind; None lets the OS choose.
on_data (callable | None): ``on_data(data, client_socket)`` called for
every received chunk.

Returns:
tuple: ``(client_socket, thread, stop_event)``; setting ``stop_event``
ends the receiver thread.
"""
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if bind_port is not None:
client_sock.bind((self.host, bind_port))
client_sock.connect((server_host, server_port))
stop_event = threading.Event()

def receiver():
"""Handle the operation."""
while not stop_event.is_set():
try:
client_sock.settimeout(1.0)
data = self.receive_message(client_sock, self.recv_messages_chunk_len)
if not data:
break
if on_data:
on_data(data, client_sock)
except socket.timeout:
continue
except:
break
client_sock.close()

recv_thread = threading.Thread(target=receiver, daemon=True)
recv_thread.start()
return client_sock, recv_thread, stop_event

def broadcast(
self, message, exclude_client=None
): # broadcast message to all clients except exclude_client
"""Send one message to every connected client.

Clients whose send fails are disconnected and removed from ``clients``.

Args:
message (str | bytes): Payload passed to `send_message`.
exclude_client (tuple | None): ``(ip, port)`` to leave out, typically
the client the message came from.
"""
with self.client_lock:
targets = [
(addr, client_info["socket"])
for addr, client_info in self.clients.items()
if not (exclude_client and addr == exclude_client)
]
disconnected_clients = []
for addr, client_socket in targets:
try:
self.send_message(client_socket, message)
except:
disconnected_clients.append((addr, client_socket))
self._log_exc()
if disconnected_clients:
with self.client_lock:
for addr, client_socket in disconnected_clients:
client_info = self.clients.get(addr)
if client_info is None or client_info.get("socket") is not client_socket:
continue
self._debug(f"deleting the disconnected client: {addr}")
client_socket.close()
del self.clients[addr]

def send_msg_to_specific_client(
self, message
): # send message to specific client by client address
"""Send the messages of a console line to the clients named in it.

Args:
message (str): ``/send_msg`` line as typed: message text followed by one
or more ``(ip, port)`` identifiers; each message is delivered to the
identifiers that follow it. Addresses that are not connected are
skipped with a console notice.
"""
command_part = shlex.split(message)
del command_part[0]
client_message_pair_list = []
client_list = []
msg_list = []
client_addr_times = 0
for command_part_index in range(len(command_part)):
part = command_part[command_part_index]
if part.startswith("(") and part.endswith(")"):
try:
client_addr = ast.literal_eval(part)
client_list.append(client_addr)
client_addr_times += 1
if command_part_index == len(command_part) - 1:
client_message_pair = [client_list, msg_list]
client_message_pair_list.append(client_message_pair)
except:
self._log_exc()
self._log(
f"ErrorWhileParsingClientAddress: {part} is not a valid client address, skipped"
)
else:
if client_addr_times != 0:
client_message_pair = [client_list, msg_list]
client_message_pair_list.append(client_message_pair)
client_list = []
msg_list = []
msg_list.append(part)
client_addr_times = 0
else:
msg_list.append(part)
for each_client_message_pair in client_message_pair_list:
for client_addr in each_client_message_pair[0]:
for msg in each_client_message_pair[1]:
if client_addr in self.clients:
client_socket = self.clients[client_addr]["socket"]
self.send_message(client_socket, msg)
else:
self._log(f"Client {client_addr} not found, cannot send message: {msg}")

def _crypto_get_send_lock(self, client_socket):
"""Per-socket lock serialising encrypt+send for one connection.

A control socket's `_SecureChannel` shares this exact lock object, so
a frame write can never interleave with a raw write on the same
socket (and vice versa) during the flip.

Args:
client_socket (socket.socket): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
with self._crypto_lock:
lock = self._crypto_send_locks.get(client_socket)
if lock is None:
lock = threading.Lock()
self._crypto_send_locks[client_socket] = lock
return lock

def send_message(self, client_socket, message, is_send_raw=False):
# send message to specific client
"""Write one message to a client socket, framing it when the channel is up.

Args:
client_socket (socket.socket): Target connection.
message (str | bytes): Payload; a str is stripped and newline
terminated, bytes are sent as they are.
is_send_raw (bool): Write the payload as plaintext even when the channel
is encrypted; only for the crypto handshake and transfer coordination lines.

Returns:
bool: True when written; False for an unsupported payload or a transfer
control line with no secure channel while encryption is enabled.

Raises:
RuntimeError: If the server is not running or no socket was passed.
OSError: If the socket write fails (the original error is re-raised).
"""
if is_send_raw:
deal_msg = message.strip()
if not deal_msg.endswith("\n"):
deal_msg += "\n"
encoded = deal_msg.encode("utf-8")
self._sendall(client_socket, encoded)
self._measure_network_speed(encoded, is_upload=True)
return True
written = self._write_message(client_socket, message)
if written:
self._after_send(client_socket, message)
return written

def _write_message(self, client_socket, message):
"""Write one payload; protected transfer commands may not fall back to plaintext.

Returns:
bool: True when written, False if unsupported or required framing is unavailable.
"""
if not self.running or not client_socket:
self._log("disable the connect to server")
raise RuntimeError("connection error")
with self._crypto_lock:
channel = self._channels.get(client_socket)
control_frame = self.is_enable_encrypto and _requires_secure_transfer_frame(message)
if channel is not None and channel.secure:
try:
if not isinstance(message, (str, bytes)):
self._log(f"Unsupported message type: {type(message)}")
return False
payload = message
if isinstance(message, str) and not message.strip().endswith("\n"):
payload = message.strip() + "\n" # line framing for the control protocol
channel.send(payload, require_secure=control_frame)
self._measure_network_speed(payload, is_upload=True)
return True
except Exception as e:
if not _is_closed_socket_error(e):
self._log(f"send msg error: {e}")
self._log_exc()
raise
if control_frame:
return False # never enter the plaintext writer, including during rekey
with self._crypto_get_send_lock(client_socket): # plaintext writes stay ordered per socket
try: # add newline character for server to distinguish messages
if isinstance(message, str):
deal_msg = message.strip()
if not deal_msg.endswith("\n"):
deal_msg += "\n"
data = deal_msg.encode("utf-8")
elif isinstance(message, bytes):
data = message
else:
self._log(f"Unsupported message type: {type(message)}")
return False
self._sendall(client_socket, data)
self._measure_network_speed(data, is_upload=True)
return True
except Exception as e:
if not _is_closed_socket_error(e):
self._log(f"send msg error: {e}")
self._log_exc()
raise

def _after_send(self, client_socket, message):
"""Record and report one payload that `_write_message` has written."""
if isinstance(message, str):
message = message.strip()
if message and client_socket in self._control_sockets:
self._record_sent(client_socket, message)
self._notify_message_sent(client_socket, message)

def _sendall(self, client_socket, data):
"""Write ``data`` in full, waiting for room on a non-blocking socket.

Args:
client_socket (socket.socket): Target connection.
data (bytes): Payload to write in full.

Raises:
OSError: If the socket write fails or the peer closed the
connection.
TimeoutError: If a non-blocking socket stays unwritable for
``SEND_WAIT_TIMEOUT`` seconds.
"""
if not self.is_asynic_clients_io: # blocking socket: a single sendall is enough
client_socket.sendall(data)
return
view = memoryview(data)
while view:
try:
sent = client_socket.send(view)
except BlockingIOError: # non-blocking socket with a full send buffer
_wait_writable(client_socket, SEND_WAIT_TIMEOUT)
continue
if sent == 0: # the peer closed the connection
raise BrokenPipeError(errno.EPIPE, "socket closed while sending")
view = view[sent:]

def _crypto_mark_encrypted(self, client_socket, peer_role, peer_pem_path):
"""Handle the operation.

Args:
client_socket (socket.socket): Value used by the operation.
peer_role (object): Value used by the operation.
peer_pem_path (str): Value used by the operation.
"""
with self._crypto_lock:
self._encrypted_sockets.add(client_socket)
self._crypto_peer[client_socket] = (peer_role, peer_pem_path)

def _crypto_session_for(self, client_address):
"""Get or create the crypto session for a client address.

The crypto session of one client address (created on demand).

Args:
client_address (tuple): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
with self._crypto_lock:
session = self._crypto_sessions.get(client_address)
if session is None and self.crypto is not None:
session = _CryptoSession(self.crypto, "server", self._log, self._debug)
self._crypto_sessions[client_address] = session
return session

def _crypto_control_state(self, client_socket):
"""Return (session, channel) of one control socket; (None, None) when unknown.

(session, channel) of one control socket; (None, None) when unknown.

Args:
client_socket (socket.socket): Value used by the operation.

Returns:
list | tuple: Result produced by the operation.
"""
with self._crypto_lock:
addr = self._crypto_sock_addr.get(client_socket)
session = self._crypto_sessions.get(addr) if addr is not None else None
channel = self._channels.get(client_socket)
return session, channel

def _crypto_after_flip(self, client_socket):
"""Announce frame readiness (plaintext) and publish the session ECDH key.

Args:
client_socket (socket.socket): Value used by the operation.
"""
_session, channel = self._crypto_control_state(client_socket)
if channel is None:
return
try:
# plaintext by design: the peer needs this line before it may frame
self.send_message(client_socket, CRYPTO_FRAMES_START, is_send_raw=True)
except Exception:
self._log_exc()
self._crypto_publish_ecdh_pub(client_socket)

def _crypto_publish_ecdh_pub(self, client_socket):
"""Send our session ECDH public key once frames are allowed both ways.

Args:
client_socket (socket.socket): Value used by the operation.
"""
session, channel = self._crypto_control_state(client_socket)
if session is not None:
session.publish_pub(channel)

def _crypto_transfer_stamp(self, control_socket, force_plain=False):
"""Mode+nonce a listener announces to a transfer connector.

Args:
control_socket (socket.socket): Value used by the operation.
force_plain (bool): Value used by the operation.

Returns:
object | str: Result produced by the operation.
"""
session, channel = self._crypto_control_state(control_socket)
if session is None:
return "plain"
return session.transfer_stamp(channel, force_plain)

def _crypto_attach_transfer_in(self, sock, control_socket, stamp):
"""Framing channel for an accepted transfer socket (listener side).

Args:
sock (object): Value used by the operation.
control_socket (socket.socket): Value used by the operation.
stamp (object): Value used by the operation.

Returns:
NoneType | object: Result produced by the operation.
"""
session, control_channel = self._crypto_control_state(control_socket)
if session is None:
return None
channel = session.attach_transfer(sock, control_channel, stamp)
if channel is not None:
with self._crypto_lock:
self._channels[sock] = channel
self._encrypted_sockets.add(sock)
return channel

def _crypto_attach_transfer_out(self, sock, control_socket, stamp):
"""Framing channel for a connected transfer socket (connector side).

Args:
sock (object): Value used by the operation.
control_socket (socket.socket): Value used by the operation.
stamp (object): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
session, control_channel = self._crypto_control_state(control_socket)
crypto = _connector_transfer_crypto(session, control_channel, stamp)
channel = _enable_connector_channel(sock, crypto)
if channel is not None:
with self._crypto_lock:
self._channels[sock] = channel
self._encrypted_sockets.add(sock)
return channel

def _crypto_drop_channel(self, sock):
"""Forget a finished transfer socket's channel.

Args:
sock (object): Value used by the operation.
"""
with self._crypto_lock:
self._channels.pop(sock, None)
self._encrypted_sockets.discard(sock)

@staticmethod
def _new_crypto_state(force=False):
"""Fresh per-connection crypto handshake state.

Args:
force (bool): Value used by the operation.

Returns:
dict: Result produced by the operation.
"""
return {
"force": force,
"peer_nonce": None,
"my_nonce": None,
"peer_pub_event": threading.Event(),
"peer_pub_ok": None,
"peer_pem_path": None,
"ready_sent": False,
"peer_ready": False,
"decode_failures": 0,
}

def receive_message(self, client_socket, msg_length): # receive message
"""Read up to ``msg_length`` bytes from a client socket.

A socket speaking frames (see `_SecureChannel`) returns decrypted
plaintext, served from the channel's buffer; a socket without one is
read raw. A read that started while the channel was raw is classified
by the channel when it returns, so bytes of a flip that landed during
the read never land in the line reader. Reads from a non-control socket
are also reported to the message listeners (see `_notify_transfer_chunk`).

Args:
client_socket (socket.socket): Connection to read from.
msg_length (int): Maximum number of bytes to read.

Returns:
bytes: Received bytes, empty when the peer closed the connection.
"""
while True:
with self._crypto_lock:
channel = self._channels.get(client_socket)
if channel is None:
data = client_socket.recv(msg_length)
self._measure_network_speed(data, is_upload=False)
self._notify_transfer_chunk(client_socket, data)
return data
data = channel.take(msg_length)
if data:
self._measure_network_speed(data, is_upload=False)
self._notify_transfer_chunk(client_socket, data)
return data # buffered plaintext is served even after a disable
raw = client_socket.recv(self.recv_messages_chunk_len if channel.secure else msg_length)
if not raw:
return b""
try:
plain = channel.feed(raw)
except _FrameError as exc:
self._log(f"crypto: {exc}")
self._crypto_channel_error(client_socket)
leftover = channel.drain_plaintext()
if leftover:
self._measure_network_speed(leftover, is_upload=False)
self._notify_transfer_chunk(client_socket, leftover)
return leftover # hand back whatever was already read
continue # framing is off now: keep serving in raw mode
if plain:
self._measure_network_speed(plain, is_upload=False)
self._notify_transfer_chunk(client_socket, plain)
return plain # plaintext mode: the line reader gets the bytes

def _crypto_channel_error(self, client_socket):
"""Handle a frame decode failure on a control or transfer socket.

A frame failed to decode: re-exchange on a control socket, close a

transfer socket (its leg has no handshake to recover with).

Args:
client_socket (socket.socket): Value used by the operation.
"""
with self._crypto_lock:
is_control = client_socket in self._crypto_sock_addr
if is_control:
self._crypto_on_decode_failure(client_socket)
return
self._log("crypto: transfer frame error, closing the transfer connection")
try:
client_socket.close()
except Exception:
pass

def _crypto_note_healthy(self, client_socket):
"""Reset the decode-failure count after a valid frame.

A frame decoded cleanly: reset the streak that feeds the breaker.

Args:
client_socket (socket.socket): Value used by the operation.
"""
with self._crypto_lock:
addr = self._crypto_sock_addr.get(client_socket)
state = self._crypto_state.get(addr) if addr is not None else None
if state is not None:
state["decode_failures"] = 0

def _crypto_on_decode_failure(self, client_socket):
"""Decryption failed (stale/wrong key): drop encryption, reload

our own key and ask the peer to re-exchange public keys.

A circuit breaker closes the connection after
``MAX_DECODE_FAILURES`` consecutive failures on one connection,
so a garbage-injection or persistent-mismatch storm cannot spin
the re-exchange loop forever.

Args:
client_socket (socket.socket): Value used by the operation.
"""
with self._crypto_lock:
channel = self._channels.get(client_socket)
if channel is not None:
channel.disable()
with self._crypto_lock:
self._encrypted_sockets.discard(client_socket)
self._crypto_peer.pop(client_socket, None)
addr = self._crypto_sock_addr.get(client_socket)
state = self._crypto_state.get(addr) if addr is not None else None
if state is None:
state = self._new_crypto_state(force=True)
if addr is not None:
self._crypto_state[addr] = state
state["decode_failures"] = state.get("decode_failures", 0) + 1
if state["decode_failures"] >= MAX_DECODE_FAILURES:
do_close = True
do_reload = False
do_exchange = False
else:
do_close = False
do_reload = True
do_exchange = True
state["force"] = True
state["my_nonce"] = self._crypto_fresh_nonce()
state["peer_pub_event"] = threading.Event()
state["peer_pub_ok"] = None
if do_close:
self._log("crypto: too many decode failures, closing connection")
try:
client_socket.close()
except Exception:
self._log_exc()
return
if do_reload and self.crypto is not None:
try:
self.crypto.reload_own_key()
except Exception:
self._log_exc()
self._debug("crypto: decode failure, re-exchanging public keys")
if do_exchange:
if addr is not None:
threading.Thread(
target=self._crypto_wait_server_ready,
args=(client_socket, addr, state),
daemon=True,
).start()
try:
with self._crypto_lock:
nonce = state.get("my_nonce") or self._crypto_fresh_nonce()
self.send_message(
client_socket, f"/crypto_key_exchange {nonce} 1", is_send_raw=True
)
except Exception:
self._log_exc()

def _crypto_drop_secure(self, client_socket):
"""Framing stopped: keep the secure-socket set and peer map truthful.

Args:
client_socket (socket.socket): Value used by the operation.
"""
with self._crypto_lock:
self._encrypted_sockets.discard(client_socket)
self._crypto_peer.pop(client_socket, None)

@staticmethod
def _crypto_fresh_nonce():
"""Handle the operation.

Returns:
object: Result produced by the operation.
"""
return secrets.token_hex(16)

def _crypto_on_client_hello(self, client_socket, client_address, client_nonce, force):
"""Server side of /crypto_key_exchange: record the client's

session nonce, reply that we need its public key (every
connection re-exchanges), then wait for it and announce
readiness.

Args:
client_socket (socket.socket): Value used by the operation.
client_address (tuple): Value used by the operation.
client_nonce (object): Value used by the operation.
force (bool): Value used by the operation.
"""
self.crypto.ensure_keys()
my_nonce = self._crypto_fresh_nonce()
with self._crypto_lock:
state = self._crypto_state.setdefault(client_address, self._new_crypto_state(force))
state["force"] = force
state["peer_nonce"] = client_nonce
state["my_nonce"] = my_nonce
state["peer_pub_event"] = threading.Event()
state["peer_pub_ok"] = None
session = self._crypto_sessions.get(client_address)
if session is not None:
session.reset_ecdh() # a fresh handshake is a fresh session key
self.send_message(
client_socket,
f"/crypto_key_exchange_ack {my_nonce} 1 {1 if force else 0}",
is_send_raw=True,
)
threading.Thread(
target=self._crypto_wait_server_ready,
args=(client_socket, client_address, state),
daemon=True,
).start()

def _crypto_try_server_flip(self, client_socket, state):
"""Flip the socket to framed encryption once the peer key passed the

TOFU check and both sides announced readiness (no plaintext/framed
interleaving).

Args:
client_socket (socket.socket): Value used by the operation.
state (object): Value used by the operation.
"""
# no send may interleave with the flip
with self._crypto_get_send_lock(client_socket):
with self._crypto_lock:
if not (
state.get("peer_pub_ok") is True
and state.get("peer_pem_path")
and state.get("ready_sent")
and state.get("peer_ready")
and client_socket not in self._encrypted_sockets
):
return
self._crypto_mark_encrypted(client_socket, "client", state["peer_pem_path"])
channel = self._channels.get(client_socket)
my_nonce = state.get("my_nonce")
peer_nonce = state.get("peer_nonce")
peer_pem_path = state.get("peer_pem_path")
if channel is not None:
channel.enable(my_nonce, peer_nonce, peer_pem_path)
threading.Thread(target=self._crypto_after_flip, args=(client_socket,), daemon=True).start()

def _crypto_wait_server_ready(self, client_socket, client_address, state):
"""Wait until the client's public key arrived and passed the

TOFU check, then announce readiness. The socket flips to
encrypted mode only when the client's /crypto_ready arrives too.

Args:
client_socket (socket.socket): Value used by the operation.
client_address (tuple): Value used by the operation.
state (object): Value used by the operation.
"""
with self._crypto_lock:
peer_pub_event = state.get("peer_pub_event")
if peer_pub_event is None or not peer_pub_event.wait(timeout=60):
self._log("crypto: waiting for client public key timed out")
return
with self._crypto_lock:
pub_ok = state.get("peer_pub_ok")
if pub_ok is not True:
self._log("crypto: client public key rejected, connection dropped")
return
with self._crypto_lock:
state["ready_sent"] = True
try:
self.send_message(client_socket, "/crypto_ready", is_send_raw=True)
except Exception:
self._log_exc()
self._crypto_try_server_flip(client_socket, state)

def _crypto_push_pub_to_client(self, client_socket, client_address):
"""Push our public key file to the client via the file-transfer

mechanism (server is the sender).

Args:
client_socket (socket.socket): Value used by the operation.
client_address (tuple): Value used by the operation.

Returns:
bool: Result produced by the operation.
"""
while True: # serialise pushes: wait for an in-flight push instead of silently skipping it
with self._crypto_lock:
if client_socket not in self._crypto_push_active:
self._crypto_push_active.add(client_socket)
break
time.sleep(0.05)
try:
client_id = self._fid_alloc.alloc(receiver=client_address)
with _transfer_handshake(self, client_socket, client_id) as handshake:
send_msg = f"/crypto_pub_key {client_id}"
if not _send_transfer_request(self, handshake, send_msg, is_send_raw=True):
return False
result = self._transfer_handshakes.wait(handshake, 10.0)
if result is None or result[0] != "port" or result[1] != client_id:
self._log("crypto: transfer port waiting timeout, public key push failed")
return False
_, _, file_server_port, _stamp = result
file_transfer_client_port = self.palloc()
try:
self.file_transfer_mode( # public-key bytes always travel plaintext
self.crypto.pub_path,
client_address[0],
file_server_port,
file_transfer_client_port,
control_socket=client_socket,
crypto="plain",
)
finally:
self.pfree(file_transfer_client_port)
except Exception:
self._log_exc()
return False
finally:
with self._crypto_lock:
self._crypto_push_active.discard(client_socket)
return True

def _crypto_store_received_pub(self, full_path, peer_role, client_address):
"""TOFU-check a public key received via the file-transfer

mechanism and cache it under the peer endpoint.

The check runs ``verify_peer_pub`` against ``pub_key.json``; on
failure the peer connection is rejected and dropped.

Args:
full_path (str): Value used by the operation.
peer_role (object): Value used by the operation.
client_address (tuple): Value used by the operation.
"""
if self.crypto is None:
return
peer_ip, peer_port = client_address
try:
with open(full_path, "r", encoding="utf-8") as f:
pem = f.read()
except OSError:
pem = ""
ok, reason = self.crypto.verify_peer_pub(peer_ip, peer_port, pem, peer_role)
with self._crypto_lock:
state = self._crypto_state.get(client_address)
if ok:
self.crypto.store_peer_pem(peer_role, peer_ip, peer_port, full_path)
if state is not None:
state["peer_pem_path"] = self.crypto.peer_pem_path(
peer_role, peer_ip, peer_port
)
state["peer_pub_ok"] = True
state["peer_pub_event"].set()
self._log(f"crypto: accepted public key from {peer_ip}:{peer_port} ({reason})")
else:
if state is not None:
state["peer_pub_ok"] = False
state["peer_pub_event"].set()
self._log(f"crypto: REJECTED public key from {peer_ip}:{peer_port}: {reason}")
try:
os.remove(full_path) # rejected key: do not leave it in received_files/
except OSError:
pass
peer_socket = self.clients.get(client_address, {}).get("socket")
if not ok and peer_socket is not None:
try:
self.send_message(peer_socket, f"/crypto_reject {reason}", is_send_raw=True)
except Exception:
self._log_exc()
try:
peer_socket.close()
except Exception:
self._log_exc()

def handle_client(self, client_socket, client_address): # deal with each client
"""Serve one accepted client until it disconnects.

Registers the client, greets it, announces the encryption mode and reads
lines until the peer closes: commands go to `handle_command`, plain
messages go to the message listeners and to ``messages_dict``. The client
is removed from ``clients`` and its socket closed when the read loop ends
for any reason.

With ``is_asynic_clients_io`` False (the default) the call blocks and owns
its thread; with it True the client is served by a coroutine on the
server's event loop instead, and the call returns as soon as that
coroutine is scheduled. A connection arriving while that mode is on but
no event loop runs is closed with a console notice.

Args:
client_socket (socket.socket): Accepted connection.
client_address (tuple): Peer ``(ip, port)``; used as the client id and
as the key in ``clients``.
"""
if self.is_asynic_clients_io:
self._schedule_client_coroutine(client_socket, client_address)
return
client_id = self._register_client(client_socket, client_address)
try:
if not self._announce_client(client_socket, client_id):
return
buffer = ""
while True:
data = self.receive_message( # get msg from client
client_socket, self.recv_messages_chunk_len
)
self._debug(data)
if not data:
break
buffer += data.decode("utf-8")
while "\n" in buffer: # deal with multiple messages in buffer
line, buffer = buffer.split("\n", 1)
message = line.strip()
if not message:
continue
response = self._process_client_line(
client_socket, client_address, client_id, message
)
if response: # send response to client
self.send_message(client_socket, response)
except ConnectionResetError:
pass # peer dropped with RST; the finally block reports the disconnect once
except Exception as e:
if not _is_closed_socket_error(e):
self._log(f"error while deal with client {client_id} : {e}")
self._log_exc()
finally:
self._unregister_client(client_socket, client_address, client_id)

def _schedule_client_coroutine(self, client_socket, client_address):
"""Schedule one accepted client on the server's asyncio event loop.

Args:
client_socket (socket.socket): Accepted connection.
client_address (tuple): Peer ``(ip, port)``.
"""
loop = self._async_loop
if loop is None or loop.is_closed():
self._log(
"asynic clients io is enabled but no event loop is running, closing the connection"
)
try:
client_socket.close()
except Exception:
self._log_exc()
return
loop.call_soon_threadsafe(
loop.create_task, self._handle_client_async(client_socket, client_address)
)

async def _async_receive(self, client_socket, loop):
"""Read up to ``recv_messages_chunk_len`` plaintext bytes from one accepted client.

Mirrors `receive_message` for the asyncio path: framed bytes are
decrypted off the event loop (RSA/ECDH are CPU-bound) and served from
the channel's buffer; a socket without a channel is read raw. As in
`receive_message`, the channel classifies what the read returned, so a
flip that landed during the read never leaks frame bytes into the line
reader.

Args:
client_socket (socket.socket): Value used by the operation.
loop (object): Value used by the operation.

Returns:
bytes | object: Result produced by the operation.
"""
while True:
with self._crypto_lock:
channel = self._channels.get(client_socket)
if channel is None:
data = await loop.sock_recv(client_socket, self.recv_messages_chunk_len)
self._notify_transfer_chunk(client_socket, data)
return data
data = channel.take(self.recv_messages_chunk_len)
if data:
self._notify_transfer_chunk(client_socket, data)
return data # buffered plaintext is served even after a disable
raw = await loop.sock_recv(client_socket, self.recv_messages_chunk_len)
if not raw:
return b""
try:
plain = await asyncio.to_thread(channel.feed, raw)
except _FrameError as exc:
self._log(f"crypto: {exc}")
await asyncio.to_thread(self._crypto_channel_error, client_socket)
leftover = channel.drain_plaintext()
if leftover:
self._notify_transfer_chunk(client_socket, leftover)
return leftover
continue # framing is off now: keep serving in raw mode
if plain:
self._notify_transfer_chunk(client_socket, plain)
return plain # plaintext mode: the line reader gets the bytes

async def _handle_client_async(self, client_socket, client_address):
"""Serve one accepted client until it disconnects, as a coroutine.

The socket is read through the event loop while the line dispatch and
every write run on worker threads, so a blocking command handler,
listener or peer cannot stall the other connections.

Args:
client_socket (socket.socket): Value used by the operation.
client_address (tuple): Value used by the operation.
"""
loop = asyncio.get_running_loop()
client_id = self._register_client(client_socket, client_address)
try:
if not await asyncio.to_thread(self._announce_client, client_socket, client_id):
return
buffer = ""
while self.running:
data = await self._async_receive(client_socket, loop) # get msg from client
self._debug(data)
if not data:
break
buffer += data.decode("utf-8", "replace")
while "\n" in buffer: # deal with multiple messages in buffer
line, buffer = buffer.split("\n", 1)
message = line.strip()
if not message:
continue
response = await asyncio.to_thread(
self._process_client_line,
client_socket,
client_address,
client_id,
message,
)
if response: # send response to client
await asyncio.to_thread(self.send_message, client_socket, response)
except ConnectionResetError:
pass # peer dropped with RST; the finally block reports the disconnect once
except Exception as e:
if not _is_closed_socket_error(e):
self._log(f"error while deal with client {client_id} : {e}")
self._log_exc()
finally:
try:
# a cancelled read can leave its poll callback registered on the fd
loop.remove_reader(client_socket.fileno())
except Exception:
pass
self._unregister_client(client_socket, client_address, client_id)

def _register_client(self, client_socket, client_address):
"""Add one accepted connection to ``clients``.

Args:
client_socket (socket.socket): Accepted connection.
client_address (tuple): Peer ``(ip, port)``.

Returns:
str: Client id, ``"<ip>:<port>"``.
"""
client_id = f"{client_address[0]}:{client_address[1]}"
with self.client_lock: # add new client
previous = self.clients.get(client_address, {}).get("socket")
self._control_sockets.add(client_socket)
self.clients[client_address] = {
"socket": client_socket,
"address": client_address,
"id": client_id,
"connected_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
}
if previous is not None and previous is not client_socket:
self._retire_client_transfers(previous, client_address)
_TransferHandshakeRegistry._close_socket(previous)
with self.client_lock:
retired = tuple(self._retired_transfer_sessions.get(client_address, ()))
if self.is_enable_encrypto and self.crypto is not None:
session = self._crypto_session_for(client_address)
channel = _SecureChannel(
client_socket,
session,
self._log,
self._debug,
send_lock=self._crypto_get_send_lock(client_socket),
sendall=lambda data, sock=client_socket: self._sendall(sock, data),
on_disable=lambda: self._crypto_drop_secure(client_socket),
)
with self._crypto_lock:
self._crypto_sock_addr[client_socket] = client_address
self._channels[client_socket] = channel
self._debug(f"new connection: {client_id}")
self._debug(f"connection count mount: {len(self.clients)}")
# a peer that comes back carries interrupted transfers: continue them
# (and wake the forwarded-resume requests that waited for it) off the
# accept path, because the resume may need this peer's handshake first
threading.Thread(
target=self._resume_after_connect,
args=(client_address, client_socket, retired), daemon=True
).start()
return client_id

def _announce_client(self, client_socket, client_id):
"""Greet one client and announce the encryption mode and port range.

Args:
client_socket (socket.socket): Connection to greet.
client_id (str): Client id used in the console log.

Returns:
bool: True when the peer was greeted, False when it was already gone
(the caller closes the connection either way).
"""
welcome_msg = f"Welcome!: {client_id}\n" # send welcome message
try:
self.send_message(client_socket, welcome_msg)
except Exception as e:
# the server is stopping (or the peer vanished): the caller's
# cleanup closes the connection; never let this escape
if not _is_closed_socket_error(e):
self._log(f"error while welcoming client {client_id} : {e}")
return False
# announce our encryption mode; a mismatched peer is disconnected in handle_command
try:
self.send_message(
client_socket,
f"/crypto_mode {1 if self.is_enable_encrypto else 0}",
is_send_raw=True,
)
except Exception as e:
# the peer vanished right after the welcome: the caller's cleanup
# closes the connection; never let this escape
if not _is_closed_socket_error(e):
self._log(f"error while announcing crypto mode to {client_id} : {e}")
return False
if self.is_hand_alloc_port == True:
port_alloc_range_msg = "/client_alloc_port_range {}".format(self.each_client_port_range)
else:
port_alloc_range_msg = "/client_alloc_port_range NO_LIMIT"
# the range is fixed for the server's lifetime, so only the connection
# that just joined needs it (announcing it to every client is O(N) per
# accepted connection)
try:
self.send_message(client_socket, port_alloc_range_msg)
except Exception as e:
# the peer vanished right after the welcome: the caller's cleanup
# closes the connection; never let this escape
if not _is_closed_socket_error(e):
self._log(f"error while announcing the port range to {client_id} : {e}")
return False
self._debug(self.clients)
return True

def _process_client_line(self, client_socket, client_address, client_id, message):
"""Report, log and dispatch one complete (already decrypted) line from a client.

Args:
client_socket (socket.socket): Connection the line came from.
client_address (tuple): Peer ``(ip, port)``.
client_id (str): Client id used in the console log.
message (str): One line with its newline removed.

Returns:
str | None: Response for that client, or None when none is due.
"""
if not _crypto_is_protocol_line(message):
# genuine peer traffic: reset the streak that feeds the breaker
self._crypto_note_healthy(client_socket)
self._log(message)
# every inbound line is an event for the message listeners (commands
# included); dispatch below is unaffected
self._notify_message_received(client_id, message)
if message.startswith("/"): # deal with special command
self._record_event(client_socket, message)
return self.handle_command(client_socket, client_address, message)
self._record_message(client_socket, message)
timestamp = datetime.now().strftime("%H:%M:%S") # deal with normal message
log_msg = f"[{timestamp}] {client_id}: {message}"
self._log(log_msg)
return f"msg send: {message}"

def _retire_client_transfers(self, control_socket, peer):
retired = _retire_transfer_session(self, control_socket)
with self.client_lock:
self._retired_transfer_sessions.setdefault(peer, []).append(retired)

def drain():
_wait_transfer_session(self, retired)
with self.client_lock:
pending = self._retired_transfer_sessions.get(peer, [])
pending[:] = [item for item in pending if item is not retired]
if not pending:
self._retired_transfer_sessions.pop(peer, None)

threading.Thread(target=drain, daemon=True).start()

def _unregister_client(self, client_socket, client_address, client_id):
"""Drop one client's state and close its socket.

Args:
client_socket (socket.socket): Connection to close.
client_address (tuple): Peer ``(ip, port)``.
client_id (str): Client id used in the console log.
"""
self._retire_client_transfers(client_socket, client_address)
with self.client_lock:
owns_peer = self.clients.get(client_address, {}).get("socket") is client_socket
if owns_peer:
del self.clients[client_address]
with self._crypto_lock:
if owns_peer:
self._crypto_state.pop(client_address, None)
self._crypto_sessions.pop(client_address, None)
self._crypto_sock_addr.pop(client_socket, None)
self._crypto_peer.pop(client_socket, None)
self._crypto_push_active.discard(client_socket)
self._encrypted_sockets.discard(client_socket)
self._control_sockets.discard(client_socket)
self._channels.pop(client_socket, None)
self._crypto_send_locks.pop(client_socket, None)
client_socket.close()
# the transfers that died with this connection are written to the
# progress file so a reconnect can continue them (_request_resumes)
self._persist_transfer_progress()
self._debug(f"client disconnected: {client_id}")
self._debug(f"current connection count: {len(self.clients)}")

def handle_command(
self, client_socket, client_address, command
): # deal with special commands from client
"""Dispatch one command line received from a client.

Built-in commands (``/help``, ``/time``, ``/clients``, ``/quit``,
``/crypto_mode``, ``/file``, ``/file_folder``,
``/server_file_transfer_port`` and the crypto exchange lines) are handled
here; any other name goes to the handlers registered for the "server" side
via `register_command`. An encryption-mode mismatch and ``/quit`` close the
connection; an unknown command is only reported on the console.

Args:
client_socket (socket.socket): Connection the line came from.
client_address (tuple): Peer ``(ip, port)``.
command (str): Line including its leading ``/``.

Returns:
str | None: Response for that client, or None when no response is due
(crypto lines, file transfers, ``/quit``, which answers on the
socket before shutting it down, and custom handlers that run in the
background).
"""
self._debug(client_socket, client_address, command)
client_id = f"{client_address[0]}:{client_address[1]}"
send_str = None
if command.split(maxsplit=1)[:1] and command.split(maxsplit=1)[0].lower() in (
"/pause_trans", "/start_trans"
):
_receive_transfer_control(self, client_socket, tuple(client_address), command)
return None
if command == "/help":
help_text = [
"avalable commands:",
"/help - print help meg\n",
"\t/time - display server time\n",
"\t/clients - display connected clients\n",
"\t/file <file_path> [destination_file_path] - send file to server\n",
"\t/multiple_file <file1> <file2> ... [destination_file_path] ",
"- send multiple files to server\n",
"\t/file_folder <folder_path> [destination_file_path] - send folder to server\n",
"\t/multiple_file_folder <folder1> <folder2> ... [destination_file_path] ",
"- send multiple folders to server\n",
"\t/quit - disconnect",
]
send_str = " ".join(help_text) + "\n"
return send_str
elif command == "/time":
send_str = f"server time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" + "\n"
return send_str
elif command == "/clients":
with self.client_lock:
client_list = [info["id"] for info in self.clients.values()]
send_str = f"online clients ({len(client_list)}): {', '.join(client_list)}" + "\n"
return send_str
elif command == "/quit":
# the goodbye is written here (not returned) so the connection can
# be shut down right after it: a client that stays connected after
# /quit must not keep the server reading from the session
try:
self.send_message(client_socket, "Bye!\n")
except Exception as e:
if not _is_closed_socket_error(e):
self._log(f"error while sending goodbye to {client_id} : {e}")
try:
client_socket.shutdown(socket.SHUT_RDWR)
except Exception:
pass # already gone or not connected any more
return None
elif command.lower().split(" ")[0] == "/crypto_mode":
try:
client_crypto = int(command.split(" ")[1])
except (IndexError, ValueError):
client_crypto = -1
if client_crypto != (1 if self.is_enable_encrypto else 0):
self._log(
f"crypto: encryption mode mismatch with client {client_id} "
f"(client={client_crypto}, server={1 if self.is_enable_encrypto else 0}), "
f"disconnecting"
)
try:
client_socket.close()
except Exception:
self._log_exc()
return None
elif shlex.split(command.lower())[0] == "/file":
self.file_transfer_server_recv_server_start_thread(client_id, client_socket, command)
elif shlex.split(command.lower())[0] == "/file_folder":
self.file_folder_transfer_server_recv_server_start_thread(
command, client_id, client_socket
)
elif shlex.split(command.lower())[0] == "/server_file_transfer_port":
announcement = _parse_transfer_port_announcement(command)
if announcement is not None:
port, fid, stamp = announcement
self._transfer_handshakes.resolve_port(client_socket, fid, port, stamp)
elif shlex.split(command.lower())[0] == "/forward_item":
threading.Thread(
target=self._forward_item_handler,
args=(client_socket, client_address, command),
daemon=True,
).start()
return None
elif shlex.split(command.lower())[0] == "/forward_send_msg":
# Internal relay request typed on a client console (client-only
# command, same name on the wire): push the messages to the
# listed destinations.
threading.Thread(
target=self._handle_forward_send_msg,
args=(client_socket, client_address, command),
daemon=True,
).start()
return "Command received, processing in background.\n"
elif shlex.split(command.lower())[0] == RESUME_LINE:
parsed = parse_resume_command(command)
if parsed is not None:
self._resume_request(client_socket, client_address, *parsed)
return None
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == "/crypto_key_exchange"
):
parts = command.split(" ")
client_nonce = parts[1] if len(parts) > 1 else ""
force = len(parts) > 2 and parts[2] == "1"
self._crypto_on_client_hello(client_socket, client_address, client_nonce, force)
return None
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == "/crypto_pub_key"
):
with self._crypto_lock: # only accept pushes from a connection that started the handshake (else the TOFU registry could be poisoned)
handshaking = client_address in self._crypto_state
if not handshaking:
self._log(f"crypto: ignoring /crypto_pub_key from non-handshaking peer {client_id}")
return None
self.file_transfer_server_recv_server_start_thread(client_id, client_socket, command)
return None
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == "/crypto_pub_key_request"
):
threading.Thread( # client asks the server to push its public key
target=self._crypto_push_pub_to_client,
args=(client_socket, client_address),
daemon=True,
).start()
return None
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == "/crypto_key_exchange_ack"
):
parts = command.split(" ")
if len(parts) < 3:
return None
client_nonce = parts[1]
client_needs_server_pub = parts[2]
force = len(parts) > 3 and parts[3] == "1"
with self._crypto_lock:
state = self._crypto_state.get(client_address)
if state is not None:
state["peer_nonce"] = (
client_nonce # reply to a server-initiated hello: fresh session nonce from the client's ack
)
if force or client_needs_server_pub == "1":
threading.Thread(
target=self._crypto_push_pub_to_client,
args=(client_socket, client_address),
daemon=True,
).start()
return None
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == "/crypto_ready"
):
with self._crypto_lock:
state = self._crypto_state.setdefault(
client_address, self._new_crypto_state(force=False)
)
state["peer_ready"] = True
self._crypto_try_server_flip(client_socket, state)
return None
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == "/crypto_reject"
):
reason = command[
len("/crypto_reject") :
].strip() # the peer rejected our public key (TOFU mismatch)
self._log(f"crypto: connection rejected by peer: {reason}")
try:
client_socket.close()
except Exception:
self._log_exc()
return None
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == CRYPTO_FRAMES_START
):
_session, channel = self._crypto_control_state(client_socket)
if channel is not None:
channel.note_peer_frames_ready()
self._crypto_publish_ecdh_pub(client_socket)
return None
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == CRYPTO_ECDH_PUB
):
# only ever accepted inside an RSA frame (see _PLAINTEXT_LINE_PREFIXES)
parts = command.split(" ", 1)
session = self._crypto_sessions.get(client_address)
if session is not None and len(parts) > 1:
if not session.set_peer_ecdh_b64(parts[1]):
self._log(f"crypto: rejected the ECDH key of {client_id}")
return None
else:
cmd_parts = shlex.split(command.strip())
if not cmd_parts:
return None
cmd_name = cmd_parts[0].lower()
if cmd_name in self._custom_handlers[0]:
handler = self._custom_handlers[0][cmd_name]
run_in_thread = self._custom_handler_threaded[0].get(cmd_name, False)
if run_in_thread:
self.submit_task(
self._execute_custom_handler,
handler,
command,
client_socket,
client_address,
)
return "Command received, processing in background.\n"
else:
response = self._execute_custom_handler(
handler, command, client_socket, client_address
)
return response
else:
self._log(f"Unknown command: {command}")

def _handle_forward_send_msg(self, sock, addr, cmd):
"""Relay plain messages to every reachable destination client.

Server side of the client-only ``/forward_send_msg`` command (typed on
a client console and relayed here over the wire). Every message is
wrapped in a ``/send_msg_from <addr> <payload>`` envelope carrying the
originator's address so receivers can attribute it. The messages are
recorded under the originator's socket (``sock``), exactly as if the
originator had sent them to the server. Destinations that are
unreachable -- or the server itself, which is never in the client
table -- are skipped and the rest are still served.

Args:
sock (object): Value used by the operation.
addr (tuple): Value used by the operation.
cmd (object): Value used by the operation.

Returns:
NoneType: Result produced by the operation.
"""
parts = shlex.split(cmd)
items, addrs = parse_forward_items_and_addrs(parts[1:])
reached = False
for target in addrs:
for msg in items:
if self.forward_message_to(target, msg, addr):
reached = True
if reached:
for msg in items:
self._record_message(sock, msg)
return None

def forward_message_to(self, target, message, originator_addr):
"""Send one plain message to a connected target, tagged with its origin.

Public API for forward extensions: the message is wrapped in a
``/send_msg_from <addr> <payload>`` envelope so the receiver can attribute
it to the originator (see `parse_forwarded_message`).

Args:
target (tuple): Destination ``(ip, port)``.
message (str): Payload to deliver.
originator_addr (tuple): Originating client ``(ip, port)``.

Returns:
bool: False when ``target`` is not connected (a console notice is
printed); True when the envelope was sent.
"""
client_info = self.clients.get(target)
if client_info is None:
self._log(forward_skip_message(target))
return False
self.send_message(
client_info["socket"],
f"/send_msg_from {shlex.quote(repr(originator_addr))} {shlex.quote(message)}",
)
return True

def forward_target_command(
self, kind, rel_dir, fname, originator_addr, tfid,
destination_path=None,
):
"""Build the receiver command using its sender-allocated child FID."""
originator = shlex.quote(repr(originator_addr))
if kind == "file":
if destination_path:
return (
f"/file {shlex.quote(fname)} {originator} "
f"{shlex.quote(destination_path)} {tfid}"
)
return f"/file {shlex.quote(fname)} {originator} {tfid}"
if destination_path:
return (
f"/file_folder {shlex.quote(rel_dir)} {shlex.quote(fname)} "
f"{originator} {shlex.quote(destination_path)} {tfid}"
)
return (
f"/file_folder {shlex.quote(rel_dir)} {shlex.quote(fname)} "
f"{originator} {tfid}"
)

def forward_item_to(
self, target, kind, rel_dir, fname, originator_addr, tfid,
destination_path=None,
):
"""Push one forwarded item to its target's receive listener."""
client_info = self.clients.get(target)
if client_info is None:
self._log(forward_skip_message(target))
return False
control = client_info["socket"]
handshake = self._transfer_handshakes.pending(control, tfid)
return _send_transfer_request(
self, handshake,
self.forward_target_command(
kind, rel_dir, fname, originator_addr, tfid, destination_path,
),
)

def _execute_custom_handler(self, handler, command, client_socket=None, client_address=None):
"""Handle the operation.

Args:
handler (callable): Value used by the operation.
command (object): Value used by the operation.
client_socket (socket.socket): Value used by the operation.
client_address (tuple): Value used by the operation.

Returns:
NoneType | object: Result produced by the operation.
"""
try:
result = handler(client_socket, client_address, command)
if result is not None:
if isinstance(result, str) and not result.endswith("\n"):
result += "\n"
try:
self.send_message(client_socket, result)
except Exception as e:
self._log(f"Error sending message: {e}")
return result
return None
except Exception as e:
error_msg = f"Error in custom command handler: {e}\n"
self._log_exc()
try:
self.send_message(client_socket, error_msg)
except Exception as e:
self._log(f"Error sending error message: {e}")
return error_msg

def file_folder_transfer_server_recv_server_start_thread( # start a file folder server thread on server
self, command, client_id, client_socket
):
"""Create a folder, or start a server-side folder receive operation.

A command without a client id (``/file_folder <rel>`` or
``/file_folder <rel> <dest>``) is folder creation: the directory is
created here, on the control line, and no transfer leg is opened. A
command with an id carries one file of the folder and starts the usual
receive leg.

Args:
command (object): Value used by the operation.
client_id (object): Value used by the operation.
client_socket (socket.socket): Value used by the operation.
"""
command_part = shlex.split(command)
relative_folder_path = command_part[1]
# >= 4 tokens means a file transfer (/file_folder <rel> <file> [<dest>] <id>);
# 2-3 tokens is folder creation (optional destination, no client id)
file_name = command_part[2] if len(command_part) >= 4 else None
if file_name is None:
created = _receive_dir_for(
self.file_transfer_dir,
relative_folder_path,
_parse_destination_path(command_part),
)
try:
os.makedirs(created, exist_ok=True)
self._log(f"folder {created} created for {client_id}")
except OSError as e:
self._log(f"folder {created} could not be created for {client_id}: {e}")
return
folder_transfer_server_recv_server_start_thread = threading.Thread(
target=self.file_transfer_server_recv_server_start,
args=(client_id, client_socket, command, relative_folder_path, file_name),
daemon=True,
)
folder_transfer_server_recv_server_start_thread.start()

def file_transfer_server_recv_server_start_thread( # start a file server thread on server
self, client_id, client_socket, command
):
"""Start a server-side file receive operation.

Args:
client_id (object): Value used by the operation.
client_socket (socket.socket): Value used by the operation.
command (object): Value used by the operation.
"""
file_transfer_server_recv_server_start_thread = threading.Thread(
target=self.file_transfer_server_recv_server_start,
args=(client_id, client_socket, command),
daemon=True,
)
file_transfer_server_recv_server_start_thread.start()

def file_transfer_server_recv_server_start( # deal with file transfer request server on server from client and receive file from client
self, client_id, client_socket, command, new_save_path=None, file_name=None
):
"""Receive a file sent by a connected client.

Args:
client_id (object): Value used by the operation.
client_socket (socket.socket): Value used by the operation.
command (object): Value used by the operation.
new_save_path (str): Value used by the operation.
file_name (str): Value used by the operation.
"""
file_transfer_server_port = self.palloc()
self.file_transfer_mode_recv(
self.host,
file_transfer_server_port,
client_socket,
client_id,
new_save_path,
file_name,
command,
peer=_peer_from_text(client_id), # the sender a resume is asked to continue from
)
self.pfree(file_transfer_server_port)

def file_transfer_mode_recv(
self,
server_file_address,
server_file_port,
client_socket,
client_id,
new_save_path,
file_name,
command,
peer=None,
):
"""Receive one file over a transfer sub-connection.

Args:
server_file_address (str): Local address for the transfer listener.
server_file_port (int): Local port for the transfer listener.
client_socket (socket.socket): Sender's control socket.
client_id (str): Sender identifier in ``"ip:port"`` form.
new_save_path (str | None): Relative directory for folder contents.
file_name (str | None): Destination filename, when specified.
command (str): Wire command that initiated the transfer.
peer (tuple | None): Original sender ``(ip, port)`` for resuming.

Returns:
None: after the leg starts or finishes.
"""
file_running = True
client_file_socket = None
server_file_socket = None
save_path = None

def close_socket():
"""Handle the operation."""
nonlocal file_running
nonlocal client_file_socket
nonlocal server_file_socket
file_running = False
self._crypto_drop_channel(client_file_socket)
if client_file_socket is not None:
self._transfer_controls.release_owner(client_file_socket)
client_file_socket.close()
if server_file_socket is not None:
server_file_socket.close()
self._transfer_handshakes.release_socket(client_socket, server_file_socket)

def setting_file_save_path():
"""Resolve, and create, the directory this leg writes into."""
nonlocal save_path
save_path = _receive_dir_for(
self.file_transfer_dir, new_save_path, destination_path
)
if new_save_path or destination_path:
os.makedirs(save_path, exist_ok=True)
if file_name or new_save_path is None:
return save_path
close_socket()
return None

def file_transfer_client_recv(client_id):
"""Handle the operation.

Args:
client_id (object): Value used by the operation.
"""
nonlocal file_running
nonlocal client_file_socket
nonlocal server_file_socket
nonlocal save_path
filename = None
full_path = None
progress = None # this leg's file_recv_progress entry, when tracked
finished_ok = False
try:
self.send_message(client_file_socket, self.server_start_file_transfer_sign)
except Exception as e:
# the instance stopped (or the peer vanished) between the accept
# and this start sign: the transfer is over. A closing instance
# raises RuntimeError("connection error") by design — the normal
# teardown signal — and it must never kill this thread (pytest
# reports any escape as an unhandled thread exception).
if not _is_closed_socket_error(e):
self._log(f"error while starting the file transfer: {e}")
self._log_exc()
close_socket()
self._release_transfer_socket(progress_fid, client_file_socket)
self._transfer_handshakes.release_socket(client_socket, client_file_socket)
return False
try:
name_len_bytes = b""
while len(name_len_bytes) < 4:
chunk = self.receive_message(client_file_socket, 4 - len(name_len_bytes))
self._debug(chunk)
if not chunk:
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
close_socket()
raise ConnectionError(
"ErrorWhileReceivingFileNameLength: client disconnected"
)
name_len_bytes += chunk
if name_len_bytes.strip() == self.error_sign.encode("utf-8"):
close_socket()
raise ConnectionError(
"ErrorSignReceivedWhileReceivingFileNameLength: client reported error and disconnected"
)
name_len = int.from_bytes(name_len_bytes, "big")
file_name_encoded = b""
while len(file_name_encoded) < name_len:
chunk = self.receive_message(
client_file_socket, name_len - len(file_name_encoded)
)
if not chunk:
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
close_socket()
raise ConnectionError("ErrorWhileReceivingFileName: client disconnected")
file_name_encoded += chunk
if file_name_encoded.strip() == self.error_sign.encode("utf-8"):
close_socket()
raise ConnectionError(
"ErrorSignReceivedWhileReceivingFileName: client reported error and disconnected"
)
filename = file_name_encoded.decode("utf-8")
filename = filename.strip()
filename = os.path.basename(filename)
size_bytes = b""
while len(size_bytes) < 8:
chunk = self.receive_message(client_file_socket, 8 - len(size_bytes))
if not chunk:
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
close_socket()
raise ConnectionError("ErrorWhileReceivingFileSize: client disconnected")
size_bytes += chunk
if size_bytes.strip() == self.error_sign.encode("utf-8"):
close_socket()
raise ConnectionError(
"ErrorSignReceivedWhileReceivingFileSize: client reported error and disconnected"
)
file_size = int.from_bytes(size_bytes, "big")
if resume_entry is not None and resume_entry[1] != file_size:
raise ConnectionError(
f"resume rejected: {filename} is {file_size} bytes, "
f"the partial file expects {resume_entry[1]}"
)
self.send_message(client_file_socket, self.server_received_file_header_sign)
original_filename = filename
if resume_entry is not None:
# continued transfer: the receiver's partial file keeps the
# bytes that are already on disk and the sender continues
full_path = resume_entry[3]
final_filename = os.path.basename(full_path)
resume_from = resume_entry[0] # the offset the sender was asked for
if resume_from <= 0 or resume_from > file_size:
resume_from = 0 # not this file's offset: start it over
else:
if file_name:
final_filename = file_name.strip()
elif command_part[0] == "/crypto_pub_key":
# concurrent key pushes share received_files/: a fixed name would be
# overwritten/moved by another connection before this one consumes it
final_filename = "{}.pem".format(uuid.uuid4().hex)
else:
final_filename = os.path.basename(original_filename)
full_path = os.path.join(save_path, final_filename).strip()
resume_from = 0
os.makedirs(os.path.dirname(full_path), exist_ok=True)
progress = self._file_progress_start(
self.file_recv_progress,
progress_fid,
file_size,
full_path,
peer=peer,
initial=resume_from,
)
if progress is None:
progress = resume_entry
with _open_transfer_target(full_path, resume_from) as f:
remaining = file_size - resume_from
while remaining > 0:
chunk = self.receive_message(
client_file_socket, min(self.file_transfer_chunk_len, remaining)
)
if not chunk:
try:
self.send_message(client_file_socket, self.error_sign)
except:
self._log_exc()
pass
close_socket()
raise ConnectionError(
"ErrorWhileReceivingFileData: client disconnected"
)
f.write(chunk)
remaining -= len(chunk)
self._file_progress_update(progress, len(chunk), is_upload=False)
f.truncate() # a longer partial file drops its stale tail
# TOFU first: the ack is only a notification, and a failed
# ack send must not skip the key registration (the server
# would never announce readiness and the handshake hangs)
self._notify_file_received(client_id, full_path, final_filename, file_size, command)
self._update_event_timestamp(
client_socket,
self._splice_event_command(command, fname=final_filename),
datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
)
self._log(f"file {filename} received from {client_id}, size {file_size} bytes")
if command_part[0] == "/crypto_pub_key":
with self._crypto_lock:
peer_addr = self._crypto_sock_addr.get(client_socket)
if peer_addr:
self._crypto_store_received_pub(full_path, "client", peer_addr)
else:
# the peer mapping is already gone (connection torn
# down mid-handshake): store nothing, leave nothing
try:
os.remove(full_path)
except OSError:
pass
try:
finished_ok = bool(self.send_message(
client_file_socket, self.server_received_file_data_sign
))
except Exception:
self._log_exc()
close_socket()
except Exception as e:
self._log_exc()
if full_path is not None and os.path.exists(full_path) and progress is None:
try:
os.remove(full_path) # untracked partial transfer: nothing can resume it
except OSError:
pass
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
close_socket()
self._log(f"ErrorWhileReceiveFile: {e}")
return False
else:
close_socket()
return None
finally:
self._file_progress_finish(
self.file_recv_progress,
progress_fid,
progress,
keep=(
not finished_ok
and progress is not None
and progress[4] is not None # resumable: it has a peer
),
)
self._release_transfer_socket(progress_fid, client_file_socket)
self._transfer_handshakes.release_socket(client_socket, client_file_socket)

server_file_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_file_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
file_transfer_server_port = _bind_local_port_with_fallback(
server_file_socket,
(server_file_address, server_file_port),
self._log,
"file transfer listener",
)
command_part = shlex.split(command)
try:
file_client_id = int(command_part[-1])
if file_client_id < 0:
raise ValueError
except (IndexError, ValueError):
server_file_socket.close()
return
progress_fid = _transfer_fid(command_part) # keys this leg in file_recv_progress
resume_entry = _resumable_entry(self.file_recv_progress, progress_fid, peer, command_part)
destination_path = _parse_destination_path(command_part)
stamp = self._crypto_transfer_stamp(
client_socket, force_plain=command_part[0] == "/crypto_pub_key"
)
transfer_server_port_msg = _transfer_port_announcement(
file_transfer_server_port, file_client_id, stamp
)
server_file_socket.listen(1)
if resume_entry is not None:
# the sender answers this resume with /file; its connection is the continued leg
server_file_socket.settimeout(RESUME_ACCEPT_TIMEOUT)
receive_record = _claim_receive(self, progress_fid, client_socket, server_file_socket)
if progress_fid is not None and receive_record is None:
server_file_socket.close()
return
handed_off = False
try:
if not self._transfer_handshakes.track_socket(client_socket, server_file_socket):
return
if not self.send_message(client_socket, transfer_server_port_msg, is_send_raw=True):
return
client_file_socket, client_file_address = server_file_socket.accept()
if not self._transfer_handshakes.track_socket(client_socket, client_file_socket):
return
if receive_record is not None:
receive_record["owner"] = client_file_socket
if resume_entry is not None:
client_file_socket.settimeout(None) # the accept timeout is the listener's only
self._crypto_attach_transfer_in(client_file_socket, client_socket, stamp)
self._register_transfer_socket(progress_fid, client_file_socket)
_bind_transfer_control(self, progress_fid, client_socket, client_file_socket, 0, 1)
if resume_entry is not None:
handed_off = True
threading.Thread(
target=file_transfer_client_recv, args=(client_id,), daemon=True
).start()
else:
is_open_file_transfer = setting_file_save_path()
if is_open_file_transfer == None:
pass
else:
handed_off = True
threading.Thread(
target=file_transfer_client_recv, args=(client_id,), daemon=True
).start()
except socket.timeout:
self._log(
f"resume: {client_id} did not continue transfer {progress_fid}, "
f"it stays in the progress stores for the next reconnect"
)
except Exception as e:
self._log(f"\nget file transfer msg error: {e}")
self._log_exc()
close_socket()
finally:
server_file_socket.close()
self._transfer_handshakes.release_socket(client_socket, server_file_socket)
if not handed_off:
if client_file_socket is not None:
self._release_transfer_socket(progress_fid, client_file_socket)
_release_receive(self, progress_fid, receive_record)
self._transfer_handshakes.release_socket(client_socket, client_file_socket)

def diff_multiple_file_diff_multiple_client_transfer_server_recv_client_start(self, message):
"""Send grouped files and folders to their listed clients.

Args:
message (object): Value used by the operation.
"""
command_part = shlex.split(message)
del command_part[0]
# optional destination directory is the last argument, after the
# client addresses (which are always tuples)
destination_path = None
if command_part and not (
command_part[-1].startswith("(") and command_part[-1].endswith(")")
):
destination_path = command_part[-1]
del command_part[-1]
file_client_pair_list = []
file_list = []
client_list = []
command_part_addr_times = 0
for command_part_index in range(len(command_part)):
part = command_part[command_part_index]
if part.startswith("(") and part.endswith(")"):
try:
client_addr = ast.literal_eval(part)
client_list.append(client_addr)
command_part_addr_times += 1
if command_part_index == len(command_part) - 1:
file_client_pair = [client_list, file_list]
file_client_pair_list.append(file_client_pair)
except:
self._log_exc()
else:
if command_part_addr_times != 0:
file_client_pair = [client_list, file_list]
file_client_pair_list.append(file_client_pair)
file_list = []
client_list = []
file_list.append(part)
command_part_addr_times = 0
else:
file_list.append(part)
for each_file_client_pair in file_client_pair_list:
file_transfer_command_message = ""
file_folder_transfer_command_message = ""
for file in each_file_client_pair[1]:
try:
if os.path.isfile(file):
if file_transfer_command_message == "":
file_transfer_command_message = "/file {}".format(shlex.quote(file))
else:
file_transfer_command_message += " {}".format(shlex.quote(file))
elif os.path.isdir(file):
if file_folder_transfer_command_message == "":
file_folder_transfer_command_message = "/file_folder {}".format(
shlex.quote(file)
)
else:
file_folder_transfer_command_message += " {}".format(shlex.quote(file))
except:
self._log_exc()
self._log(
f"ErrorWhileParsingFilePath: {file} is not a valid file or folder path, skipped"
)
pass
for client_addr in each_file_client_pair[0]:
if file_transfer_command_message != "":
file_transfer_command_message += " {}".format(shlex.quote(str(client_addr)))
if file_folder_transfer_command_message != "":
file_folder_transfer_command_message += " {}".format(
shlex.quote(str(client_addr))
)
if destination_path:
if file_transfer_command_message != "":
file_transfer_command_message += " {}".format(shlex.quote(destination_path))
if file_folder_transfer_command_message != "":
file_folder_transfer_command_message += " {}".format(
shlex.quote(destination_path)
)
if file_transfer_command_message != "":
self.multiple_file_multiple_client_transfer_server_recv_client_start(
file_transfer_command_message
)
if file_folder_transfer_command_message != "":
self.multiple_file_multiple_client_transfer_server_recv_client_start(
file_folder_transfer_command_message
)

def multiple_file_multiple_client_transfer_server_recv_client_start(self, message):
"""Send requested files or folders to each listed client.

Args:
message (object): Value used by the operation.
"""
command_part = shlex.split(message)
command_type = command_part[0]
del command_part[0]
# optional destination directory is the last argument, after the
# client addresses (which are always tuples)
destination_path = None
if command_part and not (
command_part[-1].startswith("(") and command_part[-1].endswith(")")
):
destination_path = command_part[-1]
del command_part[-1]
transfer_file_list = []
client_addr_list = []
for part in command_part:
if part.startswith("(") and part.endswith(")"):
try:
client_addr = ast.literal_eval(part)
client_addr_list.append(client_addr)
except:
self._log_exc()
else:
transfer_file_list.append(part)
for client_addr in client_addr_list:
for transfer_file in transfer_file_list:
if command_type == "/multiple_file_multiple_client":
# console form: classify each item by its own type
if os.path.isfile(transfer_file):
item_type = "/file"
elif os.path.isdir(transfer_file):
item_type = "/file_folder"
else:
self._log(
f"ErrorWhileParsingFilePath: {transfer_file} is not "
"a valid file or folder path, skipped"
)
continue
else:
item_type = command_type
if item_type == "/file":
file_transfer_command_message = "/file {} {}".format(
shlex.quote(transfer_file), shlex.quote(str(client_addr))
)
if destination_path:
file_transfer_command_message += " {}".format(shlex.quote(destination_path))
self.file_transfer_server_recv_client_start_thread(
file_transfer_command_message
)
self._log(f"start to send file command: {file_transfer_command_message}")
elif item_type == "/file_folder":
folder_transfer_command_message = "/file_folder {} {}".format(
shlex.quote(transfer_file), shlex.quote(str(client_addr))
)
if destination_path:
folder_transfer_command_message += " {}".format(
shlex.quote(destination_path)
)
self.folder_file_transfer_server_recv_client_start(
folder_transfer_command_message
)
self._log(f"start to send folder command: {folder_transfer_command_message}")

def folder_file_transfer_server_recv_client_start(self, message):
"""Send a folder's contents to one connected client.

Args:
message (object): Value used by the operation.
"""
command_part = shlex.split(message)
folder_path = command_part[1]
if command_part[-1].startswith("(") and command_part[-1].endswith(")"):
destination_path = None
client_addr = ast.literal_eval(command_part[-1])
else:
destination_path = command_part[-1]
client_addr = ast.literal_eval(command_part[-2])
client_socket = self.clients[client_addr]["socket"]
if os.path.isdir(folder_path) == False:
self._log(f"{folder_path} is not a valid folder path")
return False
base_path = os.path.dirname(folder_path)

def get_relative_path(base_path, abs_path):
"""Handle the operation.

Args:
base_path (str): Value used by the operation.
abs_path (str): Value used by the operation.
"""
base = os.path.normpath(base_path)
abs_ = os.path.normpath(abs_path)
common = os.path.commonpath([base, abs_])
if common != base:
raise ValueError(f"'{abs_path}' is not a subpath of '{base_path}'")
rel = os.path.relpath(abs_, base)
if rel == ".":
return ""
rel = rel.replace(os.sep, "/")
return "/" + rel

def send_folder_transfer_command(folder_path, file_name=None, abspath=None):
"""Handle the operation.

Args:
folder_path (str): Value used by the operation.
file_name (str): Value used by the operation.
abspath (str): Value used by the operation.
"""
folder_transfer_command_message = "/file_folder {}".format(shlex.quote(folder_path))
if file_name:
each_file_transfer_command_message = "/file_folder {} {} {}".format(
shlex.quote(folder_path), shlex.quote(file_name), shlex.quote(str(client_addr))
)
if destination_path:
each_file_transfer_command_message += " {}".format(
shlex.quote(destination_path)
)
self.file_transfer_server_recv_client_start_thread(
each_file_transfer_command_message, abspath
)
self._log(f"start to send folder command: {each_file_transfer_command_message}")
else:
if destination_path:
folder_transfer_command_message += " {}".format(shlex.quote(destination_path))
self.send_message(client_socket, folder_transfer_command_message.strip())
self._log(f"start to send folder command: {folder_transfer_command_message}")

def start_file_transfer_with_limit(rel_dir, file, root):
"""Handle the operation.

Args:
rel_dir (str): Value used by the operation.
file (str): Value used by the operation.
root (object): Value used by the operation.
"""
cmd = "/file_folder {} {} {}".format(
shlex.quote(rel_dir), shlex.quote(file), shlex.quote(str(client_addr))
)
if destination_path:
cmd += " {}".format(shlex.quote(destination_path))

def limited_transfer():
"""Handle the operation."""
self.file_semaphore.acquire()
try:
self.file_transfer_server_recv_client_start(cmd, root)
finally:
self.file_semaphore.release()

thread = threading.Thread(target=limited_transfer, daemon=True)
thread.start()
self._log(f"start to send file: {cmd} (limit {self.max_file_transfer_thread_num})")

def get_all_files_in_folder():
"""Announce the directories that need it, then send every file."""
needed = _rel_dirs_with_files(folder_path, base_path)
if transfer_path in needed:
send_folder_transfer_command(transfer_path)
for root, _dirs, files in os.walk(folder_path):
rel_dir = get_relative_path(base_path, root)
if root != folder_path and rel_dir in needed:
send_folder_transfer_command(rel_dir)
for file in files:
start_file_transfer_with_limit(rel_dir, file, root)
self._log(f"finished sending all files in folder {folder_path}")

transfer_path = get_relative_path(base_path, folder_path)
get_all_files_in_folder()

def file_transfer_server_recv_client_start_thread(self, message, file_folder_abspath=None):
"""Start a thread to send a file or folder item to a client.

Args:
message (object): Value used by the operation.
file_folder_abspath (str): Value used by the operation.
"""
file_transfer_server_recv_client_start_thread = threading.Thread(
target=self.file_transfer_server_recv_client_start,
args=(message, file_folder_abspath),
daemon=True,
)
file_transfer_server_recv_client_start_thread.start()

def file_transfer_server_recv_client_start(self, message, file_folder_abspath):
"""Send a file or folder item to the addressed connected client.

Args:
message (object): Value used by the operation.
file_folder_abspath (str): Value used by the operation.
"""
client_id = None
command_part = shlex.split(message)
# optional destination directory comes after the client address tuple
if command_part[-1].startswith("(") and command_part[-1].endswith(")"):
client_ip = ast.literal_eval(command_part[-1])
else:
client_ip = ast.literal_eval(command_part[-2])
client_address = client_ip[0]
try:
client_socket = self.clients[client_ip]["socket"]
except:
self._log(
"ErrorWhileSearchingClientSocket: can not find the client socket, file sending failed"
)
self._log_exc()
return False
self._debug(client_socket, client_address, message)
client_id = self._fid_alloc.alloc(receiver=client_ip)
try:
if shlex.split(message.lower())[0] == "/file_folder":
filename = os.path.join(file_folder_abspath, shlex.split(message)[2])
else:
filename = shlex.split(message)[1]
with _sending_transfer(self, (tuple(client_ip), client_id), control_socket=client_socket), \
_transfer_handshake(self, client_socket, client_id) as handshake:
send_msg = f"{message.strip()} {client_id}\n"
if not _send_transfer_request(self, handshake, send_msg):
return False
result = self._transfer_handshakes.wait(handshake, RESUME_PORT_TIMEOUT)
if result is None or result[0] != "port" or result[1] != client_id:
self._log("ErrorWhileReceiveFileServerPort: transfer port waiting timeout, file sending failed")
return False
_, _, file_server_port, stamp = result
file_transfer_client_port = self.palloc()
try:
self.file_transfer_mode(
filename, client_address, file_server_port, file_transfer_client_port,
control_socket=client_socket, crypto=stamp, fid=client_id,
peer=client_ip,
)
finally:
self.pfree(file_transfer_client_port)
except IndexError:
self._log("invalid command, please use '/file <filename>'")
self._log_exc()

def file_transfer_mode( # noqa: PLR0911 - peer-close and timeout exits are distinct outcomes
self,
filename,
server_address,
server_port,
client_port,
control_socket=None,
crypto=None,
fid=None,
peer=None,
resume_offset=0,
trans_type=0,
):
"""Send one file over a transfer sub-connection.

Args:
filename (str): Source file path.
server_address (str): Transfer listener address.
server_port (int): Transfer listener port.
client_port (int): Local port to bind for the transfer.
control_socket (socket.socket | None): Control socket carrying the mode stamp.
crypto (str | None): ``"plain"`` or encrypted transfer stamp.
fid (int | None): Transfer ID used for progress and pause tracking.
peer (tuple | None): Original receiver ``(ip, port)`` for resuming.
resume_offset (int): Byte offset to resume from; defaults to zero.
trans_type (int): 0 ordinary, 1 forwarded.

Returns:
bool: True when the receiver acknowledges the file; otherwise False.
"""
self._log(f"start to send file: {filename}")
receiver = tuple(peer) if peer is not None else (
control_socket.getpeername() if control_socket is not None else (server_address, server_port)
)
transfer_key = (receiver, fid) if fid is not None else None
client_file_socket = None
reset_time = 0
control = None

def close_socket():
"""Handle the operation."""
nonlocal file_running
nonlocal client_file_socket
file_running = False
self._transfer_controls.release_owner(client_file_socket)
self._crypto_drop_channel(client_file_socket)
client_file_socket.close()

while True:
try:
client_file_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if not self._transfer_handshakes.track_socket(control_socket, client_file_socket):
return False
control = _bind_transfer_control(
self, fid, control_socket, client_file_socket, trans_type, 0
)
client_file_socket.bind((self.host, client_port))
client_file_socket.connect((server_address, server_port))
break
except Exception as e:
self._transfer_handshakes.release_socket(control_socket, client_file_socket)
client_file_socket.close()
self._transfer_controls.release_owner(client_file_socket)
if _should_fallback_local_port(client_port, e):
self._log(
f"file transfer source port {client_port} is not available ({e}); "
"retrying from an OS-assigned port"
)
client_port = 0
continue
self._log(f"file transfer connection error: {e}")
self._log_exc()
if reset_time >= 20:
close_socket()
self._log("unable to connect to file transfer server, file sending failed")
return False
reset_time += 1
time.sleep(1)
try:
if crypto and crypto != "plain":
self._crypto_attach_transfer_out(client_file_socket, control_socket, crypto)
except _CryptoUnavailable as exc:
self._log(f"crypto: file transfer aborted: {exc}")
close_socket()
self._transfer_handshakes.release_socket(control_socket, client_file_socket)
return False
file_running = True
self._register_transfer_socket(transfer_key, client_file_socket)
transfer_signs = _TransferSignBuffer(
self.server_start_file_transfer_sign,
self.server_received_file_data_sign,
self.error_sign,
)

def receive_file_transfer_messages():
"""Handle the operation."""
nonlocal file_running
nonlocal client_file_socket
while file_running:
try:
data = self.receive_message(client_file_socket, self.recv_messages_chunk_len)
if not data:
self._log("\nbreak the file transfer connection from server")
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
close_socket()
break
if transfer_signs.feed(data):
self._log(
"\nError sign received from server, file transfer may have failed"
)
close_socket()
break
except Exception as e:
self._log(f"\nget file transfer msg error: {e}")
if not _is_closed_socket_error(e):
self._log_exc()
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
close_socket()
break

receive_thread = threading.Thread(target=receive_file_transfer_messages, daemon=True)
receive_thread.start()
waiting_time = 0
progress = None # this leg's file_upload_progress entry, when tracked
file_sent = False # True once the receiver acknowledged the whole file
source_missing = False # True when the source file no longer exists
try:
while True:
# Snapshot closure before consuming so ACK + EOF cannot race
# a stale empty-queue check into a false failure.
running = file_running
start_seen, _, error_seen = transfer_signs.consume()
if start_seen:
_announce_transfer_control(self, control)
break
if error_seen:
close_socket()
return False
if not running:
# peer closed the file connection: the receive thread
# already cleaned up; nothing more to wait for
return False
time.sleep(1)
waiting_time += 1
if waiting_time >= 10:
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
self._log(
f"ErrorWhileSendFile: \
Wait file transfer function start sign timeout, \
file {filename} sending failed"
)
close_socket()
return False
waiting_time = 0
file_size = os.path.getsize(filename)
file_name_encoded = os.path.basename(filename).encode("utf-8")
name_len = len(file_name_encoded)
self.send_message(client_file_socket, name_len.to_bytes(4, "big"))
self.send_message(client_file_socket, file_name_encoded)
self.send_message(client_file_socket, file_size.to_bytes(8, "big"))
if resume_offset < 0 or resume_offset > file_size:
resume_offset = 0 # not this file's offset any more: send it whole
progress = self._file_progress_start(
self.file_upload_progress, transfer_key, file_size, filename,
peer=peer, initial=resume_offset,
)
if progress is None:
progress = self.file_upload_progress.get(transfer_key)
if progress is not None:
progress[0] = resume_offset
with open(filename, "rb") as f:
if resume_offset:
f.seek(resume_offset)
while f.tell() < file_size:
transfer_signs.consume()
_wait_transfer_control(self, control, client_file_socket)
file_data = f.read(self.file_transfer_chunk_len)
if not file_data:
break
try:
written = self.send_message(client_file_socket, file_data)
except OSError as e:
self._log(f"send error: {e}")
close_socket() # the peer is gone; stop instead of reading the rest
return False
if not written:
self._log("send error: the transfer connection is closed")
close_socket()
return False
self._file_progress_update(progress, len(file_data), is_upload=True)
extra_time = (file_size // (100 * 1024 * 1024)) * 10
timeout = int(30 + extra_time)
while True:
running = file_running
_, ack_seen, error_seen = transfer_signs.consume()
if ack_seen:
break
if error_seen:
close_socket()
return False
if not running:
# peer closed the file connection: the receive thread
# already cleaned up; nothing more to wait for
return False
time.sleep(1)
waiting_time += 1
if waiting_time >= timeout:
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
close_socket()
self._log(
f"ErrorWhileSendFileData: \
wait file transfer confirmation sign timeout, \
file {filename} sending may have failed"
)
return False
file_sent = True
self._log(f"Success: file {filename} sent successfully")
close_socket()
return True
except FileNotFoundError:
# the source is gone: this transfer cannot be resumed later
source_missing = True
self._log_exc()
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
close_socket()
self._log(f"file {filename} not exist")
return False
except Exception as e:
if not _is_closed_socket_error(e):
self._log_exc()
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
close_socket()
self._log(f"send error: {e}")
return False
finally:
self._file_progress_finish(
self.file_upload_progress, transfer_key, progress,
keep=(
not file_sent
and not source_missing
and progress is not None
and progress[4] is not None
),
)
self._release_transfer_socket(transfer_key, client_file_socket)
self._transfer_handshakes.release_socket(control_socket, client_file_socket)

# ---- transfer reconnect (server side) ----------------------------------

def _request_resumes(self, peer, *, control_socket=None):
"""Ask a peer that just connected to continue this side's interrupted downloads.

Reads the persisted stores back (`_load_transfer_progress`). Every download
this instance was receiving from ``peer`` gets its offset set to the bytes
already on disk, and the unified origin/target request is sent; the sender
answers with ``/file <name> <fid>`` and the continued leg is received by
`file_transfer_mode_recv`. Uploads need no action here.

Args:
peer (tuple): Peer ``(ip, port)`` that just connected.

Returns:
int: Number of resume requests sent.
"""
restored = self._load_transfer_progress()
if restored:
self._log(f"transfer reconnect: restored {restored} interrupted transfer(s)")
peer = tuple(peer)
with self.client_lock:
info = self.clients.get(peer)
if (info is None or control_socket is not None and info["socket"] is not control_socket
or not self._wait_control_secure(info["socket"])):
return 0
target = self._control_local_endpoint(info["socket"])
started = 0
for fid, entry in list(self.file_recv_progress.items()):
if entry[4] is None or tuple(entry[4]) != peer:
continue # not a download from this peer
if self._lookup_fid_route(None, fid) is not None:
continue # a forwarded transfer: its target drives the resume
if _request_receive_resume(self, fid, entry, info["socket"], peer, target):
started += 1
return started

def resume_trans(self, peer_addr, fid, offset):
"""Reserve ordinary recovery from this receiver's existing upload row.

Args:
peer_addr (tuple | None): Receiver ``(ip, port)`` for this upload.
fid (int): Transfer id of the interrupted transfer.
offset (int): Byte offset the receiver already holds.

Returns:
bool: True only for a newly reserved ordinary recovery worker.
"""
if peer_addr is None:
return False
peer_addr = tuple(peer_addr)
with self.client_lock:
info = self.clients.get(peer_addr)
if info is None:
return False
return self._resume_on_socket(peer_addr, fid, offset, info["socket"])

def _resume_on_socket(self, peer_addr, fid, offset, control_socket):
"""Use the validated receiver session, not a replacement at the same peer."""
key = (peer_addr, fid)
entry = self.file_upload_progress.get(key)
if entry is None or entry[4] is None or tuple(entry[4]) != peer_addr:
self._log(f"resume: no outgoing transfer {fid} for {peer_addr}")
return False
with self.client_lock:
info = self.clients.get(peer_addr)
if info is None or info["socket"] is not control_socket:
return False

def send(entry):
with _transfer_handshake(self, control_socket, fid) as handshake:
command = f"/file {shlex.quote(os.path.basename(str(entry[3])))} {fid}"
if not _send_transfer_request(self, handshake, command):
return
result = self._transfer_handshakes.wait(handshake, RESUME_PORT_TIMEOUT)
if result is None or result[0] != "port" or result[1] != fid:
self._log(f"resume: {peer_addr} did not announce a transfer port for {fid}")
return
_, _, port, stamp = result
client_port = self.palloc()
try:
self.file_transfer_mode(
entry[3], peer_addr[0], port, client_port,
control_socket=control_socket, crypto=stamp, fid=fid,
peer=peer_addr, resume_offset=offset,
)
finally:
self.pfree(client_port)

return _start_resume_send(self, key, peer_addr, send, control_socket=control_socket)


def _is_control_local_endpoint(self, endpoint, sock):
"""Report whether ``endpoint`` names this control connection's local side.

The concrete address the kernel chose (a wildcard bind or a host alias
resolves to it) and the configured address both identify this instance;
either is accepted so a peer that learned the name from configuration and
one that learned it from the connection agree.

Args:
endpoint (tuple): ``(ip, port)`` sent on the wire.
sock (socket.socket | tuple | None): Control socket the line arrived
on, or the peer ``(ip, port)`` when it is not available.

Returns:
bool: True when the endpoint is this side of that connection.
"""
connected_endpoint = tuple(sock) if isinstance(sock, tuple) else _socket_local_endpoint(sock)
return _is_control_endpoint(endpoint, (self.host, self.port), connected_endpoint)

def _control_local_endpoint(self, sock):
"""Return the endpoint this instance advertises on a control connection.

Args:
sock (socket.socket | tuple | None): Control socket of the
reconnected peer, or its ``(ip, port)``.

Returns:
tuple: The concrete local ``(ip, port)``, or the configured address
when the socket is already gone.
"""
if isinstance(sock, tuple):
return tuple(sock)
return _socket_local_endpoint(sock) or (self.host, self.port)

def _resume_request(self, client_socket, client_address, fid, offset, origin, target):
"""Validate the actual requester before registering background recovery."""
client_address, origin, target = tuple(client_address), tuple(origin), tuple(target)
with self.client_lock:
info = self.clients.get(client_address)
if (target != client_address or type(offset) is not int or offset < 0
or info is None or info["socket"] is not client_socket):
return False
if self._is_control_local_endpoint(origin, client_socket):
return self._resume_on_socket(client_address, fid, offset, client_socket)
found = self._lookup_fid_route(client_address, fid)
if found is not None:
upstream, route = found
if route["originator"] == origin:
return self._queue_resume_to_originator(
upstream, route, target, offset, control_socket=client_socket)
return False
self._log(f"resume: transfer {format_fid(fid)} has no matching origin/target route")
return False

def _queue_resume_to_originator(self, fid, route, target_addr, offset, *, control_socket):
"""Retain one receiver's numeric request without interrupting its route."""
target = tuple(target_addr)
with self.client_lock:
info = self.clients.get(target)
with self._transfer_progress_lock, self._forward_relays_lock:
if (self._progress_discarded or self._fid_routes.get(fid) is not route
or target not in route["targets"] or target in route["completed"]
or type(offset) is not int or offset < 0 or info is None
or info["socket"] is not control_socket):
return False
state = self._relay_recoveries.get(fid)
if state is None:
state = {"route": route, "pending": {}, "active": {},
"control": {"control_lock": threading.RLock(),
"requested": None, "controls": {}}}
self._relay_recoveries[fid] = state
active = state["active"].get(target)
if (active is not None and active["target_socket"] is control_socket
or state["pending"].get(target) == (control_socket, offset)):
return False
state["pending"][target] = (control_socket, offset)
self._flush_pending_originator_resumes(route["originator"])
return True

def _flush_pending_originator_resumes(self, peer, *, control_socket=None):
"""Admit every ready Target after the original route's last owner exits."""
peer = tuple(peer)
with self.client_lock:
online = dict(self.clients)
if control_socket is not None and online.get(peer, {}).get("socket") is not control_socket:
return 0
workers = []
with self._transfer_progress_lock, self._forward_relays_lock:
if not self.running or self._progress_discarded:
return 0
for fid, state in self._relay_recoveries.items():
route = state["route"]
if (self._fid_routes.get(fid) is not route
or peer != route["originator"] and peer not in route["targets"]
or fid in self._receive_transfers):
continue
source = online.get(route["originator"])
for target, (sock, offset) in list(state["pending"].items()):
if (target in route["completed"]
or online.get(target, {}).get("socket") is not sock
or sock.fileno() < 0 or self._transfer_handshakes.closed(sock)):
del state["pending"][target]
continue
if (target in state["active"] or source is None
or self._transfer_handshakes.closed(source["socket"])):
continue
record = _claim_receive(self, (target, fid), source["socket"])
if record is None:
continue
reservation = {"record": record, "source_socket": source["socket"],
"target_socket": sock, "offset": offset}
state["active"][target] = reservation
del state["pending"][target]
workers.append((fid, state, target, reservation))
for args in workers:
threading.Thread(target=self._run_relay_recovery, args=args, daemon=True).start()
return len(workers)

def _run_relay_recovery(self, fid, state, target, reservation):
"""One Target's port setup/cleanup cannot wait for a sibling's body."""
source, target_socket = reservation["source_socket"], reservation["target_socket"]
record, key = reservation["record"], (target, fid)
try:
if not self._wait_control_secure(source) or not self._wait_control_secure(target_socket):
return
with self.client_lock:
if (self.clients.get(state["route"]["originator"], {}).get("socket") is not source
or self.clients.get(target, {}).get("socket") is not target_socket):
return
if not self.send_message(source, format_resume_line(
fid, reservation["offset"], state["route"]["originator"], target
)):
return
with self._transfer_progress_changed:
self._transfer_progress_changed.wait_for(lambda:
self._receive_transfers.get(key) is not record or record["owner"] is not None
or not self.running or self._transfer_handshakes.closed(source)
or self._transfer_handshakes.closed(target_socket),
timeout=RESUME_ACCEPT_TIMEOUT)
except (OSError, RuntimeError) as exc:
self._log(f"forward: recovery {fid} to {target} interrupted: {exc}")
finally:
with self._transfer_progress_changed:
if record["owner"] is not None:
self._transfer_progress_changed.wait_for(lambda:
self._receive_transfers.get(key) is not record)
_release_receive(self, key, record)
with self._transfer_progress_lock, self._forward_relays_lock:
if state["active"].get(target) is reservation:
del state["active"][target]
self._transfer_progress_changed.notify_all()
self._flush_pending_originator_resumes(state["route"]["originator"])

def _resume_after_connect(self, client_address, control_socket, retired):
"""Drain only captured old owners, then resume through the admitted socket."""
for session in retired:
_wait_transfer_session(self, session)
self._request_resumes(tuple(client_address), control_socket=control_socket)
self._flush_pending_originator_resumes(tuple(client_address), control_socket=control_socket)

# ---- native in-memory forward relay (server side) ----------------------

def _forward_notify_error(self, sock, msg, fid):
"""Return one forwarding setup failure to its socket/FID negotiation."""
if fid is None:
return
try:
self.send_message(sock, f"/forward_error {fid} {shlex.quote(str(msg))}")
except Exception:
pass

def _forward_parse_items_addrs(self, tokens):
"""Handle the operation.

Args:
tokens (list | dict): Value used by the operation.

Returns:
list | tuple: Result produced by the operation.
"""
items = []
addrs = []
for token in tokens:
if token.startswith("(") and token.endswith(")"):
try:
addr = ast.literal_eval(token)
except (ValueError, SyntaxError):
items.append(token)
continue
if isinstance(addr, tuple) and len(addr) == 2 and isinstance(addr[0], str):
addrs.append(addr)
else:
items.append(token)
else:
items.append(token)
return items, addrs

def _forward_item_handler(self, sock, addr, cmd):
"""Start a relay whose upstream FID was allocated by the sender."""
try:
parts = shlex.split(cmd)
except ValueError:
return
if len(parts) < 4:
self._log("forward: rejected command without an upstream FID")
return
kind = parts[1].lower()
rest = parts[2:]
upstream_fid = None
resume_requested = False
resume_offset = 0
while rest and rest[0].startswith(("resume=", "fid=")):
option, value = rest.pop(0).split("=", 1)
try:
number = int(value)
if number < 0:
raise ValueError
except ValueError:
self._forward_notify_error(sock, f"invalid {option}", upstream_fid)
return
if option == "resume":
if resume_requested:
self._forward_notify_error(sock, "duplicate resume", upstream_fid)
return
resume_offset = number
resume_requested = True
else:
if upstream_fid is not None:
self._forward_notify_error(sock, "duplicate fid", upstream_fid)
return
upstream_fid = number
if upstream_fid is None:
self._log("forward: rejected command without an upstream FID")
return
destination_path = None
if rest and not (rest[-1].startswith("(") and rest[-1].endswith(")")):
destination_path = rest[-1]
rest = rest[:-1]
items, addrs = self._forward_parse_items_addrs(rest)
confirmation_route = None
with self._forward_relays_lock:
route = self._fid_routes.get(upstream_fid)
if (resume_requested and route is not None and route["targets"]
and route["completed"] == route["targets"].keys()):
confirmation_route = route
if confirmation_route is not None:
with self.client_lock:
current = self.clients.get(tuple(addr), {}).get("socket") is sock
if (not current or confirmation_route["originator"] != tuple(addr)
or len(addrs) != 1 or addrs[0] not in confirmation_route["targets"]):
self._forward_notify_error(sock, "invalid completed relay owner or target", upstream_fid)
return
valid_targets = addrs # Completed Targets need not still be connected.
else:
valid_targets = []
for target in addrs:
if target == (self.host, self.port):
self._log(f"forward: target {target} is the server itself, skipped")
continue
if target not in self.clients:
self._log(f"forward: target {target} is unreachable, skipped")
continue
valid_targets.append(target)
if not valid_targets:
self._forward_notify_error(sock, "no reachable targets to forward to", upstream_fid)
return
if kind == "file":
if not items:
self._forward_notify_error(sock, "missing file name", upstream_fid)
return
rel_dir, fname = "", items[0]
elif kind == "folder":
if len(items) < 2:
self._forward_notify_error(sock, "missing folder file", upstream_fid)
return
rel_dir, fname = items[0], items[1]
else:
self._forward_notify_error(sock, f"unknown forward kind: {kind}", upstream_fid)
return
threading.Thread(
target=self._forward_relay,
args=(sock, addr, kind, rel_dir, fname, valid_targets, destination_path, resume_offset),
kwargs={
"upstream_fid": upstream_fid,
"resume_requested": resume_requested,
"expected_route": confirmation_route,
},
daemon=True,
).start()

def _forward_read_sign(self, sock, sign, timeout=15):
"""Read from a target transfer socket until ``sign`` is seen.

Reads through `receive_message`, so a framed transfer connection
yields decrypted bytes here like any other plaintext leg.

Args:
sock (object): Value used by the operation.
sign (object): Value used by the operation.
timeout (float): Value used by the operation.

Returns:
bytes | None: The decoded requested marker, or None on failure.
"""
buf = b""
target = sign.encode("utf-8")
err = self.error_sign.encode("utf-8")
overlap = max(len(target), len(err)) - 1
if overlap >= TRANSFER_SIGN_BUFFER_LIMIT:
return None
deadline = time.monotonic() + timeout
previous_timeout = sock.gettimeout()
try:
while time.monotonic() < deadline:
sock.settimeout(max(0.001, deadline - time.monotonic()))
try:
data = self.receive_message(sock, self.recv_messages_chunk_len)
except Exception:
return None
if not data:
return None
offset = 0
matched = False
while offset < len(data):
end = min(len(data), offset + TRANSFER_SIGN_BUFFER_LIMIT - len(buf))
window = buf + data[offset:end]
offset = end
if err in window:
return None
matched |= target in window
buf = window[-overlap:] if overlap else b""
# Scan the whole read before accepting a match: a later error
# in that same read still takes precedence, as before.
if matched:
return target
return None
finally:
if sock.fileno() != -1:
sock.settimeout(previous_timeout)

def _forward_recv_exact(self, sock, n):
"""Handle the operation.

Args:
sock (object): Value used by the operation.
n (int): Value used by the operation.

Returns:
object: Result produced by the operation.

Raises:
ConnectionError: When the operation cannot complete.
"""
buf = b""
while len(buf) < n:
data = self.receive_message(sock, n - len(buf))
if not data:
raise ConnectionError("forward: uploader closed the stream")
buf += data
return buf


def _forward_relay(
self,
forwarder_sock,
originator_addr,
kind,
rel_dir,
fname,
targets,
destination_path=None,
resume_offset=0,
upstream_fid=None,
resume_requested=False,
expected_route=None,
):
"""Relay one file/folder item to every target, streaming from the

uploader's transfer connection with bounded in-memory buffering.

Every pushed command is tagged with the originator's address (see
``forward_item_to``) so the receivers can attribute the transfer.

Args:
forwarder_sock (object): Value used by the operation.
originator_addr (tuple): Value used by the operation.
kind (object): Value used by the operation.
rel_dir (str): Value used by the operation.
fname (object): Value used by the operation.
targets (object): Value used by the operation.
destination_path (str): Value used by the operation.
resume_offset (object): Value used by the operation.
upstream_fid (int): Upstream ID allocated by the source sender.
"""
targets = list(dict.fromkeys(tuple(target) for target in targets))
fid = upstream_fid
if fid is None:
self._log("forward: rejected relay without an upstream FID")
return
recovery: dict | None = None
reservation = None
eof_confirmation = False
with self.client_lock:
current_source = self.clients.get(tuple(originator_addr), {}).get("socket") is forwarder_sock
if resume_requested:
with self._forward_relays_lock:
route = self._fid_routes.get(fid)
recovery = self._relay_recoveries.get(fid)
reservation = recovery["active"].get(targets[0]) if recovery and len(targets) == 1 else None
eof_confirmation = bool(route and route["targets"]
and route["completed"] == route["targets"].keys())
if (route is None or route["originator"] != tuple(originator_addr)
or len(targets) != 1 or targets[0] not in route["targets"]
or targets[0] in route["completed"] and not eof_confirmation
or expected_route is not None and route is not expected_route
or eof_confirmation and not current_source
or reservation is not None and (
reservation["offset"] != resume_offset
or reservation["source_socket"] is not forwarder_sock)):
self._forward_notify_error(
forwarder_sock, "no pending relay target for this sender", fid
)
return
tfids = [route["targets"][target] for target in targets]
else:
tfids = [self._fid_alloc.alloc(receiver=target) for target in targets]
route = None # assigned to the relay only after receive admission
manual_recovery = resume_requested and reservation is None and not eof_confirmation
relay: dict = {
"cond": threading.Condition(),
"control_lock": threading.RLock(), "requested": None,
"done": threading.Event(),
"sockets": [], "handshakes": {},
"controls": {},
"route": route,
"fid": fid,
"confirm_eof": eof_confirmation,
}
relay_keys = [(target, tfid) for target, tfid in zip(targets, tfids)]
receive_key = (targets[0], fid) if resume_requested and not eof_confirmation else fid
receive_record = None
if route is None: # only new relays reach admission without a route
receive_record = self._admit_new_relay(
relay, forwarder_sock, originator_addr, dict(relay_keys)
)
else:
with self._transfer_progress_lock, self._forward_relays_lock:
confirmation_busy = eof_confirmation and (
any(key == fid or isinstance(key, tuple) and key[1] == fid
and key[0] in route["targets"] for key in self._receive_transfers)
or any(candidate["fid"] == fid for candidate in self._forward_relays.values())
or recovery is not None and bool(recovery["active"])
)
if (self._fid_routes.get(fid) is route
and not confirmation_busy and fid not in self._receive_transfers
and (reservation is None
or self._receive_transfers.get(receive_key) is reservation["record"])
and not any(key in self._forward_relays for key in relay_keys)):
receive_record = _claim_receive(self, receive_key, forwarder_sock, relay)
if receive_record is not None:
for key in relay_keys:
self._forward_relays[key] = relay
if recovery is None and not eof_confirmation:
recovery = {"route": route, "pending": {}, "active": {},
"control": {"control_lock": threading.RLock(),
"requested": None, "controls": {}}}
self._relay_recoveries[fid] = recovery
if manual_recovery and recovery is not None:
reservation = {
"record": receive_record, "source_socket": forwarder_sock,
"target_socket": self.clients.get(targets[0], {}).get("socket"),
"offset": resume_offset,
}
recovery["active"][targets[0]] = reservation
if receive_record is None:
reason = ("relay source is already active" if resume_requested
else "relay fid is already in use")
self._forward_notify_error(forwarder_sock, reason, fid)
return
control_group: dict = recovery["control"] if recovery is not None and not eof_confirmation else relay
if os.path.exists(self.file_trans_progress_file):
self._persist_transfer_progress()
target_conns = []
up_sock = up_client = None
sport = None
allocated_sport = None
target_handshakes = relay["handshakes"]
owned_sockets = relay["sockets"]
terminal_sent = False
relay_targets = [] if eof_confirmation else list(zip(targets, tfids))

def fail(message):
nonlocal terminal_sent
if not terminal_sent:
terminal_sent = True
self._forward_notify_error(forwarder_sock, message, fid)

def own(control, transfer):
with relay["cond"]:
if not self._transfer_handshakes.track_socket(control, transfer):
return False
owned_sockets.append((control, transfer))
if (reservation is not None and control is forwarder_sock
and reservation["target_socket"] is not control):
target_control = reservation["target_socket"]
if not self._transfer_handshakes.track_socket(target_control, transfer):
return False
owned_sockets.append((target_control, transfer))
return True

try:
for target, tfid in relay_targets:
with relay["cond"]:
target_control = (reservation["target_socket"] if reservation is not None
else self.clients.get(target, {}).get("socket"))
handshake = (self._transfer_handshakes.register(target_control, tfid)
if target_control is not None else None)
if handshake is not None:
target_handshakes[(target, tfid)] = handshake
if handshake is None:
fail(f"target {target} has no available listener negotiation")
return
for target, tfid in relay_targets:
with relay["cond"]:
sent = self.forward_item_to(
target, kind, rel_dir, fname, originator_addr, tfid, destination_path)
if not sent:
fail(f"could not request a listener from {target}")
return
results = self._transfer_handshakes.wait_many(
tuple(target_handshakes.values()), 20.0
)
if results is None:
fail("target port setup timed out")
return
ports = {}
for target, tfid in relay_targets:
result = results[target_handshakes[(target, tfid)]["key"]]
if result[0] != "port":
fail(f"target {target} rejected its listener")
return
ports[(target, tfid)] = (result[2], result[3])
# connect to each target and wait for its start sign
for target, tfid in relay_targets:
tport, stamp = ports[(target, tfid)]
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
target_control = target_handshakes[(target, tfid)]["key"][0]
if not own(target_control, sock) or not own(forwarder_sock, sock):
return
with control_group["control_lock"]:
control = _bind_transfer_control(self, tfid, target_control, sock, 1, 0, relay=control_group)
relay["controls"][target] = control
control_group["controls"][target] = control
try:
sock.connect((target[0], tport))
except Exception as e:
self._log(f"forward: cannot connect to target {target}: {e}")
self._transfer_controls.release_owner(sock)
sock.close()
continue
try:
self._crypto_attach_transfer_out(sock, target_control, stamp)
except _CryptoUnavailable as exc:
self._log(f"forward: target {target} transfer aborted: {exc}")
self._transfer_controls.release_owner(sock)
sock.close()
continue
if not self._forward_read_sign(sock, self.server_start_file_transfer_sign):
self._log(f"forward: target {target} did not start, skipped")
self._transfer_controls.release_owner(sock)
sock.close()
continue
target_conns.append((tfid, target, sock))
# The target's start sign proves its receiving leg is registered.
_announce_transfer_control(self, control)
with control_group["control_lock"]:
upstream = control_group.get("upstream")
if upstream is not None and self._transfer_controls._live(upstream):
with control["lock"]:
paused = upstream["confirmed_state"]
self._transfer_controls._confirm(control, paused)
self._transfer_controls._send(control, paused, None)
if not target_conns and not eof_confirmation:
fail("no target accepted the transfer")
return
# open the upload listener and hand it to the forwarder
up_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if not own(forwarder_sock, up_sock):
return
up_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
allocated_sport = self.palloc()
sport = _bind_local_port_with_fallback(
up_sock,
(self.host, allocated_sport),
self._log,
"forward listener",
)
up_stamp = self._crypto_transfer_stamp(forwarder_sock)
up_sock.listen(1)
# coordination line: always plaintext, so it also reaches a peer
# that has not finished flipping to framed mode
terminal_sent = True
if not self.send_message(
forwarder_sock, _transfer_port_announcement(sport, fid, up_stamp),
is_send_raw=True,
):
return
up_client, _ = up_sock.accept()
if not own(forwarder_sock, up_client):
return
self._crypto_attach_transfer_in(up_client, forwarder_sock, up_stamp)
with control_group["control_lock"]:
relay["upstream"] = _bind_transfer_control(
self, fid, forwarder_sock, up_client, 1, 1,
relay=control_group, shared=resume_requested,
)
control_group["upstream"] = relay["upstream"]
if control_group.get("requested") is not None:
self._transfer_controls.local(relay["upstream"]["key"], control_group.pop("requested"))
self.send_message(up_client, self.server_start_file_transfer_sign)
self._forward_pump(
up_client, target_conns, forwarder_sock, fid, fname, relay, resume_offset
)
except Exception as exc:
self._log(f"forward: relay {fid} interrupted: {exc}")
fail(f"relay setup interrupted: {exc}")
finally:
for control, transfer in owned_sockets:
self._transfer_controls.release_owner(transfer)
for transfer_socket in [up_client, up_sock, *(sock for _, _, sock in target_conns)]:
if transfer_socket is not None:
self._crypto_drop_channel(transfer_socket)
transfer_socket.close()
if allocated_sport is not None:
self.pfree(allocated_sport)
for handshake in target_handshakes.values():
self._transfer_handshakes.cancel(handshake)
with self._forward_relays_lock:
for key in relay_keys:
if self._forward_relays.get(key) is relay:
del self._forward_relays[key]
for control, transfer in owned_sockets:
self._transfer_handshakes.release_socket(control, transfer)
with relay["cond"]:
owned_sockets.clear()
target_handshakes.clear()
relay["done"].set()
if resume_requested and not eof_confirmation:
with control_group["control_lock"]:
for target, control in relay["controls"].items():
if control_group["controls"].get(target) is control:
del control_group["controls"][target]
_release_receive(self, receive_key, receive_record)
if manual_recovery and recovery is not None:
with self._transfer_progress_lock, self._forward_relays_lock:
if recovery["active"].get(targets[0]) is reservation:
del recovery["active"][targets[0]]
self._transfer_progress_changed.notify_all()
self._flush_pending_originator_resumes(tuple(originator_addr))

def _forward_pump(
self, up_sock, target_conns, forwarder_sock, fid, fname, relay, resume_offset=0
):
"""Pump the uploader's byte stream to every target from memory.

Each downstream copy, including its header, owns server-wide credit
until the writer returns from send_message or discards that copy.

Args:
up_sock (object): Value used by the operation.
target_conns (object): Value used by the operation.
forwarder_sock (object): Value used by the operation.
fid (int): Value used by the operation.
fname (object): Value used by the operation.
relay (object): Value used by the operation.
resume_offset (object): Value used by the operation.

Returns:
int: Targets that acknowledged the whole item (they are the ones
the relay's resume record can be dropped for).
"""
budget = self._forward_budget
cond = budget.cond
controls = relay["controls"]
state = relay["buffer"] = {
"buffered": 0, "backpressured": False, "complete": False, "failed": False,
}
queues = {sock: queue.Queue() for _, _, sock in target_conns}
END = object()
result: dict = {"ok": 0, "ack": None}

def enqueue(chunk):
# Never reserve while reading the uploader. Split by both target
# and available bytes; even a one-byte budget admits a fan-out.
for _, _, sock in target_conns:
offset = 0
with cond:
while offset < len(chunk):
if self._stopped or up_sock.fileno() < 0:
raise ConnectionError("uploader control session closed")
if sock not in queues or sock.fileno() < 0:
break
count = budget.publish(queues[sock], chunk, offset, self.max_mem_buff, state)
if count:
offset += count
else:
state["backpressured"] = True
try:
cond.wait()
finally:
state["backpressured"] = False

def writer(tfid, target, sock):
pending = queues[sock]
try:
while True:
item = pending.get()
if item is END:
break
try:
if not self.send_message(sock, item):
return
finally:
with cond:
budget.release(state, len(item))
if state["complete"]:
ack = self._forward_read_sign(sock, self.server_received_file_data_sign)
if ack is not None and self._complete_fid_target(
fid, relay["route"], target, tfid
):
with cond:
result["ok"] += 1
result["ack"] = ack
except Exception as exc:
self._log(f"forward: target {target} interrupted: {exc}")
finally:
# Detach before draining: a woken reader cannot publish here
# again, and no other consumer can take the discarded items.
with cond:
del queues[sock]
discarded = 0
while not pending.empty():
item = pending.get_nowait()
if item is not END:
discarded += len(item)
with cond:
budget.release(state, discarded)
self._transfer_controls.release_owner(sock)
self._crypto_drop_channel(sock)
sock.close()

def reader():
try:
name_len_b = self._forward_recv_exact(up_sock, 4)
name_len = int.from_bytes(name_len_b, "big")
name_b = self._forward_recv_exact(up_sock, name_len)
size_b = self._forward_recv_exact(up_sock, 8)
file_size = int.from_bytes(size_b, "big")
if not 0 <= resume_offset <= file_size:
raise ValueError("resume offset exceeds the forwarded file")
if relay.get("confirm_eof") and resume_offset != file_size:
raise ValueError("completed relay confirmation requires an EOF offset")
for chunk in (name_len_b, name_b, size_b):
enqueue(chunk)
remaining = file_size - resume_offset
while remaining > 0:
chunk = self._forward_recv_exact(
up_sock, min(self.file_transfer_chunk_len, remaining)
)
remaining -= len(chunk)
enqueue(chunk)
state["complete"] = True
except Exception as exc:
self._log(f"forward: uploader stream interrupted: {exc}")
finally:
state["failed"] = not state["complete"]
if state["failed"]:
for control in controls.values():
self._transfer_controls.release(control)

threads = [
threading.Thread(target=writer, args=(tfid, target, sock), daemon=True)
for tfid, target, sock in target_conns
]
try:
for t in threads:
t.start()
reader()
finally:
with cond:
for pending in queues.values():
pending.put_nowait(END)
for t in threads:
if t.ident is not None:
t.join()
route = relay["route"]
with self._forward_relays_lock:
complete = (
state["complete"]
and self._fid_routes.get(fid) is route
and route["completed"] == route["targets"].keys()
and (result["ack"] is not None or relay.get("confirm_eof", False))
)
if relay.get("confirm_eof"):
with self.client_lock:
complete = complete and self.clients.get(tuple(route["originator"]), {}).get("socket") is forwarder_sock
complete = complete and not self._transfer_handshakes.closed(forwarder_sock)
try:
# Live delivery forwards a real Target ACK. EOF reconfirmation uses
# that route's retained, entirely acknowledged completion set.
# Send it as a protocol line: send_message adds no newline to bytes.
ack = result["ack"]
if relay.get("confirm_eof"):
ack = self.server_received_file_data_sign
elif ack is not None:
ack = ack.decode("ascii")
written = self.send_message(up_sock, ack if complete else self.error_sign)
if complete and written:
self._drop_fid_route(fid, route)
except Exception as exc:
self._log(f"forward: final ACK for {fid} could not be sent: {exc}")
self._log(f"forward: relayed {fname} to {result['ok']}/{len(target_conns)} targets")
return result["ok"]

@_config_lifecycle(starting=True)
def start_TCP_Server(self): # set up server socket
"""Bind the server socket, then accept clients until `stop` runs.

Blocks the calling thread. A console command thread is started when
``is_input_command_in_console`` is True. Every accepted connection is
served by `handle_client`: in its own thread by default, or by a
coroutine on an asyncio event loop when ``is_asynic_clients_io`` is True,
in which case ``max_clients`` no longer limits the connection count.
Socket errors and the end of the accept loop both end in `stop`.
"""
try:
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(
socket.SOMAXCONN if self.is_asynic_clients_io else self.max_clients
)
if self._stopped:
# stop() arrived while the socket was being bound: stay stopped
# instead of reviving the server (its listener would leak)
self.server_socket.close()
return
self.running = True
self._log(f"TCP server deployed on {self.host}:{self.port}")
if self.is_asynic_clients_io:
self._debug("clients io mode: asyncio, max clients mount: no limit")
else:
self._debug(f"max clients mount: {self.max_clients}")
self._log("input '/stop' to stop the server\n")
if self.is_input_command_in_console:
input_thread = threading.Thread(
target=self.console_input, daemon=True
) # set up console input thread
input_thread.start()
else:
pass
if self.is_asynic_clients_io:
asyncio.run(self._accept_clients_async())
else:
self._accept_clients_threaded()
except Exception as e:
self._log(f"Server error: {e}")
self._log_exc()
finally:
self.stop()

def _accept_clients_threaded(self):
"""Accept clients until the server stops, one thread per client."""
while self.running: # main loop to accept clients
try:
client_socket, client_address = self.server_socket.accept()
if len(self.clients) >= self.max_clients:
self.send_message(client_socket, "Max connection mount, try latter")
client_socket.close()
continue
client_thread = threading.Thread( # set up client handling thread
target=self.handle_client, args=(client_socket, client_address), daemon=True
)
client_thread.start()
except OSError as e:
# an accept error while stopping is the expected wake-up from
# stop()'s shutdown(), not a fault worth a traceback
if self.running and not _is_closed_socket_error(e):
self._log(f"accept failed: {e}")
self._log_exc()
break # server socket closed, exit loop

async def _accept_clients_async(self):
"""Accept clients until the server stops, one coroutine per client.

Runs the whole client side on one event loop: the listening socket is
used in non-blocking mode, and every accepted connection is handled by
`handle_client` on this loop, so the connection count is bounded only by
the file-descriptor limit. `stop` completes ``_async_wakeup`` to release
the loop; its remaining client coroutines are cancelled when it ends.
"""
loop = asyncio.get_running_loop()
self._async_loop = loop
wakeup = loop.create_future()
self._async_wakeup = wakeup
try:
self.server_socket.setblocking(False)
while self.running:
accept = loop.create_task(loop.sock_accept(self.server_socket))
done, _ = await asyncio.wait({accept, wakeup}, return_when=asyncio.FIRST_COMPLETED)
if wakeup in done:
if accept.done() and not accept.cancelled() and accept.exception() is None:
accept.result()[0].close() # accepted while stopping: dropped
else:
accept.cancel()
await asyncio.gather(accept, return_exceptions=True)
break
try:
client_socket, client_address = accept.result()
except OSError as e:
if not _is_closed_socket_error(e):
self._log(f"accept failed: {e}")
self._log_exc()
break # server socket closed, exit loop
except Exception as e:
self._log(f"accept loop error: {e}")
self._log_exc()
break
client_socket.setblocking(False)
self.handle_client(client_socket, client_address)
finally:
self._async_loop = None
self._async_wakeup = None

def console_input(self): # deal consule input
"""Read console commands until the server stops.

Handles ``/stop``, ``/status``, ``/clients``, ``/send_msg``, ``/file``,
``/file_folder``, ``/multiple_file_multiple_client``, ``/transfers``,
``/diff_multiple_file_diff_multiple_client`` and ``/help``; the forward
commands are client-only and are refused here. Any other name goes to the
handlers registered with ``where_to_run="client"``. Ctrl-C and EOF stop the
server.
"""
while self.running:
try:
cmd = input()
deal_cmd = cmd.strip()
if deal_cmd.lower() == "/stop":
self._log("shutting down...")
self.running = False
self.stop()
elif deal_cmd.lower().split(maxsplit=1)[:1] == ["/transfers"]:
if deal_cmd.lower() != "/transfers":
print("Usage: /transfers")
else:
print(json.dumps(self.get_transfer_progress(), ensure_ascii=False, indent=2))
elif deal_cmd.lower() == "/status":
self._log(f"current connection count: {len(self.clients)}")
self._log(f"server running: {self.running}")
elif deal_cmd.lower() == "/clients":
with self.client_lock:
for addr, info in self.clients.items():
self._log(f" {info['id']} - connection time: {info['connected_time']}")
elif shlex.split(deal_cmd)[0].lower() == "/send_msg":
self.send_msg_to_specific_client(deal_cmd)
elif shlex.split(deal_cmd)[0].lower() == "/file":
self.file_transfer_server_recv_client_start_thread(deal_cmd)
elif shlex.split(deal_cmd)[0].lower() == "/file_folder":
self.folder_file_transfer_server_recv_client_start(deal_cmd)
elif shlex.split(deal_cmd)[0].lower() == "/multiple_file_multiple_client":
self.multiple_file_multiple_client_transfer_server_recv_client_start(deal_cmd)
elif shlex.split(deal_cmd)[0].lower() == "/diff_multiple_file_diff_multiple_client":
self.diff_multiple_file_diff_multiple_client_transfer_server_recv_client_start(
deal_cmd
)
elif shlex.split(deal_cmd)[0].lower() in (
"/forward_send_msg",
"/forward_file",
"/forward_folder",
):
self._log(
"forward commands are client-only; "
"run them on a client console, not on the server"
)
elif shlex.split(deal_cmd)[0].lower() == "/help":
help_text = [
"avalable commands:",
"/stop - stop the server\n",
"\t/status - display server status\n",
"\t/clients - display connected clients\n",
"\t/transfers - inspect local memory and persisted transfer progress\n",
"\t/send_msg <message1> <message2> ... ",
"<client_id1> <client_id2> ... <messageN>",
" ... <client_idN> ... - send message or ",
"messages to specific client or clients\n",
"\t/file <file_path> <client_id> [destination_file_path] - ",
"send file to specific client\n",
"\t/file_folder <folder_path> <client_id> [destination_file_path] - ",
"send folder to specific client\n",
"\t/multiple_file_multiple_client <file1> <file2>",
" ... <client_id1> <client_id2> ... <fileN> ...",
" <client_idN> ... - send multiple files to multiple",
" clients, files should be before clients, ",
"and clients should be in format of (ip, port)\n",
"\t/diff_multiple_file_diff_multiple_client <file1> <file2>",
" ... <client_id1> <client_id2> ... <fileN> ...",
" <client_idN> ... - send multiple files to multiple clients",
" with different file list for each client, files and clients",
" should be in pairs, and clients should be in format of (ip, port)",
]
self._log("\n" + " ".join(help_text) + "\n")
else:
cmd_parts = shlex.split(deal_cmd)
if not cmd_parts:
return None
cmd_name = cmd_parts[0].lower()
if cmd_name in self._custom_handlers[1]:
handler = self._custom_handlers[1][cmd_name]
run_in_thread = self._custom_handler_threaded[1].get(cmd_name, False)
if run_in_thread:
self.submit_task(self._execute_custom_handler, handler, deal_cmd)
pass
else:
response = self._execute_custom_handler(handler, deal_cmd)
pass
else:
self._log("Unrecognized command, input '/help' for available commands")
except KeyboardInterrupt:
self._log("\nKeyboardInterrupt received, shutting down...")
self.running = False
self.stop()
break
except EOFError:
self._log("EOF received, shutting down...")
self.running = False
self.stop()
break
except Exception as e:
self._log(f"console command error: {e}")
self._log_exc()
pass

@_config_lifecycle(starting=False)
def stop(self): # shutting down the server
"""Stop the server and release everything it owns.

Closes the server socket and every client connection, flushes the message
and event stores, releases the allocated port range, clears ``running``
and releases the client event loop when ``is_asynic_clients_io`` is True.
Safe to call more than once.
Waits for accepted custom tasks unless called by this instance's own
worker. A handler that never returns can block an external stop indefinitely.
Safe to call more than once; the instance cannot restart.
"""
self._custom_executor.close(self._retire_server, self._flush_record_stores)

def _retire_server(self):
self.running = False
self._stopped = True # also cancels a start_TCP_Server() still binding
self._stop_listeners()
self.free_port()
self._flush_record_stores()
# in-flight transfers die with the server: persist them for the next run
self._persist_transfer_progress()
with self.client_lock:
clients = list(self.clients.values())
self.clients.clear()
for client_info in clients:
_retire_transfer_session(self, client_info["socket"])
try:
# Wake the control reader as well as its cancelled data legs.
client_info["socket"].shutdown(socket.SHUT_RDWR)
except OSError:
pass # already disconnected
try:
client_info["socket"].close()
except OSError:
self._log_exc()
if self.server_socket: # close server socket
try:
# close() alone does not release the port: a thread blocked in
# accept() keeps the descriptor open until the syscall returns,
# so the listener would stay up. shutdown() ends that accept
# immediately (the loop treats the error as the stop signal).
self.server_socket.shutdown(socket.SHUT_RDWR)
except OSError:
pass # not connected / already shut down
self.server_socket.close()
self._log("server stopped")
self._wake_async_accept_loop()
self.free_port()
# in-flight transfers die with the server: persist them for the next run
self._persist_transfer_progress()

def _wake_async_accept_loop(self):
"""Release the accept coroutine, if any, so its event loop can end."""
loop = self._async_loop
wakeup = self._async_wakeup
if loop is None or loop.is_closed() or wakeup is None or wakeup.done():
return
try:
loop.call_soon_threadsafe(wakeup.set_result, None)
except RuntimeError:
self._log_exc()


class TCP_Client_Base: # TCP client class
"""TCP client: connect to a server, dispatch commands, send and receive messages.

Lines received from the server go through `receive_messages`: every line is
delivered to the listeners registered with `add_message_listener` first
(commands included; a forwarded ``/send_msg_from`` envelope is delivered as
its payload), then a line starting with ``/`` is handled by
`handle_server_command` (protocol commands plus the handlers registered for
the "server" side), any other line is stored in ``messages_dict`` as a plain
message. With ``is_input_command_in_console`` the console thread
`interactive_mode` sends typed lines to the server.

Attributes:
host (str): Server address this client connects to.
port (int): Server port this client connects to.
client_host (str): Local address the socket binds to.
client_port (int | None): Local port, None when the OS chose one.
running (bool): True while the connection is up.
is_enable_encrypto (bool): Whether the RSA channel is negotiated.
is_debug (bool): Whether execution-process lines are logged as well.
is_print_log (bool): Whether the instance logs anything at all.
is_enable_file_transfer_progress_bar (bool): Whether every running file
transfer is tracked in ``file_recv_progress``/``file_upload_progress``.
is_enable_real_time_network_speed (bool): Whether the real-time network
speed is measured into ``upload_network_speed``/``recv_network_speed``.
is_auto_reconnect (bool): Whether `start_TCP_client` reconnects after
the connection drops (and resumes the interrupted transfers).
file_recv_progress (dict): Running downloads keyed by fid; each value is
``[received bytes, total bytes, current speed, file path, peer]``
(the speed is None until the transfer has moved its first chunk,
and while speed measurement is off; ``peer`` is the sender's
``(ip, port)``).
file_upload_progress (dict): Running uploads keyed by fid; each value is
``[sent bytes, total bytes, current speed, file path, peer]``, with
``peer`` the receiver's ``(ip, port)``. A forwarded transfer stores
the original peer on both sides, never the relay.
file_trans_progress_file (str): Path under the protocol's ``.Flow``
directory where the two stores are written when the connection
drops and read back on the next reconnect (`_request_resumes`).
upload_network_speed (float | None): Bytes per second sent, or None when
not measured.
recv_network_speed (float | None): Bytes per second received, or None
when not measured.
"""

def __init__(
self,
host=None,
client_host="127.0.0.1",
port=65432,
client_port=None,
timeout=None,
port_add_step=1,
max_thread_num=10,
is_input_command_in_console=True,
is_wait_server=True,
max_custom_workers=10,
is_extend_command=False,
is_enable_encrypto=True,
is_custom_keys=None,
max_mem_buff=2048,
recv_messages_chunk_len=4096,
file_transfer_chunk_len=65536,
is_debug=False,
is_print_log=True,
is_enable_file_transfer_progress_bar=True,
is_enable_real_time_network_speed=True,
is_auto_reconnect=False,
is_forward_one_to_one=False,
):
"""Create the client and, unless extended, connect and start reading.

Args:
host (str | None): Server address to connect to; required before
`connect` is called.
client_host (str): Local address the socket binds to. Defaults to
"127.0.0.1".
port (int): Server port. Defaults to 65432.
client_port (int | None): Local port to bind; None lets the OS choose
an ephemeral port.
timeout (float | None): Socket timeout in seconds for connect and
receive. Must be None when ``is_wait_server`` is True.
port_add_step (int): Step between candidate ports in the allocation
range. Defaults to 1.
max_thread_num (int): Concurrent file transfers allowed. Defaults to 10.
is_input_command_in_console (bool): Enter interactive mode after
connecting. Defaults to True.
is_wait_server (bool): Keep retrying while the server is not reachable.
Defaults to True.
max_custom_workers (int): Worker slots for `submit_task` and threaded
command handlers. Defaults to 10.
is_extend_command (bool): When True, do not call `start_TCP_client`; the
caller connects when ready. Defaults to False.
is_enable_encrypto (bool): Negotiate the RSA-encrypted channel with the
server. Defaults to True.
is_custom_keys (list | None): ``[pub_key_path, pvt_key_path]`` pair used
instead of the default key lookup; an invalid pair is ignored.
max_mem_buff (int): Buffer ceiling in MiB, kept for parity with the
server class; the client's forward path does not read it today.
Defaults to 2048.
recv_messages_chunk_len (int): Bytes read per receive on the control
connection, covering commands and messages. Defaults to 4096.
file_transfer_chunk_len (int): Chunk size in bytes streamed when
sending or receiving a file or folder. Defaults to 65536 (64 KiB).
is_debug (bool): Log execution-process lines in addition to command
and result lines. Defaults to False.
is_print_log (bool): Log at all; False silences every line this
instance would print. Defaults to True.
is_enable_file_transfer_progress_bar (bool): Track every running
file transfer in ``file_recv_progress`` (downloads) and
``file_upload_progress`` (uploads): each entry holds the bytes
transferred so far, the total size and the current speed (None
while ``is_enable_real_time_network_speed`` is False). An entry
appears when a transfer starts and is dropped when it ends.
Defaults to True.
is_enable_real_time_network_speed (bool): Measure the real-time
network speed of every send and receive — the control layer and
every temporary connection (file transfers included) — into
``upload_network_speed`` and ``recv_network_speed`` (bytes per
second, averaged over ``NETWORK_SPEED_WINDOW`` seconds). With
False nothing is measured and every speed value is None.
Defaults to True.
is_auto_reconnect (bool): Reconnect (and resume the interrupted
transfers, see `_request_resumes`) when the connection drops
while `start_TCP_client` runs. The transfers that died with
the connection are persisted to the protocol's ``.Flow``
directory and read back on the next connect. Defaults to
False: a dropped connection ends the client.
is_forward_one_to_one (bool): Send each native file/target pair as
an independent transfer using a shared file slot. False (the
default) keeps one upload per item for all its targets.

Raises:
ValueError: If ``is_wait_server`` is True and ``timeout`` is not None.
OSError: If the ``.Flow`` directories or ``decode_command_table.json``
cannot be created or read.
"""
self.max_mem_buff = max_mem_buff * 1024 * 1024
self.recv_messages_chunk_len = recv_messages_chunk_len
self.file_transfer_chunk_len = file_transfer_chunk_len
self.is_enable_file_transfer_progress_bar = is_enable_file_transfer_progress_bar
self.is_enable_real_time_network_speed = is_enable_real_time_network_speed
# Per-transfer progress stores: fid -> [transferred bytes, total bytes,
# current speed, local file path, peer (ip, port)]. An entry appears
# when a transfer starts and is removed when it ends; a transfer
# interrupted by a disconnect keeps its entry (and its partial file)
# so it can be resumed once the peer is back (see `_request_resumes`).
self.file_recv_progress = {} # downloads: fid -> [received, total, speed, path, peer]
self.file_upload_progress = {} # (receiver, fid) -> [sent, total, speed, path, peer]
self.upload_network_speed = None # bytes/s over the last NETWORK_SPEED_WINDOW seconds
self.recv_network_speed = None
self._network_speed_lock = threading.Lock() # serialises the speed sample windows
self._upload_speed_samples = collections.deque() # (timestamp, bytes) samples
self._recv_speed_samples = collections.deque()
self._upload_speed_total = 0 # bytes held in the sample windows
self._recv_speed_total = 0
# Outbound-transfer pause switches (see `pause_trans`/`start_trans`):
# (receiver, fid) -> bool, including forwarded uploads to the server.
self._transfer_pause = {}
self._transfer_pause_cond = threading.Condition()
self._transfer_controls = _TransferControlRegistry(
self._transfer_pause, self._transfer_pause_cond, self
)
self._active_transfer_fids = set() # fids of the legs running right now
self._active_transfer_sockets = {} # receive fid / (receiver, fid) -> socket
self.project_dir = os.path.dirname(os.path.abspath(__file__))
self.file_transfer_dir = os.path.join(self.project_dir, "received_files")
self.decode_command_table_file_path = os.path.join(
self.project_dir, "decode_command_table.json"
)
self.project_info_dir = os.path.join(self.project_dir, ".Flow")
if os.path.exists(self.project_info_dir) == False:
os.mkdir(self.project_info_dir)
self.project_temp_info_dir = os.path.join(self.project_info_dir, "temp_info")
self.client_port_lock_file = os.path.join(
self.project_temp_info_dir, "client_port_lock.lock"
)
# Interrupted transfers are persisted here on a disconnect and read
# back when the client reconnects (see `_persist_transfer_progress`).
self.file_trans_progress_file = os.path.join(
self.project_info_dir, "client_file_trans_progress.json"
)
self._transfer_progress_lock = threading.RLock() # serialises the persist/load pair
self._resume_sends = {} # transient locks and request sets; no file metadata
self._transfer_progress_changed = threading.Condition(self._transfer_progress_lock)
self._receive_transfers = {} # request/listener/data owner until final cleanup
self._progress_discarded = False
self._config_started = False
self._config_closed = False
self._config_busy = 0
if os.path.exists(self.project_temp_info_dir) == False:
os.mkdir(self.project_temp_info_dir)
self.all_allocated_ports_list = []
self.is_hand_alloc_port = None
self._transfer_handshakes = _TransferHandshakeRegistry()
self.client_ports_list = []
self.client_port = client_port
self.host = host
self.client_host = client_host
self.port = port
self.port_add_step = port_add_step
self.latest_port = None
self.timeout = timeout
self.client_socket = None
self.running = False
self._stopped = False # a close() before connect() must stick
self.receive_thread = None
self._resume_thread = None
self.command_decode_table_str = None
self.max_thread_num = max_thread_num
self.is_input_command_in_console = is_input_command_in_console
self.is_wait_server = is_wait_server
self.is_auto_reconnect = is_auto_reconnect
self.is_forward_one_to_one = is_forward_one_to_one
if self.is_wait_server and self.timeout != None:
error_msg = [
"wait_server_timeout is not applicable when is_wait_server is True,",
"please set wait_server_timeout to None or set is_wait_server to False",
]
raise ValueError(" ".join(error_msg))
# Transfer ids for the legs this instance sends (see `_FidAllocator`).
# Inbound keys are local integers; outbound keys include the server.
# Forward uploads keep their logical target in the progress value.
self._fid_alloc = _FidAllocator(
(self.file_upload_progress, self.file_recv_progress)
)
MAX_CONCURRENT_FILES = self.max_thread_num
self.file_semaphore = threading.Semaphore(MAX_CONCURRENT_FILES)
with open(self.decode_command_table_file_path, "r", encoding="utf-8") as f:
self.command_decode_table_str = f.read()
self.command_decode_table = ast.literal_eval(self.command_decode_table_str)
self.send_file_header_sign = self.command_decode_table[0]["file_send_server_header"]
self.send_file_data_sign = self.command_decode_table[0]["file_send_server_data"]
self.server_received_file_header_sign = self.command_decode_table[0][
"file_receive_client_header"
]
self.server_received_file_data_sign = self.command_decode_table[0][
"file_receive_client_data"
]
self.server_start_file_transfer_sign = self.command_decode_table[0][
"file_send_server_start_file_transfer"
]
self.error_sign = self.command_decode_table[0]["file_send_receive_error"]
self._custom_handlers = [{}, {}]
self._custom_handler_threaded = [{}, {}]
self._custom_executor = ThreadPoolExecutor(max_workers=max_custom_workers)
self._task_semaphore = threading.Semaphore(max_custom_workers)
self._custom_executor = _CustomCommandExecutor(max_custom_workers)
# Inbound/outbound event listeners (see add_message_listener and
# add_file_listener). They run on the thread performing the relevant
# I/O; a listener must not block and its exceptions are swallowed by
# the notify helpers.
self._message_listeners = []
self._file_listeners = []
self._send_message_listeners = []
# Set by close(); a closed instance never invokes a listener again.
self._listeners_stopped = False
self._control_sockets = set() # the control link to the server; only it is recorded
self._event_listeners_lock = threading.Lock()
# Message/event stores: external code reads these instead of registering
# listeners. Keyed by the socket; each value is a list of [content,
# timestamp] pairs. messages_dict and sent_messages_dict hold plain text
# (inbound / outbound); events_dict and sent_events_dict hold "/" commands.
# When a store's total size reaches max_dict_size (64 KiB) it is flushed
# to its JSON log and cleared (see _append_record, _flush_record_stores).
self.messages_dict = {}
self.events_dict = {}
self.sent_messages_dict = {}
self.sent_events_dict = {}
self._messages_dict_lock = threading.Lock()
self._events_dict_lock = threading.Lock()
self._sent_messages_dict_lock = threading.Lock()
self._sent_events_dict_lock = threading.Lock()
self._socket_keys = {} # record key -> "ip:port", captured while it was alive
self._socket_keys_lock = threading.Lock()
self._messages_dict_size = 0
self._events_dict_size = 0
self._sent_messages_dict_size = 0
self._sent_events_dict_size = 0
self.max_dict_size = 64 * 1024
self.messages_log_file = os.path.join(self.project_info_dir, "messages_log.json")
self.events_log_file = os.path.join(self.project_info_dir, "events_log.json")
self.sent_messages_log_file = os.path.join(self.project_info_dir, "sent_messages_log.json")
self.sent_events_log_file = os.path.join(self.project_info_dir, "sent_events_log.json")
self.is_extend_command = is_extend_command
self.is_enable_encrypto = is_enable_encrypto
self.is_custom_keys = is_custom_keys
self.is_debug = is_debug
self.is_print_log = is_print_log
self._crypto_lock = threading.RLock() # serialises the crypto collections (no-GIL safe); held only around short ops, never across I/O
self._encrypted_sockets = set() # sockets currently speaking frames (see _SecureChannel)
self._channels = {} # socket -> _SecureChannel (control and transfer connections)
self._crypto_session = None # the session context, created when crypto is used
self._crypto_peer = {} # socket -> (peer_role, peer_pem_path)
self.crypto = (
rsa_crypto.RsaCrypto("client", self.project_dir, custom_keys=is_custom_keys)
if is_enable_encrypto
else None
)
self._crypto_ack_event = threading.Event()
self._crypto_exchange_done = threading.Event()
self._crypto_server_pub_event = threading.Event()
self._crypto_force = False
self._crypto_push_active = set()
self._crypto_send_lock = threading.Lock() # send+encrypt ordered: wire order == seq order
self._crypto_handshake_gen = 0 # bumped on handshake start; stale flows act/close no-op
self._crypto_mode_event = threading.Event() # set once the server announced its crypto mode
self._crypto_mode_ok = False # server mode matches ours (negotiated at connect)
self._crypto_mode_timeout = 10 # seconds to wait for the server's mode announcement

self._crypto_requested_server_pub = False
self._crypto_server_ready = False
self._crypto_own_ready_sent = False
self._crypto_server_pub_ok = None # None/True/False: TOFU check of server key
self._crypto_server_pem_path = None # cached server public key file
self._crypto_handshake_started = False # a hello was sent/received
self._crypto_my_nonce = None # session nonce we advertise
self._crypto_server_nonce = None # session nonce the server advertises
self._crypto_decode_failures = 0 # consecutive decode failures
if self.is_extend_command:
pass
else:
self.start_TCP_client()

def register_command(self, command_name, handler, where_to_run, run_in_thread=False):
"""Register a custom command handler.

Args:
command_name (str): Command to intercept, e.g. "/my_command"; matched
case-insensitively against the first token.
handler (callable): ``handler(client_socket, client_address, command)``
called with the raw line; a non-None return value is sent back as
the response.
where_to_run (str): "server" for commands pushed by the server, "client"
for commands typed on this instance's console.
run_in_thread (bool): Run the handler on the worker pool instead of the
reader thread. Defaults to False.

Returns:
bool | None: False when ``where_to_run`` is neither "server" nor
"client"; the handler is then not registered.
"""
registe_index = None
if where_to_run == "server":
registe_index = 0
elif where_to_run == "client":
registe_index = 1
else:
self._log(f"Invalid where_to_run value: {where_to_run}, must be 'server' or 'client'")
return False
self._custom_handlers[registe_index][command_name] = handler
self._custom_handler_threaded[registe_index][command_name] = run_in_thread

def call_extension_functions(self, command):
"""Call one registered extension command handler directly from code.

The handler is selected by the first token of ``command``, matched
case-insensitively against the names given to `register_command`: the
console group is searched first, then the group fed by the lines the
server sends. The handler runs on the calling thread — ``run_in_thread``
only affects the console and inbound dispatch paths — and is called
with this client's socket and id, the context its dispatch paths give
it.

Args:
command (str): Command line to run, e.g. ``"/my_command arg"``; the
handler receives it unchanged.

Returns:
object: Whatever the handler returns.

Raises:
CommandNotFoundError: If no registered handler matches the first
token of ``command``.
ValueError: If ``command`` cannot be split (unbalanced quotes).
"""
handler = _custom_handler_for(command, self._custom_handlers)
client_id = f"{self.client_host}:{self.client_port}"
return handler(self.client_socket, client_id, command)

def add_message_listener(self, listener):
"""Register ``listener(sender_id, message)`` for inbound events.

Complete control lines are reported as ``str`` (commands included); a
message forwarded through ``/send_msg_from`` is reported as its
payload. Raw chunks from a non-control socket (file transfer,
forwarding, temporary connection) are reported as ``bytes`` without
line or frame alignment. ``sender_id`` is the forwarding/origin
client's ``"ip:port"``, ``None`` for a direct server push, or the
temporary TCP peer endpoint for a side-channel chunk.

Control-line callbacks run on the client receive thread; raw chunks run
on the thread reading that socket. Callbacks may run concurrently and
must be thread-safe, must not block, and exceptions raised inside them
are swallowed. ``close()`` stops new delivery and clears the list.

Args:
listener (callable): ``listener(sender_id, message)``.
"""
with self._event_listeners_lock:
if listener not in self._message_listeners:
self._message_listeners.append(listener)

def remove_message_listener(self, listener):
"""Unregister a listener previously added by `add_message_listener`.

Args:
listener (callable): Listener to remove; an unknown one is ignored.
"""
with self._event_listeners_lock:
try:
self._message_listeners.remove(listener)
except ValueError:
pass

def add_send_message_listener(self, listener):
"""Register ``listener(target_id, message)`` for successful sends.

Called synchronously on the sending thread after every payload that
`send_message` writes successfully, for ``str`` and ``bytes`` alike.
``str`` payloads are stripped; ``bytes`` are reported unchanged.
``target_id`` is the peer endpoint of the socket that wrote the
payload: the server's ``"ip:port"`` for the control socket, or the
temporary TCP connection's ``"ip:port"`` for a side channel.

``is_send_raw=True`` lines and internal protocol frames such as the
ECDH public-key publication are not reported. When several threads
send on one socket the writes stay serialized, but callback order is
not guaranteed to match wire order; this affects observation only.
The listener must not block, may run concurrently, and its exceptions
are swallowed. ``close()`` stops new delivery.

Args:
listener (callable): ``listener(target_id, message)``.
"""
with self._event_listeners_lock:
if listener not in self._send_message_listeners:
self._send_message_listeners.append(listener)

def remove_send_message_listener(self, listener):
"""Unregister a listener previously added by `add_send_message_listener`.

Args:
listener (callable): Listener to remove; an unknown one is ignored.
"""
with self._event_listeners_lock:
try:
self._send_message_listeners.remove(listener)
except ValueError:
pass

def add_file_listener(self, listener):
"""Register ``listener(full_path, name, size, command)`` per saved inbound file.

Fired once after a file pushed by the server (a direct send or a
forwarded item) is fully written to disk. ``command`` is the wire
command that triggered the transfer, so pushes such as
``/crypto_pub_key`` can be recognised. The callback runs on the transfer
thread before the completion sign is sent (it does not wait for an
ACK); per-chunk data goes to the message listeners as ``bytes``
instead. For ``/crypto_pub_key`` the server key is not registered yet,
so the listener must not move or delete the file. It must not block;
exceptions are swallowed. ``close()`` stops new delivery.

Args:
listener (callable): ``listener(full_path, name, size, command)``.
"""
with self._event_listeners_lock:
if listener not in self._file_listeners:
self._file_listeners.append(listener)

def remove_file_listener(self, listener):
"""Unregister a listener previously added by `add_file_listener`.

Args:
listener (callable): Listener to remove; an unknown one is ignored.
"""
with self._event_listeners_lock:
try:
self._file_listeners.remove(listener)
except ValueError:
pass

def _stop_listeners(self):
"""Stop delivering listener events and release the callback lists."""
with self._event_listeners_lock:
self._listeners_stopped = True
self._message_listeners.clear()
self._file_listeners.clear()
self._send_message_listeners.clear()

def _listeners_are_stopped(self):
"""Return True once close() has disabled listener delivery."""
with self._event_listeners_lock:
return self._listeners_stopped

def _notify_message_received(self, sender, message):
"""Handle the operation.

Args:
sender (object): Value used by the operation.
message (object): Value used by the operation.
"""
with self._event_listeners_lock:
if self._listeners_stopped:
return
listeners = list(self._message_listeners)
for listener in listeners:
if self._listeners_are_stopped():
return
try:
listener(sender, message)
except Exception as e:
self._log(f"message listener error: {e}")
self._log_exc()

def _notify_transfer_chunk(self, client_socket, data):
"""Report one chunk read from a non-control socket to the message listeners.

Side-channel sockets (file/folder transfers, forwards) carry raw bytes and
``sign`` tokens, which belong to the transfer layer, so they are reported
to the listeners but never recorded in a store.
"""
if not data or client_socket in self._control_sockets:
return
with self._event_listeners_lock:
if self._listeners_stopped:
return
listeners = list(self._message_listeners)
for listener in listeners:
if self._listeners_are_stopped():
return
try:
listener(self._socket_key(client_socket), data)
except Exception as e:
self._log(f"message listener error: {e}")
self._log_exc()

def _notify_message_sent(self, client_socket, message):
"""Report one written payload to the send listeners."""
with self._event_listeners_lock:
if self._listeners_stopped:
return
listeners = list(self._send_message_listeners)
if not listeners:
return
target_id = self._socket_key(client_socket)
for listener in listeners:
if self._listeners_are_stopped():
return
try:
listener(target_id, message)
except Exception as e:
self._log(f"send message listener error: {e}")
self._log_exc()

def _notify_file_received(self, full_path, name, size, command):
"""Handle the operation.

Args:
full_path (str): Value used by the operation.
name (object): Value used by the operation.
size (int): Value used by the operation.
command (object): Value used by the operation.
"""
with self._event_listeners_lock:
if self._listeners_stopped:
return
listeners = list(self._file_listeners)
for listener in listeners:
if self._listeners_are_stopped():
return
try:
listener(full_path, name, size, command)
except Exception as e:
self._log(f"file listener error: {e}")
self._log_exc()

def _socket_key(self, sock):
"""Serializable key for a sender socket (its peer address).

Forwarded records already carry the originator's address as a
string and are used as-is; a socket that cannot answer
``getpeername`` (already closed) falls back to its repr.

Args:
sock (object): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
if isinstance(sock, str):
return sock
try:
ip, port = sock.getpeername()[:2]
return f"{ip}:{port}"
except Exception:
return str(sock)

def _remember_socket_key(self, sock):
"""Capture the log key of ``sock`` while it is known to be alive.

A record stays buffered after its connection goes away, and the
flush that persists it must still file it under the sender's
address: by then the closed socket no longer answers
``getpeername`` and would be logged as ``str(sock)``. The key is
forgotten once nothing is buffered under it any more (see
``_flush_dict_locked``).

Args:
sock (object): Value used by the operation.
"""
with self._socket_keys_lock:
if sock not in self._socket_keys:
self._socket_keys[sock] = self._socket_key(sock)

def _record_key(self, sock):
"""Return the JSON-log key for ``sock``: the address captured when it was.

The JSON-log key for ``sock``: the address captured when it was

recorded, or the live peer address for a socket inserted without a
record.

Args:
sock (object): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
key = self._socket_keys.get(sock)
if key is not None:
return key
return self._socket_key(sock)

def _append_record(self, store, log_path, sock, content):
"""Append one ``[content, timestamp]`` pair under ``sock``; flush when full.

Args:
store (tuple): ``(dict, lock, size_attr)``; the dict maps socket to
a list of pairs, and ``size_attr`` names the byte-size attribute.
log_path (str): JSON log the store flushes into.
sock (object): Key socket.
content (str): Text to record.
"""
d, lock, size_attr = store
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with lock:
self._remember_socket_key(sock)
d.setdefault(sock, []).append([content, timestamp])
size = getattr(self, size_attr) + len(content.encode("utf-8", "replace"))
size += len(timestamp)
setattr(self, size_attr, size)
if size >= self.max_dict_size:
self._flush_dict_locked(d, size_attr, log_path)

def _record_message(self, sock, content):
"""Store one inbound plain-text message under the sender's socket."""
self._append_record(
(self.messages_dict, self._messages_dict_lock, "_messages_dict_size"),
self.messages_log_file, sock, content,
)

def _record_event(self, sock, command):
"""Store one inbound "/" command under the sender's socket."""
self._append_record(
(self.events_dict, self._events_dict_lock, "_events_dict_size"),
self.events_log_file, sock, command,
)

def _record_sent(self, sock, content):
"""Store one outbound text: a "/" line as a sent event, other text as a sent message."""
if content.startswith("/"):
self._append_record(
(self.sent_events_dict, self._sent_events_dict_lock, "_sent_events_dict_size"),
self.sent_events_log_file, sock, content,
)
else:
self._append_record(
(
self.sent_messages_dict,
self._sent_messages_dict_lock,
"_sent_messages_dict_size",
),
self.sent_messages_log_file, sock, content,
)

def _record_dicts(self):
"""Return the four record stores, in flush order."""
return (
self.messages_dict,
self.events_dict,
self.sent_messages_dict,
self.sent_events_dict,
)

def _flush_messages_dict(self):
"""Flush the inbound messages store into its JSON log."""
with self._messages_dict_lock:
self._flush_dict_locked(
self.messages_dict, "_messages_dict_size", self.messages_log_file
)

def _flush_events_dict(self):
"""Flush the inbound events store into its JSON log."""
with self._events_dict_lock:
self._flush_dict_locked(self.events_dict, "_events_dict_size", self.events_log_file)

def _flush_record_stores(self):
"""Flush every record store into its JSON log (called on stop)."""
with self._messages_dict_lock:
self._flush_dict_locked(
self.messages_dict, "_messages_dict_size", self.messages_log_file
)
with self._events_dict_lock:
self._flush_dict_locked(self.events_dict, "_events_dict_size", self.events_log_file)
with self._sent_messages_dict_lock:
self._flush_dict_locked(
self.sent_messages_dict, "_sent_messages_dict_size", self.sent_messages_log_file
)
with self._sent_events_dict_lock:
self._flush_dict_locked(
self.sent_events_dict, "_sent_events_dict_size", self.sent_events_log_file
)

def _update_event_timestamp(self, sock, command, timestamp):
"""Stamp the completion time onto the recorded event for ``command``.

File transfers finish on a worker thread after the receive thread
recorded the command, so the event's timestamp is refreshed here with
the moment the transfer actually completed.

Args:
sock (object): Value used by the operation.
command (object): Value used by the operation.
timestamp (object): Value used by the operation.
"""
with self._events_dict_lock:
entries = self.events_dict.get(sock)
if entries:
for entry in reversed(entries):
if entry[0] == command:
entry[1] = timestamp
return

def _splice_event_command(self, command, **parts):
"""Return the command to record as an event.

The wire command is recorded verbatim whenever it is available. When
this end cannot see the original command (a transfer relayed by the
server, or a protocol-internal control line), splice a readable
command from the available parts so the event still identifies the
transfer.

Args:
command (object): Value used by the operation.
**parts (list | dict): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
if command:
return command
kind = parts.get("kind")
fname = parts.get("fname")
rel_dir = parts.get("rel_dir")
if kind == "folder" and fname:
if rel_dir:
return "/file_folder {} {}".format(shlex.quote(rel_dir), shlex.quote(fname))
return "/file_folder {}".format(shlex.quote(fname))
if fname:
return "/file {}".format(shlex.quote(fname))
return parts.get("fallback") or "/unknown"

def _flush_dict_locked(self, d, size_attr, path):
"""Flush ``d`` (socket -> [[content, ts], ...]) into its JSON log and

clear it. The caller must hold the dict's lock.

Args:
d (list | dict): Value used by the operation.
size_attr (object): Value used by the operation.
path (str): Value used by the operation.
"""
if not d:
return
snapshot = dict(d)
d.clear()
setattr(self, size_attr, 0)
self._merge_json_log(path, snapshot)
with self._socket_keys_lock: # a key is only kept while some store buffers it
for sock in snapshot:
if not any(sock in store for store in self._record_dicts()):
self._socket_keys.pop(sock, None)

def _merge_json_log(self, path, snapshot):
"""Merge ``snapshot`` into the JSON log at ``path`` (append per socket).

Publishes through `_publish_json_log`: a temp file named after this
writer, and an optimistic re-merge when another instance published in
between, so concurrent flushes of several instances sharing one log
neither corrupt nor lose each other. A failure is logged, never raised
into the caller.

Args:
path (str): Value used by the operation.
snapshot (list | dict): Value used by the operation.
"""
try:
_publish_json_log(path, snapshot, self._record_key)
except Exception as e:
self._log(f"log file update failed: {e}")
self._log_exc()

def submit_task(self, func, *args, **kwargs):
"""Run a callable on the instance's worker pool.

Args:
func (callable): Callable to run.
*args (Any): Positional arguments forwarded to ``func``.
**kwargs (Any): Keyword arguments forwarded to ``func``.

Returns:
concurrent.futures.Future: Handle for the submitted call; its worker
slot is released when the call finishes.

Raises:
RuntimeError: If terminal shutdown has started, even while waiting for a slot.
"""
self._task_semaphore.acquire()
future = self._custom_executor.submit(func, *args, **kwargs)
future.add_done_callback(lambda f: self._task_semaphore.release())
return future
return self._custom_executor.submit(func, *args, **kwargs)

def _log(self, *parts):
"""Print a command/result line, unless ``is_print_log`` is False.

Args:
*parts (Any): Values forwarded to ``print``.
"""
_log_line(self.is_print_log, parts)

def _debug(self, *parts):
"""Print an execution-process line; needs ``is_print_log`` and ``is_debug``.

Args:
*parts (Any): Values forwarded to ``print``.
"""
_debug_line(self.is_print_log, self.is_debug, parts)

def _log_exc(self):
"""Print the traceback of the exception being handled, in debug mode only."""
if self.is_print_log and self.is_debug:
traceback.print_exc()

def _measure_network_speed(self, payload, is_upload):
"""Fold just-sent/received traffic into the real-time speed estimate.

Every send and receive sample feeds this — control messages, file data
and relay traffic alike — so the speed attributes describe the
instance's current traffic as a rolling average over
``NETWORK_SPEED_WINDOW`` seconds.

Args:
payload (bytes | str | int): Bytes just written or read; a str counts as its UTF-8 length, an int is a byte count already.
is_upload (bool): True for sent bytes (``upload_network_speed``), False for received ones (``recv_network_speed``).

Returns:
float | None: The refreshed speed in bytes per second, or None when
``is_enable_real_time_network_speed`` is False; both speed
attributes are None then.
"""
if not self.is_enable_real_time_network_speed:
self.upload_network_speed = None
self.recv_network_speed = None
return None
if isinstance(payload, str):
byte_count = len(payload.encode("utf-8"))
elif isinstance(payload, int):
byte_count = payload
else:
byte_count = len(payload)
if not byte_count:
return None
now = time.monotonic()
with self._network_speed_lock:
if is_upload:
samples = self._upload_speed_samples
total = self._upload_speed_total + byte_count
else:
samples = self._recv_speed_samples
total = self._recv_speed_total + byte_count
samples.append((now, byte_count))
cutoff = now - NETWORK_SPEED_WINDOW
while samples[0][0] < cutoff: # only the current window counts
total -= samples.popleft()[1]
if is_upload:
self._upload_speed_total = total
else:
self._recv_speed_total = total
span = now - samples[0][0]
if span < NETWORK_SPEED_MIN_SPAN: # a single burst is not extrapolated
span = NETWORK_SPEED_MIN_SPAN
speed = total / span
if is_upload:
self.upload_network_speed = speed
else:
self.recv_network_speed = speed
return speed

def _file_progress_start(self, progress_dict, fid, total_bytes, path, peer=None, initial=0):
"""Register one file transfer in a progress store.

Args:
progress_dict (dict): ``self.file_recv_progress`` for an inbound transfer, ``self.file_upload_progress`` for an outbound one.
fid (int | tuple | None): Receive fid or upload ``(receiver, fid)`` key; None tracks no progress.
total_bytes (int): Size of the file being transferred.
path (str): Local path of the file: the source of an outbound transfer, the file being written for an inbound one.
peer (tuple | None): ``(ip, port)`` of the transfer's original peer — the sender for an inbound transfer, the receiver for an outbound one. A forwarded transfer stores the original peer on both sides, never the relay; None marks a leg that cannot be resumed (there is no peer to continue it with).
initial (int): Bytes already transferred when the leg starts; a resumed transfer continues a partially transferred file.

Returns:
list | None: The ``[transferred, total, speed, path, peer]`` entry
the transfer updates, or None when tracking is off
(``is_enable_file_transfer_progress_bar`` False, or no fid).
"""
if fid is None or not self.is_enable_file_transfer_progress_bar:
return None
entry = [initial, total_bytes, None, path, _peer_from_json(peer) if peer else None]
with self._transfer_progress_lock:
progress_dict[fid] = entry
self._active_transfer_fids.add(fid)
return entry

def _file_progress_update(self, entry, byte_count, is_upload):
"""Fold one transferred chunk into a progress entry.

Args:
entry (list | None): Entry from `_file_progress_start`, or None when the transfer is not tracked.
byte_count (int): Bytes of the chunk just sent or received.
is_upload (bool): True for sent chunks, False for received ones. The speed slot mirrors the live measurement, so it stays None while ``is_enable_real_time_network_speed`` is False.
"""
if entry is None:
return
entry[0] += byte_count
entry[2] = self.upload_network_speed if is_upload else self.recv_network_speed

def _file_progress_finish(self, progress_dict, fid, entry, keep=False):
"""Drop a finished transfer's progress entry, or keep it for a resume.

A resumed leg can replace an older session under the same scoped key.
Only the entry's owner is removed. ``keep`` preserves an interrupted
entry and its partial file for the next reconnect.

Args:
progress_dict (dict): Store the entry belongs to.
fid (int | tuple | None): Receive fid or upload ``(receiver, fid)`` key.
entry (list | None): Entry to drop; None tracks nothing.
keep (bool): Keep the entry (and persist the stores) instead of dropping it. Defaults to False.
"""
if entry is None:
return
with self._transfer_progress_lock:
if progress_dict.get(fid) is entry:
# a leg of an earlier session may finish after a newer leg
# took the fid over: only the owner releases it
self._active_transfer_fids.discard(fid)
if not keep:
del progress_dict[fid]
if keep:
entry[2] = None # a stopped transfer has no live speed any more
if keep or os.path.exists(self.file_trans_progress_file):
# the persisted stores are only kept up to date while they exist:
# a transfer that ended must not be resumed on a later reconnect
self._persist_transfer_progress()

def _transfer_progress_snapshot(self):
"""Return the JSON-ready form of every transfer still in play.

Returns:
dict: ``{"upload": ..., "download": ..., "relays": ...}``; fids
are string keys and every peer is an ``[ip, port]`` list.
"""

def entries(store):
"""Handle the operation.

Args:
store (list | dict): Value used by the operation.

Returns:
list | tuple: Result produced by the operation.
"""
return {
(json.dumps(fid, separators=(",", ":"))
if store is self.file_upload_progress else str(fid)): [
entry[0],
entry[1],
entry[2],
entry[3],
list(entry[4]) if entry[4] else None,
]
for fid, entry in list(store.items())
}

return {
"upload": entries(self.file_upload_progress),
"download": entries(self.file_recv_progress),
"relays": {},
}

def get_transfer_progress(self, *, include_persisted=True) -> dict:
"""Return a detached, local-only view of all retained transfer records.

Args:
include_persisted (bool): Read this instance's progress file too.
Defaults to True; never loads it into the live stores.

Returns:
dict: Flags, scoped memory rows and a separate persisted snapshot
with its path, read status and error. Disk runtime flags are
unknown (None). No completion or zombie status is inferred.
"""
return _get_transfer_progress(self, include_persisted=include_persisted)

def delete_config(self, config_name=None, *, is_list_config=False) -> bool | list[str]:
"""List or delete a named local progress snapshot or message/event log.

Args:
config_name (str | None): Allowed file basename, not a path.
is_list_config (bool): Only list existing regular files, ignoring
config_name. Defaults to False; listing is allowed while running.

Returns:
bool | list[str]: Sorted file names in list mode; otherwise True
when deleted, False when absent. Discarding progress permanently
disables this object's reload/write/start; create a new instance.

Raises:
ValueError: Invalid/ambiguous name, directory or symlink.
TypeError: A deletion name is not a string.
RuntimeError: Instance not closed, operations active or logs buffered.
OSError: The filesystem refuses inspection or deletion.
"""
return _delete_config(self, config_name, is_list_config=is_list_config)

def _persist_transfer_progress(self):
"""Write the transfer stores to the protocol's ``.Flow`` directory.

Upload and download rows are written to ``client_file_trans_progress.json``
when a connection drops. Forwarded uploads use those same five-item rows;
the ``relays`` area is empty. The reconnect logic reads the rows back.
Once nothing is left the existing file is emptied; an uninterrupted run
creates no progress file. Write failures are logged, never raised.
"""
with self._transfer_progress_lock:
if self._progress_discarded:
return
snapshot = self._transfer_progress_snapshot()
if not any(snapshot.values()) and not os.path.exists(self.file_trans_progress_file):
return
tmp_path = f"{self.file_trans_progress_file}.{os.getpid()}.tmp"
try:
if os.path.exists(self.file_trans_progress_file):
_read_transfer_progress(self.file_trans_progress_file)
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(snapshot, f, ensure_ascii=False, indent=2)
os.replace(tmp_path, self.file_trans_progress_file)
except (OSError, ValueError) as e:
self._log(f"transfer progress file update failed: {e}")
try:
os.remove(tmp_path)
except OSError:
pass

def _load_transfer_progress(self):
"""Read the persisted interrupted transfers back into the stores.

Existing five-item rows retain bytes and full paths for reconnect.
Live scoped keys are not overwritten. Nonempty legacy client relay
metadata is rejected without modifying the old snapshot.

Returns:
int: Number of upload and download rows restored.
"""
with self._transfer_progress_lock:
if self._progress_discarded:
return 0
try:
data = _read_transfer_progress(self.file_trans_progress_file)
except FileNotFoundError:
return 0
except (OSError, ValueError) as e:
self._log(f"transfer progress file unreadable ({e}), ignored")
return 0
if not isinstance(data, dict):
return 0
restored = 0
for key, store in (
("download", self.file_recv_progress),
("upload", self.file_upload_progress),
):
for fid_text, row in (data.get(key) or {}).items():
try:
fid = int(fid_text) if key == "download" else json.loads(fid_text)
if key == "upload":
fid = (_peer_from_json(fid[0]), int(fid[1]))
if fid[0] is None:
continue
entry = [int(row[0]), int(row[1]), None, row[3], _peer_from_json(row[4])]
except (TypeError, ValueError, IndexError, KeyError):
continue
if fid in store:
continue # a live transfer owns this exact scoped key
store[fid] = entry
restored += 1
return restored


def pause_trans(self, fid, peer=None, *, trans_type, direction):
"""Pause an ordinary leg or request Source-arbitrated relay-wide pause.

Args:
fid (int): Nonnegative transfer id.
peer (tuple | None): Configured or connected server; None selects it.
trans_type (int): 0 ordinary, 1 forwarded.
direction (int): Local data role: 0 sender, 1 receiver.

Returns:
bool: Operation registered, not peer confirmation. Source decides
relay state; Target requests may repeat to preserve cross-peer
intent. A missing sender retains a preset pause and returns False.

Raises:
ValueError: Invalid fid, transfer type or direction.
"""
return _set_transfer_control(self, fid, peer, trans_type, direction, True)

def start_trans(self, fid, peer=None, *, trans_type, direction):
"""Continue the selected leg on its existing socket; clear preset pauses.

Arguments and registration result match ``pause_trans``. No seek,
truncation or new handshake occurs; receivers continue reading throughout.
"""
return _set_transfer_control(self, fid, peer, trans_type, direction, False)

def _register_transfer_socket(self, fid, sock):
"""Record the socket of a leg, so a dead session can be cleared out.

Args:
fid (int | tuple): Receive fid or outgoing ``(receiver, fid)`` key.
sock (object): Value used by the operation.
"""
if fid is None:
return
with self._transfer_progress_lock:
self._active_transfer_sockets[fid] = sock

def _release_transfer_socket(self, fid, sock):
"""Forget a leg's socket once the leg is over (its own, not a newer one's).

Args:
fid (int | tuple): Receive fid or outgoing ``(receiver, fid)`` key.
sock (object): Value used by the operation.
"""
self._transfer_controls.release_owner(sock)
if fid is None:
return
with self._transfer_progress_changed:
if self._active_transfer_sockets.get(fid) is sock:
del self._active_transfer_sockets[fid]
self._active_transfer_fids.discard(fid)
record = self._receive_transfers.get(fid)
if record is not None and record["owner"] is sock:
del self._receive_transfers[fid]
self._transfer_progress_changed.notify_all()


def _wait_control_secure(self, control_socket, timeout=RESUME_SECURE_TIMEOUT):
"""Wait until a control channel may carry framed protocol lines.

A reconnect may precede the end of the handshake. Wait before issuing
the request; the writer still enforces framing if rekey begins later.

Args:
control_socket (socket.socket): Value used by the operation.
timeout (float): Value used by the operation.

Returns:
bool: True when the channel speaks frames (or encryption is off).
"""
if not self.is_enable_encrypto or self.crypto is None:
return True
deadline = time.time() + timeout
while time.time() < deadline:
if not self.running or control_socket.fileno() < 0:
return False
with self._crypto_lock:
channel = self._channels.get(control_socket)
if channel is not None and channel.secure and channel.frames_allowed.is_set():
return True
time.sleep(0.05)
self._log("control channel not framed yet; transfer control was not sent")
return False

def alloc_port(self, port_add_step, port_range_num):
"""Reserve this client's port range under the cross-process lock.

No-op until the server assigns a range (see ``/client_alloc_port_range``).

Args:
port_add_step (int): Step between candidate ports.
port_range_num (int): Number of ports per step.
"""
if self.is_hand_alloc_port == True:
while self.is_client_port_temp_info_file_locked():
time.sleep(0.1)
self.client_port_temp_info_file_lock()
try:
self.hand_alloc_port(port_add_step, port_range_num)
finally:
# a failing allocation must not leave the lock behind: every
# later instance would wait for it forever
self.client_port_temp_info_file_unlock()

def free_port(self):
"""Release this client's reserved port range.

No-op unless a range was assigned (``is_hand_alloc_port`` True).
"""
if self.is_hand_alloc_port == True:
while self.is_client_port_temp_info_file_locked():
time.sleep(0.1)
self.client_port_temp_info_file_lock()
try:
self.hand_free_port()
finally:
self.client_port_temp_info_file_unlock()

def client_port_temp_info_file_lock(self):
"""Create the lock file that reserves the client port range for this process."""
with open(self.client_port_lock_file, "w", encoding="utf-8") as f:
f.write("locked")

def is_client_port_temp_info_file_locked(self):
"""Report whether the client port range is reserved by some process.

Returns:
bool: True while the lock file exists.
"""
if os.path.exists(self.client_port_lock_file):
return True
else:
return False

def client_port_temp_info_file_unlock(self):
"""Remove the lock file that reserves the client port range."""
if os.path.exists(self.client_port_lock_file):
os.remove(self.client_port_lock_file)

def hand_alloc_port(self, port_add_step, port_range_num):
"""Allocate the next free client port range and record it on disk.

``port`` is moved past the ranges already recorded by other clients on this
host, so each instance ends up with a range of its own.

Args:
port_add_step (int): Step between candidate ports.
port_range_num (int): Number of ports per step.

Raises:
OSError: If the client port info file cannot be read or written.
"""
self.port_temp_info_path = os.path.join(self.project_temp_info_dir, "clients_port_info.log")
server_port_temp_info_file_path = os.path.join(
self.project_temp_info_dir, "server_port_info.log"
)
if os.path.exists(server_port_temp_info_file_path) == True:
self._log(
"Warning: server port info file exists, means the server has already allocated a port, may cause port conflict!"
)
self.port_add_step = port_add_step
self.port_range_num = port_range_num
self.add_latest_port = self.port + 1
self.minus_latest_port = self.port
self.alloc_add_port_lock = threading.Lock()
self.alloc_minus_port_lock = threading.Lock()
if os.path.exists(self.port_temp_info_path) == False:
self.client_num = 0
self.client_port_info = []
self.min_port = self.port - self.port_add_step * self.port_range_num
self.max_port = self.port + 1 + self.port_add_step * self.port_range_num
each_client_info = {
"client_id": self.client_num,
"host": self.host,
"port": self.port,
"min_port": self.min_port,
"max_port": self.max_port,
"is_running": True,
"pid": os.getpid(), # the sweep reclaims the range once it is gone
"started_at": time.time(),
}
self.client_port_info.append(each_client_info)
with open(self.port_temp_info_path, "w", encoding="utf-8") as f:
f.write(str(self.client_port_info))
else:
with open(self.port_temp_info_path, "r", encoding="utf-8") as f:
self.client_port_info = ast.literal_eval(f.read())
# drop the entries whose owning process is gone (see the server twin)
self.client_port_info = [
entry for entry in self.client_port_info if not _port_record_stale(entry)
]
if not self.client_port_info: # nobody holds a range: start over
os.remove(self.port_temp_info_path)
self.hand_alloc_port(port_add_step, port_range_num)
return
self.client_num = self.client_port_info[len(self.client_port_info) - 1]["client_id"] + 1
auto_port_add = (
self.client_port_info[len(self.client_port_info) - 1]["max_port"]
+ self.port_add_step * self.port_range_num
+ 1
)
auto_port_minus = (
self.client_port_info[len(self.client_port_info) - 1]["min_port"]
- self.port_add_step * self.port_range_num
- 1
)
if self.port > auto_port_minus and self.port < auto_port_add:
self.port = auto_port_add
self.min_port = self.port - self.port_add_step * self.port_range_num
self.max_port = self.port + 1 + self.port_add_step * self.port_range_num
each_client_info = {
"client_id": self.client_num,
"host": self.host,
"port": self.port,
"min_port": self.min_port,
"max_port": self.max_port,
# the client is connected while it holds the range: hand_free_port()
# drops the entry on disconnect, and the pid lets a later
# instance reclaim the range of one that was killed
"is_running": True,
"pid": os.getpid(),
"started_at": time.time(),
}
self.client_port_info.append(each_client_info)
with open(self.port_temp_info_path, "w", encoding="utf-8") as f:
f.write(str(self.client_port_info))

def hand_free_port(self):
"""Drop this client's entry from the on-disk port range record."""
self.port_temp_info_path = os.path.join(self.project_temp_info_dir, "clients_port_info.log")
if os.path.exists(self.port_temp_info_path):
with open(self.port_temp_info_path, "r", encoding="utf-8") as f:
self.client_port_info = ast.literal_eval(f.read())
# rebuild instead of deleting by index: other live instances keep
# their entries, so this one is not necessarily the last, and a
# shrinking list would make the next index run past its end
self.client_port_info = [
entry for entry in self.client_port_info if entry["client_id"] != self.client_num
]
if len(self.client_port_info) == 0:
os.remove(self.port_temp_info_path)
else:
with open(self.port_temp_info_path, "w", encoding="utf-8") as f:
f.write(str(self.client_port_info))

def palloc(self):
"""Allocate a port, waiting until one is free.

Returns:
int: Allocated port, or 0 when no allocation range was assigned.
"""
alloc_port = 0
while True:
alloc_port = self.file_palloc()
if alloc_port is not None:
return alloc_port
alloc_port = self.spy_palloc()
if alloc_port is not None:
return alloc_port
# both directions are exhausted: wait for a port to come back
time.sleep(0.1)

def pfree(self, port):
"""Release a port obtained from `palloc`.

Args:
port (int): Port to release.
"""
self.file_pfree(port)
self.spy_pfree(port)

def file_palloc(self):
"""Allocate the next port above the base, or the first free one in range.

Returns:
int: Allocated port; None when the upward range is exhausted; 0 when no
allocation range was assigned.
"""
if self.is_hand_alloc_port:
with self.alloc_add_port_lock:
if self.add_latest_port + self.port_add_step > self.max_port:
for step in range(self.port + 1, self.max_port, self.port_add_step):
if step in self.all_allocated_ports_list:
pass
else:
allocated_port = step
self.all_allocated_ports_list.append(allocated_port)
return allocated_port
return None
self.add_latest_port += self.port_add_step
self.all_allocated_ports_list.append(self.add_latest_port)
return self.add_latest_port
else:
return 0

def file_pfree(self, port):
"""Release a port obtained from `file_palloc` and step the cursor back.

Args:
port (int): Port to release. Ignored when allocation is disabled.
"""
if self.is_hand_alloc_port:
with self.alloc_add_port_lock:
if port in self.all_allocated_ports_list:
self.all_allocated_ports_list.remove(port)
self._debug("releasing file transfer port, current latest port:", port)
self.add_latest_port -= self.port_add_step
else:
pass

def spy_palloc(self):
"""Allocate the next port below the base, or the first free one in range.

Returns:
int: Allocated port; None when the downward range is exhausted; 0 when
no allocation range was assigned.
"""
if self.is_hand_alloc_port:
with self.alloc_minus_port_lock:
if self.minus_latest_port - self.port_add_step < self.min_port:
for step in range(self.port, self.min_port, -self.port_add_step):
if step in self.all_allocated_ports_list:
pass
else:
allocated_port = step
self.all_allocated_ports_list.append(allocated_port)
return allocated_port
return None
self.minus_latest_port -= self.port_add_step
self.all_allocated_ports_list.append(self.minus_latest_port)
return self.minus_latest_port
else:
return 0

def spy_pfree(self, port):
"""Release a port obtained from `spy_palloc` and step the cursor back.

Args:
port (int): Port to release. Ignored when allocation is disabled.
"""
if self.is_hand_alloc_port:
with self.alloc_minus_port_lock:
if port in self.all_allocated_ports_list:
self.all_allocated_ports_list.remove(port)
self._debug("releasing file transfer port, current latest port:", port)
self.minus_latest_port += self.port_add_step
else:
pass

def create_temporary_server(self, handler, port=None, max_connections=1):
"""Start a temporary listener for a side channel (not the main protocol).

Args:
handler (callable): ``handler(client_socket, address)`` started in its
own thread for every accepted connection.
port (int | None): Port to bind; None allocates one with `palloc`.
max_connections (int): Listen backlog. Defaults to 1.

Returns:
tuple: ``(port, thread, stop_event)``; setting ``stop_event`` ends the
loop, which closes the socket and frees the port.

Raises:
RuntimeError: If ``port`` is None and no port can be allocated.
"""
if port is None:
port = self.palloc()
if port is None:
raise RuntimeError("No available port for temporary server")
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((self.client_host, port))
server_socket.listen(max_connections)
stop_event = threading.Event()

def server_loop():
"""Handle the operation."""
while not stop_event.is_set():
try:
server_socket.settimeout(1.0)
client_sock, addr = server_socket.accept()
threading.Thread(target=handler, args=(client_sock, addr), daemon=True).start()
except socket.timeout:
continue
except Exception as e:
if not stop_event.is_set():
self._log(f"Temporary server error: {e}")
break
server_socket.close()
self.pfree(port)

server_thread = threading.Thread(target=server_loop, daemon=True)
server_thread.start()
return port, server_thread, stop_event

def create_temporary_client(self, server_host, server_port, bind_port=None, on_data=None):
"""Open a temporary outbound connection for a side channel.

Args:
server_host (str): Host to connect to.
server_port (int): Port to connect to.
bind_port (int | None): Local port to bind; None allocates one with
`palloc`.
on_data (callable | None): ``on_data(data, client_socket)`` called for
every received chunk.

Returns:
tuple: ``(client_socket, thread, stop_event)``; setting ``stop_event``
ends the receiver thread.
"""
client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if bind_port is not None:
client_sock.bind((self.client_host, bind_port))
else:
bind_port = self.palloc()
client_sock.bind((self.client_host, bind_port))
client_sock.connect((server_host, server_port))
stop_event = threading.Event()

def receiver():
"""Handle the operation."""
while not stop_event.is_set():
try:
client_sock.settimeout(1.0)
data = self.receive_message(client_sock, self.recv_messages_chunk_len)
if not data:
break
if on_data:
on_data(data, client_sock)
except socket.timeout:
continue
except:
break
client_sock.close()

recv_thread = threading.Thread(target=receiver, daemon=True)
recv_thread.start()
return client_sock, recv_thread, stop_event

def _crypto_negotiate_mode(self):
"""Announce our encryption mode and wait for the server's.

Returns True only when both sides agree on ``is_enable_encrypto``.
On a mismatch (or a missing announcement) the connection is
closed and False is returned.

Returns:
bool: Result produced by the operation.
"""
self.send_message(
self.client_socket,
f"/crypto_mode {1 if self.is_enable_encrypto else 0}",
is_send_raw=True,
)
if not self._crypto_mode_event.wait(timeout=self._crypto_mode_timeout):
self._log("crypto: server did not announce its encryption mode, disconnecting")
self.close()
return False
if not self._crypto_mode_ok:
self.close() # mismatch: the receive thread signalled the refusal; close idempotently
return False
return True

@_config_lifecycle(starting=True)
def connect(self): # connect to server
"""Connect to the server and start reading from it.

Binds ``client_port`` when one was configured, then retries while
``is_wait_server`` is True and the server is not reachable yet. Once the
socket is up the receive thread is started and the encryption mode is
negotiated, which closes the connection when the two sides disagree.

Returns:
bool: True when the connection is established (and, if encryption is
enabled, the key exchange has been started); False when the attempt
failed or the mode negotiation closed the connection.
"""
retired = self._release_client_socket()
previous_resume = self._resume_thread
while True:
try:
local_address = (
(self.client_host, self.client_port)
if self.client_port is not None
else None
)
while True:
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if self.timeout != None:
self.client_socket.settimeout(self.timeout) # connect over 5 seconds timeout
else:
self.client_socket.settimeout(5)
self._log(f"connecting to {self.host}:{self.port}...")
self.local_address = local_address
try:
if local_address is not None:
self.client_socket.bind(local_address)
self.client_socket.connect((self.host, self.port))
break
except OSError as e:
# The configured source port may be unavailable because
# of TIME_WAIT or a Windows reserved-port denial. The
# previous session can then no longer match transfers by
# local address; as before, reconnect from an OS port.
self.client_socket.close()
if local_address is None or not _should_fallback_local_port(
local_address[1], e
):
raise
self._log(
f"client port {self.client_port} is not available ({e}); "
f"connecting from an OS-assigned port instead"
)
local_address = None
if self._stopped:
# close() arrived while the socket was connecting: stay
# closed instead of reviving the connection
self.client_socket.close()
self.client_socket = None
return False
self.running = True
self._control_sockets.add(self.client_socket)
control_socket = self.client_socket
self.receive_thread = threading.Thread(
target=self.receive_messages
) # set up get msg thread
with self._crypto_lock: # reset before the recv thread starts
self._crypto_mode_event.clear()
self._crypto_mode_ok = False
self.receive_thread.daemon = True
if self.is_enable_encrypto and self.crypto is not None:
session = self._crypto_session_ensure()
channel = _SecureChannel(
self.client_socket,
session,
self._log,
self._debug,
send_lock=self._crypto_send_lock,
on_disable=lambda: self._crypto_drop_secure(control_socket),
)
with self._crypto_lock:
self._channels[self.client_socket] = channel
self.receive_thread.start()
if not self._crypto_negotiate_mode():
return False
if self.is_enable_encrypto and self.crypto is not None:
with self._crypto_lock:
self._crypto_decode_failures = 0 # fresh connection, fresh breaker
self._crypto_start_exchange()
self._log("connect success! type '/help' to get help.\n")
def resume():
if previous_resume is not None:
previous_resume.join()
_wait_transfer_session(self, retired)
self._request_resumes(control_socket=control_socket)

self._resume_thread = threading.Thread(target=resume, daemon=True)
self._resume_thread.start()
return True
except socket.timeout:
if self.is_wait_server:
self._log("waiting for server to start...")
pass
else:
self._log("timeout, unable to connect to server")
self._log_exc()
return False
except ConnectionRefusedError:
if self.is_wait_server:
self._log("waiting for server to start...")
pass
else:
self._log("connection rejected by server, please ensure the server is running")
self._log_exc()
return False
except Exception as e:
self._log(f"connection error: {e}")
self._log_exc()
return False

def receive_messages(self): # get server msg
"""Read from the server until the connection ends.

Runs on the receive thread: every inbound line is reported to the message
listeners (commands included); a plain message is also stored in
``messages_dict``, while a ``/send_msg_from`` envelope is reported and
stored as its payload attributed to the forwarding client, and other ``/``
lines additionally go to `handle_server_command`. Any end of the
connection clears ``running`` and releases the port range.
"""
control_socket = self.client_socket
buffer = ""
while self.running and self.client_socket is control_socket:
try:
data = self.receive_message(control_socket, self.recv_messages_chunk_len)
if self.client_socket is not control_socket:
break
if not data:
self._log("\nbreak the connection from server")
self.running = False
self.free_port()
# the transfers running on this session died with it: keep
# them on disk for the next connect (_request_resumes)
self._persist_transfer_progress()
break
buffer += data.decode("utf-8")
while "\n" in buffer: # deal with multiple messages in buffer
line, buffer = buffer.split("\n", 1)
message = line.strip()
if not message:
continue
if not _crypto_is_protocol_line(message):
# genuine peer traffic: reset the streak that feeds the breaker
self._crypto_note_healthy(self.client_socket)
sender = None # the author's "ip:port"; None for direct server pushes
if message.startswith("/"):
# A /send_msg_from envelope is a message that another
# client forwarded to us: its records belong to the
# originator, whose socket exists only on the server, so
# the originator's address is the store key here. The
# payload is reported and stored below like any inbound
# message; the envelope itself is not dispatched.
unwrapped = parse_forwarded_message(message)
if unwrapped is not None:
raw = message
sender, message = unwrapped
self._record_event(sender, raw)
if not message:
continue
else:
# a command from the server: reported to the listeners
# like every inbound line, then handled
self._record_event(control_socket, message)
self._notify_message_received(sender, message)
self.handle_server_command(message, control_socket=control_socket)
self._log(f"\n[server] {message}")
continue
self._notify_message_received(sender, message)
if not message.startswith("/"):
self._record_message(sender or self.client_socket, message)
self._log(f"\n[server] {message}")
except socket.timeout:
continue
except ConnectionResetError:
if self.client_socket is not control_socket:
break
self._log("\nReset by server, connection closed")
self._log_exc()
self.running = False
self.free_port()
self._persist_transfer_progress()
break
except Exception as e:
if self.client_socket is not control_socket:
break
if not _is_closed_socket_error(e):
self._log(f"\nget msg error: {e}")
self._log_exc()
self.running = False
self.free_port()
self._persist_transfer_progress()
break
_retire_transfer_session(self, control_socket)

def send_message(self, client_socket, message, is_send_raw=False):
# send msg to server
"""Write one line to a socket, encrypting when the channel is up.

Args:
client_socket (socket.socket): Target connection; the client passes
``self.client_socket``.
message (str | bytes): Payload; a str is stripped and newline
terminated, bytes are sent as they are.
is_send_raw (bool): Write the payload as plaintext even when the channel
is encrypted; only for the crypto handshake and transfer coordination lines.

Returns:
bool: True when written; False if the client is disconnected, the payload
is unsupported, or required transfer-control framing is unavailable.
"""
if is_send_raw:
deal_msg = message.strip()
if not deal_msg.endswith("\n"):
deal_msg += "\n"
encoded = deal_msg.encode("utf-8")
client_socket.sendall(encoded)
self._measure_network_speed(encoded, is_upload=True)
return True
written = self._write_message(client_socket, message)
if written:
self._after_send(client_socket, message)
return written

def _write_message(self, client_socket, message): # noqa: PLR0911 - same exits as the old send_message body
"""Write one payload; protected transfer commands may not fall back to plaintext.

Returns:
bool: True when written; False if disconnected, unsupported, or unable to frame.
"""
if not self.running or not self.client_socket:
self._log("disable the connect to server")
return False
with self._crypto_lock:
channel = self._channels.get(client_socket)
control_frame = self.is_enable_encrypto and _requires_secure_transfer_frame(message)
if channel is not None and channel.secure:
try:
if not isinstance(message, (str, bytes)):
self._log(f"Unsupported message type: {type(message)}")
return False
payload = message.strip() + "\n" if isinstance(message, str) else message
channel.send(payload, require_secure=control_frame)
self._measure_network_speed(payload, is_upload=True)
return True
except Exception as e:
if not _is_closed_socket_error(e):
self._log(f"send msg error: {e}")
self._log_exc()
return False
if control_frame:
return False # never enter the plaintext writer, including during rekey
with self._crypto_send_lock: # plaintext writes stay ordered (no-GIL safe)
try: # add newline character for server to distinguish messages
if isinstance(message, str):
deal_msg = message.strip()
if not deal_msg.endswith("\n"):
deal_msg += "\n"
data = deal_msg.encode("utf-8")
elif isinstance(message, bytes):
data = message
else:
self._log(f"Unsupported message type: {type(message)}")
return False
client_socket.sendall(data)
self._measure_network_speed(data, is_upload=True)
return True
except Exception as e:
if not _is_closed_socket_error(e):
self._log(f"send msg error: {e}")
self._log_exc()
return False

def _after_send(self, client_socket, message):
"""Record and report one payload that `_write_message` has written."""
if isinstance(message, str):
message = message.strip()
if message and client_socket in self._control_sockets:
self._record_sent(client_socket, message)
self._notify_message_sent(client_socket, message)

def send_message_to_server(self, message):
"""Send the payload of a console line to the server.

Args:
message (str): Console line such as ``/send_msg hello``; the first token
(the command name) is dropped and the second one is sent.

Raises:
IndexError: If the line has fewer than two tokens.
"""
self.send_message(self.client_socket, shlex.split(message)[1])

def receive_message(self, client_socket, msg_length): # receive msg
"""Read up to ``msg_length`` bytes from a socket.

A socket speaking frames (see `_SecureChannel`) returns decrypted
plaintext, served from the channel's buffer; a socket without one is
read raw. A read that started while the channel was raw is classified
by the channel when it returns, so bytes of a flip that landed during
the read never land in the line reader.

Args:
client_socket (socket.socket): Connection to read from.
msg_length (int): Maximum number of bytes to read.

Returns:
bytes: Received bytes, empty when the peer closed the connection.
"""
while True:
with self._crypto_lock:
channel = self._channels.get(client_socket)
if channel is None:
data = client_socket.recv(msg_length)
self._measure_network_speed(data, is_upload=False)
self._notify_transfer_chunk(client_socket, data)
return data
data = channel.take(msg_length)
if data:
self._measure_network_speed(data, is_upload=False)
self._notify_transfer_chunk(client_socket, data)
return data # buffered plaintext is served even after a disable
raw = client_socket.recv(self.recv_messages_chunk_len if channel.secure else msg_length)
if not raw:
return b""
try:
plain = channel.feed(raw)
except _FrameError as exc:
self._log(f"crypto: {exc}")
self._crypto_channel_error(client_socket)
leftover = channel.drain_plaintext()
if leftover:
self._measure_network_speed(leftover, is_upload=False)
self._notify_transfer_chunk(client_socket, leftover)
return leftover # hand back whatever was already read
continue # framing is off now: keep serving in raw mode
if plain:
self._measure_network_speed(plain, is_upload=False)
self._notify_transfer_chunk(client_socket, plain)
return plain # plaintext mode: the line reader gets the bytes

def _crypto_mark_encrypted(self, client_socket, peer_role, peer_pem_path):
"""Handle the operation.

Args:
client_socket (socket.socket): Value used by the operation.
peer_role (object): Value used by the operation.
peer_pem_path (str): Value used by the operation.
"""
with self._crypto_lock:
self._encrypted_sockets.add(client_socket)
self._crypto_peer[client_socket] = (peer_role, peer_pem_path)

def _crypto_session_ensure(self):
"""Get or create the client's crypto session.

The client's crypto session context (created on demand).

Returns:
object: Result produced by the operation.
"""
with self._crypto_lock:
if self._crypto_session is None and self.crypto is not None:
self._crypto_session = _CryptoSession(self.crypto, "client", self._log, self._debug)
return self._crypto_session

def _crypto_control_state(self, client_socket):
"""Return (session, channel) of one socket; (None, None) when unknown.

(session, channel) of one socket; (None, None) when unknown.

Args:
client_socket (socket.socket): Value used by the operation.

Returns:
list | tuple: Result produced by the operation.
"""
with self._crypto_lock:
return self._crypto_session, self._channels.get(client_socket)

def _crypto_channel_error(self, client_socket):
"""Handle a frame decode failure on a control or transfer socket.

A frame failed to decode: re-exchange on the control socket, close a

transfer socket (its leg has no handshake to recover with).

Args:
client_socket (socket.socket): Value used by the operation.
"""
if client_socket is self.client_socket:
self._crypto_on_decode_failure(client_socket)
return
self._log("crypto: transfer frame error, closing the transfer connection")
try:
client_socket.close()
except Exception:
pass

def _crypto_after_flip(self, client_socket):
"""Announce frame readiness (plaintext) and publish the session ECDH key.

Args:
client_socket (socket.socket): Value used by the operation.
"""
_session, channel = self._crypto_control_state(client_socket)
if channel is None:
return
try:
# plaintext by design: the peer needs this line before it may frame
self.send_message(client_socket, CRYPTO_FRAMES_START, is_send_raw=True)
except Exception:
self._log_exc()
self._crypto_publish_ecdh_pub(client_socket)

def _crypto_publish_ecdh_pub(self, client_socket):
"""Send our session ECDH public key once frames are allowed both ways.

Args:
client_socket (socket.socket): Value used by the operation.
"""
session, channel = self._crypto_control_state(client_socket)
if session is not None:
session.publish_pub(channel)

def _crypto_transfer_stamp(self, control_socket, force_plain=False):
"""Mode+nonce a listener announces to a transfer connector.

Args:
control_socket (socket.socket): Value used by the operation.
force_plain (bool): Value used by the operation.

Returns:
object | str: Result produced by the operation.
"""
session, channel = self._crypto_control_state(control_socket)
if session is None:
return "plain"
return session.transfer_stamp(channel, force_plain)

def _crypto_attach_transfer_in(self, sock, control_socket, stamp):
"""Framing channel for an accepted transfer socket (listener side).

Args:
sock (object): Value used by the operation.
control_socket (socket.socket): Value used by the operation.
stamp (object): Value used by the operation.

Returns:
NoneType | object: Result produced by the operation.
"""
session, control_channel = self._crypto_control_state(control_socket)
if session is None:
return None
channel = session.attach_transfer(sock, control_channel, stamp)
if channel is not None:
with self._crypto_lock:
self._channels[sock] = channel
self._encrypted_sockets.add(sock)
return channel

def _crypto_drop_secure(self, client_socket):
"""Framing stopped: keep the secure-socket set and peer map truthful.

Args:
client_socket (socket.socket): Value used by the operation.
"""
with self._crypto_lock:
self._encrypted_sockets.discard(client_socket)
self._crypto_peer.pop(client_socket, None)

def _crypto_note_healthy(self, client_socket):
"""Reset the decode-failure count after a valid frame.

A frame decoded cleanly: reset the streak that feeds the breaker.

Args:
client_socket (socket.socket): Value used by the operation.
"""
with self._crypto_lock:
self._crypto_decode_failures = 0

def _crypto_attach_transfer_out(self, sock, control_socket, stamp):
"""Framing channel for a connected transfer socket (connector side).

Args:
sock (object): Value used by the operation.
control_socket (socket.socket): Value used by the operation.
stamp (object): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
session, control_channel = self._crypto_control_state(control_socket)
crypto = _connector_transfer_crypto(session, control_channel, stamp)
channel = _enable_connector_channel(sock, crypto)
if channel is not None:
with self._crypto_lock:
self._channels[sock] = channel
self._encrypted_sockets.add(sock)
return channel

def _crypto_drop_channel(self, sock):
"""Forget a finished transfer socket's channel.

Args:
sock (object): Value used by the operation.
"""
with self._crypto_lock:
self._channels.pop(sock, None)
self._encrypted_sockets.discard(sock)

def _crypto_on_decode_failure(self, client_socket):
"""Decryption failed (stale/wrong key): drop encryption, reload

our own key and re-run the public-key exchange (forced).

A circuit breaker closes the connection after
``MAX_DECODE_FAILURES`` consecutive failures, so a garbage or
persistent-mismatch storm cannot spin the loop forever.

Args:
client_socket (socket.socket): Value used by the operation.
"""
with self._crypto_lock:
channel = self._channels.get(client_socket)
if channel is not None:
channel.disable()
with self._crypto_lock:
self._encrypted_sockets.discard(client_socket)
self._crypto_peer.pop(client_socket, None)
self._crypto_decode_failures += 1
if self._crypto_decode_failures >= MAX_DECODE_FAILURES:
do_close = True
do_exchange = False
else:
do_close = False
do_exchange = True
self._crypto_my_nonce = self._crypto_fresh_nonce()
if do_close:
self._log("crypto: too many decode failures, closing connection")
try:
self.close()
except Exception:
self._log_exc()
return
if self.crypto is not None:
try:
self.crypto.reload_own_key()
except Exception:
self._log_exc()
self._debug("crypto: decode failure, re-exchanging public keys")
if do_exchange:
try:
threading.Thread(
target=self._crypto_exchange_thread, args=(True,), daemon=True
).start()
except Exception:
self._log_exc()

def _crypto_start_exchange(self):
"""Start the client side of the public-key handshake (daemon)."""
threading.Thread(target=self._crypto_exchange_thread, daemon=True).start()

def _crypto_still_current(self, gen):
"""Return true while ``gen`` is still the latest handshake generation.

True while ``gen`` is still the latest handshake generation.

Args:
gen (object): Value used by the operation.

Returns:
object: Result produced by the operation.
"""
with self._crypto_lock:
return self._crypto_handshake_gen == gen

def _crypto_exchange_thread(self, force=False):
"""Drive the client half of the handshake to completion.

Args:
force (bool): Value used by the operation.

Raises:
TimeoutError: When the operation cannot complete.
"""
try:
self.crypto.ensure_keys()
session = self._crypto_session_ensure()
if session is not None:
session.reset_ecdh() # a fresh handshake is a fresh session key
with self._crypto_lock:
ack_event = threading.Event()
done_event = threading.Event()
pub_event = threading.Event()
self._crypto_ack_event = ack_event
self._crypto_exchange_done = done_event
self._crypto_server_pub_event = pub_event
self._crypto_requested_server_pub = False
self._crypto_server_pub_ok = None
self._crypto_server_pem_path = None
self._crypto_my_nonce = self._crypto_fresh_nonce()
self._crypto_handshake_started = True
self._crypto_handshake_gen += 1
gen = self._crypto_handshake_gen
hello = f"/crypto_key_exchange {self._crypto_my_nonce}"
if force:
hello += " 1"
self.send_message(self.client_socket, hello, is_send_raw=True)
if not ack_event.wait(timeout=30):
if not self._crypto_still_current(gen):
return # superseded by a newer handshake; that flow owns the connection
raise TimeoutError("crypto handshake: no ack from server")
if not done_event.wait(timeout=90):
if not self._crypto_still_current(gen):
return
raise TimeoutError("crypto handshake: key exchange did not complete")
self._crypto_try_flip() # readiness was announced by _wait_done; wait here until the socket actually flipped
for _ in range(600):
with self._crypto_lock:
flipped = self.client_socket in self._encrypted_sockets
if flipped:
break
time.sleep(0.1)
else:
if self._crypto_still_current(gen):
raise TimeoutError("crypto handshake: server /crypto_ready never arrived")
except Exception as e:
self._log(f"crypto handshake failed: {e}")
self._log_exc()
try:
self.close()
except Exception:
pass

def _crypto_on_server_hello(self, server_nonce, force):
"""Server initiated the handshake (re-exchange after a decode

failure): record its session nonce, ack that we need its key
(every connection re-exchanges), then run our half.

Args:
server_nonce (object): Value used by the operation.
force (bool): Value used by the operation.
"""
with self._crypto_lock:
self._crypto_force = force
self._crypto_server_nonce = server_nonce
self._crypto_handshake_started = True
self._crypto_my_nonce = self._crypto_fresh_nonce()
self._crypto_handshake_gen += 1
my_nonce = self._crypto_my_nonce
session = self._crypto_session_ensure()
if session is not None:
session.reset_ecdh() # a re-exchange is a fresh session key
ack = f"/crypto_key_exchange_ack {my_nonce} 1 {1 if force else 0}"
self.send_message(self.client_socket, ack, is_send_raw=True)
self._crypto_after_ack("1" if force else "0", force)

def _crypto_try_flip(self):
"""Flip to framed encryption only when the server key passed the

TOFU check and both sides announced readiness (no plaintext/framed
interleaving).
"""
with self._crypto_send_lock: # no send may interleave with the flip
with self._crypto_lock:
if not (
self._crypto_server_ready
and self._crypto_own_ready_sent
and self._crypto_server_pub_ok is True
and self._crypto_server_pem_path
and self.client_socket not in self._encrypted_sockets
):
return
self._crypto_mark_encrypted(
self.client_socket, "server", self._crypto_server_pem_path
)
channel = self._channels.get(self.client_socket)
my_nonce = self._crypto_my_nonce
peer_nonce = self._crypto_server_nonce
peer_pem_path = self._crypto_server_pem_path
if channel is not None:
channel.enable(my_nonce, peer_nonce, peer_pem_path)
threading.Thread(
target=self._crypto_after_flip, args=(self.client_socket,), daemon=True
).start()

@staticmethod
def _crypto_fresh_nonce():
"""Handle the operation.

Returns:
object: Result produced by the operation.
"""
return secrets.token_hex(16)

def _crypto_after_ack(self, server_needs, force):
"""Server replied to our hello: push our key and request the

server's key (if it needs us to), then signal the exchange
thread. Runs under ``_crypto_lock`` so a concurrent handshake
cannot interleave (no-GIL safe).

Args:
server_needs (object): Value used by the operation.
force (bool): Value used by the operation.
"""
with self._crypto_lock:
gen = self._crypto_handshake_gen
need_push = force or server_needs == "1"
push_thread = None
if need_push:
push_thread = threading.Thread(target=self._crypto_push_pub_key, daemon=True)
push_thread.start()
if not self._crypto_requested_server_pub:
self._crypto_requested_server_pub = True
request_pub = True
else:
request_pub = False
if request_pub:
self.send_message(self.client_socket, "/crypto_pub_key_request", is_send_raw=True)

def _wait_done():
"""Handle the operation."""
with self._crypto_lock:
pub_event = self._crypto_server_pub_event
if not pub_event.wait(timeout=90):
self._log("crypto: waiting for server public key timed out")
return
if push_thread is not None:
# the push is best-effort (its ack can lag behind a slow file
# transfer): never gate our readiness on it
push_thread.join(timeout=5)
with self._crypto_lock:
if self._crypto_handshake_gen != gen or self._crypto_server_pub_ok is not True:
stale = True
else:
stale = False
self._crypto_own_ready_sent = True # announce readiness: flip only once the server's /crypto_ready arrived too; sent on every handshake path
if stale:
return
try:
self.send_message(self.client_socket, "/crypto_ready", is_send_raw=True)
except OSError:
pass # connection already closed (reject/breaker): nothing to announce
with self._crypto_lock:
self._crypto_exchange_done.set()

threading.Thread(target=_wait_done, daemon=True).start()
with self._crypto_lock:
self._crypto_ack_event.set()

def _crypto_push_pub_key(self):
"""Push our public key file to the server via the file-transfer

mechanism (client is the sender).

Returns:
bool: Result produced by the operation.
"""
control_socket = self.client_socket
while (
True
): # serialise pushes: wait for a concurrent push (double handshake) instead of skipping it
with self._crypto_lock:
if control_socket not in self._crypto_push_active:
self._crypto_push_active.add(control_socket)
break
time.sleep(0.05)
try:
client_id = self._fid_alloc.alloc(receiver=(self.host, self.port))
with _transfer_handshake(self, control_socket, client_id) as handshake:
send_msg = f"/crypto_pub_key {client_id}"
if not _send_transfer_request(self, handshake, send_msg, is_send_raw=True):
return False
result = self._transfer_handshakes.wait(handshake, 10.0)
if result is None or result[0] != "port" or result[1] != client_id:
self._log("crypto: transfer port waiting timeout, public key push failed")
return False
_, _, file_server_port, _stamp = result
file_transfer_client_port = self.palloc()
try:
self.file_transfer_mode( # public-key bytes always travel plaintext
self.crypto.pub_path,
self.host,
file_server_port,
file_transfer_client_port,
control_socket=control_socket,
crypto="plain",
)
finally:
self.pfree(file_transfer_client_port)
except Exception:
self._log_exc()
return False
finally:
with self._crypto_lock:
self._crypto_push_active.discard(control_socket)
return True

def _crypto_store_received_pub(self, full_path, peer_role, server_addr):
"""TOFU-check the server's public key received via the file

transfer mechanism and cache it under the server endpoint.

On failure the connection is rejected and closed.

Args:
full_path (str): Value used by the operation.
peer_role (object): Value used by the operation.
server_addr (tuple): Value used by the operation.
"""
if self.crypto is None:
return
peer_ip, peer_port = server_addr
try:
with open(full_path, "r", encoding="utf-8") as f:
pem = f.read()
except OSError:
pem = ""
ok, reason = self.crypto.verify_peer_pub(peer_ip, peer_port, pem, peer_role)
if ok:
self.crypto.store_peer_pem(peer_role, peer_ip, peer_port, full_path)
with self._crypto_lock:
self._crypto_server_pem_path = self.crypto.peer_pem_path(
peer_role, peer_ip, peer_port
)
self._crypto_server_pub_ok = True
self._log(f"crypto: accepted server public key ({reason})")
else:
with self._crypto_lock:
self._crypto_server_pub_ok = False
self._log(f"crypto: REJECTED server public key: {reason}")
try:
os.remove(full_path) # rejected key: do not leave it in received_files/
except OSError:
pass
try:
self.send_message(self.client_socket, f"/crypto_reject {reason}", is_send_raw=True)
except Exception:
self._log_exc()
try:
self.close()
except Exception:
self._log_exc()
return
with self._crypto_lock:
self._crypto_server_pub_event.set()

def handle_server_command(self, command, control_socket=None):
"""Dispatch one command line pushed by the server.

Handles the protocol's own lines: ``/crypto_mode`` (a mismatch closes the
connection), ``/client_alloc_port_range``, the ``/crypto_*`` exchange lines,
and the transfer lines ``/file``, ``/file_folder``,
``/server_file_transfer_port``, ``/pause_trans``, ``/start_trans``,
``/resume_trans`` and FID-scoped ``/forward_error``.
Any other name goes to the handlers registered for
the "server" side via `register_command`; an unknown command is only
reported on the console.

Args:
command (str): Line including its leading ``/``.
control_socket (socket.socket | None): Actual source socket of the line.
"""
if control_socket is None:
control_socket = self.client_socket
if control_socket is not self.client_socket:
return # a replaced control session cannot dispatch into the new one
if command.split(maxsplit=1)[:1] and command.split(maxsplit=1)[0].lower() in (
"/pause_trans", "/start_trans"
):
_receive_transfer_control(self, control_socket, (self.host, self.port), command)
return
client_id = f"{self.client_host}:{self.client_port}"
if command.lower().split(" ")[0] == "/crypto_mode":
try:
peer_mode = int(command.split(" ")[1])
except (IndexError, ValueError):
peer_mode = -1
expected = 1 if self.is_enable_encrypto else 0
with self._crypto_lock:
self._crypto_mode_ok = peer_mode == expected
self._crypto_mode_event.set()
if not self._crypto_mode_ok:
self._log(
f"crypto: encryption mode mismatch with server "
f"(server={peer_mode}, client={expected}), disconnecting"
)
self.close()
return
if command.lower().split(" ")[0] == "/client_alloc_port_range":
if command.lower().split(" ")[1] == "no_limit":
self.is_hand_alloc_port = False
self._log("server has no limit on client port allocation")
else:
self.is_hand_alloc_port = True
self.each_client_port_range = int(command.split(" ")[1])
self.alloc_port(self.port_add_step, self.each_client_port_range)
self._log(
f"server allocated port range for each client: {self.each_client_port_range}"
)
elif shlex.split(command.lower())[0] == "/server_file_transfer_port":
announcement = _parse_transfer_port_announcement(command)
if announcement is not None:
port, fid, stamp = announcement
self._transfer_handshakes.resolve_port(control_socket, fid, port, stamp)
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == "/crypto_key_exchange"
):
parts = command.split(" ")
server_nonce = parts[1] if len(parts) > 1 else ""
force = len(parts) > 2 and parts[2] == "1"
self._crypto_on_server_hello(server_nonce, force)
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == "/crypto_key_exchange_ack"
):
parts = command.split(" ")
if len(parts) < 3:
return
with self._crypto_lock:
self._crypto_server_nonce = parts[1]
server_needs = parts[2]
force = len(parts) > 3 and parts[3] == "1"
self._crypto_after_ack(server_needs, force)
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == "/crypto_reject"
):
reason = command[len("/crypto_reject") :].strip()
self._log(f"crypto: connection rejected by server: {reason}")
self.close()
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == "/crypto_pub_key"
):
with self._crypto_lock:
handshake_started = self._crypto_handshake_started
if not handshake_started: # only accept key pushes while a handshake is in progress
self._debug("crypto: ignoring /crypto_pub_key outside a handshake")
return
self.file_transfer_client_recv_server_start_thread( # server pushes its key file; the receive hook TOFU-checks it
client_id, self.client_socket, command
)
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == "/crypto_ready"
):
with self._crypto_lock:
self._crypto_server_ready = True
self._crypto_try_flip()
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == CRYPTO_FRAMES_START
):
_session, channel = self._crypto_control_state(self.client_socket)
if channel is not None:
channel.note_peer_frames_ready()
self._crypto_publish_ecdh_pub(self.client_socket)
elif (
self.is_enable_encrypto
and self.crypto is not None
and command.lower().split(" ")[0] == CRYPTO_ECDH_PUB
):
# only ever accepted inside an RSA frame (see _PLAINTEXT_LINE_PREFIXES)
parts = command.split(" ", 1)
session = self._crypto_session_ensure()
if session is not None and len(parts) > 1:
if not session.set_peer_ecdh_b64(parts[1]):
self._log("crypto: rejected the server ECDH key")
elif shlex.split(command.lower())[0] == "/file":
self.file_transfer_client_recv_server_start_thread(
client_id, self.client_socket, command
)
elif shlex.split(command.lower())[0] == "/file_folder":
self.file_folder_transfer_client_recv_server_start_thread(
command, client_id, self.client_socket
)
elif shlex.split(command.lower())[0] == RESUME_LINE:
parsed = parse_resume_command(command)
if parsed is not None and control_socket is not None:
fid, offset, origin, target = parsed
if origin == control_socket.getsockname():
self._resume_on_socket(target, fid, offset, control_socket, forward_request=True)
elif shlex.split(command.lower())[0] == "/forward_error":
try:
parts = shlex.split(command)
except ValueError:
return
try:
fid = int(parts[1]) if len(parts) == 3 else -1
except ValueError:
return
if fid >= 0:
self._transfer_handshakes.resolve_error(control_socket, fid, parts[2])
else:
cmd_parts = shlex.split(command.strip())
if not cmd_parts:
return
cmd_name = cmd_parts[0].lower()
if cmd_name in self._custom_handlers[0]:
handler = self._custom_handlers[0][cmd_name]
run_in_thread = self._custom_handler_threaded[0].get(cmd_name, False)
if run_in_thread:
self.submit_task(
self._execute_custom_handler,
handler,
command,
self.client_socket,
client_id,
)
else:
self._execute_custom_handler(handler, command, self.client_socket, client_id)
else:
self._log(f"Unknown server command: {command}")

def _console_forward_send_msg(self, command):
"""Client console entry point for ``/forward_send_msg`` (client-only).

The forwarding command is only meaningful on a client: it parses the
typed request and asks the server (which runs the same-named relay)
to push each message to every listed destination.

Args:
command (object): Value used by the operation.

Returns:
NoneType | object: Result produced by the operation.
"""
parts = shlex.split(command)
items, addrs = parse_forward_items_and_addrs(parts[1:])
if not items or not addrs:
self._log(
"forward_send_msg: need at least one message and one destination, "
'e.g. /forward_send_msg "msg" "(\'127.0.0.1\', 3000)"'
)
return None
return self.forward_messages(items, addrs)

def forward_messages(self, messages, addrs):
"""Forward plain messages to other connected clients through the server.

The console command ``/forward_send_msg`` uses this; the client must be
connected. The server wraps each message in a ``/send_msg_from`` envelope so
the receiving client can attribute it back to this one.

Args:
messages (list[str]): Message texts to forward.
addrs (list[tuple]): Destination ``(ip, port)`` tuples.

Returns:
bool: True when the request was written to the server; False when the
client is not connected.
"""
request = "/forward_send_msg " + " ".join(shlex.quote(m) for m in messages)
request += " " + " ".join(shlex.quote(str(a)) for a in addrs)
return self.send_message(self.client_socket, request)

def _execute_custom_handler(self, handler, command, client_socket=None, client_address=None):
"""Handle the operation.

Args:
handler (callable): Value used by the operation.
command (object): Value used by the operation.
client_socket (socket.socket): Value used by the operation.
client_address (tuple): Value used by the operation.

Returns:
NoneType | object: Result produced by the operation.
"""
try:
result = handler(client_socket, client_address, command)
if result is not None:
if isinstance(result, str) and not result.endswith("\n"):
result += "\n"
try:
self.send_message(client_socket, result)
except Exception as e:
self._log(f"Error sending message: {e}")
return result
return None
except Exception as e:
error_msg = f"Error in custom command handler: {e}\n"
self._log_exc()
try:
self.send_message(client_socket, error_msg)
except Exception as e:
self._log(f"Error sending error message: {e}")
return error_msg

def interactive_mode(self): # Interactive mode
"""Read console lines and act on them until the client stops.

``/quit`` closes the connection; ``/send_msg``, ``/file``,
``/multiple_file``, ``/file_folder``, ``/multiple_file_folder``,
``/forward_file``, ``/forward_folder``, ``/forward_send_msg`` and
``/transfers`` are handled locally; other names go to handlers registered with
``where_to_run="client"``, and anything left is sent to the server as it
stands. Ctrl-C and EOF close the connection.
"""
client_id = f"{self.client_host}:{self.client_port}"
try:
while self.running:
try: # get user input
message = input()
if not self.running:
break
if message.strip():
if message.lower() == "/quit":
self.send_message(self.client_socket, "/quit")
time.sleep(0.5)
break
elif message.split(maxsplit=1)[0].lower() == "/transfers":
if message.strip().lower() != "/transfers":
print("Usage: /transfers")
else:
print(json.dumps(
self.get_transfer_progress(), ensure_ascii=False, indent=2
))
elif shlex.split(message.lower())[0] == "/send_msg":
self.send_message_to_server(message)
elif shlex.split(message.lower())[0] == "/file":
self.file_transfer_client_recv_client_start_thread(message)
elif shlex.split(message.lower())[0] == "/multiple_file":
self.multiple_file_transfer_client_recv_client_start(message)
elif shlex.split(message.lower())[0] == "/file_folder":
self.folder_file_transfer_client_recv_client_start(message)
elif shlex.split(message.lower())[0] == "/multiple_file_folder":
self.multiple_folder_file_transfer_client_recv_client_start(message)
elif shlex.split(message.lower())[0] == "/forward_file":
self.forward_file_console(message)
elif shlex.split(message.lower())[0] == "/forward_folder":
self.forward_folder_console(message)
elif shlex.split(message.lower())[0] == "/forward_send_msg":
# client-only message forwarding: relayed by the server
self._console_forward_send_msg(message)
else:
# the registered name is the whole first token
# ("/mycmd"), not the line's first character
cmd_parts = shlex.split(message)
cmd_name = cmd_parts[0].lower() if cmd_parts else ""
if cmd_name in self._custom_handlers[1]:
handler = self._custom_handlers[1][cmd_name]
run_in_thread = self._custom_handler_threaded[1].get(
cmd_name, False
)
if run_in_thread:
self.submit_task(
self._execute_custom_handler,
handler,
message,
self.client_socket,
client_id,
)
else:
self._execute_custom_handler(
handler, message, self.client_socket, client_id
)
else:
self.send_message(self.client_socket, message)
self._log(f"Unknown server command: {message}")
except KeyboardInterrupt:
self.close()
self._log("\nshutting down...")
self._log_exc()
self.send_message(self.client_socket, "/quit")
time.sleep(0.5)
break
except EOFError:
self.close()
self._log("\nshutting down...")
self._log_exc()
self.send_message(self.client_socket, "/quit")
time.sleep(0.5)
break
except:
self._log_exc()
pass
finally:
self.close()

def multiple_folder_file_transfer_client_recv_client_start(self, message):
"""Start folder transfers for each path in a client command.

Args:
message (object): Value used by the operation.
"""
transfer_folder_file_list = shlex.split(message)[1:]
destination_path = None
if len(transfer_folder_file_list) >= 2 and not os.path.isdir(transfer_folder_file_list[-1]):
destination_path = transfer_folder_file_list.pop()
for transfer_folder_file in transfer_folder_file_list:
command = "/file_folder {}".format(shlex.quote(transfer_folder_file))
if destination_path:
command += " {}".format(shlex.quote(destination_path))
folder_file_transfer_client_recv_client_start_thread = threading.Thread(
target=self.folder_file_transfer_client_recv_client_start,
args=(command,),
daemon=True,
)
folder_file_transfer_client_recv_client_start_thread.start()

def folder_file_transfer_client_recv_client_start(self, message):
"""Send a folder's contents to the connected server.

Args:
message (object): Value used by the operation.
"""
command_part = shlex.split(message)
folder_path = command_part[1]
destination_path = command_part[2] if len(command_part) >= 3 else None
if os.path.isdir(folder_path) == False:
self._log(f"{folder_path} is not a valid folder path")
return False
base_path = os.path.dirname(folder_path)

def get_relative_path(base_path, abs_path):
"""Handle the operation.

Args:
base_path (str): Value used by the operation.
abs_path (str): Value used by the operation.
"""
base = os.path.normpath(base_path)
abs_ = os.path.normpath(abs_path)
common = os.path.commonpath([base, abs_])
if common != base:
raise ValueError(f"'{abs_path}' is not a subpath of '{base_path}'")
rel = os.path.relpath(abs_, base)
if rel == ".":
return ""
rel = rel.replace(os.sep, "/")
return "/" + rel

def send_folder_transfer_command(folder_path, file_name=None, abspath=None):
"""Handle the operation.

Args:
folder_path (str): Value used by the operation.
file_name (str): Value used by the operation.
abspath (str): Value used by the operation.
"""
folder_transfer_command_message = "/file_folder {}".format(shlex.quote(folder_path))
if file_name:
each_file_transfer_command_message = "/file_folder {} {}".format(
shlex.quote(folder_path), shlex.quote(file_name)
)
if destination_path:
each_file_transfer_command_message += " {}".format(
shlex.quote(destination_path)
)
self.file_transfer_client_recv_client_start_thread(
each_file_transfer_command_message, abspath
)
self._log(f"start to send folder command: {each_file_transfer_command_message}")
else:
if destination_path:
folder_transfer_command_message += " {}".format(shlex.quote(destination_path))
self.send_message(self.client_socket, folder_transfer_command_message.strip())
self._log(f"start to send folder command: {folder_transfer_command_message}")

def start_file_transfer_with_limit(rel_dir, file, root):
"""Handle the operation.

Args:
rel_dir (str): Value used by the operation.
file (str): Value used by the operation.
root (object): Value used by the operation.
"""
cmd = f"/file_folder {shlex.quote(rel_dir)} {shlex.quote(file)}"
if destination_path:
cmd += " {}".format(shlex.quote(destination_path))

def limited_transfer():
"""Handle the operation."""
self.file_semaphore.acquire()
try:
self.file_transfer_client_recv_client_start(cmd, root)
finally:
self.file_semaphore.release()

thread = threading.Thread(target=limited_transfer, daemon=True)
thread.start()
self._log(f"start to send file: {cmd} (limit {self.max_thread_num})")

def get_all_files_in_folder():
"""Announce the directories that need it, then send every file."""
needed = _rel_dirs_with_files(folder_path, base_path)
if transfer_path in needed:
send_folder_transfer_command(transfer_path)
for root, _dirs, files in os.walk(folder_path):
rel_dir = get_relative_path(base_path, root)
if root != folder_path and rel_dir in needed:
send_folder_transfer_command(rel_dir)
for file in files:
start_file_transfer_with_limit(rel_dir, file, root)
self._log(f"finished sending all files in folder {folder_path}")

transfer_path = get_relative_path(base_path, folder_path)
get_all_files_in_folder()

def multiple_file_transfer_client_recv_client_start(self, message):
"""Start file transfers for each path in a client command.

Args:
message (object): Value used by the operation.
"""
file_list = shlex.split(message)[1:]
destination_path = None
if len(file_list) >= 2 and not os.path.isfile(file_list[-1]):
destination_path = file_list.pop()
for file in file_list:
each_file_transfer_command_message = "/file {}".format(shlex.quote(file))
if destination_path:
each_file_transfer_command_message += " {}".format(shlex.quote(destination_path))

def limited_transfer(cmd=each_file_transfer_command_message):
# hold the slot for the whole transfer, not only for the
# thread start, so max_thread_num really caps concurrency
self.file_semaphore.acquire()
try:
self.file_transfer_client_recv_client_start(cmd, None)
finally:
self.file_semaphore.release()

threading.Thread(target=limited_transfer, daemon=True).start()
self._log(f"start to send file command: {each_file_transfer_command_message}")

def file_transfer_client_recv_client_start_thread(self, message, file_folder_abspath=None):
"""Start a thread to send a file or folder item to the server.

Args:
message (object): Value used by the operation.
file_folder_abspath (str): Value used by the operation.
"""
file_transfer_client_recv_client_start_thread = threading.Thread(
target=self.file_transfer_client_recv_client_start,
args=(message, file_folder_abspath),
daemon=True,
)
file_transfer_client_recv_client_start_thread.start()

def file_transfer_client_recv_client_start(self, message, file_folder_abspath):
"""Send a file or folder item to the connected server.

Args:
message (object): Value used by the operation.
file_folder_abspath (str): Value used by the operation.
"""
client_id = self._fid_alloc.alloc(receiver=(self.host, self.port))
peer = (self.host, self.port)
control_socket = self.client_socket
try:
if shlex.split(message.lower())[0] == "/file_folder":
filename = os.path.join(file_folder_abspath, shlex.split(message)[2])
else:
filename = shlex.split(message)[1]
with _sending_transfer(self, (peer, client_id), control_socket=control_socket), \
_transfer_handshake(self, control_socket, client_id) as handshake:
send_msg = f"{message.strip()} {client_id}"
if not _send_transfer_request(self, handshake, send_msg):
return False
result = self._transfer_handshakes.wait(handshake, RESUME_PORT_TIMEOUT)
if result is None or result[0] != "port" or result[1] != client_id:
self._log("ErrorWhileReceiveFileServerPort: transfer port waiting timeout, file sending failed")
return False
_, _, file_server_port, stamp = result
file_transfer_client_port = self.palloc()
try:
self.file_transfer_mode(
filename, self.host, file_server_port, file_transfer_client_port,
control_socket=control_socket, crypto=stamp, fid=client_id,
peer=peer,
)
finally:
self.pfree(file_transfer_client_port)
except IndexError:
self._log_exc()
self._log("invalid command, please use '/file <filename>'")

def file_transfer_mode(
self,
filename,
server_address,
server_port,
client_port,
control_socket=None,
crypto=None,
fid=None,
peer=None,
resume_offset=0,
trans_type=0,
):
"""Send one file over a transfer sub-connection.

Args:
filename (str): Source file path.
server_address (str): Transfer listener address.
server_port (int): Transfer listener port.
client_port (int): Local port to bind for the transfer.
control_socket (socket.socket | None): Control socket carrying the mode stamp.
crypto (str | None): ``"plain"`` or encrypted transfer stamp.
fid (int | None): Transfer ID used for progress and pause tracking.
peer (tuple | None): Original receiver ``(ip, port)`` for resuming.
resume_offset (int): Byte offset to resume from; defaults to zero.
trans_type (int): 0 ordinary, 1 forwarded.

Returns:
bool: True only after the receiver's final data ACK; otherwise False.
"""
return self._send_file(
filename, server_address, server_port, client_port, control_socket,
crypto, fid, peer, resume_offset, trans_type,
)

def _send_file( # noqa: PLR0911 - peer-close and timeout exits are distinct outcomes
self, filename, server_address, server_port, client_port,
control_socket=None, crypto=None, fid=None, peer=None, resume_offset=0,
trans_type=0, *, forward_stream=None,
):
"""Send a file with either ordinary progress or independent relay progress."""
self._log(f"start to send file: {filename}")
transfer_key = ((peer if forward_stream is not None else (self.host, self.port)), fid) if fid is not None else None
client_file_socket = None
reset_time = 0
control = None

def close_socket():
"""Handle the operation."""
nonlocal file_running
nonlocal client_file_socket
file_running = False
self._transfer_controls.release_owner(client_file_socket)
self._crypto_drop_channel(client_file_socket)
client_file_socket.close()

while True:
try:
client_file_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if not self._transfer_handshakes.track_socket(control_socket, client_file_socket):
return False
control = _bind_transfer_control(
self, fid, control_socket, client_file_socket, trans_type, 0,
shared=forward_stream is not None,
)
client_file_socket.bind((self.client_host, client_port))
client_file_socket.connect((server_address, server_port))
break
except Exception as e:
self._transfer_handshakes.release_socket(control_socket, client_file_socket)
client_file_socket.close()
self._transfer_controls.release_owner(client_file_socket)
if _should_fallback_local_port(client_port, e):
self._log(
f"file transfer source port {client_port} is not available ({e}); "
"retrying from an OS-assigned port"
)
client_port = 0
continue
self._log(f"file transfer connection error: {e}")
self._log_exc()
if reset_time >= 20:
close_socket()
self._log("unable to connect to file transfer server, file sending failed")
return False
reset_time += 1
time.sleep(1)
try:
if crypto and crypto != "plain":
self._crypto_attach_transfer_out(client_file_socket, control_socket, crypto)
except _CryptoUnavailable as exc:
self._log(f"crypto: file transfer aborted: {exc}")
close_socket()
self._transfer_handshakes.release_socket(control_socket, client_file_socket)
return False
file_running = True
self._register_transfer_socket(transfer_key, client_file_socket)
transfer_signs = _TransferSignBuffer(
self.server_start_file_transfer_sign,
self.server_received_file_data_sign,
self.error_sign,
)

def receive_file_transfer_messages():
"""Handle the operation."""
nonlocal file_running
nonlocal client_file_socket
while file_running:
try:
data = self.receive_message(client_file_socket, self.recv_messages_chunk_len)
if not data:
self._log("\nbreak the file transfer connection from server")
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
close_socket()
break
if transfer_signs.feed(data):
self._log(
"\nError sign received from server, file transfer may have failed"
)
close_socket()
break
except Exception as e:
self._log(f"\nget file transfer msg error: {e}")
if not _is_closed_socket_error(e):
self._log_exc()
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
close_socket()
break

receive_thread = threading.Thread(target=receive_file_transfer_messages, daemon=True)
receive_thread.start()
waiting_time = 0
progress = None # this leg's file_upload_progress entry, when tracked
file_sent = False # True once the receiver acknowledged the whole file
source_missing = False # True when the source file no longer exists
try:
while True:
running = file_running
start_seen, _, error_seen = transfer_signs.consume()
if start_seen:
_announce_transfer_control(self, control)
break
if error_seen:
close_socket()
return False
if not running:
# peer closed the file connection: the receive thread
# already cleaned up; nothing more to wait for
return False
time.sleep(1)
waiting_time += 1
if waiting_time >= 10:
try:
self.send_message(client_file_socket, self.error_sign)
except Exception:
pass # send_message already logged real errors; a dead peer is expected
self._log(
f"ErrorWhileSendFile: \
Wait file transfer function start sign timeout, \
file {filename} sending failed"
)
close_socket()
return False
waiting_time = 0
file_size = os.path.getsize(filename)
file_name_encoded = os.path.basename(filename).encode("utf-8")
name_len = len(file_name_encoded)
self.send_message(client_file_socket, name_len.to_bytes(4, "big"))
self.send_message(client_file_socket, file_name_encoded)
self.send_message(client_file_socket, file_size.to_bytes(8, "big"))
if resume_offset < 0 or resume_offset > file_size:
resume_offset = 0 # not this file's offset any more: send it whole
if forward_stream is not None:
progress = [resume_offset, file_size, None, str(filename), peer]
forward_stream["progress"] = progress
else:
progress = self._file_progress_start(
self.file_upload_progress, transfer_key, file_size, filename,
peer=peer, initial=resume_offset,
)
if progress is None:
progress = self.file_upload_progress.get(transfer_key)
if progress is not None:
progress[0] = resume_offset
with open(filename, "rb") as f:
if resume_offset:
f.seek(resume_offset)
while f.tell() < file_size:
transfer_signs.consume()
_wait_transfer_control(self, control, client_file_socket)
file_data = f.read(self.file_transfer_chunk_len)
if not file_data:
break
try:
written = self.send_message(client_file_socket, file_data)
except OSError as e:
self._log(f"send error: {e}")
close_socket() # the peer is gone; stop instead of reading the rest
return False
if not written:
self._log("send error: the transfer connection is closed")
close_socket()
return False
self._file_progress_update(progress, len(file_data), is_upload=True)
extra_time = (file_size // (100 * 1024 * 1024)) * 10
timeout = int(30 + extra_time)
while True:
running = file_running
Expand Down Expand Up @@ -12273,20 +12381,41 @@

Stops the receive loop, releases the port range, flushes the message and
event stores, persists the interrupted transfers and closes the socket.
Safe to call more than once.
Waits for accepted custom tasks unless called by this instance's own
worker. A handler that never returns can block an external close indefinitely.
Safe to call more than once; a reconnect is not a terminal close.
"""
self._custom_executor.close(self._retire_client, self._flush_record_stores,
join_receiver=self._join_receive_thread)

Check failure on line 12389 in PyFlow/network_api/connect_tcp.py

View workflow job for this annotation

GitHub Actions / Lint

ruff (unformatted)

PyFlow/network_api/connect_tcp.py:141:1: unformatted: File would be reformatted

def _retire_client(self):
self.running = False
self._stopped = True # also cancels a connect() still in flight
sock = self.client_socket
self._stop_listeners()
if self.client_socket:
_retire_transfer_session(self, self.client_socket)
if sock is not None:
_retire_transfer_session(self, sock)
try:
# the receive thread may be blocked in recv() on this socket:
# close() alone sends no FIN and leaves that read waiting for its
# timeout, so the server would not see the disconnect
self.client_socket.shutdown(socket.SHUT_RDWR)
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass # peer already gone
with self._crypto_lock:
if sock is not None:
self._channels.pop(sock, None)
self._encrypted_sockets.discard(sock)
self._control_sockets.discard(sock)
self._crypto_session = None
if sock is not None:
sock.close()
self.free_port()
# transfers still in flight are kept on disk for the next connect
self._persist_transfer_progress()
self._log("connection closed")

def _join_receive_thread(self):
receive_thread = self.receive_thread
if (
receive_thread is not None
Expand All @@ -12296,19 +12425,6 @@
# close() returns only after the receive loop has stopped: no
# in-flight chunk may reach a listener after this point
receive_thread.join()
self.free_port()
self._flush_record_stores()
# transfers still in flight are kept on disk for the next connect
self._persist_transfer_progress()
with self._crypto_lock:
if self.client_socket is not None:
self._channels.pop(self.client_socket, None)
self._encrypted_sockets.discard(self.client_socket)
self._control_sockets.discard(self.client_socket)
self._crypto_session = None
if self.client_socket:
self.client_socket.close()
self._log("connection closed")

def _release_client_socket(self):
"""Retire the captured control session and release its local port.
Expand Down
Loading
Loading