Debian Codegraph @

src/utils/exec.c

raw
1 /*
2 * Copyright (C) 2014 Red Hat, Inc.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
16 *
17 * Author: Vratislav Podzimek <[email protected]>
18 */
19
20 #include <glib.h>
21 #include "exec.h"
22 #include "extra_arg.h"
23 #include "logging.h"
24 #include <stdlib.h>
25 #include <poll.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/wait.h>
30 #include <unistd.h>
31
32 #ifdef __clang__
33 #define ZERO_INIT {}
34 #else
35 #define ZERO_INIT {0}
36 #endif
37
38
39 extern char **environ;
40
41 static GMutex id_counter_lock;
42 static guint64 id_counter = 0;
43
44 static GMutex task_id_counter_lock;
45 static guint64 task_id_counter = 0;
46 static BDUtilsProgFunc prog_func = NULL;
47 static __thread BDUtilsProgFunc thread_prog_func = NULL;
48
49 /**
50 * bd_utils_exec_error_quark: (skip)
51 */
52 GQuark bd_utils_exec_error_quark (void)
53 {
54 return g_quark_from_static_string ("g-bd-utils-exec-error-quark");
55 }
56
57 /**
58 * bd_utils_get_next_task_id:
59 */
60 guint64 bd_utils_get_next_task_id (void) {
61 guint64 task_id = 0;
62
63 g_mutex_lock (&id_counter_lock);
64 id_counter++;
65 task_id = id_counter;
66 g_mutex_unlock (&id_counter_lock);
67
68 return task_id;
69 }
70
71 /**
72 * bd_utils_log_task_status:
73 * @task_id: ID of the task the status of which is being logged
74 * @msg: log message
75 */
76 void bd_utils_log_task_status (guint64 task_id, const gchar *msg) {
77 gchar *log_msg = NULL;
78
79 log_msg = g_strdup_printf ("[%"G_GUINT64_FORMAT"] %s", task_id, msg);
80 bd_utils_log (BD_UTILS_LOG_INFO, log_msg);
81 g_free (log_msg);
82 }
83
84 /**
85 * log_running: (skip)
86 *
87 * Returns: id of the running task
88 */
89 static guint64 log_running (const gchar **argv) {
90 guint64 task_id = 0;
91 gchar *str_argv = NULL;
92 gchar *log_msg = NULL;
93
94 task_id = bd_utils_get_next_task_id ();
95
96 str_argv = g_strjoinv (" ", (gchar **) argv);
97 log_msg = g_strdup_printf ("Running [%"G_GUINT64_FORMAT"] %s ...", task_id, str_argv);
98 bd_utils_log (BD_UTILS_LOG_INFO, log_msg);
99 g_free (str_argv);
100 g_free (log_msg);
101
102 return task_id;
103 }
104
105 /**
106 * log_out: (skip)
107 *
108 */
109 static void log_out (guint64 task_id, const gchar *stdout, const gchar *stderr) {
110 gchar *log_msg = NULL;
111
112 log_msg = g_strdup_printf ("stdout[%"G_GUINT64_FORMAT"]: %s", task_id, stdout);
113 bd_utils_log (BD_UTILS_LOG_INFO, log_msg);
114 g_free (log_msg);
115
116 log_msg = g_strdup_printf ("stderr[%"G_GUINT64_FORMAT"]: %s", task_id, stderr);
117 bd_utils_log (BD_UTILS_LOG_INFO, log_msg);
118 g_free (log_msg);
119
120 return;
121 }
122
123 /**
124 * log_done: (skip)
125 *
126 */
127 static void log_done (guint64 task_id, gint exit_code) {
128 gchar *log_msg = NULL;
129
130 log_msg = g_strdup_printf ("...done [%"G_GUINT64_FORMAT"] (exit code: %d)", task_id, exit_code);
131 bd_utils_log (BD_UTILS_LOG_INFO, log_msg);
132 g_free (log_msg);
133
134
135 return;
136 }
137
138 static const gchar ** _append_extra_args (const gchar **argv, const BDExtraArg **extra) {
139 const gchar **args = NULL;
140 guint args_len = 0;
141 const BDExtraArg **extra_p = NULL;
142 const gchar **arg_p = NULL;
143 guint i = 0;
144
145 if (!extra)
146 return NULL;
147
148 args_len = g_strv_length ((gchar **) argv);
149 for (extra_p = extra; *extra_p; extra_p++) {
150 if ((*extra_p)->opt && (g_strcmp0 ((*extra_p)->opt, "") != 0))
151 args_len++;
152 if ((*extra_p)->val && (g_strcmp0 ((*extra_p)->val, "") != 0))
153 args_len++;
154 }
155
156 args = g_new0 (const gchar *, args_len + 1);
157 for (arg_p = argv; *arg_p; arg_p++)
158 args[i++] = *arg_p;
159 for (extra_p = extra; *extra_p; extra_p++) {
160 if ((*extra_p)->opt && (g_strcmp0 ((*extra_p)->opt, "") != 0))
161 args[i++] = (*extra_p)->opt;
162 if ((*extra_p)->val && (g_strcmp0 ((*extra_p)->val, "") != 0))
163 args[i++] = (*extra_p)->val;
164 }
165
166 return args;
167 }
168
169 /**
170 * bd_utils_exec_and_report_error:
171 * @argv: (array zero-terminated=1): the argv array for the call
172 * @extra: (nullable) (array zero-terminated=1): extra arguments
173 * @error: (out) (optional): place to store error (if any)
174 *
175 * Returns: whether the @argv was successfully executed (no error and exit code 0) or not
176 */
177 gboolean bd_utils_exec_and_report_error (const gchar **argv, const BDExtraArg **extra, GError **error) {
178 gint status = 0;
179 /* just use the "stronger" function providing dumb progress reporting (just
180 'started' and 'finished') and throw away the returned status */
181 return bd_utils_exec_and_report_progress (argv, extra, NULL, &status, error);
182 }
183
184 /**
185 * bd_utils_exec_and_report_error_no_progress:
186 * @argv: (array zero-terminated=1): the argv array for the call
187 * @extra: (nullable) (array zero-terminated=1): extra arguments
188 * @error: (out) (optional): place to store error (if any)
189 *
190 * Returns: whether the @argv was successfully executed (no error and exit code 0) or not
191 */
192 gboolean bd_utils_exec_and_report_error_no_progress (const gchar **argv, const BDExtraArg **extra, GError **error) {
193 gint status = 0;
194 /* just use the "stronger" function and throw away the returned status */
195 return bd_utils_exec_and_report_status_error (argv, extra, &status, error);
196 }
197
198 /**
199 * bd_utils_exec_and_capture_output_no_progress:
200 * @argv: (array zero-terminated=1): the argv array for the call
201 * @extra: (nullable) (array zero-terminated=1): extra arguments
202 * @output: (out) (optional): place to store stdout to
203 * @stderr: (out) (optional): place to store stderr to
204 * @status: (out): place to store the process return code
205 * @error: (out) (optional): place to store error (if any)
206 *
207 * Returns: whether the @argv was successfully executed capturing the output or not
208 */
209 gboolean bd_utils_exec_and_capture_output_no_progress (const gchar **argv, const BDExtraArg **extra, gchar **output, gchar **stderr, gint *status, GError **error) {
210 gboolean success = FALSE;
211 gchar *stdout_data = NULL;
212 gchar *stderr_data = NULL;
213 guint64 task_id = 0;
214 const gchar **args = NULL;
215 gint exit_status = 0;
216 gchar **old_env = NULL;
217 gchar **new_env = NULL;
218 GError *l_error = NULL;
219
220 args = _append_extra_args (argv, extra);
221
222 old_env = g_get_environ ();
223 new_env = g_environ_setenv (old_env, "LC_ALL", "C.UTF-8", TRUE);
224 new_env = g_environ_unsetenv (new_env, "LANGUAGE");
225
226 task_id = log_running (args ? args : argv);
227 success = g_spawn_sync (NULL, args ? (gchar **) args : (gchar **) argv, new_env, G_SPAWN_SEARCH_PATH,
228 NULL, NULL, &stdout_data, &stderr_data, &exit_status, error);
229 g_strfreev (new_env);
230 if (!success) {
231 /* error is already populated from the call */
232 g_free (stdout_data);
233 g_free (stderr_data);
234 g_free (args);
235 return FALSE;
236 }
237
238 /* g_spawn_sync set the status in the same way waitpid() does, we need
239 to get the process exit code manually (this is similar to calling
240 WEXITSTATUS but also sets the error for terminated processes */
241
242 #if !GLIB_CHECK_VERSION(2, 69, 0)
243 #define g_spawn_check_wait_status(x,y) (g_spawn_check_exit_status (x,y))
244 #endif
245
246 if (!g_spawn_check_wait_status (exit_status, &l_error)) {
247 if (g_error_matches (l_error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED)) {
248 /* process was terminated abnormally (e.g. using a signal) */
249 g_free (stdout_data);
250 g_free (stderr_data);
251 g_free (args);
252 g_propagate_error (error, l_error);
253 return FALSE;
254 }
255
256 *status = l_error->code;
257 g_clear_error (&l_error);
258 } else
259 *status = 0;
260
261 log_out (task_id, stdout_data, stderr_data);
262 log_done (task_id, *status);
263
264 g_free (args);
265 if (output)
266 *output = stdout_data;
267 else
268 g_free (stdout_data);
269 if (stderr)
270 *stderr = stderr_data;
271 else
272 g_free (stderr_data);
273
274 return TRUE;
275 }
276
277 /**
278 * bd_utils_exec_and_report_status_error:
279 * @argv: (array zero-terminated=1): the argv array for the call
280 * @extra: (nullable) (array zero-terminated=1): extra arguments
281 * @status: (out): place to store the status
282 * @error: (out) (optional): place to store error (if any)
283 *
284 * Returns: whether the @argv was successfully executed (no error and exit code 0) or not
285 */
286 gboolean bd_utils_exec_and_report_status_error (const gchar **argv, const BDExtraArg **extra, gint *status, GError **error) {
287 gboolean ret;
288 gchar *stdout_data = NULL;
289 gchar *stderr_data = NULL;
290
291 ret = bd_utils_exec_and_capture_output_no_progress (argv, extra, &stdout_data, &stderr_data, status, error);
292
293 if (ret && *status != 0) {
294 if (stderr_data && (g_strcmp0 ("", stderr_data) != 0))
295 g_set_error (error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_FAILED,
296 "Process reported exit code %d: %s", *status, stderr_data);
297 else
298 g_set_error (error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_FAILED,
299 "Process reported exit code %d: %s", *status, stdout_data);
300 ret = FALSE;
301 }
302 g_free (stdout_data);
303 g_free (stderr_data);
304 return ret;
305 }
306
307 /* buffer size in bytes used to read from stdout and stderr */
308 #define _EXEC_BUF_SIZE 64*1024
309
310 /* similar to g_strstr_len() yet treats 'null' byte as @needle. */
311 static gchar *bd_strchr_len_null (const gchar *haystack, gssize haystack_len, const gchar needle) {
312 gchar *ret;
313 gchar *ret_null;
314
315 ret = memchr (haystack, needle, haystack_len);
316 ret_null = memchr (haystack, 0, haystack_len);
317 if (ret && ret_null)
318 return MIN (ret, ret_null);
319 else
320 return MAX (ret, ret_null);
321 }
322
323 static gboolean
324 _process_fd_event (gint fd, struct pollfd *poll_fd, GString *read_buffer, GString *filtered_buffer, gsize *read_buffer_pos, gboolean *done,
325 guint64 progress_id, guint8 *progress, BDUtilsProgExtract prog_extract, GError **error) {
326 gchar buf[_EXEC_BUF_SIZE] = { 0 };
327 ssize_t num_read;
328 gchar *line;
329 gchar *newline_pos;
330 int errno_saved;
331 gboolean eof = FALSE;
332
333 if (! *done && (poll_fd->revents & POLLIN)) {
334 /* read until we get EOF (0) or error (-1), expecting EAGAIN */
335 while ((num_read = read (fd, buf, _EXEC_BUF_SIZE)) > 0)
336 g_string_append_len (read_buffer, buf, num_read);
337 errno_saved = errno;
338
339 /* process the fresh data by lines */
340 if (read_buffer->len > *read_buffer_pos) {
341 gchar *buf_ptr;
342 gsize buf_len;
343
344 while ((buf_ptr = read_buffer->str + *read_buffer_pos,
345 buf_len = read_buffer->len - *read_buffer_pos,
346 newline_pos = bd_strchr_len_null (buf_ptr, buf_len, '\n'))) {
347 line = g_strndup (buf_ptr, newline_pos - buf_ptr + 1);
348 if (prog_extract && prog_extract (line, progress))
349 bd_utils_report_progress (progress_id, *progress, NULL);
350 else
351 g_string_append (filtered_buffer, line);
352 g_free (line);
353 *read_buffer_pos = newline_pos - read_buffer->str + 1;
354 }
355 }
356
357 /* read error */
358 if (num_read < 0 && errno_saved != EAGAIN && errno_saved != EINTR) {
359 g_set_error (error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_FAILED,
360 "Error reading from pipe: %s", g_strerror (errno_saved));
361 return FALSE;
362 }
363
364 /* EOF */
365 if (num_read == 0)
366 eof = TRUE;
367 }
368
369 if (poll_fd->revents & POLLHUP || poll_fd->revents & POLLERR || poll_fd->revents & POLLNVAL)
370 eof = TRUE;
371
372 if (eof) {
373 *done = TRUE;
374 /* process the remaining buffer */
375 line = read_buffer->str + *read_buffer_pos;
376 /* GString guarantees the buffer is always NULL-terminated. */
377 if (strlen (line) > 0) {
378 if (prog_extract && prog_extract (line, progress))
379 bd_utils_report_progress (progress_id, *progress, NULL);
380 else
381 g_string_append (filtered_buffer, line);
382 }
383 }
384
385 return TRUE;
386 }
387
388 static gboolean _utils_exec_and_report_progress (const gchar **argv, const BDExtraArg **extra, BDUtilsProgExtract prog_extract, const gchar *input, gint *proc_status, gchar **stdout, gchar **stderr, GError **error) {
389 const gchar **args = NULL;
390 gchar *args_str = NULL;
391 guint64 task_id = 0;
392 guint64 progress_id = 0;
393 gchar *msg = NULL;
394 GPid pid = 0;
395 gint out_fd = 0;
396 gint err_fd = 0;
397 gint in_fd = 0;
398 gint child_ret = -1;
399 gint status = 0;
400 gboolean ret = FALSE;
401 gint poll_status = 0;
402 guint8 completion = 0;
403 struct pollfd fds[2] = { ZERO_INIT, ZERO_INIT };
404 int flags;
405 gboolean out_done = FALSE;
406 gboolean err_done = FALSE;
407 GString *stdout_data;
408 GString *stdout_buffer;
409 GString *stderr_data;
410 GString *stderr_buffer;
411 gsize stdout_buffer_pos = 0;
412 gsize stderr_buffer_pos = 0;
413 gchar **old_env = NULL;
414 gchar **new_env = NULL;
415 gboolean success = TRUE;
416 GError *l_error = NULL;
417
418 args = _append_extra_args (argv, extra);
419
420 task_id = log_running (args ? args : argv);
421
422 old_env = g_get_environ ();
423 new_env = g_environ_setenv (old_env, "LC_ALL", "C.UTF-8", TRUE);
424 new_env = g_environ_unsetenv (new_env, "LANGUAGE");
425
426 ret = g_spawn_async_with_pipes (NULL, args ? (gchar**) args : (gchar**) argv, new_env,
427 G_SPAWN_DEFAULT|G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD,
428 NULL, NULL, &pid, input ? &in_fd : NULL, &out_fd, &err_fd, error);
429
430 g_strfreev (new_env);
431
432 if (!ret) {
433 /* error is already populated */
434 g_free (args);
435 return FALSE;
436 }
437
438 args_str = g_strjoinv (" ", args ? (gchar **) args : (gchar **) argv);
439 msg = g_strdup_printf ("Started '%s'", args_str);
440 progress_id = bd_utils_report_started (msg);
441 g_free (args_str);
442 g_free (args);
443 g_free (msg);
444
445 /* set both fds for non-blocking read */
446 flags = fcntl (out_fd, F_GETFL, 0);
447 if (fcntl (out_fd, F_SETFL, flags | O_NONBLOCK))
448 bd_utils_log_format (BD_UTILS_LOG_WARNING,
449 "_utils_exec_and_report_progress: Failed to set out_fd non-blocking: %m");
450 flags = fcntl (err_fd, F_GETFL, 0);
451 if (fcntl (err_fd, F_SETFL, flags | O_NONBLOCK))
452 bd_utils_log_format (BD_UTILS_LOG_WARNING,
453 "_utils_exec_and_report_progress: Failed to set err_fd non-blocking: %m");
454
455 if (input) {
456 ssize_t num_written = 0;
457 ssize_t num_written_total = 0;
458 size_t len = strlen (input);
459
460 while (len - num_written_total > 0 && (num_written = write (in_fd, input + num_written_total, len - num_written_total)) > 0)
461 num_written_total += num_written;
462
463 if (num_written < 0) {
464 g_set_error (&l_error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_FAILED,
465 "Failed to write to stdin of the process: %m");
466 bd_utils_report_finished (progress_id, l_error->message);
467 g_propagate_error (error, l_error);
468 /* would overwrite errno, need to close as a last step */
469 close (in_fd);
470 close (out_fd);
471 close (err_fd);
472 waitpid (pid, NULL, 0);
473 return FALSE;
474 }
475 close (in_fd);
476 g_warn_if_fail (len - num_written_total == 0);
477 }
478
479 stdout_data = g_string_new (NULL);
480 stdout_buffer = g_string_new (NULL);
481 stderr_data = g_string_new (NULL);
482 stderr_buffer = g_string_new (NULL);
483
484 fds[0].fd = out_fd;
485 fds[1].fd = err_fd;
486 fds[0].events = POLLIN | POLLHUP | POLLERR;
487 fds[1].events = POLLIN | POLLHUP | POLLERR;
488 while (! (out_done && err_done)) {
489 poll_status = poll (fds, 2, -1 /* timeout */);
490 g_warn_if_fail (poll_status != 0); /* no timeout specified, zero should never be returned */
491 if (poll_status < 0) {
492 if (errno == EAGAIN || errno == EINTR)
493 continue;
494 g_set_error (&l_error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_FAILED,
495 "Failed to poll output FDs: %m");
496 bd_utils_report_finished (progress_id, l_error->message);
497 g_propagate_error (error, l_error);
498 success = FALSE;
499 break;
500 }
501
502 if (!out_done) {
503 if (! _process_fd_event (out_fd, &fds[0], stdout_buffer, stdout_data, &stdout_buffer_pos, &out_done, progress_id, &completion, prog_extract, &l_error)) {
504 bd_utils_report_finished (progress_id, l_error->message);
505 g_propagate_error (error, l_error);
506 success = FALSE;
507 break;
508 }
509 }
510
511 if (!err_done) {
512 if (! _process_fd_event (err_fd, &fds[1], stderr_buffer, stderr_data, &stderr_buffer_pos, &err_done, progress_id, &completion, prog_extract, &l_error)) {
513 bd_utils_report_finished (progress_id, l_error->message);
514 g_propagate_error (error, l_error);
515 success = FALSE;
516 break;
517 }
518 }
519 }
520
521 g_string_free (stdout_buffer, TRUE);
522 g_string_free (stderr_buffer, TRUE);
523 close (out_fd);
524 close (err_fd);
525
526 child_ret = waitpid (pid, &status, 0);
527 if (success) {
528 if (child_ret > 0) {
529 if (WIFSIGNALED (status)) {
530 *proc_status = 128 + WTERMSIG (status);
531 g_set_error (&l_error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_FAILED,
532 "Process killed with a signal");
533 bd_utils_report_finished (progress_id, l_error->message);
534 g_propagate_error (error, l_error);
535 success = FALSE;
536 } else if (WIFEXITED (status) && WEXITSTATUS (status) != 0) {
537 *proc_status = WEXITSTATUS (status);
538 msg = stderr_data->len > 0 ? stderr_data->str : stdout_data->str;
539 g_set_error (&l_error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_FAILED,
540 "Process reported exit code %d: %s", *proc_status, msg);
541 bd_utils_report_finished (progress_id, l_error->message);
542 g_propagate_error (error, l_error);
543 success = FALSE;
544 } else {
545 *proc_status = WIFEXITED (status) ? WEXITSTATUS (status) : 0;
546 }
547 } else if (child_ret == -1) {
548 if (errno != ECHILD) {
549 errno = 0;
550 g_set_error_literal (&l_error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_FAILED,
551 "Failed to wait for the process");
552 bd_utils_report_finished (progress_id, l_error->message);
553 g_propagate_error (error, l_error);
554 success = FALSE;
555 } else {
556 /* no such process (the child exited before we tried to wait for it) */
557 errno = 0;
558 }
559 }
560 if (success)
561 bd_utils_report_finished (progress_id, "Completed");
562 }
563 log_out (task_id, stdout_data->str, stderr_data->str);
564 log_done (task_id, *proc_status);
565
566 if (success && stdout)
567 *stdout = g_string_free (stdout_data, FALSE);
568 else
569 g_string_free (stdout_data, TRUE);
570 if (success && stderr)
571 *stderr = g_string_free (stderr_data, FALSE);
572 else
573 g_string_free (stderr_data, TRUE);
574
575 return success;
576 }
577
578 /**
579 * bd_utils_exec_and_report_progress:
580 * @argv: (array zero-terminated=1): the argv array for the call
581 * @extra: (nullable) (array zero-terminated=1): extra arguments
582 * @prog_extract: (scope notified) (nullable): function for extracting progress information
583 * @proc_status: (out): place to store the process exit status
584 * @error: (out) (optional): place to store error (if any)
585 *
586 * Note that any NULL bytes read from standard output and standard error
587 * output are treated as separators similar to newlines and @prog_extract
588 * will be called with the respective chunk.
589 *
590 * Returns: whether the @argv was successfully executed (no error and exit code 0) or not
591 */
592 gboolean bd_utils_exec_and_report_progress (const gchar **argv, const BDExtraArg **extra, BDUtilsProgExtract prog_extract, gint *proc_status, GError **error) {
593 return _utils_exec_and_report_progress (argv, extra, prog_extract, NULL, proc_status, NULL, NULL, error);
594 }
595
596 /**
597 * bd_utils_exec_with_input:
598 * @argv: (array zero-terminated=1): the argv array for the call
599 * @input: (nullable): input for the executed program
600 * @extra: (nullable) (array zero-terminated=1): extra arguments
601 * @error: (out) (optional): place to store error (if any)
602 *
603 * Returns: whether the @argv was successfully executed (no error and exit code 0) or not
604 */
605 gboolean bd_utils_exec_with_input (const gchar **argv, const gchar *input, const BDExtraArg **extra, GError **error) {
606 gint status = 0;
607 /* just use the "stronger" function providing dumb progress reporting (just
608 'started' and 'finished') and throw away the returned status */
609 return _utils_exec_and_report_progress (argv, extra, NULL, input, &status, NULL, NULL, error);
610 }
611
612 /**
613 * bd_utils_exec_and_capture_output:
614 * @argv: (array zero-terminated=1): the argv array for the call
615 * @extra: (nullable) (array zero-terminated=1): extra arguments
616 * @output: (out): variable to store output to
617 * @error: (out) (optional): place to store error (if any)
618 *
619 * Note that any NULL bytes read from standard output and standard error
620 * output will be discarded.
621 *
622 * Returns: whether the @argv was successfully executed capturing the output or not
623 */
624 gboolean bd_utils_exec_and_capture_output (const gchar **argv, const BDExtraArg **extra, gchar **output, GError **error) {
625 gint status = 0;
626 gchar *stdout = NULL;
627 gchar *stderr = NULL;
628 gboolean ret = FALSE;
629
630 ret = _utils_exec_and_report_progress (argv, extra, NULL, NULL, &status, &stdout, &stderr, error);
631 if (!ret)
632 return ret;
633
634 if ((status != 0) || (g_strcmp0 ("", stdout) == 0)) {
635 if (status != 0)
636 g_set_error (error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_FAILED,
637 "Process reported exit code %d: %s%s", status,
638 stdout ? stdout : "",
639 stderr ? stderr : "");
640 else
641 g_set_error (error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_NOOUT,
642 "Process didn't provide any data on standard output. "
643 "Error output: %s", stderr ? stderr : "");
644 g_free (stderr);
645 g_free (stdout);
646 return FALSE;
647 } else {
648 *output = stdout;
649 g_free (stderr);
650 return TRUE;
651 }
652 }
653
654 /**
655 * bd_utils_version_cmp:
656 * @ver_string1: first version string
657 * @ver_string2: second version string
658 * @error: (out) (optional): place to store error (if any)
659 *
660 * Returns: -1, 0 or 1 if @ver_string1 is lower, the same or higher version as
661 * @ver_string2 respectively. If an error occurs, returns -2 and @error
662 * is set.
663 *
664 * **ONLY SUPPORTS VERSION STRINGS OF FORMAT `X[.Y[.Z[.Z2[.Z3...[-R]]]]]` where all components
665 * are natural numbers!**
666 */
667 gint bd_utils_version_cmp (const gchar *ver_string1, const gchar *ver_string2, GError **error) {
668 gchar **v1_fields = NULL;
669 gchar **v2_fields = NULL;
670 guint v1_fields_len = 0;
671 guint v2_fields_len = 0;
672 guint64 v1_value = 0;
673 guint64 v2_value = 0;
674 GRegex *regex = NULL;
675 gboolean success = FALSE;
676 gint ret = -2;
677
678 regex = g_regex_new ("^(\\d+)(\\.\\d+)*(-\\d)?$", 0, 0, error);
679 if (!regex) {
680 /* error is already populated */
681 return -2;
682 }
683
684 success = g_regex_match (regex, ver_string1, 0, NULL);
685 if (!success) {
686 g_set_error (error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_INVAL_VER,
687 "Invalid or unsupported version (1) format: %s", ver_string1);
688 g_regex_unref (regex);
689 return -2;
690 }
691 success = g_regex_match (regex, ver_string2, 0, NULL);
692 if (!success) {
693 g_set_error (error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_INVAL_VER,
694 "Invalid or unsupported version (2) format: %s", ver_string2);
695 g_regex_unref (regex);
696 return -2;
697 }
698 g_regex_unref (regex);
699
700 v1_fields = g_strsplit_set (ver_string1, ".-", 0);
701 v2_fields = g_strsplit_set (ver_string2, ".-", 0);
702 v1_fields_len = g_strv_length (v1_fields);
703 v2_fields_len = g_strv_length (v2_fields);
704
705 for (guint i=0; (i < v1_fields_len) && (i < v2_fields_len) && ret == -2; i++) {
706 v1_value = g_ascii_strtoull (v1_fields[i], NULL, 0);
707 v2_value = g_ascii_strtoull (v2_fields[i], NULL, 0);
708 if (v1_value < v2_value)
709 ret = -1;
710 else if (v1_value > v2_value)
711 ret = 1;
712 }
713
714 if (ret == -2) {
715 if (v1_fields_len < v2_fields_len)
716 ret = -1;
717 else if (v1_fields_len > v2_fields_len)
718 ret = 1;
719 else
720 ret = 0;
721 }
722
723 g_strfreev (v1_fields);
724 g_strfreev (v2_fields);
725
726 return ret;
727 }
728
729 /**
730 * bd_utils_check_util_version:
731 * @util: name of the utility to check
732 * @version: (nullable): minimum required version of the utility or %NULL
733 * if no version is required
734 * @version_arg: (nullable): argument to use with the @util to get version
735 * info or %NULL to use "--version"
736 * @version_regexp: (nullable): regexp to extract version from the version
737 * info or %NULL if only version is printed by "$ @util @version_arg"
738 * @error: (out) (optional): place to store error (if any)
739 *
740 * Note: Both supplied @version and parsed result using @version_regexp must be in format
741 * `X[.Y[.Z[.Z2[.Z3...[-R]]]]]` where all components are natural numbers, see
742 * %bd_utils_version_cmp for details.
743 *
744 * Returns: whether the @util is available in a version >= @version or not
745 * (@error is set in such case).
746 */
747 gboolean bd_utils_check_util_version (const gchar *util, const gchar *version, const gchar *version_arg, const gchar *version_regexp, GError **error) {
748 gchar *util_path = NULL;
749 const gchar *argv[] = {util, version_arg ? version_arg : "--version", NULL};
750 gchar *output = NULL;
751 gboolean succ = FALSE;
752 GRegex *regex = NULL;
753 GMatchInfo *match_info = NULL;
754 gchar *version_str = NULL;
755 GError *l_error = NULL;
756
757 util_path = g_find_program_in_path (util);
758 if (!util_path) {
759 g_set_error (error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_UTIL_UNAVAILABLE,
760 "The '%s' utility is not available", util);
761 return FALSE;
762 }
763 g_free (util_path);
764
765 if (!version)
766 /* nothing more to do here */
767 return TRUE;
768
769 succ = bd_utils_exec_and_capture_output (argv, NULL, &output, &l_error);
770 if (!succ) {
771 /* if we got nothing on STDOUT, try using STDERR data from error message */
772 if (g_error_matches (l_error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_NOOUT)) {
773 output = g_strdup (l_error->message);
774 g_clear_error (&l_error);
775 } else if (g_error_matches (l_error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_FAILED)) {
776 /* exit status != 0, try using the output anyway */
777 output = g_strdup (l_error->message);
778 g_clear_error (&l_error);
779 }
780 }
781
782 if (version_regexp) {
783 regex = g_regex_new (version_regexp, 0, 0, error);
784 if (!regex) {
785 g_free (output);
786 /* error is already populated */
787 return FALSE;
788 }
789
790 succ = g_regex_match (regex, output, 0, &match_info);
791 if (!succ) {
792 g_set_error (error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_UTIL_UNKNOWN_VER,
793 "Failed to determine %s's version from: %s", util, output);
794 g_free (output);
795 g_regex_unref (regex);
796 g_match_info_free (match_info);
797 return FALSE;
798 }
799 g_regex_unref (regex);
800
801 version_str = g_match_info_fetch (match_info, 1);
802 g_match_info_free (match_info);
803 }
804 else
805 version_str = g_strstrip (g_strdup (output));
806
807 if (!version_str || (g_strcmp0 (version_str, "") == 0)) {
808 g_set_error (error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_UTIL_UNKNOWN_VER,
809 "Failed to determine %s's version from: %s", util, output);
810 g_free (version_str);
811 g_free (output);
812 return FALSE;
813 }
814
815 g_free (output);
816
817 if (bd_utils_version_cmp (version_str, version, &l_error) < 0) {
818 /* smaller version or error */
819 if (!l_error)
820 g_set_error (error, BD_UTILS_EXEC_ERROR, BD_UTILS_EXEC_ERROR_UTIL_LOW_VER,
821 "Too low version of %s: %s. At least %s required.",
822 util, version_str, version);
823 else
824 g_propagate_error (error, l_error);
825 g_free (version_str);
826 return FALSE;
827 }
828
829 g_free (version_str);
830 return TRUE;
831 }
832
833 /**
834 * bd_utils_init_prog_reporting:
835 * @new_prog_func: (nullable) (scope notified): progress reporting function to
836 * use or %NULL to reset to default
837 * @error: (out) (optional): place to store error (if any)
838 *
839 * Returns: whether progress reporting was successfully initialized or not
840 */
841 gboolean bd_utils_init_prog_reporting (BDUtilsProgFunc new_prog_func, GError **error G_GNUC_UNUSED) {
842 /* XXX: the error attribute will likely be used in the future when this
843 function gets more complicated */
844
845 prog_func = new_prog_func;
846
847 return TRUE;
848 }
849
850 /**
851 * bd_utils_init_prog_reporting_thread:
852 * @new_prog_func: (nullable) (scope notified): progress reporting function to
853 * use on current thread or %NULL
854 * to reset to default or global
855 * @error: (out) (optional): place to store error (if any)
856 *
857 * Returns: whether progress reporting was successfully initialized or not
858 */
859 gboolean bd_utils_init_prog_reporting_thread (BDUtilsProgFunc new_prog_func, GError **error G_GNUC_UNUSED) {
860 /* XXX: the error attribute will likely be used in the future when this
861 function gets more complicated */
862
863 thread_prog_func = new_prog_func;
864
865 return TRUE;
866 }
867
868 static void thread_progress_muted (guint64 task_id G_GNUC_UNUSED, BDUtilsProgStatus status G_GNUC_UNUSED,
869 guint8 completion G_GNUC_UNUSED, gchar *msg G_GNUC_UNUSED) {
870 /* This function serves as a special value for the progress reporting
871 * function to detect that nothing is done here. If clients use their own
872 * empty function then bd_utils_prog_reporting_initialized will return TRUE
873 * but with this function here it returns FALSE.
874 */
875 }
876
877 /**
878 * bd_utils_mute_prog_reporting_thread:
879 * @error: (out) (optional): place to store error (if any)
880 *
881 * Returns: whether progress reporting for the current thread was successfully
882 * muted (deinitialized even in presence of a global reporting function) or not
883 */
884 gboolean bd_utils_mute_prog_reporting_thread (GError **error G_GNUC_UNUSED) {
885 /* XXX: the error attribute will likely be used in the future when this
886 function gets more complicated */
887
888 thread_prog_func = thread_progress_muted;
889
890 return TRUE;
891 }
892
893 /**
894 * bd_utils_prog_reporting_initialized:
895 *
896 * Returns: TRUE if progress reporting has been initialized, i.e. a reporting
897 * function was set up with either bd_utils_init_prog_reporting or
898 * bd_utils_init_prog_reporting_thread (takes precedence). FALSE if
899 * bd_utils_mute_prog_reporting_thread was used to mute the thread.
900 */
901 gboolean bd_utils_prog_reporting_initialized (void) {
902 return (thread_prog_func != NULL || prog_func != NULL) && thread_prog_func != thread_progress_muted;
903 }
904
905 /**
906 * bd_utils_report_started:
907 * @msg: message describing the started task/action
908 *
909 * Returns: ID of the started task/action
910 */
911 guint64 bd_utils_report_started (const gchar *msg) {
912 guint64 task_id = 0;
913 BDUtilsProgFunc current_prog_func;
914
915 current_prog_func = thread_prog_func != NULL ? thread_prog_func : prog_func;
916
917 g_mutex_lock (&task_id_counter_lock);
918 task_id_counter++;
919 task_id = task_id_counter;
920 g_mutex_unlock (&task_id_counter_lock);
921
922 if (current_prog_func)
923 current_prog_func (task_id, BD_UTILS_PROG_STARTED, 0, (gchar *)msg);
924 return task_id;
925 }
926
927 /**
928 * bd_utils_report_progress:
929 * @task_id: ID of the task/action
930 * @completion: percentage of completion
931 * @msg: message describing the status of the task/action
932 */
933 void bd_utils_report_progress (guint64 task_id, guint64 completion, const gchar *msg) {
934 BDUtilsProgFunc current_prog_func;
935
936 current_prog_func = thread_prog_func != NULL ? thread_prog_func : prog_func;
937 if (current_prog_func)
938 current_prog_func (task_id, BD_UTILS_PROG_PROGRESS, completion, (gchar *)msg);
939 }
940
941 /**
942 * bd_utils_report_finished:
943 * @task_id: ID of the task/action
944 * @msg: message describing the status of the task/action
945 */
946 void bd_utils_report_finished (guint64 task_id, const gchar *msg) {
947 BDUtilsProgFunc current_prog_func;
948
949 current_prog_func = thread_prog_func != NULL ? thread_prog_func : prog_func;
950 if (current_prog_func)
951 current_prog_func (task_id, BD_UTILS_PROG_FINISHED, 100, (gchar *)msg);
952 }
953
954 /**
955 * bd_utils_echo_str_to_file:
956 * @str: string to write to @file_path
957 * @file_path: path to file
958 * @error: (out) (optional): place to store error (if any)
959 *
960 * Returns: whether the @str was successfully written to @file_path
961 * or not.
962 */
963 gboolean bd_utils_echo_str_to_file (const gchar *str, const gchar *file_path, GError **error) {
964 GIOChannel *out_file = NULL;
965 gsize bytes_written = 0;
966
967 out_file = g_io_channel_new_file (file_path, "w", error);
968 if (!out_file) {
969 g_prefix_error (error, "Failed to write '%s' to file '%s': ", str, file_path);
970 return FALSE;
971 }
972 if (g_io_channel_write_chars (out_file, str, -1, &bytes_written, error) != G_IO_STATUS_NORMAL) {
973 g_prefix_error (error, "Failed to write '%s' to file '%s': ", str, file_path);
974 g_io_channel_unref (out_file);
975 return FALSE;
976 }
977 if (g_io_channel_shutdown (out_file, TRUE, error) != G_IO_STATUS_NORMAL) {
978 g_prefix_error (error, "Failed to flush and close the file '%s': ", file_path);
979 g_io_channel_unref (out_file);
980 return FALSE;
981 }
982 g_io_channel_unref (out_file);
983 return TRUE;
984 }