Skillfarm / skills · skillfarm.ai / converted / docx / scripts / office / soffice.py
| 1 | """ |
| 2 | Helper for running LibreOffice (soffice) in environments where AF_UNIX |
| 3 | sockets may be blocked (e.g., sandboxed VMs). Detects the restriction |
| 4 | at runtime and applies an LD_PRELOAD shim if needed. |
| 5 | |
| 6 | Usage: |
| 7 | from office.soffice import run_soffice |
| 8 | |
| 9 | result = run_soffice(["--headless", "--convert-to", "pdf", "input.docx"]) |
| 10 | |
| 11 | Call soffice through run_soffice, not through subprocess with get_soffice_env(): |
| 12 | the env dict carries the shim but names no user profile, and a non-root sandbox |
| 13 | cannot bootstrap the default one -- soffice aborts with "User installation could |
| 14 | not be completed" and converts nothing. get_soffice_env() stays public for the |
| 15 | callers that build their own argv (they must pass -env:UserInstallation too). |
| 16 | """ |
| 17 | |
| 18 | from __future__ import annotations |
| 19 | |
| 20 | import contextlib |
| 21 | import os |
| 22 | import re |
| 23 | import shutil |
| 24 | import socket |
| 25 | import subprocess |
| 26 | import tempfile |
| 27 | import zipfile |
| 28 | from collections.abc import Iterable |
| 29 | from pathlib import Path |
| 30 | |
| 31 | |
| 32 | def get_soffice_env() -> dict: |
| 33 | env = os.environ.copy() |
| 34 | env["SAL_USE_VCLPLUGIN"] = "svp" |
| 35 | |
| 36 | if _needs_shim(): |
| 37 | shim = _ensure_shim() |
| 38 | env["LD_PRELOAD"] = str(shim) |
| 39 | |
| 40 | return env |
| 41 | |
| 42 | |
| 43 | def run_soffice(args: Iterable[str], **kwargs) -> subprocess.CompletedProcess: |
| 44 | args = list(args) |
| 45 | with contextlib.ExitStack() as stack: |
| 46 | if not any(str(a).startswith("-env:UserInstallation") for a in args): |
| 47 | profile = stack.enter_context( |
| 48 | tempfile.TemporaryDirectory(prefix="lo_profile_", ignore_cleanup_errors=True) |
| 49 | ) |
| 50 | args = [f"-env:UserInstallation={Path(profile).as_uri()}"] + args |
| 51 | if _draws_the_document(args): |
| 52 | copies = Path(stack.enter_context( |
| 53 | tempfile.TemporaryDirectory(prefix="lo_input_", ignore_cleanup_errors=True) |
| 54 | )) |
| 55 | args = [_without_outside_links(str(a), copies / str(i)) for i, a in enumerate(args)] |
| 56 | return subprocess.run(["soffice"] + args, env=get_soffice_env(), **kwargs) |
| 57 | |
| 58 | |
| 59 | |
| 60 | _SHIM_SO = Path(tempfile.gettempdir()) / "lo_socket_shim.so" |
| 61 | |
| 62 | _DRAWN_FORMATS = frozenset( |
| 63 | {"pdf", "png", "jpg", "jpeg", "gif", "bmp", "tif", "tiff", "webp", "svg", "eps", "emf", "wmf"} |
| 64 | ) |
| 65 | _WEB_OR_MAIL = re.compile(r"^(?:https?|mailto):", re.I) |
| 66 | _RELS_NS = "http://schemas.openxmlformats.org/package/2006/relationships" |
| 67 | _NO_RELS = f'<Relationships xmlns="{_RELS_NS}"/>'.encode() |
| 68 | _MAX_RELS_BYTES = 32 * 1024 * 1024 |
| 69 | |
| 70 | |
| 71 | def _draws_the_document(args: list) -> bool: |
| 72 | for flag, value in zip(args, args[1:]): |
| 73 | if str(flag) in ("--convert-to", "-convert-to"): |
| 74 | return str(value).split(":")[0].lower() in _DRAWN_FORMATS |
| 75 | return False |
| 76 | |
| 77 | |
| 78 | def _cut_outside_links(rels: bytes) -> bytes | None: |
| 79 | from defusedxml import ElementTree |
| 80 | |
| 81 | try: |
| 82 | root = ElementTree.fromstring(rels) |
| 83 | except (ElementTree.ParseError, ValueError, LookupError): |
| 84 | return _NO_RELS |
| 85 | cut = False |
| 86 | for entry in root.iter(): |
| 87 | if entry.get("TargetMode", "Internal") == "Internal": |
| 88 | continue |
| 89 | if _WEB_OR_MAIL.match(entry.get("Target", "")): |
| 90 | continue |
| 91 | entry.set("TargetMode", "External") |
| 92 | entry.set("Target", "about:blank") |
| 93 | cut = True |
| 94 | if not cut: |
| 95 | return None |
| 96 | for element in root.iter(): |
| 97 | element.tag = element.tag.rsplit("}", 1)[-1] |
| 98 | root.set("xmlns", _RELS_NS) |
| 99 | return ElementTree.tostring(root) |
| 100 | |
| 101 | |
| 102 | def _without_outside_links(arg: str, folder: Path) -> str: |
| 103 | |
| 104 | if not os.path.isfile(arg) or not zipfile.is_zipfile(arg): |
| 105 | return arg |
| 106 | with open(arg, "rb") as file: |
| 107 | if file.read(4) != b"PK\x03\x04": |
| 108 | return arg |
| 109 | with zipfile.ZipFile(arg) as package: |
| 110 | cut = {} |
| 111 | for member in package.infolist(): |
| 112 | if member.filename.lower().endswith(".rels"): |
| 113 | try: |
| 114 | data = package.read(member) if member.file_size <= _MAX_RELS_BYTES else None |
| 115 | except Exception: |
| 116 | data = None |
| 117 | rels = _NO_RELS if data is None else _cut_outside_links(data) |
| 118 | if rels is not None: |
| 119 | cut[member.filename] = rels |
| 120 | if not cut: |
| 121 | return arg |
| 122 | folder.mkdir() |
| 123 | copy = folder / Path(arg).name |
| 124 | with zipfile.ZipFile(copy, "w") as out: |
| 125 | for member in package.infolist(): |
| 126 | entry = zipfile.ZipInfo(member.filename, member.date_time) |
| 127 | entry.compress_type = member.compress_type |
| 128 | if member.filename in cut: |
| 129 | entry.compress_type = zipfile.ZIP_DEFLATED |
| 130 | out.writestr(entry, cut[member.filename]) |
| 131 | else: |
| 132 | with package.open(member) as source, out.open(entry, "w", force_zip64=True) as target: |
| 133 | shutil.copyfileobj(source, target) |
| 134 | return str(copy) |
| 135 | |
| 136 | |
| 137 | def _needs_shim() -> bool: |
| 138 | try: |
| 139 | s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 140 | s.close() |
| 141 | return False |
| 142 | except OSError: |
| 143 | return True |
| 144 | |
| 145 | |
| 146 | def _ensure_shim() -> Path: |
| 147 | if _SHIM_SO.exists(): |
| 148 | return _SHIM_SO |
| 149 | |
| 150 | src = Path(tempfile.gettempdir()) / "lo_socket_shim.c" |
| 151 | src.write_text(_SHIM_SOURCE, encoding="utf-8") |
| 152 | subprocess.run( |
| 153 | ["gcc", "-shared", "-fPIC", "-o", str(_SHIM_SO), str(src), "-ldl"], |
| 154 | check=True, |
| 155 | capture_output=True, |
| 156 | ) |
| 157 | src.unlink() |
| 158 | return _SHIM_SO |
| 159 | |
| 160 | |
| 161 | |
| 162 | _SHIM_SOURCE = r""" |
| 163 | #define _GNU_SOURCE |
| 164 | #include <dlfcn.h> |
| 165 | #include <errno.h> |
| 166 | #include <signal.h> |
| 167 | #include <stdio.h> |
| 168 | #include <stdlib.h> |
| 169 | #include <sys/socket.h> |
| 170 | #include <unistd.h> |
| 171 | |
| 172 | static int (*real_socket)(int, int, int); |
| 173 | static int (*real_socketpair)(int, int, int, int[2]); |
| 174 | static int (*real_listen)(int, int); |
| 175 | static int (*real_accept)(int, struct sockaddr *, socklen_t *); |
| 176 | static int (*real_close)(int); |
| 177 | static int (*real_read)(int, void *, size_t); |
| 178 | |
| 179 | /* Per-FD bookkeeping (FDs >= 1024 are passed through unshimmed). */ |
| 180 | static int is_shimmed[1024]; |
| 181 | static int peer_of[1024]; |
| 182 | static int wake_r[1024]; /* accept() blocks reading this */ |
| 183 | static int wake_w[1024]; /* close() writes to this */ |
| 184 | static int listener_fd = -1; /* FD that received listen() */ |
| 185 | |
| 186 | __attribute__((constructor)) |
| 187 | static void init(void) { |
| 188 | real_socket = dlsym(RTLD_NEXT, "socket"); |
| 189 | real_socketpair = dlsym(RTLD_NEXT, "socketpair"); |
| 190 | real_listen = dlsym(RTLD_NEXT, "listen"); |
| 191 | real_accept = dlsym(RTLD_NEXT, "accept"); |
| 192 | real_close = dlsym(RTLD_NEXT, "close"); |
| 193 | real_read = dlsym(RTLD_NEXT, "read"); |
| 194 | for (int i = 0; i < 1024; i++) { |
| 195 | peer_of[i] = -1; |
| 196 | wake_r[i] = -1; |
| 197 | wake_w[i] = -1; |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | /* ---- socket ---------------------------------------------------------- */ |
| 202 | int socket(int domain, int type, int protocol) { |
| 203 | if (domain == AF_UNIX) { |
| 204 | int fd = real_socket(domain, type, protocol); |
| 205 | if (fd >= 0) return fd; |
| 206 | /* socket(AF_UNIX) blocked – fall back to socketpair(). */ |
| 207 | int sv[2]; |
| 208 | if (real_socketpair(domain, type, protocol, sv) == 0) { |
| 209 | if (sv[0] >= 0 && sv[0] < 1024) { |
| 210 | is_shimmed[sv[0]] = 1; |
| 211 | peer_of[sv[0]] = sv[1]; |
| 212 | int wp[2]; |
| 213 | if (pipe(wp) == 0) { |
| 214 | wake_r[sv[0]] = wp[0]; |
| 215 | wake_w[sv[0]] = wp[1]; |
| 216 | } |
| 217 | } |
| 218 | return sv[0]; |
| 219 | } |
| 220 | errno = EPERM; |
| 221 | return -1; |
| 222 | } |
| 223 | return real_socket(domain, type, protocol); |
| 224 | } |
| 225 | |
| 226 | /* ---- listen ---------------------------------------------------------- */ |
| 227 | int listen(int sockfd, int backlog) { |
| 228 | if (sockfd >= 0 && sockfd < 1024 && is_shimmed[sockfd]) { |
| 229 | listener_fd = sockfd; |
| 230 | return 0; |
| 231 | } |
| 232 | return real_listen(sockfd, backlog); |
| 233 | } |
| 234 | |
| 235 | /* ---- accept ---------------------------------------------------------- */ |
| 236 | int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen) { |
| 237 | if (sockfd >= 0 && sockfd < 1024 && is_shimmed[sockfd]) { |
| 238 | /* Block until close() writes to the wake pipe. */ |
| 239 | if (wake_r[sockfd] >= 0) { |
| 240 | char buf; |
| 241 | real_read(wake_r[sockfd], &buf, 1); |
| 242 | } |
| 243 | errno = ECONNABORTED; |
| 244 | return -1; |
| 245 | } |
| 246 | return real_accept(sockfd, addr, addrlen); |
| 247 | } |
| 248 | |
| 249 | /* ---- close ----------------------------------------------------------- */ |
| 250 | int close(int fd) { |
| 251 | if (fd >= 0 && fd < 1024 && is_shimmed[fd]) { |
| 252 | int was_listener = (fd == listener_fd); |
| 253 | is_shimmed[fd] = 0; |
| 254 | |
| 255 | if (wake_w[fd] >= 0) { /* unblock accept() */ |
| 256 | char c = 0; |
| 257 | write(wake_w[fd], &c, 1); |
| 258 | real_close(wake_w[fd]); |
| 259 | wake_w[fd] = -1; |
| 260 | } |
| 261 | if (wake_r[fd] >= 0) { real_close(wake_r[fd]); wake_r[fd] = -1; } |
| 262 | if (peer_of[fd] >= 0) { real_close(peer_of[fd]); peer_of[fd] = -1; } |
| 263 | |
| 264 | if (was_listener) |
| 265 | _exit(0); /* conversion done – exit */ |
| 266 | } |
| 267 | return real_close(fd); |
| 268 | } |
| 269 | """ |
| 270 | |
| 271 | |
| 272 | |
| 273 | if __name__ == "__main__": |
| 274 | import sys |
| 275 | result = run_soffice(sys.argv[1:]) |
| 276 | sys.exit(result.returncode) |