Codebase list realmd / upstream/0.6 service / realm-command.c
upstream/0.6

Tree @upstream/0.6 (Download .tar.gz)

realm-command.c @upstream/0.6raw · history · blame

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
/*
 * Copyright (C) 2011 Collabora Ltd.
 * Copyright (C) 2012 Red Hat Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; either version 2.1 of the licence or (at
 * your option) any later version.
 *
 * See the included COPYING file for more information.
 *
 * Author: Stef Walter <stefw@collabora.co.uk>
 */

#include "config.h"

#include "realm-daemon.h"
#define DEBUG_FLAG REALM_DEBUG_PROCESS
#include "realm-debug.h"
#include "realm-command.h"
#include "realm-diagnostics.h"
#include "realm-settings.h"

#include <glib/gi18n-lib.h>

#include <sys/wait.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

enum {
	FD_INPUT,
	FD_OUTPUT,
	FD_ERROR,
	NUM_FDS
};


typedef struct {
	GString *input;
	GString *output;
	guint source_sig;
	gint exit_code;
	gboolean cancelled;
	GDBusMethodInvocation *invocation;
} CommandClosure;

typedef struct {
	GSource source;
	GPollFD polls[NUM_FDS];         /* The various fd's we're listening to */

	GPid child_pid;
	guint child_sig;

	GSimpleAsyncResult *res;
	CommandClosure *command;

	GCancellable *cancellable;
	guint cancel_sig;
} ProcessSource;

static void
command_closure_free (gpointer data)
{
	CommandClosure *command = data;
	g_string_free (command->output, TRUE);
	g_assert (command->source_sig == 0);
	g_slice_free (CommandClosure, command);
}

static void
complete_source_is_done (ProcessSource *process_source)
{
	realm_debug ("all fds closed and process exited, completing");

	g_assert (process_source->child_sig == 0);

	if (process_source->cancel_sig) {
		g_signal_handler_disconnect (process_source->cancellable, process_source->cancel_sig);
		process_source->cancel_sig = 0;
	}

	g_clear_object (&process_source->cancellable);
	g_simple_async_result_complete (process_source->res);

	/* All done, the source can go away now */
	g_source_unref ((GSource*)process_source);
}

static void
close_fd (int *fd)
{
	g_assert (fd);
	if (*fd >= 0) {
		realm_debug ("closing fd: %d", *fd);
		close (*fd);
	}
	*fd = -1;
}

static void
close_poll (GSource *source, GPollFD *poll)
{
	g_source_remove_poll (source, poll);
	close_fd (&poll->fd);
	poll->revents = 0;
}

static gboolean
unused_callback (gpointer data)
{
	/* Never called */
	g_assert_not_reached ();
	return FALSE;
}

static gboolean
on_process_source_prepare (GSource *source, gint *timeout_)
{
	ProcessSource *process_source = (ProcessSource*)source;
	gint i;

	for (i = 0; i < NUM_FDS; ++i) {
		if (process_source->polls[i].fd >= 0)
			return FALSE;
	}

	/* If none of the FDs are valid, then process immediately */
	return TRUE;
}

static gboolean
on_process_source_check (GSource *source)
{
	ProcessSource *process_source = (ProcessSource*)source;
	gint i;

	for (i = 0; i < NUM_FDS; ++i) {
		if (process_source->polls[i].fd >= 0 && process_source->polls[i].revents != 0)
			return TRUE;
	}
	return FALSE;
}

static void
on_process_source_finalize (GSource *source)
{
	ProcessSource *process_source = (ProcessSource*)source;
	gint i;

	g_assert (process_source->cancellable == NULL);
	g_assert (process_source->cancel_sig == 0);

	for (i = 0; i < NUM_FDS; ++i)
		close_fd (&process_source->polls[i].fd);

	g_assert (!process_source->child_pid);
	g_assert (!process_source->child_sig);
}

static gboolean
read_output (int fd,
             GString *buffer)
{
	gchar block[1024];
	gssize result;

	g_return_val_if_fail (fd >= 0, FALSE);

	do {
		result = read (fd, block, sizeof (block));
		if (result < 0) {
			if (errno == EINTR || errno == EAGAIN)
				continue;
			return FALSE;
		} else {
			g_string_append_len (buffer, block, result);
		}
	} while (result == sizeof (block));

	return TRUE;
}

static gboolean
write_input (int fd,
             GString *buffer)
{
	gssize result;

	g_return_val_if_fail (fd >= 0, FALSE);

	for (;;) {
		result = write (fd, buffer->str, buffer->len);
		if (result < 0) {
			if (errno == EINTR || errno == EAGAIN)
				continue;
			return FALSE;
		} else {
			g_string_erase (buffer, 0, result);
			return TRUE;
		}
	}
}

static gboolean
on_process_source_input (CommandClosure *command,
                         ProcessSource *process_source,
                         gint fd)
{
	if (command->input == NULL)
		return FALSE;
	if (!write_input (fd, command->input)) {
		g_warning ("couldn't write output data to process");
		return FALSE;
	}

	return TRUE;
}

static gboolean
on_process_source_output (CommandClosure *command,
                          ProcessSource *process_source,
                          gint fd)
{
	if (!read_output (fd, command->output)) {
		g_warning ("couldn't read output data from process");
		return FALSE;
	}

	return TRUE;
}

static gboolean
on_process_source_error (CommandClosure *command,
                         ProcessSource *process_source,
                         gint fd)
{
	if (!read_output (fd, command->output)) {
		g_warning ("couldn't read error data from process");
		return FALSE;
	}

	return TRUE;
}

static gboolean
on_process_source_dispatch (GSource *source,
                            GSourceFunc unused,
                            gpointer user_data)
{
	ProcessSource *process_source = (ProcessSource*)source;
	CommandClosure *command = process_source->command;
	GPollFD *poll;
	guint i;

	/* Standard input, no support yet */
	poll = &process_source->polls[FD_INPUT];
	if (poll->fd >= 0) {
		if (poll->revents & G_IO_OUT)
			if (!on_process_source_input (command, process_source, poll->fd))
				poll->revents |= G_IO_HUP;
		if (poll->revents & G_IO_HUP)
			close_poll (source, poll);
		poll->revents = 0;
	}

	/* Standard output */
	poll = &process_source->polls[FD_OUTPUT];
	if (poll->fd >= 0) {
		if (poll->revents & G_IO_IN)
			if (!on_process_source_output (command, process_source, poll->fd))
				poll->revents |= G_IO_HUP;
		if (poll->revents & G_IO_HUP)
			close_poll (source, poll);
		poll->revents = 0;
	}

	/* Standard error */
	poll = &process_source->polls[FD_ERROR];
	if (poll->fd >= 0) {
		if (poll->revents & G_IO_IN)
			if (!on_process_source_error (command, process_source, poll->fd))
				poll->revents |= G_IO_HUP;
		if (poll->revents & G_IO_HUP)
			close_poll (source, poll);
		poll->revents = 0;
	}

	for (i = 0; i < NUM_FDS; ++i) {
		if (process_source->polls[i].fd >= 0)
			return TRUE;
	}

	/* Because we return below */
	command->source_sig = 0;

	if (!process_source->child_pid)
		complete_source_is_done (process_source);

	return FALSE; /* Disconnect this source */
}

static GSourceFuncs process_source_funcs = {
	on_process_source_prepare,
	on_process_source_check,
	on_process_source_dispatch,
	on_process_source_finalize,
};

static void
on_unix_process_child_exited (GPid pid,
                              gint status,
                              gpointer user_data)
{
	ProcessSource *process_source = user_data;
	CommandClosure *command = process_source->command;
	gint code;
	guint i;

	realm_debug ("process exited: %d", (int)pid);

	g_spawn_close_pid (process_source->child_pid);
	process_source->child_pid = 0;
	process_source->child_sig = 0;

	if (WIFEXITED (status)) {
		command->exit_code = WEXITSTATUS (status);

	} else if (WIFSIGNALED (status)) {
		code = WTERMSIG (status);
		/* Ignore cases where we've signaled the process because we were cancelled */
		if (!command->cancelled)
			g_simple_async_result_set_error (process_source->res, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
			                                 _("Process was terminated with signal: %d"), code);
	}

	for (i = 0; i < NUM_FDS; ++i) {
		if (process_source->polls[i].fd >= 0)
			return;
	}

	complete_source_is_done (process_source);
}

static void
on_unix_process_child_setup (gpointer user_data)
{
	int *child_fds = user_data;
	long val;
	guint i;

	/*
	 * Clear close-on-exec flag for these file descriptors, so that
	 * gnupg can write to them
	 */

	for (i = 0; i < NUM_FDS; i++) {
		if (child_fds[i] >= 0) {
			val = fcntl (child_fds[i], F_GETFD);
			fcntl (child_fds[i], F_SETFD, val & ~FD_CLOEXEC);
		}
	}
}

static void
on_cancellable_cancelled (GCancellable *cancellable,
                          gpointer user_data)
{
	ProcessSource *process_source = user_data;

	realm_debug ("process cancelled");

	/* Set an error, which is respected when this actually completes. */
	g_simple_async_result_set_error (process_source->res, G_IO_ERROR, G_IO_ERROR_CANCELLED,
	                                 _("The operation was cancelled"));
	process_source->command->cancelled = TRUE;

	/* Try and kill the child process */
	if (process_source->child_pid) {
		realm_debug ("sending term signal to process: %d",
		            (int)process_source->child_pid);
		kill (process_source->child_pid, SIGTERM);
	}
}

void
realm_command_run_async (gchar **environ,
                         GDBusMethodInvocation *invocation,
                         GCancellable *cancellable,
                         GAsyncReadyCallback callback,
                         gpointer user_data,
                         const gchar *name_or_path,
                         ...)
{
	GPtrArray *array;
	va_list va;
	gchar *arg;

	g_return_if_fail (name_or_path != NULL);
	g_return_if_fail (invocation == NULL || G_IS_DBUS_METHOD_INVOCATION (invocation));
	g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));

	array = g_ptr_array_new ();
	g_ptr_array_add (array, (gchar *)name_or_path);

	va_start (va, name_or_path);
	do {
		arg = va_arg (va, gchar *);
		g_ptr_array_add (array, arg);
	} while (arg != NULL);
	va_end (va);

	realm_command_runv_async ((gchar **)array->pdata, environ, invocation,
	                       cancellable, callback, user_data);
}

void
realm_command_runv_async (gchar **argv,
                          gchar **environ,
                          GDBusMethodInvocation *invocation,
                          GCancellable *cancellable,
                          GAsyncReadyCallback callback,
                          gpointer user_data)
{
	GSimpleAsyncResult *res;
	CommandClosure *command;
	GError *error = NULL;
	int child_fds[NUM_FDS];
	int output_fd = -1;
	int error_fd = -1;
	int input_fd = -1;
	ProcessSource *process_source;
	GSource *source;
	GPid pid;
	guint i;

	g_return_if_fail (argv != NULL);
	g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
	g_return_if_fail (invocation == NULL || G_IS_DBUS_METHOD_INVOCATION (invocation));

	for (i = 0; i < NUM_FDS; i++)
		child_fds[i] = -1;

	/* TODO: Figure out if it's a name, and lookup the path */

	/* Spawn/child will close all other attributes, besides thesthose in child_fds */
	child_fds[FD_INPUT] = 0;
	child_fds[FD_OUTPUT] = 1;
	child_fds[FD_ERROR] = 2;

	if (realm_debugging) {
		gchar *command = g_strjoinv (" ", argv);
		realm_debug ("running command: %s", command);
		realm_diagnostics_info (invocation, "%s", command);
		g_free (command);

		if (environ) {
			gchar *environment = g_strjoinv (", ", (gchar**)environ);
			realm_debug ("process environment: %s", environment);
			g_free (environment);
		}
	}

	g_spawn_async_with_pipes (NULL, argv, environ,
	                          G_SPAWN_DO_NOT_REAP_CHILD,
	                          on_unix_process_child_setup, child_fds,
	                          &pid, &input_fd, &output_fd, &error_fd, &error);

	res = g_simple_async_result_new (NULL, callback, user_data, realm_command_runv_async);
	command = g_slice_new0 (CommandClosure);
	command->input = NULL;
	command->output = g_string_sized_new (128);
	command->invocation = invocation ? g_object_ref (invocation) : NULL;
	g_simple_async_result_set_op_res_gpointer (res, command, command_closure_free);

	if (error) {
		g_simple_async_result_take_error (res, error);
		g_simple_async_result_complete_in_idle (res);
		g_object_unref (res);
		return;
	}

	realm_debug ("process started: %d", (int)pid);

	source = g_source_new (&process_source_funcs, sizeof (ProcessSource));

	/* Initialize the source */
	process_source = (ProcessSource *)source;
	for (i = 0; i < NUM_FDS; i++)
		process_source->polls[i].fd = -1;
	process_source->res = g_object_ref (res);
	process_source->command = command;
	process_source->child_pid = pid;

	process_source->polls[FD_INPUT].fd = input_fd;
	if (input_fd >= 0) {
		process_source->polls[FD_INPUT].events = G_IO_HUP | G_IO_OUT;
		g_source_add_poll (source, &process_source->polls[FD_INPUT]);
	}
	process_source->polls[FD_OUTPUT].fd = output_fd;
	if (output_fd >= 0) {
		process_source->polls[FD_OUTPUT].events = G_IO_HUP | G_IO_IN;
		g_source_add_poll (source, &process_source->polls[FD_OUTPUT]);
	}
	process_source->polls[FD_ERROR].fd = error_fd;
	if (error_fd >= 0) {
		process_source->polls[FD_ERROR].events = G_IO_HUP | G_IO_IN;
		g_source_add_poll (source, &process_source->polls[FD_ERROR]);
	}

	if (cancellable) {
		process_source->cancellable = g_object_ref (cancellable);
		process_source->cancel_sig = g_cancellable_connect (cancellable,
		                                                    G_CALLBACK (on_cancellable_cancelled),
		                                                    g_source_ref (source),
		                                                    (GDestroyNotify)g_source_unref);
	}

	g_assert (command->source_sig == 0);
	g_source_set_callback (source, unused_callback, NULL, NULL);
	command->source_sig = g_source_attach (source, g_main_context_default ());

	/* This assumes the outstanding reference to source */
	g_assert (process_source->child_sig == 0);
	process_source->child_sig = g_child_watch_add_full (G_PRIORITY_DEFAULT, pid,
	                                                    on_unix_process_child_exited,
	                                                    g_source_ref (source),
	                                                    (GDestroyNotify)g_source_unref);

	/* source is unreffed in complete_if_source_is_done() */
}

static gboolean
is_only_whitespace (const gchar *string)
{
	while (*string != '\0') {
		if (!g_ascii_isspace (*string))
			return FALSE;
		string++;
	}

	return TRUE;
}

void
realm_command_run_known_async (const gchar *known_command,
                               gchar **environ,
                               GDBusMethodInvocation *invocation,
                               GCancellable *cancellable,
                               GAsyncReadyCallback callback,
                               gpointer user_data)
{
	const gchar *command_line;
	GError *error = NULL;
	gchar **argv;
	gint unused;

	const gchar *empty_argv[] = {
		"/bin/true",
		"empty-configured-command",
		known_command,
		NULL,
	};

	const gchar *invalid_argv[] = {
		"/bin/false",
		"invalid-configured-command",
		known_command,
		NULL
	};

	g_return_if_fail (known_command != NULL);
	g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
	g_return_if_fail (invocation == NULL || G_IS_DBUS_METHOD_INVOCATION (invocation));

	command_line = realm_settings_value ("commands", known_command);
	if (command_line == NULL) {
		g_warning ("Couldn't find the configured string commands/%s", known_command);
		argv = g_strdupv ((gchar **)invalid_argv);

	} else if (is_only_whitespace (command_line)) {
		argv = g_strdupv ((gchar **)empty_argv);

	} else if (!g_shell_parse_argv (command_line, &unused, &argv, &error)) {
		g_warning ("Couldn't parse the command line: %s: %s", command_line, error->message);
		g_error_free (error);
		argv = g_strdupv ((gchar **)invalid_argv);
	}

	realm_command_runv_async (argv, environ, invocation, cancellable, callback, user_data);
	g_strfreev (argv);
}

gint
realm_command_run_finish (GAsyncResult *result,
                          GString **output,
                          GError **error)
{
	GSimpleAsyncResult *res;
	CommandClosure *command;

	g_return_val_if_fail (error == NULL || *error == NULL, -1);
	g_return_val_if_fail (g_simple_async_result_is_valid (result, NULL,
	                      realm_command_runv_async), -1);

	res = G_SIMPLE_ASYNC_RESULT (result);

	if (g_simple_async_result_propagate_error (res, error))
		return -1;

	command = g_simple_async_result_get_op_res_gpointer (res);
	if (command->output->len)
		realm_diagnostics_info_data (command->invocation,
		                             command->output->str,
		                             command->output->len);
	if (output) {
		*output = command->output;
		command->output = NULL;
	}

	return command->exit_code;
}