Debian Codegraph @

src/briefcase/integrations/linuxdeploy.py

raw
1 from __future__ import annotations
2
3 import hashlib
4 import shlex
5 from abc import ABC, abstractmethod
6 from collections.abc import Collection
7 from pathlib import Path
8 from typing import TypeVar
9 from urllib.parse import urlparse
10
11 from briefcase.exceptions import (
12 BriefcaseCommandError,
13 CorruptToolError,
14 MissingToolError,
15 UnsupportedHostError,
16 )
17 from briefcase.integrations.base import ManagedTool, Tool, ToolCache
18
19 LinuxDeployT = TypeVar("LinuxDeployT", bound="LinuxDeployBase")
20
21 ELF_HEADER_IDENT = bytes.fromhex("7F454C46")
22 ELF_PATCH_OFFSET = 0x08
23 ELF_PATCH_ORIGINAL_BYTES = bytes.fromhex("414902")
24 ELF_PATCH_PATCHED_BYTES = bytes.fromhex("000000")
25
26
27 class LinuxDeployBase(ABC):
28 name: str
29 full_name: str
30 install_msg: str
31 tools: ToolCache
32 # Although Linuxdeploy can only *run* on Linux, it can be *verified* with macOS,
33 # because verification only requires downloading and permission checks, not
34 # execution. The commands where the LinuxDeploy tool is actually used do the
35 # additional check to ensure that if we're on macOS, we're also using Docker.
36 supported_host_os: Collection[str] = {"Darwin", "Linux"}
37
38 @property
39 @abstractmethod
40 def file_name(self) -> str:
41 """The name of the executable file for the tool/plugin, excluding the path."""
42
43 @property
44 @abstractmethod
45 def download_url(self) -> str:
46 """The URL where the tool/plugin can be downloaded."""
47
48 @property
49 @abstractmethod
50 def file_path(self) -> Path:
51 """The folder on the local filesystem that contains the file_name."""
52
53 @classmethod
54 def arch(cls, tools: ToolCache) -> str:
55 """The architecture defined (and supported) by linuxdeploy for AppImages."""
56 system_arch = tools.host_arch
57
58 # If Python is 32 bit, then use 32 bit linuxdeploy regardless of hardware.
59 # It is non-trivial to determine if Linux is 32 bit or 64 bit; so, this uses
60 # Python's bitness as a proxy for Linux's bitness. Furthermore, though, pip
61 # will install 32 bit packages if Python is 32 bit. So, using 32 bit
62 # linuxdeploy in this case ensures the entire resulting AppImage is consistent.
63 if tools.is_32bit_python:
64 system_arch = {
65 "aarch64": "armv8l",
66 "x86_64": "i686",
67 }.get(tools.host_arch, tools.host_arch)
68
69 try:
70 return {
71 "x86_64": "x86_64",
72 "i686": "i386",
73 "armv7l": "armhf",
74 "armv8l": "armhf",
75 "aarch64": "aarch64",
76 }[system_arch]
77 except KeyError as e:
78 raise UnsupportedHostError(
79 f"Linux AppImages cannot be built on {tools.host_arch}."
80 ) from e
81
82 def exists(self) -> bool:
83 return (self.file_path / self.file_name).is_file()
84
85 def install(self):
86 """Download and install linuxdeploy or plugin."""
87 self.tools.file.download(
88 url=self.download_url,
89 download_path=self.file_path,
90 role=self.full_name,
91 )
92 self.prepare_executable()
93
94 def prepare_executable(self):
95 """Update linuxdeploy and its plugins to allow execution.
96
97 All files must be made executable to run or for linuxdeploy to use them as
98 plugins while building the AppImage. ELF files need special "magic" bytes zeroed
99 to run properly in Docker.
100 """
101 with self.tools.console.wait_bar(f"Installing {self.file_name}..."):
102 self.tools.os.chmod(self.file_path / self.file_name, 0o755)
103 if self.is_elf_file():
104 self.patch_elf_header()
105
106 @classmethod
107 def verify_install(
108 cls: type[LinuxDeployT],
109 tools: ToolCache,
110 install: bool = True,
111 **kwargs,
112 ) -> LinuxDeployT:
113 """Verify that linuxdeploy tool or plugin is available.
114
115 :param tools: ToolCache of available tools
116 :param install: Should the tool/plugin be installed if it is not found?
117 :param kwargs: Any additional keyword arguments that should be passed to the
118 tool at time of construction.
119 :returns: A valid tool wrapper. If the tool/plugin is not available, and was not
120 installed, raises MissingToolError.
121 """
122 is_plugin = issubclass(cls, LinuxDeployPluginBase)
123
124 # short circuit since already verified and available
125 if not is_plugin and hasattr(tools, "linuxdeploy"):
126 return tools.linuxdeploy
127
128 tool: LinuxDeployT = cls(tools=tools, **kwargs)
129 if not tool.exists():
130 if install:
131 tools.console.info(
132 cls.install_msg.format(full_name=cls.full_name),
133 prefix="linuxdeploy",
134 )
135 tool.install()
136 else:
137 raise MissingToolError(cls.name)
138
139 if not is_plugin:
140 tools.linuxdeploy = tool
141
142 return tool
143
144 def uninstall(self):
145 """Uninstall tool."""
146 with self.tools.console.wait_bar(f"Removing old {self.full_name} install..."):
147 (self.file_path / self.file_name).unlink()
148
149 def is_elf_file(self) -> bool:
150 """Returns True if the file is an ELF object file.
151
152 The header for an ELF object file always starts with 0x7F454C46; this is 0x7fELF
153 if you interpret the last three bytes as ASCII.
154 """
155 with (self.file_path / self.file_name).open("r+b") as file:
156 return file.read(len(ELF_HEADER_IDENT)) == ELF_HEADER_IDENT
157
158 def patch_elf_header(self):
159 """Patch the ELF header of the AppImage to ensure it can successfully run in all
160 contexts.
161
162 This patch is necessary on Linux hosts that use AppImageLauncher.
163 AppImages use a modified ELF binary header starting at offset 0x08
164 for additional identification. If a system has AppImageLauncher,
165 the Linux kernel module `binfmt-misc` will try to load the AppImage
166 with AppImageLauncher. As this binary does not exist in the Docker
167 container context, we patch the ELF header of linuxdeploy to remove
168 the AppImage bits, thus making all systems treat it like a regular
169 ELF binary.
170
171 Citations:
172 - https://github.com/AppImage/AppImageKit/issues/1027#issuecomment-1028232809
173 - https://github.com/AppImage/AppImageKit/issues/828
174 """
175 with (self.file_path / self.file_name).open("r+b") as appimage:
176 appimage.seek(ELF_PATCH_OFFSET)
177 # Check if the header at the offset is the original value
178 # If so, patch it.
179 if appimage.read(len(ELF_PATCH_ORIGINAL_BYTES)) == ELF_PATCH_ORIGINAL_BYTES:
180 appimage.seek(ELF_PATCH_OFFSET)
181 appimage.write(ELF_PATCH_PATCHED_BYTES)
182 appimage.flush()
183 appimage.seek(0)
184 self.tools.console.info(f"Patched ELF header for {self.file_name}.")
185 # Else if the header is the patched value, do nothing.
186 elif (
187 appimage.read(len(ELF_PATCH_ORIGINAL_BYTES)) == ELF_PATCH_PATCHED_BYTES
188 ):
189 self.tools.console.info(
190 f"ELF header for {self.file_name} is already patched."
191 )
192 else:
193 # We should only get here if the file at the AppImage patch doesn't have
194 # the original or patched value. If this is the case, the file is likely
195 # wrong and we should raise an exception.
196 raise CorruptToolError(self.name)
197
198
199 class LinuxDeployPluginBase(LinuxDeployBase, ABC):
200 """Base class for linuxdeploy plugins."""
201
202 install_msg = "{full_name} was not found; downloading and installing..."
203
204 def __init__(self, *args, **kwargs):
205 super().__init__(*args, **kwargs)
206 self.env = {}
207
208 if not self.file_name.startswith("linuxdeploy-plugin-"):
209 raise BriefcaseCommandError(f"{self.file_name} is not a linuxdeploy plugin")
210
211 @property
212 def plugin_id(self) -> str:
213 return self.file_name.split(".")[0].split("-")[2]
214
215 @property
216 def file_path(self) -> Path:
217 return self.tools.base_path / "linuxdeploy_plugins" / self.plugin_id
218
219
220 class LinuxDeployGtkPlugin(LinuxDeployPluginBase, ManagedTool):
221 name = "linuxdeploy_gtk_plugin"
222 full_name = "linuxdeploy GTK plugin"
223
224 @property
225 def file_name(self) -> str:
226 return "linuxdeploy-plugin-gtk.sh"
227
228 @property
229 def download_url(self) -> str:
230 return (
231 "https://raw.githubusercontent.com/linuxdeploy/linuxdeploy-plugin-gtk/"
232 f"master/{self.file_name}"
233 )
234
235
236 class LinuxDeployQtPlugin(LinuxDeployPluginBase, ManagedTool):
237 name = "linuxdeploy_qt_plugin"
238 full_name = "linuxdeploy Qt plugin"
239
240 @property
241 def file_name(self) -> str:
242 return f"linuxdeploy-plugin-qt-{self.arch(self.tools)}.AppImage"
243
244 @property
245 def download_url(self) -> str:
246 return (
247 "https://github.com/linuxdeploy/linuxdeploy-plugin-qt/"
248 f"releases/download/continuous/{self.file_name}"
249 )
250
251
252 class LinuxDeployLocalFilePlugin(LinuxDeployPluginBase, Tool):
253 name = "linuxdeploy_user_file_plugin"
254 full_name = "user-provided linuxdeploy plugin from local file"
255 install_msg = "Copying user-provided plugin into project"
256
257 def __init__(
258 self,
259 tools: ToolCache,
260 plugin_path: Path,
261 bundle_path: Path,
262 **kwargs,
263 ):
264 self._file_name = plugin_path.name
265 self.local_path = plugin_path.parent
266 self._file_path = bundle_path
267
268 # Call the super last to ensure validation of the filename
269 super().__init__(tools=tools)
270
271 @property
272 def file_name(self) -> str:
273 return self._file_name
274
275 @property
276 def file_path(self) -> Path:
277 return self._file_path
278
279 @property
280 def download_url(self) -> str:
281 raise RuntimeError("Shouldn't be trying to download a local file plugin")
282
283 def install(self):
284 # Install the plugin by copying from the local path to the bundle
285 # folder. This is required to ensure that the file is available inside
286 # the Docker context.
287 try:
288 self.tools.shutil.copy(
289 self.local_path / self.file_name,
290 self.file_path / self.file_name,
291 )
292 except OSError as e:
293 raise BriefcaseCommandError(
294 f"Could not locate linuxdeploy plugin "
295 f"{self.local_path / self.file_name}. "
296 "Is the path correct?"
297 ) from e
298
299 self.prepare_executable()
300
301
302 class LinuxDeployURLPlugin(LinuxDeployPluginBase, Tool):
303 name = "linuxdeploy_user_url_plugin"
304 full_name = "user-provided linuxdeploy plugin from URL"
305
306 def __init__(self, tools: ToolCache, url: str, **kwargs):
307 self._download_url = url
308
309 url_parts = urlparse(url)
310 self._file_name = url_parts.path.split("/")[-1]
311
312 # Build a hash of the download URL; this hash is used to
313 # identify plugins downloaded from different sources. We don't
314 # just use the domain, because we need:
315 # * https://example.com/release/linuxdeploy-plugin-foobar.sh
316 # * https://example.com/dev/linuxdeploy-plugin-foobar.sh
317 # * https://example.com/archive/linuxdeploy-plugin-foobar.sh?version=1
318 # to hash as different plugins, because we lose the path/query
319 # component when we cache the plugin locally.
320 self.hash = hashlib.sha256(url.encode("utf-8"))
321
322 # Call the super last to ensure validation of the filename
323 super().__init__(tools=tools)
324
325 @property
326 def file_name(self) -> str:
327 return self._file_name
328
329 @property
330 def file_path(self) -> Path:
331 return (
332 self.tools.base_path
333 / "linuxdeploy_plugins"
334 / self.plugin_id
335 / self.hash.hexdigest()
336 )
337
338 @property
339 def download_url(self) -> str:
340 return self._download_url
341
342
343 class LinuxDeploy(LinuxDeployBase, ManagedTool):
344 name = "linuxdeploy"
345 full_name = "linuxdeploy"
346 install_msg = "linuxdeploy was not found; downloading and installing..."
347
348 @property
349 def file_path(self) -> Path:
350 return self.tools.base_path
351
352 @property
353 def file_name(self) -> str:
354 return f"linuxdeploy-{self.arch(self.tools)}.AppImage"
355
356 @property
357 def download_url(self) -> str:
358 return (
359 "https://github.com/linuxdeploy/linuxdeploy/"
360 f"releases/download/continuous/{self.file_name}"
361 )
362
363 @property
364 def plugins(self) -> dict[str, type[LinuxDeployPluginBase]]:
365 """The known linuxdeploy plugins."""
366 return {
367 "gtk": LinuxDeployGtkPlugin,
368 "qt": LinuxDeployQtPlugin,
369 }
370
371 def verify_plugins(
372 self,
373 plugin_definitions: list[str],
374 bundle_path: Path,
375 ) -> dict[str, LinuxDeployPluginBase]:
376 """Verify that all the declared plugin dependencies are available.
377
378 Each plugin definition is a string, and can be:
379 * The name of a known plugin (gtk, qt)
380 * A URL
381 * A local file.
382
383 This definition can be preceded by environment variables that must
384 exist in the environment. For example, a plugin definition of:
385
386 DEPLOY_GTK_VERSION=3 FOO='bar whiz' gtk
387
388 would specify the known GTK plugin, adding `DEPLOY_GTK_VERSION` and
389 `FOO` in the environment. The definition will be split the same way as
390 shell arguments, so spaces should be escaped.
391
392 :param plugin_definitions: A list of strings defining the required plugins.
393 :param bundle_path: The location of the app bundle that requires the plugins.
394 :returns: A dictionary of plugin ID->instantiated plugin instances.
395 """
396 plugins = {}
397 for plugin_definition in plugin_definitions:
398 # Split the plugin definition lexically.
399 # The last element is the plugin ID.
400 plugin_definition_parts = shlex.split(plugin_definition)
401 plugin_name = plugin_definition_parts[-1]
402
403 try:
404 plugin_klass = self.plugins[plugin_name]
405 self.tools.console.info(f"Using default {plugin_name} plugin")
406 plugin = plugin_klass.verify(self.tools)
407 except KeyError:
408 if plugin_name.startswith(("https://", "http://")):
409 self.tools.console.info(f"Using URL plugin {plugin_name}")
410 plugin = LinuxDeployURLPlugin.verify(self.tools, url=plugin_name)
411 else: # pragma: no-cover-if-is-windows
412 self.tools.console.info(f"Using local file plugin {plugin_name}")
413 plugin = LinuxDeployLocalFilePlugin.verify(
414 self.tools,
415 plugin_path=Path(plugin_name),
416 bundle_path=bundle_path,
417 )
418
419 # Preserve the environment declarations required by the plugin.
420 for part in plugin_definition_parts[:-1]:
421 try:
422 var, value = part.split("=", 1)
423 plugin.env[var] = value
424 except ValueError:
425 # `export FOO` is valid, if unusual
426 plugin.env[part] = ""
427
428 plugins[plugin.plugin_id] = plugin
429
430 return plugins