46 lines
1.5 KiB
Python
46 lines
1.5 KiB
Python
|
|
import asyncio
|
|||
|
|
import os, stat
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
|
|||
|
|
async def file_thread(operation, *args, **kwargs):
|
|||
|
|
"""取消等待不会停止系统线程;真实文件操作结束后才能释放执行/上传保护。"""
|
|||
|
|
worker = asyncio.create_task(asyncio.to_thread(operation, *args, **kwargs))
|
|||
|
|
try:
|
|||
|
|
return await asyncio.shield(worker)
|
|||
|
|
except asyncio.CancelledError:
|
|||
|
|
# 多次cancel也不能让底层线程失去跟踪;只等待本次本地文件操作。
|
|||
|
|
while not worker.done():
|
|||
|
|
try:
|
|||
|
|
await asyncio.shield(worker)
|
|||
|
|
except asyncio.CancelledError:
|
|||
|
|
continue
|
|||
|
|
except Exception:
|
|||
|
|
break
|
|||
|
|
if not worker.cancelled():
|
|||
|
|
worker.exception()
|
|||
|
|
raise
|
|||
|
|
|
|||
|
|
|
|||
|
|
def confined(root, value, *, exists=False):
|
|||
|
|
root = Path(root).resolve()
|
|||
|
|
path = Path(value)
|
|||
|
|
path = (path if path.is_absolute() else root / path).resolve(strict=exists)
|
|||
|
|
if not path.is_relative_to(root):
|
|||
|
|
raise ValueError("File is outside its permitted directory")
|
|||
|
|
return path
|
|||
|
|
|
|||
|
|
|
|||
|
|
def safe_file(root, value):
|
|||
|
|
path = confined(root, value, exists=True)
|
|||
|
|
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
|
|||
|
|
try:
|
|||
|
|
if not stat.S_ISREG(os.fstat(fd).st_mode):
|
|||
|
|
raise ValueError("Regular file required")
|
|||
|
|
if os.name == "posix":
|
|||
|
|
confined(root, os.readlink(f"/proc/self/fd/{fd}"), exists=True)
|
|||
|
|
return os.fdopen(fd, "rb")
|
|||
|
|
except BaseException:
|
|||
|
|
os.close(fd)
|
|||
|
|
raise
|