blob: 02082bdeeeacdc9efdc3175f2f547db22be6258e [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
Richard Hughese52e1b42021-01-26 09:59:15 +00001916
1917/**
1918 * fu_common_strjoin_array:
1919 * @separator: (nullable): string to insert between each of the strings, or %NULL
1920 * @array: (element-type utf8): A #GPtrArray
1921 *
1922 * Joins an array of strings together to form one long string, with the optional
1923 * separator inserted between each of them.
1924 *
1925 * If @array has no items, the return value will be an empty string.
1926 * If @array contains a single item, separator will not appear in the resulting
1927 * string.
1928 *
1929 * Returns: a string
1930 *
1931 * Since: 1.5.6
1932 **/
1933gchar *
1934fu_common_strjoin_array (const gchar *separator, GPtrArray *array)
1935{
1936 g_autofree const gchar **strv = NULL;
1937
1938 g_return_val_if_fail (array != NULL, NULL);
1939
1940 strv = g_new0 (const gchar *, array->len + 1);
1941 for (guint i = 0; i < array->len; i++)
1942 strv[i] = g_ptr_array_index (array, i);
1943 return g_strjoinv (separator, (gchar **) strv);
1944}
1945
Richard Hughes364e2682021-01-05 14:38:15 +00001946/**
Richard Hughes5308ea42019-08-09 12:25:13 +01001947 * fu_memcpy_safe:
1948 * @dst: destination buffer
1949 * @dst_sz: maximum size of @dst, typically `sizeof(dst)`
1950 * @dst_offset: offset in bytes into @dst to copy to
1951 * @src: source buffer
1952 * @src_sz: maximum size of @dst, typically `sizeof(src)`
1953 * @src_offset: offset in bytes into @src to copy from
1954 * @n: number of bytes to copy from @src+@offset from
1955 * @error: A #GError or %NULL
1956 *
1957 * Copies some memory using memcpy in a safe way. Providing the buffer sizes
1958 * of both the destination and the source allows us to check for buffer overflow.
1959 *
1960 * Providing the buffer offsets also allows us to check reading past the end of
1961 * the source buffer. For this reason the caller should NEVER add an offset to
1962 * @src or @dst.
1963 *
1964 * You don't need to use this function in "obviously correct" cases, nor should
1965 * you use it when performance is a concern. Only us it when you're not sure if
1966 * malicious data from a device or firmware could cause memory corruption.
1967 *
1968 * Return value: %TRUE if the bytes were copied, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06001969 *
1970 * Since: 1.3.1
Richard Hughes5308ea42019-08-09 12:25:13 +01001971 **/
1972gboolean
1973fu_memcpy_safe (guint8 *dst, gsize dst_sz, gsize dst_offset,
1974 const guint8 *src, gsize src_sz, gsize src_offset,
1975 gsize n, GError **error)
1976{
Richard Hughes6a489a92020-12-22 10:32:06 +00001977 g_return_val_if_fail (dst != NULL, FALSE);
1978 g_return_val_if_fail (src != NULL, FALSE);
1979 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1980
Richard Hughes5308ea42019-08-09 12:25:13 +01001981 if (n == 0)
1982 return TRUE;
1983
1984 if (n > src_sz) {
1985 g_set_error (error,
1986 FWUPD_ERROR,
1987 FWUPD_ERROR_READ,
1988 "attempted to read 0x%02x bytes from buffer of 0x%02x",
1989 (guint) n, (guint) src_sz);
1990 return FALSE;
1991 }
1992 if (n + src_offset > src_sz) {
1993 g_set_error (error,
1994 FWUPD_ERROR,
1995 FWUPD_ERROR_READ,
1996 "attempted to read 0x%02x bytes at offset 0x%02x from buffer of 0x%02x",
1997 (guint) n, (guint) src_offset, (guint) src_sz);
1998 return FALSE;
1999 }
2000 if (n > dst_sz) {
2001 g_set_error (error,
2002 FWUPD_ERROR,
2003 FWUPD_ERROR_WRITE,
2004 "attempted to write 0x%02x bytes to buffer of 0x%02x",
2005 (guint) n, (guint) dst_sz);
2006 return FALSE;
2007 }
2008 if (n + dst_offset > dst_sz) {
2009 g_set_error (error,
2010 FWUPD_ERROR,
2011 FWUPD_ERROR_WRITE,
2012 "attempted to write 0x%02x bytes at offset 0x%02x to buffer of 0x%02x",
2013 (guint) n, (guint) dst_offset, (guint) dst_sz);
2014 return FALSE;
2015 }
2016
2017 /* phew! */
2018 memcpy (dst + dst_offset, src + src_offset, n);
2019 return TRUE;
2020}
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002021
Richard Hughes80768f52019-10-22 07:19:14 +01002022/**
Richard Hughes9b11af92021-02-04 20:28:49 +00002023 * fu_memdup_safe:
2024 * @src: source buffer
2025 * @n: number of bytes to copy from @src
2026 * @error: A #GError or %NULL
2027 *
2028 * Duplicates some memory using memdup in a safe way.
2029 *
2030 * You don't need to use this function in "obviously correct" cases, nor should
2031 * you use it when performance is a concern. Only us it when you're not sure if
2032 * malicious data from a device or firmware could cause memory corruption.
2033 *
2034 * NOTE: This function intentionally limits allocation size to 1GB.
2035 *
2036 * Return value: (transfer full): block of allocated memory, or %NULL for an error.
2037 *
2038 * Since: 1.5.6
2039 **/
2040guint8 *
2041fu_memdup_safe (const guint8 *src, gsize n, GError **error)
2042{
Richard Hughes9b11af92021-02-04 20:28:49 +00002043 /* sanity check */
2044 if (n > 0x40000000) {
2045 g_set_error (error,
2046 G_IO_ERROR,
2047 G_IO_ERROR_NOT_SUPPORTED,
2048 "cannot allocate %uGB of memory",
2049 (guint) (n / 0x40000000));
2050 return NULL;
2051 }
2052
Richard Hughes5294d0c2021-02-05 09:50:02 +00002053#if GLIB_CHECK_VERSION(2,67,3)
Richard Hughes9b11af92021-02-04 20:28:49 +00002054 /* linear block of memory */
Richard Hughes5294d0c2021-02-05 09:50:02 +00002055 return g_memdup2 (src, n);
2056#else
2057 return g_memdup (src, (guint) n);
2058#endif
Richard Hughes9b11af92021-02-04 20:28:49 +00002059}
2060
2061/**
Richard Hughesc21a0b92019-10-24 12:24:37 +01002062 * fu_common_read_uint8_safe:
2063 * @buf: source buffer
2064 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2065 * @offset: offset in bytes into @buf to copy from
2066 * @value: (out) (allow-none): the parsed value
2067 * @error: A #GError or %NULL
2068 *
2069 * Read a value from a buffer in a safe way.
2070 *
2071 * You don't need to use this function in "obviously correct" cases, nor should
2072 * you use it when performance is a concern. Only us it when you're not sure if
2073 * malicious data from a device or firmware could cause memory corruption.
2074 *
2075 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002076 *
2077 * Since: 1.3.3
Richard Hughesc21a0b92019-10-24 12:24:37 +01002078 **/
2079gboolean
2080fu_common_read_uint8_safe (const guint8 *buf,
2081 gsize bufsz,
2082 gsize offset,
2083 guint8 *value,
2084 GError **error)
2085{
2086 guint8 tmp;
Richard Hughes6a489a92020-12-22 10:32:06 +00002087
2088 g_return_val_if_fail (buf != NULL, FALSE);
2089 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2090
Richard Hughesc21a0b92019-10-24 12:24:37 +01002091 if (!fu_memcpy_safe (&tmp, sizeof(tmp), 0x0, /* dst */
2092 buf, bufsz, offset, /* src */
2093 sizeof(tmp), error))
2094 return FALSE;
2095 if (value != NULL)
2096 *value = tmp;
2097 return TRUE;
2098}
2099
2100/**
Richard Hughes80768f52019-10-22 07:19:14 +01002101 * fu_common_read_uint16_safe:
2102 * @buf: source buffer
2103 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2104 * @offset: offset in bytes into @buf to copy from
2105 * @value: (out) (allow-none): the parsed value
2106 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2107 * @error: A #GError or %NULL
2108 *
2109 * Read a value from a buffer using a specified endian in a safe way.
2110 *
2111 * You don't need to use this function in "obviously correct" cases, nor should
2112 * you use it when performance is a concern. Only us it when you're not sure if
2113 * malicious data from a device or firmware could cause memory corruption.
2114 *
2115 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002116 *
2117 * Since: 1.3.3
Richard Hughes80768f52019-10-22 07:19:14 +01002118 **/
2119gboolean
2120fu_common_read_uint16_safe (const guint8 *buf,
2121 gsize bufsz,
2122 gsize offset,
2123 guint16 *value,
2124 FuEndianType endian,
2125 GError **error)
2126{
2127 guint8 dst[2] = { 0x0 };
Richard Hughes6a489a92020-12-22 10:32:06 +00002128
2129 g_return_val_if_fail (buf != NULL, FALSE);
2130 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2131
Richard Hughes7d01ac92019-10-23 14:31:46 +01002132 if (!fu_memcpy_safe (dst, sizeof(dst), 0x0, /* dst */
Richard Hughes80768f52019-10-22 07:19:14 +01002133 buf, bufsz, offset, /* src */
Richard Hughes7d01ac92019-10-23 14:31:46 +01002134 sizeof(dst), error))
Richard Hughes80768f52019-10-22 07:19:14 +01002135 return FALSE;
2136 if (value != NULL)
2137 *value = fu_common_read_uint16 (dst, endian);
2138 return TRUE;
2139}
2140
2141/**
2142 * fu_common_read_uint32_safe:
2143 * @buf: source buffer
2144 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2145 * @offset: offset in bytes into @buf to copy from
2146 * @value: (out) (allow-none): the parsed value
2147 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2148 * @error: A #GError or %NULL
2149 *
2150 * Read a value from a buffer using a specified endian in a safe way.
2151 *
2152 * You don't need to use this function in "obviously correct" cases, nor should
2153 * you use it when performance is a concern. Only us it when you're not sure if
2154 * malicious data from a device or firmware could cause memory corruption.
2155 *
2156 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002157 *
2158 * Since: 1.3.3
Richard Hughes80768f52019-10-22 07:19:14 +01002159 **/
2160gboolean
2161fu_common_read_uint32_safe (const guint8 *buf,
2162 gsize bufsz,
2163 gsize offset,
2164 guint32 *value,
2165 FuEndianType endian,
2166 GError **error)
2167{
2168 guint8 dst[4] = { 0x0 };
Richard Hughes6a489a92020-12-22 10:32:06 +00002169
2170 g_return_val_if_fail (buf != NULL, FALSE);
2171 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2172
Richard Hughes7d01ac92019-10-23 14:31:46 +01002173 if (!fu_memcpy_safe (dst, sizeof(dst), 0x0, /* dst */
Richard Hughes80768f52019-10-22 07:19:14 +01002174 buf, bufsz, offset, /* src */
Richard Hughes7d01ac92019-10-23 14:31:46 +01002175 sizeof(dst), error))
Richard Hughes80768f52019-10-22 07:19:14 +01002176 return FALSE;
2177 if (value != NULL)
2178 *value = fu_common_read_uint32 (dst, endian);
2179 return TRUE;
2180}
2181
Mario Limonciello1a680f32019-11-25 19:44:53 -06002182/**
2183 * fu_byte_array_append_uint8:
2184 * @array: A #GByteArray
2185 * @data: #guint8
2186 *
2187 * Adds a 8 bit integer to a byte array
2188 *
2189 * Since: 1.3.1
2190 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002191void
2192fu_byte_array_append_uint8 (GByteArray *array, guint8 data)
2193{
2194 g_byte_array_append (array, &data, sizeof(data));
2195}
2196
Mario Limonciello1a680f32019-11-25 19:44:53 -06002197/**
2198 * fu_byte_array_append_uint16:
2199 * @array: A #GByteArray
2200 * @data: #guint16
2201 * @endian: #FuEndianType
2202 *
2203 * Adds a 16 bit integer to a byte array
2204 *
2205 * Since: 1.3.1
2206 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002207void
2208fu_byte_array_append_uint16 (GByteArray *array, guint16 data, FuEndianType endian)
2209{
2210 guint8 buf[2];
2211 fu_common_write_uint16 (buf, data, endian);
2212 g_byte_array_append (array, buf, sizeof(buf));
2213}
2214
Mario Limonciello1a680f32019-11-25 19:44:53 -06002215/**
2216 * fu_byte_array_append_uint32:
2217 * @array: A #GByteArray
2218 * @data: #guint32
2219 * @endian: #FuEndianType
2220 *
2221 * Adds a 32 bit integer to a byte array
2222 *
2223 * Since: 1.3.1
2224 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002225void
2226fu_byte_array_append_uint32 (GByteArray *array, guint32 data, FuEndianType endian)
2227{
2228 guint8 buf[4];
2229 fu_common_write_uint32 (buf, data, endian);
2230 g_byte_array_append (array, buf, sizeof(buf));
2231}
Mario Limonciello9dce1f72020-02-04 09:12:52 -06002232
2233/**
Richard Hughesa2a8f8e2020-10-20 09:27:26 +01002234 * fu_byte_array_set_size:
2235 * @array: a #GByteArray
2236 * @length: the new size of the GByteArray
2237 *
2238 * Sets the size of the GByteArray, expanding it with NULs if necessary.
2239 *
2240 * Since: 1.5.0
2241 **/
2242void
2243fu_byte_array_set_size (GByteArray *array, guint length)
2244{
2245 guint oldlength = array->len;
2246 g_byte_array_set_size (array, length);
2247 if (length > oldlength)
2248 memset (array->data + oldlength, 0x0, length - oldlength);
2249}
2250
2251/**
Mario Limonciello9dce1f72020-02-04 09:12:52 -06002252 * fu_common_kernel_locked_down:
2253 *
2254 * Determines if kernel lockdown in effect
2255 *
2256 * Since: 1.3.8
2257 **/
2258gboolean
2259fu_common_kernel_locked_down (void)
2260{
2261#ifndef _WIN32
2262 gsize len = 0;
2263 g_autofree gchar *dir = fu_common_get_path (FU_PATH_KIND_SYSFSDIR_SECURITY);
2264 g_autofree gchar *fname = g_build_filename (dir, "lockdown", NULL);
2265 g_autofree gchar *data = NULL;
2266 g_auto(GStrv) options = NULL;
2267
2268 if (!g_file_test (fname, G_FILE_TEST_EXISTS))
2269 return FALSE;
2270 if (!g_file_get_contents (fname, &data, &len, NULL))
2271 return FALSE;
2272 if (len < 1)
2273 return FALSE;
2274 options = g_strsplit (data, " ", -1);
2275 for (guint i = 0; options[i] != NULL; i++) {
2276 if (g_strcmp0 (options[i], "[none]") == 0)
2277 return FALSE;
2278 }
2279 return TRUE;
2280#else
2281 return FALSE;
2282#endif
2283}
Richard Hughes9223c892020-05-09 20:32:08 +01002284
2285/**
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002286 * fu_common_cpuid:
2287 * @leaf: The CPUID level, now called the 'leaf' by Intel
2288 * @eax: (out) (nullable): EAX register
2289 * @ebx: (out) (nullable): EBX register
2290 * @ecx: (out) (nullable): ECX register
2291 * @edx: (out) (nullable): EDX register
2292 * @error: A #GError or NULL
2293 *
2294 * Calls CPUID and returns the registers for the given leaf.
2295 *
2296 * Return value: %TRUE if the registers are set.
2297 *
2298 * Since: 1.5.0
2299 **/
2300gboolean
2301fu_common_cpuid (guint32 leaf,
2302 guint32 *eax,
2303 guint32 *ebx,
2304 guint32 *ecx,
2305 guint32 *edx,
2306 GError **error)
2307{
2308#ifdef HAVE_CPUID_H
2309 guint eax_tmp = 0;
2310 guint ebx_tmp = 0;
2311 guint ecx_tmp = 0;
2312 guint edx_tmp = 0;
2313
Richard Hughes6a489a92020-12-22 10:32:06 +00002314 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2315
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002316 /* get vendor */
Richard Hughes7c4a64b2020-08-23 21:20:58 +01002317 __get_cpuid_count (leaf, 0x0, &eax_tmp, &ebx_tmp, &ecx_tmp, &edx_tmp);
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002318 if (eax != NULL)
2319 *eax = eax_tmp;
2320 if (ebx != NULL)
2321 *ebx = ebx_tmp;
2322 if (ecx != NULL)
2323 *ecx = ecx_tmp;
2324 if (edx != NULL)
2325 *edx = edx_tmp;
2326 return TRUE;
2327#else
2328 g_set_error_literal (error,
2329 G_IO_ERROR,
2330 G_IO_ERROR_NOT_SUPPORTED,
2331 "no <cpuid.h> support");
2332 return FALSE;
2333#endif
2334}
2335
2336/**
Richard Hughes9223c892020-05-09 20:32:08 +01002337 * fu_common_is_cpu_intel:
2338 *
2339 * Uses CPUID to discover the CPU vendor and check if it is Intel.
2340 *
2341 * Return value: %TRUE if the vendor was Intel.
Richard Hughesb63cfa92021-01-05 22:57:12 +00002342 * Deprecated: 1.5.5: Use fu_common_get_cpu_vendor() instead.
Richard Hughes9223c892020-05-09 20:32:08 +01002343 *
2344 * Since: 1.5.0
2345 **/
2346gboolean
2347fu_common_is_cpu_intel (void)
2348{
Richard Hughesb63cfa92021-01-05 22:57:12 +00002349 return fu_common_get_cpu_vendor () == FU_CPU_VENDOR_INTEL;
2350}
2351
2352/**
2353 * fu_common_get_cpu_vendor:
2354 *
2355 * Uses CPUID to discover the CPU vendor.
2356 *
2357 * Return value: a #FuCpuVendor, e.g. %FU_CPU_VENDOR_AMD if the vendor was AMD.
2358 *
2359 * Since: 1.5.5
2360 **/
2361FuCpuVendor
2362fu_common_get_cpu_vendor (void)
2363{
2364#ifdef HAVE_CPUID_H
Richard Hughes9223c892020-05-09 20:32:08 +01002365 guint ebx = 0;
2366 guint ecx = 0;
2367 guint edx = 0;
Richard Hughes9223c892020-05-09 20:32:08 +01002368
Richard Hughesb63cfa92021-01-05 22:57:12 +00002369 if (fu_common_cpuid (0x0, NULL, &ebx, &ecx, &edx, NULL)) {
2370 if (ebx == signature_INTEL_ebx &&
2371 edx == signature_INTEL_edx &&
2372 ecx == signature_INTEL_ecx) {
2373 return FU_CPU_VENDOR_INTEL;
2374 }
2375 if (ebx == signature_AMD_ebx &&
2376 edx == signature_AMD_edx &&
2377 ecx == signature_AMD_ecx) {
2378 return FU_CPU_VENDOR_AMD;
2379 }
Richard Hughes9223c892020-05-09 20:32:08 +01002380 }
Richard Hughesbd444322020-05-21 12:05:03 +01002381#endif
Richard Hughesb63cfa92021-01-05 22:57:12 +00002382
2383 /* failed */
2384 return FU_CPU_VENDOR_UNKNOWN;
Richard Hughes9223c892020-05-09 20:32:08 +01002385}
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002386
Richard Hughes36111472020-08-12 15:04:24 +01002387/**
2388 * fu_common_is_live_media:
2389 *
2390 * Checks if the user is running from a live media using various heuristics.
2391 *
2392 * Returns: %TRUE if live
2393 *
2394 * Since: 1.4.6
2395 **/
2396gboolean
2397fu_common_is_live_media (void)
2398{
2399 gsize bufsz = 0;
2400 g_autofree gchar *buf = NULL;
2401 g_auto(GStrv) tokens = NULL;
2402 const gchar *args[] = {
2403 "rd.live.image",
2404 "boot=live",
2405 NULL, /* last entry */
2406 };
2407 if (g_file_test ("/cdrom/.disk/info", G_FILE_TEST_EXISTS))
2408 return TRUE;
2409 if (!g_file_get_contents ("/proc/cmdline", &buf, &bufsz, NULL))
2410 return FALSE;
2411 if (bufsz == 0)
2412 return FALSE;
2413 tokens = fu_common_strnsplit (buf, bufsz - 1, " ", -1);
2414 for (guint i = 0; args[i] != NULL; i++) {
2415 if (g_strv_contains ((const gchar * const *) tokens, args[i]))
2416 return TRUE;
2417 }
2418 return FALSE;
2419}
2420
Richard Hughes68175e92021-01-14 09:43:33 +00002421/**
2422 * fu_common_get_memory_size:
2423 *
2424 * Returns the size of physical memory.
2425 *
2426 * Returns: bytes
2427 *
2428 * Since: 1.5.6
2429 **/
2430guint64
2431fu_common_get_memory_size (void)
2432{
2433#ifdef _WIN32
2434 MEMORYSTATUSEX status;
2435 status.dwLength = sizeof(status);
2436 GlobalMemoryStatusEx (&status);
2437 return (guint64) status.ullTotalPhys;
2438#else
2439 return sysconf (_SC_PHYS_PAGES) * sysconf (_SC_PAGE_SIZE);
2440#endif
2441}
2442
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002443static GPtrArray *
Richard Hughes43417b22020-10-30 14:46:16 +00002444fu_common_get_block_devices (GError **error)
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002445{
2446 GVariantBuilder builder;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002447 const gchar *obj;
2448 g_autoptr(GVariant) output = NULL;
2449 g_autoptr(GDBusProxy) proxy = NULL;
2450 g_autoptr(GPtrArray) devices = NULL;
2451 g_autoptr(GVariantIter) iter = NULL;
Richard Hughes43417b22020-10-30 14:46:16 +00002452 g_autoptr(GDBusConnection) connection = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002453
Richard Hughes43417b22020-10-30 14:46:16 +00002454 connection = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, error);
2455 if (connection == NULL) {
2456 g_prefix_error (error, "failed to get system bus: ");
2457 return NULL;
2458 }
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002459 proxy = g_dbus_proxy_new_sync (connection,
2460 G_DBUS_PROXY_FLAGS_NONE, NULL,
2461 UDISKS_DBUS_SERVICE,
2462 UDISKS_DBUS_PATH,
2463 UDISKS_DBUS_MANAGER_INTERFACE,
2464 NULL, error);
2465 if (proxy == NULL) {
2466 g_prefix_error (error, "failed to find %s: ", UDISKS_DBUS_SERVICE);
2467 return NULL;
2468 }
2469 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002470 output = g_dbus_proxy_call_sync (proxy,
Richard Hughesdb344d52020-09-09 19:42:27 +01002471 "GetBlockDevices",
2472 g_variant_new ("(a{sv})", &builder),
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002473 G_DBUS_CALL_FLAGS_NONE,
2474 -1, NULL, error);
Richard Hughes0bdf5612020-10-30 14:56:22 +00002475 if (output == NULL) {
2476 if (error != NULL)
2477 g_dbus_error_strip_remote_error (*error);
2478 g_prefix_error (error, "failed to call %s.%s(): ",
2479 UDISKS_DBUS_SERVICE,
2480 "GetBlockDevices");
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002481 return NULL;
Richard Hughes0bdf5612020-10-30 14:56:22 +00002482 }
Richard Hughes43417b22020-10-30 14:46:16 +00002483 devices = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002484 g_variant_get (output, "(ao)", &iter);
Richard Hughes43417b22020-10-30 14:46:16 +00002485 while (g_variant_iter_next (iter, "&o", &obj)) {
2486 g_autoptr(GDBusProxy) proxy_blk = NULL;
2487 proxy_blk = g_dbus_proxy_new_sync (connection,
2488 G_DBUS_PROXY_FLAGS_NONE, NULL,
2489 UDISKS_DBUS_SERVICE,
2490 obj,
2491 UDISKS_DBUS_INTERFACE_BLOCK,
2492 NULL, error);
2493 if (proxy_blk == NULL) {
2494 g_prefix_error (error, "failed to initialize d-bus proxy for %s: ", obj);
2495 return NULL;
2496 }
2497 g_ptr_array_add (devices, g_steal_pointer (&proxy_blk));
2498 }
2499
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002500
2501 return g_steal_pointer (&devices);
2502}
2503
2504/**
2505 * fu_common_get_volumes_by_kind:
2506 * @kind: A volume kind, typically a GUID
2507 * @error: A #GError or NULL
2508 *
Richard Hughesc57a8f52020-10-30 14:42:42 +00002509 * Finds all volumes of a specific partition type
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002510 *
2511 * Returns: (transfer container) (element-type FuVolume): a #GPtrArray, or %NULL if the kind was not found
2512 *
2513 * Since: 1.4.6
2514 **/
2515GPtrArray *
2516fu_common_get_volumes_by_kind (const gchar *kind, GError **error)
2517{
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002518 g_autoptr(GPtrArray) devices = NULL;
2519 g_autoptr(GPtrArray) volumes = NULL;
2520
Richard Hughes6a489a92020-12-22 10:32:06 +00002521 g_return_val_if_fail (kind != NULL, NULL);
2522 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2523
Richard Hughes43417b22020-10-30 14:46:16 +00002524 devices = fu_common_get_block_devices (error);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002525 if (devices == NULL)
Richard Hughesb81140d2020-08-17 14:47:17 +01002526 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002527 volumes = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
2528 for (guint i = 0; i < devices->len; i++) {
Richard Hughes43417b22020-10-30 14:46:16 +00002529 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002530 const gchar *type_str;
Mario Limonciello56d816a2020-11-11 16:59:30 -06002531 g_autoptr(FuVolume) vol = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002532 g_autoptr(GDBusProxy) proxy_part = NULL;
Richard Hughes43417b22020-10-30 14:46:16 +00002533 g_autoptr(GDBusProxy) proxy_fs = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002534 g_autoptr(GVariant) val = NULL;
2535
Richard Hughes43417b22020-10-30 14:46:16 +00002536 proxy_part = g_dbus_proxy_new_sync (g_dbus_proxy_get_connection (proxy_blk),
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002537 G_DBUS_PROXY_FLAGS_NONE, NULL,
2538 UDISKS_DBUS_SERVICE,
Richard Hughes43417b22020-10-30 14:46:16 +00002539 g_dbus_proxy_get_object_path (proxy_blk),
2540 UDISKS_DBUS_INTERFACE_PARTITION,
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002541 NULL, error);
2542 if (proxy_part == NULL) {
Richard Hughes43417b22020-10-30 14:46:16 +00002543 g_prefix_error (error, "failed to initialize d-bus proxy %s: ",
2544 g_dbus_proxy_get_object_path (proxy_blk));
Richard Hughesb81140d2020-08-17 14:47:17 +01002545 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002546 }
2547 val = g_dbus_proxy_get_cached_property (proxy_part, "Type");
2548 if (val == NULL)
2549 continue;
2550
Richard Hughesdb344d52020-09-09 19:42:27 +01002551 g_variant_get (val, "&s", &type_str);
Richard Hughes43417b22020-10-30 14:46:16 +00002552 proxy_fs = g_dbus_proxy_new_sync (g_dbus_proxy_get_connection (proxy_blk),
2553 G_DBUS_PROXY_FLAGS_NONE, NULL,
2554 UDISKS_DBUS_SERVICE,
2555 g_dbus_proxy_get_object_path (proxy_blk),
2556 UDISKS_DBUS_INTERFACE_FILESYSTEM,
2557 NULL, error);
2558 if (proxy_fs == NULL) {
2559 g_prefix_error (error, "failed to initialize d-bus proxy %s: ",
2560 g_dbus_proxy_get_object_path (proxy_blk));
Richard Hughesb81140d2020-08-17 14:47:17 +01002561 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002562 }
Mario Limonciello56d816a2020-11-11 16:59:30 -06002563 vol = g_object_new (FU_TYPE_VOLUME,
2564 "proxy-block", proxy_blk,
2565 "proxy-filesystem", proxy_fs,
2566 NULL);
2567 g_debug ("device %s, type: %s, internal: %d, fs: %s",
2568 g_dbus_proxy_get_object_path (proxy_blk), type_str,
2569 fu_volume_is_internal (vol),
2570 fu_volume_get_id_type (vol));
2571 if (g_strcmp0 (type_str, kind) != 0)
2572 continue;
2573 g_ptr_array_add (volumes, g_steal_pointer (&vol));
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002574 }
2575 if (volumes->len == 0) {
2576 g_set_error (error,
2577 G_IO_ERROR,
2578 G_IO_ERROR_NOT_FOUND,
2579 "no volumes of type %s", kind);
2580 return NULL;
2581 }
2582 return g_steal_pointer (&volumes);
2583}
2584
2585/**
Richard Hughes0bdf5612020-10-30 14:56:22 +00002586 * fu_common_get_volume_by_device:
2587 * @device: A device string, typcically starting with `/dev/`
2588 * @error: A #GError or NULL
2589 *
2590 * Finds the first volume from the specified device.
2591 *
2592 * Returns: (transfer full): a #GPtrArray, or %NULL if the kind was not found
2593 *
2594 * Since: 1.5.1
2595 **/
2596FuVolume *
2597fu_common_get_volume_by_device (const gchar *device, GError **error)
2598{
2599 g_autoptr(GPtrArray) devices = NULL;
2600
Richard Hughes6a489a92020-12-22 10:32:06 +00002601 g_return_val_if_fail (device != NULL, NULL);
2602 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2603
Richard Hughes0bdf5612020-10-30 14:56:22 +00002604 /* find matching block device */
2605 devices = fu_common_get_block_devices (error);
2606 if (devices == NULL)
2607 return NULL;
2608 for (guint i = 0; i < devices->len; i++) {
2609 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
2610 g_autoptr(GVariant) val = NULL;
2611 val = g_dbus_proxy_get_cached_property (proxy_blk, "Device");
2612 if (val == NULL)
2613 continue;
2614 if (g_strcmp0 (g_variant_get_bytestring (val), device) == 0) {
2615 return g_object_new (FU_TYPE_VOLUME,
2616 "proxy-block", proxy_blk,
2617 NULL);
2618 }
2619 }
2620
2621 /* failed */
2622 g_set_error (error,
2623 G_IO_ERROR,
2624 G_IO_ERROR_NOT_FOUND,
2625 "no volumes for device %s",
2626 device);
2627 return NULL;
2628}
2629
2630/**
2631 * fu_common_get_volume_by_devnum:
Richard Hughese0f92072020-11-06 09:50:29 +00002632 * @devnum: A device number
Richard Hughes0bdf5612020-10-30 14:56:22 +00002633 * @error: A #GError or NULL
2634 *
2635 * Finds the first volume from the specified device.
2636 *
2637 * Returns: (transfer full): a #GPtrArray, or %NULL if the kind was not found
2638 *
2639 * Since: 1.5.1
2640 **/
2641FuVolume *
2642fu_common_get_volume_by_devnum (guint32 devnum, GError **error)
2643{
2644 g_autoptr(GPtrArray) devices = NULL;
2645
Richard Hughes6a489a92020-12-22 10:32:06 +00002646 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2647
Richard Hughes0bdf5612020-10-30 14:56:22 +00002648 /* find matching block device */
2649 devices = fu_common_get_block_devices (error);
2650 if (devices == NULL)
2651 return NULL;
2652 for (guint i = 0; i < devices->len; i++) {
2653 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
2654 g_autoptr(GVariant) val = NULL;
2655 val = g_dbus_proxy_get_cached_property (proxy_blk, "DeviceNumber");
2656 if (val == NULL)
2657 continue;
2658 if (devnum == g_variant_get_uint64 (val)) {
2659 return g_object_new (FU_TYPE_VOLUME,
2660 "proxy-block", proxy_blk,
2661 NULL);
2662 }
2663 }
2664
2665 /* failed */
2666 g_set_error (error,
2667 G_IO_ERROR,
2668 G_IO_ERROR_NOT_FOUND,
2669 "no volumes for devnum %u",
2670 devnum);
2671 return NULL;
2672}
2673
2674/**
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002675 * fu_common_get_esp_default:
2676 * @error: A #GError or NULL
2677 *
2678 * Gets the platform default ESP
2679 *
2680 * Returns: (transfer full): a #FuVolume, or %NULL if the ESP was not found
2681 *
2682 * Since: 1.4.6
2683 **/
2684FuVolume *
2685fu_common_get_esp_default (GError **error)
2686{
2687 const gchar *path_tmp;
Richard Hughes9d20bf92020-12-14 09:36:46 +00002688 gboolean has_internal = FALSE;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002689 g_autoptr(GPtrArray) volumes_fstab = g_ptr_array_new ();
2690 g_autoptr(GPtrArray) volumes_mtab = g_ptr_array_new ();
Mario Limonciello56d816a2020-11-11 16:59:30 -06002691 g_autoptr(GPtrArray) volumes_vfat = g_ptr_array_new ();
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002692 g_autoptr(GPtrArray) volumes = NULL;
Mario Limonciello56d816a2020-11-11 16:59:30 -06002693 g_autoptr(GError) error_local = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002694
Richard Hughes6a489a92020-12-22 10:32:06 +00002695 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2696
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002697 /* for the test suite use local directory for ESP */
2698 path_tmp = g_getenv ("FWUPD_UEFI_ESP_PATH");
2699 if (path_tmp != NULL)
2700 return fu_volume_new_from_mount_path (path_tmp);
2701
Mario Limonciello56d816a2020-11-11 16:59:30 -06002702 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_ESP, &error_local);
2703 if (volumes == NULL) {
2704 g_debug ("%s, falling back to %s", error_local->message, FU_VOLUME_KIND_BDP);
2705 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_BDP, error);
2706 if (volumes == NULL) {
2707 g_prefix_error (error, "%s: ", error_local->message);
2708 return NULL;
2709 }
2710 }
Richard Hughes9d20bf92020-12-14 09:36:46 +00002711
2712 /* are there _any_ internal vfat partitions?
2713 * remember HintSystem is just that -- a hint! */
2714 for (guint i = 0; i < volumes->len; i++) {
2715 FuVolume *vol = g_ptr_array_index (volumes, i);
2716 g_autofree gchar *type = fu_volume_get_id_type (vol);
2717 if (g_strcmp0 (type, "vfat") == 0 &&
2718 fu_volume_is_internal (vol)) {
2719 has_internal = TRUE;
2720 break;
2721 }
2722 }
2723
2724 /* filter to vfat partitions */
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002725 for (guint i = 0; i < volumes->len; i++) {
2726 FuVolume *vol = g_ptr_array_index (volumes, i);
Mario Limonciello56d816a2020-11-11 16:59:30 -06002727 g_autofree gchar *type = fu_volume_get_id_type (vol);
2728 if (type == NULL)
2729 continue;
Richard Hughes9d20bf92020-12-14 09:36:46 +00002730 if (has_internal && !fu_volume_is_internal (vol))
Mario Limonciello56d816a2020-11-11 16:59:30 -06002731 continue;
2732 if (g_strcmp0 (type, "vfat") == 0)
2733 g_ptr_array_add (volumes_vfat, vol);
2734 }
2735 if (volumes_vfat->len == 0) {
2736 g_set_error (error,
2737 G_IO_ERROR,
2738 G_IO_ERROR_INVALID_FILENAME,
2739 "No ESP found");
2740 return NULL;
2741 }
2742 for (guint i = 0; i < volumes_vfat->len; i++) {
2743 FuVolume *vol = g_ptr_array_index (volumes_vfat, i);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002744 g_ptr_array_add (fu_volume_is_mounted (vol) ? volumes_mtab : volumes_fstab, vol);
2745 }
2746 if (volumes_mtab->len == 1) {
2747 FuVolume *vol = g_ptr_array_index (volumes_mtab, 0);
2748 return g_object_ref (vol);
2749 }
2750 if (volumes_mtab->len == 0 && volumes_fstab->len == 1) {
2751 FuVolume *vol = g_ptr_array_index (volumes_fstab, 0);
2752 return g_object_ref (vol);
2753 }
2754 g_set_error (error,
2755 G_IO_ERROR,
2756 G_IO_ERROR_INVALID_FILENAME,
2757 "More than one available ESP");
2758 return NULL;
2759}
2760
2761/**
2762 * fu_common_get_esp_for_path:
2763 * @esp_path: A path to the ESP
2764 * @error: A #GError or NULL
2765 *
2766 * Gets the platform ESP using a UNIX or UDisks path
2767 *
2768 * Returns: (transfer full): a #FuVolume, or %NULL if the ESP was not found
2769 *
2770 * Since: 1.4.6
2771 **/
2772FuVolume *
2773fu_common_get_esp_for_path (const gchar *esp_path, GError **error)
2774{
Richard Hughes6a489a92020-12-22 10:32:06 +00002775 g_autofree gchar *basename = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002776 g_autoptr(GPtrArray) volumes = NULL;
2777
Richard Hughes6a489a92020-12-22 10:32:06 +00002778 g_return_val_if_fail (esp_path != NULL, NULL);
2779 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2780
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002781 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_ESP, error);
2782 if (volumes == NULL)
Richard Hughesb81140d2020-08-17 14:47:17 +01002783 return NULL;
Richard Hughes6a489a92020-12-22 10:32:06 +00002784 basename = g_path_get_basename (esp_path);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002785 for (guint i = 0; i < volumes->len; i++) {
2786 FuVolume *vol = g_ptr_array_index (volumes, i);
Mario Limonciello5a835632020-10-07 14:22:08 -05002787 g_autofree gchar *vol_basename = g_path_get_basename (fu_volume_get_mount_point (vol));
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002788 if (g_strcmp0 (basename, vol_basename) == 0)
2789 return g_object_ref (vol);
2790 }
2791 g_set_error (error,
2792 G_IO_ERROR,
2793 G_IO_ERROR_INVALID_FILENAME,
2794 "No ESP with path %s",
2795 esp_path);
2796 return NULL;
2797}
Richard Hughes6f5e35a2020-09-25 14:14:52 +01002798
2799/**
Richard Hughes44ae2a72020-09-25 18:00:21 +01002800 * fu_common_crc8:
2801 * @buf: memory buffer
2802 * @bufsz: sizeof buf
2803 *
2804 * Returns the cyclic redundancy check value for the given memory buffer.
2805 *
2806 * Returns: CRC value
2807 *
2808 * Since: 1.5.0
2809 **/
2810guint8
2811fu_common_crc8 (const guint8 *buf, gsize bufsz)
2812{
2813 guint32 crc = 0;
2814 for (gsize j = bufsz; j > 0; j--) {
2815 crc ^= (*(buf++) << 8);
2816 for (guint32 i = 8; i; i--) {
2817 if (crc & 0x8000)
2818 crc ^= (0x1070 << 3);
2819 crc <<= 1;
2820 }
2821 }
2822 return ~((guint8) (crc >> 8));
2823}
2824
2825/**
Richard Hughes6f5e35a2020-09-25 14:14:52 +01002826 * fu_common_crc16:
2827 * @buf: memory buffer
2828 * @bufsz: sizeof buf
2829 *
2830 * Returns the cyclic redundancy check value for the given memory buffer.
2831 *
2832 * Returns: CRC value
2833 *
2834 * Since: 1.5.0
2835 **/
2836guint16
2837fu_common_crc16 (const guint8 *buf, gsize bufsz)
2838{
2839 guint16 crc = 0xffff;
2840 for (gsize len = bufsz; len > 0; len--) {
2841 crc = (guint16) (crc ^ (*buf++));
2842 for (guint8 i = 0; i < 8; i++) {
2843 if (crc & 0x1) {
2844 crc = (crc >> 1) ^ 0xa001;
2845 } else {
2846 crc >>= 1;
2847 }
2848 }
2849 }
2850 return ~crc;
2851}
2852
2853/**
2854 * fu_common_crc32_full:
2855 * @buf: memory buffer
2856 * @bufsz: sizeof buf
2857 * @crc: initial CRC value, typically 0xFFFFFFFF
2858 * @polynomial: CRC polynomial, typically 0xEDB88320
2859 *
2860 * Returns the cyclic redundancy check value for the given memory buffer.
2861 *
2862 * Returns: CRC value
2863 *
2864 * Since: 1.5.0
2865 **/
2866guint32
2867fu_common_crc32_full (const guint8 *buf, gsize bufsz, guint32 crc, guint32 polynomial)
2868{
2869 for (guint32 idx = 0; idx < bufsz; idx++) {
2870 guint8 data = *buf++;
2871 crc = crc ^ data;
2872 for (guint32 bit = 0; bit < 8; bit++) {
2873 guint32 mask = -(crc & 1);
2874 crc = (crc >> 1) ^ (polynomial & mask);
2875 }
2876 }
2877 return ~crc;
2878}
2879
2880/**
2881 * fu_common_crc32:
2882 * @buf: memory buffer
2883 * @bufsz: sizeof buf
2884 *
2885 * Returns the cyclic redundancy check value for the given memory buffer.
2886 *
2887 * Returns: CRC value
2888 *
2889 * Since: 1.5.0
2890 **/
2891guint32
2892fu_common_crc32 (const guint8 *buf, gsize bufsz)
2893{
2894 return fu_common_crc32_full (buf, bufsz, 0xFFFFFFFF, 0xEDB88320);
2895}
Richard Hughesc7546672021-01-28 10:53:30 +00002896
2897/**
2898 * fu_common_uri_get_scheme:
2899 * @uri: valid URI, e.g. `https://foo.bar/baz`
2900 *
2901 * Returns the USI scheme for the given URI.
2902 *
2903 * Returns: scheme value, or %NULL if invalid, e.g. `https`
2904 *
2905 * Since: 1.5.6
2906 **/
2907gchar *
2908fu_common_uri_get_scheme (const gchar *uri)
2909{
2910 gchar *tmp;
2911
2912 g_return_val_if_fail (uri != NULL, NULL);
2913
2914 tmp = g_strstr_len (uri, -1, ":");
2915 if (tmp == NULL || tmp[0] == '\0')
2916 return NULL;
2917 return g_utf8_strdown (uri, tmp - uri);
2918}