blob: 071a7e5a1ec569667eeb2187918aeafc697cd862 [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 Hughesbd444322020-05-21 12:05:03 +010022#ifdef HAVE_CPUID_H
Richard Hughes9223c892020-05-09 20:32:08 +010023#include <cpuid.h>
Richard Hughesbd444322020-05-21 12:05:03 +010024#endif
Richard Hughes9223c892020-05-09 20:32:08 +010025
Richard Hughes94f939a2017-08-08 12:21:39 +010026#include <archive_entry.h>
27#include <archive.h>
Richard Hughes7ee42fe2017-08-15 14:06:21 +010028#include <errno.h>
Richard Hughes484ee292019-03-22 16:10:50 +000029#include <limits.h>
Richard Hughesae252cd2017-12-08 10:48:15 +000030#include <string.h>
Richard Hughes484ee292019-03-22 16:10:50 +000031#include <stdlib.h>
Richard Hughes943d2c92017-06-21 09:04:39 +010032
33#include "fwupd-error.h"
34
35#include "fu-common.h"
36
37/**
Richard Hughes4eada342017-10-03 21:20:32 +010038 * SECTION:fu-common
39 * @short_description: common functionality for plugins to use
40 *
41 * Helper functions that can be used by the daemon and plugins.
42 *
43 * See also: #FuPlugin
44 */
45
46/**
Richard Hughes954dd9f2017-08-08 13:36:25 +010047 * fu_common_rmtree:
48 * @directory: a directory name
49 * @error: A #GError or %NULL
50 *
51 * Recursively removes a directory.
52 *
53 * Returns: %TRUE for success, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -060054 *
55 * Since: 0.9.7
Richard Hughes954dd9f2017-08-08 13:36:25 +010056 **/
57gboolean
58fu_common_rmtree (const gchar *directory, GError **error)
59{
60 const gchar *filename;
61 g_autoptr(GDir) dir = NULL;
62
63 /* try to open */
Richard Hughes455fdd32017-08-16 12:26:44 +010064 g_debug ("removing %s", directory);
Richard Hughes954dd9f2017-08-08 13:36:25 +010065 dir = g_dir_open (directory, 0, error);
66 if (dir == NULL)
67 return FALSE;
68
69 /* find each */
70 while ((filename = g_dir_read_name (dir))) {
71 g_autofree gchar *src = NULL;
72 src = g_build_filename (directory, filename, NULL);
73 if (g_file_test (src, G_FILE_TEST_IS_DIR)) {
74 if (!fu_common_rmtree (src, error))
75 return FALSE;
76 } else {
77 if (g_unlink (src) != 0) {
78 g_set_error (error,
79 FWUPD_ERROR,
80 FWUPD_ERROR_INTERNAL,
81 "Failed to delete: %s", src);
82 return FALSE;
83 }
84 }
85 }
86 if (g_remove (directory) != 0) {
87 g_set_error (error,
88 FWUPD_ERROR,
89 FWUPD_ERROR_INTERNAL,
90 "Failed to delete: %s", directory);
91 return FALSE;
92 }
93 return TRUE;
94}
95
Richard Hughes89e968b2018-03-07 10:01:08 +000096static gboolean
97fu_common_get_file_list_internal (GPtrArray *files, const gchar *directory, GError **error)
98{
99 const gchar *filename;
100 g_autoptr(GDir) dir = NULL;
101
102 /* try to open */
103 dir = g_dir_open (directory, 0, error);
104 if (dir == NULL)
105 return FALSE;
106
107 /* find each */
108 while ((filename = g_dir_read_name (dir))) {
109 g_autofree gchar *src = g_build_filename (directory, filename, NULL);
110 if (g_file_test (src, G_FILE_TEST_IS_DIR)) {
111 if (!fu_common_get_file_list_internal (files, src, error))
112 return FALSE;
113 } else {
114 g_ptr_array_add (files, g_steal_pointer (&src));
115 }
116 }
117 return TRUE;
118
119}
120
121/**
122 * fu_common_get_files_recursive:
Richard Hughes8aa72392018-05-02 08:38:43 +0100123 * @path: a directory name
Richard Hughes89e968b2018-03-07 10:01:08 +0000124 * @error: A #GError or %NULL
125 *
126 * Returns every file found under @directory, and any subdirectory.
127 * If any path under @directory cannot be accessed due to permissions an error
128 * will be returned.
129 *
Richard Hughesa0d81c72019-11-27 11:41:54 +0000130 * Returns: (transfer container) (element-type utf8): array of files, or %NULL for error
Mario Limonciello1a680f32019-11-25 19:44:53 -0600131 *
132 * Since: 1.0.6
Richard Hughes89e968b2018-03-07 10:01:08 +0000133 **/
134GPtrArray *
135fu_common_get_files_recursive (const gchar *path, GError **error)
136{
137 g_autoptr(GPtrArray) files = g_ptr_array_new_with_free_func (g_free);
138 if (!fu_common_get_file_list_internal (files, path, error))
139 return NULL;
140 return g_steal_pointer (&files);
141}
Richard Hughes954dd9f2017-08-08 13:36:25 +0100142/**
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100143 * fu_common_mkdir_parent:
144 * @filename: A full pathname
145 * @error: A #GError, or %NULL
146 *
147 * Creates any required directories, including any parent directories.
148 *
149 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600150 *
151 * Since: 0.9.7
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100152 **/
153gboolean
154fu_common_mkdir_parent (const gchar *filename, GError **error)
155{
156 g_autofree gchar *parent = NULL;
Richard Hughes455fdd32017-08-16 12:26:44 +0100157
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100158 parent = g_path_get_dirname (filename);
Richard Hughes455fdd32017-08-16 12:26:44 +0100159 g_debug ("creating path %s", parent);
Richard Hughes7ee42fe2017-08-15 14:06:21 +0100160 if (g_mkdir_with_parents (parent, 0755) == -1) {
161 g_set_error (error,
162 FWUPD_ERROR,
163 FWUPD_ERROR_INTERNAL,
164 "Failed to create '%s': %s",
165 parent, g_strerror (errno));
166 return FALSE;
167 }
168 return TRUE;
169}
170
171/**
Richard Hughes943d2c92017-06-21 09:04:39 +0100172 * fu_common_set_contents_bytes:
173 * @filename: A filename
174 * @bytes: The data to write
175 * @error: A #GError, or %NULL
176 *
177 * Writes a blob of data to a filename, creating the parent directories as
178 * required.
179 *
180 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600181 *
182 * Since: 0.9.5
Richard Hughes943d2c92017-06-21 09:04:39 +0100183 **/
184gboolean
185fu_common_set_contents_bytes (const gchar *filename, GBytes *bytes, GError **error)
186{
187 const gchar *data;
188 gsize size;
189 g_autoptr(GFile) file = NULL;
190 g_autoptr(GFile) file_parent = NULL;
191
192 file = g_file_new_for_path (filename);
193 file_parent = g_file_get_parent (file);
194 if (!g_file_query_exists (file_parent, NULL)) {
195 if (!g_file_make_directory_with_parents (file_parent, NULL, error))
196 return FALSE;
197 }
198 data = g_bytes_get_data (bytes, &size);
Richard Hughes455fdd32017-08-16 12:26:44 +0100199 g_debug ("writing %s with %" G_GSIZE_FORMAT " bytes", filename, size);
Richard Hughes943d2c92017-06-21 09:04:39 +0100200 return g_file_set_contents (filename, data, size, error);
201}
202
Richard Hughesd0d2ae62017-08-08 12:22:30 +0100203/**
204 * fu_common_get_contents_bytes:
205 * @filename: A filename
206 * @error: A #GError, or %NULL
207 *
208 * Reads a blob of data from a file.
209 *
210 * Returns: a #GBytes, or %NULL for failure
Mario Limonciello1a680f32019-11-25 19:44:53 -0600211 *
212 * Since: 0.9.7
Richard Hughesd0d2ae62017-08-08 12:22:30 +0100213 **/
214GBytes *
215fu_common_get_contents_bytes (const gchar *filename, GError **error)
216{
217 gchar *data = NULL;
218 gsize len = 0;
219 if (!g_file_get_contents (filename, &data, &len, error))
220 return NULL;
Richard Hughes455fdd32017-08-16 12:26:44 +0100221 g_debug ("reading %s with %" G_GSIZE_FORMAT " bytes", filename, len);
Richard Hughesd0d2ae62017-08-08 12:22:30 +0100222 return g_bytes_new_take (data, len);
223}
Richard Hughes943d2c92017-06-21 09:04:39 +0100224
225/**
226 * fu_common_get_contents_fd:
227 * @fd: A file descriptor
228 * @count: The maximum number of bytes to read
229 * @error: A #GError, or %NULL
230 *
231 * Reads a blob from a specific file descriptor.
232 *
233 * Note: this will close the fd when done
234 *
Richard Hughes4eada342017-10-03 21:20:32 +0100235 * Returns: (transfer full): a #GBytes, or %NULL
Mario Limonciello1a680f32019-11-25 19:44:53 -0600236 *
237 * Since: 0.9.5
Richard Hughes943d2c92017-06-21 09:04:39 +0100238 **/
239GBytes *
240fu_common_get_contents_fd (gint fd, gsize count, GError **error)
241{
Richard Hughes9e5675e2019-11-22 09:35:03 +0000242#ifdef HAVE_GIO_UNIX
Richard Hughes943d2c92017-06-21 09:04:39 +0100243 g_autoptr(GBytes) blob = NULL;
244 g_autoptr(GError) error_local = NULL;
245 g_autoptr(GInputStream) stream = NULL;
246
247 g_return_val_if_fail (fd > 0, NULL);
Richard Hughes943d2c92017-06-21 09:04:39 +0100248 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
249
Richard Hughes919f8ab2018-02-14 10:24:56 +0000250 /* this is invalid */
251 if (count == 0) {
252 g_set_error_literal (error,
253 FWUPD_ERROR,
254 FWUPD_ERROR_NOT_SUPPORTED,
255 "A maximum read size must be specified");
256 return NULL;
257 }
258
Richard Hughes943d2c92017-06-21 09:04:39 +0100259 /* read the entire fd to a data blob */
260 stream = g_unix_input_stream_new (fd, TRUE);
261 blob = g_input_stream_read_bytes (stream, count, NULL, &error_local);
262 if (blob == NULL) {
263 g_set_error_literal (error,
264 FWUPD_ERROR,
265 FWUPD_ERROR_INVALID_FILE,
266 error_local->message);
267 return NULL;
268 }
269 return g_steal_pointer (&blob);
Richard Hughes9e5675e2019-11-22 09:35:03 +0000270#else
271 g_set_error_literal (error,
272 FWUPD_ERROR,
273 FWUPD_ERROR_NOT_SUPPORTED,
274 "Not supported as <glib-unix.h> is unavailable");
275 return NULL;
276#endif
Richard Hughes943d2c92017-06-21 09:04:39 +0100277}
Richard Hughes94f939a2017-08-08 12:21:39 +0100278
279static gboolean
280fu_common_extract_archive_entry (struct archive_entry *entry, const gchar *dir)
281{
282 const gchar *tmp;
283 g_autofree gchar *buf = NULL;
284
285 /* no output file */
286 if (archive_entry_pathname (entry) == NULL)
287 return FALSE;
288
289 /* update output path */
290 tmp = archive_entry_pathname (entry);
291 buf = g_build_filename (dir, tmp, NULL);
292 archive_entry_update_pathname_utf8 (entry, buf);
293 return TRUE;
294}
295
296/**
297 * fu_common_extract_archive:
298 * @blob: a #GBytes archive as a blob
Richard Hughes4eada342017-10-03 21:20:32 +0100299 * @dir: a directory name to extract to
Richard Hughes94f939a2017-08-08 12:21:39 +0100300 * @error: A #GError, or %NULL
301 *
Richard Hughes21eaeef2020-01-14 12:10:01 +0000302 * Extracts an archive to a directory.
Richard Hughes94f939a2017-08-08 12:21:39 +0100303 *
304 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600305 *
306 * Since: 0.9.7
Richard Hughes94f939a2017-08-08 12:21:39 +0100307 **/
308gboolean
309fu_common_extract_archive (GBytes *blob, const gchar *dir, GError **error)
310{
311 gboolean ret = TRUE;
312 int r;
313 struct archive *arch = NULL;
314 struct archive_entry *entry;
315
316 /* decompress anything matching either glob */
Richard Hughes455fdd32017-08-16 12:26:44 +0100317 g_debug ("decompressing into %s", dir);
Richard Hughes94f939a2017-08-08 12:21:39 +0100318 arch = archive_read_new ();
319 archive_read_support_format_all (arch);
320 archive_read_support_filter_all (arch);
321 r = archive_read_open_memory (arch,
322 (void *) g_bytes_get_data (blob, NULL),
323 (size_t) g_bytes_get_size (blob));
324 if (r != 0) {
325 ret = FALSE;
326 g_set_error (error,
327 FWUPD_ERROR,
328 FWUPD_ERROR_INTERNAL,
329 "Cannot open: %s",
330 archive_error_string (arch));
331 goto out;
332 }
333 for (;;) {
334 gboolean valid;
Richard Hughes94f939a2017-08-08 12:21:39 +0100335 r = archive_read_next_header (arch, &entry);
336 if (r == ARCHIVE_EOF)
337 break;
338 if (r != ARCHIVE_OK) {
339 ret = FALSE;
340 g_set_error (error,
341 FWUPD_ERROR,
342 FWUPD_ERROR_INTERNAL,
343 "Cannot read header: %s",
344 archive_error_string (arch));
345 goto out;
346 }
347
348 /* only extract if valid */
349 valid = fu_common_extract_archive_entry (entry, dir);
350 if (!valid)
351 continue;
352 r = archive_read_extract (arch, entry, 0);
353 if (r != ARCHIVE_OK) {
354 ret = FALSE;
355 g_set_error (error,
356 FWUPD_ERROR,
357 FWUPD_ERROR_INTERNAL,
358 "Cannot extract: %s",
359 archive_error_string (arch));
360 goto out;
361 }
362 }
363out:
364 if (arch != NULL) {
365 archive_read_close (arch);
366 archive_read_free (arch);
367 }
368 return ret;
369}
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100370
371static void
Yehezkel Bernate43f7fb2017-08-30 12:09:34 +0300372fu_common_add_argv (GPtrArray *argv, const gchar *fmt, ...) G_GNUC_PRINTF (2, 3);
373
374static void
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100375fu_common_add_argv (GPtrArray *argv, const gchar *fmt, ...)
376{
377 va_list args;
378 g_autofree gchar *tmp = NULL;
379 g_auto(GStrv) split = NULL;
380
381 va_start (args, fmt);
382 tmp = g_strdup_vprintf (fmt, args);
383 va_end (args);
384
385 split = g_strsplit (tmp, " ", -1);
386 for (guint i = 0; split[i] != NULL; i++)
387 g_ptr_array_add (argv, g_strdup (split[i]));
388}
389
Mario Limonciello1a680f32019-11-25 19:44:53 -0600390/**
391 * fu_common_find_program_in_path:
392 * @basename: The program to search
393 * @error: A #GError, or %NULL
394 *
395 * Looks for a program in the PATH variable
396 *
397 * Returns: a new #gchar, or %NULL for error
398 *
399 * Since: 1.1.2
400 **/
Richard Hughes22367e72018-08-30 10:24:04 +0100401gchar *
402fu_common_find_program_in_path (const gchar *basename, GError **error)
403{
404 gchar *fn = g_find_program_in_path (basename);
405 if (fn == NULL) {
406 g_set_error (error,
407 FWUPD_ERROR,
408 FWUPD_ERROR_NOT_SUPPORTED,
409 "missing executable %s in PATH",
410 basename);
411 return NULL;
412 }
413 return fn;
414}
415
416static gboolean
417fu_common_test_namespace_support (GError **error)
418{
419 /* test if CONFIG_USER_NS is valid */
420 if (!g_file_test ("/proc/self/ns/user", G_FILE_TEST_IS_SYMLINK)) {
421 g_set_error (error,
422 FWUPD_ERROR,
423 FWUPD_ERROR_NOT_SUPPORTED,
424 "missing CONFIG_USER_NS in kernel");
425 return FALSE;
426 }
427 if (g_file_test ("/proc/sys/kernel/unprivileged_userns_clone", G_FILE_TEST_EXISTS)) {
428 g_autofree gchar *clone = NULL;
429 if (!g_file_get_contents ("/proc/sys/kernel/unprivileged_userns_clone", &clone, NULL, error))
430 return FALSE;
431 if (g_ascii_strtoll (clone, NULL, 10) == 0) {
432 g_set_error (error,
433 FWUPD_ERROR,
434 FWUPD_ERROR_NOT_SUPPORTED,
435 "unprivileged user namespace clones disabled by distro");
436 return FALSE;
437 }
438 }
439 return TRUE;
440}
441
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100442/**
443 * fu_common_firmware_builder:
444 * @bytes: The data to use
Richard Hughes4eada342017-10-03 21:20:32 +0100445 * @script_fn: Name of the script to run in the tarball, e.g. `startup.sh`
446 * @output_fn: Name of the generated firmware, e.g. `firmware.bin`
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100447 * @error: A #GError, or %NULL
448 *
449 * Builds a firmware file using tools from the host session in a bubblewrap
450 * jail. Several things happen during build:
451 *
452 * 1. The @bytes data is untarred to a temporary location
453 * 2. A bubblewrap container is set up
454 * 3. The startup.sh script is run inside the container
455 * 4. The firmware.bin is extracted from the container
456 * 5. The temporary location is deleted
457 *
458 * Returns: a new #GBytes, or %NULL for error
Mario Limonciello1a680f32019-11-25 19:44:53 -0600459 *
460 * Since: 0.9.7
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100461 **/
462GBytes *
463fu_common_firmware_builder (GBytes *bytes,
464 const gchar *script_fn,
465 const gchar *output_fn,
466 GError **error)
467{
468 gint rc = 0;
469 g_autofree gchar *argv_str = NULL;
Mario Limonciello37b59582018-08-13 08:38:01 -0500470 g_autofree gchar *bwrap_fn = NULL;
Richard Hughes4be17d12018-05-30 20:36:29 +0100471 g_autofree gchar *localstatebuilderdir = NULL;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100472 g_autofree gchar *localstatedir = NULL;
473 g_autofree gchar *output2_fn = NULL;
474 g_autofree gchar *standard_error = NULL;
475 g_autofree gchar *standard_output = NULL;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100476 g_autofree gchar *tmpdir = NULL;
477 g_autoptr(GBytes) firmware_blob = NULL;
478 g_autoptr(GPtrArray) argv = g_ptr_array_new_with_free_func (g_free);
479
480 g_return_val_if_fail (bytes != NULL, NULL);
481 g_return_val_if_fail (script_fn != NULL, NULL);
482 g_return_val_if_fail (output_fn != NULL, NULL);
483 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
484
Mario Limonciello37b59582018-08-13 08:38:01 -0500485 /* find bwrap in the path */
Richard Hughes22367e72018-08-30 10:24:04 +0100486 bwrap_fn = fu_common_find_program_in_path ("bwrap", error);
487 if (bwrap_fn == NULL)
Richard Hughesddb3e202018-08-23 11:29:57 +0100488 return NULL;
Mario Limonciello37b59582018-08-13 08:38:01 -0500489
490 /* test if CONFIG_USER_NS is valid */
Richard Hughes22367e72018-08-30 10:24:04 +0100491 if (!fu_common_test_namespace_support (error))
Richard Hughesddb3e202018-08-23 11:29:57 +0100492 return NULL;
Mario Limonciello37b59582018-08-13 08:38:01 -0500493
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100494 /* untar file to temp location */
495 tmpdir = g_dir_make_tmp ("fwupd-gen-XXXXXX", error);
496 if (tmpdir == NULL)
497 return NULL;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100498 if (!fu_common_extract_archive (bytes, tmpdir, error))
499 return NULL;
500
501 /* this is shared with the plugins */
Richard Hughes4be17d12018-05-30 20:36:29 +0100502 localstatedir = fu_common_get_path (FU_PATH_KIND_LOCALSTATEDIR_PKG);
503 localstatebuilderdir = g_build_filename (localstatedir, "builder", NULL);
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100504
505 /* launch bubblewrap and generate firmware */
Mario Limonciello37b59582018-08-13 08:38:01 -0500506 g_ptr_array_add (argv, g_steal_pointer (&bwrap_fn));
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100507 fu_common_add_argv (argv, "--die-with-parent");
508 fu_common_add_argv (argv, "--ro-bind /usr /usr");
Mario Limonciellob8215572018-07-13 09:49:55 -0500509 fu_common_add_argv (argv, "--ro-bind /lib /lib");
510 fu_common_add_argv (argv, "--ro-bind /lib64 /lib64");
511 fu_common_add_argv (argv, "--ro-bind /bin /bin");
512 fu_common_add_argv (argv, "--ro-bind /sbin /sbin");
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100513 fu_common_add_argv (argv, "--dir /tmp");
514 fu_common_add_argv (argv, "--dir /var");
515 fu_common_add_argv (argv, "--bind %s /tmp", tmpdir);
Richard Hughes4be17d12018-05-30 20:36:29 +0100516 if (g_file_test (localstatebuilderdir, G_FILE_TEST_EXISTS))
517 fu_common_add_argv (argv, "--ro-bind %s /boot", localstatebuilderdir);
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100518 fu_common_add_argv (argv, "--dev /dev");
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100519 fu_common_add_argv (argv, "--chdir /tmp");
520 fu_common_add_argv (argv, "--unshare-all");
Richard Hughes443e4092017-08-09 16:07:31 +0100521 fu_common_add_argv (argv, "/tmp/%s", script_fn);
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100522 g_ptr_array_add (argv, NULL);
523 argv_str = g_strjoinv (" ", (gchar **) argv->pdata);
524 g_debug ("running '%s' in %s", argv_str, tmpdir);
525 if (!g_spawn_sync ("/tmp",
526 (gchar **) argv->pdata,
527 NULL,
Richard Hughesf6f72a42017-08-09 16:25:25 +0100528 G_SPAWN_SEARCH_PATH,
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100529 NULL, NULL, /* child_setup */
530 &standard_output,
531 &standard_error,
532 &rc,
533 error)) {
534 g_prefix_error (error, "failed to run '%s': ", argv_str);
535 return NULL;
536 }
537 if (standard_output != NULL && standard_output[0] != '\0')
538 g_debug ("console output was: %s", standard_output);
539 if (rc != 0) {
Mario Limonciello37b59582018-08-13 08:38:01 -0500540 FwupdError code = FWUPD_ERROR_INTERNAL;
541 if (errno == ENOTTY)
542 code = FWUPD_ERROR_PERMISSION_DENIED;
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100543 g_set_error (error,
544 FWUPD_ERROR,
Mario Limonciello37b59582018-08-13 08:38:01 -0500545 code,
Richard Hughes41cbe2a2017-08-08 14:13:35 +0100546 "failed to build firmware: %s",
547 standard_error);
548 return NULL;
549 }
550
551 /* get generated file */
552 output2_fn = g_build_filename (tmpdir, output_fn, NULL);
553 firmware_blob = fu_common_get_contents_bytes (output2_fn, error);
554 if (firmware_blob == NULL)
555 return NULL;
556
557 /* cleanup temp directory */
558 if (!fu_common_rmtree (tmpdir, error))
559 return NULL;
560
561 /* success */
562 return g_steal_pointer (&firmware_blob);
563}
Richard Hughes049ccc82017-08-09 15:26:56 +0100564
565typedef struct {
566 FuOutputHandler handler_cb;
567 gpointer handler_user_data;
568 GMainLoop *loop;
569 GSource *source;
570 GInputStream *stream;
571 GCancellable *cancellable;
Richard Hughesb768e4d2019-02-26 13:55:18 +0000572 guint timeout_id;
Richard Hughes049ccc82017-08-09 15:26:56 +0100573} FuCommonSpawnHelper;
574
575static void fu_common_spawn_create_pollable_source (FuCommonSpawnHelper *helper);
576
577static gboolean
578fu_common_spawn_source_pollable_cb (GObject *stream, gpointer user_data)
579{
580 FuCommonSpawnHelper *helper = (FuCommonSpawnHelper *) user_data;
581 gchar buffer[1024];
582 gssize sz;
583 g_auto(GStrv) split = NULL;
584 g_autoptr(GError) error = NULL;
585
586 /* read from stream */
587 sz = g_pollable_input_stream_read_nonblocking (G_POLLABLE_INPUT_STREAM (stream),
588 buffer,
589 sizeof(buffer) - 1,
590 NULL,
591 &error);
592 if (sz < 0) {
Richard Hughes67cbe642017-08-16 12:26:14 +0100593 if (!g_error_matches (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
594 g_warning ("failed to get read from nonblocking fd: %s",
595 error->message);
596 }
Richard Hughes049ccc82017-08-09 15:26:56 +0100597 return G_SOURCE_REMOVE;
598 }
599
600 /* no read possible */
601 if (sz == 0)
602 g_main_loop_quit (helper->loop);
603
604 /* emit lines */
605 if (helper->handler_cb != NULL) {
606 buffer[sz] = '\0';
607 split = g_strsplit (buffer, "\n", -1);
608 for (guint i = 0; split[i] != NULL; i++) {
609 if (split[i][0] == '\0')
610 continue;
611 helper->handler_cb (split[i], helper->handler_user_data);
612 }
613 }
614
615 /* set up the source for the next read */
616 fu_common_spawn_create_pollable_source (helper);
617 return G_SOURCE_REMOVE;
618}
619
620static void
621fu_common_spawn_create_pollable_source (FuCommonSpawnHelper *helper)
622{
623 if (helper->source != NULL)
624 g_source_destroy (helper->source);
625 helper->source = g_pollable_input_stream_create_source (G_POLLABLE_INPUT_STREAM (helper->stream),
626 helper->cancellable);
627 g_source_attach (helper->source, NULL);
628 g_source_set_callback (helper->source, (GSourceFunc) fu_common_spawn_source_pollable_cb, helper, NULL);
629}
630
631static void
632fu_common_spawn_helper_free (FuCommonSpawnHelper *helper)
633{
Richard Hughesb768e4d2019-02-26 13:55:18 +0000634 g_object_unref (helper->cancellable);
Richard Hughes049ccc82017-08-09 15:26:56 +0100635 if (helper->stream != NULL)
636 g_object_unref (helper->stream);
637 if (helper->source != NULL)
638 g_source_destroy (helper->source);
639 if (helper->loop != NULL)
640 g_main_loop_unref (helper->loop);
Richard Hughesb768e4d2019-02-26 13:55:18 +0000641 if (helper->timeout_id != 0)
642 g_source_remove (helper->timeout_id);
Richard Hughes049ccc82017-08-09 15:26:56 +0100643 g_free (helper);
644}
645
Mario Limoncielloa98df552018-04-16 12:15:51 -0500646#pragma clang diagnostic push
647#pragma clang diagnostic ignored "-Wunused-function"
Richard Hughes049ccc82017-08-09 15:26:56 +0100648G_DEFINE_AUTOPTR_CLEANUP_FUNC(FuCommonSpawnHelper, fu_common_spawn_helper_free)
Mario Limoncielloa98df552018-04-16 12:15:51 -0500649#pragma clang diagnostic pop
Richard Hughes049ccc82017-08-09 15:26:56 +0100650
Richard Hughesb768e4d2019-02-26 13:55:18 +0000651static gboolean
652fu_common_spawn_timeout_cb (gpointer user_data)
653{
654 FuCommonSpawnHelper *helper = (FuCommonSpawnHelper *) user_data;
655 g_cancellable_cancel (helper->cancellable);
656 g_main_loop_quit (helper->loop);
657 helper->timeout_id = 0;
658 return G_SOURCE_REMOVE;
659}
660
661static void
662fu_common_spawn_cancelled_cb (GCancellable *cancellable, FuCommonSpawnHelper *helper)
663{
664 /* just propagate */
665 g_cancellable_cancel (helper->cancellable);
666}
667
Richard Hughes049ccc82017-08-09 15:26:56 +0100668/**
669 * fu_common_spawn_sync:
670 * @argv: The argument list to run
Richard Hughes4eada342017-10-03 21:20:32 +0100671 * @handler_cb: (scope call): A #FuOutputHandler or %NULL
672 * @handler_user_data: the user data to pass to @handler_cb
Richard Hughesb768e4d2019-02-26 13:55:18 +0000673 * @timeout_ms: a timeout in ms, or 0 for no limit
Richard Hughes049ccc82017-08-09 15:26:56 +0100674 * @cancellable: a #GCancellable, or %NULL
675 * @error: A #GError or %NULL
676 *
677 * Runs a subprocess and waits for it to exit. Any output on standard out or
678 * standard error will be forwarded to @handler_cb as whole lines.
679 *
680 * Returns: %TRUE for success
Mario Limonciello1a680f32019-11-25 19:44:53 -0600681 *
682 * Since: 0.9.7
Richard Hughes049ccc82017-08-09 15:26:56 +0100683 **/
684gboolean
685fu_common_spawn_sync (const gchar * const * argv,
686 FuOutputHandler handler_cb,
687 gpointer handler_user_data,
Richard Hughesb768e4d2019-02-26 13:55:18 +0000688 guint timeout_ms,
Richard Hughes049ccc82017-08-09 15:26:56 +0100689 GCancellable *cancellable, GError **error)
690{
691 g_autoptr(FuCommonSpawnHelper) helper = NULL;
692 g_autoptr(GSubprocess) subprocess = NULL;
Richard Hughes455fdd32017-08-16 12:26:44 +0100693 g_autofree gchar *argv_str = NULL;
Richard Hughesb768e4d2019-02-26 13:55:18 +0000694 gulong cancellable_id = 0;
Richard Hughes049ccc82017-08-09 15:26:56 +0100695
696 /* create subprocess */
Richard Hughes455fdd32017-08-16 12:26:44 +0100697 argv_str = g_strjoinv (" ", (gchar **) argv);
698 g_debug ("running '%s'", argv_str);
Richard Hughes049ccc82017-08-09 15:26:56 +0100699 subprocess = g_subprocess_newv (argv, G_SUBPROCESS_FLAGS_STDOUT_PIPE |
700 G_SUBPROCESS_FLAGS_STDERR_MERGE, error);
701 if (subprocess == NULL)
702 return FALSE;
703
704 /* watch for process to exit */
705 helper = g_new0 (FuCommonSpawnHelper, 1);
706 helper->handler_cb = handler_cb;
707 helper->handler_user_data = handler_user_data;
708 helper->loop = g_main_loop_new (NULL, FALSE);
709 helper->stream = g_subprocess_get_stdout_pipe (subprocess);
Richard Hughesb768e4d2019-02-26 13:55:18 +0000710
711 /* always create a cancellable, and connect up the parent */
712 helper->cancellable = g_cancellable_new ();
713 if (cancellable != NULL) {
714 cancellable_id = g_cancellable_connect (cancellable,
715 G_CALLBACK (fu_common_spawn_cancelled_cb),
716 helper, NULL);
717 }
718
719 /* allow timeout */
720 if (timeout_ms > 0) {
721 helper->timeout_id = g_timeout_add (timeout_ms,
722 fu_common_spawn_timeout_cb,
723 helper);
724 }
Richard Hughes049ccc82017-08-09 15:26:56 +0100725 fu_common_spawn_create_pollable_source (helper);
726 g_main_loop_run (helper->loop);
Richard Hughesb768e4d2019-02-26 13:55:18 +0000727 g_cancellable_disconnect (cancellable, cancellable_id);
728 if (g_cancellable_set_error_if_cancelled (helper->cancellable, error))
729 return FALSE;
Richard Hughes049ccc82017-08-09 15:26:56 +0100730 return g_subprocess_wait_check (subprocess, cancellable, error);
731}
Richard Hughesae252cd2017-12-08 10:48:15 +0000732
733/**
734 * fu_common_write_uint16:
735 * @buf: A writable buffer
736 * @val_native: a value in host byte-order
Richard Hughes8aa72392018-05-02 08:38:43 +0100737 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000738 *
739 * Writes a value to a buffer using a specified endian.
Mario Limonciello1a680f32019-11-25 19:44:53 -0600740 *
741 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000742 **/
743void
744fu_common_write_uint16 (guint8 *buf, guint16 val_native, FuEndianType endian)
745{
746 guint16 val_hw;
747 switch (endian) {
748 case G_BIG_ENDIAN:
749 val_hw = GUINT16_TO_BE(val_native);
750 break;
751 case G_LITTLE_ENDIAN:
752 val_hw = GUINT16_TO_LE(val_native);
753 break;
754 default:
755 g_assert_not_reached ();
756 }
757 memcpy (buf, &val_hw, sizeof(val_hw));
758}
759
760/**
761 * fu_common_write_uint32:
762 * @buf: A writable buffer
763 * @val_native: a value in host byte-order
Richard Hughes8aa72392018-05-02 08:38:43 +0100764 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000765 *
766 * Writes a value to a buffer using a specified endian.
Mario Limonciello1a680f32019-11-25 19:44:53 -0600767 *
768 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000769 **/
770void
771fu_common_write_uint32 (guint8 *buf, guint32 val_native, FuEndianType endian)
772{
773 guint32 val_hw;
774 switch (endian) {
775 case G_BIG_ENDIAN:
776 val_hw = GUINT32_TO_BE(val_native);
777 break;
778 case G_LITTLE_ENDIAN:
779 val_hw = GUINT32_TO_LE(val_native);
780 break;
781 default:
782 g_assert_not_reached ();
783 }
784 memcpy (buf, &val_hw, sizeof(val_hw));
785}
786
787/**
788 * fu_common_read_uint16:
789 * @buf: A readable buffer
Richard Hughes8aa72392018-05-02 08:38:43 +0100790 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000791 *
792 * Read a value from a buffer using a specified endian.
793 *
794 * Returns: a value in host byte-order
Mario Limonciello1a680f32019-11-25 19:44:53 -0600795 *
796 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000797 **/
798guint16
799fu_common_read_uint16 (const guint8 *buf, FuEndianType endian)
800{
801 guint16 val_hw, val_native;
802 memcpy (&val_hw, buf, sizeof(val_hw));
803 switch (endian) {
804 case G_BIG_ENDIAN:
805 val_native = GUINT16_FROM_BE(val_hw);
806 break;
807 case G_LITTLE_ENDIAN:
808 val_native = GUINT16_FROM_LE(val_hw);
809 break;
810 default:
811 g_assert_not_reached ();
812 }
813 return val_native;
814}
815
816/**
817 * fu_common_read_uint32:
818 * @buf: A readable buffer
Richard Hughes8aa72392018-05-02 08:38:43 +0100819 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
Richard Hughesae252cd2017-12-08 10:48:15 +0000820 *
821 * Read a value from a buffer using a specified endian.
822 *
823 * Returns: a value in host byte-order
Mario Limonciello1a680f32019-11-25 19:44:53 -0600824 *
825 * Since: 1.0.3
Richard Hughesae252cd2017-12-08 10:48:15 +0000826 **/
827guint32
828fu_common_read_uint32 (const guint8 *buf, FuEndianType endian)
829{
830 guint32 val_hw, val_native;
831 memcpy (&val_hw, buf, sizeof(val_hw));
832 switch (endian) {
833 case G_BIG_ENDIAN:
834 val_native = GUINT32_FROM_BE(val_hw);
835 break;
836 case G_LITTLE_ENDIAN:
837 val_native = GUINT32_FROM_LE(val_hw);
838 break;
839 default:
840 g_assert_not_reached ();
841 }
842 return val_native;
843}
Richard Hughese82eef32018-05-20 10:41:26 +0100844
Richard Hughes73bf2332018-08-28 09:38:09 +0100845/**
846 * fu_common_strtoull:
847 * @str: A string, e.g. "0x1234"
848 *
849 * Converts a string value to an integer. Values are assumed base 10, unless
850 * prefixed with "0x" where they are parsed as base 16.
851 *
852 * Returns: integer value, or 0x0 for error
Mario Limonciello1a680f32019-11-25 19:44:53 -0600853 *
854 * Since: 1.1.2
Richard Hughes73bf2332018-08-28 09:38:09 +0100855 **/
856guint64
857fu_common_strtoull (const gchar *str)
858{
859 guint base = 10;
860 if (str == NULL)
861 return 0x0;
862 if (g_str_has_prefix (str, "0x")) {
863 str += 2;
864 base = 16;
865 }
866 return g_ascii_strtoull (str, NULL, base);
867}
868
Richard Hughesa574a752018-08-31 13:31:03 +0100869/**
870 * fu_common_strstrip:
871 * @str: A string, e.g. " test "
872 *
873 * Removes leading and trailing whitespace from a constant string.
874 *
875 * Returns: newly allocated string
Mario Limonciello1a680f32019-11-25 19:44:53 -0600876 *
877 * Since: 1.1.2
Richard Hughesa574a752018-08-31 13:31:03 +0100878 **/
879gchar *
880fu_common_strstrip (const gchar *str)
881{
882 guint head = G_MAXUINT;
883 guint tail = 0;
884
885 g_return_val_if_fail (str != NULL, NULL);
886
887 /* find first non-space char */
888 for (guint i = 0; str[i] != '\0'; i++) {
889 if (str[i] != ' ') {
890 head = i;
891 break;
892 }
893 }
894 if (head == G_MAXUINT)
895 return g_strdup ("");
896
897 /* find last non-space char */
898 for (guint i = head; str[i] != '\0'; i++) {
Mario Limoncielloef3c7662019-09-04 23:37:59 -0500899 if (!g_ascii_isspace (str[i]))
Richard Hughesa574a752018-08-31 13:31:03 +0100900 tail = i;
901 }
902 return g_strndup (str + head, tail - head + 1);
903}
904
Richard Hughese82eef32018-05-20 10:41:26 +0100905static const GError *
906fu_common_error_array_find (GPtrArray *errors, FwupdError error_code)
907{
908 for (guint j = 0; j < errors->len; j++) {
909 const GError *error = g_ptr_array_index (errors, j);
910 if (g_error_matches (error, FWUPD_ERROR, error_code))
911 return error;
912 }
913 return NULL;
914}
915
916static guint
917fu_common_error_array_count (GPtrArray *errors, FwupdError error_code)
918{
919 guint cnt = 0;
920 for (guint j = 0; j < errors->len; j++) {
921 const GError *error = g_ptr_array_index (errors, j);
922 if (g_error_matches (error, FWUPD_ERROR, error_code))
923 cnt++;
924 }
925 return cnt;
926}
927
928static gboolean
929fu_common_error_array_matches_any (GPtrArray *errors, FwupdError *error_codes)
930{
931 for (guint j = 0; j < errors->len; j++) {
932 const GError *error = g_ptr_array_index (errors, j);
933 gboolean matches_any = FALSE;
934 for (guint i = 0; error_codes[i] != FWUPD_ERROR_LAST; i++) {
935 if (g_error_matches (error, FWUPD_ERROR, error_codes[i])) {
936 matches_any = TRUE;
937 break;
938 }
939 }
940 if (!matches_any)
941 return FALSE;
942 }
943 return TRUE;
944}
945
946/**
947 * fu_common_error_array_get_best:
948 * @errors: (element-type GError): array of errors
949 *
950 * Finds the 'best' error to show the user from a array of errors, creating a
951 * completely bespoke error where required.
952 *
953 * Returns: (transfer full): a #GError, never %NULL
Mario Limonciello1a680f32019-11-25 19:44:53 -0600954 *
955 * Since: 1.0.8
Richard Hughese82eef32018-05-20 10:41:26 +0100956 **/
957GError *
958fu_common_error_array_get_best (GPtrArray *errors)
959{
960 FwupdError err_prio[] = { FWUPD_ERROR_INVALID_FILE,
961 FWUPD_ERROR_VERSION_SAME,
962 FWUPD_ERROR_VERSION_NEWER,
963 FWUPD_ERROR_NOT_SUPPORTED,
964 FWUPD_ERROR_INTERNAL,
965 FWUPD_ERROR_NOT_FOUND,
966 FWUPD_ERROR_LAST };
967 FwupdError err_all_uptodate[] = { FWUPD_ERROR_VERSION_SAME,
968 FWUPD_ERROR_NOT_FOUND,
969 FWUPD_ERROR_NOT_SUPPORTED,
970 FWUPD_ERROR_LAST };
971 FwupdError err_all_newer[] = { FWUPD_ERROR_VERSION_NEWER,
972 FWUPD_ERROR_VERSION_SAME,
973 FWUPD_ERROR_NOT_FOUND,
974 FWUPD_ERROR_NOT_SUPPORTED,
975 FWUPD_ERROR_LAST };
976
977 /* are all the errors either GUID-not-matched or version-same? */
978 if (fu_common_error_array_count (errors, FWUPD_ERROR_VERSION_SAME) > 1 &&
979 fu_common_error_array_matches_any (errors, err_all_uptodate)) {
980 return g_error_new (FWUPD_ERROR,
981 FWUPD_ERROR_NOTHING_TO_DO,
982 "All updatable firmware is already installed");
983 }
984
985 /* are all the errors either GUID-not-matched or version same or newer? */
986 if (fu_common_error_array_count (errors, FWUPD_ERROR_VERSION_NEWER) > 1 &&
987 fu_common_error_array_matches_any (errors, err_all_newer)) {
988 return g_error_new (FWUPD_ERROR,
989 FWUPD_ERROR_NOTHING_TO_DO,
990 "All updatable devices already have newer versions");
991 }
992
993 /* get the most important single error */
994 for (guint i = 0; err_prio[i] != FWUPD_ERROR_LAST; i++) {
995 const GError *error_tmp = fu_common_error_array_find (errors, err_prio[i]);
996 if (error_tmp != NULL)
997 return g_error_copy (error_tmp);
998 }
999
1000 /* fall back to something */
1001 return g_error_new (FWUPD_ERROR,
1002 FWUPD_ERROR_NOT_FOUND,
1003 "No supported devices found");
1004}
Richard Hughes4be17d12018-05-30 20:36:29 +01001005
1006/**
1007 * fu_common_get_path:
1008 * @path_kind: A #FuPathKind e.g. %FU_PATH_KIND_DATADIR_PKG
1009 *
1010 * Gets a fwupd-specific system path. These can be overridden with various
1011 * environment variables, for instance %FWUPD_DATADIR.
1012 *
1013 * Returns: a system path, or %NULL if invalid
Mario Limonciello1a680f32019-11-25 19:44:53 -06001014 *
1015 * Since: 1.0.8
Richard Hughes4be17d12018-05-30 20:36:29 +01001016 **/
1017gchar *
1018fu_common_get_path (FuPathKind path_kind)
1019{
1020 const gchar *tmp;
1021 g_autofree gchar *basedir = NULL;
1022
1023 switch (path_kind) {
1024 /* /var */
1025 case FU_PATH_KIND_LOCALSTATEDIR:
1026 tmp = g_getenv ("FWUPD_LOCALSTATEDIR");
1027 if (tmp != NULL)
1028 return g_strdup (tmp);
1029 tmp = g_getenv ("SNAP_USER_DATA");
1030 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001031 return g_build_filename (tmp, FWUPD_LOCALSTATEDIR, NULL);
1032 return g_build_filename (FWUPD_LOCALSTATEDIR, NULL);
Richard Hughesc3689582020-05-06 12:35:20 +01001033 /* /proc */
1034 case FU_PATH_KIND_PROCFS:
1035 tmp = g_getenv ("FWUPD_PROCFS");
1036 if (tmp != NULL)
1037 return g_strdup (tmp);
1038 return g_strdup ("/proc");
Richard Hughes282b10d2018-06-22 14:48:00 +01001039 /* /sys/firmware */
1040 case FU_PATH_KIND_SYSFSDIR_FW:
1041 tmp = g_getenv ("FWUPD_SYSFSFWDIR");
1042 if (tmp != NULL)
1043 return g_strdup (tmp);
1044 return g_strdup ("/sys/firmware");
Mario Limonciello39602652019-04-29 21:08:58 -05001045 /* /sys/class/tpm */
Richard Hughesb56015e2018-12-12 09:25:32 +00001046 case FU_PATH_KIND_SYSFSDIR_TPM:
1047 tmp = g_getenv ("FWUPD_SYSFSTPMDIR");
1048 if (tmp != NULL)
1049 return g_strdup (tmp);
1050 return g_strdup ("/sys/class/tpm");
Richard Hughes83390f62018-06-22 20:36:46 +01001051 /* /sys/bus/platform/drivers */
1052 case FU_PATH_KIND_SYSFSDIR_DRIVERS:
1053 tmp = g_getenv ("FWUPD_SYSFSDRIVERDIR");
1054 if (tmp != NULL)
1055 return g_strdup (tmp);
1056 return g_strdup ("/sys/bus/platform/drivers");
Mario Limonciello9dce1f72020-02-04 09:12:52 -06001057 /* /sys/kernel/security */
1058 case FU_PATH_KIND_SYSFSDIR_SECURITY:
1059 tmp = g_getenv ("FWUPD_SYSFSSECURITYDIR");
1060 if (tmp != NULL)
1061 return g_strdup (tmp);
1062 return g_strdup ("/sys/kernel/security");
Richard Hughesa7157912020-05-11 17:14:05 +01001063 /* /sys/firmware/acpi/tables */
1064 case FU_PATH_KIND_ACPI_TABLES:
1065 tmp = g_getenv ("FWUPD_ACPITABLESDIR");
1066 if (tmp != NULL)
1067 return g_strdup (tmp);
1068 return g_strdup ("/sys/firmware/acpi/tables");
Richard Hughes4be17d12018-05-30 20:36:29 +01001069 /* /etc */
1070 case FU_PATH_KIND_SYSCONFDIR:
1071 tmp = g_getenv ("FWUPD_SYSCONFDIR");
1072 if (tmp != NULL)
1073 return g_strdup (tmp);
1074 tmp = g_getenv ("SNAP_USER_DATA");
1075 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001076 return g_build_filename (tmp, FWUPD_SYSCONFDIR, NULL);
1077 return g_strdup (FWUPD_SYSCONFDIR);
Richard Hughes4be17d12018-05-30 20:36:29 +01001078 /* /usr/lib/<triplet>/fwupd-plugins-3 */
1079 case FU_PATH_KIND_PLUGINDIR_PKG:
1080 tmp = g_getenv ("FWUPD_PLUGINDIR");
1081 if (tmp != NULL)
1082 return g_strdup (tmp);
1083 tmp = g_getenv ("SNAP");
1084 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001085 return g_build_filename (tmp, FWUPD_PLUGINDIR, NULL);
1086 return g_build_filename (FWUPD_PLUGINDIR, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001087 /* /usr/share/fwupd */
1088 case FU_PATH_KIND_DATADIR_PKG:
1089 tmp = g_getenv ("FWUPD_DATADIR");
1090 if (tmp != NULL)
1091 return g_strdup (tmp);
1092 tmp = g_getenv ("SNAP");
1093 if (tmp != NULL)
Richard Hughes668ee212019-11-22 09:17:46 +00001094 return g_build_filename (tmp, FWUPD_DATADIR, PACKAGE_NAME, NULL);
1095 return g_build_filename (FWUPD_DATADIR, PACKAGE_NAME, NULL);
Mario Limoncielloe6e2bf92018-07-10 12:11:25 -05001096 /* /usr/libexec/fwupd/efi */
1097 case FU_PATH_KIND_EFIAPPDIR:
1098 tmp = g_getenv ("FWUPD_EFIAPPDIR");
1099 if (tmp != NULL)
1100 return g_strdup (tmp);
1101#ifdef EFI_APP_LOCATION
1102 tmp = g_getenv ("SNAP");
1103 if (tmp != NULL)
1104 return g_build_filename (tmp, EFI_APP_LOCATION, NULL);
1105 return g_strdup (EFI_APP_LOCATION);
1106#else
1107 return NULL;
1108#endif
Richard Hughesb9640a22020-05-05 20:42:47 +01001109 /* /usr/share/fwupd/dbx */
1110 case FU_PATH_KIND_EFIDBXDIR:
1111 tmp = g_getenv ("FWUPD_EFIDBXDIR");
1112 if (tmp != NULL)
1113 return g_strdup (tmp);
1114#ifdef FWUPD_EFI_DBXDIR
1115 tmp = g_getenv ("SNAP");
1116 if (tmp != NULL)
1117 return g_build_filename (tmp, FWUPD_EFI_DBXDIR, NULL);
1118 return g_strdup (FWUPD_EFI_DBXDIR);
1119#else
1120 basedir = fu_common_get_path (FU_PATH_KIND_LOCALSTATEDIR_PKG);
1121 return g_build_filename (basedir, "dbx", NULL);
1122#endif
Richard Hughes4be17d12018-05-30 20:36:29 +01001123 /* /etc/fwupd */
1124 case FU_PATH_KIND_SYSCONFDIR_PKG:
Mario Limonciello277c1962019-08-26 23:42:23 -05001125 tmp = g_getenv ("CONFIGURATION_DIRECTORY");
Mario Limonciello695cb582019-12-12 10:45:42 -06001126 if (tmp != NULL && g_file_test (tmp, G_FILE_TEST_EXISTS))
Mario Limonciello277c1962019-08-26 23:42:23 -05001127 return g_build_filename (tmp, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001128 basedir = fu_common_get_path (FU_PATH_KIND_SYSCONFDIR);
1129 return g_build_filename (basedir, PACKAGE_NAME, NULL);
1130 /* /var/lib/fwupd */
1131 case FU_PATH_KIND_LOCALSTATEDIR_PKG:
Mario Limonciello277c1962019-08-26 23:42:23 -05001132 tmp = g_getenv ("STATE_DIRECTORY");
Mario Limonciello695cb582019-12-12 10:45:42 -06001133 if (tmp != NULL && g_file_test (tmp, G_FILE_TEST_EXISTS))
Mario Limonciello277c1962019-08-26 23:42:23 -05001134 return g_build_filename (tmp, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001135 basedir = fu_common_get_path (FU_PATH_KIND_LOCALSTATEDIR);
1136 return g_build_filename (basedir, "lib", PACKAGE_NAME, NULL);
1137 /* /var/cache/fwupd */
1138 case FU_PATH_KIND_CACHEDIR_PKG:
Mario Limonciello277c1962019-08-26 23:42:23 -05001139 tmp = g_getenv ("CACHE_DIRECTORY");
Mario Limonciello695cb582019-12-12 10:45:42 -06001140 if (tmp != NULL && g_file_test (tmp, G_FILE_TEST_EXISTS))
Mario Limonciello277c1962019-08-26 23:42:23 -05001141 return g_build_filename (tmp, NULL);
Richard Hughes4be17d12018-05-30 20:36:29 +01001142 basedir = fu_common_get_path (FU_PATH_KIND_LOCALSTATEDIR);
1143 return g_build_filename (basedir, "cache", PACKAGE_NAME, NULL);
Richard Hughesafdba372019-11-23 12:57:35 +00001144 case FU_PATH_KIND_OFFLINE_TRIGGER:
1145 tmp = g_getenv ("FWUPD_OFFLINE_TRIGGER");
1146 if (tmp != NULL)
1147 return g_strdup (tmp);
1148 return g_strdup ("/system-update");
Mario Limonciello057c67a2019-05-23 10:44:19 -05001149 case FU_PATH_KIND_POLKIT_ACTIONS:
1150#ifdef POLKIT_ACTIONDIR
1151 return g_strdup (POLKIT_ACTIONDIR);
1152#else
1153 return NULL;
1154#endif
Richard Hughes4be17d12018-05-30 20:36:29 +01001155 /* this shouldn't happen */
1156 default:
Richard Hughesbeb47a82018-09-11 18:28:53 +01001157 g_warning ("cannot build path for unknown kind %u", path_kind);
Richard Hughes4be17d12018-05-30 20:36:29 +01001158 }
1159
1160 return NULL;
1161}
Richard Hughes83e56c12018-10-10 20:24:41 +01001162
1163/**
1164 * fu_common_string_replace:
1165 * @string: The #GString to operate on
1166 * @search: The text to search for
1167 * @replace: The text to use for substitutions
1168 *
1169 * Performs multiple search and replace operations on the given string.
1170 *
1171 * Returns: the number of replacements done, or 0 if @search is not found.
1172 *
1173 * Since: 1.2.0
1174 **/
1175guint
1176fu_common_string_replace (GString *string, const gchar *search, const gchar *replace)
1177{
1178 gchar *tmp;
1179 guint count = 0;
1180 gsize search_idx = 0;
1181 gsize replace_len;
1182 gsize search_len;
1183
1184 g_return_val_if_fail (string != NULL, 0);
1185 g_return_val_if_fail (search != NULL, 0);
1186 g_return_val_if_fail (replace != NULL, 0);
1187
1188 /* nothing to do */
1189 if (string->len == 0)
1190 return 0;
1191
1192 search_len = strlen (search);
1193 replace_len = strlen (replace);
1194
1195 do {
1196 tmp = g_strstr_len (string->str + search_idx, -1, search);
1197 if (tmp == NULL)
1198 break;
1199
1200 /* advance the counter in case @replace contains @search */
1201 search_idx = (gsize) (tmp - string->str);
1202
1203 /* reallocate the string if required */
1204 if (search_len > replace_len) {
1205 g_string_erase (string,
1206 (gssize) search_idx,
1207 (gssize) (search_len - replace_len));
1208 memcpy (tmp, replace, replace_len);
1209 } else if (search_len < replace_len) {
1210 g_string_insert_len (string,
1211 (gssize) search_idx,
1212 replace,
1213 (gssize) (replace_len - search_len));
1214 /* we have to treat this specially as it could have
1215 * been reallocated when the insertion happened */
1216 memcpy (string->str + search_idx, replace, replace_len);
1217 } else {
1218 /* just memcmp in the new string */
1219 memcpy (tmp, replace, replace_len);
1220 }
1221 search_idx += replace_len;
1222 count++;
1223 } while (TRUE);
1224
1225 return count;
1226}
Richard Hughese59cb9a2018-12-05 14:37:40 +00001227
Richard Hughesae96a1f2019-09-23 11:16:36 +01001228/**
1229 * fu_common_strwidth:
1230 * @text: The string to operate on
1231 *
1232 * Returns the width of the string in displayed characters on the console.
1233 *
1234 * Returns: width of text
1235 *
1236 * Since: 1.3.2
1237 **/
1238gsize
1239fu_common_strwidth (const gchar *text)
1240{
1241 const gchar *p = text;
1242 gsize width = 0;
1243 while (*p) {
1244 gunichar c = g_utf8_get_char (p);
1245 if (g_unichar_iswide (c))
1246 width += 2;
1247 else if (!g_unichar_iszerowidth (c))
1248 width += 1;
1249 p = g_utf8_next_char (p);
1250 }
1251 return width;
1252}
1253
Mario Limonciello1a680f32019-11-25 19:44:53 -06001254/**
1255 * fu_common_string_append_kv:
1256 * @str: A #GString
1257 * @idt: The indent
1258 * @key: A string to append
1259 * @value: a string to append
1260 *
1261 * Appends a key and string value to a string
1262 *
1263 * Since: 1.2.4
1264 */
Richard Hughescea28de2019-08-09 11:16:40 +01001265void
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001266fu_common_string_append_kv (GString *str, guint idt, const gchar *key, const gchar *value)
Richard Hughescea28de2019-08-09 11:16:40 +01001267{
Richard Hughes847cae82019-08-27 11:22:23 +01001268 const guint align = 25;
1269 gsize keysz;
Richard Hughescea28de2019-08-09 11:16:40 +01001270
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001271 g_return_if_fail (idt * 2 < align);
Richard Hughescea28de2019-08-09 11:16:40 +01001272
1273 /* ignore */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001274 if (key == NULL)
Richard Hughescea28de2019-08-09 11:16:40 +01001275 return;
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001276 for (gsize i = 0; i < idt; i++)
1277 g_string_append (str, " ");
Mario Limonciellofee8f492019-08-18 12:16:07 -05001278 if (key[0] != '\0') {
1279 g_string_append_printf (str, "%s:", key);
Richard Hughesae96a1f2019-09-23 11:16:36 +01001280 keysz = (idt * 2) + fu_common_strwidth (key) + 1;
Richard Hughes847cae82019-08-27 11:22:23 +01001281 } else {
1282 keysz = idt * 2;
Mario Limonciellofee8f492019-08-18 12:16:07 -05001283 }
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001284 if (value != NULL) {
Mario Limonciello1dbb82d2019-09-20 14:22:14 -05001285 g_auto(GStrv) split = NULL;
1286 split = g_strsplit (value, "\n", -1);
1287 for (guint i = 0; split[i] != NULL; i++) {
1288 if (i == 0) {
1289 for (gsize j = keysz; j < align; j++)
1290 g_string_append (str, " ");
1291 } else {
1292 for (gsize j = 0; j < idt; j++)
1293 g_string_append (str, " ");
1294 }
1295 g_string_append (str, split[i]);
1296 g_string_append (str, "\n");
1297 }
1298 } else {
1299 g_string_append (str, "\n");
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001300 }
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001301}
1302
Mario Limonciello1a680f32019-11-25 19:44:53 -06001303/**
1304 * fu_common_string_append_ku:
1305 * @str: A #GString
1306 * @idt: The indent
1307 * @key: A string to append
1308 * @value: guint64
1309 *
1310 * Appends a key and unsigned integer to a string
1311 *
1312 * Since: 1.2.4
1313 */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001314void
1315fu_common_string_append_ku (GString *str, guint idt, const gchar *key, guint64 value)
1316{
1317 g_autofree gchar *tmp = g_strdup_printf ("%" G_GUINT64_FORMAT, value);
1318 fu_common_string_append_kv (str, idt, key, tmp);
1319}
1320
Mario Limonciello1a680f32019-11-25 19:44:53 -06001321/**
1322 * fu_common_string_append_kx:
1323 * @str: A #GString
1324 * @idt: The indent
1325 * @key: A string to append
1326 * @value: guint64
1327 *
1328 * Appends a key and hex integer to a string
1329 *
1330 * Since: 1.2.4
1331 */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001332void
1333fu_common_string_append_kx (GString *str, guint idt, const gchar *key, guint64 value)
1334{
1335 g_autofree gchar *tmp = g_strdup_printf ("0x%x", (guint) value);
1336 fu_common_string_append_kv (str, idt, key, tmp);
1337}
1338
Mario Limonciello1a680f32019-11-25 19:44:53 -06001339/**
1340 * fu_common_string_append_kb:
1341 * @str: A #GString
1342 * @idt: The indent
1343 * @key: A string to append
1344 * @value: Boolean
1345 *
1346 * Appends a key and boolean value to a string
1347 *
1348 * Since: 1.2.4
1349 */
Richard Hughes6e3e62b2019-08-14 10:43:08 +01001350void
1351fu_common_string_append_kb (GString *str, guint idt, const gchar *key, gboolean value)
1352{
1353 fu_common_string_append_kv (str, idt, key, value ? "true" : "false");
Richard Hughescea28de2019-08-09 11:16:40 +01001354}
1355
Richard Hughese59cb9a2018-12-05 14:37:40 +00001356/**
Richard Hughes35481862019-01-06 12:01:58 +00001357 * fu_common_dump_full:
1358 * @log_domain: log domain, typically %G_LOG_DOMAIN or %NULL
1359 * @title: prefix title, or %NULL
1360 * @data: buffer to print
1361 * @len: the size of @data
1362 * @columns: break new lines after this many bytes
1363 * @flags: some #FuDumpFlags, e.g. %FU_DUMP_FLAGS_SHOW_ASCII
1364 *
1365 * Dumps a raw buffer to the screen.
1366 *
1367 * Since: 1.2.4
1368 **/
1369void
1370fu_common_dump_full (const gchar *log_domain,
1371 const gchar *title,
1372 const guint8 *data,
1373 gsize len,
1374 guint columns,
1375 FuDumpFlags flags)
1376{
1377 g_autoptr(GString) str = g_string_new (NULL);
1378
1379 /* optional */
1380 if (title != NULL)
1381 g_string_append_printf (str, "%s:", title);
1382
1383 /* if more than can fit on one line then start afresh */
1384 if (len > columns || flags & FU_DUMP_FLAGS_SHOW_ADDRESSES) {
1385 g_string_append (str, "\n");
1386 } else {
1387 for (gsize i = str->len; i < 16; i++)
1388 g_string_append (str, " ");
1389 }
1390
1391 /* offset line */
1392 if (flags & FU_DUMP_FLAGS_SHOW_ADDRESSES) {
1393 g_string_append (str, " │ ");
1394 for (gsize i = 0; i < columns; i++)
1395 g_string_append_printf (str, "%02x ", (guint) i);
1396 g_string_append (str, "\n───────┼");
1397 for (gsize i = 0; i < columns; i++)
1398 g_string_append (str, "───");
1399 g_string_append_printf (str, "\n0x%04x │ ", (guint) 0);
1400 }
1401
1402 /* print each row */
1403 for (gsize i = 0; i < len; i++) {
1404 g_string_append_printf (str, "%02x ", data[i]);
1405
1406 /* optionally print ASCII char */
1407 if (flags & FU_DUMP_FLAGS_SHOW_ASCII) {
1408 if (g_ascii_isprint (data[i]))
1409 g_string_append_printf (str, "[%c] ", data[i]);
1410 else
1411 g_string_append (str, "[?] ");
1412 }
1413
1414 /* new row required */
1415 if (i > 0 && i != len - 1 && (i + 1) % columns == 0) {
1416 g_string_append (str, "\n");
1417 if (flags & FU_DUMP_FLAGS_SHOW_ADDRESSES)
1418 g_string_append_printf (str, "0x%04x │ ", (guint) i + 1);
1419 }
1420 }
1421 g_log (log_domain, G_LOG_LEVEL_DEBUG, "%s", str->str);
1422}
1423
1424/**
Richard Hughese59cb9a2018-12-05 14:37:40 +00001425 * fu_common_dump_raw:
1426 * @log_domain: log domain, typically %G_LOG_DOMAIN or %NULL
1427 * @title: prefix title, or %NULL
1428 * @data: buffer to print
1429 * @len: the size of @data
1430 *
1431 * Dumps a raw buffer to the screen.
1432 *
1433 * Since: 1.2.2
1434 **/
1435void
1436fu_common_dump_raw (const gchar *log_domain,
1437 const gchar *title,
1438 const guint8 *data,
1439 gsize len)
1440{
Richard Hughes35481862019-01-06 12:01:58 +00001441 FuDumpFlags flags = FU_DUMP_FLAGS_NONE;
1442 if (len > 64)
1443 flags |= FU_DUMP_FLAGS_SHOW_ADDRESSES;
1444 fu_common_dump_full (log_domain, title, data, len, 32, flags);
Richard Hughese59cb9a2018-12-05 14:37:40 +00001445}
1446
1447/**
Mario Limonciello39602652019-04-29 21:08:58 -05001448 * fu_common_dump_bytes:
Richard Hughese59cb9a2018-12-05 14:37:40 +00001449 * @log_domain: log domain, typically %G_LOG_DOMAIN or %NULL
1450 * @title: prefix title, or %NULL
1451 * @bytes: a #GBytes
1452 *
1453 * Dumps a byte buffer to the screen.
1454 *
1455 * Since: 1.2.2
1456 **/
1457void
1458fu_common_dump_bytes (const gchar *log_domain,
1459 const gchar *title,
1460 GBytes *bytes)
1461{
1462 gsize len = 0;
1463 const guint8 *data = g_bytes_get_data (bytes, &len);
1464 fu_common_dump_raw (log_domain, title, data, len);
1465}
Richard Hughesfc90f392019-01-15 21:21:16 +00001466
1467/**
1468 * fu_common_bytes_align:
1469 * @bytes: a #GBytes
1470 * @blksz: block size in bytes
1471 * @padval: the byte used to pad the byte buffer
1472 *
1473 * Aligns a block of memory to @blksize using the @padval value; if
1474 * the block is already aligned then the original @bytes is returned.
1475 *
1476 * Returns: (transfer full): a #GBytes, possibly @bytes
1477 *
1478 * Since: 1.2.4
1479 **/
1480GBytes *
1481fu_common_bytes_align (GBytes *bytes, gsize blksz, gchar padval)
1482{
1483 const guint8 *data;
1484 gsize sz;
1485
1486 g_return_val_if_fail (bytes != NULL, NULL);
1487 g_return_val_if_fail (blksz > 0, NULL);
1488
1489 /* pad */
1490 data = g_bytes_get_data (bytes, &sz);
1491 if (sz % blksz != 0) {
1492 gsize sz_align = ((sz / blksz) + 1) * blksz;
1493 guint8 *data_align = g_malloc (sz_align);
1494 memcpy (data_align, data, sz);
1495 memset (data_align + sz, padval, sz_align - sz);
1496 g_debug ("aligning 0x%x bytes to 0x%x",
1497 (guint) sz, (guint) sz_align);
1498 return g_bytes_new_take (data_align, sz_align);
1499 }
1500
1501 /* perfectly aligned */
1502 return g_bytes_ref (bytes);
1503}
Richard Hughes36999462019-03-19 20:23:29 +00001504
1505/**
1506 * fu_common_bytes_is_empty:
1507 * @bytes: a #GBytes
1508 *
1509 * Checks if a byte array are just empty (0xff) bytes.
1510 *
1511 * Return value: %TRUE if @bytes is empty
Mario Limonciello1a680f32019-11-25 19:44:53 -06001512 *
1513 * Since: 1.2.6
Richard Hughes36999462019-03-19 20:23:29 +00001514 **/
1515gboolean
1516fu_common_bytes_is_empty (GBytes *bytes)
1517{
1518 gsize sz = 0;
1519 const guint8 *buf = g_bytes_get_data (bytes, &sz);
1520 for (gsize i = 0; i < sz; i++) {
1521 if (buf[i] != 0xff)
1522 return FALSE;
1523 }
1524 return TRUE;
1525}
Richard Hughes2aad1042019-03-21 09:03:32 +00001526
1527/**
Richard Hughes38245ff2019-09-18 14:46:09 +01001528 * fu_common_bytes_compare_raw:
1529 * @buf1: a buffer
1530 * @bufsz1: sizeof @buf1
1531 * @buf2: another buffer
1532 * @bufsz2: sizeof @buf2
Richard Hughes2aad1042019-03-21 09:03:32 +00001533 * @error: A #GError or %NULL
1534 *
Richard Hughes38245ff2019-09-18 14:46:09 +01001535 * Compares the buffers for equality.
Richard Hughes2aad1042019-03-21 09:03:32 +00001536 *
Richard Hughes38245ff2019-09-18 14:46:09 +01001537 * Return value: %TRUE if @buf1 and @buf2 are identical
Mario Limonciello1a680f32019-11-25 19:44:53 -06001538 *
1539 * Since: 1.3.2
Richard Hughes2aad1042019-03-21 09:03:32 +00001540 **/
1541gboolean
Richard Hughes38245ff2019-09-18 14:46:09 +01001542fu_common_bytes_compare_raw (const guint8 *buf1, gsize bufsz1,
1543 const guint8 *buf2, gsize bufsz2,
1544 GError **error)
Richard Hughes2aad1042019-03-21 09:03:32 +00001545{
Richard Hughes38245ff2019-09-18 14:46:09 +01001546 g_return_val_if_fail (buf1 != NULL, FALSE);
1547 g_return_val_if_fail (buf2 != NULL, FALSE);
Richard Hughes2aad1042019-03-21 09:03:32 +00001548 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1549
1550 /* not the same length */
Richard Hughes2aad1042019-03-21 09:03:32 +00001551 if (bufsz1 != bufsz2) {
1552 g_set_error (error,
1553 G_IO_ERROR,
1554 G_IO_ERROR_INVALID_DATA,
1555 "got %" G_GSIZE_FORMAT " bytes, expected "
1556 "%" G_GSIZE_FORMAT, bufsz1, bufsz2);
1557 return FALSE;
1558 }
1559
1560 /* check matches */
1561 for (guint i = 0x0; i < bufsz1; i++) {
1562 if (buf1[i] != buf2[i]) {
1563 g_set_error (error,
1564 G_IO_ERROR,
1565 G_IO_ERROR_INVALID_DATA,
1566 "got 0x%02x, expected 0x%02x @ 0x%04x",
1567 buf1[i], buf2[i], i);
1568 return FALSE;
1569 }
1570 }
1571
1572 /* success */
1573 return TRUE;
1574}
Richard Hughes484ee292019-03-22 16:10:50 +00001575
1576/**
Richard Hughes38245ff2019-09-18 14:46:09 +01001577 * fu_common_bytes_compare:
1578 * @bytes1: a #GBytes
1579 * @bytes2: another #GBytes
1580 * @error: A #GError or %NULL
1581 *
1582 * Compares the buffers for equality.
1583 *
1584 * Return value: %TRUE if @bytes1 and @bytes2 are identical
Mario Limonciello1a680f32019-11-25 19:44:53 -06001585 *
1586 * Since: 1.2.6
Richard Hughes38245ff2019-09-18 14:46:09 +01001587 **/
1588gboolean
1589fu_common_bytes_compare (GBytes *bytes1, GBytes *bytes2, GError **error)
1590{
1591 const guint8 *buf1;
1592 const guint8 *buf2;
1593 gsize bufsz1;
1594 gsize bufsz2;
1595
1596 g_return_val_if_fail (bytes1 != NULL, FALSE);
1597 g_return_val_if_fail (bytes2 != NULL, FALSE);
1598 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1599
1600 buf1 = g_bytes_get_data (bytes1, &bufsz1);
1601 buf2 = g_bytes_get_data (bytes2, &bufsz2);
1602 return fu_common_bytes_compare_raw (buf1, bufsz1, buf2, bufsz2, error);
1603}
1604
1605/**
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001606 * fu_common_bytes_pad:
1607 * @bytes: a #GBytes
1608 * @sz: the desired size in bytes
1609 *
1610 * Pads a GBytes to a given @sz with `0xff`.
1611 *
1612 * Return value: (transfer full): a #GBytes
Mario Limonciello1a680f32019-11-25 19:44:53 -06001613 *
1614 * Since: 1.3.1
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001615 **/
1616GBytes *
1617fu_common_bytes_pad (GBytes *bytes, gsize sz)
1618{
1619 gsize bytes_sz;
1620
1621 g_return_val_if_fail (g_bytes_get_size (bytes) <= sz, NULL);
1622
1623 /* pad */
1624 bytes_sz = g_bytes_get_size (bytes);
1625 if (bytes_sz < sz) {
1626 const guint8 *data = g_bytes_get_data (bytes, NULL);
1627 guint8 *data_new = g_malloc (sz);
1628 memcpy (data_new, data, bytes_sz);
1629 memset (data_new + bytes_sz, 0xff, sz - bytes_sz);
1630 return g_bytes_new_take (data_new, sz);
1631 }
1632
1633 /* exactly right */
1634 return g_bytes_ref (bytes);
1635}
1636
1637/**
Richard Hughes484ee292019-03-22 16:10:50 +00001638 * fu_common_realpath:
1639 * @filename: a filename
1640 * @error: A #GError or %NULL
1641 *
1642 * Finds the canonicalized absolute filename for a path.
1643 *
1644 * Return value: A filename, or %NULL if invalid or not found
Mario Limonciello1a680f32019-11-25 19:44:53 -06001645 *
1646 * Since: 1.2.6
Richard Hughes484ee292019-03-22 16:10:50 +00001647 **/
1648gchar *
1649fu_common_realpath (const gchar *filename, GError **error)
1650{
1651 char full_tmp[PATH_MAX];
1652
1653 g_return_val_if_fail (filename != NULL, NULL);
1654
Richard Hughes8694dee2019-11-22 09:16:34 +00001655#ifdef HAVE_REALPATH
Richard Hughes484ee292019-03-22 16:10:50 +00001656 if (realpath (filename, full_tmp) == NULL) {
Richard Hughes8694dee2019-11-22 09:16:34 +00001657#else
1658 if (_fullpath (full_tmp, filename, sizeof(full_tmp)) == NULL) {
1659#endif
Richard Hughes484ee292019-03-22 16:10:50 +00001660 g_set_error (error,
1661 G_IO_ERROR,
1662 G_IO_ERROR_INVALID_DATA,
1663 "cannot resolve path: %s",
1664 strerror (errno));
1665 return NULL;
1666 }
Richard Hughes8694dee2019-11-22 09:16:34 +00001667 if (!g_file_test (full_tmp, G_FILE_TEST_EXISTS)) {
1668 g_set_error (error,
1669 G_IO_ERROR,
1670 G_IO_ERROR_INVALID_DATA,
1671 "cannot find path: %s",
1672 full_tmp);
1673 return NULL;
1674 }
Richard Hughes484ee292019-03-22 16:10:50 +00001675 return g_strdup (full_tmp);
1676}
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001677
1678/**
Richard Hughes5c508de2019-11-22 09:57:34 +00001679 * fu_common_fnmatch:
1680 * @pattern: a glob pattern, e.g. `*foo*`
1681 * @str: a string to match against the pattern, e.g. `bazfoobar`
1682 *
1683 * Matches a string against a glob pattern.
1684 *
1685 * Return value: %TRUE if the string matched
1686 *
1687 * Since: 1.3.5
1688 **/
1689gboolean
1690fu_common_fnmatch (const gchar *pattern, const gchar *str)
1691{
1692 g_return_val_if_fail (pattern != NULL, FALSE);
1693 g_return_val_if_fail (str != NULL, FALSE);
1694#ifdef HAVE_FNMATCH_H
1695 return fnmatch (pattern, str, FNM_NOESCAPE) == 0;
Richard Hughes45a00732019-11-22 16:57:14 +00001696#elif _WIN32
1697 g_return_val_if_fail (strlen (pattern) < MAX_PATH, FALSE);
1698 g_return_val_if_fail (strlen (str) < MAX_PATH, FALSE);
1699 return PathMatchSpecA (str, pattern);
Richard Hughes5c508de2019-11-22 09:57:34 +00001700#else
1701 return g_strcmp0 (pattern, str) == 0;
1702#endif
1703}
1704
Richard Hughesa84d7a72020-05-06 12:11:51 +01001705static gint
1706fu_common_filename_glob_sort_cb (gconstpointer a, gconstpointer b)
1707{
1708 return g_strcmp0 (*(const gchar **)a, *(const gchar **)b);
1709}
1710
1711/**
1712 * fu_common_filename_glob:
1713 * @directory: a directory path
1714 * @pattern: a glob pattern, e.g. `*foo*`
1715 * @error: A #GError or %NULL
1716 *
1717 * Returns all the filenames that match a specific glob pattern.
1718 * Any results are sorted. No matching files will set @error.
1719 *
1720 * Return value: (element-type utf8) (transfer container): matching files, or %NULL
1721 *
1722 * Since: 1.5.0
1723 **/
1724GPtrArray *
1725fu_common_filename_glob (const gchar *directory, const gchar *pattern, GError **error)
1726{
1727 const gchar *basename;
1728 g_autoptr(GDir) dir = g_dir_open (directory, 0, error);
1729 g_autoptr(GPtrArray) files = g_ptr_array_new_with_free_func (g_free);
1730 if (dir == NULL)
1731 return NULL;
1732 while ((basename = g_dir_read_name (dir)) != NULL) {
1733 if (!fu_common_fnmatch (pattern, basename))
1734 continue;
1735 g_ptr_array_add (files, g_build_filename (directory, basename, NULL));
1736 }
1737 if (files->len == 0) {
1738 g_set_error_literal (error,
1739 G_IO_ERROR,
1740 G_IO_ERROR_NOT_FOUND,
1741 "no files matched pattern");
1742 return NULL;
1743 }
1744 g_ptr_array_sort (files, fu_common_filename_glob_sort_cb);
1745 return g_steal_pointer (&files);
1746}
1747
Richard Hughes5c508de2019-11-22 09:57:34 +00001748/**
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001749 * fu_common_strnsplit:
1750 * @str: a string to split
1751 * @sz: size of @str
1752 * @delimiter: a string which specifies the places at which to split the string
1753 * @max_tokens: the maximum number of pieces to split @str into
1754 *
1755 * Splits a string into a maximum of @max_tokens pieces, using the given
1756 * delimiter. If @max_tokens is reached, the remainder of string is appended
1757 * to the last token.
1758 *
Richard Hughesa0d81c72019-11-27 11:41:54 +00001759 * Return value: (transfer full): a newly-allocated NULL-terminated array of strings
Mario Limonciello1a680f32019-11-25 19:44:53 -06001760 *
1761 * Since: 1.3.1
Richard Hughes7afd7cb2019-08-07 11:42:42 +01001762 **/
1763gchar **
1764fu_common_strnsplit (const gchar *str, gsize sz,
1765 const gchar *delimiter, gint max_tokens)
1766{
1767 if (str[sz - 1] != '\0') {
1768 g_autofree gchar *str2 = g_strndup (str, sz);
1769 return g_strsplit (str2, delimiter, max_tokens);
1770 }
1771 return g_strsplit (str, delimiter, max_tokens);
1772}
Richard Hughes5308ea42019-08-09 12:25:13 +01001773
1774/**
1775 * fu_memcpy_safe:
1776 * @dst: destination buffer
1777 * @dst_sz: maximum size of @dst, typically `sizeof(dst)`
1778 * @dst_offset: offset in bytes into @dst to copy to
1779 * @src: source buffer
1780 * @src_sz: maximum size of @dst, typically `sizeof(src)`
1781 * @src_offset: offset in bytes into @src to copy from
1782 * @n: number of bytes to copy from @src+@offset from
1783 * @error: A #GError or %NULL
1784 *
1785 * Copies some memory using memcpy in a safe way. Providing the buffer sizes
1786 * of both the destination and the source allows us to check for buffer overflow.
1787 *
1788 * Providing the buffer offsets also allows us to check reading past the end of
1789 * the source buffer. For this reason the caller should NEVER add an offset to
1790 * @src or @dst.
1791 *
1792 * You don't need to use this function in "obviously correct" cases, nor should
1793 * you use it when performance is a concern. Only us it when you're not sure if
1794 * malicious data from a device or firmware could cause memory corruption.
1795 *
1796 * Return value: %TRUE if the bytes were copied, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06001797 *
1798 * Since: 1.3.1
Richard Hughes5308ea42019-08-09 12:25:13 +01001799 **/
1800gboolean
1801fu_memcpy_safe (guint8 *dst, gsize dst_sz, gsize dst_offset,
1802 const guint8 *src, gsize src_sz, gsize src_offset,
1803 gsize n, GError **error)
1804{
1805 if (n == 0)
1806 return TRUE;
1807
1808 if (n > src_sz) {
1809 g_set_error (error,
1810 FWUPD_ERROR,
1811 FWUPD_ERROR_READ,
1812 "attempted to read 0x%02x bytes from buffer of 0x%02x",
1813 (guint) n, (guint) src_sz);
1814 return FALSE;
1815 }
1816 if (n + src_offset > src_sz) {
1817 g_set_error (error,
1818 FWUPD_ERROR,
1819 FWUPD_ERROR_READ,
1820 "attempted to read 0x%02x bytes at offset 0x%02x from buffer of 0x%02x",
1821 (guint) n, (guint) src_offset, (guint) src_sz);
1822 return FALSE;
1823 }
1824 if (n > dst_sz) {
1825 g_set_error (error,
1826 FWUPD_ERROR,
1827 FWUPD_ERROR_WRITE,
1828 "attempted to write 0x%02x bytes to buffer of 0x%02x",
1829 (guint) n, (guint) dst_sz);
1830 return FALSE;
1831 }
1832 if (n + dst_offset > dst_sz) {
1833 g_set_error (error,
1834 FWUPD_ERROR,
1835 FWUPD_ERROR_WRITE,
1836 "attempted to write 0x%02x bytes at offset 0x%02x to buffer of 0x%02x",
1837 (guint) n, (guint) dst_offset, (guint) dst_sz);
1838 return FALSE;
1839 }
1840
1841 /* phew! */
1842 memcpy (dst + dst_offset, src + src_offset, n);
1843 return TRUE;
1844}
Richard Hughes37c6a7b2019-08-14 21:57:43 +01001845
Richard Hughes80768f52019-10-22 07:19:14 +01001846/**
Richard Hughesc21a0b92019-10-24 12:24:37 +01001847 * fu_common_read_uint8_safe:
1848 * @buf: source buffer
1849 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
1850 * @offset: offset in bytes into @buf to copy from
1851 * @value: (out) (allow-none): the parsed value
1852 * @error: A #GError or %NULL
1853 *
1854 * Read a value from a buffer in a safe way.
1855 *
1856 * You don't need to use this function in "obviously correct" cases, nor should
1857 * you use it when performance is a concern. Only us it when you're not sure if
1858 * malicious data from a device or firmware could cause memory corruption.
1859 *
1860 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06001861 *
1862 * Since: 1.3.3
Richard Hughesc21a0b92019-10-24 12:24:37 +01001863 **/
1864gboolean
1865fu_common_read_uint8_safe (const guint8 *buf,
1866 gsize bufsz,
1867 gsize offset,
1868 guint8 *value,
1869 GError **error)
1870{
1871 guint8 tmp;
1872 if (!fu_memcpy_safe (&tmp, sizeof(tmp), 0x0, /* dst */
1873 buf, bufsz, offset, /* src */
1874 sizeof(tmp), error))
1875 return FALSE;
1876 if (value != NULL)
1877 *value = tmp;
1878 return TRUE;
1879}
1880
1881/**
Richard Hughes80768f52019-10-22 07:19:14 +01001882 * fu_common_read_uint16_safe:
1883 * @buf: source buffer
1884 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
1885 * @offset: offset in bytes into @buf to copy from
1886 * @value: (out) (allow-none): the parsed value
1887 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
1888 * @error: A #GError or %NULL
1889 *
1890 * Read a value from a buffer using a specified endian in a safe way.
1891 *
1892 * You don't need to use this function in "obviously correct" cases, nor should
1893 * you use it when performance is a concern. Only us it when you're not sure if
1894 * malicious data from a device or firmware could cause memory corruption.
1895 *
1896 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06001897 *
1898 * Since: 1.3.3
Richard Hughes80768f52019-10-22 07:19:14 +01001899 **/
1900gboolean
1901fu_common_read_uint16_safe (const guint8 *buf,
1902 gsize bufsz,
1903 gsize offset,
1904 guint16 *value,
1905 FuEndianType endian,
1906 GError **error)
1907{
1908 guint8 dst[2] = { 0x0 };
Richard Hughes7d01ac92019-10-23 14:31:46 +01001909 if (!fu_memcpy_safe (dst, sizeof(dst), 0x0, /* dst */
Richard Hughes80768f52019-10-22 07:19:14 +01001910 buf, bufsz, offset, /* src */
Richard Hughes7d01ac92019-10-23 14:31:46 +01001911 sizeof(dst), error))
Richard Hughes80768f52019-10-22 07:19:14 +01001912 return FALSE;
1913 if (value != NULL)
1914 *value = fu_common_read_uint16 (dst, endian);
1915 return TRUE;
1916}
1917
1918/**
1919 * fu_common_read_uint32_safe:
1920 * @buf: source buffer
1921 * @bufsz: maximum size of @buf, typically `sizeof(buf)`
1922 * @offset: offset in bytes into @buf to copy from
1923 * @value: (out) (allow-none): the parsed value
1924 * @endian: A #FuEndianType, e.g. %G_LITTLE_ENDIAN
1925 * @error: A #GError or %NULL
1926 *
1927 * Read a value from a buffer using a specified endian in a safe way.
1928 *
1929 * You don't need to use this function in "obviously correct" cases, nor should
1930 * you use it when performance is a concern. Only us it when you're not sure if
1931 * malicious data from a device or firmware could cause memory corruption.
1932 *
1933 * Return value: %TRUE if @value was set, %FALSE otherwise
Mario Limonciello1a680f32019-11-25 19:44:53 -06001934 *
1935 * Since: 1.3.3
Richard Hughes80768f52019-10-22 07:19:14 +01001936 **/
1937gboolean
1938fu_common_read_uint32_safe (const guint8 *buf,
1939 gsize bufsz,
1940 gsize offset,
1941 guint32 *value,
1942 FuEndianType endian,
1943 GError **error)
1944{
1945 guint8 dst[4] = { 0x0 };
Richard Hughes7d01ac92019-10-23 14:31:46 +01001946 if (!fu_memcpy_safe (dst, sizeof(dst), 0x0, /* dst */
Richard Hughes80768f52019-10-22 07:19:14 +01001947 buf, bufsz, offset, /* src */
Richard Hughes7d01ac92019-10-23 14:31:46 +01001948 sizeof(dst), error))
Richard Hughes80768f52019-10-22 07:19:14 +01001949 return FALSE;
1950 if (value != NULL)
1951 *value = fu_common_read_uint32 (dst, endian);
1952 return TRUE;
1953}
1954
Mario Limonciello1a680f32019-11-25 19:44:53 -06001955/**
1956 * fu_byte_array_append_uint8:
1957 * @array: A #GByteArray
1958 * @data: #guint8
1959 *
1960 * Adds a 8 bit integer to a byte array
1961 *
1962 * Since: 1.3.1
1963 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01001964void
1965fu_byte_array_append_uint8 (GByteArray *array, guint8 data)
1966{
1967 g_byte_array_append (array, &data, sizeof(data));
1968}
1969
Mario Limonciello1a680f32019-11-25 19:44:53 -06001970/**
1971 * fu_byte_array_append_uint16:
1972 * @array: A #GByteArray
1973 * @data: #guint16
1974 * @endian: #FuEndianType
1975 *
1976 * Adds a 16 bit integer to a byte array
1977 *
1978 * Since: 1.3.1
1979 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01001980void
1981fu_byte_array_append_uint16 (GByteArray *array, guint16 data, FuEndianType endian)
1982{
1983 guint8 buf[2];
1984 fu_common_write_uint16 (buf, data, endian);
1985 g_byte_array_append (array, buf, sizeof(buf));
1986}
1987
Mario Limonciello1a680f32019-11-25 19:44:53 -06001988/**
1989 * fu_byte_array_append_uint32:
1990 * @array: A #GByteArray
1991 * @data: #guint32
1992 * @endian: #FuEndianType
1993 *
1994 * Adds a 32 bit integer to a byte array
1995 *
1996 * Since: 1.3.1
1997 **/
Richard Hughes37c6a7b2019-08-14 21:57:43 +01001998void
1999fu_byte_array_append_uint32 (GByteArray *array, guint32 data, FuEndianType endian)
2000{
2001 guint8 buf[4];
2002 fu_common_write_uint32 (buf, data, endian);
2003 g_byte_array_append (array, buf, sizeof(buf));
2004}
Mario Limonciello9dce1f72020-02-04 09:12:52 -06002005
2006/**
2007 * fu_common_kernel_locked_down:
2008 *
2009 * Determines if kernel lockdown in effect
2010 *
2011 * Since: 1.3.8
2012 **/
2013gboolean
2014fu_common_kernel_locked_down (void)
2015{
2016#ifndef _WIN32
2017 gsize len = 0;
2018 g_autofree gchar *dir = fu_common_get_path (FU_PATH_KIND_SYSFSDIR_SECURITY);
2019 g_autofree gchar *fname = g_build_filename (dir, "lockdown", NULL);
2020 g_autofree gchar *data = NULL;
2021 g_auto(GStrv) options = NULL;
2022
2023 if (!g_file_test (fname, G_FILE_TEST_EXISTS))
2024 return FALSE;
2025 if (!g_file_get_contents (fname, &data, &len, NULL))
2026 return FALSE;
2027 if (len < 1)
2028 return FALSE;
2029 options = g_strsplit (data, " ", -1);
2030 for (guint i = 0; options[i] != NULL; i++) {
2031 if (g_strcmp0 (options[i], "[none]") == 0)
2032 return FALSE;
2033 }
2034 return TRUE;
2035#else
2036 return FALSE;
2037#endif
2038}
Richard Hughes9223c892020-05-09 20:32:08 +01002039
2040/**
2041 * fu_common_is_cpu_intel:
2042 *
2043 * Uses CPUID to discover the CPU vendor and check if it is Intel.
2044 *
2045 * Return value: %TRUE if the vendor was Intel.
2046 *
2047 * Since: 1.5.0
2048 **/
2049gboolean
2050fu_common_is_cpu_intel (void)
2051{
Richard Hughesbd444322020-05-21 12:05:03 +01002052#ifdef HAVE_CPUID_H
Richard Hughes9223c892020-05-09 20:32:08 +01002053 guint eax = 0;
2054 guint ebx = 0;
2055 guint ecx = 0;
2056 guint edx = 0;
2057 guint level = 0;
2058
2059 /* get vendor */
2060 __get_cpuid(level, &eax, &ebx, &ecx, &edx);
2061 if (ebx == signature_INTEL_ebx &&
2062 edx == signature_INTEL_edx &&
2063 ecx == signature_INTEL_ecx) {
2064 return TRUE;
2065 }
Richard Hughesbd444322020-05-21 12:05:03 +01002066#endif
Richard Hughes9223c892020-05-09 20:32:08 +01002067 return FALSE;
2068}