soffice.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. """LibreOffice (soffice) launcher with AF_UNIX fallback.
  2. Sandboxed VMs (e.g. macOS App Sandbox / Linux seccomp) may prohibit AF_UNIX
  3. sockets. Detect this at runtime and use an LD_PRELOAD shim to replace
  4. socket(AF_UNIX) with socketpair() as a fallback.
  5. Public API (identical to upstream, outside this rewrite's scope)::
  6. from office.soffice import run_soffice, get_soffice_env
  7. # Run soffice directly
  8. result = run_soffice(["--headless", "--convert-to", "pdf", "input.docx"])
  9. # Get an environment with LD_PRELOAD and spawn the process yourself
  10. env = get_soffice_env()
  11. subprocess.run(["soffice", ...], env=env)
  12. Part of the MiniMax xlsx skill (MIT). See LICENSE for terms.
  13. """
  14. import os
  15. import socket
  16. import subprocess
  17. import tempfile
  18. from pathlib import Path
  19. def get_soffice_env() -> dict:
  20. env = os.environ.copy()
  21. env["SAL_USE_VCLPLUGIN"] = "svp"
  22. if _needs_unix_socket_shim():
  23. preload = _compile_preload()
  24. env["LD_PRELOAD"] = str(preload)
  25. return env
  26. def run_soffice(args: list[str], **kwargs) -> subprocess.CompletedProcess:
  27. env = get_soffice_env()
  28. return subprocess.run(["soffice"] + args, env=env, **kwargs)
  29. _PRELOAD_OBJECT = Path(tempfile.gettempdir()) / "lo_socket_shim.so"
  30. def _needs_unix_socket_shim() -> bool:
  31. try:
  32. s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  33. s.close()
  34. return False
  35. except OSError:
  36. return True
  37. def _compile_preload() -> Path:
  38. if _PRELOAD_OBJECT.exists():
  39. return _PRELOAD_OBJECT
  40. src = Path(tempfile.gettempdir()) / "lo_socket_shim.c"
  41. src.write_text(_PRELOAD_C_SOURCE)
  42. subprocess.run(
  43. ["gcc", "-shared", "-fPIC", "-o", str(_PRELOAD_OBJECT), str(src), "-ldl"],
  44. check=True,
  45. capture_output=True,
  46. )
  47. src.unlink()
  48. return _PRELOAD_OBJECT
  49. # Note: The C source below is compiled at runtime to /tmp/lo_socket_shim.so and loaded through LD_PRELOAD.
  50. # The build uses source bytes as input. Even seemingly insignificant source edits (renaming locals,
  51. # removing whitespace) make the cached .so differ from the new source and can prevent LibreOffice
  52. # from starting on sandboxed Linux. This differentiated rewrite strictly preserves the C source bytes;
  53. # only the Python wrapper is renamed.
  54. _PRELOAD_C_SOURCE = r"""
  55. #define _GNU_SOURCE
  56. #include <dlfcn.h>
  57. #include <errno.h>
  58. #include <signal.h>
  59. #include <stdio.h>
  60. #include <stdlib.h>
  61. #include <sys/socket.h>
  62. #include <unistd.h>
  63. static int (*real_socket)(int, int, int);
  64. static int (*real_socketpair)(int, int, int, int[2]);
  65. static int (*real_listen)(int, int);
  66. static int (*real_accept)(int, struct sockaddr *, socklen_t *);
  67. static int (*real_close)(int);
  68. static int (*real_read)(int, void *, size_t);
  69. /* Per-FD bookkeeping (FDs >= 1024 are passed through unshimmed). */
  70. static int is_shimmed[1024];
  71. static int peer_of[1024];
  72. static int wake_r[1024]; /* accept() blocks reading this */
  73. static int wake_w[1024]; /* close() writes to this */
  74. static int listener_fd = -1; /* FD that received listen() */
  75. __attribute__((constructor))
  76. static void init(void) {
  77. real_socket = dlsym(RTLD_NEXT, "socket");
  78. real_socketpair = dlsym(RTLD_NEXT, "socketpair");
  79. real_listen = dlsym(RTLD_NEXT, "listen");
  80. real_accept = dlsym(RTLD_NEXT, "accept");
  81. real_close = dlsym(RTLD_NEXT, "close");
  82. real_read = dlsym(RTLD_NEXT, "read");
  83. for (int i = 0; i < 1024; i++) {
  84. peer_of[i] = -1;
  85. wake_r[i] = -1;
  86. wake_w[i] = -1;
  87. }
  88. }
  89. /* ---- socket ---------------------------------------------------------- */
  90. int socket(int domain, int type, int protocol) {
  91. if (domain == AF_UNIX) {
  92. int fd = real_socket(domain, type, protocol);
  93. if (fd >= 0) return fd;
  94. /* socket(AF_UNIX) blocked – fall back to socketpair(). */
  95. int sv[2];
  96. if (real_socketpair(domain, type, protocol, sv) == 0) {
  97. if (sv[0] >= 0 && sv[0] < 1024) {
  98. is_shimmed[sv[0]] = 1;
  99. peer_of[sv[0]] = sv[1];
  100. int wp[2];
  101. if (pipe(wp) == 0) {
  102. wake_r[sv[0]] = wp[0];
  103. wake_w[sv[0]] = wp[1];
  104. }
  105. }
  106. return sv[0];
  107. }
  108. errno = EPERM;
  109. return -1;
  110. }
  111. return real_socket(domain, type, protocol);
  112. }
  113. /* ---- listen ---------------------------------------------------------- */
  114. int listen(int sockfd, int backlog) {
  115. if (sockfd >= 0 && sockfd < 1024 && is_shimmed[sockfd]) {
  116. listener_fd = sockfd;
  117. return 0;
  118. }
  119. return real_listen(sockfd, backlog);
  120. }
  121. /* ---- accept ---------------------------------------------------------- */
  122. int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen) {
  123. if (sockfd >= 0 && sockfd < 1024 && is_shimmed[sockfd]) {
  124. /* Block until close() writes to the wake pipe. */
  125. if (wake_r[sockfd] >= 0) {
  126. char buf;
  127. real_read(wake_r[sockfd], &buf, 1);
  128. }
  129. errno = ECONNABORTED;
  130. return -1;
  131. }
  132. return real_accept(sockfd, addr, addrlen);
  133. }
  134. /* ---- close ----------------------------------------------------------- */
  135. int close(int fd) {
  136. if (fd >= 0 && fd < 1024 && is_shimmed[fd]) {
  137. int was_listener = (fd == listener_fd);
  138. is_shimmed[fd] = 0;
  139. if (wake_w[fd] >= 0) { /* unblock accept() */
  140. char c = 0;
  141. write(wake_w[fd], &c, 1);
  142. real_close(wake_w[fd]);
  143. wake_w[fd] = -1;
  144. }
  145. if (wake_r[fd] >= 0) { real_close(wake_r[fd]); wake_r[fd] = -1; }
  146. if (peer_of[fd] >= 0) { real_close(peer_of[fd]); peer_of[fd] = -1; }
  147. if (was_listener)
  148. _exit(0); /* conversion done – exit */
  149. }
  150. return real_close(fd);
  151. }
  152. """
  153. if __name__ == "__main__":
  154. import sys
  155. result = run_soffice(sys.argv[1:])
  156. sys.exit(result.returncode)