blob: 5703ca8d929927b0010ff64f3015c8afd9ae85b7 [file] [log] [blame]
Richard Hughes02c90d82018-08-09 12:13:03 +01001/*
Richard Hughes943d2c92017-06-21 09:04:39 +01002 * Copyright (C) 2017 Richard Hughes <richard@hughsie.com>
3 *
Mario Limonciello51308e62018-05-28 20:05:46 -05004 * SPDX-License-Identifier: LGPL-2.1+
Richard Hughes943d2c92017-06-21 09:04:39 +01005 */
6
Richard Hughesb08e7bc2018-09-11 10:51:13 +01007#define G_LOG_DOMAIN "FuCommon"
8
Richard Hughes943d2c92017-06-21 09:04:39 +01009#include <config.h>
10
Richard Hughes9e5675e2019-11-22 09:35:03 +000011#ifdef HAVE_GIO_UNIX
Richard Hughes943d2c92017-06-21 09:04:39 +010012#include <gio/gunixinputstream.h>
Richard Hughes9e5675e2019-11-22 09:35:03 +000013#endif
Richard Hughes954dd9f2017-08-08 13:36:25 +010014#include <glib/gstdio.h>
15
Richard Hughes5c508de2019-11-22 09:57:34 +000016#ifdef HAVE_FNMATCH_H
17#include <fnmatch.h>
Richard Hughes45a00732019-11-22 16:57:14 +000018#elif _WIN32
19#include <shlwapi.h>
Richard Hughes5c508de2019-11-22 09:57:34 +000020#endif
21
Richard Hughes68175e92021-01-14 09:43:33 +000022#ifdef _WIN32
23#include <sysinfoapi.h>
24#endif
25
Richard Hughesbd444322020-05-21 12:05:03 +010026#ifdef HAVE_CPUID_H
Richard Hughes9223c892020-05-09 20:32:08 +010027#include <cpuid.h>
Richard Hughesbd444322020-05-21 12:05:03 +010028#endif
Richard Hughes9223c892020-05-09 20:32:08 +010029
Richard Hughes5add3a72021-01-13 19:25:10 +000030#ifdef HAVE_LIBARCHIVE
Richard Hughes94f939a2017-08-08 12:21:39 +010031#include <archive_entry.h>
32#include <archive.h>
Richard Hughes5add3a72021-01-13 19:25:10 +000033#endif
Richard Hughes7ee42fe2017-08-15 14:06:21 +010034#include <errno.h>
Richard Hughes484ee292019-03-22 16:10:50 +000035#include <limits.h>
Richard Hughesae252cd2017-12-08 10:48:15 +000036#include <string.h>
Richard Hughes484ee292019-03-22 16:10:50 +000037#include <stdlib.h>
Richard Hughes68175e92021-01-14 09:43:33 +000038#include <unistd.h>
Richard Hughes943d2c92017-06-21 09:04:39 +010039
40#include "fwupd-error.h"
41
42#include "fu-common.h"
Richard Hughes8f0b2d12020-08-12 12:41:53 +010043#include "fu-volume-private.h"
44
Richard Hughes43417b22020-10-30 14:46:16 +000045#define UDISKS_DBUS_SERVICE "org.freedesktop.UDisks2"
46#define UDISKS_DBUS_PATH "/org/freedesktop/UDisks2/Manager"
47#define UDISKS_DBUS_MANAGER_INTERFACE "org.freedesktop.UDisks2.Manager"
48#define UDISKS_DBUS_INTERFACE_PARTITION "org.freedesktop.UDisks2.Partition"
49#define UDISKS_DBUS_INTERFACE_FILESYSTEM "org.freedesktop.UDisks2.Filesystem"
50#define UDISKS_DBUS_INTERFACE_BLOCK "org.freedesktop.UDisks2.Block"
Richard Hughes943d2c92017-06-21 09:04:39 +010051
52/**
Richard Hughes4eada342017-10-03 21:20:32 +010053 * SECTION:fu-common
54 * @short_description: common functionality for plugins to use
55 *
56 * Helper functions that can be used by the daemon and plugins.
57 *
58 * See also: #FuPlugin
59 */
60
61/**
Richard Hughes954dd9f2017-08-08 13:36:25 +010062 * fu_common_rmtree:
63 * @directory: a directory name
64 * @error: A #GError or %NULL
65 *
66 * Recursively removes a directory.
67 *
68 * Returns: %TRUE for success, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -060069 *
70 * Since: 0.9.7
Richard Hughes954dd9f2017-08-08 13:36:25 +010071 **/
72gboolean
73fu_common_rmtree (const gchar *directory, GError **error)
74{
75 const gchar *filename;
76 g_autoptr(GDir) dir = NULL;
77
Richard Hughes6a489a92020-12-22 10:32:06 +000078 g_return_val_if_fail (directory != NULL, FALSE);
79 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
80
Richard Hughes954dd9f2017-08-08 13:36:25 +010081 /* try to open */
Richard Hughes455fdd32017-08-16 12:26:44 +010082 g_debug ("removing %s", directory);
Richard Hughes954dd9f2017-08-08 13:36:25 +010083 dir = g_dir_open (directory, 0, error);
84 if (dir == NULL)
85 return FALSE;
86
87 /* find each */
88 while ((filename = g_dir_read_name (dir))) {
89 g_autofree gchar *src = NULL;
90 src = g_build_filename (directory, filename, NULL);
91 if (g_file_test (src, G_FILE_TEST_IS_DIR)) {
92 if (!fu_common_rmtree (src, error))
93 return FALSE;
94 } else {
95 if (g_unlink (src) != 0) {
96 g_set_error (error,
97 FWUPD_ERROR,
98 FWUPD_ERROR_INTERNAL,
99 "Failed to delete: %s", src);
100 return FALSE;
101 }
102 }
103 }
104 if (g_remove (directory) != 0) {
105 g_set_error (error,
106 FWUPD_ERROR,
107 FWUPD_ERROR_INTERNAL,
108 "Failed to delete: %s", directory);
109 return FALSE;
110 }
111 return TRUE;
112}
113
Richard Hughes89e968b2018-03-07 10:01:08 +0000114static gboolean
115fu_common_get_file_list_internal (GPtrArray *files, const gchar *directory, GError **error)
116{
117 const gchar *filename;
118 g_autoptr(GDir) dir = NULL;
119
120 /* try to open */
121 dir = g_dir_open (directory, 0, error);
122 if (dir == NULL)
123 return FALSE;
124
125 /* find each */
126 while ((filename = g_dir_read_name (dir))) {
127 g_autofree gchar *src = g_build_filename (directory, filename, NULL);
128 if (g_file_test (src, G_FILE_TEST_IS_DIR)) {
129 if (!fu_common_get_file_list_internal (files, src, error))
130 return FALSE;
131 } else {
132 g_ptr_array_add (files, g_steal_pointer (&src));
133 }
134 }
135 return TRUE;
136
137}
138
139/**
140 * fu_common_get_files_recursive:
Richard Hughes8aa72392018-05-02 08:38:43 +0100141 * @path: a directory name
Richard Hughes89e968b2018-03-07 10:01:08 +0000142 * @error: A #GError or %NULL
143 *
144 * Returns every file found under @directory, and any subdirectory.
145 * If any path under @directory cannot be accessed due to permissions an error
146 * will be returned.
147 *
Richard Hughesa0d81c72019-11-27 11:41:54 +0000148 * Returns: (transfer container) (element-type utf8): array of files, or %NULL for error
Mario Limonciello1a680f32019-11-25 19:44:53 -0600149 *
150 * Since: 1.0.6
Richard Hughes89e968b2018-03-07 10:01:08 +0000151 **/
152GPtrArray *
153fu_common_get_files_recursive (const gchar *path, GError **error)
154{
155 g_autoptr(GPtrArray) files = g_ptr_array_new_with_free_func (g_free);
Richard Hughes6a489a92020-12-22 10:32:06 +0000156
157 g_return_val_if_fail (path != NULL, NULL);
158 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
159
Richard Hughes89e968b2018-03-07 10:01:08 +0000160 if (!fu_common_get_file_list_internal (files, path, error))
161 return NULL;
162 return g_steal_pointer (&files);
163}
Richard Hughes954dd9f2017-08-08 13:36:25 +0100164/**
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100165 * fu_common_mkdir_parent:
166 * @filename: A full pathname
167 * @error: A #GError, or %NULL
168 *
169 * Creates any required directories, including any parent directories.
170 *
171 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600172 *
173 * Since: 0.9.7
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100174 **/
175gboolean
176fu_common_mkdir_parent (const gchar *filename, GError **error)
177{
178 g_autofree gchar *parent = NULL;
Richard Hughes455fdd32017-08-16 12:26:44 +0100179
Richard Hughes6a489a92020-12-22 10:32:06 +0000180 g_return_val_if_fail (filename != NULL, FALSE);
181 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
182
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100183 parent = g_path_get_dirname (filename);
Mario Limonciellod4155ff2020-09-28 15:20:07 -0500184 if (!g_file_test (parent, G_FILE_TEST_IS_DIR))
185 g_debug ("creating path %s", parent);
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100186 if (g_mkdir_with_parents (parent, 0755) == -1) {
187 g_set_error (error,
188 FWUPD_ERROR,
189 FWUPD_ERROR_INTERNAL,
190 "Failed to create '%s': %s",
191 parent, g_strerror (errno));
192 return FALSE;
193 }
194 return TRUE;
195}
196
197/**
Richard Hughes943d2c92017-06-21 09:04:39 +0100198 * fu_common_set_contents_bytes:
199 * @filename: A filename
200 * @bytes: The data to write
201 * @error: A #GError, or %NULL
202 *
203 * Writes a blob of data to a filename, creating the parent directories as
204 * required.
205 *
206 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600207 *
208 * Since: 0.9.5
Richard Hughes943d2c92017-06-21 09:04:39 +0100209 **/
210gboolean
211fu_common_set_contents_bytes (const gchar *filename, GBytes *bytes, GError **error)
212{
213 const gchar *data;
214 gsize size;
215 g_autoptr(GFile) file = NULL;
216 g_autoptr(GFile) file_parent = NULL;
217
Richard Hughes6a489a92020-12-22 10:32:06 +0000218 g_return_val_if_fail (filename != NULL, FALSE);
219 g_return_val_if_fail (bytes != NULL, FALSE);
220 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
221
Richard Hughes943d2c92017-06-21 09:04:39 +0100222 file = g_file_new_for_path (filename);
223 file_parent = g_file_get_parent (file);
224 if (!g_file_query_exists (file_parent, NULL)) {
225 if (!g_file_make_directory_with_parents (file_parent, NULL, error))
226 return FALSE;
227 }
228 data = g_bytes_get_data (bytes, &size);
Richard Hughes455fdd32017-08-16 12:26:44 +0100229 g_debug ("writing %s with %" G_GSIZE_FORMAT " bytes", filename, size);
Richard Hughes943d2c92017-06-21 09:04:39 +0100230 return g_file_set_contents (filename, data, size, error);
231}
232
Richard Hughesd0d2ae62017-08-08 12:22:30 +0100233/**
234 * fu_common_get_contents_bytes:
235 * @filename: A filename
236 * @error: A #GError, or %NULL
237 *
238 * Reads a blob of data from a file.
239 *
240 * Returns: a #GBytes, or %NULL for failure
Mario Limonciello1a680f32019-11-25 19:44:53 -0600241 *
242 * Since: 0.9.7
Richard Hughesd0d2ae62017-08-08 12:22:30 +0100243 **/
244GBytes *
245fu_common_get_contents_bytes (const gchar *filename, GError **error)
246{
247 gchar *data = NULL;
248 gsize len = 0;
Richard Hughes6a489a92020-12-22 10:32:06 +0000249
250 g_return_val_if_fail (filename != NULL, NULL);
251 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
252
Richard Hughesd0d2ae62017-08-08 12:22:30 +0100253 if (!g_file_get_contents (filename, &data, &len, error))
254 return NULL;
Richard Hughes455fdd32017-08-16 12:26:44 +0100255 g_debug ("reading %s with %" G_GSIZE_FORMAT " bytes", filename, len);
Richard Hughesd0d2ae62017-08-08 12:22:30 +0100256 return g_bytes_new_take (data, len);
257}
Richard Hughes943d2c92017-06-21 09:04:39 +0100258
259/**
260 * fu_common_get_contents_fd:
261 * @fd: A file descriptor
262 * @count: The maximum number of bytes to read
263 * @error: A #GError, or %NULL
264 *
265 * Reads a blob from a specific file descriptor.
266 *
267 * Note: this will close the fd when done
268 *
Richard Hughes4eada342017-10-03 21:20:32 +0100269 * Returns: (transfer full): a #GBytes, or %NULL
Mario Limonciello1a680f32019-11-25 19:44:53 -0600270 *
271 * Since: 0.9.5
Richard Hughes943d2c92017-06-21 09:04:39 +0100272 **/
273GBytes *
274fu_common_get_contents_fd (gint fd, gsize count, GError **error)
275{
Richard Hughes9e5675e2019-11-22 09:35:03 +0000276#ifdef HAVE_GIO_UNIX
Richard Hughes97ad3352021-01-14 20:07:47 +0000277 guint8 tmp[0x8000] = { 0x0 };
278 g_autoptr(GByteArray) buf = g_byte_array_new ();
Richard Hughes943d2c92017-06-21 09:04:39 +0100279 g_autoptr(GError) error_local = NULL;
280 g_autoptr(GInputStream) stream = NULL;
281
282 g_return_val_if_fail (fd > 0, NULL);
Richard Hughes943d2c92017-06-21 09:04:39 +0100283 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
284
Richard Hughes919f8ab2018-02-14 10:24:56 +0000285 /* this is invalid */
286 if (count == 0) {
287 g_set_error_literal (error,
288 FWUPD_ERROR,
289 FWUPD_ERROR_NOT_SUPPORTED,
290 "A maximum read size must be specified");
291 return NULL;
292 }
293
Richard Hughes943d2c92017-06-21 09:04:39 +0100294 /* read the entire fd to a data blob */
295 stream = g_unix_input_stream_new (fd, TRUE);
Richard Hughes97ad3352021-01-14 20:07:47 +0000296
297 /* read from stream in 32kB chunks */
298 while (TRUE) {
299 gssize sz;
300 sz = g_input_stream_read (stream, tmp, sizeof(tmp), NULL, &error_local);
301 if (sz == 0)
302 break;
303 if (sz < 0) {
304 g_set_error_literal (error,
305 FWUPD_ERROR,
306 FWUPD_ERROR_INVALID_FILE,
307 error_local->message);
308 return NULL;
309 }
310 g_byte_array_append (buf, tmp, sz);
311 if (buf->len > count) {
312 g_set_error (error,
Richard Hughes943d2c92017-06-21 09:04:39 +0100313 FWUPD_ERROR,
314 FWUPD_ERROR_INVALID_FILE,
Richard Hughes97ad3352021-01-14 20:07:47 +0000315 "cannot read from fd: 0x%x > 0x%x",
316 buf->len, (guint) count);
317 return NULL;
318 }
Richard Hughes943d2c92017-06-21 09:04:39 +0100319 }
Richard Hughes97ad3352021-01-14 20:07:47 +0000320 return g_byte_array_free_to_bytes (g_steal_pointer (&buf));
Richard Hughes9e5675e2019-11-22 09:35:03 +0000321#else
322 g_set_error_literal (error,
323 FWUPD_ERROR,
324 FWUPD_ERROR_NOT_SUPPORTED,
325 "Not supported as <glib-unix.h> is unavailable");
326 return NULL;
327#endif
Richard Hughes943d2c92017-06-21 09:04:39 +0100328}
Richard Hughes94f939a2017-08-08 12:21:39 +0100329
Richard Hughes5add3a72021-01-13 19:25:10 +0000330#ifdef HAVE_LIBARCHIVE
Richard Hughes94f939a2017-08-08 12:21:39 +0100331static gboolean
332fu_common_extract_archive_entry (struct archive_entry *entry, const gchar *dir)
333{
334 const gchar *tmp;
335 g_autofree gchar *buf = NULL;
336
337 /* no output file */
338 if (archive_entry_pathname (entry) == NULL)
339 return FALSE;
340
341 /* update output path */
342 tmp = archive_entry_pathname (entry);
343 buf = g_build_filename (dir, tmp, NULL);
344 archive_entry_update_pathname_utf8 (entry, buf);
345 return TRUE;
346}
Richard Hughes5add3a72021-01-13 19:25:10 +0000347#endif
Richard Hughes94f939a2017-08-08 12:21:39 +0100348
349/**
350 * fu_common_extract_archive:
351 * @blob: a #GBytes archive as a blob
Richard Hughes4eada342017-10-03 21:20:32 +0100352 * @dir: a directory name to extract to
Richard Hughes94f939a2017-08-08 12:21:39 +0100353 * @error: A #GError, or %NULL
354 *
Richard Hughes21eaeef2020-01-14 12:10:01 +0000355 * Extracts an archive to a directory.
Richard Hughes94f939a2017-08-08 12:21:39 +0100356 *
357 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600358 *
359 * Since: 0.9.7
Richard Hughes94f939a2017-08-08 12:21:39 +0100360 **/
361gboolean
362fu_common_extract_archive (GBytes *blob, const gchar *dir, GError **error)
363{
Richard Hughes5add3a72021-01-13 19:25:10 +0000364#ifdef HAVE_LIBARCHIVE
Richard Hughes94f939a2017-08-08 12:21:39 +0100365 gboolean ret = TRUE;
366 int r;
367 struct archive *arch = NULL;
368 struct archive_entry *entry;
369
Richard Hughes6a489a92020-12-22 10:32:06 +0000370 g_return_val_if_fail (blob != NULL, FALSE);
371 g_return_val_if_fail (dir != NULL, FALSE);
372 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
373
Richard Hughes94f939a2017-08-08 12:21:39 +0100374 /* decompress anything matching either glob */
Richard Hughes455fdd32017-08-16 12:26:44 +0100375 g_debug ("decompressing into %s", dir);
Richard Hughes94f939a2017-08-08 12:21:39 +0100376 arch = archive_read_new ();
377 archive_read_support_format_all (arch);
378 archive_read_support_filter_all (arch);
379 r = archive_read_open_memory (arch,
380 (void *) g_bytes_get_data (blob, NULL),
381 (size_t) g_bytes_get_size (blob));
382 if (r != 0) {
383 ret = FALSE;
384 g_set_error (error,
385 FWUPD_ERROR,
386 FWUPD_ERROR_INTERNAL,
387 "Cannot open: %s",
388 archive_error_string (arch));
389 goto out;
390 }
391 for (;;) {
392 gboolean valid;
Richard Hughes94f939a2017-08-08 12:21:39 +0100393 r = archive_read_next_header (arch, &entry);
394 if (r == ARCHIVE_EOF)
395 break;
396 if (r != ARCHIVE_OK) {
397 ret = FALSE;
398 g_set_error (error,
399 FWUPD_ERROR,
400 FWUPD_ERROR_INTERNAL,
401 "Cannot read header: %s",
402 archive_error_string (arch));
403 goto out;
404 }
405
406 /* only extract if valid */
407 valid = fu_common_extract_archive_entry (entry, dir);
408 if (!valid)
409 continue;
410 r = archive_read_extract (arch, entry, 0);
411 if (r != ARCHIVE_OK) {
412 ret = FALSE;
413 g_set_error (error,
414 FWUPD_ERROR,
415 FWUPD_ERROR_INTERNAL,
416 "Cannot extract: %s",
417 archive_error_string (arch));
418 goto out;
419 }
420 }
421out:
422 if (arch != NULL) {
423 archive_read_close (arch);
424 archive_read_free (arch);
425 }
426 return ret;
Richard Hughes5add3a72021-01-13 19:25:10 +0000427#else
428 g_set_error_literal (error,
429 FWUPD_ERROR,
430 FWUPD_ERROR_NOT_SUPPORTED,
431 "missing libarchive support");
432 return FALSE;
433#endif
Richard Hughes94f939a2017-08-08 12:21:39 +0100434}
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100435
436static void
Yehezkel Bernate43f7fb2017-08-30 12:09:34 +0300437fu_common_add_argv (GPtrArray *argv, const gchar *fmt, ...) G_GNUC_PRINTF (2, 3);
438
439static void
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100440fu_common_add_argv (GPtrArray *argv, const gchar *fmt, ...)
441{
442 va_list args;
443 g_autofree gchar *tmp = NULL;
444 g_auto(GStrv) split = NULL;
445
446 va_start (args, fmt);
447 tmp = g_strdup_vprintf (fmt, args);
448 va_end (args);
449
450 split = g_strsplit (tmp, " ", -1);
451 for (guint i = 0; split[i] != NULL; i++)
452 g_ptr_array_add (argv, g_strdup (split[i]));
453}
454
Mario Limonciello1a680f32019-11-25 19:44:53 -0600455/**
456 * fu_common_find_program_in_path:
457 * @basename: The program to search
458 * @error: A #GError, or %NULL
459 *
460 * Looks for a program in the PATH variable
461 *
462 * Returns: a new #gchar, or %NULL for error
463 *
464 * Since: 1.1.2
465 **/
Richard Hughes22367e72018-08-30 10:24:04 +0100466gchar *
467fu_common_find_program_in_path (const gchar *basename, GError **error)
468{
469 gchar *fn = g_find_program_in_path (basename);
470 if (fn == NULL) {
471 g_set_error (error,
472 FWUPD_ERROR,
473 FWUPD_ERROR_NOT_SUPPORTED,
474 "missing executable %s in PATH",
475 basename);
476 return NULL;
477 }
478 return fn;
479}
480
481static gboolean
482fu_common_test_namespace_support (GError **error)
483{
484 /* test if CONFIG_USER_NS is valid */
485 if (!g_file_test ("/proc/self/ns/user", G_FILE_TEST_IS_SYMLINK)) {
486 g_set_error (error,
487 FWUPD_ERROR,
488 FWUPD_ERROR_NOT_SUPPORTED,
489 "missing CONFIG_USER_NS in kernel");
490 return FALSE;
491 }
492 if (g_file_test ("/proc/sys/kernel/unprivileged_userns_clone", G_FILE_TEST_EXISTS)) {
493 g_autofree gchar *clone = NULL;
494 if (!g_file_get_contents ("/proc/sys/kernel/unprivileged_userns_clone", &clone, NULL, error))
495 return FALSE;
496 if (g_ascii_strtoll (clone, NULL, 10) == 0) {
497 g_set_error (error,
498 FWUPD_ERROR,
499 FWUPD_ERROR_NOT_SUPPORTED,
500 "unprivileged user namespace clones disabled by distro");
501 return FALSE;
502 }
503 }
504 return TRUE;
505}
506
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100507/**
508 * fu_common_firmware_builder:
509 * @bytes: The data to use
Richard Hughes4eada342017-10-03 21:20:32 +0100510 * @script_fn: Name of the script to run in the tarball, e.g. `startup.sh`
511 * @output_fn: Name of the generated firmware, e.g. `firmware.bin`
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100512 * @error: A #GError, or %NULL
513 *
514 * Builds a firmware file using tools from the host session in a bubblewrap
515 * jail. Several things happen during build:
516 *
517 * 1. The @bytes data is untarred to a temporary location
518 * 2. A bubblewrap container is set up
519 * 3. The startup.sh script is run inside the container
520 * 4. The firmware.bin is extracted from the container
521 * 5. The temporary location is deleted
522 *
523 * Returns: a new #GBytes, or %NULL for error
Mario Limonciello1a680f32019-11-25 19:44:53 -0600524 *
525 * Since: 0.9.7
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100526 **/
527GBytes *
528fu_common_firmware_builder (GBytes *bytes,
529 const gchar *script_fn,
530 const gchar *output_fn,
531 GError **error)
532{
533 gint rc = 0;
534 g_autofree gchar *argv_str = NULL;
Mario Limonciello37b59582018-08-13 08:38:01 -0500535 g_autofree gchar *bwrap_fn = NULL;
Richard Hughes4be17d12018-05-30 20:36:29 +0100536 g_autofree gchar *localstatebuilderdir = NULL;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100537 g_autofree gchar *localstatedir = NULL;
538 g_autofree gchar *output2_fn = NULL;
539 g_autofree gchar *standard_error = NULL;
540 g_autofree gchar *standard_output = NULL;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100541 g_autofree gchar *tmpdir = NULL;
542 g_autoptr(GBytes) firmware_blob = NULL;
543 g_autoptr(GPtrArray) argv = g_ptr_array_new_with_free_func (g_free);
544
545 g_return_val_if_fail (bytes != NULL, NULL);
546 g_return_val_if_fail (script_fn != NULL, NULL);
547 g_return_val_if_fail (output_fn != NULL, NULL);
548 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
549
Mario Limonciello37b59582018-08-13 08:38:01 -0500550 /* find bwrap in the path */
Richard Hughes22367e72018-08-30 10:24:04 +0100551 bwrap_fn = fu_common_find_program_in_path ("bwrap", error);
552 if (bwrap_fn == NULL)
Richard Hughesddb3e202018-08-23 11:29:57 +0100553 return NULL;
Mario Limonciello37b59582018-08-13 08:38:01 -0500554
555 /* test if CONFIG_USER_NS is valid */
Richard Hughes22367e72018-08-30 10:24:04 +0100556 if (!fu_common_test_namespace_support (error))
Richard Hughesddb3e202018-08-23 11:29:57 +0100557 return NULL;
Mario Limonciello37b59582018-08-13 08:38:01 -0500558
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100559 /* untar file to temp location */
560 tmpdir = g_dir_make_tmp ("fwupd-gen-XXXXXX", error);
561 if (tmpdir == NULL)
562 return NULL;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100563 if (!fu_common_extract_archive (bytes, tmpdir, error))
564 return NULL;
565
566 /* this is shared with the plugins */
Richard Hughes4be17d12018-05-30 20:36:29 +0100567 localstatedir = fu_common_get_path (FU_PATH_KIND_LOCALSTATEDIR_PKG);
568 localstatebuilderdir = g_build_filename (localstatedir, "builder", NULL);
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100569
570 /* launch bubblewrap and generate firmware */
Mario Limonciello37b59582018-08-13 08:38:01 -0500571 g_ptr_array_add (argv, g_steal_pointer (&bwrap_fn));
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100572 fu_common_add_argv (argv, "--die-with-parent");
573 fu_common_add_argv (argv, "--ro-bind /usr /usr");
Mario Limonciellob8215572018-07-13 09:49:55 -0500574 fu_common_add_argv (argv, "--ro-bind /lib /lib");
Mario Limoncielloed4e9122020-12-15 20:26:50 -0600575 fu_common_add_argv (argv, "--ro-bind-try /lib64 /lib64");
Mario Limonciellob8215572018-07-13 09:49:55 -0500576 fu_common_add_argv (argv, "--ro-bind /bin /bin");
577 fu_common_add_argv (argv, "--ro-bind /sbin /sbin");
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100578 fu_common_add_argv (argv, "--dir /tmp");
579 fu_common_add_argv (argv, "--dir /var");
580 fu_common_add_argv (argv, "--bind %s /tmp", tmpdir);
Richard Hughes4be17d12018-05-30 20:36:29 +0100581 if (g_file_test (localstatebuilderdir, G_FILE_TEST_EXISTS))
582 fu_common_add_argv (argv, "--ro-bind %s /boot", localstatebuilderdir);
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100583 fu_common_add_argv (argv, "--dev /dev");
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100584 fu_common_add_argv (argv, "--chdir /tmp");
585 fu_common_add_argv (argv, "--unshare-all");
Richard Hughes443e4092017-08-09 16:07:31 +0100586 fu_common_add_argv (argv, "/tmp/%s", script_fn);
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100587 g_ptr_array_add (argv, NULL);
588 argv_str = g_strjoinv (" ", (gchar **) argv->pdata);
589 g_debug ("running '%s' in %s", argv_str, tmpdir);
590 if (!g_spawn_sync ("/tmp",
591 (gchar **) argv->pdata,
592 NULL,
Richard Hughesf6f72a42017-08-09 16:25:25 +0100593 G_SPAWN_SEARCH_PATH,
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100594 NULL, NULL, /* child_setup */
595 &standard_output,
596 &standard_error,
597 &rc,
598 error)) {
599 g_prefix_error (error, "failed to run '%s': ", argv_str);
600 return NULL;
601 }
602 if (standard_output != NULL && standard_output[0] != '\0')
603 g_debug ("console output was: %s", standard_output);
604 if (rc != 0) {
Mario Limonciello37b59582018-08-13 08:38:01 -0500605 FwupdError code = FWUPD_ERROR_INTERNAL;
606 if (errno == ENOTTY)
607 code = FWUPD_ERROR_PERMISSION_DENIED;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100608 g_set_error (error,
609 FWUPD_ERROR,
Mario Limonciello37b59582018-08-13 08:38:01 -0500610 code,
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100611 "failed to build firmware: %s",
612 standard_error);
613 return NULL;
614 }
615
616 /* get generated file */
617 output2_fn = g_build_filename (tmpdir, output_fn, NULL);
618 firmware_blob = fu_common_get_contents_bytes (output2_fn, error);
619 if (firmware_blob == NULL)
620 return NULL;
621
622 /* cleanup temp directory */
623 if (!fu_common_rmtree (tmpdir, error))
624 return NULL;
625
626 /* success */
627 return g_steal_pointer (&firmware_blob);
628}
Richard Hughes049ccc82017-08-09 15:26:56 +0100629
630typedef struct {
631 FuOutputHandler handler_cb;
632 gpointer handler_user_data;
633 GMainLoop *loop;
634 GSource *source;
635 GInputStream *stream;
636 GCancellable *cancellable;
Richard Hughesb768e4d2019-02-26 13:55:18 +0000637 guint timeout_id;
Richard Hughes049ccc82017-08-09 15:26:56 +0100638} FuCommonSpawnHelper;
639
640static void fu_common_spawn_create_pollable_source (FuCommonSpawnHelper *helper);
641
642static gboolean
643fu_common_spawn_source_pollable_cb (GObject *stream, gpointer user_data)
644{
645 FuCommonSpawnHelper *helper = (FuCommonSpawnHelper *) user_data;
646 gchar buffer[1024];
647 gssize sz;
648 g_auto(GStrv) split = NULL;
649 g_autoptr(GError) error = NULL;
650
651 /* read from stream */
652 sz = g_pollable_input_stream_read_nonblocking (G_POLLABLE_INPUT_STREAM (stream),
653 buffer,
654 sizeof(buffer) - 1,
655 NULL,
656 &error);
657 if (sz < 0) {
Richard Hughes67cbe642017-08-16 12:26:14 +0100658 if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
659 g_warning ("failed to get read from nonblocking fd: %s",
660 error->message);
661 }
Richard Hughes049ccc82017-08-09 15:26:56 +0100662 return G_SOURCE_REMOVE;
663 }
664
665 /* no read possible */
666 if (sz == 0)
667 g_main_loop_quit (helper->loop);
668
669 /* emit lines */
670 if (helper->handler_cb != NULL) {
671 buffer[sz] = '\0';
672 split = g_strsplit (buffer, "\n", -1);
673 for (guint i = 0; split[i] != NULL; i++) {
674 if (split[i][0] == '\0')
675 continue;
676 helper->handler_cb (split[i], helper->handler_user_data);
677 }
678 }
679
680 /* set up the source for the next read */
681 fu_common_spawn_create_pollable_source (helper);
682 return G_SOURCE_REMOVE;
683}
684
685static void
686fu_common_spawn_create_pollable_source (FuCommonSpawnHelper *helper)
687{
688 if (helper->source != NULL)
689 g_source_destroy (helper->source);
690 helper->source = g_pollable_input_stream_create_source (G_POLLABLE_INPUT_STREAM (helper->stream),
691 helper->cancellable);
692 g_source_attach (helper->source, NULL);
693 g_source_set_callback (helper->source, (GSourceFunc) fu_common_spawn_source_pollable_cb, helper, NULL);
694}
695
696static void
697fu_common_spawn_helper_free (FuCommonSpawnHelper *helper)
698{
Richard Hughesb768e4d2019-02-26 13:55:18 +0000699 g_object_unref (helper->cancellable);
Richard Hughes049ccc82017-08-09 15:26:56 +0100700 if (helper->stream != NULL)
701 g_object_unref (helper->stream);
702 if (helper->source != NULL)
703 g_source_destroy (helper->source);
704 if (helper->loop != NULL)
705 g_main_loop_unref (helper->loop);
Richard Hughesb768e4d2019-02-26 13:55:18 +0000706 if (helper->timeout_id != 0)
707 g_source_remove (helper->timeout_id);
Richard Hughes049ccc82017-08-09 15:26:56 +0100708 g_free (helper);
709}
710
Mario Limoncielloa98df552018-04-16 12:15:51 -0500711#pragma clang diagnostic push
712#pragma clang diagnostic ignored "-Wunused-function"
Richard Hughes049ccc82017-08-09 15:26:56 +0100713G_DEFINE_AUTOPTR_CLEANUP_FUNC(FuCommonSpawnHelper, fu_common_spawn_helper_free)
Mario Limoncielloa98df552018-04-16 12:15:51 -0500714#pragma clang diagnostic pop
Richard Hughes049ccc82017-08-09 15:26:56 +0100715
Richard Hughesb768e4d2019-02-26 13:55:18 +0000716static gboolean
717fu_common_spawn_timeout_cb (gpointer user_data)
718{
719 FuCommonSpawnHelper *helper = (FuCommonSpawnHelper *) user_data;
720 g_cancellable_cancel (helper->cancellable);
721 g_main_loop_quit (helper->loop);
722 helper->timeout_id = 0;
723 return G_SOURCE_REMOVE;
724}
725
726static void
727fu_common_spawn_cancelled_cb (GCancellable *cancellable, FuCommonSpawnHelper *helper)
728{
729 /* just propagate */
730 g_cancellable_cancel (helper->cancellable);
731}
732
Richard Hughes049ccc82017-08-09 15:26:56 +0100733/**
734 * fu_common_spawn_sync:
735 * @argv: The argument list to run
Richard Hughes4eada342017-10-03 21:20:32 +0100736 * @handler_cb: (scope call): A #FuOutputHandler or %NULL
737 * @handler_user_data: the user data to pass to @handler_cb
Richard Hughesb768e4d2019-02-26 13:55:18 +0000738 * @timeout_ms: a timeout in ms, or 0 for no limit
Richard Hughes049ccc82017-08-09 15:26:56 +0100739 * @cancellable: a #GCancellable, or %NULL
740 * @error: A #GError or %NULL
741 *
742 * Runs a subprocess and waits for it to exit. Any output on standard out or
743 * standard error will be forwarded to @handler_cb as whole lines.
744 *
745 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600746 *
747 * Since: 0.9.7
Richard Hughes049ccc82017-08-09 15:26:56 +0100748 **/
749gboolean
750fu_common_spawn_sync (const gchar * const * argv,
751 FuOutputHandler handler_cb,
752 gpointer handler_user_data,
Richard Hughesb768e4d2019-02-26 13:55:18 +0000753 guint timeout_ms,
Richard Hughes049ccc82017-08-09 15:26:56 +0100754 GCancellable *cancellable, GError **error)
755{
756 g_autoptr(FuCommonSpawnHelper) helper = NULL;
757 g_autoptr(GSubprocess) subprocess = NULL;
Richard Hughes455fdd32017-08-16 12:26:44 +0100758 g_autofree gchar *argv_str = NULL;
Richard Hughesb768e4d2019-02-26 13:55:18 +0000759 gulong cancellable_id = 0;
Richard Hughes049ccc82017-08-09 15:26:56 +0100760
Richard Hughes6a489a92020-12-22 10:32:06 +0000761 g_return_val_if_fail (argv != NULL, FALSE);
762 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
763 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
764
Richard Hughes049ccc82017-08-09 15:26:56 +0100765 /* create subprocess */
Richard Hughes455fdd32017-08-16 12:26:44 +0100766 argv_str = g_strjoinv (" ", (gchar **) argv);
767 g_debug ("running '%s'", argv_str);
Richard Hughes049ccc82017-08-09 15:26:56 +0100768 subprocess = g_subprocess_newv (argv, G_SUBPROCESS_FLAGS_STDOUT_PIPE |
769 G_SUBPROCESS_FLAGS_STDERR_MERGE, error);
770 if (subprocess == NULL)
771 return FALSE;
772
773 /* watch for process to exit */
774 helper = g_new0 (FuCommonSpawnHelper, 1);
775 helper->handler_cb = handler_cb;
776 helper->handler_user_data = handler_user_data;
777 helper->loop = g_main_loop_new (NULL, FALSE);
778 helper->stream = g_subprocess_get_stdout_pipe (subprocess);
Richard Hughesb768e4d2019-02-26 13:55:18 +0000779
780 /* always create a cancellable, and connect up the parent */
781 helper->cancellable = g_cancellable_new ();
782 if (cancellable != NULL) {
783 cancellable_id = g_cancellable_connect (cancellable,
784 G_CALLBACK (fu_common_spawn_cancelled_cb),
785 helper, NULL);
786 }
787
788 /* allow timeout */
789 if (timeout_ms > 0) {
790 helper->timeout_id = g_timeout_add (timeout_ms,
791 fu_common_spawn_timeout_cb,
792 helper);
793 }
Richard Hughes049ccc82017-08-09 15:26:56 +0100794 fu_common_spawn_create_pollable_source (helper);
795 g_main_loop_run (helper->loop);
Richard Hughesb768e4d2019-02-26 13:55:18 +0000796 g_cancellable_disconnect (cancellable, cancellable_id);
797 if (g_cancellable_set_error_if_cancelled (helper->cancellable, error))
798 return FALSE;
Richard Hughes049ccc82017-08-09 15:26:56 +0100799 return g_subprocess_wait_check (subprocess, cancellable, error);
800}
Richard Hughesae252cd2017-12-08 10:48:15 +0000801
802/**
803 * fu_common_write_uint16:
804 * @buf: A writable buffer
805 * @val_native: a value in host byte-order
Richard Hughes8aa72392018-05-02 08:38:43 +0100806 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000807 *
808 * Writes a value to a buffer using a specified endian.
Mario Limonciello1a680f32019-11-25 19:44:53 -0600809 *
810 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000811 **/
812void
813fu_common_write_uint16 (guint8 *buf, guint16 val_native, FuEndianType endian)
814{
815 guint16 val_hw;
816 switch (endian) {
817 case G_BIG_ENDIAN:
818 val_hw = GUINT16_TO_BE(val_native);
819 break;
820 case G_LITTLE_ENDIAN:
821 val_hw = GUINT16_TO_LE(val_native);
822 break;
823 default:
824 g_assert_not_reached ();
825 }
826 memcpy (buf, &val_hw, sizeof(val_hw));
827}
828
829/**
830 * fu_common_write_uint32:
831 * @buf: A writable buffer
832 * @val_native: a value in host byte-order
Richard Hughes8aa72392018-05-02 08:38:43 +0100833 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000834 *
835 * Writes a value to a buffer using a specified endian.
Mario Limonciello1a680f32019-11-25 19:44:53 -0600836 *
837 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000838 **/
839void
840fu_common_write_uint32 (guint8 *buf, guint32 val_native, FuEndianType endian)
841{
842 guint32 val_hw;
843 switch (endian) {
844 case G_BIG_ENDIAN:
845 val_hw = GUINT32_TO_BE(val_native);
846 break;
847 case G_LITTLE_ENDIAN:
848 val_hw = GUINT32_TO_LE(val_native);
849 break;
850 default:
851 g_assert_not_reached ();
852 }
853 memcpy (buf, &val_hw, sizeof(val_hw));
854}
855
856/**
857 * fu_common_read_uint16:
858 * @buf: A readable buffer
Richard Hughes8aa72392018-05-02 08:38:43 +0100859 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000860 *
861 * Read a value from a buffer using a specified endian.
862 *
863 * Returns: a value in host byte-order
Mario Limonciello1a680f32019-11-25 19:44:53 -0600864 *
865 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000866 **/
867guint16
868fu_common_read_uint16 (const guint8 *buf, FuEndianType endian)
869{
870 guint16 val_hw, val_native;
871 memcpy (&val_hw, buf, sizeof(val_hw));
872 switch (endian) {
873 case G_BIG_ENDIAN:
874 val_native = GUINT16_FROM_BE(val_hw);
875 break;
876 case G_LITTLE_ENDIAN:
877 val_native = GUINT16_FROM_LE(val_hw);
878 break;
879 default:
880 g_assert_not_reached ();
881 }
882 return val_native;
883}
884
885/**
886 * fu_common_read_uint32:
887 * @buf: A readable buffer
Richard Hughes8aa72392018-05-02 08:38:43 +0100888 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000889 *
890 * Read a value from a buffer using a specified endian.
891 *
892 * Returns: a value in host byte-order
Mario Limonciello1a680f32019-11-25 19:44:53 -0600893 *
894 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000895 **/
896guint32
897fu_common_read_uint32 (const guint8 *buf, FuEndianType endian)
898{
899 guint32 val_hw, val_native;
900 memcpy (&val_hw, buf, sizeof(val_hw));
901 switch (endian) {
902 case G_BIG_ENDIAN:
903 val_native = GUINT32_FROM_BE(val_hw);
904 break;
905 case G_LITTLE_ENDIAN:
906 val_native = GUINT32_FROM_LE(val_hw);
907 break;
908 default:
909 g_assert_not_reached ();
910 }
911 return val_native;
912}
Richard Hughese82eef32018-05-20 10:41:26 +0100913
Richard Hughes73bf2332018-08-28 09:38:09 +0100914/**
915 * fu_common_strtoull:
916 * @str: A string, e.g. "0x1234"
917 *
918 * Converts a string value to an integer. Values are assumed base 10, unless
919 * prefixed with "0x" where they are parsed as base 16.
920 *
921 * Returns: integer value, or 0x0 for error
Mario Limonciello1a680f32019-11-25 19:44:53 -0600922 *
923 * Since: 1.1.2
Richard Hughes73bf2332018-08-28 09:38:09 +0100924 **/
925guint64
926fu_common_strtoull (const gchar *str)
927{
928 guint base = 10;
929 if (str == NULL)
930 return 0x0;
931 if (g_str_has_prefix (str, "0x")) {
932 str += 2;
933 base = 16;
934 }
935 return g_ascii_strtoull (str, NULL, base);
936}
937
Richard Hughesa574a752018-08-31 13:31:03 +0100938/**
939 * fu_common_strstrip:
940 * @str: A string, e.g. " test "
941 *
942 * Removes leading and trailing whitespace from a constant string.
943 *
944 * Returns: newly allocated string
Mario Limonciello1a680f32019-11-25 19:44:53 -0600945 *
946 * Since: 1.1.2
Richard Hughesa574a752018-08-31 13:31:03 +0100947 **/
948gchar *
949fu_common_strstrip (const gchar *str)
950{
951 guint head = G_MAXUINT;
952 guint tail = 0;
953
954 g_return_val_if_fail (str != NULL, NULL);
955
956 /* find first non-space char */
957 for (guint i = 0; str[i] != '\0'; i++) {
958 if (str[i] != ' ') {
959 head = i;
960 break;
961 }
962 }
963 if (head == G_MAXUINT)
964 return g_strdup ("");
965
966 /* find last non-space char */
967 for (guint i = head; str[i] != '\0'; i++) {
Mario Limoncielloef3c7662019-09-04 23:37:59 -0500968 if (!g_ascii_isspace (str[i]))
Richard Hughesa574a752018-08-31 13:31:03 +0100969 tail = i;
970 }
971 return g_strndup (str + head, tail - head + 1);
972}
973
Richard Hughese82eef32018-05-20 10:41:26 +0100974static const GError *
975fu_common_error_array_find (GPtrArray *errors, FwupdError error_code)
976{
977 for (guint j = 0; j < errors->len; j++) {
978 const GError *error = g_ptr_array_index (errors, j);
979 if (g_error_matches (error, FWUPD_ERROR, error_code))
980 return error;
981 }
982 return NULL;
983}
984
985static guint
986fu_common_error_array_count (GPtrArray *errors, FwupdError error_code)
987{
988 guint cnt = 0;
989 for (guint j = 0; j < errors->len; j++) {
990 const GError *error = g_ptr_array_index (errors, j);
991 if (g_error_matches (error, FWUPD_ERROR, error_code))
992 cnt++;
993 }
994 return cnt;
995}
996
997static gboolean
998fu_common_error_array_matches_any (GPtrArray *errors, FwupdError *error_codes)
999{
1000 for (guint j = 0; j < errors->len; j++) {
1001 const GError *error = g_ptr_array_index (errors, j);
1002 gboolean matches_any = FALSE;
1003 for (guint i = 0; error_codes[i] != FWUPD_ERROR_LAST; i++) {
1004 if (g_error_matches (error, FWUPD_ERROR, error_codes[i])) {
1005 matches_any = TRUE;
1006 break;
1007 }
1008 }
1009 if (!matches_any)
1010 return FALSE;
1011 }
1012 return TRUE;
1013}
1014
1015/**
1016 * fu_common_error_array_get_best:
1017 * @errors: (element-type GError): array of errors
1018 *
1019 * Finds the 'best' error to show the user from a array of errors, creating a
1020 * completely bespoke error where required.
1021 *
1022 * Returns: (transfer full): a #GError, never %NULL
Mario Limonciello1a680f32019-11-25 19:44:53 -06001023 *
1024 * Since: 1.0.8
Richard Hughese82eef32018-05-20 10:41:26 +01001025 **/
1026GError *
1027fu_common_error_array_get_best (GPtrArray *errors)
1028{
1029 FwupdError err_prio[] = { FWUPD_ERROR_INVALID_FILE,
1030 FWUPD_ERROR_VERSION_SAME,
1031 FWUPD_ERROR_VERSION_NEWER,
1032 FWUPD_ERROR_NOT_SUPPORTED,
1033 FWUPD_ERROR_INTERNAL,
1034 FWUPD_ERROR_NOT_FOUND,
1035 FWUPD_ERROR_LAST };
1036 FwupdError err_all_uptodate[] = { FWUPD_ERROR_VERSION_SAME,
1037 FWUPD_ERROR_NOT_FOUND,
1038 FWUPD_ERROR_NOT_SUPPORTED,
1039 FWUPD_ERROR_LAST };
1040 FwupdError err_all_newer[] = { FWUPD_ERROR_VERSION_NEWER,
1041 FWUPD_ERROR_VERSION_SAME,
1042 FWUPD_ERROR_NOT_FOUND,
1043 FWUPD_ERROR_NOT_SUPPORTED,
1044 FWUPD_ERROR_LAST };
1045
1046 /* are all the errors either GUID-not-matched or version-same? */
1047 if (fu_common_error_array_count (errors, FWUPD_ERROR_VERSION_SAME) > 1 &&
1048 fu_common_error_array_matches_any (errors, err_all_uptodate)) {
1049 return g_error_new (FWUPD_ERROR,
1050 FWUPD_ERROR_NOTHING_TO_DO,
1051 "All updatable firmware is already installed");
1052 }
1053
1054 /* are all the errors either GUID-not-matched or version same or newer? */
1055 if (fu_common_error_array_count (errors, FWUPD_ERROR_VERSION_NEWER) > 1 &&
1056 fu_common_error_array_matches_any (errors, err_all_newer)) {
1057 return g_error_new (FWUPD_ERROR,
1058 FWUPD_ERROR_NOTHING_TO_DO,
1059 "All updatable devices already have newer versions");
1060 }
1061
1062 /* get the most important single error */
1063 for (guint i = 0; err_prio[i] != FWUPD_ERROR_LAST; i++) {
1064 const GError *error_tmp = fu_common_error_array_find (errors, err_prio[i]);
1065 if (error_tmp != NULL)
1066 return g_error_copy (error_tmp);
1067 }
1068
1069 /* fall back to something */
1070 return g_error_new (FWUPD_ERROR,
1071 FWUPD_ERROR_NOT_FOUND,
1072 "No supported devices found");
1073}
Richard Hughes4be17d12018-05-30 20:36:29 +01001074
1075/**
1076 * fu_common_get_path:
1077 * @path_kind: A #FuPathKind e.g. %FU_PATH_KIND_DATADIR_PKG
1078 *
1079 * Gets a fwupd-specific system path. These can be overridden with various
1080 * environment variables, for instance %FWUPD_DATADIR.
1081 *
1082 * Returns: a system path, or %NULL if invalid
Mario Limonciello1a680f32019-11-25 19:44:53 -06001083 *
1084 * Since: 1.0.8
Richard Hughes4be17d12018-05-30 20:36:29 +01001085 **/
1086gchar *
1087fu_common_get_path (FuPathKind path_kind)
1088{
1089 const gchar *tmp;
1090 g_autofree gchar *basedir = NULL;
1091
1092 switch (path_kind) {
1093 /* /var */
1094 case FU_PATH_KIND_LOCALSTATEDIR:
1095 tmp = g_getenv ("FWUPD_LOCALSTATEDIR");
1096 if (tmp != NULL)
1097 return g_strdup (tmp);
1098 tmp = g_getenv ("SNAP_USER_DATA");
1099 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001100 return g_build_filename (tmp, FWUPD_LOCALSTATEDIR, NULL);
1101 return g_build_filename (FWUPD_LOCALSTATEDIR, NULL);
Richard Hughesc3689582020-05-06 12:35:20 +01001102 /* /proc */
1103 case FU_PATH_KIND_PROCFS:
1104 tmp = g_getenv ("FWUPD_PROCFS");
1105 if (tmp != NULL)
1106 return g_strdup (tmp);
1107 return g_strdup ("/proc");
Richard Hughes282b10d2018-06-22 14:48:00 +01001108 /* /sys/firmware */
1109 case FU_PATH_KIND_SYSFSDIR_FW:
1110 tmp = g_getenv ("FWUPD_SYSFSFWDIR");
1111 if (tmp != NULL)
1112 return g_strdup (tmp);
1113 return g_strdup ("/sys/firmware");
Mario Limonciello39602652019-04-29 21:08:58 -05001114 /* /sys/class/tpm */
Richard Hughesb56015e2018-12-12 09:25:32 +00001115 case FU_PATH_KIND_SYSFSDIR_TPM:
1116 tmp = g_getenv ("FWUPD_SYSFSTPMDIR");
1117 if (tmp != NULL)
1118 return g_strdup (tmp);
1119 return g_strdup ("/sys/class/tpm");
Richard Hughes83390f62018-06-22 20:36:46 +01001120 /* /sys/bus/platform/drivers */
1121 case FU_PATH_KIND_SYSFSDIR_DRIVERS:
1122 tmp = g_getenv ("FWUPD_SYSFSDRIVERDIR");
1123 if (tmp != NULL)
1124 return g_strdup (tmp);
1125 return g_strdup ("/sys/bus/platform/drivers");
Mario Limonciello9dce1f72020-02-04 09:12:52 -06001126 /* /sys/kernel/security */
1127 case FU_PATH_KIND_SYSFSDIR_SECURITY:
1128 tmp = g_getenv ("FWUPD_SYSFSSECURITYDIR");
1129 if (tmp != NULL)
1130 return g_strdup (tmp);
1131 return g_strdup ("/sys/kernel/security");
Richard Hughesa7157912020-05-11 17:14:05 +01001132 /* /sys/firmware/acpi/tables */
1133 case FU_PATH_KIND_ACPI_TABLES:
1134 tmp = g_getenv ("FWUPD_ACPITABLESDIR");
1135 if (tmp != NULL)
1136 return g_strdup (tmp);
1137 return g_strdup ("/sys/firmware/acpi/tables");
Richard Hughes4be17d12018-05-30 20:36:29 +01001138 /* /etc */
1139 case FU_PATH_KIND_SYSCONFDIR:
1140 tmp = g_getenv ("FWUPD_SYSCONFDIR");
1141 if (tmp != NULL)
1142 return g_strdup (tmp);
1143 tmp = g_getenv ("SNAP_USER_DATA");
1144 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001145 return g_build_filename (tmp, FWUPD_SYSCONFDIR, NULL);
1146 return g_strdup (FWUPD_SYSCONFDIR);
Richard Hughes4be17d12018-05-30 20:36:29 +01001147 /* /usr/lib/<triplet>/fwupd-plugins-3 */
1148 case FU_PATH_KIND_PLUGINDIR_PKG:
1149 tmp = g_getenv ("FWUPD_PLUGINDIR");
1150 if (tmp != NULL)
1151 return g_strdup (tmp);
1152 tmp = g_getenv ("SNAP");
1153 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001154 return g_build_filename (tmp, FWUPD_PLUGINDIR, NULL);
1155 return g_build_filename (FWUPD_PLUGINDIR, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001156 /* /usr/share/fwupd */
1157 case FU_PATH_KIND_DATADIR_PKG:
1158 tmp = g_getenv ("FWUPD_DATADIR");
1159 if (tmp != NULL)
1160 return g_strdup (tmp);
1161 tmp = g_getenv ("SNAP");
1162 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001163 return g_build_filename (tmp, FWUPD_DATADIR, PACKAGE_NAME, NULL);
1164 return g_build_filename (FWUPD_DATADIR, PACKAGE_NAME, NULL);
Mario Limoncielloe6e2bf92018-07-10 12:11:25 -05001165 /* /usr/libexec/fwupd/efi */
1166 case FU_PATH_KIND_EFIAPPDIR:
1167 tmp = g_getenv ("FWUPD_EFIAPPDIR");
1168 if (tmp != NULL)
1169 return g_strdup (tmp);
1170#ifdef EFI_APP_LOCATION
1171 tmp = g_getenv ("SNAP");
1172 if (tmp != NULL)
1173 return g_build_filename (tmp, EFI_APP_LOCATION, NULL);
1174 return g_strdup (EFI_APP_LOCATION);
1175#else
1176 return NULL;
1177#endif
Richard Hughes4be17d12018-05-30 20:36:29 +01001178 /* /etc/fwupd */
1179 case FU_PATH_KIND_SYSCONFDIR_PKG:
Mario Limonciello277c1962019-08-26 23:42:23 -05001180 tmp = g_getenv ("CONFIGURATION_DIRECTORY");
Mario Limonciello695cb582019-12-12 10:45:42 -06001181 if (tmp != NULL && g_file_test (tmp, G_FILE_TEST_EXISTS))
Mario Limonciello277c1962019-08-26 23:42:23 -05001182 return g_build_filename (tmp, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001183 basedir = fu_common_get_path (FU_PATH_KIND_SYSCONFDIR);
1184 return g_build_filename (basedir, PACKAGE_NAME, NULL);
1185 /* /var/lib/fwupd */
1186 case FU_PATH_KIND_LOCALSTATEDIR_PKG:
Mario Limonciello277c1962019-08-26 23:42:23 -05001187 tmp = g_getenv ("STATE_DIRECTORY");
Mario Limonciello695cb582019-12-12 10:45:42 -06001188 if (tmp != NULL && g_file_test (tmp, G_FILE_TEST_EXISTS))
Mario Limonciello277c1962019-08-26 23:42:23 -05001189 return g_build_filename (tmp, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001190 basedir = fu_common_get_path (FU_PATH_KIND_LOCALSTATEDIR);
1191 return g_build_filename (basedir, "lib", PACKAGE_NAME, NULL);
1192 /* /var/cache/fwupd */
1193 case FU_PATH_KIND_CACHEDIR_PKG:
Mario Limonciello277c1962019-08-26 23:42:23 -05001194 tmp = g_getenv ("CACHE_DIRECTORY");
Mario Limonciello695cb582019-12-12 10:45:42 -06001195 if (tmp != NULL && g_file_test (tmp, G_FILE_TEST_EXISTS))
Mario Limonciello277c1962019-08-26 23:42:23 -05001196 return g_build_filename (tmp, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001197 basedir = fu_common_get_path (FU_PATH_KIND_LOCALSTATEDIR);
1198 return g_build_filename (basedir, "cache", PACKAGE_NAME, NULL);
Richard Hughesafdba372019-11-23 12:57:35 +00001199 case FU_PATH_KIND_OFFLINE_TRIGGER:
1200 tmp = g_getenv ("FWUPD_OFFLINE_TRIGGER");
1201 if (tmp != NULL)
1202 return g_strdup (tmp);
1203 return g_strdup ("/system-update");
Mario Limonciello057c67a2019-05-23 10:44:19 -05001204 case FU_PATH_KIND_POLKIT_ACTIONS:
1205#ifdef POLKIT_ACTIONDIR
1206 return g_strdup (POLKIT_ACTIONDIR);
1207#else
1208 return NULL;
1209#endif
Richard Hughes4be17d12018-05-30 20:36:29 +01001210 /* this shouldn't happen */
1211 default:
Richard Hughesbeb47a82018-09-11 18:28:53 +01001212 g_warning ("cannot build path for unknown kind %u", path_kind);
Richard Hughes4be17d12018-05-30 20:36:29 +01001213 }
1214
1215 return NULL;
1216}
Richard Hughes83e56c12018-10-10 20:24:41 +01001217
1218/**
1219 * fu_common_string_replace:
1220 * @string: The #GString to operate on
1221 * @search: The text to search for
1222 * @replace: The text to use for substitutions
1223 *
1224 * Performs multiple search and replace operations on the given string.
1225 *
1226 * Returns: the number of replacements done, or 0 if @search is not found.
1227 *
1228 * Since: 1.2.0
1229 **/
1230guint
1231fu_common_string_replace (GString *string, const gchar *search, const gchar *replace)
1232{
1233 gchar *tmp;
1234 guint count = 0;
1235 gsize search_idx = 0;
1236 gsize replace_len;
1237 gsize search_len;
1238
1239 g_return_val_if_fail (string != NULL, 0);
1240 g_return_val_if_fail (search != NULL, 0);
1241 g_return_val_if_fail (replace != NULL, 0);
1242
1243 /* nothing to do */
1244 if (string->len == 0)
1245 return 0;
1246
1247 search_len = strlen (search);
1248 replace_len = strlen (replace);
1249
1250 do {
1251 tmp = g_strstr_len (string->str + search_idx, -1, search);
1252 if (tmp == NULL)
1253 break;
1254
1255 /* advance the counter in case @replace contains @search */
1256 search_idx = (gsize) (tmp - string->str);
1257
1258 /* reallocate the string if required */
1259 if (search_len > replace_len) {
1260 g_string_erase (string,
1261 (gssize) search_idx,
1262 (gssize) (search_len - replace_len));
1263 memcpy (tmp, replace, replace_len);
1264 } else if (search_len < replace_len) {
1265 g_string_insert_len (string,
1266 (gssize) search_idx,
1267 replace,
1268 (gssize) (replace_len - search_len));
1269 /* we have to treat this specially as it could have
1270 * been reallocated when the insertion happened */
1271 memcpy (string->str + search_idx, replace, replace_len);
1272 } else {
1273 /* just memcmp in the new string */
1274 memcpy (tmp, replace, replace_len);
1275 }
1276 search_idx += replace_len;
1277 count++;
1278 } while (TRUE);
1279
1280 return count;
1281}
Richard Hughese59cb9a2018-12-05 14:37:40 +00001282
Richard Hughesae96a1f2019-09-23 11:16:36 +01001283/**
1284 * fu_common_strwidth:
1285 * @text: The string to operate on
1286 *
1287 * Returns the width of the string in displayed characters on the console.
1288 *
1289 * Returns: width of text
1290 *
1291 * Since: 1.3.2
1292 **/
1293gsize
1294fu_common_strwidth (const gchar *text)
1295{
1296 const gchar *p = text;
1297 gsize width = 0;
Richard Hughes4d2c0f82020-07-07 12:02:30 +01001298
1299 g_return_val_if_fail (text != NULL, 0);
1300
Richard Hughesae96a1f2019-09-23 11:16:36 +01001301 while (*p) {
1302 gunichar c = g_utf8_get_char (p);
1303 if (g_unichar_iswide (c))
1304 width += 2;
1305 else if (!g_unichar_iszerowidth (c))
1306 width += 1;
1307 p = g_utf8_next_char (p);
1308 }
1309 return width;
1310}
1311
Mario Limonciello1a680f32019-11-25 19:44:53 -06001312/**
1313 * fu_common_string_append_kv:
1314 * @str: A #GString
1315 * @idt: The indent
1316 * @key: A string to append
1317 * @value: a string to append
1318 *
1319 * Appends a key and string value to a string
1320 *
1321 * Since: 1.2.4
1322 */
Richard Hughescea28de2019-08-09 11:16:40 +01001323void
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001324fu_common_string_append_kv (GString *str, guint idt, const gchar *key, const gchar *value)
Richard Hughescea28de2019-08-09 11:16:40 +01001325{
Richard Hughes2506dbf2020-09-03 10:04:19 +01001326 const guint align = 24;
Richard Hughes847cae82019-08-27 11:22:23 +01001327 gsize keysz;
Richard Hughescea28de2019-08-09 11:16:40 +01001328
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001329 g_return_if_fail (idt * 2 < align);
Richard Hughescea28de2019-08-09 11:16:40 +01001330
1331 /* ignore */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001332 if (key == NULL)
Richard Hughescea28de2019-08-09 11:16:40 +01001333 return;
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001334 for (gsize i = 0; i < idt; i++)
1335 g_string_append (str, " ");
Mario Limonciellofee8f492019-08-18 12:16:07 -05001336 if (key[0] != '\0') {
1337 g_string_append_printf (str, "%s:", key);
Richard Hughesae96a1f2019-09-23 11:16:36 +01001338 keysz = (idt * 2) + fu_common_strwidth (key) + 1;
Richard Hughes847cae82019-08-27 11:22:23 +01001339 } else {
1340 keysz = idt * 2;
Mario Limonciellofee8f492019-08-18 12:16:07 -05001341 }
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001342 if (value != NULL) {
Mario Limonciello1dbb82d2019-09-20 14:22:14 -05001343 g_auto(GStrv) split = NULL;
1344 split = g_strsplit (value, "\n", -1);
1345 for (guint i = 0; split[i] != NULL; i++) {
1346 if (i == 0) {
1347 for (gsize j = keysz; j < align; j++)
1348 g_string_append (str, " ");
1349 } else {
1350 for (gsize j = 0; j < idt; j++)
1351 g_string_append (str, " ");
1352 }
1353 g_string_append (str, split[i]);
1354 g_string_append (str, "\n");
1355 }
1356 } else {
1357 g_string_append (str, "\n");
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001358 }
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001359}
1360
Mario Limonciello1a680f32019-11-25 19:44:53 -06001361/**
1362 * fu_common_string_append_ku:
1363 * @str: A #GString
1364 * @idt: The indent
1365 * @key: A string to append
1366 * @value: guint64
1367 *
1368 * Appends a key and unsigned integer to a string
1369 *
1370 * Since: 1.2.4
1371 */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001372void
1373fu_common_string_append_ku (GString *str, guint idt, const gchar *key, guint64 value)
1374{
1375 g_autofree gchar *tmp = g_strdup_printf ("%" G_GUINT64_FORMAT, value);
1376 fu_common_string_append_kv (str, idt, key, tmp);
1377}
1378
Mario Limonciello1a680f32019-11-25 19:44:53 -06001379/**
1380 * fu_common_string_append_kx:
1381 * @str: A #GString
1382 * @idt: The indent
1383 * @key: A string to append
1384 * @value: guint64
1385 *
1386 * Appends a key and hex integer to a string
1387 *
1388 * Since: 1.2.4
1389 */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001390void
1391fu_common_string_append_kx (GString *str, guint idt, const gchar *key, guint64 value)
1392{
1393 g_autofree gchar *tmp = g_strdup_printf ("0x%x", (guint) value);
1394 fu_common_string_append_kv (str, idt, key, tmp);
1395}
1396
Mario Limonciello1a680f32019-11-25 19:44:53 -06001397/**
1398 * fu_common_string_append_kb:
1399 * @str: A #GString
1400 * @idt: The indent
1401 * @key: A string to append
1402 * @value: Boolean
1403 *
1404 * Appends a key and boolean value to a string
1405 *
1406 * Since: 1.2.4
1407 */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001408void
1409fu_common_string_append_kb (GString *str, guint idt, const gchar *key, gboolean value)
1410{
1411 fu_common_string_append_kv (str, idt, key, value ? "true" : "false");
Richard Hughescea28de2019-08-09 11:16:40 +01001412}
1413
Richard Hughese59cb9a2018-12-05 14:37:40 +00001414/**
Richard Hughes35481862019-01-06 12:01:58 +00001415 * fu_common_dump_full:
1416 * @log_domain: log domain, typically %G_LOG_DOMAIN or %NULL
1417 * @title: prefix title, or %NULL
1418 * @data: buffer to print
1419 * @len: the size of @data
1420 * @columns: break new lines after this many bytes
1421 * @flags: some #FuDumpFlags, e.g. %FU_DUMP_FLAGS_SHOW_ASCII
1422 *
1423 * Dumps a raw buffer to the screen.
1424 *
1425 * Since: 1.2.4
1426 **/
1427void
1428fu_common_dump_full (const gchar *log_domain,
1429 const gchar *title,
1430 const guint8 *data,
1431 gsize len,
1432 guint columns,
1433 FuDumpFlags flags)
1434{
1435 g_autoptr(GString) str = g_string_new (NULL);
1436
1437 /* optional */
1438 if (title != NULL)
1439 g_string_append_printf (str, "%s:", title);
1440
1441 /* if more than can fit on one line then start afresh */
1442 if (len > columns || flags & FU_DUMP_FLAGS_SHOW_ADDRESSES) {
1443 g_string_append (str, "\n");
1444 } else {
1445 for (gsize i = str->len; i < 16; i++)
1446 g_string_append (str, " ");
1447 }
1448
1449 /* offset line */
1450 if (flags & FU_DUMP_FLAGS_SHOW_ADDRESSES) {
1451 g_string_append (str, " │ ");
1452 for (gsize i = 0; i < columns; i++)
1453 g_string_append_printf (str, "%02x ", (guint) i);
1454 g_string_append (str, "\n───────┼");
1455 for (gsize i = 0; i < columns; i++)
1456 g_string_append (str, "───");
1457 g_string_append_printf (str, "\n0x%04x │ ", (guint) 0);
1458 }
1459
1460 /* print each row */
1461 for (gsize i = 0; i < len; i++) {
1462 g_string_append_printf (str, "%02x ", data[i]);
1463
1464 /* optionally print ASCII char */
1465 if (flags & FU_DUMP_FLAGS_SHOW_ASCII) {
1466 if (g_ascii_isprint (data[i]))
1467 g_string_append_printf (str, "[%c] ", data[i]);
1468 else
1469 g_string_append (str, "[?] ");
1470 }
1471
1472 /* new row required */
1473 if (i > 0 && i != len - 1 && (i + 1) % columns == 0) {
1474 g_string_append (str, "\n");
1475 if (flags & FU_DUMP_FLAGS_SHOW_ADDRESSES)
1476 g_string_append_printf (str, "0x%04x │ ", (guint) i + 1);
1477 }
1478 }
1479 g_log (log_domain, G_LOG_LEVEL_DEBUG, "%s", str->str);
1480}
1481
1482/**
Richard Hughese59cb9a2018-12-05 14:37:40 +00001483 * fu_common_dump_raw:
1484 * @log_domain: log domain, typically %G_LOG_DOMAIN or %NULL
1485 * @title: prefix title, or %NULL
1486 * @data: buffer to print
1487 * @len: the size of @data
1488 *
1489 * Dumps a raw buffer to the screen.
1490 *
1491 * Since: 1.2.2
1492 **/
1493void
1494fu_common_dump_raw (const gchar *log_domain,
1495 const gchar *title,
1496 const guint8 *data,
1497 gsize len)
1498{
Richard Hughes35481862019-01-06 12:01:58 +00001499 FuDumpFlags flags = FU_DUMP_FLAGS_NONE;
1500 if (len > 64)
1501 flags |= FU_DUMP_FLAGS_SHOW_ADDRESSES;
1502 fu_common_dump_full (log_domain, title, data, len, 32, flags);
Richard Hughese59cb9a2018-12-05 14:37:40 +00001503}
1504
1505/**
Mario Limonciello39602652019-04-29 21:08:58 -05001506 * fu_common_dump_bytes:
Richard Hughese59cb9a2018-12-05 14:37:40 +00001507 * @log_domain: log domain, typically %G_LOG_DOMAIN or %NULL
1508 * @title: prefix title, or %NULL
1509 * @bytes: a #GBytes
1510 *
1511 * Dumps a byte buffer to the screen.
1512 *
1513 * Since: 1.2.2
1514 **/
1515void
1516fu_common_dump_bytes (const gchar *log_domain,
1517 const gchar *title,
1518 GBytes *bytes)
1519{
1520 gsize len = 0;
1521 const guint8 *data = g_bytes_get_data (bytes, &len);
1522 fu_common_dump_raw (log_domain, title, data, len);
1523}
Richard Hughesfc90f392019-01-15 21:21:16 +00001524
1525/**
1526 * fu_common_bytes_align:
1527 * @bytes: a #GBytes
1528 * @blksz: block size in bytes
1529 * @padval: the byte used to pad the byte buffer
1530 *
1531 * Aligns a block of memory to @blksize using the @padval value; if
1532 * the block is already aligned then the original @bytes is returned.
1533 *
1534 * Returns: (transfer full): a #GBytes, possibly @bytes
1535 *
1536 * Since: 1.2.4
1537 **/
1538GBytes *
1539fu_common_bytes_align (GBytes *bytes, gsize blksz, gchar padval)
1540{
1541 const guint8 *data;
1542 gsize sz;
1543
1544 g_return_val_if_fail (bytes != NULL, NULL);
1545 g_return_val_if_fail (blksz > 0, NULL);
1546
1547 /* pad */
1548 data = g_bytes_get_data (bytes, &sz);
1549 if (sz % blksz != 0) {
1550 gsize sz_align = ((sz / blksz) + 1) * blksz;
1551 guint8 *data_align = g_malloc (sz_align);
1552 memcpy (data_align, data, sz);
1553 memset (data_align + sz, padval, sz_align - sz);
1554 g_debug ("aligning 0x%x bytes to 0x%x",
1555 (guint) sz, (guint) sz_align);
1556 return g_bytes_new_take (data_align, sz_align);
1557 }
1558
1559 /* perfectly aligned */
1560 return g_bytes_ref (bytes);
1561}
Richard Hughes36999462019-03-19 20:23:29 +00001562
1563/**
1564 * fu_common_bytes_is_empty:
1565 * @bytes: a #GBytes
1566 *
1567 * Checks if a byte array are just empty (0xff) bytes.
1568 *
1569 * Return value: %TRUE if @bytes is empty
Mario Limonciello1a680f32019-11-25 19:44:53 -06001570 *
1571 * Since: 1.2.6
Richard Hughes36999462019-03-19 20:23:29 +00001572 **/
1573gboolean
1574fu_common_bytes_is_empty (GBytes *bytes)
1575{
1576 gsize sz = 0;
1577 const guint8 *buf = g_bytes_get_data (bytes, &sz);
1578 for (gsize i = 0; i < sz; i++) {
1579 if (buf[i] != 0xff)
1580 return FALSE;
1581 }
1582 return TRUE;
1583}
Richard Hughes2aad1042019-03-21 09:03:32 +00001584
1585/**
Richard Hughes38245ff2019-09-18 14:46:09 +01001586 * fu_common_bytes_compare_raw:
1587 * @buf1: a buffer
1588 * @bufsz1: sizeof @buf1
1589 * @buf2: another buffer
1590 * @bufsz2: sizeof @buf2
Richard Hughes2aad1042019-03-21 09:03:32 +00001591 * @error: A #GError or %NULL
1592 *
Richard Hughes38245ff2019-09-18 14:46:09 +01001593 * Compares the buffers for equality.
Richard Hughes2aad1042019-03-21 09:03:32 +00001594 *
Richard Hughes38245ff2019-09-18 14:46:09 +01001595 * Return value: %TRUE if @buf1 and @buf2 are identical
Mario Limonciello1a680f32019-11-25 19:44:53 -06001596 *
1597 * Since: 1.3.2
Richard Hughes2aad1042019-03-21 09:03:32 +00001598 **/
1599gboolean
Richard Hughes38245ff2019-09-18 14:46:09 +01001600fu_common_bytes_compare_raw (const guint8 *buf1, gsize bufsz1,
1601 const guint8 *buf2, gsize bufsz2,
1602 GError **error)
Richard Hughes2aad1042019-03-21 09:03:32 +00001603{
Richard Hughes38245ff2019-09-18 14:46:09 +01001604 g_return_val_if_fail (buf1 != NULL, FALSE);
1605 g_return_val_if_fail (buf2 != NULL, FALSE);
Richard Hughes2aad1042019-03-21 09:03:32 +00001606 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1607
1608 /* not the same length */
Richard Hughes2aad1042019-03-21 09:03:32 +00001609 if (bufsz1 != bufsz2) {
1610 g_set_error (error,
1611 G_IO_ERROR,
1612 G_IO_ERROR_INVALID_DATA,
1613 "got %" G_GSIZE_FORMAT " bytes, expected "
1614 "%" G_GSIZE_FORMAT, bufsz1, bufsz2);
1615 return FALSE;
1616 }
1617
1618 /* check matches */
1619 for (guint i = 0x0; i < bufsz1; i++) {
1620 if (buf1[i] != buf2[i]) {
1621 g_set_error (error,
1622 G_IO_ERROR,
1623 G_IO_ERROR_INVALID_DATA,
1624 "got 0x%02x, expected 0x%02x @ 0x%04x",
1625 buf1[i], buf2[i], i);
1626 return FALSE;
1627 }
1628 }
1629
1630 /* success */
1631 return TRUE;
1632}
Richard Hughes484ee292019-03-22 16:10:50 +00001633
1634/**
Richard Hughes38245ff2019-09-18 14:46:09 +01001635 * fu_common_bytes_compare:
1636 * @bytes1: a #GBytes
1637 * @bytes2: another #GBytes
1638 * @error: A #GError or %NULL
1639 *
1640 * Compares the buffers for equality.
1641 *
1642 * Return value: %TRUE if @bytes1 and @bytes2 are identical
Mario Limonciello1a680f32019-11-25 19:44:53 -06001643 *
1644 * Since: 1.2.6
Richard Hughes38245ff2019-09-18 14:46:09 +01001645 **/
1646gboolean
1647fu_common_bytes_compare (GBytes *bytes1, GBytes *bytes2, GError **error)
1648{
1649 const guint8 *buf1;
1650 const guint8 *buf2;
1651 gsize bufsz1;
1652 gsize bufsz2;
1653
1654 g_return_val_if_fail (bytes1 != NULL, FALSE);
1655 g_return_val_if_fail (bytes2 != NULL, FALSE);
1656 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1657
1658 buf1 = g_bytes_get_data (bytes1, &bufsz1);
1659 buf2 = g_bytes_get_data (bytes2, &bufsz2);
1660 return fu_common_bytes_compare_raw (buf1, bufsz1, buf2, bufsz2, error);
1661}
1662
1663/**
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001664 * fu_common_bytes_pad:
1665 * @bytes: a #GBytes
1666 * @sz: the desired size in bytes
1667 *
1668 * Pads a GBytes to a given @sz with `0xff`.
1669 *
1670 * Return value: (transfer full): a #GBytes
Mario Limonciello1a680f32019-11-25 19:44:53 -06001671 *
1672 * Since: 1.3.1
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001673 **/
1674GBytes *
1675fu_common_bytes_pad (GBytes *bytes, gsize sz)
1676{
1677 gsize bytes_sz;
1678
1679 g_return_val_if_fail (g_bytes_get_size (bytes) <= sz, NULL);
1680
1681 /* pad */
1682 bytes_sz = g_bytes_get_size (bytes);
1683 if (bytes_sz < sz) {
1684 const guint8 *data = g_bytes_get_data (bytes, NULL);
1685 guint8 *data_new = g_malloc (sz);
1686 memcpy (data_new, data, bytes_sz);
1687 memset (data_new + bytes_sz, 0xff, sz - bytes_sz);
1688 return g_bytes_new_take (data_new, sz);
1689 }
1690
1691 /* exactly right */
1692 return g_bytes_ref (bytes);
1693}
1694
1695/**
Richard Hughes05e33772020-12-08 18:37:02 +00001696 * fu_common_bytes_new_offset:
1697 * @bytes: a #GBytes
1698 * @offset: where subsection starts at
1699 * @length: length of subsection
1700 * @error: A #GError or %NULL
1701 *
1702 * Creates a #GBytes which is a subsection of another #GBytes.
1703 *
1704 * Return value: (transfer full): a #GBytes, or #NULL if range is invalid
1705 *
1706 * Since: 1.5.4
1707 **/
1708GBytes *
1709fu_common_bytes_new_offset (GBytes *bytes,
1710 gsize offset,
1711 gsize length,
1712 GError **error)
1713{
1714 g_return_val_if_fail (bytes != NULL, NULL);
Richard Hughes6a489a92020-12-22 10:32:06 +00001715 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
Richard Hughes05e33772020-12-08 18:37:02 +00001716
1717 /* sanity check */
1718 if (offset + length > g_bytes_get_size (bytes)) {
1719 g_set_error (error,
1720 G_IO_ERROR,
1721 G_IO_ERROR_INVALID_DATA,
1722 "cannot create bytes @0x%02x for 0x%02x "
1723 "as buffer only 0x%04x bytes in size",
1724 (guint) offset,
1725 (guint) length,
1726 (guint) g_bytes_get_size (bytes));
1727 return NULL;
1728 }
1729 return g_bytes_new_from_bytes (bytes, offset, length);
1730}
1731
1732/**
Richard Hughes484ee292019-03-22 16:10:50 +00001733 * fu_common_realpath:
1734 * @filename: a filename
1735 * @error: A #GError or %NULL
1736 *
1737 * Finds the canonicalized absolute filename for a path.
1738 *
1739 * Return value: A filename, or %NULL if invalid or not found
Mario Limonciello1a680f32019-11-25 19:44:53 -06001740 *
1741 * Since: 1.2.6
Richard Hughes484ee292019-03-22 16:10:50 +00001742 **/
1743gchar *
1744fu_common_realpath (const gchar *filename, GError **error)
1745{
1746 char full_tmp[PATH_MAX];
1747
1748 g_return_val_if_fail (filename != NULL, NULL);
Richard Hughes6a489a92020-12-22 10:32:06 +00001749 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
Richard Hughes484ee292019-03-22 16:10:50 +00001750
Richard Hughes8694dee2019-11-22 09:16:34 +00001751#ifdef HAVE_REALPATH
Richard Hughes484ee292019-03-22 16:10:50 +00001752 if (realpath (filename, full_tmp) == NULL) {
Richard Hughes8694dee2019-11-22 09:16:34 +00001753#else
1754 if (_fullpath (full_tmp, filename, sizeof(full_tmp)) == NULL) {
1755#endif
Richard Hughes484ee292019-03-22 16:10:50 +00001756 g_set_error (error,
1757 G_IO_ERROR,
1758 G_IO_ERROR_INVALID_DATA,
1759 "cannot resolve path: %s",
1760 strerror (errno));
1761 return NULL;
1762 }
Richard Hughes8694dee2019-11-22 09:16:34 +00001763 if (!g_file_test (full_tmp, G_FILE_TEST_EXISTS)) {
1764 g_set_error (error,
1765 G_IO_ERROR,
1766 G_IO_ERROR_INVALID_DATA,
1767 "cannot find path: %s",
1768 full_tmp);
1769 return NULL;
1770 }
Richard Hughes484ee292019-03-22 16:10:50 +00001771 return g_strdup (full_tmp);
1772}
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001773
1774/**
Richard Hughes5c508de2019-11-22 09:57:34 +00001775 * fu_common_fnmatch:
1776 * @pattern: a glob pattern, e.g. `*foo*`
1777 * @str: a string to match against the pattern, e.g. `bazfoobar`
1778 *
1779 * Matches a string against a glob pattern.
1780 *
1781 * Return value: %TRUE if the string matched
1782 *
1783 * Since: 1.3.5
1784 **/
1785gboolean
1786fu_common_fnmatch (const gchar *pattern, const gchar *str)
1787{
1788 g_return_val_if_fail (pattern != NULL, FALSE);
1789 g_return_val_if_fail (str != NULL, FALSE);
1790#ifdef HAVE_FNMATCH_H
1791 return fnmatch (pattern, str, FNM_NOESCAPE) == 0;
Richard Hughes45a00732019-11-22 16:57:14 +00001792#elif _WIN32
1793 g_return_val_if_fail (strlen (pattern) < MAX_PATH, FALSE);
1794 g_return_val_if_fail (strlen (str) < MAX_PATH, FALSE);
1795 return PathMatchSpecA (str, pattern);
Richard Hughes5c508de2019-11-22 09:57:34 +00001796#else
1797 return g_strcmp0 (pattern, str) == 0;
1798#endif
1799}
1800
Richard Hughesa84d7a72020-05-06 12:11:51 +01001801static gint
1802fu_common_filename_glob_sort_cb (gconstpointer a, gconstpointer b)
1803{
1804 return g_strcmp0 (*(const gchar **)a, *(const gchar **)b);
1805}
1806
1807/**
1808 * fu_common_filename_glob:
1809 * @directory: a directory path
1810 * @pattern: a glob pattern, e.g. `*foo*`
1811 * @error: A #GError or %NULL
1812 *
1813 * Returns all the filenames that match a specific glob pattern.
1814 * Any results are sorted. No matching files will set @error.
1815 *
1816 * Return value: (element-type utf8) (transfer container): matching files, or %NULL
1817 *
1818 * Since: 1.5.0
1819 **/
1820GPtrArray *
1821fu_common_filename_glob (const gchar *directory, const gchar *pattern, GError **error)
1822{
1823 const gchar *basename;
Richard Hughes6a489a92020-12-22 10:32:06 +00001824 g_autoptr(GDir) dir = NULL;
Richard Hughesa84d7a72020-05-06 12:11:51 +01001825 g_autoptr(GPtrArray) files = g_ptr_array_new_with_free_func (g_free);
Richard Hughes6a489a92020-12-22 10:32:06 +00001826
1827 g_return_val_if_fail (directory != NULL, NULL);
1828 g_return_val_if_fail (pattern != NULL, NULL);
1829 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1830
1831 dir = g_dir_open (directory, 0, error);
Richard Hughesa84d7a72020-05-06 12:11:51 +01001832 if (dir == NULL)
1833 return NULL;
1834 while ((basename = g_dir_read_name (dir)) != NULL) {
1835 if (!fu_common_fnmatch (pattern, basename))
1836 continue;
1837 g_ptr_array_add (files, g_build_filename (directory, basename, NULL));
1838 }
1839 if (files->len == 0) {
1840 g_set_error_literal (error,
1841 G_IO_ERROR,
1842 G_IO_ERROR_NOT_FOUND,
1843 "no files matched pattern");
1844 return NULL;
1845 }
1846 g_ptr_array_sort (files, fu_common_filename_glob_sort_cb);
1847 return g_steal_pointer (&files);
1848}
1849
Richard Hughes5c508de2019-11-22 09:57:34 +00001850/**
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001851 * fu_common_strnsplit:
1852 * @str: a string to split
1853 * @sz: size of @str
1854 * @delimiter: a string which specifies the places at which to split the string
1855 * @max_tokens: the maximum number of pieces to split @str into
1856 *
1857 * Splits a string into a maximum of @max_tokens pieces, using the given
1858 * delimiter. If @max_tokens is reached, the remainder of string is appended
1859 * to the last token.
1860 *
Richard Hughesa0d81c72019-11-27 11:41:54 +00001861 * Return value: (transfer full): a newly-allocated NULL-terminated array of strings
Mario Limonciello1a680f32019-11-25 19:44:53 -06001862 *
1863 * Since: 1.3.1
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001864 **/
1865gchar **
1866fu_common_strnsplit (const gchar *str, gsize sz,
1867 const gchar *delimiter, gint max_tokens)
1868{
1869 if (str[sz - 1] != '\0') {
1870 g_autofree gchar *str2 = g_strndup (str, sz);
1871 return g_strsplit (str2, delimiter, max_tokens);
1872 }
1873 return g_strsplit (str, delimiter, max_tokens);
1874}
Richard Hughes5308ea42019-08-09 12:25:13 +01001875
1876/**
Richard Hughes364e2682021-01-05 14:38:15 +00001877 * fu_common_strsafe:
1878 * @str: (nullable): a string to make safe for printing
1879 * @maxsz: maximum size of returned string
1880 *
1881 * Converts a string into something that can be safely printed.
1882 *
1883 * Return value: (transfer full): safe string, or %NULL if there was nothing valid
1884 *
1885 * Since: 1.5.5
1886 **/
1887gchar *
1888fu_common_strsafe (const gchar *str, gsize maxsz)
1889{
1890 gboolean valid = FALSE;
1891 g_autoptr(GString) tmp = NULL;
1892
Richard Hughes364e2682021-01-05 14:38:15 +00001893 /* sanity check */
Richard Hughesc123bee2021-02-08 16:47:05 +00001894 if (str == NULL || maxsz == 0)
Richard Hughes364e2682021-01-05 14:38:15 +00001895 return NULL;
1896
1897 /* replace non-printable chars with '.' */
Richard Hughesc123bee2021-02-08 16:47:05 +00001898 tmp = g_string_sized_new (maxsz);
Richard Hughesa4e0de42021-02-14 20:33:47 +00001899 for (gsize i = 0; i < maxsz && str[i] != '\0'; i++) {
Richard Hughes364e2682021-01-05 14:38:15 +00001900 if (!g_ascii_isprint (str[i])) {
1901 g_string_append_c (tmp, '.');
1902 continue;
1903 }
1904 g_string_append_c (tmp, str[i]);
Richard Hughesffbb1172021-02-14 20:34:31 +00001905 if (!g_ascii_isspace (str[i]))
1906 valid = TRUE;
Richard Hughes364e2682021-01-05 14:38:15 +00001907 }
1908
1909 /* if just junk, don't return 'all dots' */
1910 if (tmp->len == 0 || !valid)
1911 return NULL;
1912 return g_string_free (g_steal_pointer (&tmp), FALSE);
1913}
1914
Richard Hughese52e1b42021-01-26 09:59:15 +00001915
1916/**
1917 * fu_common_strjoin_array:
1918 * @separator: (nullable): string to insert between each of the strings, or %NULL
1919 * @array: (element-type utf8): A #GPtrArray
1920 *
1921 * Joins an array of strings together to form one long string, with the optional
1922 * separator inserted between each of them.
1923 *
1924 * If @array has no items, the return value will be an empty string.
1925 * If @array contains a single item, separator will not appear in the resulting
1926 * string.
1927 *
1928 * Returns: a string
1929 *
1930 * Since: 1.5.6
1931 **/
1932gchar *
1933fu_common_strjoin_array (const gchar *separator, GPtrArray *array)
1934{
1935 g_autofree const gchar **strv = NULL;
1936
1937 g_return_val_if_fail (array != NULL, NULL);
1938
1939 strv = g_new0 (const gchar *, array->len + 1);
1940 for (guint i = 0; i < array->len; i++)
1941 strv[i] = g_ptr_array_index (array, i);
1942 return g_strjoinv (separator, (gchar **) strv);
1943}
1944
Richard Hughes364e2682021-01-05 14:38:15 +00001945/**
Richard Hughes5308ea42019-08-09 12:25:13 +01001946 * fu_memcpy_safe:
1947 * @dst: destination buffer
1948 * @dst_sz: maximum size of @dst, typically `sizeof(dst)`
1949 * @dst_offset: offset in bytes into @dst to copy to
1950 * @src: source buffer
1951 * @src_sz: maximum size of @dst, typically `sizeof(src)`
1952 * @src_offset: offset in bytes into @src to copy from
1953 * @n: number of bytes to copy from @src+@offset from
1954 * @error: A #GError or %NULL
1955 *
1956 * Copies some memory using memcpy in a safe way. Providing the buffer sizes
1957 * of both the destination and the source allows us to check for buffer overflow.
1958 *
1959 * Providing the buffer offsets also allows us to check reading past the end of
1960 * the source buffer. For this reason the caller should NEVER add an offset to
1961 * @src or @dst.
1962 *
1963 * You don't need to use this function in "obviously correct" cases, nor should
1964 * you use it when performance is a concern. Only us it when you're not sure if
1965 * malicious data from a device or firmware could cause memory corruption.
1966 *
1967 * Return value: %TRUE if the bytes were copied, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06001968 *
1969 * Since: 1.3.1
Richard Hughes5308ea42019-08-09 12:25:13 +01001970 **/
1971gboolean
1972fu_memcpy_safe (guint8 *dst, gsize dst_sz, gsize dst_offset,
1973 const guint8 *src, gsize src_sz, gsize src_offset,
1974 gsize n, GError **error)
1975{
Richard Hughes6a489a92020-12-22 10:32:06 +00001976 g_return_val_if_fail (dst != NULL, FALSE);
1977 g_return_val_if_fail (src != NULL, FALSE);
1978 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1979
Richard Hughes5308ea42019-08-09 12:25:13 +01001980 if (n == 0)
1981 return TRUE;
1982
1983 if (n > src_sz) {
1984 g_set_error (error,
1985 FWUPD_ERROR,
1986 FWUPD_ERROR_READ,
1987 "attempted to read 0x%02x bytes from buffer of 0x%02x",
1988 (guint) n, (guint) src_sz);
1989 return FALSE;
1990 }
1991 if (n + src_offset > src_sz) {
1992 g_set_error (error,
1993 FWUPD_ERROR,
1994 FWUPD_ERROR_READ,
1995 "attempted to read 0x%02x bytes at offset 0x%02x from buffer of 0x%02x",
1996 (guint) n, (guint) src_offset, (guint) src_sz);
1997 return FALSE;
1998 }
1999 if (n > dst_sz) {
2000 g_set_error (error,
2001 FWUPD_ERROR,
2002 FWUPD_ERROR_WRITE,
2003 "attempted to write 0x%02x bytes to buffer of 0x%02x",
2004 (guint) n, (guint) dst_sz);
2005 return FALSE;
2006 }
2007 if (n + dst_offset > dst_sz) {
2008 g_set_error (error,
2009 FWUPD_ERROR,
2010 FWUPD_ERROR_WRITE,
2011 "attempted to write 0x%02x bytes at offset 0x%02x to buffer of 0x%02x",
2012 (guint) n, (guint) dst_offset, (guint) dst_sz);
2013 return FALSE;
2014 }
2015
2016 /* phew! */
2017 memcpy (dst + dst_offset, src + src_offset, n);
2018 return TRUE;
2019}
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002020
Richard Hughes80768f52019-10-22 07:19:14 +01002021/**
Richard Hughes9b11af92021-02-04 20:28:49 +00002022 * fu_memdup_safe:
2023 * @src: source buffer
2024 * @n: number of bytes to copy from @src
2025 * @error: A #GError or %NULL
2026 *
2027 * Duplicates some memory using memdup in a safe way.
2028 *
2029 * You don't need to use this function in "obviously correct" cases, nor should
2030 * you use it when performance is a concern. Only us it when you're not sure if
2031 * malicious data from a device or firmware could cause memory corruption.
2032 *
2033 * NOTE: This function intentionally limits allocation size to 1GB.
2034 *
2035 * Return value: (transfer full): block of allocated memory, or %NULL for an error.
2036 *
2037 * Since: 1.5.6
2038 **/
2039guint8 *
2040fu_memdup_safe (const guint8 *src, gsize n, GError **error)
2041{
Richard Hughes9b11af92021-02-04 20:28:49 +00002042 /* sanity check */
2043 if (n > 0x40000000) {
2044 g_set_error (error,
2045 G_IO_ERROR,
2046 G_IO_ERROR_NOT_SUPPORTED,
2047 "cannot allocate %uGB of memory",
2048 (guint) (n / 0x40000000));
2049 return NULL;
2050 }
2051
Richard Hughes5294d0c2021-02-05 09:50:02 +00002052#if GLIB_CHECK_VERSION(2,67,3)
Richard Hughes9b11af92021-02-04 20:28:49 +00002053 /* linear block of memory */
Richard Hughes5294d0c2021-02-05 09:50:02 +00002054 return g_memdup2 (src, n);
2055#else
2056 return g_memdup (src, (guint) n);
2057#endif
Richard Hughes9b11af92021-02-04 20:28:49 +00002058}
2059
2060/**
Richard Hughesc21a0b92019-10-24 12:24:37 +01002061 * fu_common_read_uint8_safe:
2062 * @buf: source buffer
2063 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2064 * @offset: offset in bytes into @buf to copy from
2065 * @value: (out) (allow-none): the parsed value
2066 * @error: A #GError or %NULL
2067 *
2068 * Read a value from a buffer in a safe way.
2069 *
2070 * You don't need to use this function in "obviously correct" cases, nor should
2071 * you use it when performance is a concern. Only us it when you're not sure if
2072 * malicious data from a device or firmware could cause memory corruption.
2073 *
2074 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002075 *
2076 * Since: 1.3.3
Richard Hughesc21a0b92019-10-24 12:24:37 +01002077 **/
2078gboolean
2079fu_common_read_uint8_safe (const guint8 *buf,
2080 gsize bufsz,
2081 gsize offset,
2082 guint8 *value,
2083 GError **error)
2084{
2085 guint8 tmp;
Richard Hughes6a489a92020-12-22 10:32:06 +00002086
2087 g_return_val_if_fail (buf != NULL, FALSE);
2088 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2089
Richard Hughesc21a0b92019-10-24 12:24:37 +01002090 if (!fu_memcpy_safe (&tmp, sizeof(tmp), 0x0, /* dst */
2091 buf, bufsz, offset, /* src */
2092 sizeof(tmp), error))
2093 return FALSE;
2094 if (value != NULL)
2095 *value = tmp;
2096 return TRUE;
2097}
2098
2099/**
Richard Hughes80768f52019-10-22 07:19:14 +01002100 * fu_common_read_uint16_safe:
2101 * @buf: source buffer
2102 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2103 * @offset: offset in bytes into @buf to copy from
2104 * @value: (out) (allow-none): the parsed value
2105 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2106 * @error: A #GError or %NULL
2107 *
2108 * Read a value from a buffer using a specified endian in a safe way.
2109 *
2110 * You don't need to use this function in "obviously correct" cases, nor should
2111 * you use it when performance is a concern. Only us it when you're not sure if
2112 * malicious data from a device or firmware could cause memory corruption.
2113 *
2114 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002115 *
2116 * Since: 1.3.3
Richard Hughes80768f52019-10-22 07:19:14 +01002117 **/
2118gboolean
2119fu_common_read_uint16_safe (const guint8 *buf,
2120 gsize bufsz,
2121 gsize offset,
2122 guint16 *value,
2123 FuEndianType endian,
2124 GError **error)
2125{
2126 guint8 dst[2] = { 0x0 };
Richard Hughes6a489a92020-12-22 10:32:06 +00002127
2128 g_return_val_if_fail (buf != NULL, FALSE);
2129 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2130
Richard Hughes7d01ac92019-10-23 14:31:46 +01002131 if (!fu_memcpy_safe (dst, sizeof(dst), 0x0, /* dst */
Richard Hughes80768f52019-10-22 07:19:14 +01002132 buf, bufsz, offset, /* src */
Richard Hughes7d01ac92019-10-23 14:31:46 +01002133 sizeof(dst), error))
Richard Hughes80768f52019-10-22 07:19:14 +01002134 return FALSE;
2135 if (value != NULL)
2136 *value = fu_common_read_uint16 (dst, endian);
2137 return TRUE;
2138}
2139
2140/**
2141 * fu_common_read_uint32_safe:
2142 * @buf: source buffer
2143 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2144 * @offset: offset in bytes into @buf to copy from
2145 * @value: (out) (allow-none): the parsed value
2146 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2147 * @error: A #GError or %NULL
2148 *
2149 * Read a value from a buffer using a specified endian in a safe way.
2150 *
2151 * You don't need to use this function in "obviously correct" cases, nor should
2152 * you use it when performance is a concern. Only us it when you're not sure if
2153 * malicious data from a device or firmware could cause memory corruption.
2154 *
2155 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002156 *
2157 * Since: 1.3.3
Richard Hughes80768f52019-10-22 07:19:14 +01002158 **/
2159gboolean
2160fu_common_read_uint32_safe (const guint8 *buf,
2161 gsize bufsz,
2162 gsize offset,
2163 guint32 *value,
2164 FuEndianType endian,
2165 GError **error)
2166{
2167 guint8 dst[4] = { 0x0 };
Richard Hughes6a489a92020-12-22 10:32:06 +00002168
2169 g_return_val_if_fail (buf != NULL, FALSE);
2170 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2171
Richard Hughes7d01ac92019-10-23 14:31:46 +01002172 if (!fu_memcpy_safe (dst, sizeof(dst), 0x0, /* dst */
Richard Hughes80768f52019-10-22 07:19:14 +01002173 buf, bufsz, offset, /* src */
Richard Hughes7d01ac92019-10-23 14:31:46 +01002174 sizeof(dst), error))
Richard Hughes80768f52019-10-22 07:19:14 +01002175 return FALSE;
2176 if (value != NULL)
2177 *value = fu_common_read_uint32 (dst, endian);
2178 return TRUE;
2179}
2180
Mario Limonciello1a680f32019-11-25 19:44:53 -06002181/**
2182 * fu_byte_array_append_uint8:
2183 * @array: A #GByteArray
2184 * @data: #guint8
2185 *
2186 * Adds a 8 bit integer to a byte array
2187 *
2188 * Since: 1.3.1
2189 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002190void
2191fu_byte_array_append_uint8 (GByteArray *array, guint8 data)
2192{
2193 g_byte_array_append (array, &data, sizeof(data));
2194}
2195
Mario Limonciello1a680f32019-11-25 19:44:53 -06002196/**
2197 * fu_byte_array_append_uint16:
2198 * @array: A #GByteArray
2199 * @data: #guint16
2200 * @endian: #FuEndianType
2201 *
2202 * Adds a 16 bit integer to a byte array
2203 *
2204 * Since: 1.3.1
2205 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002206void
2207fu_byte_array_append_uint16 (GByteArray *array, guint16 data, FuEndianType endian)
2208{
2209 guint8 buf[2];
2210 fu_common_write_uint16 (buf, data, endian);
2211 g_byte_array_append (array, buf, sizeof(buf));
2212}
2213
Mario Limonciello1a680f32019-11-25 19:44:53 -06002214/**
2215 * fu_byte_array_append_uint32:
2216 * @array: A #GByteArray
2217 * @data: #guint32
2218 * @endian: #FuEndianType
2219 *
2220 * Adds a 32 bit integer to a byte array
2221 *
2222 * Since: 1.3.1
2223 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002224void
2225fu_byte_array_append_uint32 (GByteArray *array, guint32 data, FuEndianType endian)
2226{
2227 guint8 buf[4];
2228 fu_common_write_uint32 (buf, data, endian);
2229 g_byte_array_append (array, buf, sizeof(buf));
2230}
Mario Limonciello9dce1f72020-02-04 09:12:52 -06002231
2232/**
Richard Hughesa2a8f8e2020-10-20 09:27:26 +01002233 * fu_byte_array_set_size:
2234 * @array: a #GByteArray
2235 * @length: the new size of the GByteArray
2236 *
2237 * Sets the size of the GByteArray, expanding it with NULs if necessary.
2238 *
2239 * Since: 1.5.0
2240 **/
2241void
2242fu_byte_array_set_size (GByteArray *array, guint length)
2243{
2244 guint oldlength = array->len;
2245 g_byte_array_set_size (array, length);
2246 if (length > oldlength)
2247 memset (array->data + oldlength, 0x0, length - oldlength);
2248}
2249
2250/**
Mario Limonciello9dce1f72020-02-04 09:12:52 -06002251 * fu_common_kernel_locked_down:
2252 *
2253 * Determines if kernel lockdown in effect
2254 *
2255 * Since: 1.3.8
2256 **/
2257gboolean
2258fu_common_kernel_locked_down (void)
2259{
2260#ifndef _WIN32
2261 gsize len = 0;
2262 g_autofree gchar *dir = fu_common_get_path (FU_PATH_KIND_SYSFSDIR_SECURITY);
2263 g_autofree gchar *fname = g_build_filename (dir, "lockdown", NULL);
2264 g_autofree gchar *data = NULL;
2265 g_auto(GStrv) options = NULL;
2266
2267 if (!g_file_test (fname, G_FILE_TEST_EXISTS))
2268 return FALSE;
2269 if (!g_file_get_contents (fname, &data, &len, NULL))
2270 return FALSE;
2271 if (len < 1)
2272 return FALSE;
2273 options = g_strsplit (data, " ", -1);
2274 for (guint i = 0; options[i] != NULL; i++) {
2275 if (g_strcmp0 (options[i], "[none]") == 0)
2276 return FALSE;
2277 }
2278 return TRUE;
2279#else
2280 return FALSE;
2281#endif
2282}
Richard Hughes9223c892020-05-09 20:32:08 +01002283
2284/**
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002285 * fu_common_cpuid:
2286 * @leaf: The CPUID level, now called the 'leaf' by Intel
2287 * @eax: (out) (nullable): EAX register
2288 * @ebx: (out) (nullable): EBX register
2289 * @ecx: (out) (nullable): ECX register
2290 * @edx: (out) (nullable): EDX register
2291 * @error: A #GError or NULL
2292 *
2293 * Calls CPUID and returns the registers for the given leaf.
2294 *
2295 * Return value: %TRUE if the registers are set.
2296 *
2297 * Since: 1.5.0
2298 **/
2299gboolean
2300fu_common_cpuid (guint32 leaf,
2301 guint32 *eax,
2302 guint32 *ebx,
2303 guint32 *ecx,
2304 guint32 *edx,
2305 GError **error)
2306{
2307#ifdef HAVE_CPUID_H
2308 guint eax_tmp = 0;
2309 guint ebx_tmp = 0;
2310 guint ecx_tmp = 0;
2311 guint edx_tmp = 0;
2312
Richard Hughes6a489a92020-12-22 10:32:06 +00002313 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2314
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002315 /* get vendor */
Richard Hughes7c4a64b2020-08-23 21:20:58 +01002316 __get_cpuid_count (leaf, 0x0, &eax_tmp, &ebx_tmp, &ecx_tmp, &edx_tmp);
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002317 if (eax != NULL)
2318 *eax = eax_tmp;
2319 if (ebx != NULL)
2320 *ebx = ebx_tmp;
2321 if (ecx != NULL)
2322 *ecx = ecx_tmp;
2323 if (edx != NULL)
2324 *edx = edx_tmp;
2325 return TRUE;
2326#else
2327 g_set_error_literal (error,
2328 G_IO_ERROR,
2329 G_IO_ERROR_NOT_SUPPORTED,
2330 "no <cpuid.h> support");
2331 return FALSE;
2332#endif
2333}
2334
2335/**
Richard Hughes9223c892020-05-09 20:32:08 +01002336 * fu_common_is_cpu_intel:
2337 *
2338 * Uses CPUID to discover the CPU vendor and check if it is Intel.
2339 *
2340 * Return value: %TRUE if the vendor was Intel.
Richard Hughesb63cfa92021-01-05 22:57:12 +00002341 * Deprecated: 1.5.5: Use fu_common_get_cpu_vendor() instead.
Richard Hughes9223c892020-05-09 20:32:08 +01002342 *
2343 * Since: 1.5.0
2344 **/
2345gboolean
2346fu_common_is_cpu_intel (void)
2347{
Richard Hughesb63cfa92021-01-05 22:57:12 +00002348 return fu_common_get_cpu_vendor () == FU_CPU_VENDOR_INTEL;
2349}
2350
2351/**
2352 * fu_common_get_cpu_vendor:
2353 *
2354 * Uses CPUID to discover the CPU vendor.
2355 *
2356 * Return value: a #FuCpuVendor, e.g. %FU_CPU_VENDOR_AMD if the vendor was AMD.
2357 *
2358 * Since: 1.5.5
2359 **/
2360FuCpuVendor
2361fu_common_get_cpu_vendor (void)
2362{
2363#ifdef HAVE_CPUID_H
Richard Hughes9223c892020-05-09 20:32:08 +01002364 guint ebx = 0;
2365 guint ecx = 0;
2366 guint edx = 0;
Richard Hughes9223c892020-05-09 20:32:08 +01002367
Richard Hughesb63cfa92021-01-05 22:57:12 +00002368 if (fu_common_cpuid (0x0, NULL, &ebx, &ecx, &edx, NULL)) {
2369 if (ebx == signature_INTEL_ebx &&
2370 edx == signature_INTEL_edx &&
2371 ecx == signature_INTEL_ecx) {
2372 return FU_CPU_VENDOR_INTEL;
2373 }
2374 if (ebx == signature_AMD_ebx &&
2375 edx == signature_AMD_edx &&
2376 ecx == signature_AMD_ecx) {
2377 return FU_CPU_VENDOR_AMD;
2378 }
Richard Hughes9223c892020-05-09 20:32:08 +01002379 }
Richard Hughesbd444322020-05-21 12:05:03 +01002380#endif
Richard Hughesb63cfa92021-01-05 22:57:12 +00002381
2382 /* failed */
2383 return FU_CPU_VENDOR_UNKNOWN;
Richard Hughes9223c892020-05-09 20:32:08 +01002384}
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002385
Richard Hughes36111472020-08-12 15:04:24 +01002386/**
2387 * fu_common_is_live_media:
2388 *
2389 * Checks if the user is running from a live media using various heuristics.
2390 *
2391 * Returns: %TRUE if live
2392 *
2393 * Since: 1.4.6
2394 **/
2395gboolean
2396fu_common_is_live_media (void)
2397{
2398 gsize bufsz = 0;
2399 g_autofree gchar *buf = NULL;
2400 g_auto(GStrv) tokens = NULL;
2401 const gchar *args[] = {
2402 "rd.live.image",
2403 "boot=live",
2404 NULL, /* last entry */
2405 };
2406 if (g_file_test ("/cdrom/.disk/info", G_FILE_TEST_EXISTS))
2407 return TRUE;
2408 if (!g_file_get_contents ("/proc/cmdline", &buf, &bufsz, NULL))
2409 return FALSE;
2410 if (bufsz == 0)
2411 return FALSE;
2412 tokens = fu_common_strnsplit (buf, bufsz - 1, " ", -1);
2413 for (guint i = 0; args[i] != NULL; i++) {
2414 if (g_strv_contains ((const gchar * const *) tokens, args[i]))
2415 return TRUE;
2416 }
2417 return FALSE;
2418}
2419
Richard Hughes68175e92021-01-14 09:43:33 +00002420/**
2421 * fu_common_get_memory_size:
2422 *
2423 * Returns the size of physical memory.
2424 *
2425 * Returns: bytes
2426 *
2427 * Since: 1.5.6
2428 **/
2429guint64
2430fu_common_get_memory_size (void)
2431{
2432#ifdef _WIN32
2433 MEMORYSTATUSEX status;
2434 status.dwLength = sizeof(status);
2435 GlobalMemoryStatusEx (&status);
2436 return (guint64) status.ullTotalPhys;
2437#else
2438 return sysconf (_SC_PHYS_PAGES) * sysconf (_SC_PAGE_SIZE);
2439#endif
2440}
2441
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002442static GPtrArray *
Richard Hughes43417b22020-10-30 14:46:16 +00002443fu_common_get_block_devices (GError **error)
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002444{
2445 GVariantBuilder builder;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002446 const gchar *obj;
2447 g_autoptr(GVariant) output = NULL;
2448 g_autoptr(GDBusProxy) proxy = NULL;
2449 g_autoptr(GPtrArray) devices = NULL;
2450 g_autoptr(GVariantIter) iter = NULL;
Richard Hughes43417b22020-10-30 14:46:16 +00002451 g_autoptr(GDBusConnection) connection = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002452
Richard Hughes43417b22020-10-30 14:46:16 +00002453 connection = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, error);
2454 if (connection == NULL) {
2455 g_prefix_error (error, "failed to get system bus: ");
2456 return NULL;
2457 }
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002458 proxy = g_dbus_proxy_new_sync (connection,
2459 G_DBUS_PROXY_FLAGS_NONE, NULL,
2460 UDISKS_DBUS_SERVICE,
2461 UDISKS_DBUS_PATH,
2462 UDISKS_DBUS_MANAGER_INTERFACE,
2463 NULL, error);
2464 if (proxy == NULL) {
2465 g_prefix_error (error, "failed to find %s: ", UDISKS_DBUS_SERVICE);
2466 return NULL;
2467 }
2468 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002469 output = g_dbus_proxy_call_sync (proxy,
Richard Hughesdb344d52020-09-09 19:42:27 +01002470 "GetBlockDevices",
2471 g_variant_new ("(a{sv})", &builder),
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002472 G_DBUS_CALL_FLAGS_NONE,
2473 -1, NULL, error);
Richard Hughes0bdf5612020-10-30 14:56:22 +00002474 if (output == NULL) {
2475 if (error != NULL)
2476 g_dbus_error_strip_remote_error (*error);
2477 g_prefix_error (error, "failed to call %s.%s(): ",
2478 UDISKS_DBUS_SERVICE,
2479 "GetBlockDevices");
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002480 return NULL;
Richard Hughes0bdf5612020-10-30 14:56:22 +00002481 }
Richard Hughes43417b22020-10-30 14:46:16 +00002482 devices = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002483 g_variant_get (output, "(ao)", &iter);
Richard Hughes43417b22020-10-30 14:46:16 +00002484 while (g_variant_iter_next (iter, "&o", &obj)) {
2485 g_autoptr(GDBusProxy) proxy_blk = NULL;
2486 proxy_blk = g_dbus_proxy_new_sync (connection,
2487 G_DBUS_PROXY_FLAGS_NONE, NULL,
2488 UDISKS_DBUS_SERVICE,
2489 obj,
2490 UDISKS_DBUS_INTERFACE_BLOCK,
2491 NULL, error);
2492 if (proxy_blk == NULL) {
2493 g_prefix_error (error, "failed to initialize d-bus proxy for %s: ", obj);
2494 return NULL;
2495 }
2496 g_ptr_array_add (devices, g_steal_pointer (&proxy_blk));
2497 }
2498
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002499
2500 return g_steal_pointer (&devices);
2501}
2502
Richard Hughesad3cfc02021-02-22 10:02:54 +00002503static const gchar *
2504fu_common_convert_to_gpt_type (const gchar *type)
2505{
2506 struct {
2507 const gchar *mbr;
2508 const gchar *gpt;
2509 } typeguids[] = {
2510 { "0xef", "c12a7328-f81f-11d2-ba4b-00a0c93ec93b" }, /* esp */
2511 { "0x0b", "ebd0a0a2-b9e5-4433-87c0-68b6b72699c7" }, /* fat32 */
2512 { NULL, NULL }
2513 };
2514 for (guint i = 0; typeguids[i].mbr != NULL; i++) {
2515 if (g_strcmp0 (type, typeguids[i].mbr) == 0)
2516 return typeguids[i].gpt;
2517 }
2518 return type;
2519}
2520
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002521/**
2522 * fu_common_get_volumes_by_kind:
2523 * @kind: A volume kind, typically a GUID
2524 * @error: A #GError or NULL
2525 *
Richard Hughesc57a8f52020-10-30 14:42:42 +00002526 * Finds all volumes of a specific partition type
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002527 *
2528 * Returns: (transfer container) (element-type FuVolume): a #GPtrArray, or %NULL if the kind was not found
2529 *
2530 * Since: 1.4.6
2531 **/
2532GPtrArray *
2533fu_common_get_volumes_by_kind (const gchar *kind, GError **error)
2534{
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002535 g_autoptr(GPtrArray) devices = NULL;
2536 g_autoptr(GPtrArray) volumes = NULL;
2537
Richard Hughes6a489a92020-12-22 10:32:06 +00002538 g_return_val_if_fail (kind != NULL, NULL);
2539 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2540
Richard Hughes43417b22020-10-30 14:46:16 +00002541 devices = fu_common_get_block_devices (error);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002542 if (devices == NULL)
Richard Hughesb81140d2020-08-17 14:47:17 +01002543 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002544 volumes = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
2545 for (guint i = 0; i < devices->len; i++) {
Richard Hughes43417b22020-10-30 14:46:16 +00002546 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002547 const gchar *type_str;
Mario Limonciello56d816a2020-11-11 16:59:30 -06002548 g_autoptr(FuVolume) vol = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002549 g_autoptr(GDBusProxy) proxy_part = NULL;
Richard Hughes43417b22020-10-30 14:46:16 +00002550 g_autoptr(GDBusProxy) proxy_fs = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002551 g_autoptr(GVariant) val = NULL;
2552
Richard Hughes43417b22020-10-30 14:46:16 +00002553 proxy_part = g_dbus_proxy_new_sync (g_dbus_proxy_get_connection (proxy_blk),
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002554 G_DBUS_PROXY_FLAGS_NONE, NULL,
2555 UDISKS_DBUS_SERVICE,
Richard Hughes43417b22020-10-30 14:46:16 +00002556 g_dbus_proxy_get_object_path (proxy_blk),
2557 UDISKS_DBUS_INTERFACE_PARTITION,
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002558 NULL, error);
2559 if (proxy_part == NULL) {
Richard Hughes43417b22020-10-30 14:46:16 +00002560 g_prefix_error (error, "failed to initialize d-bus proxy %s: ",
2561 g_dbus_proxy_get_object_path (proxy_blk));
Richard Hughesb81140d2020-08-17 14:47:17 +01002562 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002563 }
2564 val = g_dbus_proxy_get_cached_property (proxy_part, "Type");
2565 if (val == NULL)
2566 continue;
2567
Richard Hughesdb344d52020-09-09 19:42:27 +01002568 g_variant_get (val, "&s", &type_str);
Richard Hughes43417b22020-10-30 14:46:16 +00002569 proxy_fs = g_dbus_proxy_new_sync (g_dbus_proxy_get_connection (proxy_blk),
2570 G_DBUS_PROXY_FLAGS_NONE, NULL,
2571 UDISKS_DBUS_SERVICE,
2572 g_dbus_proxy_get_object_path (proxy_blk),
2573 UDISKS_DBUS_INTERFACE_FILESYSTEM,
2574 NULL, error);
2575 if (proxy_fs == NULL) {
2576 g_prefix_error (error, "failed to initialize d-bus proxy %s: ",
2577 g_dbus_proxy_get_object_path (proxy_blk));
Richard Hughesb81140d2020-08-17 14:47:17 +01002578 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002579 }
Mario Limonciello56d816a2020-11-11 16:59:30 -06002580 vol = g_object_new (FU_TYPE_VOLUME,
2581 "proxy-block", proxy_blk,
2582 "proxy-filesystem", proxy_fs,
2583 NULL);
Richard Hughesad3cfc02021-02-22 10:02:54 +00002584
2585 /* convert MBR type to GPT type */
2586 type_str = fu_common_convert_to_gpt_type (type_str);
Mario Limonciello56d816a2020-11-11 16:59:30 -06002587 g_debug ("device %s, type: %s, internal: %d, fs: %s",
2588 g_dbus_proxy_get_object_path (proxy_blk), type_str,
2589 fu_volume_is_internal (vol),
2590 fu_volume_get_id_type (vol));
2591 if (g_strcmp0 (type_str, kind) != 0)
2592 continue;
2593 g_ptr_array_add (volumes, g_steal_pointer (&vol));
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002594 }
2595 if (volumes->len == 0) {
2596 g_set_error (error,
2597 G_IO_ERROR,
2598 G_IO_ERROR_NOT_FOUND,
2599 "no volumes of type %s", kind);
2600 return NULL;
2601 }
2602 return g_steal_pointer (&volumes);
2603}
2604
2605/**
Richard Hughes0bdf5612020-10-30 14:56:22 +00002606 * fu_common_get_volume_by_device:
2607 * @device: A device string, typcically starting with `/dev/`
2608 * @error: A #GError or NULL
2609 *
2610 * Finds the first volume from the specified device.
2611 *
2612 * Returns: (transfer full): a #GPtrArray, or %NULL if the kind was not found
2613 *
2614 * Since: 1.5.1
2615 **/
2616FuVolume *
2617fu_common_get_volume_by_device (const gchar *device, GError **error)
2618{
2619 g_autoptr(GPtrArray) devices = NULL;
2620
Richard Hughes6a489a92020-12-22 10:32:06 +00002621 g_return_val_if_fail (device != NULL, NULL);
2622 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2623
Richard Hughes0bdf5612020-10-30 14:56:22 +00002624 /* find matching block device */
2625 devices = fu_common_get_block_devices (error);
2626 if (devices == NULL)
2627 return NULL;
2628 for (guint i = 0; i < devices->len; i++) {
2629 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
2630 g_autoptr(GVariant) val = NULL;
2631 val = g_dbus_proxy_get_cached_property (proxy_blk, "Device");
2632 if (val == NULL)
2633 continue;
2634 if (g_strcmp0 (g_variant_get_bytestring (val), device) == 0) {
2635 return g_object_new (FU_TYPE_VOLUME,
2636 "proxy-block", proxy_blk,
2637 NULL);
2638 }
2639 }
2640
2641 /* failed */
2642 g_set_error (error,
2643 G_IO_ERROR,
2644 G_IO_ERROR_NOT_FOUND,
2645 "no volumes for device %s",
2646 device);
2647 return NULL;
2648}
2649
2650/**
2651 * fu_common_get_volume_by_devnum:
Richard Hughese0f92072020-11-06 09:50:29 +00002652 * @devnum: A device number
Richard Hughes0bdf5612020-10-30 14:56:22 +00002653 * @error: A #GError or NULL
2654 *
2655 * Finds the first volume from the specified device.
2656 *
2657 * Returns: (transfer full): a #GPtrArray, or %NULL if the kind was not found
2658 *
2659 * Since: 1.5.1
2660 **/
2661FuVolume *
2662fu_common_get_volume_by_devnum (guint32 devnum, GError **error)
2663{
2664 g_autoptr(GPtrArray) devices = NULL;
2665
Richard Hughes6a489a92020-12-22 10:32:06 +00002666 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2667
Richard Hughes0bdf5612020-10-30 14:56:22 +00002668 /* find matching block device */
2669 devices = fu_common_get_block_devices (error);
2670 if (devices == NULL)
2671 return NULL;
2672 for (guint i = 0; i < devices->len; i++) {
2673 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
2674 g_autoptr(GVariant) val = NULL;
2675 val = g_dbus_proxy_get_cached_property (proxy_blk, "DeviceNumber");
2676 if (val == NULL)
2677 continue;
2678 if (devnum == g_variant_get_uint64 (val)) {
2679 return g_object_new (FU_TYPE_VOLUME,
2680 "proxy-block", proxy_blk,
2681 NULL);
2682 }
2683 }
2684
2685 /* failed */
2686 g_set_error (error,
2687 G_IO_ERROR,
2688 G_IO_ERROR_NOT_FOUND,
2689 "no volumes for devnum %u",
2690 devnum);
2691 return NULL;
2692}
2693
2694/**
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002695 * fu_common_get_esp_default:
2696 * @error: A #GError or NULL
2697 *
2698 * Gets the platform default ESP
2699 *
2700 * Returns: (transfer full): a #FuVolume, or %NULL if the ESP was not found
2701 *
2702 * Since: 1.4.6
2703 **/
2704FuVolume *
2705fu_common_get_esp_default (GError **error)
2706{
2707 const gchar *path_tmp;
Richard Hughes9d20bf92020-12-14 09:36:46 +00002708 gboolean has_internal = FALSE;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002709 g_autoptr(GPtrArray) volumes_fstab = g_ptr_array_new ();
2710 g_autoptr(GPtrArray) volumes_mtab = g_ptr_array_new ();
Mario Limonciello56d816a2020-11-11 16:59:30 -06002711 g_autoptr(GPtrArray) volumes_vfat = g_ptr_array_new ();
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002712 g_autoptr(GPtrArray) volumes = NULL;
Mario Limonciello56d816a2020-11-11 16:59:30 -06002713 g_autoptr(GError) error_local = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002714
Richard Hughes6a489a92020-12-22 10:32:06 +00002715 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2716
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002717 /* for the test suite use local directory for ESP */
2718 path_tmp = g_getenv ("FWUPD_UEFI_ESP_PATH");
2719 if (path_tmp != NULL)
2720 return fu_volume_new_from_mount_path (path_tmp);
2721
Mario Limonciello56d816a2020-11-11 16:59:30 -06002722 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_ESP, &error_local);
2723 if (volumes == NULL) {
2724 g_debug ("%s, falling back to %s", error_local->message, FU_VOLUME_KIND_BDP);
2725 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_BDP, error);
2726 if (volumes == NULL) {
2727 g_prefix_error (error, "%s: ", error_local->message);
2728 return NULL;
2729 }
2730 }
Richard Hughes9d20bf92020-12-14 09:36:46 +00002731
2732 /* are there _any_ internal vfat partitions?
2733 * remember HintSystem is just that -- a hint! */
2734 for (guint i = 0; i < volumes->len; i++) {
2735 FuVolume *vol = g_ptr_array_index (volumes, i);
2736 g_autofree gchar *type = fu_volume_get_id_type (vol);
2737 if (g_strcmp0 (type, "vfat") == 0 &&
2738 fu_volume_is_internal (vol)) {
2739 has_internal = TRUE;
2740 break;
2741 }
2742 }
2743
2744 /* filter to vfat partitions */
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002745 for (guint i = 0; i < volumes->len; i++) {
2746 FuVolume *vol = g_ptr_array_index (volumes, i);
Mario Limonciello56d816a2020-11-11 16:59:30 -06002747 g_autofree gchar *type = fu_volume_get_id_type (vol);
2748 if (type == NULL)
2749 continue;
Richard Hughes9d20bf92020-12-14 09:36:46 +00002750 if (has_internal && !fu_volume_is_internal (vol))
Mario Limonciello56d816a2020-11-11 16:59:30 -06002751 continue;
2752 if (g_strcmp0 (type, "vfat") == 0)
2753 g_ptr_array_add (volumes_vfat, vol);
2754 }
2755 if (volumes_vfat->len == 0) {
2756 g_set_error (error,
2757 G_IO_ERROR,
2758 G_IO_ERROR_INVALID_FILENAME,
2759 "No ESP found");
2760 return NULL;
2761 }
2762 for (guint i = 0; i < volumes_vfat->len; i++) {
2763 FuVolume *vol = g_ptr_array_index (volumes_vfat, i);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002764 g_ptr_array_add (fu_volume_is_mounted (vol) ? volumes_mtab : volumes_fstab, vol);
2765 }
2766 if (volumes_mtab->len == 1) {
2767 FuVolume *vol = g_ptr_array_index (volumes_mtab, 0);
2768 return g_object_ref (vol);
2769 }
2770 if (volumes_mtab->len == 0 && volumes_fstab->len == 1) {
2771 FuVolume *vol = g_ptr_array_index (volumes_fstab, 0);
2772 return g_object_ref (vol);
2773 }
2774 g_set_error (error,
2775 G_IO_ERROR,
2776 G_IO_ERROR_INVALID_FILENAME,
2777 "More than one available ESP");
2778 return NULL;
2779}
2780
2781/**
2782 * fu_common_get_esp_for_path:
2783 * @esp_path: A path to the ESP
2784 * @error: A #GError or NULL
2785 *
2786 * Gets the platform ESP using a UNIX or UDisks path
2787 *
2788 * Returns: (transfer full): a #FuVolume, or %NULL if the ESP was not found
2789 *
2790 * Since: 1.4.6
2791 **/
2792FuVolume *
2793fu_common_get_esp_for_path (const gchar *esp_path, GError **error)
2794{
Richard Hughes6a489a92020-12-22 10:32:06 +00002795 g_autofree gchar *basename = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002796 g_autoptr(GPtrArray) volumes = NULL;
Mario Limonciellobe220a42021-02-10 10:39:58 -06002797 g_autoptr(GError) error_local = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002798
Richard Hughes6a489a92020-12-22 10:32:06 +00002799 g_return_val_if_fail (esp_path != NULL, NULL);
2800 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2801
Mario Limonciellobe220a42021-02-10 10:39:58 -06002802 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_ESP, &error_local);
2803 if (volumes == NULL) {
2804 /* check if it's a valid directory already */
2805 if (g_file_test (esp_path, G_FILE_TEST_IS_DIR))
2806 return fu_volume_new_from_mount_path (esp_path);
2807 g_propagate_error (error, g_steal_pointer (&error_local));
Richard Hughesb81140d2020-08-17 14:47:17 +01002808 return NULL;
Mario Limonciellobe220a42021-02-10 10:39:58 -06002809 }
Richard Hughes6a489a92020-12-22 10:32:06 +00002810 basename = g_path_get_basename (esp_path);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002811 for (guint i = 0; i < volumes->len; i++) {
2812 FuVolume *vol = g_ptr_array_index (volumes, i);
Mario Limonciello5a835632020-10-07 14:22:08 -05002813 g_autofree gchar *vol_basename = g_path_get_basename (fu_volume_get_mount_point (vol));
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002814 if (g_strcmp0 (basename, vol_basename) == 0)
2815 return g_object_ref (vol);
2816 }
2817 g_set_error (error,
2818 G_IO_ERROR,
2819 G_IO_ERROR_INVALID_FILENAME,
2820 "No ESP with path %s",
2821 esp_path);
2822 return NULL;
2823}
Richard Hughes6f5e35a2020-09-25 14:14:52 +01002824
2825/**
Richard Hughes44ae2a72020-09-25 18:00:21 +01002826 * fu_common_crc8:
2827 * @buf: memory buffer
2828 * @bufsz: sizeof buf
2829 *
2830 * Returns the cyclic redundancy check value for the given memory buffer.
2831 *
2832 * Returns: CRC value
2833 *
2834 * Since: 1.5.0
2835 **/
2836guint8
2837fu_common_crc8 (const guint8 *buf, gsize bufsz)
2838{
2839 guint32 crc = 0;
2840 for (gsize j = bufsz; j > 0; j--) {
2841 crc ^= (*(buf++) << 8);
2842 for (guint32 i = 8; i; i--) {
2843 if (crc & 0x8000)
2844 crc ^= (0x1070 << 3);
2845 crc <<= 1;
2846 }
2847 }
2848 return ~((guint8) (crc >> 8));
2849}
2850
2851/**
Richard Hughes6f5e35a2020-09-25 14:14:52 +01002852 * fu_common_crc16:
2853 * @buf: memory buffer
2854 * @bufsz: sizeof buf
2855 *
2856 * Returns the cyclic redundancy check value for the given memory buffer.
2857 *
2858 * Returns: CRC value
2859 *
2860 * Since: 1.5.0
2861 **/
2862guint16
2863fu_common_crc16 (const guint8 *buf, gsize bufsz)
2864{
2865 guint16 crc = 0xffff;
2866 for (gsize len = bufsz; len > 0; len--) {
2867 crc = (guint16) (crc ^ (*buf++));
2868 for (guint8 i = 0; i < 8; i++) {
2869 if (crc & 0x1) {
2870 crc = (crc >> 1) ^ 0xa001;
2871 } else {
2872 crc >>= 1;
2873 }
2874 }
2875 }
2876 return ~crc;
2877}
2878
2879/**
2880 * fu_common_crc32_full:
2881 * @buf: memory buffer
2882 * @bufsz: sizeof buf
2883 * @crc: initial CRC value, typically 0xFFFFFFFF
2884 * @polynomial: CRC polynomial, typically 0xEDB88320
2885 *
2886 * Returns the cyclic redundancy check value for the given memory buffer.
2887 *
2888 * Returns: CRC value
2889 *
2890 * Since: 1.5.0
2891 **/
2892guint32
2893fu_common_crc32_full (const guint8 *buf, gsize bufsz, guint32 crc, guint32 polynomial)
2894{
2895 for (guint32 idx = 0; idx < bufsz; idx++) {
2896 guint8 data = *buf++;
2897 crc = crc ^ data;
2898 for (guint32 bit = 0; bit < 8; bit++) {
2899 guint32 mask = -(crc & 1);
2900 crc = (crc >> 1) ^ (polynomial & mask);
2901 }
2902 }
2903 return ~crc;
2904}
2905
2906/**
2907 * fu_common_crc32:
2908 * @buf: memory buffer
2909 * @bufsz: sizeof buf
2910 *
2911 * Returns the cyclic redundancy check value for the given memory buffer.
2912 *
2913 * Returns: CRC value
2914 *
2915 * Since: 1.5.0
2916 **/
2917guint32
2918fu_common_crc32 (const guint8 *buf, gsize bufsz)
2919{
2920 return fu_common_crc32_full (buf, bufsz, 0xFFFFFFFF, 0xEDB88320);
2921}
Richard Hughesc7546672021-01-28 10:53:30 +00002922
2923/**
2924 * fu_common_uri_get_scheme:
2925 * @uri: valid URI, e.g. `https://foo.bar/baz`
2926 *
2927 * Returns the USI scheme for the given URI.
2928 *
2929 * Returns: scheme value, or %NULL if invalid, e.g. `https`
2930 *
2931 * Since: 1.5.6
2932 **/
2933gchar *
2934fu_common_uri_get_scheme (const gchar *uri)
2935{
2936 gchar *tmp;
2937
2938 g_return_val_if_fail (uri != NULL, NULL);
2939
2940 tmp = g_strstr_len (uri, -1, ":");
2941 if (tmp == NULL || tmp[0] == '\0')
2942 return NULL;
2943 return g_utf8_strdown (uri, tmp - uri);
2944}