327 lines
11 KiB
Python
327 lines
11 KiB
Python
import ctypes
|
|
import errno
|
|
import fcntl
|
|
import heapq
|
|
import os
|
|
import signal
|
|
import stat
|
|
import sys
|
|
from contextlib import contextmanager, suppress
|
|
from uuid import uuid4
|
|
|
|
from . import web_node_apply as web
|
|
from .node_stream import STREAM_CHUNK_SIZE, encode_header, read_header
|
|
from .web_node_access import website_suspension_path
|
|
from .website_files import (
|
|
LIST_PAGE_SIZE,
|
|
REQUEST_HEADER_LIMIT,
|
|
TEMPORARY_PREFIX,
|
|
WebsiteFileRequest,
|
|
directory_parts,
|
|
validate_entry_name,
|
|
)
|
|
|
|
OPEN_DIRECTORY = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW
|
|
RENAME_NOREPLACE = 1
|
|
PROBLEMS = {
|
|
errno.EDQUOT: "The website storage quota has been reached.",
|
|
errno.ENOSPC: "The web node has no space for this upload.",
|
|
errno.EEXIST: "A file or folder with that name already exists.",
|
|
errno.ENOENT: "The selected file or folder is no longer available.",
|
|
errno.ENOTEMPTY: "Empty the folder before removing it.",
|
|
errno.ELOOP: "The path must point to a regular website file or folder.",
|
|
errno.ENOTDIR: "The selected folder is unavailable.",
|
|
errno.EACCES: "The website user cannot access this entry.",
|
|
errno.EPERM: "The website user cannot change this entry.",
|
|
}
|
|
|
|
# Resolve libc before entering the website filesystem.
|
|
renameat2 = getattr(ctypes.CDLL(None, use_errno=True), "renameat2", None)
|
|
if renameat2 is not None:
|
|
renameat2.argtypes = (
|
|
ctypes.c_int,
|
|
ctypes.c_char_p,
|
|
ctypes.c_int,
|
|
ctypes.c_char_p,
|
|
ctypes.c_uint,
|
|
)
|
|
renameat2.restype = ctypes.c_int
|
|
|
|
|
|
@contextmanager
|
|
def website_user(site):
|
|
if os.geteuid() != 0:
|
|
raise ValueError("Run the website files receiver as root.")
|
|
with web.locked_web_node(fcntl.LOCK_SH):
|
|
if os.path.lexists(website_suspension_path(site)):
|
|
raise ValueError("This website is suspended.")
|
|
try:
|
|
public, uid, web_gid = web.site_storage(site)
|
|
account = web.current_user(site.service_user)
|
|
if account is None or account.pw_uid != uid:
|
|
raise ValueError
|
|
except (OSError, ValueError):
|
|
raise ValueError(
|
|
"This website is unavailable on the web node."
|
|
) from None
|
|
file_descriptor = os.open(public, OPEN_DIRECTORY)
|
|
try:
|
|
root = os.fstat(file_descriptor)
|
|
if uid == 0 or (root.st_uid, root.st_gid) != (uid, web_gid):
|
|
raise ValueError(
|
|
"This website is unavailable on the web node."
|
|
)
|
|
os.fchdir(file_descriptor)
|
|
os.chroot(".")
|
|
os.chdir("/")
|
|
os.setgroups([web_gid])
|
|
os.setresgid(account.pw_gid, account.pw_gid, account.pw_gid)
|
|
os.setresuid(uid, uid, uid)
|
|
finally:
|
|
os.close(file_descriptor)
|
|
yield uid, web_gid, root.st_dev
|
|
|
|
|
|
def permitted(info, uid, device):
|
|
return (
|
|
info.st_uid == uid
|
|
and info.st_dev == device
|
|
and (
|
|
stat.S_ISDIR(info.st_mode)
|
|
or (stat.S_ISREG(info.st_mode) and info.st_nlink == 1)
|
|
)
|
|
)
|
|
|
|
|
|
@contextmanager
|
|
def open_folder(path, uid, device):
|
|
folder = os.open("/", OPEN_DIRECTORY)
|
|
try:
|
|
for part in directory_parts(path):
|
|
child = os.open(part, OPEN_DIRECTORY, dir_fd=folder)
|
|
os.close(folder)
|
|
folder = child
|
|
if not permitted(os.fstat(folder), uid, device):
|
|
raise ValueError("The selected folder is unavailable.")
|
|
yield folder
|
|
finally:
|
|
os.close(folder)
|
|
|
|
|
|
def entry_info(folder, name, uid, device):
|
|
info = os.stat(name, dir_fd=folder, follow_symlinks=False)
|
|
if not permitted(info, uid, device):
|
|
raise ValueError("The selected website entry is unavailable.")
|
|
return info
|
|
|
|
|
|
def list_folder(folder, after, uid, device):
|
|
def candidates(entries):
|
|
for entry in entries:
|
|
if entry.name <= after:
|
|
continue
|
|
try:
|
|
validate_entry_name(entry.name)
|
|
info = entry.stat(follow_symlinks=False)
|
|
except (FileNotFoundError, ValueError):
|
|
continue
|
|
if permitted(info, uid, device):
|
|
yield entry.name, stat.S_ISDIR(info.st_mode), info.st_size
|
|
|
|
with os.scandir(folder) as entries:
|
|
items = heapq.nsmallest(LIST_PAGE_SIZE + 1, candidates(entries))
|
|
page = [
|
|
{
|
|
"name": name,
|
|
"is_directory": directory,
|
|
"size": 0 if directory else size,
|
|
}
|
|
for name, directory, size in items[:LIST_PAGE_SIZE]
|
|
]
|
|
after = page[-1]["name"] if len(items) > LIST_PAGE_SIZE else ""
|
|
return {"entries": page, "after": after}
|
|
|
|
|
|
def rename_entry(folder, source, target):
|
|
if renameat2 is None:
|
|
raise ValueError(
|
|
"This web node cannot rename files without replacing them."
|
|
)
|
|
result = renameat2(
|
|
folder,
|
|
os.fsencode(source),
|
|
folder,
|
|
os.fsencode(target),
|
|
RENAME_NOREPLACE,
|
|
)
|
|
if result:
|
|
error = ctypes.get_errno()
|
|
raise OSError(error, os.strerror(error))
|
|
|
|
|
|
def upload_file(folder, name, size, source, web_gid):
|
|
staged = TEMPORARY_PREFIX + uuid4().hex
|
|
descriptor = os.open(
|
|
staged,
|
|
os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW,
|
|
0o600,
|
|
dir_fd=folder,
|
|
)
|
|
try:
|
|
with os.fdopen(descriptor, "wb") as output:
|
|
remaining = size
|
|
while remaining:
|
|
chunk = source.read(min(STREAM_CHUNK_SIZE, remaining))
|
|
if not chunk:
|
|
raise ValueError(
|
|
"The upload ended before the file was complete."
|
|
)
|
|
output.write(chunk)
|
|
remaining -= len(chunk)
|
|
if source.read(1):
|
|
raise ValueError("The upload exceeded its declared file size.")
|
|
output.flush()
|
|
os.fchown(output.fileno(), -1, web_gid)
|
|
os.fchmod(output.fileno(), 0o640)
|
|
os.fsync(output.fileno())
|
|
rename_entry(folder, staged, name)
|
|
os.fsync(folder)
|
|
finally:
|
|
with suppress(FileNotFoundError):
|
|
os.unlink(staged, dir_fd=folder)
|
|
|
|
|
|
def open_download(folder, name, uid, device):
|
|
if not stat.S_ISREG(entry_info(folder, name, uid, device).st_mode):
|
|
raise ValueError("Choose a file to download.")
|
|
descriptor = os.open(
|
|
name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=folder
|
|
)
|
|
source = os.fdopen(descriptor, "rb")
|
|
info = os.fstat(source.fileno())
|
|
if not stat.S_ISREG(info.st_mode) or not permitted(info, uid, device):
|
|
source.close()
|
|
raise ValueError(
|
|
"The file changed before download. Refresh the folder."
|
|
)
|
|
return source, info.st_size
|
|
|
|
|
|
def create_directory(folder, name, web_gid):
|
|
staged = TEMPORARY_PREFIX + uuid4().hex
|
|
os.mkdir(staged, 0o700, dir_fd=folder)
|
|
try:
|
|
descriptor = os.open(staged, OPEN_DIRECTORY, dir_fd=folder)
|
|
try:
|
|
os.fchown(descriptor, -1, web_gid)
|
|
os.fchmod(descriptor, 0o750)
|
|
finally:
|
|
os.close(descriptor)
|
|
rename_entry(folder, staged, name)
|
|
finally:
|
|
with suppress(FileNotFoundError):
|
|
os.rmdir(staged, dir_fd=folder)
|
|
|
|
|
|
def change_entry(request, folder, uid, web_gid, device):
|
|
if request.operation == "mkdir":
|
|
create_directory(folder, request.name, web_gid)
|
|
else:
|
|
info = entry_info(folder, request.name, uid, device)
|
|
if request.operation == "rename":
|
|
rename_entry(folder, request.name, request.target)
|
|
elif stat.S_ISDIR(info.st_mode):
|
|
os.rmdir(request.name, dir_fd=folder)
|
|
else:
|
|
os.unlink(request.name, dir_fd=folder)
|
|
os.fsync(folder)
|
|
|
|
|
|
def reply(output, identity, state, **data):
|
|
output.write(
|
|
encode_header(
|
|
{
|
|
"version": 1,
|
|
"identity": identity,
|
|
"state": state,
|
|
**data,
|
|
}
|
|
)
|
|
)
|
|
output.flush()
|
|
|
|
|
|
def cancel_upload(signum, frame):
|
|
raise InterruptedError("The file request expired.")
|
|
|
|
|
|
def discard_upload(source, size):
|
|
while size:
|
|
chunk = source.read1(min(STREAM_CHUNK_SIZE, size))
|
|
if not chunk:
|
|
return
|
|
size -= len(chunk)
|
|
|
|
|
|
def serve_website_files():
|
|
source, output = sys.stdin.buffer, sys.stdout.buffer
|
|
request = None
|
|
identity = ""
|
|
started_download = False
|
|
signal.signal(signal.SIGTERM, cancel_upload)
|
|
try:
|
|
request = WebsiteFileRequest.from_manifest(
|
|
read_header(
|
|
source,
|
|
maximum=REQUEST_HEADER_LIMIT,
|
|
label="website file request",
|
|
)
|
|
)
|
|
identity = request.identity()
|
|
with (
|
|
website_user(request.site) as (uid, web_gid, device),
|
|
open_folder(request.directory, uid, device) as folder,
|
|
):
|
|
if request.operation == "download":
|
|
file, remaining = open_download(
|
|
folder, request.name, uid, device
|
|
)
|
|
with file:
|
|
reply(output, identity, "ready", size=remaining)
|
|
started_download = True
|
|
while remaining:
|
|
chunk = file.read(min(STREAM_CHUNK_SIZE, remaining))
|
|
if not chunk:
|
|
return 1
|
|
output.write(chunk)
|
|
remaining -= len(chunk)
|
|
output.flush()
|
|
return 0
|
|
if request.operation == "list":
|
|
result = list_folder(folder, request.after, uid, device)
|
|
else:
|
|
if request.operation == "upload":
|
|
upload_file(
|
|
folder, request.name, request.size, source, web_gid
|
|
)
|
|
else:
|
|
change_entry(request, folder, uid, web_gid, device)
|
|
result = {}
|
|
reply(output, identity, "ready", **result)
|
|
return 0
|
|
except (OSError, ValueError) as error:
|
|
if not started_download:
|
|
problem = (
|
|
str(error)
|
|
if isinstance(error, ValueError)
|
|
else PROBLEMS.get(
|
|
error.errno,
|
|
"The web node could not complete this file operation.",
|
|
)
|
|
)
|
|
with suppress(OSError):
|
|
reply(output, identity, "failed", problem=problem)
|
|
if request is not None and request.operation == "upload":
|
|
discard_upload(source, request.size)
|
|
return 1
|