blob: b4e4064ff0ccc7fc5abac45cb76677ad0ec361e4 [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 Hughes119d2602021-03-17 10:07:38 +000043#include "fu-firmware.h"
Richard Hughes8f0b2d12020-08-12 12:41:53 +010044#include "fu-volume-private.h"
45
Richard Hughes43417b22020-10-30 14:46:16 +000046#define UDISKS_DBUS_SERVICE "org.freedesktop.UDisks2"
47#define UDISKS_DBUS_PATH "/org/freedesktop/UDisks2/Manager"
48#define UDISKS_DBUS_MANAGER_INTERFACE "org.freedesktop.UDisks2.Manager"
49#define UDISKS_DBUS_INTERFACE_PARTITION "org.freedesktop.UDisks2.Partition"
50#define UDISKS_DBUS_INTERFACE_FILESYSTEM "org.freedesktop.UDisks2.Filesystem"
51#define UDISKS_DBUS_INTERFACE_BLOCK "org.freedesktop.UDisks2.Block"
Richard Hughes943d2c92017-06-21 09:04:39 +010052
53/**
Richard Hughes4eada342017-10-03 21:20:32 +010054 * SECTION:fu-common
55 * @short_description: common functionality for plugins to use
56 *
57 * Helper functions that can be used by the daemon and plugins.
58 *
59 * See also: #FuPlugin
60 */
61
62/**
Richard Hughes954dd9f2017-08-08 13:36:25 +010063 * fu_common_rmtree:
64 * @directory: a directory name
65 * @error: A #GError or %NULL
66 *
67 * Recursively removes a directory.
68 *
69 * Returns: %TRUE for success, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -060070 *
71 * Since: 0.9.7
Richard Hughes954dd9f2017-08-08 13:36:25 +010072 **/
73gboolean
74fu_common_rmtree (const gchar *directory, GError **error)
75{
76 const gchar *filename;
77 g_autoptr(GDir) dir = NULL;
78
Richard Hughes6a489a92020-12-22 10:32:06 +000079 g_return_val_if_fail (directory != NULL, FALSE);
80 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
81
Richard Hughes954dd9f2017-08-08 13:36:25 +010082 /* try to open */
Richard Hughes455fdd32017-08-16 12:26:44 +010083 g_debug ("removing %s", directory);
Richard Hughes954dd9f2017-08-08 13:36:25 +010084 dir = g_dir_open (directory, 0, error);
85 if (dir == NULL)
86 return FALSE;
87
88 /* find each */
89 while ((filename = g_dir_read_name (dir))) {
90 g_autofree gchar *src = NULL;
91 src = g_build_filename (directory, filename, NULL);
92 if (g_file_test (src, G_FILE_TEST_IS_DIR)) {
93 if (!fu_common_rmtree (src, error))
94 return FALSE;
95 } else {
96 if (g_unlink (src) != 0) {
97 g_set_error (error,
98 FWUPD_ERROR,
99 FWUPD_ERROR_INTERNAL,
100 "Failed to delete: %s", src);
101 return FALSE;
102 }
103 }
104 }
105 if (g_remove (directory) != 0) {
106 g_set_error (error,
107 FWUPD_ERROR,
108 FWUPD_ERROR_INTERNAL,
109 "Failed to delete: %s", directory);
110 return FALSE;
111 }
112 return TRUE;
113}
114
Richard Hughes89e968b2018-03-07 10:01:08 +0000115static gboolean
116fu_common_get_file_list_internal (GPtrArray *files, const gchar *directory, GError **error)
117{
118 const gchar *filename;
119 g_autoptr(GDir) dir = NULL;
120
121 /* try to open */
122 dir = g_dir_open (directory, 0, error);
123 if (dir == NULL)
124 return FALSE;
125
126 /* find each */
127 while ((filename = g_dir_read_name (dir))) {
128 g_autofree gchar *src = g_build_filename (directory, filename, NULL);
129 if (g_file_test (src, G_FILE_TEST_IS_DIR)) {
130 if (!fu_common_get_file_list_internal (files, src, error))
131 return FALSE;
132 } else {
133 g_ptr_array_add (files, g_steal_pointer (&src));
134 }
135 }
136 return TRUE;
137
138}
139
140/**
141 * fu_common_get_files_recursive:
Richard Hughes8aa72392018-05-02 08:38:43 +0100142 * @path: a directory name
Richard Hughes89e968b2018-03-07 10:01:08 +0000143 * @error: A #GError or %NULL
144 *
145 * Returns every file found under @directory, and any subdirectory.
146 * If any path under @directory cannot be accessed due to permissions an error
147 * will be returned.
148 *
Richard Hughesa0d81c72019-11-27 11:41:54 +0000149 * Returns: (transfer container) (element-type utf8): array of files, or %NULL for error
Mario Limonciello1a680f32019-11-25 19:44:53 -0600150 *
151 * Since: 1.0.6
Richard Hughes89e968b2018-03-07 10:01:08 +0000152 **/
153GPtrArray *
154fu_common_get_files_recursive (const gchar *path, GError **error)
155{
156 g_autoptr(GPtrArray) files = g_ptr_array_new_with_free_func (g_free);
Richard Hughes6a489a92020-12-22 10:32:06 +0000157
158 g_return_val_if_fail (path != NULL, NULL);
159 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
160
Richard Hughes89e968b2018-03-07 10:01:08 +0000161 if (!fu_common_get_file_list_internal (files, path, error))
162 return NULL;
163 return g_steal_pointer (&files);
164}
Richard Hughes954dd9f2017-08-08 13:36:25 +0100165/**
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100166 * fu_common_mkdir_parent:
167 * @filename: A full pathname
168 * @error: A #GError, or %NULL
169 *
170 * Creates any required directories, including any parent directories.
171 *
172 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600173 *
174 * Since: 0.9.7
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100175 **/
176gboolean
177fu_common_mkdir_parent (const gchar *filename, GError **error)
178{
179 g_autofree gchar *parent = NULL;
Richard Hughes455fdd32017-08-16 12:26:44 +0100180
Richard Hughes6a489a92020-12-22 10:32:06 +0000181 g_return_val_if_fail (filename != NULL, FALSE);
182 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
183
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100184 parent = g_path_get_dirname (filename);
Mario Limonciellod4155ff2020-09-28 15:20:07 -0500185 if (!g_file_test (parent, G_FILE_TEST_IS_DIR))
186 g_debug ("creating path %s", parent);
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100187 if (g_mkdir_with_parents (parent, 0755) == -1) {
188 g_set_error (error,
189 FWUPD_ERROR,
190 FWUPD_ERROR_INTERNAL,
191 "Failed to create '%s': %s",
192 parent, g_strerror (errno));
193 return FALSE;
194 }
195 return TRUE;
196}
197
198/**
Richard Hughes943d2c92017-06-21 09:04:39 +0100199 * fu_common_set_contents_bytes:
200 * @filename: A filename
201 * @bytes: The data to write
202 * @error: A #GError, or %NULL
203 *
204 * Writes a blob of data to a filename, creating the parent directories as
205 * required.
206 *
207 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600208 *
209 * Since: 0.9.5
Richard Hughes943d2c92017-06-21 09:04:39 +0100210 **/
211gboolean
212fu_common_set_contents_bytes (const gchar *filename, GBytes *bytes, GError **error)
213{
214 const gchar *data;
215 gsize size;
216 g_autoptr(GFile) file = NULL;
217 g_autoptr(GFile) file_parent = NULL;
218
Richard Hughes6a489a92020-12-22 10:32:06 +0000219 g_return_val_if_fail (filename != NULL, FALSE);
220 g_return_val_if_fail (bytes != NULL, FALSE);
221 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
222
Richard Hughes943d2c92017-06-21 09:04:39 +0100223 file = g_file_new_for_path (filename);
224 file_parent = g_file_get_parent (file);
225 if (!g_file_query_exists (file_parent, NULL)) {
226 if (!g_file_make_directory_with_parents (file_parent, NULL, error))
227 return FALSE;
228 }
229 data = g_bytes_get_data (bytes, &size);
Richard Hughes455fdd32017-08-16 12:26:44 +0100230 g_debug ("writing %s with %" G_GSIZE_FORMAT " bytes", filename, size);
Richard Hughes943d2c92017-06-21 09:04:39 +0100231 return g_file_set_contents (filename, data, size, error);
232}
233
Richard Hughesd0d2ae62017-08-08 12:22:30 +0100234/**
235 * fu_common_get_contents_bytes:
236 * @filename: A filename
237 * @error: A #GError, or %NULL
238 *
239 * Reads a blob of data from a file.
240 *
241 * Returns: a #GBytes, or %NULL for failure
Mario Limonciello1a680f32019-11-25 19:44:53 -0600242 *
243 * Since: 0.9.7
Richard Hughesd0d2ae62017-08-08 12:22:30 +0100244 **/
245GBytes *
246fu_common_get_contents_bytes (const gchar *filename, GError **error)
247{
248 gchar *data = NULL;
249 gsize len = 0;
Richard Hughes6a489a92020-12-22 10:32:06 +0000250
251 g_return_val_if_fail (filename != NULL, NULL);
252 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
253
Richard Hughesd0d2ae62017-08-08 12:22:30 +0100254 if (!g_file_get_contents (filename, &data, &len, error))
255 return NULL;
Richard Hughes455fdd32017-08-16 12:26:44 +0100256 g_debug ("reading %s with %" G_GSIZE_FORMAT " bytes", filename, len);
Richard Hughesd0d2ae62017-08-08 12:22:30 +0100257 return g_bytes_new_take (data, len);
258}
Richard Hughes943d2c92017-06-21 09:04:39 +0100259
260/**
261 * fu_common_get_contents_fd:
262 * @fd: A file descriptor
263 * @count: The maximum number of bytes to read
264 * @error: A #GError, or %NULL
265 *
266 * Reads a blob from a specific file descriptor.
267 *
268 * Note: this will close the fd when done
269 *
Richard Hughes4eada342017-10-03 21:20:32 +0100270 * Returns: (transfer full): a #GBytes, or %NULL
Mario Limonciello1a680f32019-11-25 19:44:53 -0600271 *
272 * Since: 0.9.5
Richard Hughes943d2c92017-06-21 09:04:39 +0100273 **/
274GBytes *
275fu_common_get_contents_fd (gint fd, gsize count, GError **error)
276{
Richard Hughes9e5675e2019-11-22 09:35:03 +0000277#ifdef HAVE_GIO_UNIX
Richard Hughes97ad3352021-01-14 20:07:47 +0000278 guint8 tmp[0x8000] = { 0x0 };
279 g_autoptr(GByteArray) buf = g_byte_array_new ();
Richard Hughes943d2c92017-06-21 09:04:39 +0100280 g_autoptr(GError) error_local = NULL;
281 g_autoptr(GInputStream) stream = NULL;
282
283 g_return_val_if_fail (fd > 0, NULL);
Richard Hughes943d2c92017-06-21 09:04:39 +0100284 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
285
Richard Hughes919f8ab2018-02-14 10:24:56 +0000286 /* this is invalid */
287 if (count == 0) {
288 g_set_error_literal (error,
289 FWUPD_ERROR,
290 FWUPD_ERROR_NOT_SUPPORTED,
291 "A maximum read size must be specified");
292 return NULL;
293 }
294
Richard Hughes943d2c92017-06-21 09:04:39 +0100295 /* read the entire fd to a data blob */
296 stream = g_unix_input_stream_new (fd, TRUE);
Richard Hughes97ad3352021-01-14 20:07:47 +0000297
298 /* read from stream in 32kB chunks */
299 while (TRUE) {
300 gssize sz;
301 sz = g_input_stream_read (stream, tmp, sizeof(tmp), NULL, &error_local);
302 if (sz == 0)
303 break;
304 if (sz < 0) {
305 g_set_error_literal (error,
306 FWUPD_ERROR,
307 FWUPD_ERROR_INVALID_FILE,
308 error_local->message);
309 return NULL;
310 }
311 g_byte_array_append (buf, tmp, sz);
312 if (buf->len > count) {
313 g_set_error (error,
Richard Hughes943d2c92017-06-21 09:04:39 +0100314 FWUPD_ERROR,
315 FWUPD_ERROR_INVALID_FILE,
Richard Hughes97ad3352021-01-14 20:07:47 +0000316 "cannot read from fd: 0x%x > 0x%x",
317 buf->len, (guint) count);
318 return NULL;
319 }
Richard Hughes943d2c92017-06-21 09:04:39 +0100320 }
Richard Hughes97ad3352021-01-14 20:07:47 +0000321 return g_byte_array_free_to_bytes (g_steal_pointer (&buf));
Richard Hughes9e5675e2019-11-22 09:35:03 +0000322#else
323 g_set_error_literal (error,
324 FWUPD_ERROR,
325 FWUPD_ERROR_NOT_SUPPORTED,
326 "Not supported as <glib-unix.h> is unavailable");
327 return NULL;
328#endif
Richard Hughes943d2c92017-06-21 09:04:39 +0100329}
Richard Hughes94f939a2017-08-08 12:21:39 +0100330
Richard Hughes5add3a72021-01-13 19:25:10 +0000331#ifdef HAVE_LIBARCHIVE
Richard Hughes94f939a2017-08-08 12:21:39 +0100332static gboolean
333fu_common_extract_archive_entry (struct archive_entry *entry, const gchar *dir)
334{
335 const gchar *tmp;
336 g_autofree gchar *buf = NULL;
337
338 /* no output file */
339 if (archive_entry_pathname (entry) == NULL)
340 return FALSE;
341
342 /* update output path */
343 tmp = archive_entry_pathname (entry);
344 buf = g_build_filename (dir, tmp, NULL);
345 archive_entry_update_pathname_utf8 (entry, buf);
346 return TRUE;
347}
Richard Hughes5add3a72021-01-13 19:25:10 +0000348#endif
Richard Hughes94f939a2017-08-08 12:21:39 +0100349
350/**
351 * fu_common_extract_archive:
352 * @blob: a #GBytes archive as a blob
Richard Hughes4eada342017-10-03 21:20:32 +0100353 * @dir: a directory name to extract to
Richard Hughes94f939a2017-08-08 12:21:39 +0100354 * @error: A #GError, or %NULL
355 *
Richard Hughes21eaeef2020-01-14 12:10:01 +0000356 * Extracts an archive to a directory.
Richard Hughes94f939a2017-08-08 12:21:39 +0100357 *
358 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600359 *
360 * Since: 0.9.7
Richard Hughes94f939a2017-08-08 12:21:39 +0100361 **/
362gboolean
363fu_common_extract_archive (GBytes *blob, const gchar *dir, GError **error)
364{
Richard Hughes5add3a72021-01-13 19:25:10 +0000365#ifdef HAVE_LIBARCHIVE
Richard Hughes94f939a2017-08-08 12:21:39 +0100366 gboolean ret = TRUE;
367 int r;
368 struct archive *arch = NULL;
369 struct archive_entry *entry;
370
Richard Hughes6a489a92020-12-22 10:32:06 +0000371 g_return_val_if_fail (blob != NULL, FALSE);
372 g_return_val_if_fail (dir != NULL, FALSE);
373 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
374
Richard Hughes94f939a2017-08-08 12:21:39 +0100375 /* decompress anything matching either glob */
Richard Hughes455fdd32017-08-16 12:26:44 +0100376 g_debug ("decompressing into %s", dir);
Richard Hughes94f939a2017-08-08 12:21:39 +0100377 arch = archive_read_new ();
378 archive_read_support_format_all (arch);
379 archive_read_support_filter_all (arch);
380 r = archive_read_open_memory (arch,
381 (void *) g_bytes_get_data (blob, NULL),
382 (size_t) g_bytes_get_size (blob));
383 if (r != 0) {
384 ret = FALSE;
385 g_set_error (error,
386 FWUPD_ERROR,
387 FWUPD_ERROR_INTERNAL,
388 "Cannot open: %s",
389 archive_error_string (arch));
390 goto out;
391 }
392 for (;;) {
393 gboolean valid;
Richard Hughes94f939a2017-08-08 12:21:39 +0100394 r = archive_read_next_header (arch, &entry);
395 if (r == ARCHIVE_EOF)
396 break;
397 if (r != ARCHIVE_OK) {
398 ret = FALSE;
399 g_set_error (error,
400 FWUPD_ERROR,
401 FWUPD_ERROR_INTERNAL,
402 "Cannot read header: %s",
403 archive_error_string (arch));
404 goto out;
405 }
406
407 /* only extract if valid */
408 valid = fu_common_extract_archive_entry (entry, dir);
409 if (!valid)
410 continue;
411 r = archive_read_extract (arch, entry, 0);
412 if (r != ARCHIVE_OK) {
413 ret = FALSE;
414 g_set_error (error,
415 FWUPD_ERROR,
416 FWUPD_ERROR_INTERNAL,
417 "Cannot extract: %s",
418 archive_error_string (arch));
419 goto out;
420 }
421 }
422out:
423 if (arch != NULL) {
424 archive_read_close (arch);
425 archive_read_free (arch);
426 }
427 return ret;
Richard Hughes5add3a72021-01-13 19:25:10 +0000428#else
429 g_set_error_literal (error,
430 FWUPD_ERROR,
431 FWUPD_ERROR_NOT_SUPPORTED,
432 "missing libarchive support");
433 return FALSE;
434#endif
Richard Hughes94f939a2017-08-08 12:21:39 +0100435}
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100436
437static void
Yehezkel Bernate43f7fb2017-08-30 12:09:34 +0300438fu_common_add_argv (GPtrArray *argv, const gchar *fmt, ...) G_GNUC_PRINTF (2, 3);
439
440static void
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100441fu_common_add_argv (GPtrArray *argv, const gchar *fmt, ...)
442{
443 va_list args;
444 g_autofree gchar *tmp = NULL;
445 g_auto(GStrv) split = NULL;
446
447 va_start (args, fmt);
448 tmp = g_strdup_vprintf (fmt, args);
449 va_end (args);
450
451 split = g_strsplit (tmp, " ", -1);
452 for (guint i = 0; split[i] != NULL; i++)
453 g_ptr_array_add (argv, g_strdup (split[i]));
454}
455
Mario Limonciello1a680f32019-11-25 19:44:53 -0600456/**
457 * fu_common_find_program_in_path:
458 * @basename: The program to search
459 * @error: A #GError, or %NULL
460 *
461 * Looks for a program in the PATH variable
462 *
463 * Returns: a new #gchar, or %NULL for error
464 *
465 * Since: 1.1.2
466 **/
Richard Hughes22367e72018-08-30 10:24:04 +0100467gchar *
468fu_common_find_program_in_path (const gchar *basename, GError **error)
469{
470 gchar *fn = g_find_program_in_path (basename);
471 if (fn == NULL) {
472 g_set_error (error,
473 FWUPD_ERROR,
474 FWUPD_ERROR_NOT_SUPPORTED,
475 "missing executable %s in PATH",
476 basename);
477 return NULL;
478 }
479 return fn;
480}
481
482static gboolean
483fu_common_test_namespace_support (GError **error)
484{
485 /* test if CONFIG_USER_NS is valid */
486 if (!g_file_test ("/proc/self/ns/user", G_FILE_TEST_IS_SYMLINK)) {
487 g_set_error (error,
488 FWUPD_ERROR,
489 FWUPD_ERROR_NOT_SUPPORTED,
490 "missing CONFIG_USER_NS in kernel");
491 return FALSE;
492 }
493 if (g_file_test ("/proc/sys/kernel/unprivileged_userns_clone", G_FILE_TEST_EXISTS)) {
494 g_autofree gchar *clone = NULL;
495 if (!g_file_get_contents ("/proc/sys/kernel/unprivileged_userns_clone", &clone, NULL, error))
496 return FALSE;
497 if (g_ascii_strtoll (clone, NULL, 10) == 0) {
498 g_set_error (error,
499 FWUPD_ERROR,
500 FWUPD_ERROR_NOT_SUPPORTED,
501 "unprivileged user namespace clones disabled by distro");
502 return FALSE;
503 }
504 }
505 return TRUE;
506}
507
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100508/**
509 * fu_common_firmware_builder:
510 * @bytes: The data to use
Richard Hughes4eada342017-10-03 21:20:32 +0100511 * @script_fn: Name of the script to run in the tarball, e.g. `startup.sh`
512 * @output_fn: Name of the generated firmware, e.g. `firmware.bin`
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100513 * @error: A #GError, or %NULL
514 *
515 * Builds a firmware file using tools from the host session in a bubblewrap
516 * jail. Several things happen during build:
517 *
518 * 1. The @bytes data is untarred to a temporary location
519 * 2. A bubblewrap container is set up
520 * 3. The startup.sh script is run inside the container
521 * 4. The firmware.bin is extracted from the container
522 * 5. The temporary location is deleted
523 *
524 * Returns: a new #GBytes, or %NULL for error
Mario Limonciello1a680f32019-11-25 19:44:53 -0600525 *
526 * Since: 0.9.7
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100527 **/
528GBytes *
529fu_common_firmware_builder (GBytes *bytes,
530 const gchar *script_fn,
531 const gchar *output_fn,
532 GError **error)
533{
534 gint rc = 0;
535 g_autofree gchar *argv_str = NULL;
Mario Limonciello37b59582018-08-13 08:38:01 -0500536 g_autofree gchar *bwrap_fn = NULL;
Richard Hughes4be17d12018-05-30 20:36:29 +0100537 g_autofree gchar *localstatebuilderdir = NULL;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100538 g_autofree gchar *localstatedir = NULL;
539 g_autofree gchar *output2_fn = NULL;
540 g_autofree gchar *standard_error = NULL;
541 g_autofree gchar *standard_output = NULL;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100542 g_autofree gchar *tmpdir = NULL;
543 g_autoptr(GBytes) firmware_blob = NULL;
544 g_autoptr(GPtrArray) argv = g_ptr_array_new_with_free_func (g_free);
545
546 g_return_val_if_fail (bytes != NULL, NULL);
547 g_return_val_if_fail (script_fn != NULL, NULL);
548 g_return_val_if_fail (output_fn != NULL, NULL);
549 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
550
Mario Limonciello37b59582018-08-13 08:38:01 -0500551 /* find bwrap in the path */
Richard Hughes22367e72018-08-30 10:24:04 +0100552 bwrap_fn = fu_common_find_program_in_path ("bwrap", error);
553 if (bwrap_fn == NULL)
Richard Hughesddb3e202018-08-23 11:29:57 +0100554 return NULL;
Mario Limonciello37b59582018-08-13 08:38:01 -0500555
556 /* test if CONFIG_USER_NS is valid */
Richard Hughes22367e72018-08-30 10:24:04 +0100557 if (!fu_common_test_namespace_support (error))
Richard Hughesddb3e202018-08-23 11:29:57 +0100558 return NULL;
Mario Limonciello37b59582018-08-13 08:38:01 -0500559
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100560 /* untar file to temp location */
561 tmpdir = g_dir_make_tmp ("fwupd-gen-XXXXXX", error);
562 if (tmpdir == NULL)
563 return NULL;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100564 if (!fu_common_extract_archive (bytes, tmpdir, error))
565 return NULL;
566
567 /* this is shared with the plugins */
Richard Hughes4be17d12018-05-30 20:36:29 +0100568 localstatedir = fu_common_get_path (FU_PATH_KIND_LOCALSTATEDIR_PKG);
569 localstatebuilderdir = g_build_filename (localstatedir, "builder", NULL);
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100570
571 /* launch bubblewrap and generate firmware */
Mario Limonciello37b59582018-08-13 08:38:01 -0500572 g_ptr_array_add (argv, g_steal_pointer (&bwrap_fn));
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100573 fu_common_add_argv (argv, "--die-with-parent");
574 fu_common_add_argv (argv, "--ro-bind /usr /usr");
Mario Limonciellob8215572018-07-13 09:49:55 -0500575 fu_common_add_argv (argv, "--ro-bind /lib /lib");
Mario Limoncielloed4e9122020-12-15 20:26:50 -0600576 fu_common_add_argv (argv, "--ro-bind-try /lib64 /lib64");
Mario Limonciellob8215572018-07-13 09:49:55 -0500577 fu_common_add_argv (argv, "--ro-bind /bin /bin");
578 fu_common_add_argv (argv, "--ro-bind /sbin /sbin");
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100579 fu_common_add_argv (argv, "--dir /tmp");
580 fu_common_add_argv (argv, "--dir /var");
581 fu_common_add_argv (argv, "--bind %s /tmp", tmpdir);
Richard Hughes4be17d12018-05-30 20:36:29 +0100582 if (g_file_test (localstatebuilderdir, G_FILE_TEST_EXISTS))
583 fu_common_add_argv (argv, "--ro-bind %s /boot", localstatebuilderdir);
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100584 fu_common_add_argv (argv, "--dev /dev");
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100585 fu_common_add_argv (argv, "--chdir /tmp");
586 fu_common_add_argv (argv, "--unshare-all");
Richard Hughes443e4092017-08-09 16:07:31 +0100587 fu_common_add_argv (argv, "/tmp/%s", script_fn);
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100588 g_ptr_array_add (argv, NULL);
589 argv_str = g_strjoinv (" ", (gchar **) argv->pdata);
590 g_debug ("running '%s' in %s", argv_str, tmpdir);
591 if (!g_spawn_sync ("/tmp",
592 (gchar **) argv->pdata,
593 NULL,
Richard Hughesf6f72a42017-08-09 16:25:25 +0100594 G_SPAWN_SEARCH_PATH,
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100595 NULL, NULL, /* child_setup */
596 &standard_output,
597 &standard_error,
598 &rc,
599 error)) {
600 g_prefix_error (error, "failed to run '%s': ", argv_str);
601 return NULL;
602 }
603 if (standard_output != NULL && standard_output[0] != '\0')
604 g_debug ("console output was: %s", standard_output);
605 if (rc != 0) {
Mario Limonciello37b59582018-08-13 08:38:01 -0500606 FwupdError code = FWUPD_ERROR_INTERNAL;
607 if (errno == ENOTTY)
608 code = FWUPD_ERROR_PERMISSION_DENIED;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100609 g_set_error (error,
610 FWUPD_ERROR,
Mario Limonciello37b59582018-08-13 08:38:01 -0500611 code,
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100612 "failed to build firmware: %s",
613 standard_error);
614 return NULL;
615 }
616
617 /* get generated file */
618 output2_fn = g_build_filename (tmpdir, output_fn, NULL);
619 firmware_blob = fu_common_get_contents_bytes (output2_fn, error);
620 if (firmware_blob == NULL)
621 return NULL;
622
623 /* cleanup temp directory */
624 if (!fu_common_rmtree (tmpdir, error))
625 return NULL;
626
627 /* success */
628 return g_steal_pointer (&firmware_blob);
629}
Richard Hughes049ccc82017-08-09 15:26:56 +0100630
631typedef struct {
632 FuOutputHandler handler_cb;
633 gpointer handler_user_data;
634 GMainLoop *loop;
635 GSource *source;
636 GInputStream *stream;
637 GCancellable *cancellable;
Richard Hughesb768e4d2019-02-26 13:55:18 +0000638 guint timeout_id;
Richard Hughes049ccc82017-08-09 15:26:56 +0100639} FuCommonSpawnHelper;
640
641static void fu_common_spawn_create_pollable_source (FuCommonSpawnHelper *helper);
642
643static gboolean
644fu_common_spawn_source_pollable_cb (GObject *stream, gpointer user_data)
645{
646 FuCommonSpawnHelper *helper = (FuCommonSpawnHelper *) user_data;
647 gchar buffer[1024];
648 gssize sz;
649 g_auto(GStrv) split = NULL;
650 g_autoptr(GError) error = NULL;
651
652 /* read from stream */
653 sz = g_pollable_input_stream_read_nonblocking (G_POLLABLE_INPUT_STREAM (stream),
654 buffer,
655 sizeof(buffer) - 1,
656 NULL,
657 &error);
658 if (sz < 0) {
Richard Hughes67cbe642017-08-16 12:26:14 +0100659 if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
660 g_warning ("failed to get read from nonblocking fd: %s",
661 error->message);
662 }
Richard Hughes049ccc82017-08-09 15:26:56 +0100663 return G_SOURCE_REMOVE;
664 }
665
666 /* no read possible */
667 if (sz == 0)
668 g_main_loop_quit (helper->loop);
669
670 /* emit lines */
671 if (helper->handler_cb != NULL) {
672 buffer[sz] = '\0';
673 split = g_strsplit (buffer, "\n", -1);
674 for (guint i = 0; split[i] != NULL; i++) {
675 if (split[i][0] == '\0')
676 continue;
677 helper->handler_cb (split[i], helper->handler_user_data);
678 }
679 }
680
681 /* set up the source for the next read */
682 fu_common_spawn_create_pollable_source (helper);
683 return G_SOURCE_REMOVE;
684}
685
686static void
687fu_common_spawn_create_pollable_source (FuCommonSpawnHelper *helper)
688{
689 if (helper->source != NULL)
690 g_source_destroy (helper->source);
691 helper->source = g_pollable_input_stream_create_source (G_POLLABLE_INPUT_STREAM (helper->stream),
692 helper->cancellable);
693 g_source_attach (helper->source, NULL);
694 g_source_set_callback (helper->source, (GSourceFunc) fu_common_spawn_source_pollable_cb, helper, NULL);
695}
696
697static void
698fu_common_spawn_helper_free (FuCommonSpawnHelper *helper)
699{
Richard Hughesb768e4d2019-02-26 13:55:18 +0000700 g_object_unref (helper->cancellable);
Richard Hughes049ccc82017-08-09 15:26:56 +0100701 if (helper->stream != NULL)
702 g_object_unref (helper->stream);
703 if (helper->source != NULL)
704 g_source_destroy (helper->source);
705 if (helper->loop != NULL)
706 g_main_loop_unref (helper->loop);
Richard Hughesb768e4d2019-02-26 13:55:18 +0000707 if (helper->timeout_id != 0)
708 g_source_remove (helper->timeout_id);
Richard Hughes049ccc82017-08-09 15:26:56 +0100709 g_free (helper);
710}
711
Mario Limoncielloa98df552018-04-16 12:15:51 -0500712#pragma clang diagnostic push
713#pragma clang diagnostic ignored "-Wunused-function"
Richard Hughes049ccc82017-08-09 15:26:56 +0100714G_DEFINE_AUTOPTR_CLEANUP_FUNC(FuCommonSpawnHelper, fu_common_spawn_helper_free)
Mario Limoncielloa98df552018-04-16 12:15:51 -0500715#pragma clang diagnostic pop
Richard Hughes049ccc82017-08-09 15:26:56 +0100716
Richard Hughesb768e4d2019-02-26 13:55:18 +0000717static gboolean
718fu_common_spawn_timeout_cb (gpointer user_data)
719{
720 FuCommonSpawnHelper *helper = (FuCommonSpawnHelper *) user_data;
721 g_cancellable_cancel (helper->cancellable);
722 g_main_loop_quit (helper->loop);
723 helper->timeout_id = 0;
724 return G_SOURCE_REMOVE;
725}
726
727static void
728fu_common_spawn_cancelled_cb (GCancellable *cancellable, FuCommonSpawnHelper *helper)
729{
730 /* just propagate */
731 g_cancellable_cancel (helper->cancellable);
732}
733
Richard Hughes049ccc82017-08-09 15:26:56 +0100734/**
735 * fu_common_spawn_sync:
736 * @argv: The argument list to run
Richard Hughes4eada342017-10-03 21:20:32 +0100737 * @handler_cb: (scope call): A #FuOutputHandler or %NULL
738 * @handler_user_data: the user data to pass to @handler_cb
Richard Hughesb768e4d2019-02-26 13:55:18 +0000739 * @timeout_ms: a timeout in ms, or 0 for no limit
Richard Hughes049ccc82017-08-09 15:26:56 +0100740 * @cancellable: a #GCancellable, or %NULL
741 * @error: A #GError or %NULL
742 *
743 * Runs a subprocess and waits for it to exit. Any output on standard out or
744 * standard error will be forwarded to @handler_cb as whole lines.
745 *
746 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600747 *
748 * Since: 0.9.7
Richard Hughes049ccc82017-08-09 15:26:56 +0100749 **/
750gboolean
751fu_common_spawn_sync (const gchar * const * argv,
752 FuOutputHandler handler_cb,
753 gpointer handler_user_data,
Richard Hughesb768e4d2019-02-26 13:55:18 +0000754 guint timeout_ms,
Richard Hughes049ccc82017-08-09 15:26:56 +0100755 GCancellable *cancellable, GError **error)
756{
757 g_autoptr(FuCommonSpawnHelper) helper = NULL;
758 g_autoptr(GSubprocess) subprocess = NULL;
Richard Hughes455fdd32017-08-16 12:26:44 +0100759 g_autofree gchar *argv_str = NULL;
Richard Hughesb768e4d2019-02-26 13:55:18 +0000760 gulong cancellable_id = 0;
Richard Hughes049ccc82017-08-09 15:26:56 +0100761
Richard Hughes6a489a92020-12-22 10:32:06 +0000762 g_return_val_if_fail (argv != NULL, FALSE);
763 g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
764 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
765
Richard Hughes049ccc82017-08-09 15:26:56 +0100766 /* create subprocess */
Richard Hughes455fdd32017-08-16 12:26:44 +0100767 argv_str = g_strjoinv (" ", (gchar **) argv);
768 g_debug ("running '%s'", argv_str);
Richard Hughes049ccc82017-08-09 15:26:56 +0100769 subprocess = g_subprocess_newv (argv, G_SUBPROCESS_FLAGS_STDOUT_PIPE |
770 G_SUBPROCESS_FLAGS_STDERR_MERGE, error);
771 if (subprocess == NULL)
772 return FALSE;
773
774 /* watch for process to exit */
775 helper = g_new0 (FuCommonSpawnHelper, 1);
776 helper->handler_cb = handler_cb;
777 helper->handler_user_data = handler_user_data;
778 helper->loop = g_main_loop_new (NULL, FALSE);
779 helper->stream = g_subprocess_get_stdout_pipe (subprocess);
Richard Hughesb768e4d2019-02-26 13:55:18 +0000780
781 /* always create a cancellable, and connect up the parent */
782 helper->cancellable = g_cancellable_new ();
783 if (cancellable != NULL) {
784 cancellable_id = g_cancellable_connect (cancellable,
785 G_CALLBACK (fu_common_spawn_cancelled_cb),
786 helper, NULL);
787 }
788
789 /* allow timeout */
790 if (timeout_ms > 0) {
791 helper->timeout_id = g_timeout_add (timeout_ms,
792 fu_common_spawn_timeout_cb,
793 helper);
794 }
Richard Hughes049ccc82017-08-09 15:26:56 +0100795 fu_common_spawn_create_pollable_source (helper);
796 g_main_loop_run (helper->loop);
Richard Hughesb768e4d2019-02-26 13:55:18 +0000797 g_cancellable_disconnect (cancellable, cancellable_id);
798 if (g_cancellable_set_error_if_cancelled (helper->cancellable, error))
799 return FALSE;
Richard Hughes049ccc82017-08-09 15:26:56 +0100800 return g_subprocess_wait_check (subprocess, cancellable, error);
801}
Richard Hughesae252cd2017-12-08 10:48:15 +0000802
803/**
804 * fu_common_write_uint16:
805 * @buf: A writable buffer
806 * @val_native: a value in host byte-order
Richard Hughes8aa72392018-05-02 08:38:43 +0100807 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000808 *
809 * Writes a value to a buffer using a specified endian.
Mario Limonciello1a680f32019-11-25 19:44:53 -0600810 *
811 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000812 **/
813void
814fu_common_write_uint16 (guint8 *buf, guint16 val_native, FuEndianType endian)
815{
816 guint16 val_hw;
817 switch (endian) {
818 case G_BIG_ENDIAN:
819 val_hw = GUINT16_TO_BE(val_native);
820 break;
821 case G_LITTLE_ENDIAN:
822 val_hw = GUINT16_TO_LE(val_native);
823 break;
824 default:
825 g_assert_not_reached ();
826 }
827 memcpy (buf, &val_hw, sizeof(val_hw));
828}
829
830/**
831 * fu_common_write_uint32:
832 * @buf: A writable buffer
833 * @val_native: a value in host byte-order
Richard Hughes8aa72392018-05-02 08:38:43 +0100834 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000835 *
836 * Writes a value to a buffer using a specified endian.
Mario Limonciello1a680f32019-11-25 19:44:53 -0600837 *
838 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000839 **/
840void
841fu_common_write_uint32 (guint8 *buf, guint32 val_native, FuEndianType endian)
842{
843 guint32 val_hw;
844 switch (endian) {
845 case G_BIG_ENDIAN:
846 val_hw = GUINT32_TO_BE(val_native);
847 break;
848 case G_LITTLE_ENDIAN:
849 val_hw = GUINT32_TO_LE(val_native);
850 break;
851 default:
852 g_assert_not_reached ();
853 }
854 memcpy (buf, &val_hw, sizeof(val_hw));
855}
856
857/**
Richard Hughesf2849d22021-03-05 17:19:17 +0000858 * fu_common_write_uint64:
859 * @buf: A writable buffer
860 * @val_native: a value in host byte-order
861 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
862 *
863 * Writes a value to a buffer using a specified endian.
864 *
865 * Since: 1.5.8
866 **/
867void
868fu_common_write_uint64 (guint8 *buf, guint64 val_native, FuEndianType endian)
869{
870 guint64 val_hw;
871 switch (endian) {
872 case G_BIG_ENDIAN:
873 val_hw = GUINT64_TO_BE(val_native);
874 break;
875 case G_LITTLE_ENDIAN:
876 val_hw = GUINT64_TO_LE(val_native);
877 break;
878 default:
879 g_assert_not_reached ();
880 }
881 memcpy (buf, &val_hw, sizeof(val_hw));
882}
883
884/**
Richard Hughesae252cd2017-12-08 10:48:15 +0000885 * fu_common_read_uint16:
886 * @buf: A readable buffer
Richard Hughes8aa72392018-05-02 08:38:43 +0100887 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000888 *
889 * Read a value from a buffer using a specified endian.
890 *
891 * Returns: a value in host byte-order
Mario Limonciello1a680f32019-11-25 19:44:53 -0600892 *
893 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000894 **/
895guint16
896fu_common_read_uint16 (const guint8 *buf, FuEndianType endian)
897{
898 guint16 val_hw, val_native;
899 memcpy (&val_hw, buf, sizeof(val_hw));
900 switch (endian) {
901 case G_BIG_ENDIAN:
902 val_native = GUINT16_FROM_BE(val_hw);
903 break;
904 case G_LITTLE_ENDIAN:
905 val_native = GUINT16_FROM_LE(val_hw);
906 break;
907 default:
908 g_assert_not_reached ();
909 }
910 return val_native;
911}
912
913/**
914 * fu_common_read_uint32:
915 * @buf: A readable buffer
Richard Hughes8aa72392018-05-02 08:38:43 +0100916 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000917 *
918 * Read a value from a buffer using a specified endian.
919 *
920 * Returns: a value in host byte-order
Mario Limonciello1a680f32019-11-25 19:44:53 -0600921 *
922 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000923 **/
924guint32
925fu_common_read_uint32 (const guint8 *buf, FuEndianType endian)
926{
927 guint32 val_hw, val_native;
928 memcpy (&val_hw, buf, sizeof(val_hw));
929 switch (endian) {
930 case G_BIG_ENDIAN:
931 val_native = GUINT32_FROM_BE(val_hw);
932 break;
933 case G_LITTLE_ENDIAN:
934 val_native = GUINT32_FROM_LE(val_hw);
935 break;
936 default:
937 g_assert_not_reached ();
938 }
939 return val_native;
940}
Richard Hughese82eef32018-05-20 10:41:26 +0100941
Richard Hughes73bf2332018-08-28 09:38:09 +0100942/**
Richard Hughesf2849d22021-03-05 17:19:17 +0000943 * fu_common_read_uint64:
944 * @buf: A readable buffer
945 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
946 *
947 * Read a value from a buffer using a specified endian.
948 *
949 * Returns: a value in host byte-order
950 *
951 * Since: 1.5.8
952 **/
953guint64
954fu_common_read_uint64 (const guint8 *buf, FuEndianType endian)
955{
956 guint64 val_hw, val_native;
957 memcpy (&val_hw, buf, sizeof(val_hw));
958 switch (endian) {
959 case G_BIG_ENDIAN:
960 val_native = GUINT64_FROM_BE(val_hw);
961 break;
962 case G_LITTLE_ENDIAN:
963 val_native = GUINT64_FROM_LE(val_hw);
964 break;
965 default:
966 g_assert_not_reached ();
967 }
968 return val_native;
969}
970
971/**
Richard Hughes73bf2332018-08-28 09:38:09 +0100972 * fu_common_strtoull:
973 * @str: A string, e.g. "0x1234"
974 *
975 * Converts a string value to an integer. Values are assumed base 10, unless
976 * prefixed with "0x" where they are parsed as base 16.
977 *
978 * Returns: integer value, or 0x0 for error
Mario Limonciello1a680f32019-11-25 19:44:53 -0600979 *
980 * Since: 1.1.2
Richard Hughes73bf2332018-08-28 09:38:09 +0100981 **/
982guint64
983fu_common_strtoull (const gchar *str)
984{
985 guint base = 10;
986 if (str == NULL)
987 return 0x0;
988 if (g_str_has_prefix (str, "0x")) {
989 str += 2;
990 base = 16;
991 }
992 return g_ascii_strtoull (str, NULL, base);
993}
994
Richard Hughesa574a752018-08-31 13:31:03 +0100995/**
996 * fu_common_strstrip:
997 * @str: A string, e.g. " test "
998 *
999 * Removes leading and trailing whitespace from a constant string.
1000 *
1001 * Returns: newly allocated string
Mario Limonciello1a680f32019-11-25 19:44:53 -06001002 *
1003 * Since: 1.1.2
Richard Hughesa574a752018-08-31 13:31:03 +01001004 **/
1005gchar *
1006fu_common_strstrip (const gchar *str)
1007{
1008 guint head = G_MAXUINT;
1009 guint tail = 0;
1010
1011 g_return_val_if_fail (str != NULL, NULL);
1012
1013 /* find first non-space char */
1014 for (guint i = 0; str[i] != '\0'; i++) {
1015 if (str[i] != ' ') {
1016 head = i;
1017 break;
1018 }
1019 }
1020 if (head == G_MAXUINT)
1021 return g_strdup ("");
1022
1023 /* find last non-space char */
1024 for (guint i = head; str[i] != '\0'; i++) {
Mario Limoncielloef3c7662019-09-04 23:37:59 -05001025 if (!g_ascii_isspace (str[i]))
Richard Hughesa574a752018-08-31 13:31:03 +01001026 tail = i;
1027 }
1028 return g_strndup (str + head, tail - head + 1);
1029}
1030
Richard Hughese82eef32018-05-20 10:41:26 +01001031static const GError *
1032fu_common_error_array_find (GPtrArray *errors, FwupdError error_code)
1033{
1034 for (guint j = 0; j < errors->len; j++) {
1035 const GError *error = g_ptr_array_index (errors, j);
1036 if (g_error_matches (error, FWUPD_ERROR, error_code))
1037 return error;
1038 }
1039 return NULL;
1040}
1041
1042static guint
1043fu_common_error_array_count (GPtrArray *errors, FwupdError error_code)
1044{
1045 guint cnt = 0;
1046 for (guint j = 0; j < errors->len; j++) {
1047 const GError *error = g_ptr_array_index (errors, j);
1048 if (g_error_matches (error, FWUPD_ERROR, error_code))
1049 cnt++;
1050 }
1051 return cnt;
1052}
1053
1054static gboolean
1055fu_common_error_array_matches_any (GPtrArray *errors, FwupdError *error_codes)
1056{
1057 for (guint j = 0; j < errors->len; j++) {
1058 const GError *error = g_ptr_array_index (errors, j);
1059 gboolean matches_any = FALSE;
1060 for (guint i = 0; error_codes[i] != FWUPD_ERROR_LAST; i++) {
1061 if (g_error_matches (error, FWUPD_ERROR, error_codes[i])) {
1062 matches_any = TRUE;
1063 break;
1064 }
1065 }
1066 if (!matches_any)
1067 return FALSE;
1068 }
1069 return TRUE;
1070}
1071
1072/**
1073 * fu_common_error_array_get_best:
1074 * @errors: (element-type GError): array of errors
1075 *
1076 * Finds the 'best' error to show the user from a array of errors, creating a
1077 * completely bespoke error where required.
1078 *
1079 * Returns: (transfer full): a #GError, never %NULL
Mario Limonciello1a680f32019-11-25 19:44:53 -06001080 *
1081 * Since: 1.0.8
Richard Hughese82eef32018-05-20 10:41:26 +01001082 **/
1083GError *
1084fu_common_error_array_get_best (GPtrArray *errors)
1085{
1086 FwupdError err_prio[] = { FWUPD_ERROR_INVALID_FILE,
1087 FWUPD_ERROR_VERSION_SAME,
1088 FWUPD_ERROR_VERSION_NEWER,
1089 FWUPD_ERROR_NOT_SUPPORTED,
1090 FWUPD_ERROR_INTERNAL,
1091 FWUPD_ERROR_NOT_FOUND,
1092 FWUPD_ERROR_LAST };
1093 FwupdError err_all_uptodate[] = { FWUPD_ERROR_VERSION_SAME,
1094 FWUPD_ERROR_NOT_FOUND,
1095 FWUPD_ERROR_NOT_SUPPORTED,
1096 FWUPD_ERROR_LAST };
1097 FwupdError err_all_newer[] = { FWUPD_ERROR_VERSION_NEWER,
1098 FWUPD_ERROR_VERSION_SAME,
1099 FWUPD_ERROR_NOT_FOUND,
1100 FWUPD_ERROR_NOT_SUPPORTED,
1101 FWUPD_ERROR_LAST };
1102
1103 /* are all the errors either GUID-not-matched or version-same? */
1104 if (fu_common_error_array_count (errors, FWUPD_ERROR_VERSION_SAME) > 1 &&
1105 fu_common_error_array_matches_any (errors, err_all_uptodate)) {
1106 return g_error_new (FWUPD_ERROR,
1107 FWUPD_ERROR_NOTHING_TO_DO,
1108 "All updatable firmware is already installed");
1109 }
1110
1111 /* are all the errors either GUID-not-matched or version same or newer? */
1112 if (fu_common_error_array_count (errors, FWUPD_ERROR_VERSION_NEWER) > 1 &&
1113 fu_common_error_array_matches_any (errors, err_all_newer)) {
1114 return g_error_new (FWUPD_ERROR,
1115 FWUPD_ERROR_NOTHING_TO_DO,
1116 "All updatable devices already have newer versions");
1117 }
1118
1119 /* get the most important single error */
1120 for (guint i = 0; err_prio[i] != FWUPD_ERROR_LAST; i++) {
1121 const GError *error_tmp = fu_common_error_array_find (errors, err_prio[i]);
1122 if (error_tmp != NULL)
1123 return g_error_copy (error_tmp);
1124 }
1125
1126 /* fall back to something */
1127 return g_error_new (FWUPD_ERROR,
1128 FWUPD_ERROR_NOT_FOUND,
1129 "No supported devices found");
1130}
Richard Hughes4be17d12018-05-30 20:36:29 +01001131
1132/**
1133 * fu_common_get_path:
1134 * @path_kind: A #FuPathKind e.g. %FU_PATH_KIND_DATADIR_PKG
1135 *
1136 * Gets a fwupd-specific system path. These can be overridden with various
1137 * environment variables, for instance %FWUPD_DATADIR.
1138 *
1139 * Returns: a system path, or %NULL if invalid
Mario Limonciello1a680f32019-11-25 19:44:53 -06001140 *
1141 * Since: 1.0.8
Richard Hughes4be17d12018-05-30 20:36:29 +01001142 **/
1143gchar *
1144fu_common_get_path (FuPathKind path_kind)
1145{
1146 const gchar *tmp;
1147 g_autofree gchar *basedir = NULL;
1148
1149 switch (path_kind) {
1150 /* /var */
1151 case FU_PATH_KIND_LOCALSTATEDIR:
1152 tmp = g_getenv ("FWUPD_LOCALSTATEDIR");
1153 if (tmp != NULL)
1154 return g_strdup (tmp);
1155 tmp = g_getenv ("SNAP_USER_DATA");
1156 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001157 return g_build_filename (tmp, FWUPD_LOCALSTATEDIR, NULL);
1158 return g_build_filename (FWUPD_LOCALSTATEDIR, NULL);
Richard Hughesc3689582020-05-06 12:35:20 +01001159 /* /proc */
1160 case FU_PATH_KIND_PROCFS:
1161 tmp = g_getenv ("FWUPD_PROCFS");
1162 if (tmp != NULL)
1163 return g_strdup (tmp);
1164 return g_strdup ("/proc");
Richard Hughes282b10d2018-06-22 14:48:00 +01001165 /* /sys/firmware */
1166 case FU_PATH_KIND_SYSFSDIR_FW:
1167 tmp = g_getenv ("FWUPD_SYSFSFWDIR");
1168 if (tmp != NULL)
1169 return g_strdup (tmp);
1170 return g_strdup ("/sys/firmware");
Mario Limonciello39602652019-04-29 21:08:58 -05001171 /* /sys/class/tpm */
Richard Hughesb56015e2018-12-12 09:25:32 +00001172 case FU_PATH_KIND_SYSFSDIR_TPM:
1173 tmp = g_getenv ("FWUPD_SYSFSTPMDIR");
1174 if (tmp != NULL)
1175 return g_strdup (tmp);
1176 return g_strdup ("/sys/class/tpm");
Richard Hughes83390f62018-06-22 20:36:46 +01001177 /* /sys/bus/platform/drivers */
1178 case FU_PATH_KIND_SYSFSDIR_DRIVERS:
1179 tmp = g_getenv ("FWUPD_SYSFSDRIVERDIR");
1180 if (tmp != NULL)
1181 return g_strdup (tmp);
1182 return g_strdup ("/sys/bus/platform/drivers");
Mario Limonciello9dce1f72020-02-04 09:12:52 -06001183 /* /sys/kernel/security */
1184 case FU_PATH_KIND_SYSFSDIR_SECURITY:
1185 tmp = g_getenv ("FWUPD_SYSFSSECURITYDIR");
1186 if (tmp != NULL)
1187 return g_strdup (tmp);
1188 return g_strdup ("/sys/kernel/security");
Richard Hughesa7157912020-05-11 17:14:05 +01001189 /* /sys/firmware/acpi/tables */
1190 case FU_PATH_KIND_ACPI_TABLES:
1191 tmp = g_getenv ("FWUPD_ACPITABLESDIR");
1192 if (tmp != NULL)
1193 return g_strdup (tmp);
1194 return g_strdup ("/sys/firmware/acpi/tables");
Richard Hughes4be17d12018-05-30 20:36:29 +01001195 /* /etc */
1196 case FU_PATH_KIND_SYSCONFDIR:
1197 tmp = g_getenv ("FWUPD_SYSCONFDIR");
1198 if (tmp != NULL)
1199 return g_strdup (tmp);
1200 tmp = g_getenv ("SNAP_USER_DATA");
1201 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001202 return g_build_filename (tmp, FWUPD_SYSCONFDIR, NULL);
1203 return g_strdup (FWUPD_SYSCONFDIR);
Richard Hughes4be17d12018-05-30 20:36:29 +01001204 /* /usr/lib/<triplet>/fwupd-plugins-3 */
1205 case FU_PATH_KIND_PLUGINDIR_PKG:
1206 tmp = g_getenv ("FWUPD_PLUGINDIR");
1207 if (tmp != NULL)
1208 return g_strdup (tmp);
1209 tmp = g_getenv ("SNAP");
1210 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001211 return g_build_filename (tmp, FWUPD_PLUGINDIR, NULL);
1212 return g_build_filename (FWUPD_PLUGINDIR, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001213 /* /usr/share/fwupd */
1214 case FU_PATH_KIND_DATADIR_PKG:
1215 tmp = g_getenv ("FWUPD_DATADIR");
1216 if (tmp != NULL)
1217 return g_strdup (tmp);
1218 tmp = g_getenv ("SNAP");
1219 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001220 return g_build_filename (tmp, FWUPD_DATADIR, PACKAGE_NAME, NULL);
1221 return g_build_filename (FWUPD_DATADIR, PACKAGE_NAME, NULL);
Mario Limoncielloe6e2bf92018-07-10 12:11:25 -05001222 /* /usr/libexec/fwupd/efi */
1223 case FU_PATH_KIND_EFIAPPDIR:
1224 tmp = g_getenv ("FWUPD_EFIAPPDIR");
1225 if (tmp != NULL)
1226 return g_strdup (tmp);
1227#ifdef EFI_APP_LOCATION
1228 tmp = g_getenv ("SNAP");
1229 if (tmp != NULL)
1230 return g_build_filename (tmp, EFI_APP_LOCATION, NULL);
1231 return g_strdup (EFI_APP_LOCATION);
1232#else
1233 return NULL;
1234#endif
Richard Hughes4be17d12018-05-30 20:36:29 +01001235 /* /etc/fwupd */
1236 case FU_PATH_KIND_SYSCONFDIR_PKG:
Mario Limonciello277c1962019-08-26 23:42:23 -05001237 tmp = g_getenv ("CONFIGURATION_DIRECTORY");
Mario Limonciello695cb582019-12-12 10:45:42 -06001238 if (tmp != NULL && g_file_test (tmp, G_FILE_TEST_EXISTS))
Mario Limonciello277c1962019-08-26 23:42:23 -05001239 return g_build_filename (tmp, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001240 basedir = fu_common_get_path (FU_PATH_KIND_SYSCONFDIR);
1241 return g_build_filename (basedir, PACKAGE_NAME, NULL);
1242 /* /var/lib/fwupd */
1243 case FU_PATH_KIND_LOCALSTATEDIR_PKG:
Mario Limonciello277c1962019-08-26 23:42:23 -05001244 tmp = g_getenv ("STATE_DIRECTORY");
Mario Limonciello695cb582019-12-12 10:45:42 -06001245 if (tmp != NULL && g_file_test (tmp, G_FILE_TEST_EXISTS))
Mario Limonciello277c1962019-08-26 23:42:23 -05001246 return g_build_filename (tmp, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001247 basedir = fu_common_get_path (FU_PATH_KIND_LOCALSTATEDIR);
1248 return g_build_filename (basedir, "lib", PACKAGE_NAME, NULL);
1249 /* /var/cache/fwupd */
1250 case FU_PATH_KIND_CACHEDIR_PKG:
Mario Limonciello277c1962019-08-26 23:42:23 -05001251 tmp = g_getenv ("CACHE_DIRECTORY");
Mario Limonciello695cb582019-12-12 10:45:42 -06001252 if (tmp != NULL && g_file_test (tmp, G_FILE_TEST_EXISTS))
Mario Limonciello277c1962019-08-26 23:42:23 -05001253 return g_build_filename (tmp, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001254 basedir = fu_common_get_path (FU_PATH_KIND_LOCALSTATEDIR);
1255 return g_build_filename (basedir, "cache", PACKAGE_NAME, NULL);
Richard Hughesafdba372019-11-23 12:57:35 +00001256 case FU_PATH_KIND_OFFLINE_TRIGGER:
1257 tmp = g_getenv ("FWUPD_OFFLINE_TRIGGER");
1258 if (tmp != NULL)
1259 return g_strdup (tmp);
1260 return g_strdup ("/system-update");
Mario Limonciello057c67a2019-05-23 10:44:19 -05001261 case FU_PATH_KIND_POLKIT_ACTIONS:
1262#ifdef POLKIT_ACTIONDIR
1263 return g_strdup (POLKIT_ACTIONDIR);
1264#else
1265 return NULL;
1266#endif
Richard Hughes4be17d12018-05-30 20:36:29 +01001267 /* this shouldn't happen */
1268 default:
Richard Hughesbeb47a82018-09-11 18:28:53 +01001269 g_warning ("cannot build path for unknown kind %u", path_kind);
Richard Hughes4be17d12018-05-30 20:36:29 +01001270 }
1271
1272 return NULL;
1273}
Richard Hughes83e56c12018-10-10 20:24:41 +01001274
1275/**
1276 * fu_common_string_replace:
1277 * @string: The #GString to operate on
1278 * @search: The text to search for
1279 * @replace: The text to use for substitutions
1280 *
1281 * Performs multiple search and replace operations on the given string.
1282 *
1283 * Returns: the number of replacements done, or 0 if @search is not found.
1284 *
1285 * Since: 1.2.0
1286 **/
1287guint
1288fu_common_string_replace (GString *string, const gchar *search, const gchar *replace)
1289{
1290 gchar *tmp;
1291 guint count = 0;
1292 gsize search_idx = 0;
1293 gsize replace_len;
1294 gsize search_len;
1295
1296 g_return_val_if_fail (string != NULL, 0);
1297 g_return_val_if_fail (search != NULL, 0);
1298 g_return_val_if_fail (replace != NULL, 0);
1299
1300 /* nothing to do */
1301 if (string->len == 0)
1302 return 0;
1303
1304 search_len = strlen (search);
1305 replace_len = strlen (replace);
1306
1307 do {
1308 tmp = g_strstr_len (string->str + search_idx, -1, search);
1309 if (tmp == NULL)
1310 break;
1311
1312 /* advance the counter in case @replace contains @search */
1313 search_idx = (gsize) (tmp - string->str);
1314
1315 /* reallocate the string if required */
1316 if (search_len > replace_len) {
1317 g_string_erase (string,
1318 (gssize) search_idx,
1319 (gssize) (search_len - replace_len));
1320 memcpy (tmp, replace, replace_len);
1321 } else if (search_len < replace_len) {
1322 g_string_insert_len (string,
1323 (gssize) search_idx,
1324 replace,
1325 (gssize) (replace_len - search_len));
1326 /* we have to treat this specially as it could have
1327 * been reallocated when the insertion happened */
1328 memcpy (string->str + search_idx, replace, replace_len);
1329 } else {
1330 /* just memcmp in the new string */
1331 memcpy (tmp, replace, replace_len);
1332 }
1333 search_idx += replace_len;
1334 count++;
1335 } while (TRUE);
1336
1337 return count;
1338}
Richard Hughese59cb9a2018-12-05 14:37:40 +00001339
Richard Hughesae96a1f2019-09-23 11:16:36 +01001340/**
1341 * fu_common_strwidth:
1342 * @text: The string to operate on
1343 *
1344 * Returns the width of the string in displayed characters on the console.
1345 *
1346 * Returns: width of text
1347 *
1348 * Since: 1.3.2
1349 **/
1350gsize
1351fu_common_strwidth (const gchar *text)
1352{
1353 const gchar *p = text;
1354 gsize width = 0;
Richard Hughes4d2c0f82020-07-07 12:02:30 +01001355
1356 g_return_val_if_fail (text != NULL, 0);
1357
Richard Hughesae96a1f2019-09-23 11:16:36 +01001358 while (*p) {
1359 gunichar c = g_utf8_get_char (p);
1360 if (g_unichar_iswide (c))
1361 width += 2;
1362 else if (!g_unichar_iszerowidth (c))
1363 width += 1;
1364 p = g_utf8_next_char (p);
1365 }
1366 return width;
1367}
1368
Mario Limonciello1a680f32019-11-25 19:44:53 -06001369/**
1370 * fu_common_string_append_kv:
1371 * @str: A #GString
1372 * @idt: The indent
1373 * @key: A string to append
1374 * @value: a string to append
1375 *
1376 * Appends a key and string value to a string
1377 *
1378 * Since: 1.2.4
1379 */
Richard Hughescea28de2019-08-09 11:16:40 +01001380void
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001381fu_common_string_append_kv (GString *str, guint idt, const gchar *key, const gchar *value)
Richard Hughescea28de2019-08-09 11:16:40 +01001382{
Richard Hughes2506dbf2020-09-03 10:04:19 +01001383 const guint align = 24;
Richard Hughes847cae82019-08-27 11:22:23 +01001384 gsize keysz;
Richard Hughescea28de2019-08-09 11:16:40 +01001385
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001386 g_return_if_fail (idt * 2 < align);
Richard Hughescea28de2019-08-09 11:16:40 +01001387
1388 /* ignore */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001389 if (key == NULL)
Richard Hughescea28de2019-08-09 11:16:40 +01001390 return;
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001391 for (gsize i = 0; i < idt; i++)
1392 g_string_append (str, " ");
Mario Limonciellofee8f492019-08-18 12:16:07 -05001393 if (key[0] != '\0') {
1394 g_string_append_printf (str, "%s:", key);
Richard Hughesae96a1f2019-09-23 11:16:36 +01001395 keysz = (idt * 2) + fu_common_strwidth (key) + 1;
Richard Hughes847cae82019-08-27 11:22:23 +01001396 } else {
1397 keysz = idt * 2;
Mario Limonciellofee8f492019-08-18 12:16:07 -05001398 }
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001399 if (value != NULL) {
Mario Limonciello1dbb82d2019-09-20 14:22:14 -05001400 g_auto(GStrv) split = NULL;
1401 split = g_strsplit (value, "\n", -1);
1402 for (guint i = 0; split[i] != NULL; i++) {
1403 if (i == 0) {
1404 for (gsize j = keysz; j < align; j++)
1405 g_string_append (str, " ");
1406 } else {
1407 for (gsize j = 0; j < idt; j++)
1408 g_string_append (str, " ");
1409 }
1410 g_string_append (str, split[i]);
1411 g_string_append (str, "\n");
1412 }
1413 } else {
1414 g_string_append (str, "\n");
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001415 }
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001416}
1417
Mario Limonciello1a680f32019-11-25 19:44:53 -06001418/**
1419 * fu_common_string_append_ku:
1420 * @str: A #GString
1421 * @idt: The indent
1422 * @key: A string to append
1423 * @value: guint64
1424 *
1425 * Appends a key and unsigned integer to a string
1426 *
1427 * Since: 1.2.4
1428 */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001429void
1430fu_common_string_append_ku (GString *str, guint idt, const gchar *key, guint64 value)
1431{
1432 g_autofree gchar *tmp = g_strdup_printf ("%" G_GUINT64_FORMAT, value);
1433 fu_common_string_append_kv (str, idt, key, tmp);
1434}
1435
Mario Limonciello1a680f32019-11-25 19:44:53 -06001436/**
1437 * fu_common_string_append_kx:
1438 * @str: A #GString
1439 * @idt: The indent
1440 * @key: A string to append
1441 * @value: guint64
1442 *
1443 * Appends a key and hex integer to a string
1444 *
1445 * Since: 1.2.4
1446 */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001447void
1448fu_common_string_append_kx (GString *str, guint idt, const gchar *key, guint64 value)
1449{
1450 g_autofree gchar *tmp = g_strdup_printf ("0x%x", (guint) value);
1451 fu_common_string_append_kv (str, idt, key, tmp);
1452}
1453
Mario Limonciello1a680f32019-11-25 19:44:53 -06001454/**
1455 * fu_common_string_append_kb:
1456 * @str: A #GString
1457 * @idt: The indent
1458 * @key: A string to append
1459 * @value: Boolean
1460 *
1461 * Appends a key and boolean value to a string
1462 *
1463 * Since: 1.2.4
1464 */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001465void
1466fu_common_string_append_kb (GString *str, guint idt, const gchar *key, gboolean value)
1467{
1468 fu_common_string_append_kv (str, idt, key, value ? "true" : "false");
Richard Hughescea28de2019-08-09 11:16:40 +01001469}
1470
Richard Hughese59cb9a2018-12-05 14:37:40 +00001471/**
Richard Hughes35481862019-01-06 12:01:58 +00001472 * fu_common_dump_full:
1473 * @log_domain: log domain, typically %G_LOG_DOMAIN or %NULL
1474 * @title: prefix title, or %NULL
1475 * @data: buffer to print
1476 * @len: the size of @data
1477 * @columns: break new lines after this many bytes
1478 * @flags: some #FuDumpFlags, e.g. %FU_DUMP_FLAGS_SHOW_ASCII
1479 *
1480 * Dumps a raw buffer to the screen.
1481 *
1482 * Since: 1.2.4
1483 **/
1484void
1485fu_common_dump_full (const gchar *log_domain,
1486 const gchar *title,
1487 const guint8 *data,
1488 gsize len,
1489 guint columns,
1490 FuDumpFlags flags)
1491{
1492 g_autoptr(GString) str = g_string_new (NULL);
1493
1494 /* optional */
1495 if (title != NULL)
1496 g_string_append_printf (str, "%s:", title);
1497
1498 /* if more than can fit on one line then start afresh */
1499 if (len > columns || flags & FU_DUMP_FLAGS_SHOW_ADDRESSES) {
1500 g_string_append (str, "\n");
1501 } else {
1502 for (gsize i = str->len; i < 16; i++)
1503 g_string_append (str, " ");
1504 }
1505
1506 /* offset line */
1507 if (flags & FU_DUMP_FLAGS_SHOW_ADDRESSES) {
1508 g_string_append (str, " │ ");
1509 for (gsize i = 0; i < columns; i++)
1510 g_string_append_printf (str, "%02x ", (guint) i);
1511 g_string_append (str, "\n───────┼");
1512 for (gsize i = 0; i < columns; i++)
1513 g_string_append (str, "───");
1514 g_string_append_printf (str, "\n0x%04x │ ", (guint) 0);
1515 }
1516
1517 /* print each row */
1518 for (gsize i = 0; i < len; i++) {
1519 g_string_append_printf (str, "%02x ", data[i]);
1520
1521 /* optionally print ASCII char */
1522 if (flags & FU_DUMP_FLAGS_SHOW_ASCII) {
1523 if (g_ascii_isprint (data[i]))
1524 g_string_append_printf (str, "[%c] ", data[i]);
1525 else
1526 g_string_append (str, "[?] ");
1527 }
1528
1529 /* new row required */
1530 if (i > 0 && i != len - 1 && (i + 1) % columns == 0) {
1531 g_string_append (str, "\n");
1532 if (flags & FU_DUMP_FLAGS_SHOW_ADDRESSES)
1533 g_string_append_printf (str, "0x%04x │ ", (guint) i + 1);
1534 }
1535 }
1536 g_log (log_domain, G_LOG_LEVEL_DEBUG, "%s", str->str);
1537}
1538
1539/**
Richard Hughese59cb9a2018-12-05 14:37:40 +00001540 * fu_common_dump_raw:
1541 * @log_domain: log domain, typically %G_LOG_DOMAIN or %NULL
1542 * @title: prefix title, or %NULL
1543 * @data: buffer to print
1544 * @len: the size of @data
1545 *
1546 * Dumps a raw buffer to the screen.
1547 *
1548 * Since: 1.2.2
1549 **/
1550void
1551fu_common_dump_raw (const gchar *log_domain,
1552 const gchar *title,
1553 const guint8 *data,
1554 gsize len)
1555{
Richard Hughes35481862019-01-06 12:01:58 +00001556 FuDumpFlags flags = FU_DUMP_FLAGS_NONE;
1557 if (len > 64)
1558 flags |= FU_DUMP_FLAGS_SHOW_ADDRESSES;
1559 fu_common_dump_full (log_domain, title, data, len, 32, flags);
Richard Hughese59cb9a2018-12-05 14:37:40 +00001560}
1561
1562/**
Mario Limonciello39602652019-04-29 21:08:58 -05001563 * fu_common_dump_bytes:
Richard Hughese59cb9a2018-12-05 14:37:40 +00001564 * @log_domain: log domain, typically %G_LOG_DOMAIN or %NULL
1565 * @title: prefix title, or %NULL
1566 * @bytes: a #GBytes
1567 *
1568 * Dumps a byte buffer to the screen.
1569 *
1570 * Since: 1.2.2
1571 **/
1572void
1573fu_common_dump_bytes (const gchar *log_domain,
1574 const gchar *title,
1575 GBytes *bytes)
1576{
1577 gsize len = 0;
1578 const guint8 *data = g_bytes_get_data (bytes, &len);
1579 fu_common_dump_raw (log_domain, title, data, len);
1580}
Richard Hughesfc90f392019-01-15 21:21:16 +00001581
1582/**
1583 * fu_common_bytes_align:
1584 * @bytes: a #GBytes
1585 * @blksz: block size in bytes
1586 * @padval: the byte used to pad the byte buffer
1587 *
1588 * Aligns a block of memory to @blksize using the @padval value; if
1589 * the block is already aligned then the original @bytes is returned.
1590 *
1591 * Returns: (transfer full): a #GBytes, possibly @bytes
1592 *
1593 * Since: 1.2.4
1594 **/
1595GBytes *
1596fu_common_bytes_align (GBytes *bytes, gsize blksz, gchar padval)
1597{
1598 const guint8 *data;
1599 gsize sz;
1600
1601 g_return_val_if_fail (bytes != NULL, NULL);
1602 g_return_val_if_fail (blksz > 0, NULL);
1603
1604 /* pad */
1605 data = g_bytes_get_data (bytes, &sz);
1606 if (sz % blksz != 0) {
1607 gsize sz_align = ((sz / blksz) + 1) * blksz;
1608 guint8 *data_align = g_malloc (sz_align);
1609 memcpy (data_align, data, sz);
1610 memset (data_align + sz, padval, sz_align - sz);
1611 g_debug ("aligning 0x%x bytes to 0x%x",
1612 (guint) sz, (guint) sz_align);
1613 return g_bytes_new_take (data_align, sz_align);
1614 }
1615
1616 /* perfectly aligned */
1617 return g_bytes_ref (bytes);
1618}
Richard Hughes36999462019-03-19 20:23:29 +00001619
1620/**
1621 * fu_common_bytes_is_empty:
1622 * @bytes: a #GBytes
1623 *
1624 * Checks if a byte array are just empty (0xff) bytes.
1625 *
1626 * Return value: %TRUE if @bytes is empty
Mario Limonciello1a680f32019-11-25 19:44:53 -06001627 *
1628 * Since: 1.2.6
Richard Hughes36999462019-03-19 20:23:29 +00001629 **/
1630gboolean
1631fu_common_bytes_is_empty (GBytes *bytes)
1632{
1633 gsize sz = 0;
1634 const guint8 *buf = g_bytes_get_data (bytes, &sz);
1635 for (gsize i = 0; i < sz; i++) {
1636 if (buf[i] != 0xff)
1637 return FALSE;
1638 }
1639 return TRUE;
1640}
Richard Hughes2aad1042019-03-21 09:03:32 +00001641
1642/**
Richard Hughes38245ff2019-09-18 14:46:09 +01001643 * fu_common_bytes_compare_raw:
1644 * @buf1: a buffer
1645 * @bufsz1: sizeof @buf1
1646 * @buf2: another buffer
1647 * @bufsz2: sizeof @buf2
Richard Hughes2aad1042019-03-21 09:03:32 +00001648 * @error: A #GError or %NULL
1649 *
Richard Hughes38245ff2019-09-18 14:46:09 +01001650 * Compares the buffers for equality.
Richard Hughes2aad1042019-03-21 09:03:32 +00001651 *
Richard Hughes38245ff2019-09-18 14:46:09 +01001652 * Return value: %TRUE if @buf1 and @buf2 are identical
Mario Limonciello1a680f32019-11-25 19:44:53 -06001653 *
1654 * Since: 1.3.2
Richard Hughes2aad1042019-03-21 09:03:32 +00001655 **/
1656gboolean
Richard Hughes38245ff2019-09-18 14:46:09 +01001657fu_common_bytes_compare_raw (const guint8 *buf1, gsize bufsz1,
1658 const guint8 *buf2, gsize bufsz2,
1659 GError **error)
Richard Hughes2aad1042019-03-21 09:03:32 +00001660{
Richard Hughes38245ff2019-09-18 14:46:09 +01001661 g_return_val_if_fail (buf1 != NULL, FALSE);
1662 g_return_val_if_fail (buf2 != NULL, FALSE);
Richard Hughes2aad1042019-03-21 09:03:32 +00001663 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1664
1665 /* not the same length */
Richard Hughes2aad1042019-03-21 09:03:32 +00001666 if (bufsz1 != bufsz2) {
1667 g_set_error (error,
1668 G_IO_ERROR,
1669 G_IO_ERROR_INVALID_DATA,
1670 "got %" G_GSIZE_FORMAT " bytes, expected "
1671 "%" G_GSIZE_FORMAT, bufsz1, bufsz2);
1672 return FALSE;
1673 }
1674
1675 /* check matches */
1676 for (guint i = 0x0; i < bufsz1; i++) {
1677 if (buf1[i] != buf2[i]) {
1678 g_set_error (error,
1679 G_IO_ERROR,
1680 G_IO_ERROR_INVALID_DATA,
1681 "got 0x%02x, expected 0x%02x @ 0x%04x",
1682 buf1[i], buf2[i], i);
1683 return FALSE;
1684 }
1685 }
1686
1687 /* success */
1688 return TRUE;
1689}
Richard Hughes484ee292019-03-22 16:10:50 +00001690
1691/**
Richard Hughes38245ff2019-09-18 14:46:09 +01001692 * fu_common_bytes_compare:
1693 * @bytes1: a #GBytes
1694 * @bytes2: another #GBytes
1695 * @error: A #GError or %NULL
1696 *
1697 * Compares the buffers for equality.
1698 *
1699 * Return value: %TRUE if @bytes1 and @bytes2 are identical
Mario Limonciello1a680f32019-11-25 19:44:53 -06001700 *
1701 * Since: 1.2.6
Richard Hughes38245ff2019-09-18 14:46:09 +01001702 **/
1703gboolean
1704fu_common_bytes_compare (GBytes *bytes1, GBytes *bytes2, GError **error)
1705{
1706 const guint8 *buf1;
1707 const guint8 *buf2;
1708 gsize bufsz1;
1709 gsize bufsz2;
1710
1711 g_return_val_if_fail (bytes1 != NULL, FALSE);
1712 g_return_val_if_fail (bytes2 != NULL, FALSE);
1713 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1714
1715 buf1 = g_bytes_get_data (bytes1, &bufsz1);
1716 buf2 = g_bytes_get_data (bytes2, &bufsz2);
1717 return fu_common_bytes_compare_raw (buf1, bufsz1, buf2, bufsz2, error);
1718}
1719
1720/**
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001721 * fu_common_bytes_pad:
1722 * @bytes: a #GBytes
1723 * @sz: the desired size in bytes
1724 *
Richard Hughes2ad99bb2021-03-03 10:19:13 +00001725 * Pads a GBytes to a minimum @sz with `0xff`.
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001726 *
1727 * Return value: (transfer full): a #GBytes
Mario Limonciello1a680f32019-11-25 19:44:53 -06001728 *
1729 * Since: 1.3.1
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001730 **/
1731GBytes *
1732fu_common_bytes_pad (GBytes *bytes, gsize sz)
1733{
1734 gsize bytes_sz;
1735
Richard Hughes2ad99bb2021-03-03 10:19:13 +00001736 g_return_val_if_fail (bytes != NULL, NULL);
1737 g_return_val_if_fail (sz != 0, NULL);
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001738
1739 /* pad */
1740 bytes_sz = g_bytes_get_size (bytes);
1741 if (bytes_sz < sz) {
1742 const guint8 *data = g_bytes_get_data (bytes, NULL);
1743 guint8 *data_new = g_malloc (sz);
1744 memcpy (data_new, data, bytes_sz);
1745 memset (data_new + bytes_sz, 0xff, sz - bytes_sz);
1746 return g_bytes_new_take (data_new, sz);
1747 }
1748
Richard Hughes2ad99bb2021-03-03 10:19:13 +00001749 /* not required */
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001750 return g_bytes_ref (bytes);
1751}
1752
1753/**
Richard Hughes05e33772020-12-08 18:37:02 +00001754 * fu_common_bytes_new_offset:
1755 * @bytes: a #GBytes
1756 * @offset: where subsection starts at
1757 * @length: length of subsection
1758 * @error: A #GError or %NULL
1759 *
1760 * Creates a #GBytes which is a subsection of another #GBytes.
1761 *
1762 * Return value: (transfer full): a #GBytes, or #NULL if range is invalid
1763 *
1764 * Since: 1.5.4
1765 **/
1766GBytes *
1767fu_common_bytes_new_offset (GBytes *bytes,
1768 gsize offset,
1769 gsize length,
1770 GError **error)
1771{
1772 g_return_val_if_fail (bytes != NULL, NULL);
Richard Hughes6a489a92020-12-22 10:32:06 +00001773 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
Richard Hughes05e33772020-12-08 18:37:02 +00001774
1775 /* sanity check */
1776 if (offset + length > g_bytes_get_size (bytes)) {
1777 g_set_error (error,
1778 G_IO_ERROR,
1779 G_IO_ERROR_INVALID_DATA,
1780 "cannot create bytes @0x%02x for 0x%02x "
1781 "as buffer only 0x%04x bytes in size",
1782 (guint) offset,
1783 (guint) length,
1784 (guint) g_bytes_get_size (bytes));
1785 return NULL;
1786 }
1787 return g_bytes_new_from_bytes (bytes, offset, length);
1788}
1789
1790/**
Richard Hughes484ee292019-03-22 16:10:50 +00001791 * fu_common_realpath:
1792 * @filename: a filename
1793 * @error: A #GError or %NULL
1794 *
1795 * Finds the canonicalized absolute filename for a path.
1796 *
1797 * Return value: A filename, or %NULL if invalid or not found
Mario Limonciello1a680f32019-11-25 19:44:53 -06001798 *
1799 * Since: 1.2.6
Richard Hughes484ee292019-03-22 16:10:50 +00001800 **/
1801gchar *
1802fu_common_realpath (const gchar *filename, GError **error)
1803{
1804 char full_tmp[PATH_MAX];
1805
1806 g_return_val_if_fail (filename != NULL, NULL);
Richard Hughes6a489a92020-12-22 10:32:06 +00001807 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
Richard Hughes484ee292019-03-22 16:10:50 +00001808
Richard Hughes8694dee2019-11-22 09:16:34 +00001809#ifdef HAVE_REALPATH
Richard Hughes484ee292019-03-22 16:10:50 +00001810 if (realpath (filename, full_tmp) == NULL) {
Richard Hughes8694dee2019-11-22 09:16:34 +00001811#else
1812 if (_fullpath (full_tmp, filename, sizeof(full_tmp)) == NULL) {
1813#endif
Richard Hughes484ee292019-03-22 16:10:50 +00001814 g_set_error (error,
1815 G_IO_ERROR,
1816 G_IO_ERROR_INVALID_DATA,
1817 "cannot resolve path: %s",
1818 strerror (errno));
1819 return NULL;
1820 }
Richard Hughes8694dee2019-11-22 09:16:34 +00001821 if (!g_file_test (full_tmp, G_FILE_TEST_EXISTS)) {
1822 g_set_error (error,
1823 G_IO_ERROR,
1824 G_IO_ERROR_INVALID_DATA,
1825 "cannot find path: %s",
1826 full_tmp);
1827 return NULL;
1828 }
Richard Hughes484ee292019-03-22 16:10:50 +00001829 return g_strdup (full_tmp);
1830}
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001831
1832/**
Richard Hughes5c508de2019-11-22 09:57:34 +00001833 * fu_common_fnmatch:
1834 * @pattern: a glob pattern, e.g. `*foo*`
1835 * @str: a string to match against the pattern, e.g. `bazfoobar`
1836 *
1837 * Matches a string against a glob pattern.
1838 *
1839 * Return value: %TRUE if the string matched
1840 *
1841 * Since: 1.3.5
1842 **/
1843gboolean
1844fu_common_fnmatch (const gchar *pattern, const gchar *str)
1845{
1846 g_return_val_if_fail (pattern != NULL, FALSE);
1847 g_return_val_if_fail (str != NULL, FALSE);
1848#ifdef HAVE_FNMATCH_H
1849 return fnmatch (pattern, str, FNM_NOESCAPE) == 0;
Richard Hughes45a00732019-11-22 16:57:14 +00001850#elif _WIN32
1851 g_return_val_if_fail (strlen (pattern) < MAX_PATH, FALSE);
1852 g_return_val_if_fail (strlen (str) < MAX_PATH, FALSE);
1853 return PathMatchSpecA (str, pattern);
Richard Hughes5c508de2019-11-22 09:57:34 +00001854#else
1855 return g_strcmp0 (pattern, str) == 0;
1856#endif
1857}
1858
Richard Hughesa84d7a72020-05-06 12:11:51 +01001859static gint
1860fu_common_filename_glob_sort_cb (gconstpointer a, gconstpointer b)
1861{
1862 return g_strcmp0 (*(const gchar **)a, *(const gchar **)b);
1863}
1864
1865/**
1866 * fu_common_filename_glob:
1867 * @directory: a directory path
1868 * @pattern: a glob pattern, e.g. `*foo*`
1869 * @error: A #GError or %NULL
1870 *
1871 * Returns all the filenames that match a specific glob pattern.
1872 * Any results are sorted. No matching files will set @error.
1873 *
1874 * Return value: (element-type utf8) (transfer container): matching files, or %NULL
1875 *
1876 * Since: 1.5.0
1877 **/
1878GPtrArray *
1879fu_common_filename_glob (const gchar *directory, const gchar *pattern, GError **error)
1880{
1881 const gchar *basename;
Richard Hughes6a489a92020-12-22 10:32:06 +00001882 g_autoptr(GDir) dir = NULL;
Richard Hughesa84d7a72020-05-06 12:11:51 +01001883 g_autoptr(GPtrArray) files = g_ptr_array_new_with_free_func (g_free);
Richard Hughes6a489a92020-12-22 10:32:06 +00001884
1885 g_return_val_if_fail (directory != NULL, NULL);
1886 g_return_val_if_fail (pattern != NULL, NULL);
1887 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1888
1889 dir = g_dir_open (directory, 0, error);
Richard Hughesa84d7a72020-05-06 12:11:51 +01001890 if (dir == NULL)
1891 return NULL;
1892 while ((basename = g_dir_read_name (dir)) != NULL) {
1893 if (!fu_common_fnmatch (pattern, basename))
1894 continue;
1895 g_ptr_array_add (files, g_build_filename (directory, basename, NULL));
1896 }
1897 if (files->len == 0) {
1898 g_set_error_literal (error,
1899 G_IO_ERROR,
1900 G_IO_ERROR_NOT_FOUND,
1901 "no files matched pattern");
1902 return NULL;
1903 }
1904 g_ptr_array_sort (files, fu_common_filename_glob_sort_cb);
1905 return g_steal_pointer (&files);
1906}
1907
Richard Hughes5c508de2019-11-22 09:57:34 +00001908/**
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001909 * fu_common_strnsplit:
1910 * @str: a string to split
1911 * @sz: size of @str
1912 * @delimiter: a string which specifies the places at which to split the string
1913 * @max_tokens: the maximum number of pieces to split @str into
1914 *
1915 * Splits a string into a maximum of @max_tokens pieces, using the given
1916 * delimiter. If @max_tokens is reached, the remainder of string is appended
1917 * to the last token.
1918 *
Richard Hughesa0d81c72019-11-27 11:41:54 +00001919 * Return value: (transfer full): a newly-allocated NULL-terminated array of strings
Mario Limonciello1a680f32019-11-25 19:44:53 -06001920 *
1921 * Since: 1.3.1
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001922 **/
1923gchar **
1924fu_common_strnsplit (const gchar *str, gsize sz,
1925 const gchar *delimiter, gint max_tokens)
1926{
1927 if (str[sz - 1] != '\0') {
1928 g_autofree gchar *str2 = g_strndup (str, sz);
1929 return g_strsplit (str2, delimiter, max_tokens);
1930 }
1931 return g_strsplit (str, delimiter, max_tokens);
1932}
Richard Hughes5308ea42019-08-09 12:25:13 +01001933
1934/**
Richard Hughes364e2682021-01-05 14:38:15 +00001935 * fu_common_strsafe:
1936 * @str: (nullable): a string to make safe for printing
1937 * @maxsz: maximum size of returned string
1938 *
1939 * Converts a string into something that can be safely printed.
1940 *
1941 * Return value: (transfer full): safe string, or %NULL if there was nothing valid
1942 *
1943 * Since: 1.5.5
1944 **/
1945gchar *
1946fu_common_strsafe (const gchar *str, gsize maxsz)
1947{
1948 gboolean valid = FALSE;
1949 g_autoptr(GString) tmp = NULL;
1950
Richard Hughes364e2682021-01-05 14:38:15 +00001951 /* sanity check */
Richard Hughesc123bee2021-02-08 16:47:05 +00001952 if (str == NULL || maxsz == 0)
Richard Hughes364e2682021-01-05 14:38:15 +00001953 return NULL;
1954
1955 /* replace non-printable chars with '.' */
Richard Hughesc123bee2021-02-08 16:47:05 +00001956 tmp = g_string_sized_new (maxsz);
Richard Hughesa4e0de42021-02-14 20:33:47 +00001957 for (gsize i = 0; i < maxsz && str[i] != '\0'; i++) {
Richard Hughes364e2682021-01-05 14:38:15 +00001958 if (!g_ascii_isprint (str[i])) {
1959 g_string_append_c (tmp, '.');
1960 continue;
1961 }
1962 g_string_append_c (tmp, str[i]);
Richard Hughesffbb1172021-02-14 20:34:31 +00001963 if (!g_ascii_isspace (str[i]))
1964 valid = TRUE;
Richard Hughes364e2682021-01-05 14:38:15 +00001965 }
1966
1967 /* if just junk, don't return 'all dots' */
1968 if (tmp->len == 0 || !valid)
1969 return NULL;
1970 return g_string_free (g_steal_pointer (&tmp), FALSE);
1971}
1972
Richard Hughese52e1b42021-01-26 09:59:15 +00001973
1974/**
1975 * fu_common_strjoin_array:
1976 * @separator: (nullable): string to insert between each of the strings, or %NULL
1977 * @array: (element-type utf8): A #GPtrArray
1978 *
1979 * Joins an array of strings together to form one long string, with the optional
1980 * separator inserted between each of them.
1981 *
1982 * If @array has no items, the return value will be an empty string.
1983 * If @array contains a single item, separator will not appear in the resulting
1984 * string.
1985 *
1986 * Returns: a string
1987 *
1988 * Since: 1.5.6
1989 **/
1990gchar *
1991fu_common_strjoin_array (const gchar *separator, GPtrArray *array)
1992{
1993 g_autofree const gchar **strv = NULL;
1994
1995 g_return_val_if_fail (array != NULL, NULL);
1996
1997 strv = g_new0 (const gchar *, array->len + 1);
1998 for (guint i = 0; i < array->len; i++)
1999 strv[i] = g_ptr_array_index (array, i);
2000 return g_strjoinv (separator, (gchar **) strv);
2001}
2002
Richard Hughes364e2682021-01-05 14:38:15 +00002003/**
Richard Hughes5308ea42019-08-09 12:25:13 +01002004 * fu_memcpy_safe:
2005 * @dst: destination buffer
2006 * @dst_sz: maximum size of @dst, typically `sizeof(dst)`
2007 * @dst_offset: offset in bytes into @dst to copy to
2008 * @src: source buffer
2009 * @src_sz: maximum size of @dst, typically `sizeof(src)`
2010 * @src_offset: offset in bytes into @src to copy from
2011 * @n: number of bytes to copy from @src+@offset from
2012 * @error: A #GError or %NULL
2013 *
2014 * Copies some memory using memcpy in a safe way. Providing the buffer sizes
2015 * of both the destination and the source allows us to check for buffer overflow.
2016 *
2017 * Providing the buffer offsets also allows us to check reading past the end of
2018 * the source buffer. For this reason the caller should NEVER add an offset to
2019 * @src or @dst.
2020 *
2021 * You don't need to use this function in "obviously correct" cases, nor should
2022 * you use it when performance is a concern. Only us it when you're not sure if
2023 * malicious data from a device or firmware could cause memory corruption.
2024 *
2025 * Return value: %TRUE if the bytes were copied, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002026 *
2027 * Since: 1.3.1
Richard Hughes5308ea42019-08-09 12:25:13 +01002028 **/
2029gboolean
2030fu_memcpy_safe (guint8 *dst, gsize dst_sz, gsize dst_offset,
2031 const guint8 *src, gsize src_sz, gsize src_offset,
2032 gsize n, GError **error)
2033{
Richard Hughes6a489a92020-12-22 10:32:06 +00002034 g_return_val_if_fail (dst != NULL, FALSE);
2035 g_return_val_if_fail (src != NULL, FALSE);
2036 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2037
Richard Hughes5308ea42019-08-09 12:25:13 +01002038 if (n == 0)
2039 return TRUE;
2040
2041 if (n > src_sz) {
2042 g_set_error (error,
2043 FWUPD_ERROR,
2044 FWUPD_ERROR_READ,
2045 "attempted to read 0x%02x bytes from buffer of 0x%02x",
2046 (guint) n, (guint) src_sz);
2047 return FALSE;
2048 }
2049 if (n + src_offset > src_sz) {
2050 g_set_error (error,
2051 FWUPD_ERROR,
2052 FWUPD_ERROR_READ,
2053 "attempted to read 0x%02x bytes at offset 0x%02x from buffer of 0x%02x",
2054 (guint) n, (guint) src_offset, (guint) src_sz);
2055 return FALSE;
2056 }
2057 if (n > dst_sz) {
2058 g_set_error (error,
2059 FWUPD_ERROR,
2060 FWUPD_ERROR_WRITE,
2061 "attempted to write 0x%02x bytes to buffer of 0x%02x",
2062 (guint) n, (guint) dst_sz);
2063 return FALSE;
2064 }
2065 if (n + dst_offset > dst_sz) {
2066 g_set_error (error,
2067 FWUPD_ERROR,
2068 FWUPD_ERROR_WRITE,
2069 "attempted to write 0x%02x bytes at offset 0x%02x to buffer of 0x%02x",
2070 (guint) n, (guint) dst_offset, (guint) dst_sz);
2071 return FALSE;
2072 }
2073
2074 /* phew! */
2075 memcpy (dst + dst_offset, src + src_offset, n);
2076 return TRUE;
2077}
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002078
Richard Hughes80768f52019-10-22 07:19:14 +01002079/**
Richard Hughes9b11af92021-02-04 20:28:49 +00002080 * fu_memdup_safe:
2081 * @src: source buffer
2082 * @n: number of bytes to copy from @src
2083 * @error: A #GError or %NULL
2084 *
2085 * Duplicates some memory using memdup in a safe way.
2086 *
2087 * You don't need to use this function in "obviously correct" cases, nor should
2088 * you use it when performance is a concern. Only us it when you're not sure if
2089 * malicious data from a device or firmware could cause memory corruption.
2090 *
2091 * NOTE: This function intentionally limits allocation size to 1GB.
2092 *
2093 * Return value: (transfer full): block of allocated memory, or %NULL for an error.
2094 *
2095 * Since: 1.5.6
2096 **/
2097guint8 *
2098fu_memdup_safe (const guint8 *src, gsize n, GError **error)
2099{
Richard Hughes9b11af92021-02-04 20:28:49 +00002100 /* sanity check */
2101 if (n > 0x40000000) {
2102 g_set_error (error,
2103 G_IO_ERROR,
2104 G_IO_ERROR_NOT_SUPPORTED,
2105 "cannot allocate %uGB of memory",
2106 (guint) (n / 0x40000000));
2107 return NULL;
2108 }
2109
Richard Hughes5294d0c2021-02-05 09:50:02 +00002110#if GLIB_CHECK_VERSION(2,67,3)
Richard Hughes9b11af92021-02-04 20:28:49 +00002111 /* linear block of memory */
Richard Hughes5294d0c2021-02-05 09:50:02 +00002112 return g_memdup2 (src, n);
2113#else
2114 return g_memdup (src, (guint) n);
2115#endif
Richard Hughes9b11af92021-02-04 20:28:49 +00002116}
2117
2118/**
Richard Hughesc21a0b92019-10-24 12:24:37 +01002119 * fu_common_read_uint8_safe:
2120 * @buf: source buffer
2121 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2122 * @offset: offset in bytes into @buf to copy from
2123 * @value: (out) (allow-none): the parsed value
2124 * @error: A #GError or %NULL
2125 *
2126 * Read a value from a buffer in a safe way.
2127 *
2128 * You don't need to use this function in "obviously correct" cases, nor should
2129 * you use it when performance is a concern. Only us it when you're not sure if
2130 * malicious data from a device or firmware could cause memory corruption.
2131 *
2132 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002133 *
2134 * Since: 1.3.3
Richard Hughesc21a0b92019-10-24 12:24:37 +01002135 **/
2136gboolean
2137fu_common_read_uint8_safe (const guint8 *buf,
2138 gsize bufsz,
2139 gsize offset,
2140 guint8 *value,
2141 GError **error)
2142{
2143 guint8 tmp;
Richard Hughes6a489a92020-12-22 10:32:06 +00002144
2145 g_return_val_if_fail (buf != NULL, FALSE);
2146 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2147
Richard Hughesc21a0b92019-10-24 12:24:37 +01002148 if (!fu_memcpy_safe (&tmp, sizeof(tmp), 0x0, /* dst */
2149 buf, bufsz, offset, /* src */
2150 sizeof(tmp), error))
2151 return FALSE;
2152 if (value != NULL)
2153 *value = tmp;
2154 return TRUE;
2155}
2156
2157/**
Richard Hughes80768f52019-10-22 07:19:14 +01002158 * fu_common_read_uint16_safe:
2159 * @buf: source buffer
2160 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2161 * @offset: offset in bytes into @buf to copy from
2162 * @value: (out) (allow-none): the parsed value
2163 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2164 * @error: A #GError or %NULL
2165 *
2166 * Read a value from a buffer using a specified endian in a safe way.
2167 *
2168 * You don't need to use this function in "obviously correct" cases, nor should
2169 * you use it when performance is a concern. Only us it when you're not sure if
2170 * malicious data from a device or firmware could cause memory corruption.
2171 *
2172 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002173 *
2174 * Since: 1.3.3
Richard Hughes80768f52019-10-22 07:19:14 +01002175 **/
2176gboolean
2177fu_common_read_uint16_safe (const guint8 *buf,
2178 gsize bufsz,
2179 gsize offset,
2180 guint16 *value,
2181 FuEndianType endian,
2182 GError **error)
2183{
2184 guint8 dst[2] = { 0x0 };
Richard Hughes6a489a92020-12-22 10:32:06 +00002185
2186 g_return_val_if_fail (buf != NULL, FALSE);
2187 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2188
Richard Hughes7d01ac92019-10-23 14:31:46 +01002189 if (!fu_memcpy_safe (dst, sizeof(dst), 0x0, /* dst */
Richard Hughes80768f52019-10-22 07:19:14 +01002190 buf, bufsz, offset, /* src */
Richard Hughes7d01ac92019-10-23 14:31:46 +01002191 sizeof(dst), error))
Richard Hughes80768f52019-10-22 07:19:14 +01002192 return FALSE;
2193 if (value != NULL)
2194 *value = fu_common_read_uint16 (dst, endian);
2195 return TRUE;
2196}
2197
2198/**
2199 * fu_common_read_uint32_safe:
2200 * @buf: source buffer
2201 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2202 * @offset: offset in bytes into @buf to copy from
2203 * @value: (out) (allow-none): the parsed value
2204 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2205 * @error: A #GError or %NULL
2206 *
2207 * Read a value from a buffer using a specified endian in a safe way.
2208 *
2209 * You don't need to use this function in "obviously correct" cases, nor should
2210 * you use it when performance is a concern. Only us it when you're not sure if
2211 * malicious data from a device or firmware could cause memory corruption.
2212 *
2213 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06002214 *
2215 * Since: 1.3.3
Richard Hughes80768f52019-10-22 07:19:14 +01002216 **/
2217gboolean
2218fu_common_read_uint32_safe (const guint8 *buf,
2219 gsize bufsz,
2220 gsize offset,
2221 guint32 *value,
2222 FuEndianType endian,
2223 GError **error)
2224{
2225 guint8 dst[4] = { 0x0 };
Richard Hughes6a489a92020-12-22 10:32:06 +00002226
2227 g_return_val_if_fail (buf != NULL, FALSE);
2228 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2229
Richard Hughes7d01ac92019-10-23 14:31:46 +01002230 if (!fu_memcpy_safe (dst, sizeof(dst), 0x0, /* dst */
Richard Hughes80768f52019-10-22 07:19:14 +01002231 buf, bufsz, offset, /* src */
Richard Hughes7d01ac92019-10-23 14:31:46 +01002232 sizeof(dst), error))
Richard Hughes80768f52019-10-22 07:19:14 +01002233 return FALSE;
2234 if (value != NULL)
2235 *value = fu_common_read_uint32 (dst, endian);
2236 return TRUE;
2237}
2238
Mario Limonciello1a680f32019-11-25 19:44:53 -06002239/**
Richard Hughesf2849d22021-03-05 17:19:17 +00002240 * fu_common_read_uint64_safe:
2241 * @buf: source buffer
2242 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2243 * @offset: offset in bytes into @buf to copy from
2244 * @value: (out) (allow-none): the parsed value
2245 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2246 * @error: A #GError or %NULL
2247 *
2248 * Read a value from a buffer using a specified endian in a safe way.
2249 *
2250 * You don't need to use this function in "obviously correct" cases, nor should
2251 * you use it when performance is a concern. Only us it when you're not sure if
2252 * malicious data from a device or firmware could cause memory corruption.
2253 *
2254 * Return value: %TRUE if @value was set, %FALSE otherwise
2255 *
2256 * Since: 1.5.8
2257 **/
2258gboolean
2259fu_common_read_uint64_safe (const guint8 *buf,
2260 gsize bufsz,
2261 gsize offset,
2262 guint64 *value,
2263 FuEndianType endian,
2264 GError **error)
2265{
2266 guint8 dst[8] = { 0x0 };
2267
2268 g_return_val_if_fail (buf != NULL, FALSE);
2269 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2270
2271 if (!fu_memcpy_safe (dst, sizeof(dst), 0x0, /* dst */
2272 buf, bufsz, offset, /* src */
2273 sizeof(dst), error))
2274 return FALSE;
2275 if (value != NULL)
2276 *value = fu_common_read_uint64 (dst, endian);
2277 return TRUE;
2278}
2279
2280/**
Richard Hughes32ffdb22021-03-04 17:38:12 +00002281 * fu_common_write_uint8_safe:
2282 * @buf: source buffer
2283 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2284 * @offset: offset in bytes into @buf to write to
2285 * @value: the value to write
2286 * @error: A #GError or %NULL
2287 *
2288 * Write a value to a buffer in a safe way.
2289 *
2290 * You don't need to use this function in "obviously correct" cases, nor should
2291 * you use it when performance is a concern. Only us it when you're not sure if
2292 * malicious data from a device or firmware could cause memory corruption.
2293 *
2294 * Return value: %TRUE if @value was written, %FALSE otherwise
2295 *
2296 * Since: 1.5.8
2297 **/
2298gboolean
2299fu_common_write_uint8_safe (guint8 *buf,
2300 gsize bufsz,
2301 gsize offset,
2302 guint8 value,
2303 GError **error)
2304{
2305 g_return_val_if_fail (buf != NULL, FALSE);
2306 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2307
2308 return fu_memcpy_safe (buf, bufsz, offset, /* dst */
2309 &value, sizeof(value), 0x0, /* src */
2310 sizeof(value), error);
2311}
2312
2313/**
2314 * fu_common_write_uint16_safe:
2315 * @buf: source buffer
2316 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2317 * @offset: offset in bytes into @buf to write to
2318 * @value: the value to write
2319 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2320 * @error: A #GError or %NULL
2321 *
2322 * Write a value to a buffer using a specified endian in a safe way.
2323 *
2324 * You don't need to use this function in "obviously correct" cases, nor should
2325 * you use it when performance is a concern. Only us it when you're not sure if
2326 * malicious data from a device or firmware could cause memory corruption.
2327 *
2328 * Return value: %TRUE if @value was written, %FALSE otherwise
2329 *
2330 * Since: 1.5.8
2331 **/
2332gboolean
2333fu_common_write_uint16_safe (guint8 *buf,
2334 gsize bufsz,
2335 gsize offset,
2336 guint16 value,
2337 FuEndianType endian,
2338 GError **error)
2339{
2340 guint8 tmp[2] = { 0x0 };
2341
2342 g_return_val_if_fail (buf != NULL, FALSE);
2343 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2344
2345 fu_common_write_uint16 (tmp, value, endian);
2346 return fu_memcpy_safe (buf, bufsz, offset, /* dst */
2347 tmp, sizeof(tmp), 0x0, /* src */
2348 sizeof(tmp), error);
2349}
2350
2351/**
2352 * fu_common_write_uint32_safe:
2353 * @buf: source buffer
2354 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2355 * @offset: offset in bytes into @buf to write to
2356 * @value: the value to write
2357 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2358 * @error: A #GError or %NULL
2359 *
2360 * Write a value to a buffer using a specified endian in a safe way.
2361 *
2362 * You don't need to use this function in "obviously correct" cases, nor should
2363 * you use it when performance is a concern. Only us it when you're not sure if
2364 * malicious data from a device or firmware could cause memory corruption.
2365 *
2366 * Return value: %TRUE if @value was written, %FALSE otherwise
2367 *
2368 * Since: 1.5.8
2369 **/
2370gboolean
2371fu_common_write_uint32_safe (guint8 *buf,
2372 gsize bufsz,
2373 gsize offset,
2374 guint32 value,
2375 FuEndianType endian,
2376 GError **error)
2377{
2378 guint8 tmp[4] = { 0x0 };
2379
2380 g_return_val_if_fail (buf != NULL, FALSE);
2381 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2382
2383 fu_common_write_uint32 (tmp, value, endian);
2384 return fu_memcpy_safe (buf, bufsz, offset, /* dst */
2385 tmp, sizeof(tmp), 0x0, /* src */
2386 sizeof(tmp), error);
2387}
2388
2389/**
Richard Hughesf2849d22021-03-05 17:19:17 +00002390 * fu_common_write_uint64_safe:
2391 * @buf: source buffer
2392 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
2393 * @offset: offset in bytes into @buf to write to
2394 * @value: the value to write
2395 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
2396 * @error: A #GError or %NULL
2397 *
2398 * Write a value to a buffer using a specified endian in a safe way.
2399 *
2400 * You don't need to use this function in "obviously correct" cases, nor should
2401 * you use it when performance is a concern. Only us it when you're not sure if
2402 * malicious data from a device or firmware could cause memory corruption.
2403 *
2404 * Return value: %TRUE if @value was written, %FALSE otherwise
2405 *
2406 * Since: 1.5.8
2407 **/
2408gboolean
2409fu_common_write_uint64_safe (guint8 *buf,
2410 gsize bufsz,
2411 gsize offset,
2412 guint64 value,
2413 FuEndianType endian,
2414 GError **error)
2415{
2416 guint8 tmp[8] = { 0x0 };
2417
2418 g_return_val_if_fail (buf != NULL, FALSE);
2419 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2420
2421 fu_common_write_uint64 (tmp, value, endian);
2422 return fu_memcpy_safe (buf, bufsz, offset, /* dst */
2423 tmp, sizeof(tmp), 0x0, /* src */
2424 sizeof(tmp), error);
2425}
2426
2427/**
Mario Limonciello1a680f32019-11-25 19:44:53 -06002428 * fu_byte_array_append_uint8:
2429 * @array: A #GByteArray
2430 * @data: #guint8
2431 *
2432 * Adds a 8 bit integer to a byte array
2433 *
2434 * Since: 1.3.1
2435 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002436void
2437fu_byte_array_append_uint8 (GByteArray *array, guint8 data)
2438{
2439 g_byte_array_append (array, &data, sizeof(data));
2440}
2441
Mario Limonciello1a680f32019-11-25 19:44:53 -06002442/**
2443 * fu_byte_array_append_uint16:
2444 * @array: A #GByteArray
2445 * @data: #guint16
2446 * @endian: #FuEndianType
2447 *
2448 * Adds a 16 bit integer to a byte array
2449 *
2450 * Since: 1.3.1
2451 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002452void
2453fu_byte_array_append_uint16 (GByteArray *array, guint16 data, FuEndianType endian)
2454{
2455 guint8 buf[2];
2456 fu_common_write_uint16 (buf, data, endian);
2457 g_byte_array_append (array, buf, sizeof(buf));
2458}
2459
Mario Limonciello1a680f32019-11-25 19:44:53 -06002460/**
2461 * fu_byte_array_append_uint32:
2462 * @array: A #GByteArray
2463 * @data: #guint32
2464 * @endian: #FuEndianType
2465 *
2466 * Adds a 32 bit integer to a byte array
2467 *
2468 * Since: 1.3.1
2469 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01002470void
2471fu_byte_array_append_uint32 (GByteArray *array, guint32 data, FuEndianType endian)
2472{
2473 guint8 buf[4];
2474 fu_common_write_uint32 (buf, data, endian);
2475 g_byte_array_append (array, buf, sizeof(buf));
2476}
Mario Limonciello9dce1f72020-02-04 09:12:52 -06002477
2478/**
Richard Hughesf2849d22021-03-05 17:19:17 +00002479 * fu_byte_array_append_uint64:
2480 * @array: A #GByteArray
2481 * @data: #guint64
2482 * @endian: #FuEndianType
2483 *
2484 * Adds a 64 bit integer to a byte array
2485 *
2486 * Since: 1.5.8
2487 **/
2488void
2489fu_byte_array_append_uint64 (GByteArray *array, guint64 data, FuEndianType endian)
2490{
2491 guint8 buf[8];
2492 fu_common_write_uint64 (buf, data, endian);
2493 g_byte_array_append (array, buf, sizeof(buf));
2494}
2495
2496/**
Richard Hughese9664e82021-03-10 13:38:06 +00002497 * fu_byte_array_append_bytes:
2498 * @array: A #GByteArray
2499 * @bytes: A #GBytes
2500 *
2501 * Adds the contents of a GBytes to a byte array
2502 *
2503 * Since: 1.5.8
2504 **/
2505void
2506fu_byte_array_append_bytes (GByteArray *array, GBytes *bytes)
2507{
2508 g_byte_array_append (array,
2509 g_bytes_get_data (bytes, NULL),
2510 g_bytes_get_size (bytes));
2511}
2512
2513/**
Richard Hughes74db3402021-03-11 13:20:25 +00002514 * fu_byte_array_set_size_full:
2515 * @array: a #GByteArray
2516 * @length: the new size of the GByteArray
2517 * @data: the byte used to pad the array
2518 *
2519 * Sets the size of the GByteArray, expanding with @data as required.
2520 *
2521 * Since: 1.6.0
2522 **/
2523void
2524fu_byte_array_set_size_full (GByteArray *array, guint length, guint8 data)
2525{
2526 guint oldlength = array->len;
2527 g_byte_array_set_size (array, length);
2528 if (length > oldlength)
2529 memset (array->data + oldlength, data, length - oldlength);
2530}
2531
2532/**
Richard Hughesa2a8f8e2020-10-20 09:27:26 +01002533 * fu_byte_array_set_size:
2534 * @array: a #GByteArray
2535 * @length: the new size of the GByteArray
2536 *
2537 * Sets the size of the GByteArray, expanding it with NULs if necessary.
2538 *
2539 * Since: 1.5.0
2540 **/
2541void
2542fu_byte_array_set_size (GByteArray *array, guint length)
2543{
Richard Hughes74db3402021-03-11 13:20:25 +00002544 return fu_byte_array_set_size_full (array, length, 0x0);
2545}
2546
2547/**
2548 * fu_byte_array_align_up:
2549 * @array: a #GByteArray
2550 * @alignment: align to this power of 2
2551 * @data: the byte used to pad the array
2552 *
2553 * Align a byte array length to a power of 2 boundary, where @alignment is the
2554 * bit position to align to. If @alignment is zero then @array is unchanged.
2555 *
2556 * Since: 1.6.0
2557 **/
2558void
2559fu_byte_array_align_up (GByteArray *array, guint8 alignment, guint8 data)
2560{
2561 fu_byte_array_set_size_full (array,
2562 fu_common_align_up (array->len, alignment),
2563 data);
Richard Hughesa2a8f8e2020-10-20 09:27:26 +01002564}
2565
2566/**
Mario Limonciello9dce1f72020-02-04 09:12:52 -06002567 * fu_common_kernel_locked_down:
2568 *
2569 * Determines if kernel lockdown in effect
2570 *
2571 * Since: 1.3.8
2572 **/
2573gboolean
2574fu_common_kernel_locked_down (void)
2575{
Norbert Kamiński76e19932021-03-08 11:38:43 +01002576#ifdef __linux__
Mario Limonciello9dce1f72020-02-04 09:12:52 -06002577 gsize len = 0;
2578 g_autofree gchar *dir = fu_common_get_path (FU_PATH_KIND_SYSFSDIR_SECURITY);
2579 g_autofree gchar *fname = g_build_filename (dir, "lockdown", NULL);
2580 g_autofree gchar *data = NULL;
2581 g_auto(GStrv) options = NULL;
2582
2583 if (!g_file_test (fname, G_FILE_TEST_EXISTS))
2584 return FALSE;
2585 if (!g_file_get_contents (fname, &data, &len, NULL))
2586 return FALSE;
2587 if (len < 1)
2588 return FALSE;
2589 options = g_strsplit (data, " ", -1);
2590 for (guint i = 0; options[i] != NULL; i++) {
2591 if (g_strcmp0 (options[i], "[none]") == 0)
2592 return FALSE;
2593 }
2594 return TRUE;
2595#else
2596 return FALSE;
2597#endif
2598}
Richard Hughes9223c892020-05-09 20:32:08 +01002599
2600/**
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002601 * fu_common_cpuid:
2602 * @leaf: The CPUID level, now called the 'leaf' by Intel
2603 * @eax: (out) (nullable): EAX register
2604 * @ebx: (out) (nullable): EBX register
2605 * @ecx: (out) (nullable): ECX register
2606 * @edx: (out) (nullable): EDX register
2607 * @error: A #GError or NULL
2608 *
2609 * Calls CPUID and returns the registers for the given leaf.
2610 *
2611 * Return value: %TRUE if the registers are set.
2612 *
2613 * Since: 1.5.0
2614 **/
2615gboolean
2616fu_common_cpuid (guint32 leaf,
2617 guint32 *eax,
2618 guint32 *ebx,
2619 guint32 *ecx,
2620 guint32 *edx,
2621 GError **error)
2622{
2623#ifdef HAVE_CPUID_H
2624 guint eax_tmp = 0;
2625 guint ebx_tmp = 0;
2626 guint ecx_tmp = 0;
2627 guint edx_tmp = 0;
2628
Richard Hughes6a489a92020-12-22 10:32:06 +00002629 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
2630
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002631 /* get vendor */
Richard Hughes7c4a64b2020-08-23 21:20:58 +01002632 __get_cpuid_count (leaf, 0x0, &eax_tmp, &ebx_tmp, &ecx_tmp, &edx_tmp);
Richard Hughesbd1dc2a2020-08-20 15:35:28 +01002633 if (eax != NULL)
2634 *eax = eax_tmp;
2635 if (ebx != NULL)
2636 *ebx = ebx_tmp;
2637 if (ecx != NULL)
2638 *ecx = ecx_tmp;
2639 if (edx != NULL)
2640 *edx = edx_tmp;
2641 return TRUE;
2642#else
2643 g_set_error_literal (error,
2644 G_IO_ERROR,
2645 G_IO_ERROR_NOT_SUPPORTED,
2646 "no <cpuid.h> support");
2647 return FALSE;
2648#endif
2649}
2650
2651/**
Richard Hughesb63cfa92021-01-05 22:57:12 +00002652 * fu_common_get_cpu_vendor:
2653 *
2654 * Uses CPUID to discover the CPU vendor.
2655 *
2656 * Return value: a #FuCpuVendor, e.g. %FU_CPU_VENDOR_AMD if the vendor was AMD.
2657 *
2658 * Since: 1.5.5
2659 **/
2660FuCpuVendor
2661fu_common_get_cpu_vendor (void)
2662{
2663#ifdef HAVE_CPUID_H
Richard Hughes9223c892020-05-09 20:32:08 +01002664 guint ebx = 0;
2665 guint ecx = 0;
2666 guint edx = 0;
Richard Hughes9223c892020-05-09 20:32:08 +01002667
Richard Hughesb63cfa92021-01-05 22:57:12 +00002668 if (fu_common_cpuid (0x0, NULL, &ebx, &ecx, &edx, NULL)) {
2669 if (ebx == signature_INTEL_ebx &&
2670 edx == signature_INTEL_edx &&
2671 ecx == signature_INTEL_ecx) {
2672 return FU_CPU_VENDOR_INTEL;
2673 }
2674 if (ebx == signature_AMD_ebx &&
2675 edx == signature_AMD_edx &&
2676 ecx == signature_AMD_ecx) {
2677 return FU_CPU_VENDOR_AMD;
2678 }
Richard Hughes9223c892020-05-09 20:32:08 +01002679 }
Richard Hughesbd444322020-05-21 12:05:03 +01002680#endif
Richard Hughesb63cfa92021-01-05 22:57:12 +00002681
2682 /* failed */
2683 return FU_CPU_VENDOR_UNKNOWN;
Richard Hughes9223c892020-05-09 20:32:08 +01002684}
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002685
Richard Hughes36111472020-08-12 15:04:24 +01002686/**
2687 * fu_common_is_live_media:
2688 *
2689 * Checks if the user is running from a live media using various heuristics.
2690 *
2691 * Returns: %TRUE if live
2692 *
2693 * Since: 1.4.6
2694 **/
2695gboolean
2696fu_common_is_live_media (void)
2697{
2698 gsize bufsz = 0;
2699 g_autofree gchar *buf = NULL;
2700 g_auto(GStrv) tokens = NULL;
2701 const gchar *args[] = {
2702 "rd.live.image",
2703 "boot=live",
2704 NULL, /* last entry */
2705 };
2706 if (g_file_test ("/cdrom/.disk/info", G_FILE_TEST_EXISTS))
2707 return TRUE;
2708 if (!g_file_get_contents ("/proc/cmdline", &buf, &bufsz, NULL))
2709 return FALSE;
2710 if (bufsz == 0)
2711 return FALSE;
2712 tokens = fu_common_strnsplit (buf, bufsz - 1, " ", -1);
2713 for (guint i = 0; args[i] != NULL; i++) {
2714 if (g_strv_contains ((const gchar * const *) tokens, args[i]))
2715 return TRUE;
2716 }
2717 return FALSE;
2718}
2719
Richard Hughes68175e92021-01-14 09:43:33 +00002720/**
2721 * fu_common_get_memory_size:
2722 *
2723 * Returns the size of physical memory.
2724 *
2725 * Returns: bytes
2726 *
2727 * Since: 1.5.6
2728 **/
2729guint64
2730fu_common_get_memory_size (void)
2731{
2732#ifdef _WIN32
2733 MEMORYSTATUSEX status;
2734 status.dwLength = sizeof(status);
2735 GlobalMemoryStatusEx (&status);
2736 return (guint64) status.ullTotalPhys;
2737#else
Richard Hughes9c318a52021-03-20 16:11:00 +00002738 return (guint64) sysconf (_SC_PHYS_PAGES) * (guint64) sysconf (_SC_PAGE_SIZE);
Richard Hughes68175e92021-01-14 09:43:33 +00002739#endif
2740}
2741
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002742static GPtrArray *
Richard Hughes43417b22020-10-30 14:46:16 +00002743fu_common_get_block_devices (GError **error)
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002744{
2745 GVariantBuilder builder;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002746 const gchar *obj;
2747 g_autoptr(GVariant) output = NULL;
2748 g_autoptr(GDBusProxy) proxy = NULL;
2749 g_autoptr(GPtrArray) devices = NULL;
2750 g_autoptr(GVariantIter) iter = NULL;
Richard Hughes43417b22020-10-30 14:46:16 +00002751 g_autoptr(GDBusConnection) connection = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002752
Richard Hughes43417b22020-10-30 14:46:16 +00002753 connection = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, error);
2754 if (connection == NULL) {
2755 g_prefix_error (error, "failed to get system bus: ");
2756 return NULL;
2757 }
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002758 proxy = g_dbus_proxy_new_sync (connection,
2759 G_DBUS_PROXY_FLAGS_NONE, NULL,
2760 UDISKS_DBUS_SERVICE,
2761 UDISKS_DBUS_PATH,
2762 UDISKS_DBUS_MANAGER_INTERFACE,
2763 NULL, error);
2764 if (proxy == NULL) {
2765 g_prefix_error (error, "failed to find %s: ", UDISKS_DBUS_SERVICE);
2766 return NULL;
2767 }
2768 g_variant_builder_init (&builder, G_VARIANT_TYPE_VARDICT);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002769 output = g_dbus_proxy_call_sync (proxy,
Richard Hughesdb344d52020-09-09 19:42:27 +01002770 "GetBlockDevices",
2771 g_variant_new ("(a{sv})", &builder),
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002772 G_DBUS_CALL_FLAGS_NONE,
2773 -1, NULL, error);
Richard Hughes0bdf5612020-10-30 14:56:22 +00002774 if (output == NULL) {
2775 if (error != NULL)
2776 g_dbus_error_strip_remote_error (*error);
2777 g_prefix_error (error, "failed to call %s.%s(): ",
2778 UDISKS_DBUS_SERVICE,
2779 "GetBlockDevices");
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002780 return NULL;
Richard Hughes0bdf5612020-10-30 14:56:22 +00002781 }
Richard Hughes43417b22020-10-30 14:46:16 +00002782 devices = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002783 g_variant_get (output, "(ao)", &iter);
Richard Hughes43417b22020-10-30 14:46:16 +00002784 while (g_variant_iter_next (iter, "&o", &obj)) {
2785 g_autoptr(GDBusProxy) proxy_blk = NULL;
2786 proxy_blk = g_dbus_proxy_new_sync (connection,
2787 G_DBUS_PROXY_FLAGS_NONE, NULL,
2788 UDISKS_DBUS_SERVICE,
2789 obj,
2790 UDISKS_DBUS_INTERFACE_BLOCK,
2791 NULL, error);
2792 if (proxy_blk == NULL) {
2793 g_prefix_error (error, "failed to initialize d-bus proxy for %s: ", obj);
2794 return NULL;
2795 }
2796 g_ptr_array_add (devices, g_steal_pointer (&proxy_blk));
2797 }
2798
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002799
2800 return g_steal_pointer (&devices);
2801}
2802
Richard Hughesad3cfc02021-02-22 10:02:54 +00002803static const gchar *
2804fu_common_convert_to_gpt_type (const gchar *type)
2805{
2806 struct {
2807 const gchar *mbr;
2808 const gchar *gpt;
2809 } typeguids[] = {
2810 { "0xef", "c12a7328-f81f-11d2-ba4b-00a0c93ec93b" }, /* esp */
2811 { "0x0b", "ebd0a0a2-b9e5-4433-87c0-68b6b72699c7" }, /* fat32 */
2812 { NULL, NULL }
2813 };
2814 for (guint i = 0; typeguids[i].mbr != NULL; i++) {
2815 if (g_strcmp0 (type, typeguids[i].mbr) == 0)
2816 return typeguids[i].gpt;
2817 }
2818 return type;
2819}
2820
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002821/**
2822 * fu_common_get_volumes_by_kind:
2823 * @kind: A volume kind, typically a GUID
2824 * @error: A #GError or NULL
2825 *
Richard Hughesc57a8f52020-10-30 14:42:42 +00002826 * Finds all volumes of a specific partition type
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002827 *
2828 * Returns: (transfer container) (element-type FuVolume): a #GPtrArray, or %NULL if the kind was not found
2829 *
2830 * Since: 1.4.6
2831 **/
2832GPtrArray *
2833fu_common_get_volumes_by_kind (const gchar *kind, GError **error)
2834{
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002835 g_autoptr(GPtrArray) devices = NULL;
2836 g_autoptr(GPtrArray) volumes = NULL;
2837
Richard Hughes6a489a92020-12-22 10:32:06 +00002838 g_return_val_if_fail (kind != NULL, NULL);
2839 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2840
Richard Hughes43417b22020-10-30 14:46:16 +00002841 devices = fu_common_get_block_devices (error);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002842 if (devices == NULL)
Richard Hughesb81140d2020-08-17 14:47:17 +01002843 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002844 volumes = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref);
2845 for (guint i = 0; i < devices->len; i++) {
Richard Hughes43417b22020-10-30 14:46:16 +00002846 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002847 const gchar *type_str;
Mario Limonciello56d816a2020-11-11 16:59:30 -06002848 g_autoptr(FuVolume) vol = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002849 g_autoptr(GDBusProxy) proxy_part = NULL;
Richard Hughes43417b22020-10-30 14:46:16 +00002850 g_autoptr(GDBusProxy) proxy_fs = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002851 g_autoptr(GVariant) val = NULL;
2852
Richard Hughes43417b22020-10-30 14:46:16 +00002853 proxy_part = g_dbus_proxy_new_sync (g_dbus_proxy_get_connection (proxy_blk),
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002854 G_DBUS_PROXY_FLAGS_NONE, NULL,
2855 UDISKS_DBUS_SERVICE,
Richard Hughes43417b22020-10-30 14:46:16 +00002856 g_dbus_proxy_get_object_path (proxy_blk),
2857 UDISKS_DBUS_INTERFACE_PARTITION,
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002858 NULL, error);
2859 if (proxy_part == NULL) {
Richard Hughes43417b22020-10-30 14:46:16 +00002860 g_prefix_error (error, "failed to initialize d-bus proxy %s: ",
2861 g_dbus_proxy_get_object_path (proxy_blk));
Richard Hughesb81140d2020-08-17 14:47:17 +01002862 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002863 }
2864 val = g_dbus_proxy_get_cached_property (proxy_part, "Type");
2865 if (val == NULL)
2866 continue;
2867
Richard Hughesdb344d52020-09-09 19:42:27 +01002868 g_variant_get (val, "&s", &type_str);
Richard Hughes43417b22020-10-30 14:46:16 +00002869 proxy_fs = g_dbus_proxy_new_sync (g_dbus_proxy_get_connection (proxy_blk),
2870 G_DBUS_PROXY_FLAGS_NONE, NULL,
2871 UDISKS_DBUS_SERVICE,
2872 g_dbus_proxy_get_object_path (proxy_blk),
2873 UDISKS_DBUS_INTERFACE_FILESYSTEM,
2874 NULL, error);
2875 if (proxy_fs == NULL) {
2876 g_prefix_error (error, "failed to initialize d-bus proxy %s: ",
2877 g_dbus_proxy_get_object_path (proxy_blk));
Richard Hughesb81140d2020-08-17 14:47:17 +01002878 return NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002879 }
Mario Limonciello56d816a2020-11-11 16:59:30 -06002880 vol = g_object_new (FU_TYPE_VOLUME,
2881 "proxy-block", proxy_blk,
2882 "proxy-filesystem", proxy_fs,
2883 NULL);
Richard Hughesad3cfc02021-02-22 10:02:54 +00002884
2885 /* convert MBR type to GPT type */
2886 type_str = fu_common_convert_to_gpt_type (type_str);
Mario Limonciello56d816a2020-11-11 16:59:30 -06002887 g_debug ("device %s, type: %s, internal: %d, fs: %s",
2888 g_dbus_proxy_get_object_path (proxy_blk), type_str,
2889 fu_volume_is_internal (vol),
2890 fu_volume_get_id_type (vol));
2891 if (g_strcmp0 (type_str, kind) != 0)
2892 continue;
2893 g_ptr_array_add (volumes, g_steal_pointer (&vol));
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002894 }
2895 if (volumes->len == 0) {
2896 g_set_error (error,
2897 G_IO_ERROR,
2898 G_IO_ERROR_NOT_FOUND,
2899 "no volumes of type %s", kind);
2900 return NULL;
2901 }
2902 return g_steal_pointer (&volumes);
2903}
2904
2905/**
Richard Hughes0bdf5612020-10-30 14:56:22 +00002906 * fu_common_get_volume_by_device:
2907 * @device: A device string, typcically starting with `/dev/`
2908 * @error: A #GError or NULL
2909 *
2910 * Finds the first volume from the specified device.
2911 *
2912 * Returns: (transfer full): a #GPtrArray, or %NULL if the kind was not found
2913 *
2914 * Since: 1.5.1
2915 **/
2916FuVolume *
2917fu_common_get_volume_by_device (const gchar *device, GError **error)
2918{
2919 g_autoptr(GPtrArray) devices = NULL;
2920
Richard Hughes6a489a92020-12-22 10:32:06 +00002921 g_return_val_if_fail (device != NULL, NULL);
2922 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2923
Richard Hughes0bdf5612020-10-30 14:56:22 +00002924 /* find matching block device */
2925 devices = fu_common_get_block_devices (error);
2926 if (devices == NULL)
2927 return NULL;
2928 for (guint i = 0; i < devices->len; i++) {
2929 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
2930 g_autoptr(GVariant) val = NULL;
2931 val = g_dbus_proxy_get_cached_property (proxy_blk, "Device");
2932 if (val == NULL)
2933 continue;
2934 if (g_strcmp0 (g_variant_get_bytestring (val), device) == 0) {
2935 return g_object_new (FU_TYPE_VOLUME,
2936 "proxy-block", proxy_blk,
2937 NULL);
2938 }
2939 }
2940
2941 /* failed */
2942 g_set_error (error,
2943 G_IO_ERROR,
2944 G_IO_ERROR_NOT_FOUND,
2945 "no volumes for device %s",
2946 device);
2947 return NULL;
2948}
2949
2950/**
2951 * fu_common_get_volume_by_devnum:
Richard Hughese0f92072020-11-06 09:50:29 +00002952 * @devnum: A device number
Richard Hughes0bdf5612020-10-30 14:56:22 +00002953 * @error: A #GError or NULL
2954 *
2955 * Finds the first volume from the specified device.
2956 *
2957 * Returns: (transfer full): a #GPtrArray, or %NULL if the kind was not found
2958 *
2959 * Since: 1.5.1
2960 **/
2961FuVolume *
2962fu_common_get_volume_by_devnum (guint32 devnum, GError **error)
2963{
2964 g_autoptr(GPtrArray) devices = NULL;
2965
Richard Hughes6a489a92020-12-22 10:32:06 +00002966 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2967
Richard Hughes0bdf5612020-10-30 14:56:22 +00002968 /* find matching block device */
2969 devices = fu_common_get_block_devices (error);
2970 if (devices == NULL)
2971 return NULL;
2972 for (guint i = 0; i < devices->len; i++) {
2973 GDBusProxy *proxy_blk = g_ptr_array_index (devices, i);
2974 g_autoptr(GVariant) val = NULL;
2975 val = g_dbus_proxy_get_cached_property (proxy_blk, "DeviceNumber");
2976 if (val == NULL)
2977 continue;
2978 if (devnum == g_variant_get_uint64 (val)) {
2979 return g_object_new (FU_TYPE_VOLUME,
2980 "proxy-block", proxy_blk,
2981 NULL);
2982 }
2983 }
2984
2985 /* failed */
2986 g_set_error (error,
2987 G_IO_ERROR,
2988 G_IO_ERROR_NOT_FOUND,
2989 "no volumes for devnum %u",
2990 devnum);
2991 return NULL;
2992}
2993
2994/**
Richard Hughes8f0b2d12020-08-12 12:41:53 +01002995 * fu_common_get_esp_default:
2996 * @error: A #GError or NULL
2997 *
2998 * Gets the platform default ESP
2999 *
3000 * Returns: (transfer full): a #FuVolume, or %NULL if the ESP was not found
3001 *
3002 * Since: 1.4.6
3003 **/
3004FuVolume *
3005fu_common_get_esp_default (GError **error)
3006{
3007 const gchar *path_tmp;
Richard Hughes9d20bf92020-12-14 09:36:46 +00003008 gboolean has_internal = FALSE;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01003009 g_autoptr(GPtrArray) volumes_fstab = g_ptr_array_new ();
3010 g_autoptr(GPtrArray) volumes_mtab = g_ptr_array_new ();
Mario Limonciello56d816a2020-11-11 16:59:30 -06003011 g_autoptr(GPtrArray) volumes_vfat = g_ptr_array_new ();
Richard Hughes8f0b2d12020-08-12 12:41:53 +01003012 g_autoptr(GPtrArray) volumes = NULL;
Mario Limonciello56d816a2020-11-11 16:59:30 -06003013 g_autoptr(GError) error_local = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01003014
Richard Hughes6a489a92020-12-22 10:32:06 +00003015 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3016
Richard Hughes8f0b2d12020-08-12 12:41:53 +01003017 /* for the test suite use local directory for ESP */
3018 path_tmp = g_getenv ("FWUPD_UEFI_ESP_PATH");
3019 if (path_tmp != NULL)
3020 return fu_volume_new_from_mount_path (path_tmp);
3021
Mario Limonciello56d816a2020-11-11 16:59:30 -06003022 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_ESP, &error_local);
3023 if (volumes == NULL) {
3024 g_debug ("%s, falling back to %s", error_local->message, FU_VOLUME_KIND_BDP);
3025 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_BDP, error);
3026 if (volumes == NULL) {
3027 g_prefix_error (error, "%s: ", error_local->message);
3028 return NULL;
3029 }
3030 }
Richard Hughes9d20bf92020-12-14 09:36:46 +00003031
3032 /* are there _any_ internal vfat partitions?
3033 * remember HintSystem is just that -- a hint! */
3034 for (guint i = 0; i < volumes->len; i++) {
3035 FuVolume *vol = g_ptr_array_index (volumes, i);
3036 g_autofree gchar *type = fu_volume_get_id_type (vol);
3037 if (g_strcmp0 (type, "vfat") == 0 &&
3038 fu_volume_is_internal (vol)) {
3039 has_internal = TRUE;
3040 break;
3041 }
3042 }
3043
3044 /* filter to vfat partitions */
Richard Hughes8f0b2d12020-08-12 12:41:53 +01003045 for (guint i = 0; i < volumes->len; i++) {
3046 FuVolume *vol = g_ptr_array_index (volumes, i);
Mario Limonciello56d816a2020-11-11 16:59:30 -06003047 g_autofree gchar *type = fu_volume_get_id_type (vol);
3048 if (type == NULL)
3049 continue;
Richard Hughes9d20bf92020-12-14 09:36:46 +00003050 if (has_internal && !fu_volume_is_internal (vol))
Mario Limonciello56d816a2020-11-11 16:59:30 -06003051 continue;
3052 if (g_strcmp0 (type, "vfat") == 0)
3053 g_ptr_array_add (volumes_vfat, vol);
3054 }
3055 if (volumes_vfat->len == 0) {
3056 g_set_error (error,
3057 G_IO_ERROR,
3058 G_IO_ERROR_INVALID_FILENAME,
3059 "No ESP found");
3060 return NULL;
3061 }
3062 for (guint i = 0; i < volumes_vfat->len; i++) {
3063 FuVolume *vol = g_ptr_array_index (volumes_vfat, i);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01003064 g_ptr_array_add (fu_volume_is_mounted (vol) ? volumes_mtab : volumes_fstab, vol);
3065 }
3066 if (volumes_mtab->len == 1) {
3067 FuVolume *vol = g_ptr_array_index (volumes_mtab, 0);
3068 return g_object_ref (vol);
3069 }
3070 if (volumes_mtab->len == 0 && volumes_fstab->len == 1) {
3071 FuVolume *vol = g_ptr_array_index (volumes_fstab, 0);
3072 return g_object_ref (vol);
3073 }
3074 g_set_error (error,
3075 G_IO_ERROR,
3076 G_IO_ERROR_INVALID_FILENAME,
3077 "More than one available ESP");
3078 return NULL;
3079}
3080
3081/**
3082 * fu_common_get_esp_for_path:
3083 * @esp_path: A path to the ESP
3084 * @error: A #GError or NULL
3085 *
3086 * Gets the platform ESP using a UNIX or UDisks path
3087 *
3088 * Returns: (transfer full): a #FuVolume, or %NULL if the ESP was not found
3089 *
3090 * Since: 1.4.6
3091 **/
3092FuVolume *
3093fu_common_get_esp_for_path (const gchar *esp_path, GError **error)
3094{
Richard Hughes6a489a92020-12-22 10:32:06 +00003095 g_autofree gchar *basename = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01003096 g_autoptr(GPtrArray) volumes = NULL;
Mario Limonciellobe220a42021-02-10 10:39:58 -06003097 g_autoptr(GError) error_local = NULL;
Richard Hughes8f0b2d12020-08-12 12:41:53 +01003098
Richard Hughes6a489a92020-12-22 10:32:06 +00003099 g_return_val_if_fail (esp_path != NULL, NULL);
3100 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
3101
Mario Limonciellobe220a42021-02-10 10:39:58 -06003102 volumes = fu_common_get_volumes_by_kind (FU_VOLUME_KIND_ESP, &error_local);
3103 if (volumes == NULL) {
3104 /* check if it's a valid directory already */
3105 if (g_file_test (esp_path, G_FILE_TEST_IS_DIR))
3106 return fu_volume_new_from_mount_path (esp_path);
3107 g_propagate_error (error, g_steal_pointer (&error_local));
Richard Hughesb81140d2020-08-17 14:47:17 +01003108 return NULL;
Mario Limonciellobe220a42021-02-10 10:39:58 -06003109 }
Richard Hughes6a489a92020-12-22 10:32:06 +00003110 basename = g_path_get_basename (esp_path);
Richard Hughes8f0b2d12020-08-12 12:41:53 +01003111 for (guint i = 0; i < volumes->len; i++) {
3112 FuVolume *vol = g_ptr_array_index (volumes, i);
Mario Limonciello5a835632020-10-07 14:22:08 -05003113 g_autofree gchar *vol_basename = g_path_get_basename (fu_volume_get_mount_point (vol));
Richard Hughes8f0b2d12020-08-12 12:41:53 +01003114 if (g_strcmp0 (basename, vol_basename) == 0)
3115 return g_object_ref (vol);
3116 }
3117 g_set_error (error,
3118 G_IO_ERROR,
3119 G_IO_ERROR_INVALID_FILENAME,
3120 "No ESP with path %s",
3121 esp_path);
3122 return NULL;
3123}
Richard Hughes6f5e35a2020-09-25 14:14:52 +01003124
3125/**
Richard Hughes44ae2a72020-09-25 18:00:21 +01003126 * fu_common_crc8:
3127 * @buf: memory buffer
3128 * @bufsz: sizeof buf
3129 *
3130 * Returns the cyclic redundancy check value for the given memory buffer.
3131 *
3132 * Returns: CRC value
3133 *
3134 * Since: 1.5.0
3135 **/
3136guint8
3137fu_common_crc8 (const guint8 *buf, gsize bufsz)
3138{
3139 guint32 crc = 0;
3140 for (gsize j = bufsz; j > 0; j--) {
3141 crc ^= (*(buf++) << 8);
3142 for (guint32 i = 8; i; i--) {
3143 if (crc & 0x8000)
3144 crc ^= (0x1070 << 3);
3145 crc <<= 1;
3146 }
3147 }
3148 return ~((guint8) (crc >> 8));
3149}
3150
3151/**
Richard Hughes6f5e35a2020-09-25 14:14:52 +01003152 * fu_common_crc16:
3153 * @buf: memory buffer
3154 * @bufsz: sizeof buf
3155 *
3156 * Returns the cyclic redundancy check value for the given memory buffer.
3157 *
3158 * Returns: CRC value
3159 *
3160 * Since: 1.5.0
3161 **/
3162guint16
3163fu_common_crc16 (const guint8 *buf, gsize bufsz)
3164{
3165 guint16 crc = 0xffff;
3166 for (gsize len = bufsz; len > 0; len--) {
3167 crc = (guint16) (crc ^ (*buf++));
3168 for (guint8 i = 0; i < 8; i++) {
3169 if (crc & 0x1) {
3170 crc = (crc >> 1) ^ 0xa001;
3171 } else {
3172 crc >>= 1;
3173 }
3174 }
3175 }
3176 return ~crc;
3177}
3178
3179/**
3180 * fu_common_crc32_full:
3181 * @buf: memory buffer
3182 * @bufsz: sizeof buf
3183 * @crc: initial CRC value, typically 0xFFFFFFFF
3184 * @polynomial: CRC polynomial, typically 0xEDB88320
3185 *
3186 * Returns the cyclic redundancy check value for the given memory buffer.
3187 *
3188 * Returns: CRC value
3189 *
3190 * Since: 1.5.0
3191 **/
3192guint32
3193fu_common_crc32_full (const guint8 *buf, gsize bufsz, guint32 crc, guint32 polynomial)
3194{
3195 for (guint32 idx = 0; idx < bufsz; idx++) {
3196 guint8 data = *buf++;
3197 crc = crc ^ data;
3198 for (guint32 bit = 0; bit < 8; bit++) {
3199 guint32 mask = -(crc & 1);
3200 crc = (crc >> 1) ^ (polynomial & mask);
3201 }
3202 }
3203 return ~crc;
3204}
3205
3206/**
3207 * fu_common_crc32:
3208 * @buf: memory buffer
3209 * @bufsz: sizeof buf
3210 *
3211 * Returns the cyclic redundancy check value for the given memory buffer.
3212 *
3213 * Returns: CRC value
3214 *
3215 * Since: 1.5.0
3216 **/
3217guint32
3218fu_common_crc32 (const guint8 *buf, gsize bufsz)
3219{
3220 return fu_common_crc32_full (buf, bufsz, 0xFFFFFFFF, 0xEDB88320);
3221}
Richard Hughesc7546672021-01-28 10:53:30 +00003222
3223/**
3224 * fu_common_uri_get_scheme:
3225 * @uri: valid URI, e.g. `https://foo.bar/baz`
3226 *
3227 * Returns the USI scheme for the given URI.
3228 *
3229 * Returns: scheme value, or %NULL if invalid, e.g. `https`
3230 *
3231 * Since: 1.5.6
3232 **/
3233gchar *
3234fu_common_uri_get_scheme (const gchar *uri)
3235{
3236 gchar *tmp;
3237
3238 g_return_val_if_fail (uri != NULL, NULL);
3239
3240 tmp = g_strstr_len (uri, -1, ":");
3241 if (tmp == NULL || tmp[0] == '\0')
3242 return NULL;
3243 return g_utf8_strdown (uri, tmp - uri);
3244}
Richard Hughes58d52ed2021-03-10 13:42:59 +00003245
3246/**
3247 * fu_common_align_up:
3248 * @value: value to align
Richard Hughes119d2602021-03-17 10:07:38 +00003249 * @alignment: align to this power of 2, where 0x1F is the maximum value of 2GB
Richard Hughes58d52ed2021-03-10 13:42:59 +00003250 *
3251 * Align a value to a power of 2 boundary, where @alignment is the bit position
3252 * to align to. If @alignment is zero then @value is always returned unchanged.
3253 *
3254 * Returns: aligned value, which will be the same as @value if already aligned,
3255 * or %G_MAXSIZE if the value would overflow
3256 *
3257 * Since: 1.6.0
3258 **/
3259gsize
3260fu_common_align_up (gsize value, guint8 alignment)
3261{
3262 gsize value_new;
3263 guint32 mask = 1 << alignment;
3264
Richard Hughes119d2602021-03-17 10:07:38 +00003265 g_return_val_if_fail (alignment <= FU_FIRMWARE_ALIGNMENT_2G, G_MAXSIZE);
3266
Richard Hughes58d52ed2021-03-10 13:42:59 +00003267 /* no alignment required */
3268 if ((value & (mask - 1)) == 0)
3269 return value;
3270
3271 /* increment up to the next alignment value */
3272 value_new = value + mask;
3273 value_new &= ~(mask - 1);
3274
3275 /* overflow */
3276 if (value_new < value)
3277 return G_MAXSIZE;
3278
3279 /* success */
3280 return value_new;
3281}
Richard Hughes52441f22021-03-12 21:21:10 +00003282
3283/**
Richard Hughes4d76d182021-04-06 13:35:15 +01003284 * fu_battery_state_to_string:
3285 * @battery_state: a #FuBatteryState, e.g. %FU_BATTERY_STATE_FULLY_CHARGED
3286 *
3287 * Converts an enumerated type to a string.
3288 *
3289 * Returns: a string, or %NULL for invalid
3290 *
3291 * Since: 1.6.0
3292 **/
3293const gchar *
3294fu_battery_state_to_string (FuBatteryState battery_state)
3295{
3296 if (battery_state == FU_BATTERY_STATE_UNKNOWN)
3297 return "unknown";
3298 if (battery_state == FU_BATTERY_STATE_CHARGING)
3299 return "charging";
3300 if (battery_state == FU_BATTERY_STATE_DISCHARGING)
3301 return "discharging";
3302 if (battery_state == FU_BATTERY_STATE_EMPTY)
3303 return "empty";
3304 if (battery_state == FU_BATTERY_STATE_FULLY_CHARGED)
3305 return "fully-charged";
3306 return NULL;
3307}
3308
3309/**
Richard Hughes52441f22021-03-12 21:21:10 +00003310 * fu_xmlb_builder_insert_kv:
3311 * @bn: #JsonBuilder
3312 * @key: string key
3313 * @value: string value
3314 *
3315 * Convenience function to add an XML node with a string value. If @value is %NULL
3316 * then no member is added.
3317 *
3318 * Since: 1.6.0
3319 **/
3320void
3321fu_xmlb_builder_insert_kv (XbBuilderNode *bn, const gchar *key, const gchar *value)
3322{
3323 if (value == NULL)
3324 return;
3325 xb_builder_node_insert_text (bn, key, value, NULL);
3326}
3327
3328/**
3329 * fu_xmlb_builder_insert_kx:
3330 * @bn: #JsonBuilder
3331 * @key: string key
3332 * @value: integer value
3333 *
3334 * Convenience function to add an XML node with a integer value. If @value is 0
3335 * then no member is added.
3336 *
3337 * Since: 1.6.0
3338 **/
3339void
3340fu_xmlb_builder_insert_kx (XbBuilderNode *bn, const gchar *key, guint64 value)
3341{
3342 g_autofree gchar *value_hex = NULL;
3343 if (value == 0)
3344 return;
3345 value_hex = g_strdup_printf ("0x%x", (guint) value);
3346 xb_builder_node_insert_text (bn, key, value_hex, NULL);
3347}
3348
3349/**
3350 * fu_xmlb_builder_insert_kb:
3351 * @bn: #JsonBuilder
3352 * @key: string key
3353 * @value: boolean value
3354 *
3355 * Convenience function to add an XML node with a boolean value.
3356 *
3357 * Since: 1.6.0
3358 **/
3359void
3360fu_xmlb_builder_insert_kb (XbBuilderNode *bn, const gchar *key, gboolean value)
3361{
3362 xb_builder_node_insert_text (bn, key, value ? "true" : "false", NULL);
3363}