blob: dfea1a811725c5679cfe405807e568cb1127d5ac [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
1893 g_return_val_if_fail (maxsz > 0, NULL);
1894
1895 /* sanity check */
1896 if (str == NULL)
1897 return NULL;
1898
1899 /* replace non-printable chars with '.' */
1900 tmp = g_string_sized_new (strlen (str));
1901 for (gsize i = 0; str[i] != '\0' && i < maxsz; i++) {
1902 if (!g_ascii_isprint (str[i])) {
1903 g_string_append_c (tmp, '.');
1904 continue;
1905 }
1906 g_string_append_c (tmp, str[i]);
1907 valid = TRUE;
1908 }
1909
1910 /* if just junk, don't return 'all dots' */
1911 if (tmp->len == 0 || !valid)
1912 return NULL;
1913 return g_string_free (g_steal_pointer (&tmp), FALSE);
1914}
1915
1916/**
Richard Hughes5308ea42019-08-09 12:25:13 +01001917 * fu_memcpy_safe:
1918 * @dst: destination buffer
1919 * @dst_sz: maximum size of @dst, typically `sizeof(dst)`
1920 * @dst_offset: offset in bytes into @dst to copy to
1921 * @src: source buffer
1922 * @src_sz: maximum size of @dst, typically `sizeof(src)`
1923 * @src_offset: offset in bytes into @src to copy from
1924 * @n: number of bytes to copy from @src+@offset from
1925 * @error: A #GError or %NULL
1926 *
1927 * Copies some memory using memcpy in a safe way. Providing the buffer sizes
1928 * of both the destination and the source allows us to check for buffer overflow.
1929 *
1930 * Providing the buffer offsets also allows us to check reading past the end of
1931 * the source buffer. For this reason the caller should NEVER add an offset to
1932 * @src or @dst.
1933 *
1934 * You don't need to use this function in "obviously correct" cases, nor should
1935 * you use it when performance is a concern. Only us it when you're not sure if
1936 * malicious data from a device or firmware could cause memory corruption.
1937 *
1938 * Return value: %TRUE if the bytes were copied, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06001939 *
1940 * Since: 1.3.1
Richard Hughes5308ea42019-08-09 12:25:13 +01001941 **/
1942gboolean
1943fu_memcpy_safe (guint8 *dst, gsize dst_sz, gsize dst_offset,
1944 const guint8 *src, gsize src_sz, gsize src_offset,
1945 gsize n, GError **error)
1946{
Richard Hughes6a489a92020-12-22 10:32:06 +00001947 g_return_val_if_fail (dst != NULL, FALSE);
1948 g_return_val_if_fail (src != NULL, FALSE);
1949 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1950
Richard Hughes5308ea42019-08-09 12:25:13 +01001951 if (n == 0)
1952 return TRUE;
1953
1954 if (n > src_sz) {
1955 g_set_error (error,
1956 FWUPD_ERROR,
1957 FWUPD_ERROR_READ,
1958 "attempted to read 0x%02x bytes from buffer of 0x%02x",
1959 (guint) n, (guint) src_sz);
1960 return FALSE;
1961 }
1962 if (n + src_offset > src_sz) {
1963 g_set_error (error,
1964 FWUPD_ERROR,
1965 FWUPD_ERROR_READ,
1966 "attempted to read 0x%02x bytes at offset 0x%02x from buffer of 0x%02x",
1967 (guint) n, (guint) src_offset, (guint) src_sz);
1968 return FALSE;
1969 }
1970 if (n > dst_sz) {
1971 g_set_error (error,
1972 FWUPD_ERROR,
1973 FWUPD_ERROR_WRITE,
1974 "attempted to write 0x%02x bytes to buffer of 0x%02x",
1975 (guint) n, (guint) dst_sz);
1976 return FALSE;
1977 }
1978 if (n + dst_offset > dst_sz) {
1979 g_set_error (error,
1980 FWUPD_ERROR,
1981 FWUPD_ERROR_WRITE,
1982 "attempted to write 0x%02x bytes at offset 0x%02x to buffer of 0x%02x",
1983 (guint) n, (guint) dst_offset, (guint) dst_sz);
1984 return FALSE;
1985 }
1986
1987 /* phew! */
1988 memcpy (dst + dst_offset, src + src_offset, n);
1989 return TRUE;
1990}
Richard Hughes37c6a7b2019-08-14 21:57:43 +01001991
Richard Hughes80768f52019-10-22 07:19:14 +01001992/**
Richard Hughesc21a0b92019-10-24 12:24:37 +01001993 * fu_common_read_uint8_safe:
1994 * @buf: source buffer
1995 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
1996 * @offset: offset in bytes into @buf to copy from
1997 * @value: (out) (allow-none): the parsed value
1998 * @error: A #GError or %NULL
1999 *
2000 * Read a value from a buffer in a safe way.
2001 *
2002 * You don't need to use this function in "obviously correct" cases, nor should
2003 * you use it when performance is a concern. Only us it when you're not sure if
2004 * malicious data from a device or firmware could cause memory corruption.
2005 *
2006 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002007 *
2008 * Since: 1.3.3
Richard Hughesc21a0b92019-10-24 12:24:37 +01002009 **/
2010gboolean
2011fu_common_read_uint8_safe (const guint8 *buf,
2012 gsize bufsz,
2013 gsize offset,
2014 guint8 *value,
2015 GError **error)
2016{
2017 guint8 tmp;
Richard Hughes6a489a92020-12-22 10:32:06 +00002018
2019 g_return_val_if_fail (buf != NULL, FALSE);
2020 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2021
Richard Hughesc21a0b92019-10-24 12:24:37 +01002022 if (!fu_memcpy_safe (&tmp, sizeof(tmp), 0x0, /* dst */
2023 buf, bufsz, offset, /* src */
2024 sizeof(tmp), error))
2025 return FALSE;
2026 if (value != NULL)
2027 *value = tmp;
2028 return TRUE;
2029}
2030
2031/**
Richard Hughes80768f52019-10-22 07:19:14 +01002032 * fu_common_read_uint16_safe:
2033 * @buf: source buffer
2034 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2035 * @offset: offset in bytes into @buf to copy from
2036 * @value: (out) (allow-none): the parsed value
2037 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2038 * @error: A #GError or %NULL
2039 *
2040 * Read a value from a buffer using a specified endian in a safe way.
2041 *
2042 * You don't need to use this function in "obviously correct" cases, nor should
2043 * you use it when performance is a concern. Only us it when you're not sure if
2044 * malicious data from a device or firmware could cause memory corruption.
2045 *
2046 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002047 *
2048 * Since: 1.3.3
Richard Hughes80768f52019-10-22 07:19:14 +01002049 **/
2050gboolean
2051fu_common_read_uint16_safe (const guint8 *buf,
2052 gsize bufsz,
2053 gsize offset,
2054 guint16 *value,
2055 FuEndianType endian,
2056 GError **error)
2057{
2058 guint8 dst[2] = { 0x0 };
Richard Hughes6a489a92020-12-22 10:32:06 +00002059
2060 g_return_val_if_fail (buf != NULL, FALSE);
2061 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2062
Richard Hughes7d01ac92019-10-23 14:31:46 +01002063 if (!fu_memcpy_safe (dst, sizeof(dst), 0x0, /* dst */
Richard Hughes80768f52019-10-22 07:19:14 +01002064 buf, bufsz, offset, /* src */
Richard Hughes7d01ac92019-10-23 14:31:46 +01002065 sizeof(dst), error))
Richard Hughes80768f52019-10-22 07:19:14 +01002066 return FALSE;
2067 if (value != NULL)
2068 *value = fu_common_read_uint16 (dst, endian);
2069 return TRUE;
2070}
2071
2072/**
2073 * fu_common_read_uint32_safe:
2074 * @buf: source buffer
2075 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2076 * @offset: offset in bytes into @buf to copy from
2077 * @value: (out) (allow-none): the parsed value
2078 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2079 * @error: A #GError or %NULL
2080 *
2081 * Read a value from a buffer using a specified endian in a safe way.
2082 *
2083 * You don't need to use this function in "obviously correct" cases, nor should
2084 * you use it when performance is a concern. Only us it when you're not sure if
2085 * malicious data from a device or firmware could cause memory corruption.
2086 *
2087 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002088 *
2089 * Since: 1.3.3
Richard Hughes80768f52019-10-22 07:19:14 +01002090 **/
2091gboolean
2092fu_common_read_uint32_safe (const guint8 *buf,
2093 gsize bufsz,
2094 gsize offset,
2095 guint32 *value,
2096 FuEndianType endian,
2097 GError **error)
2098{
2099 guint8 dst[4] = { 0x0 };
Richard Hughes6a489a92020-12-22 10:32:06 +00002100
2101 g_return_val_if_fail (buf != NULL, FALSE);
2102 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2103
Richard Hughes7d01ac92019-10-23 14:31:46 +01002104 if (!fu_memcpy_safe (dst, sizeof(dst), 0x0, /* dst */
Richard Hughes80768f52019-10-22 07:19:14 +01002105 buf, bufsz, offset, /* src */
Richard Hughes7d01ac92019-10-23 14:31:46 +01002106 sizeof(dst), error))
Richard Hughes80768f52019-10-22 07:19:14 +01002107 return FALSE;
2108 if (value != NULL)
2109 *value = fu_common_read_uint32 (dst, endian);
2110 return TRUE;
2111}
2112
Mario Limonciello1a680f32019-11-25 19:44:53 -06002113/**
2114 * fu_byte_array_append_uint8:
2115 * @array: A #GByteArray
2116 * @data: #guint8
2117 *
2118 * Adds a 8 bit integer to a byte array
2119 *
2120 * Since: 1.3.1
2121 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002122void
2123fu_byte_array_append_uint8 (GByteArray *array, guint8 data)
2124{
2125 g_byte_array_append (array, &data, sizeof(data));
2126}
2127
Mario Limonciello1a680f32019-11-25 19:44:53 -06002128/**
2129 * fu_byte_array_append_uint16:
2130 * @array: A #GByteArray
2131 * @data: #guint16
2132 * @endian: #FuEndianType
2133 *
2134 * Adds a 16 bit integer to a byte array
2135 *
2136 * Since: 1.3.1
2137 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002138void
2139fu_byte_array_append_uint16 (GByteArray *array, guint16 data, FuEndianType endian)
2140{
2141 guint8 buf[2];
2142 fu_common_write_uint16 (buf, data, endian);
2143 g_byte_array_append (array, buf, sizeof(buf));
2144}
2145
Mario Limonciello1a680f32019-11-25 19:44:53 -06002146/**
2147 * fu_byte_array_append_uint32:
2148 * @array: A #GByteArray
2149 * @data: #guint32
2150 * @endian: #FuEndianType
2151 *
2152 * Adds a 32 bit integer to a byte array
2153 *
2154 * Since: 1.3.1
2155 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002156void
2157fu_byte_array_append_uint32 (GByteArray *array, guint32 data, FuEndianType endian)
2158{
2159 guint8 buf[4];
2160 fu_common_write_uint32 (buf, data, endian);
2161 g_byte_array_append (array, buf, sizeof(buf));
2162}
Mario Limonciello9dce1f72020-02-04 09:12:52 -06002163
2164/**
Richard Hughesa2a8f8e2020-10-20 09:27:26 +01002165 * fu_byte_array_set_size:
2166 * @array: a #GByteArray
2167 * @length: the new size of the GByteArray
2168 *
2169 * Sets the size of the GByteArray, expanding it with NULs if necessary.
2170 *
2171 * Since: 1.5.0
2172 **/
2173void
2174fu_byte_array_set_size (GByteArray *array, guint length)
2175{
2176 guint oldlength = array->len;
2177 g_byte_array_set_size (array, length);
2178 if (length > oldlength)
2179 memset (array->data + oldlength, 0x0, length - oldlength);
2180}
2181
2182/**
Mario Limonciello9dce1f72020-02-04 09:12:52 -06002183 * fu_common_kernel_locked_down:
2184 *
2185 * Determines if kernel lockdown in effect
2186 *
2187 * Since: 1.3.8
2188 **/
2189gboolean
2190fu_common_kernel_locked_down (void)
2191{
2192#ifndef _WIN32
2193 gsize len = 0;
2194 g_autofree gchar *dir = fu_common_get_path (FU_PATH_KIND_SYSFSDIR_SECURITY);
2195 g_autofree gchar *fname = g_build_filename (dir, "lockdown", NULL);
2196 g_autofree gchar *data = NULL;
2197 g_auto(GStrv) options = NULL;
2198
2199 if (!g_file_test (fname, G_FILE_TEST_EXISTS))
2200 return FALSE;
2201 if (!g_file_get_contents (fname, &data, &len, NULL))
2202 return FALSE;
2203 if (len < 1)
2204 return FALSE;
2205 options = g_strsplit (data, " ", -1);
2206 for (guint i = 0; options[i] != NULL; i++) {
2207 if (g_strcmp0 (options[i], "[none]") == 0)
2208 return FALSE;
2209 }
2210 return TRUE;
2211#else
2212 return FALSE;
2213#endif
2214}
Richard Hughes9223c892020-05-09 20:32:08 +01002215
2216/**
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002217 * fu_common_cpuid:
2218 * @leaf: The CPUID level, now called the 'leaf' by Intel
2219 * @eax: (out) (nullable): EAX register
2220 * @ebx: (out) (nullable): EBX register
2221 * @ecx: (out) (nullable): ECX register
2222 * @edx: (out) (nullable): EDX register
2223 * @error: A #GError or NULL
2224 *
2225 * Calls CPUID and returns the registers for the given leaf.
2226 *
2227 * Return value: %TRUE if the registers are set.
2228 *
2229 * Since: 1.5.0
2230 **/
2231gboolean
2232fu_common_cpuid (guint32 leaf,
2233 guint32 *eax,
2234 guint32 *ebx,
2235 guint32 *ecx,
2236 guint32 *edx,
2237 GError **error)
2238{
2239#ifdef HAVE_CPUID_H
2240 guint eax_tmp = 0;
2241 guint ebx_tmp = 0;
2242 guint ecx_tmp = 0;
2243 guint edx_tmp = 0;
2244
Richard Hughes6a489a92020-12-22 10:32:06 +00002245 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2246
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002247 /* get vendor */
Richard Hughes7c4a64b2020-08-23 21:20:58 +01002248 __get_cpuid_count (leaf, 0x0, &eax_tmp, &ebx_tmp, &ecx_tmp, &edx_tmp);
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002249 if (eax != NULL)
2250 *eax = eax_tmp;
2251 if (ebx != NULL)
2252 *ebx = ebx_tmp;
2253 if (ecx != NULL)
2254 *ecx = ecx_tmp;
2255 if (edx != NULL)
2256 *edx = edx_tmp;
2257 return TRUE;
2258#else
2259 g_set_error_literal (error,
2260 G_IO_ERROR,
2261 G_IO_ERROR_NOT_SUPPORTED,
2262 "no <cpuid.h> support");
2263 return FALSE;
2264#endif
2265}
2266
2267/**
Richard Hughes9223c892020-05-09 20:32:08 +01002268 * fu_common_is_cpu_intel:
2269 *
2270 * Uses CPUID to discover the CPU vendor and check if it is Intel.
2271 *
2272 * Return value: %TRUE if the vendor was Intel.
Richard Hughesb63cfa92021-01-05 22:57:12 +00002273 * Deprecated: 1.5.5: Use fu_common_get_cpu_vendor() instead.
Richard Hughes9223c892020-05-09 20:32:08 +01002274 *
2275 * Since: 1.5.0
2276 **/
2277gboolean
2278fu_common_is_cpu_intel (void)
2279{
Richard Hughesb63cfa92021-01-05 22:57:12 +00002280 return fu_common_get_cpu_vendor () == FU_CPU_VENDOR_INTEL;
2281}
2282
2283/**
2284 * fu_common_get_cpu_vendor:
2285 *
2286 * Uses CPUID to discover the CPU vendor.
2287 *
2288 * Return value: a #FuCpuVendor, e.g. %FU_CPU_VENDOR_AMD if the vendor was AMD.
2289 *
2290 * Since: 1.5.5
2291 **/
2292FuCpuVendor
2293fu_common_get_cpu_vendor (void)
2294{
2295#ifdef HAVE_CPUID_H
Richard Hughes9223c892020-05-09 20:32:08 +01002296 guint ebx = 0;
2297 guint ecx = 0;
2298 guint edx = 0;
Richard Hughes9223c892020-05-09 20:32:08 +01002299
Richard Hughesb63cfa92021-01-05 22:57:12 +00002300 if (fu_common_cpuid (0x0, NULL, &ebx, &ecx, &edx, NULL)) {
2301 if (ebx == signature_INTEL_ebx &&
2302 edx == signature_INTEL_edx &&
2303 ecx == signature_INTEL_ecx) {
2304 return FU_CPU_VENDOR_INTEL;
2305 }
2306 if (ebx == signature_AMD_ebx &&
2307 edx == signature_AMD_edx &&
2308 ecx == signature_AMD_ecx) {
2309 return FU_CPU_VENDOR_AMD;
2310 }
Richard Hughes9223c892020-05-09 20:32:08 +01002311 }
Richard Hughesbd444322020-05-21 12:05:03 +01002312#endif
Richard Hughesb63cfa92021-01-05 22:57:12 +00002313
2314 /* failed */
2315 return FU_CPU_VENDOR_UNKNOWN;
Richard Hughes9223c892020-05-09 20:32:08 +01002316}
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002317
Richard Hughes36111472020-08-12 15:04:24 +01002318/**
2319 * fu_common_is_live_media:
2320 *
2321 * Checks if the user is running from a live media using various heuristics.
2322 *
2323 * Returns: %TRUE if live
2324 *
2325 * Since: 1.4.6
2326 **/
2327gboolean
2328fu_common_is_live_media (void)
2329{
2330 gsize bufsz = 0;
2331 g_autofree gchar *buf = NULL;
2332 g_auto(GStrv) tokens = NULL;
2333 const gchar *args[] = {
2334 "rd.live.image",
2335 "boot=live",
2336 NULL, /* last entry */
2337 };
2338 if (g_file_test ("/cdrom/.disk/info", G_FILE_TEST_EXISTS))
2339 return TRUE;
2340 if (!g_file_get_contents ("/proc/cmdline", &buf, &bufsz, NULL))
2341 return FALSE;
2342 if (bufsz == 0)
2343 return FALSE;
2344 tokens = fu_common_strnsplit (buf, bufsz - 1, " ", -1);
2345 for (guint i = 0; args[i] != NULL; i++) {
2346 if (g_strv_contains ((const gchar * const *) tokens, args[i]))
2347 return TRUE;
2348 }
2349 return FALSE;
2350}
2351
Richard Hughes68175e92021-01-14 09:43:33 +00002352/**
2353 * fu_common_get_memory_size:
2354 *
2355 * Returns the size of physical memory.
2356 *
2357 * Returns: bytes
2358 *
2359 * Since: 1.5.6
2360 **/
2361guint64
2362fu_common_get_memory_size (void)
2363{
2364#ifdef _WIN32
2365 MEMORYSTATUSEX status;
2366 status.dwLength = sizeof(status);
2367 GlobalMemoryStatusEx (&status);
2368 return (guint64) status.ullTotalPhys;
2369#else
2370 return sysconf (_SC_PHYS_PAGES) * sysconf (_SC_PAGE_SIZE);
2371#endif
2372}
2373
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002374static GPtrArray *
Richard Hughes43417b22020-10-30 14:46:16 +00002375fu_common_get_block_devices (GError **error)
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002376{
2377 GVariantBuilder builder;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002378 const gchar *obj;
2379 g_autoptr(GVariant) output = NULL;
2380 g_autoptr(GDBusProxy) proxy = NULL;
2381 g_autoptr(GPtrArray) devices = NULL;
2382 g_autoptr(GVariantIter) iter = NULL;
Richard Hughes43417b22020-10-30 14:46:16 +00002383 g_autoptr(GDBusConnection) connection = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002384
Richard Hughes43417b22020-10-30 14:46:16 +00002385 connection = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, error);
2386 if (connection == NULL) {
2387 g_prefix_error (error, "failed to get system bus: ");
2388 return NULL;
2389 }
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002390 proxy = g_dbus_proxy_new_sync (connection,
2391 G_DBUS_PROXY_FLAGS_NONE, NULL,
2392 UDISKS_DBUS_SERVICE,
2393 UDISKS_DBUS_PATH,
2394 UDISKS_DBUS_MANAGER_INTERFACE,
2395 NULL, error);
2396 if (proxy == NULL) {
2397 g_prefix_error (error, "failed to find %s: ", UDISKS_DBUS_SERVICE);
2398 return NULL;
2399 }
2400 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002401 output = g_dbus_proxy_call_sync (proxy,
Richard Hughesdb344d52020-09-09 19:42:27 +01002402 "GetBlockDevices",
2403 g_variant_new ("(a{sv})", &builder),
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002404 G_DBUS_CALL_FLAGS_NONE,
2405 -1, NULL, error);
Richard Hughes0bdf5612020-10-30 14:56:22 +00002406 if (output == NULL) {
2407 if (error != NULL)
2408 g_dbus_error_strip_remote_error (*error);
2409 g_prefix_error (error, "failed to call %s.%s(): ",
2410 UDISKS_DBUS_SERVICE,
2411 "GetBlockDevices");
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002412 return NULL;
Richard Hughes0bdf5612020-10-30 14:56:22 +00002413 }
Richard Hughes43417b22020-10-30 14:46:16 +00002414 devices = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002415 g_variant_get (output, "(ao)", &iter);
Richard Hughes43417b22020-10-30 14:46:16 +00002416 while (g_variant_iter_next (iter, "&o", &obj)) {
2417 g_autoptr(GDBusProxy) proxy_blk = NULL;
2418 proxy_blk = g_dbus_proxy_new_sync (connection,
2419 G_DBUS_PROXY_FLAGS_NONE, NULL,
2420 UDISKS_DBUS_SERVICE,
2421 obj,
2422 UDISKS_DBUS_INTERFACE_BLOCK,
2423 NULL, error);
2424 if (proxy_blk == NULL) {
2425 g_prefix_error (error, "failed to initialize d-bus proxy for %s: ", obj);
2426 return NULL;
2427 }
2428 g_ptr_array_add (devices, g_steal_pointer (&proxy_blk));
2429 }
2430
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002431
2432 return g_steal_pointer (&devices);
2433}
2434
2435/**
2436 * fu_common_get_volumes_by_kind:
2437 * @kind: A volume kind, typically a GUID
2438 * @error: A #GError or NULL
2439 *
Richard Hughesc57a8f52020-10-30 14:42:42 +00002440 * Finds all volumes of a specific partition type
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002441 *
2442 * Returns: (transfer container) (element-type FuVolume): a #GPtrArray, or %NULL if the kind was not found
2443 *
2444 * Since: 1.4.6
2445 **/
2446GPtrArray *
2447fu_common_get_volumes_by_kind (const gchar *kind, GError **error)
2448{
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002449 g_autoptr(GPtrArray) devices = NULL;
2450 g_autoptr(GPtrArray) volumes = NULL;
2451
Richard Hughes6a489a92020-12-22 10:32:06 +00002452 g_return_val_if_fail (kind != NULL, NULL);
2453 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2454
Richard Hughes43417b22020-10-30 14:46:16 +00002455 devices = fu_common_get_block_devices (error);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002456 if (devices == NULL)
Richard Hughesb81140d2020-08-17 14:47:17 +01002457 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002458 volumes = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
2459 for (guint i = 0; i < devices->len; i++) {
Richard Hughes43417b22020-10-30 14:46:16 +00002460 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002461 const gchar *type_str;
Mario Limonciello56d816a2020-11-11 16:59:30 -06002462 g_autoptr(FuVolume) vol = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002463 g_autoptr(GDBusProxy) proxy_part = NULL;
Richard Hughes43417b22020-10-30 14:46:16 +00002464 g_autoptr(GDBusProxy) proxy_fs = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002465 g_autoptr(GVariant) val = NULL;
2466
Richard Hughes43417b22020-10-30 14:46:16 +00002467 proxy_part = g_dbus_proxy_new_sync (g_dbus_proxy_get_connection (proxy_blk),
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002468 G_DBUS_PROXY_FLAGS_NONE, NULL,
2469 UDISKS_DBUS_SERVICE,
Richard Hughes43417b22020-10-30 14:46:16 +00002470 g_dbus_proxy_get_object_path (proxy_blk),
2471 UDISKS_DBUS_INTERFACE_PARTITION,
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002472 NULL, error);
2473 if (proxy_part == NULL) {
Richard Hughes43417b22020-10-30 14:46:16 +00002474 g_prefix_error (error, "failed to initialize d-bus proxy %s: ",
2475 g_dbus_proxy_get_object_path (proxy_blk));
Richard Hughesb81140d2020-08-17 14:47:17 +01002476 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002477 }
2478 val = g_dbus_proxy_get_cached_property (proxy_part, "Type");
2479 if (val == NULL)
2480 continue;
2481
Richard Hughesdb344d52020-09-09 19:42:27 +01002482 g_variant_get (val, "&s", &type_str);
Richard Hughes43417b22020-10-30 14:46:16 +00002483 proxy_fs = g_dbus_proxy_new_sync (g_dbus_proxy_get_connection (proxy_blk),
2484 G_DBUS_PROXY_FLAGS_NONE, NULL,
2485 UDISKS_DBUS_SERVICE,
2486 g_dbus_proxy_get_object_path (proxy_blk),
2487 UDISKS_DBUS_INTERFACE_FILESYSTEM,
2488 NULL, error);
2489 if (proxy_fs == NULL) {
2490 g_prefix_error (error, "failed to initialize d-bus proxy %s: ",
2491 g_dbus_proxy_get_object_path (proxy_blk));
Richard Hughesb81140d2020-08-17 14:47:17 +01002492 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002493 }
Mario Limonciello56d816a2020-11-11 16:59:30 -06002494 vol = g_object_new (FU_TYPE_VOLUME,
2495 "proxy-block", proxy_blk,
2496 "proxy-filesystem", proxy_fs,
2497 NULL);
2498 g_debug ("device %s, type: %s, internal: %d, fs: %s",
2499 g_dbus_proxy_get_object_path (proxy_blk), type_str,
2500 fu_volume_is_internal (vol),
2501 fu_volume_get_id_type (vol));
2502 if (g_strcmp0 (type_str, kind) != 0)
2503 continue;
2504 g_ptr_array_add (volumes, g_steal_pointer (&vol));
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002505 }
2506 if (volumes->len == 0) {
2507 g_set_error (error,
2508 G_IO_ERROR,
2509 G_IO_ERROR_NOT_FOUND,
2510 "no volumes of type %s", kind);
2511 return NULL;
2512 }
2513 return g_steal_pointer (&volumes);
2514}
2515
2516/**
Richard Hughes0bdf5612020-10-30 14:56:22 +00002517 * fu_common_get_volume_by_device:
2518 * @device: A device string, typcically starting with `/dev/`
2519 * @error: A #GError or NULL
2520 *
2521 * Finds the first volume from the specified device.
2522 *
2523 * Returns: (transfer full): a #GPtrArray, or %NULL if the kind was not found
2524 *
2525 * Since: 1.5.1
2526 **/
2527FuVolume *
2528fu_common_get_volume_by_device (const gchar *device, GError **error)
2529{
2530 g_autoptr(GPtrArray) devices = NULL;
2531
Richard Hughes6a489a92020-12-22 10:32:06 +00002532 g_return_val_if_fail (device != NULL, NULL);
2533 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2534
Richard Hughes0bdf5612020-10-30 14:56:22 +00002535 /* find matching block device */
2536 devices = fu_common_get_block_devices (error);
2537 if (devices == NULL)
2538 return NULL;
2539 for (guint i = 0; i < devices->len; i++) {
2540 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
2541 g_autoptr(GVariant) val = NULL;
2542 val = g_dbus_proxy_get_cached_property (proxy_blk, "Device");
2543 if (val == NULL)
2544 continue;
2545 if (g_strcmp0 (g_variant_get_bytestring (val), device) == 0) {
2546 return g_object_new (FU_TYPE_VOLUME,
2547 "proxy-block", proxy_blk,
2548 NULL);
2549 }
2550 }
2551
2552 /* failed */
2553 g_set_error (error,
2554 G_IO_ERROR,
2555 G_IO_ERROR_NOT_FOUND,
2556 "no volumes for device %s",
2557 device);
2558 return NULL;
2559}
2560
2561/**
2562 * fu_common_get_volume_by_devnum:
Richard Hughese0f92072020-11-06 09:50:29 +00002563 * @devnum: A device number
Richard Hughes0bdf5612020-10-30 14:56:22 +00002564 * @error: A #GError or NULL
2565 *
2566 * Finds the first volume from the specified device.
2567 *
2568 * Returns: (transfer full): a #GPtrArray, or %NULL if the kind was not found
2569 *
2570 * Since: 1.5.1
2571 **/
2572FuVolume *
2573fu_common_get_volume_by_devnum (guint32 devnum, GError **error)
2574{
2575 g_autoptr(GPtrArray) devices = NULL;
2576
Richard Hughes6a489a92020-12-22 10:32:06 +00002577 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2578
Richard Hughes0bdf5612020-10-30 14:56:22 +00002579 /* find matching block device */
2580 devices = fu_common_get_block_devices (error);
2581 if (devices == NULL)
2582 return NULL;
2583 for (guint i = 0; i < devices->len; i++) {
2584 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
2585 g_autoptr(GVariant) val = NULL;
2586 val = g_dbus_proxy_get_cached_property (proxy_blk, "DeviceNumber");
2587 if (val == NULL)
2588 continue;
2589 if (devnum == g_variant_get_uint64 (val)) {
2590 return g_object_new (FU_TYPE_VOLUME,
2591 "proxy-block", proxy_blk,
2592 NULL);
2593 }
2594 }
2595
2596 /* failed */
2597 g_set_error (error,
2598 G_IO_ERROR,
2599 G_IO_ERROR_NOT_FOUND,
2600 "no volumes for devnum %u",
2601 devnum);
2602 return NULL;
2603}
2604
2605/**
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002606 * fu_common_get_esp_default:
2607 * @error: A #GError or NULL
2608 *
2609 * Gets the platform default ESP
2610 *
2611 * Returns: (transfer full): a #FuVolume, or %NULL if the ESP was not found
2612 *
2613 * Since: 1.4.6
2614 **/
2615FuVolume *
2616fu_common_get_esp_default (GError **error)
2617{
2618 const gchar *path_tmp;
Richard Hughes9d20bf92020-12-14 09:36:46 +00002619 gboolean has_internal = FALSE;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002620 g_autoptr(GPtrArray) volumes_fstab = g_ptr_array_new ();
2621 g_autoptr(GPtrArray) volumes_mtab = g_ptr_array_new ();
Mario Limonciello56d816a2020-11-11 16:59:30 -06002622 g_autoptr(GPtrArray) volumes_vfat = g_ptr_array_new ();
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002623 g_autoptr(GPtrArray) volumes = NULL;
Mario Limonciello56d816a2020-11-11 16:59:30 -06002624 g_autoptr(GError) error_local = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002625
Richard Hughes6a489a92020-12-22 10:32:06 +00002626 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2627
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002628 /* for the test suite use local directory for ESP */
2629 path_tmp = g_getenv ("FWUPD_UEFI_ESP_PATH");
2630 if (path_tmp != NULL)
2631 return fu_volume_new_from_mount_path (path_tmp);
2632
Mario Limonciello56d816a2020-11-11 16:59:30 -06002633 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_ESP, &error_local);
2634 if (volumes == NULL) {
2635 g_debug ("%s, falling back to %s", error_local->message, FU_VOLUME_KIND_BDP);
2636 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_BDP, error);
2637 if (volumes == NULL) {
2638 g_prefix_error (error, "%s: ", error_local->message);
2639 return NULL;
2640 }
2641 }
Richard Hughes9d20bf92020-12-14 09:36:46 +00002642
2643 /* are there _any_ internal vfat partitions?
2644 * remember HintSystem is just that -- a hint! */
2645 for (guint i = 0; i < volumes->len; i++) {
2646 FuVolume *vol = g_ptr_array_index (volumes, i);
2647 g_autofree gchar *type = fu_volume_get_id_type (vol);
2648 if (g_strcmp0 (type, "vfat") == 0 &&
2649 fu_volume_is_internal (vol)) {
2650 has_internal = TRUE;
2651 break;
2652 }
2653 }
2654
2655 /* filter to vfat partitions */
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002656 for (guint i = 0; i < volumes->len; i++) {
2657 FuVolume *vol = g_ptr_array_index (volumes, i);
Mario Limonciello56d816a2020-11-11 16:59:30 -06002658 g_autofree gchar *type = fu_volume_get_id_type (vol);
2659 if (type == NULL)
2660 continue;
Richard Hughes9d20bf92020-12-14 09:36:46 +00002661 if (has_internal && !fu_volume_is_internal (vol))
Mario Limonciello56d816a2020-11-11 16:59:30 -06002662 continue;
2663 if (g_strcmp0 (type, "vfat") == 0)
2664 g_ptr_array_add (volumes_vfat, vol);
2665 }
2666 if (volumes_vfat->len == 0) {
2667 g_set_error (error,
2668 G_IO_ERROR,
2669 G_IO_ERROR_INVALID_FILENAME,
2670 "No ESP found");
2671 return NULL;
2672 }
2673 for (guint i = 0; i < volumes_vfat->len; i++) {
2674 FuVolume *vol = g_ptr_array_index (volumes_vfat, i);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002675 g_ptr_array_add (fu_volume_is_mounted (vol) ? volumes_mtab : volumes_fstab, vol);
2676 }
2677 if (volumes_mtab->len == 1) {
2678 FuVolume *vol = g_ptr_array_index (volumes_mtab, 0);
2679 return g_object_ref (vol);
2680 }
2681 if (volumes_mtab->len == 0 && volumes_fstab->len == 1) {
2682 FuVolume *vol = g_ptr_array_index (volumes_fstab, 0);
2683 return g_object_ref (vol);
2684 }
2685 g_set_error (error,
2686 G_IO_ERROR,
2687 G_IO_ERROR_INVALID_FILENAME,
2688 "More than one available ESP");
2689 return NULL;
2690}
2691
2692/**
2693 * fu_common_get_esp_for_path:
2694 * @esp_path: A path to the ESP
2695 * @error: A #GError or NULL
2696 *
2697 * Gets the platform ESP using a UNIX or UDisks path
2698 *
2699 * Returns: (transfer full): a #FuVolume, or %NULL if the ESP was not found
2700 *
2701 * Since: 1.4.6
2702 **/
2703FuVolume *
2704fu_common_get_esp_for_path (const gchar *esp_path, GError **error)
2705{
Richard Hughes6a489a92020-12-22 10:32:06 +00002706 g_autofree gchar *basename = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002707 g_autoptr(GPtrArray) volumes = NULL;
2708
Richard Hughes6a489a92020-12-22 10:32:06 +00002709 g_return_val_if_fail (esp_path != NULL, NULL);
2710 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2711
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002712 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_ESP, error);
2713 if (volumes == NULL)
Richard Hughesb81140d2020-08-17 14:47:17 +01002714 return NULL;
Richard Hughes6a489a92020-12-22 10:32:06 +00002715 basename = g_path_get_basename (esp_path);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002716 for (guint i = 0; i < volumes->len; i++) {
2717 FuVolume *vol = g_ptr_array_index (volumes, i);
Mario Limonciello5a835632020-10-07 14:22:08 -05002718 g_autofree gchar *vol_basename = g_path_get_basename (fu_volume_get_mount_point (vol));
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002719 if (g_strcmp0 (basename, vol_basename) == 0)
2720 return g_object_ref (vol);
2721 }
2722 g_set_error (error,
2723 G_IO_ERROR,
2724 G_IO_ERROR_INVALID_FILENAME,
2725 "No ESP with path %s",
2726 esp_path);
2727 return NULL;
2728}
Richard Hughes6f5e35a2020-09-25 14:14:52 +01002729
2730/**
Richard Hughes44ae2a72020-09-25 18:00:21 +01002731 * fu_common_crc8:
2732 * @buf: memory buffer
2733 * @bufsz: sizeof buf
2734 *
2735 * Returns the cyclic redundancy check value for the given memory buffer.
2736 *
2737 * Returns: CRC value
2738 *
2739 * Since: 1.5.0
2740 **/
2741guint8
2742fu_common_crc8 (const guint8 *buf, gsize bufsz)
2743{
2744 guint32 crc = 0;
2745 for (gsize j = bufsz; j > 0; j--) {
2746 crc ^= (*(buf++) << 8);
2747 for (guint32 i = 8; i; i--) {
2748 if (crc & 0x8000)
2749 crc ^= (0x1070 << 3);
2750 crc <<= 1;
2751 }
2752 }
2753 return ~((guint8) (crc >> 8));
2754}
2755
2756/**
Richard Hughes6f5e35a2020-09-25 14:14:52 +01002757 * fu_common_crc16:
2758 * @buf: memory buffer
2759 * @bufsz: sizeof buf
2760 *
2761 * Returns the cyclic redundancy check value for the given memory buffer.
2762 *
2763 * Returns: CRC value
2764 *
2765 * Since: 1.5.0
2766 **/
2767guint16
2768fu_common_crc16 (const guint8 *buf, gsize bufsz)
2769{
2770 guint16 crc = 0xffff;
2771 for (gsize len = bufsz; len > 0; len--) {
2772 crc = (guint16) (crc ^ (*buf++));
2773 for (guint8 i = 0; i < 8; i++) {
2774 if (crc & 0x1) {
2775 crc = (crc >> 1) ^ 0xa001;
2776 } else {
2777 crc >>= 1;
2778 }
2779 }
2780 }
2781 return ~crc;
2782}
2783
2784/**
2785 * fu_common_crc32_full:
2786 * @buf: memory buffer
2787 * @bufsz: sizeof buf
2788 * @crc: initial CRC value, typically 0xFFFFFFFF
2789 * @polynomial: CRC polynomial, typically 0xEDB88320
2790 *
2791 * Returns the cyclic redundancy check value for the given memory buffer.
2792 *
2793 * Returns: CRC value
2794 *
2795 * Since: 1.5.0
2796 **/
2797guint32
2798fu_common_crc32_full (const guint8 *buf, gsize bufsz, guint32 crc, guint32 polynomial)
2799{
2800 for (guint32 idx = 0; idx < bufsz; idx++) {
2801 guint8 data = *buf++;
2802 crc = crc ^ data;
2803 for (guint32 bit = 0; bit < 8; bit++) {
2804 guint32 mask = -(crc & 1);
2805 crc = (crc >> 1) ^ (polynomial & mask);
2806 }
2807 }
2808 return ~crc;
2809}
2810
2811/**
2812 * fu_common_crc32:
2813 * @buf: memory buffer
2814 * @bufsz: sizeof buf
2815 *
2816 * Returns the cyclic redundancy check value for the given memory buffer.
2817 *
2818 * Returns: CRC value
2819 *
2820 * Since: 1.5.0
2821 **/
2822guint32
2823fu_common_crc32 (const guint8 *buf, gsize bufsz)
2824{
2825 return fu_common_crc32_full (buf, bufsz, 0xFFFFFFFF, 0xEDB88320);
2826}