Debian Codegraph @

src/sensors/argyll/cd-spawn.c

raw
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
2 *
3 * Copyright (C) 2007-2012 Richard Hughes <[email protected]>
4 *
5 * Licensed under the GNU General Public License Version 2
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 */
21
22 #include "config.h"
23
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <time.h>
27 #include <errno.h>
28 #include <signal.h>
29
30 #include <string.h>
31 #include <sys/time.h>
32 #include <sys/types.h>
33 #include <sys/resource.h>
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif /* HAVE_UNISTD_H */
37
38 #include <sys/wait.h>
39 #include <fcntl.h>
40
41 #include <glib/gi18n.h>
42
43 #include "cd-spawn.h"
44
45 static void cd_spawn_finalize (GObject *object);
46
47 #define CD_SPAWN_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), CD_TYPE_SPAWN, CdSpawnPrivate))
48 #define CD_SPAWN_POLL_DELAY 50 /* ms */
49 #define CD_SPAWN_SIGKILL_DELAY 2500 /* ms */
50
51 struct CdSpawnPrivate
52 {
53 pid_t child_pid;
54 gint stdin_fd;
55 gint stdout_fd;
56 gint stderr_fd;
57 guint poll_id;
58 guint kill_id;
59 gboolean finished;
60 gboolean allow_sigkill;
61 CdSpawnExitType exit;
62 GString *stdout_buf;
63 GString *stderr_buf;
64 };
65
66 enum {
67 SIGNAL_EXIT,
68 SIGNAL_STDOUT,
69 SIGNAL_STDERR,
70 SIGNAL_LAST
71 };
72
73 static guint signals [SIGNAL_LAST] = { 0 };
74
75 G_DEFINE_TYPE (CdSpawn, cd_spawn, G_TYPE_OBJECT)
76
77 static gboolean
78 cd_spawn_read_fd_into_buffer (gint fd, GString *string)
79 {
80 gint bytes_read;
81 gchar buffer[BUFSIZ];
82
83 /* ITS4: ignore, we manually NULL terminate and GString cannot overflow */
84 while ((bytes_read = read (fd, buffer, BUFSIZ-1)) > 0) {
85 buffer[bytes_read] = '\0';
86 g_string_append (string, buffer);
87 }
88
89 return TRUE;
90 }
91
92 static gboolean
93 cd_spawn_emit_whole_lines (CdSpawn *spawn, GString *string)
94 {
95 guint i;
96 guint size;
97 guint bytes_processed;
98 g_auto(GStrv) lines = NULL;
99
100 /* if nothing then don't emit */
101 if (string->len == 0)
102 return FALSE;
103
104 /* split into lines - the last line may be incomplete */
105 lines = g_strsplit (string->str, "\n", 0);
106 if (lines == NULL)
107 return FALSE;
108
109 /* find size */
110 size = g_strv_length (lines);
111
112 bytes_processed = 0;
113 /* we only emit n-1 strings */
114 for (i = 0; i < (size-1); i++) {
115 g_signal_emit (spawn, signals [SIGNAL_STDOUT], 0, lines[i]);
116 /* ITS4: ignore, g_strsplit always NULL terminates */
117 bytes_processed += strlen (lines[i]) + 1;
118 }
119
120 /* remove the text we've processed */
121 g_string_erase (string, 0, bytes_processed);
122 return TRUE;
123 }
124
125 static const gchar *
126 cd_spawn_exit_type_enum_to_string (CdSpawnExitType type)
127 {
128 if (type == CD_SPAWN_EXIT_TYPE_SUCCESS)
129 return "success";
130 if (type == CD_SPAWN_EXIT_TYPE_FAILED)
131 return "failed";
132 if (type == CD_SPAWN_EXIT_TYPE_SIGQUIT)
133 return "sigquit";
134 if (type == CD_SPAWN_EXIT_TYPE_SIGKILL)
135 return "sigkill";
136 return "unknown";
137 }
138
139 static gboolean
140 cd_spawn_check_child (CdSpawn *spawn)
141 {
142 pid_t pid;
143 int status;
144 gint retval;
145 static guint limit_printing = 0;
146
147 /* this shouldn't happen */
148 if (spawn->priv->finished) {
149 g_warning ("finished twice!");
150 return G_SOURCE_REMOVE;
151 }
152
153 cd_spawn_read_fd_into_buffer (spawn->priv->stdout_fd, spawn->priv->stdout_buf);
154 cd_spawn_read_fd_into_buffer (spawn->priv->stderr_fd, spawn->priv->stderr_buf);
155
156 /* emit all lines on standard out in one callback, as it's all probably
157 * related to the error that just happened */
158 if (spawn->priv->stderr_buf->len != 0) {
159 g_signal_emit (spawn, signals [SIGNAL_STDERR], 0, spawn->priv->stderr_buf->str);
160 g_string_set_size (spawn->priv->stderr_buf, 0);
161 }
162
163 /* all usual output goes on standard out, only bad libraries bitch to stderr */
164 cd_spawn_emit_whole_lines (spawn, spawn->priv->stdout_buf);
165
166 /* Only print one in twenty times to avoid filling the screen */
167 if (limit_printing++ % 20 == 0)
168 g_debug ("polling child_pid=%ld (1/20)", (long)spawn->priv->child_pid);
169
170 /* check if the child exited */
171 pid = waitpid (spawn->priv->child_pid, &status, WNOHANG);
172 if (pid == -1) {
173 g_warning ("failed to get the child PID data for %ld", (long)spawn->priv->child_pid);
174 return G_SOURCE_CONTINUE;
175 }
176 if (pid == 0) {
177 /* process still exist, but has not changed state */
178 return G_SOURCE_CONTINUE;
179 }
180 if (pid != spawn->priv->child_pid) {
181 g_warning ("some other process id was returned: got %ld and wanted %ld",
182 (long)pid, (long)spawn->priv->child_pid);
183 return G_SOURCE_CONTINUE;
184 }
185
186 /* disconnect the poll as there will be no more updates */
187 if (spawn->priv->poll_id > 0) {
188 g_source_remove (spawn->priv->poll_id);
189 spawn->priv->poll_id = 0;
190 }
191
192 /* child exited, close resources */
193 close (spawn->priv->stdin_fd);
194 close (spawn->priv->stdout_fd);
195 close (spawn->priv->stderr_fd);
196 spawn->priv->stdin_fd = -1;
197 spawn->priv->stdout_fd = -1;
198 spawn->priv->stderr_fd = -1;
199 spawn->priv->child_pid = -1;
200
201 /* use this to detect SIGKILL and SIGQUIT */
202 if (WIFSIGNALED (status)) {
203 retval = WTERMSIG (status);
204 if (retval == SIGQUIT) {
205 g_debug ("the child process was terminated by SIGQUIT");
206 spawn->priv->exit = CD_SPAWN_EXIT_TYPE_SIGQUIT;
207 } else if (retval == SIGKILL) {
208 g_debug ("the child process was terminated by SIGKILL");
209 spawn->priv->exit = CD_SPAWN_EXIT_TYPE_SIGKILL;
210 } else {
211 g_warning ("the child process was terminated by signal %i", WTERMSIG (status));
212 spawn->priv->exit = CD_SPAWN_EXIT_TYPE_SIGKILL;
213 }
214 } else {
215 /* check we are dead and buried */
216 if (!WIFEXITED (status)) {
217 g_warning ("the process did not exit, but waitpid() returned!");
218 return G_SOURCE_CONTINUE;
219 }
220
221 /* get the exit code */
222 retval = WEXITSTATUS (status);
223 if (retval == 0) {
224 g_debug ("the child exited with success");
225 if (spawn->priv->exit == CD_SPAWN_EXIT_TYPE_UNKNOWN)
226 spawn->priv->exit = CD_SPAWN_EXIT_TYPE_SUCCESS;
227 } else if (retval == 254) {
228 g_debug ("backend was exited rather than finished");
229 spawn->priv->exit = CD_SPAWN_EXIT_TYPE_FAILED;
230 } else {
231 g_warning ("the child exited with return code %i", retval);
232 if (spawn->priv->exit == CD_SPAWN_EXIT_TYPE_UNKNOWN)
233 spawn->priv->exit = CD_SPAWN_EXIT_TYPE_FAILED;
234 }
235 }
236
237 /* officially done, although no signal yet */
238 spawn->priv->finished = TRUE;
239
240 /* if we are trying to kill this process, cancel the SIGKILL */
241 if (spawn->priv->kill_id != 0) {
242 g_source_remove (spawn->priv->kill_id);
243 spawn->priv->kill_id = 0;
244 }
245
246 /* don't emit if we just closed an invalid dispatcher */
247 g_debug ("emitting exit %s", cd_spawn_exit_type_enum_to_string (spawn->priv->exit));
248 g_signal_emit (spawn, signals [SIGNAL_EXIT], 0, spawn->priv->exit);
249 return G_SOURCE_REMOVE;
250 }
251
252 static gboolean
253 cd_spawn_sigkill_cb (CdSpawn *spawn)
254 {
255 gint retval;
256
257 /* check if process has already gone */
258 if (spawn->priv->finished) {
259 g_debug ("already finished, ignoring");
260 return G_SOURCE_REMOVE;
261 }
262
263 /* set this in case the script catches the signal and exits properly */
264 spawn->priv->exit = CD_SPAWN_EXIT_TYPE_SIGKILL;
265
266 g_debug ("sending SIGKILL %ld", (long)spawn->priv->child_pid);
267 retval = kill (spawn->priv->child_pid, SIGKILL);
268 if (retval == EINVAL) {
269 g_warning ("The signum argument is an invalid or unsupported number");
270 return G_SOURCE_REMOVE;
271 }
272 if (retval == EPERM) {
273 g_warning ("You do not have the privilege to send a signal to the process");
274 return G_SOURCE_REMOVE;
275 }
276
277 /* never repeat */
278 return G_SOURCE_REMOVE;
279 }
280
281 /**
282 * cd_spawn_is_running:
283 *
284 * Is this instance controlling a script?
285 *
286 **/
287 gboolean
288 cd_spawn_is_running (CdSpawn *spawn)
289 {
290 return (spawn->priv->child_pid != -1);
291 }
292
293 /**
294 * cd_spawn_kill:
295 *
296 * We send SIGQUIT and after a few ms SIGKILL (if allowed)
297 *
298 * IMPORTANT: This is not a synchronous operation, and client programs will need
299 * to wait for the ::exit signal.
300 **/
301 gboolean
302 cd_spawn_kill (CdSpawn *spawn)
303 {
304 gint retval;
305
306 g_return_val_if_fail (CD_IS_SPAWN (spawn), FALSE);
307 g_return_val_if_fail (spawn->priv->kill_id == 0, FALSE);
308
309 /* is there a process running? */
310 if (spawn->priv->child_pid == -1) {
311 g_warning ("no child pid to kill!");
312 return FALSE;
313 }
314
315 /* check if process has already gone */
316 if (spawn->priv->finished) {
317 g_debug ("already finished, ignoring");
318 return FALSE;
319 }
320
321 /* set this in case the script catches the signal and exits properly */
322 spawn->priv->exit = CD_SPAWN_EXIT_TYPE_SIGQUIT;
323
324 g_debug ("sending SIGQUIT %ld", (long)spawn->priv->child_pid);
325 retval = kill (spawn->priv->child_pid, SIGQUIT);
326 if (retval == EINVAL) {
327 g_warning ("The signum argument is an invalid or unsupported number");
328 return FALSE;
329 } else if (retval == EPERM) {
330 g_warning ("You do not have the privilege to send a signal to the process");
331 return FALSE;
332 }
333
334 /* the program might not be able to handle SIGQUIT, give it a few seconds and then SIGKILL it */
335 if (spawn->priv->allow_sigkill) {
336 spawn->priv->kill_id = g_timeout_add (CD_SPAWN_SIGKILL_DELAY, (GSourceFunc) cd_spawn_sigkill_cb, spawn);
337 g_source_set_name_by_id (spawn->priv->kill_id, "[CdSpawn] sigkill");
338 }
339 return TRUE;
340 }
341
342 /**
343 * cd_spawn_send_stdin:
344 *
345 * Send new comands to a running (but idle) dispatcher script
346 *
347 **/
348 gboolean
349 cd_spawn_send_stdin (CdSpawn *spawn, const gchar *command)
350 {
351 gint wrote;
352 gint length;
353 g_autofree gchar *buffer = NULL;
354
355 g_return_val_if_fail (CD_IS_SPAWN (spawn), FALSE);
356
357 /* check if process has already gone */
358 if (spawn->priv->finished) {
359 g_debug ("already finished, ignoring");
360 return FALSE;
361 }
362
363 /* is there a process running? */
364 if (spawn->priv->child_pid == -1) {
365 g_debug ("no child pid");
366 return FALSE;
367 }
368
369 /* buffer always has to have trailing newline */
370 g_debug ("sending '%s'", command);
371 buffer = g_strdup_printf ("%s\n", command);
372
373 /* ITS4: ignore, we generated this */
374 length = strlen (buffer);
375
376 /* write to the waiting process */
377 wrote = write (spawn->priv->stdin_fd, buffer, length);
378 if (wrote != length) {
379 g_warning ("wrote %i/%i bytes on fd %i (%s)", wrote, length, spawn->priv->stdin_fd, strerror (errno));
380 return FALSE;
381 }
382 return TRUE;
383 }
384
385 gboolean
386 cd_spawn_argv (CdSpawn *spawn, gchar **argv, gchar **envp, GError **error)
387 {
388 gboolean ret = TRUE;
389 guint i;
390 guint len;
391 gint rc;
392 g_autoptr(GError) error_local = NULL;
393
394 g_return_val_if_fail (CD_IS_SPAWN (spawn), FALSE);
395 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
396 g_return_val_if_fail (argv != NULL, FALSE);
397
398 len = g_strv_length (argv);
399 for (i = 0; i < len; i++)
400 g_debug ("argv[%u] '%s'", i, argv[i]);
401 if (envp != NULL) {
402 len = g_strv_length (envp);
403 for (i = 0; i < len; i++)
404 g_debug ("envp[%u] '%s'", i, envp[i]);
405 }
406
407 /* create spawned object for tracking */
408 spawn->priv->finished = FALSE;
409 g_debug ("creating new instance of %s", argv[0]);
410 ret = g_spawn_async_with_pipes (NULL, argv, envp,
411 G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH,
412 NULL, NULL, &spawn->priv->child_pid,
413 &spawn->priv->stdin_fd,
414 &spawn->priv->stdout_fd,
415 &spawn->priv->stderr_fd,
416 &error_local);
417 if (!ret) {
418 g_set_error (error, 1, 0, "failed to spawn %s: %s", argv[0], error_local->message);
419 return FALSE;
420 }
421
422 /* install an idle handler to check if the child returned successfully. */
423 rc = fcntl (spawn->priv->stdout_fd, F_SETFL, O_NONBLOCK);
424 if (rc < 0) {
425 g_set_error_literal (error, 1, 0, "stdout fcntl failed");
426 return FALSE;
427 }
428 rc = fcntl (spawn->priv->stderr_fd, F_SETFL, O_NONBLOCK);
429 if (rc < 0) {
430 g_set_error_literal (error, 1, 0, "stderr fcntl failed");
431 return FALSE;
432 }
433
434 /* sanity check */
435 if (spawn->priv->poll_id != 0) {
436 g_warning ("trying to set timeout when already set");
437 g_source_remove (spawn->priv->poll_id);
438 }
439
440 /* poll quickly */
441 spawn->priv->poll_id = g_timeout_add (CD_SPAWN_POLL_DELAY, (GSourceFunc) cd_spawn_check_child, spawn);
442 g_source_set_name_by_id (spawn->priv->poll_id, "[CdSpawn] main poll");
443 return TRUE;
444 }
445
446 static void
447 cd_spawn_class_init (CdSpawnClass *klass)
448 {
449 GObjectClass *object_class = G_OBJECT_CLASS (klass);
450
451 object_class->finalize = cd_spawn_finalize;
452
453 signals [SIGNAL_EXIT] =
454 g_signal_new ("exit",
455 G_TYPE_FROM_CLASS (object_class), G_SIGNAL_RUN_LAST,
456 0, NULL, NULL, g_cclosure_marshal_VOID__INT,
457 G_TYPE_NONE, 1, G_TYPE_INT);
458 signals [SIGNAL_STDOUT] =
459 g_signal_new ("stdout",
460 G_TYPE_FROM_CLASS (object_class), G_SIGNAL_RUN_LAST,
461 0, NULL, NULL, g_cclosure_marshal_VOID__STRING,
462 G_TYPE_NONE, 1, G_TYPE_STRING);
463 signals [SIGNAL_STDERR] =
464 g_signal_new ("stderr",
465 G_TYPE_FROM_CLASS (object_class), G_SIGNAL_RUN_LAST,
466 0, NULL, NULL, g_cclosure_marshal_VOID__STRING,
467 G_TYPE_NONE, 1, G_TYPE_STRING);
468
469 g_type_class_add_private (klass, sizeof (CdSpawnPrivate));
470 }
471
472 static void
473 cd_spawn_init (CdSpawn *spawn)
474 {
475 spawn->priv = CD_SPAWN_GET_PRIVATE (spawn);
476
477 spawn->priv->child_pid = -1;
478 spawn->priv->stdout_fd = -1;
479 spawn->priv->stderr_fd = -1;
480 spawn->priv->stdin_fd = -1;
481 spawn->priv->allow_sigkill = TRUE;
482 spawn->priv->exit = CD_SPAWN_EXIT_TYPE_UNKNOWN;
483
484 spawn->priv->stdout_buf = g_string_new ("");
485 spawn->priv->stderr_buf = g_string_new ("");
486 }
487
488 static void
489 cd_spawn_finalize (GObject *object)
490 {
491 CdSpawn *spawn;
492
493 g_return_if_fail (object != NULL);
494 g_return_if_fail (CD_IS_SPAWN (object));
495
496 spawn = CD_SPAWN (object);
497
498 g_return_if_fail (spawn->priv != NULL);
499
500 /* disconnect the poll in case we were cancelled before completion */
501 if (spawn->priv->poll_id != 0) {
502 g_source_remove (spawn->priv->poll_id);
503 spawn->priv->poll_id = 0;
504 }
505
506 /* disconnect the SIGKILL check */
507 if (spawn->priv->kill_id != 0) {
508 g_source_remove (spawn->priv->kill_id);
509 spawn->priv->kill_id = 0;
510 }
511
512 /* still running? */
513 if (spawn->priv->stdin_fd != -1) {
514 g_debug ("killing as still running in finalize");
515 cd_spawn_kill (spawn);
516 /* just hope the script responded to SIGQUIT */
517 if (spawn->priv->kill_id != 0)
518 g_source_remove (spawn->priv->kill_id);
519 }
520
521 /* free the buffers */
522 g_string_free (spawn->priv->stdout_buf, TRUE);
523 g_string_free (spawn->priv->stderr_buf, TRUE);
524
525 G_OBJECT_CLASS (cd_spawn_parent_class)->finalize (object);
526 }
527
528 CdSpawn *
529 cd_spawn_new (void)
530 {
531 CdSpawn *spawn;
532 spawn = g_object_new (CD_TYPE_SPAWN, NULL);
533 return CD_SPAWN (spawn);
534 }