]> rtime.felk.cvut.cz Git - sojka/lightdm.git/blob - src/process.c
d9b7eb9ae16875a3a164533f2cf5bbdf17860c7a
[sojka/lightdm.git] / src / process.c
1 /*
2  * Copyright (C) 2010-2011 Robert Ancell.
3  * Author: Robert Ancell <robert.ancell@canonical.com>
4  *
5  * This program is free software: you can redistribute it and/or modify it under
6  * the terms of the GNU General Public License as published by the Free Software
7  * Foundation, either version 3 of the License, or (at your option) any later
8  * version. See http://www.gnu.org/copyleft/gpl.html the full text of the
9  * license.
10  */
11
12 #include <stdlib.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <errno.h>
16 #include <sys/wait.h>
17 #include <fcntl.h>
18 #include <signal.h>
19 #include <grp.h>
20 #include <config.h>
21
22 #include "log-file.h"
23 #include "process.h"
24
25 enum {
26     GOT_DATA,
27     GOT_SIGNAL,
28     STOPPED,
29     LAST_SIGNAL
30 };
31 static guint signals[LAST_SIGNAL] = { 0 };
32
33 struct ProcessPrivate
34 {
35     /* Function to run inside subprocess before exec */
36     ProcessRunFunc run_func;
37     gpointer run_func_data;
38
39     /* File to log to */
40     gchar *log_file;
41     gboolean log_stdout;
42     LogMode log_mode;
43
44     /* Command to run */
45     gchar *command;
46
47     /* TRUE to clear the environment in this process */
48     gboolean clear_environment;
49
50     /* Environment variables to set */
51     GHashTable *env;
52
53     /* Process ID */
54     GPid pid;
55
56     /* Exit status of process */
57     int exit_status;
58
59     /* TRUE if stopping this process (waiting for child process to stop) */
60     gboolean stopping;
61
62     /* Timeout waiting for process to quit */
63     guint quit_timeout;
64
65     /* Watch on process */
66     guint watch;
67 };
68
69 G_DEFINE_TYPE (Process, process, G_TYPE_OBJECT);
70
71 static Process *current_process = NULL;
72 static GHashTable *processes = NULL;
73 static pid_t signal_pid;
74 static int signal_pipe[2];
75
76 Process *
77 process_get_current (void)
78 {
79     if (current_process)
80         return current_process;
81
82     current_process = process_new (NULL, NULL);
83     current_process->priv->pid = getpid ();
84
85     return current_process;
86 }
87
88 Process *
89 process_new (ProcessRunFunc run_func, gpointer run_func_data)
90 {
91     Process *process = g_object_new (PROCESS_TYPE, NULL);
92     process->priv->run_func = run_func;
93     process->priv->run_func_data = run_func_data;
94     process->priv->log_mode = LOG_MODE_INVALID;
95     return process;
96 }
97
98 void
99 process_set_log_file (Process *process, const gchar *path, gboolean log_stdout, LogMode log_mode)
100 {
101     g_return_if_fail (process != NULL);
102     g_free (process->priv->log_file);
103     process->priv->log_file = g_strdup (path);
104     process->priv->log_stdout = log_stdout;
105     process->priv->log_mode = log_mode;
106 }
107
108 void
109 process_set_clear_environment (Process *process, gboolean clear_environment)
110 {
111     g_return_if_fail (process != NULL);
112     process->priv->clear_environment = clear_environment;
113 }
114
115 gboolean
116 process_get_clear_environment (Process *process)
117 {
118     g_return_val_if_fail (process != NULL, FALSE);
119     return process->priv->clear_environment;
120 }
121
122 void
123 process_set_env (Process *process, const gchar *name, const gchar *value)
124 {
125     g_return_if_fail (process != NULL);
126     g_return_if_fail (name != NULL);
127     g_hash_table_insert (process->priv->env, g_strdup (name), g_strdup (value));
128 }
129
130 const gchar *
131 process_get_env (Process *process, const gchar *name)
132 {
133     g_return_val_if_fail (process != NULL, NULL);
134     g_return_val_if_fail (name != NULL, NULL);
135     return g_hash_table_lookup (process->priv->env, name);
136 }
137
138 void
139 process_set_command (Process *process, const gchar *command)
140 {
141     g_return_if_fail (process != NULL);
142
143     g_free (process->priv->command);
144     process->priv->command = g_strdup (command);
145 }
146
147 const gchar *
148 process_get_command (Process *process)
149 {
150     g_return_val_if_fail (process != NULL, NULL);
151     return process->priv->command;
152 }
153
154 static void
155 process_watch_cb (GPid pid, gint status, gpointer data)
156 {
157     Process *process = data;
158
159     process->priv->watch = 0;
160     process->priv->exit_status = status;
161
162     if (WIFEXITED (status))
163         g_debug ("Process %d exited with return value %d", pid, WEXITSTATUS (status));
164     else if (WIFSIGNALED (status))
165         g_debug ("Process %d terminated with signal %d", pid, WTERMSIG (status));
166
167     if (process->priv->quit_timeout)
168         g_source_remove (process->priv->quit_timeout);
169     process->priv->quit_timeout = 0;
170     process->priv->pid = 0;
171     g_hash_table_remove (processes, GINT_TO_POINTER (pid));
172
173     g_signal_emit (process, signals[STOPPED], 0);
174 }
175
176 gboolean
177 process_start (Process *process, gboolean block)
178 {
179     gint argc;
180     gchar **argv;
181     gchar **env_keys, **env_values;
182     guint i, env_length;
183     GList *keys, *link;
184     pid_t pid;
185     int log_fd = -1;
186     GError *error = NULL;
187
188     g_return_val_if_fail (process != NULL, FALSE);
189     g_return_val_if_fail (process->priv->command != NULL, FALSE);
190     g_return_val_if_fail (process->priv->pid == 0, FALSE);
191
192     if (!g_shell_parse_argv (process->priv->command, &argc, &argv, &error))
193     {
194         g_warning ("Error parsing command %s: %s", process->priv->command, error->message);
195         return FALSE;
196     }
197
198     if (process->priv->log_file)
199         log_fd = log_file_open (process->priv->log_file, process->priv->log_mode);
200
201     /* Work out variables to set */
202     env_length = g_hash_table_size (process->priv->env);
203     env_keys = g_malloc (sizeof (gchar *) * env_length);
204     env_values = g_malloc (sizeof (gchar *) * env_length);
205     keys = g_hash_table_get_keys (process->priv->env);
206     for (i = 0, link = keys; i < env_length; i++, link = link->next)
207     {
208         env_keys[i] = link->data;
209         env_values[i] = g_hash_table_lookup (process->priv->env, env_keys[i]);
210     }
211     g_list_free (keys);
212
213     pid = fork ();
214     if (pid == 0)
215     {
216         /* Do custom setup */
217         if (process->priv->run_func)
218             process->priv->run_func (process, process->priv->run_func_data);
219
220         /* Redirect output to logfile */
221         if (log_fd >= 0)
222         {
223              if (process->priv->log_stdout)
224                  dup2 (log_fd, STDOUT_FILENO);
225              dup2 (log_fd, STDERR_FILENO);
226              close (log_fd);
227         }
228
229         /* Set environment */
230         if (process->priv->clear_environment)
231 #ifdef HAVE_CLEARENV
232             clearenv ();
233 #else
234             environ = NULL;
235 #endif
236         for (i = 0; i < env_length; i++)
237             setenv (env_keys[i], env_values[i], TRUE);
238
239         execvp (argv[0], argv);
240         _exit (EXIT_FAILURE);
241     }
242
243     close (log_fd);
244     g_strfreev (argv);
245     g_free (env_keys);
246     g_free (env_values);
247
248     if (pid < 0)
249     {
250         g_warning ("Failed to fork: %s", strerror (errno));
251         return FALSE;
252     }
253
254     g_debug ("Launching process %d: %s", pid, process->priv->command);
255
256     process->priv->pid = pid;
257
258     if (block)
259     {
260         int exit_status;
261         waitpid (process->priv->pid, &exit_status, 0);
262         process_watch_cb (process->priv->pid, exit_status, process);
263     }
264     else
265     {
266         g_hash_table_insert (processes, GINT_TO_POINTER (process->priv->pid), g_object_ref (process));
267         process->priv->watch = g_child_watch_add (process->priv->pid, process_watch_cb, process);
268     }
269
270     return TRUE;
271 }
272
273 gboolean
274 process_get_is_running (Process *process)
275 {
276     g_return_val_if_fail (process != NULL, FALSE);
277     return process->priv->pid != 0;
278 }
279
280 GPid
281 process_get_pid (Process *process)
282 {
283     g_return_val_if_fail (process != NULL, 0);
284     return process->priv->pid;
285 }
286
287 void
288 process_signal (Process *process, int signum)
289 {
290     g_return_if_fail (process != NULL);
291
292     if (process->priv->pid == 0)
293         return;
294
295     g_debug ("Sending signal %d to process %d", signum, process->priv->pid);
296
297     if (kill (process->priv->pid, signum) < 0)
298     {
299         /* Ignore ESRCH, we will pick that up in our wait */
300         if (errno != ESRCH)
301             g_warning ("Error sending signal %d to process %d: %s", signum, process->priv->pid, strerror (errno));
302     }
303 }
304
305 static gboolean
306 quit_timeout_cb (Process *process)
307 {
308     process->priv->quit_timeout = 0;
309     process_signal (process, SIGKILL);
310     return FALSE;
311 }
312
313 void
314 process_stop (Process *process)
315 {
316     g_return_if_fail (process != NULL);
317
318     if (process->priv->stopping)
319         return;
320     process->priv->stopping = TRUE;
321
322     /* If already stopped then we're done! */
323     if (process->priv->pid == 0)
324         return;
325
326     /* Send SIGTERM, and then SIGKILL if no response */
327     process->priv->quit_timeout = g_timeout_add (5000, (GSourceFunc) quit_timeout_cb, process);
328     process_signal (process, SIGTERM);
329 }
330
331 int
332 process_get_exit_status (Process *process)
333 {
334     g_return_val_if_fail (process != NULL, -1);
335     return process->priv->exit_status;
336 }
337
338 static void
339 process_init (Process *process)
340 {
341     process->priv = G_TYPE_INSTANCE_GET_PRIVATE (process, PROCESS_TYPE, ProcessPrivate);
342     process->priv->env = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
343 }
344
345 static void
346 process_stopped (Process *process)
347 {
348 }
349
350 static void
351 process_finalize (GObject *object)
352 {
353     Process *self = PROCESS (object);
354
355     if (self->priv->pid > 0)
356         g_hash_table_remove (processes, GINT_TO_POINTER (self->priv->pid));
357
358     g_free (self->priv->log_file);
359     g_free (self->priv->command);
360     g_hash_table_unref (self->priv->env);
361     if (self->priv->quit_timeout)
362         g_source_remove (self->priv->quit_timeout);
363     if (self->priv->watch)
364         g_source_remove (self->priv->watch);
365
366     if (self->priv->pid)
367         kill (self->priv->pid, SIGTERM);
368
369     G_OBJECT_CLASS (process_parent_class)->finalize (object);
370 }
371
372 static void
373 signal_cb (int signum, siginfo_t *info, void *data)
374 {
375     /* Check if we are from a forked process that hasn't updated the signal handlers or execed.
376        If so, then we should just quit */
377     if (getpid () != signal_pid)
378         _exit (EXIT_SUCCESS);
379
380     /* Write signal to main thread, if something goes wrong just close the pipe so it is detected on the other end */
381     if (write (signal_pipe[1], &info->si_signo, sizeof (int)) < 0 ||
382         write (signal_pipe[1], &info->si_pid, sizeof (pid_t)) < 0)
383         close (signal_pipe[1]);
384 }
385
386 static gboolean
387 handle_signal (GIOChannel *source, GIOCondition condition, gpointer data)
388 {
389     int signo;
390     pid_t pid;
391     Process *process;
392
393     errno = 0;
394     if (read (signal_pipe[0], &signo, sizeof (int)) != sizeof (int) ||
395         read (signal_pipe[0], &pid, sizeof (pid_t)) != sizeof (pid_t))
396     {
397         g_warning ("Error reading from signal pipe: %s", strerror (errno));
398         return FALSE;
399     }
400
401     g_debug ("Got signal %d from process %d", signo, pid);
402
403     process = g_hash_table_lookup (processes, GINT_TO_POINTER (pid));
404     if (process == NULL)
405         process = process_get_current ();
406     if (process)
407         g_signal_emit (process, signals[GOT_SIGNAL], 0, signo);
408
409     return TRUE;
410 }
411
412 static void
413 process_class_init (ProcessClass *klass)
414 {
415     GObjectClass *object_class = G_OBJECT_CLASS (klass);
416     struct sigaction action;
417
418     klass->stopped = process_stopped;
419     object_class->finalize = process_finalize;
420
421     g_type_class_add_private (klass, sizeof (ProcessPrivate));
422
423     signals[GOT_DATA] =
424         g_signal_new (PROCESS_SIGNAL_GOT_DATA,
425                       G_TYPE_FROM_CLASS (klass),
426                       G_SIGNAL_RUN_LAST,
427                       G_STRUCT_OFFSET (ProcessClass, got_data),
428                       NULL, NULL,
429                       NULL,
430                       G_TYPE_NONE, 0);
431     signals[GOT_SIGNAL] =
432         g_signal_new (PROCESS_SIGNAL_GOT_SIGNAL,
433                       G_TYPE_FROM_CLASS (klass),
434                       G_SIGNAL_RUN_LAST,
435                       G_STRUCT_OFFSET (ProcessClass, got_signal),
436                       NULL, NULL,
437                       NULL,
438                       G_TYPE_NONE, 1, G_TYPE_INT);
439     signals[STOPPED] =
440         g_signal_new (PROCESS_SIGNAL_STOPPED,
441                       G_TYPE_FROM_CLASS (klass),
442                       G_SIGNAL_RUN_LAST,
443                       G_STRUCT_OFFSET (ProcessClass, stopped),
444                       NULL, NULL,
445                       NULL,
446                       G_TYPE_NONE, 0);
447
448     /* Catch signals and feed them to the main loop via a pipe */
449     processes = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);
450     signal_pid = getpid ();
451     if (pipe (signal_pipe) != 0)
452         g_critical ("Failed to create signal pipe");
453     fcntl (signal_pipe[0], F_SETFD, FD_CLOEXEC);
454     fcntl (signal_pipe[1], F_SETFD, FD_CLOEXEC);
455     g_io_add_watch (g_io_channel_unix_new (signal_pipe[0]), G_IO_IN, handle_signal, NULL);
456     action.sa_sigaction = signal_cb;
457     sigemptyset (&action.sa_mask);
458     action.sa_flags = SA_SIGINFO;
459     sigaction (SIGTERM, &action, NULL);
460     sigaction (SIGINT, &action, NULL);
461     sigaction (SIGHUP, &action, NULL);
462     sigaction (SIGUSR1, &action, NULL);
463     sigaction (SIGUSR2, &action, NULL);
464 }